diff --git a/client/sessions.tsx b/client/sessions.tsx index 56b3962..77196e5 100644 --- a/client/sessions.tsx +++ b/client/sessions.tsx @@ -1,9 +1,10 @@ import type { PluginSurfaceProps } from "@getpaseo/plugin/client"; import { useRpc } from "@getpaseo/plugin/client"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { FlatList, Image, Modal, Pressable, ScrollView, Text, TextInput, View } from "react-native"; +import { ActivityIndicator, FlatList, Image, Modal, Pressable, ScrollView, Text, TextInput, View } from "react-native"; import { archiveSessionRpc, + CleanupCandidateSchema, cleanupSessionsRpc, deleteSessionsRpc, discoverSessionsRpc, @@ -16,6 +17,7 @@ import { import type { z } from "zod"; type SessionDto = z.infer; +type CleanupCandidate = z.infer; type RelationshipDto = z.infer; type Tone = "neutral" | "danger" | "accent"; @@ -518,11 +520,17 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { const [sort, setSort] = useState<{ column: SortColumn; direction: SortDirection }>({ column: "created", direction: "desc" }); const [selected, setSelected] = useState>(new Set()); const [lastSelectedIndex, setLastSelectedIndex] = useState(null); - const [loading, setLoading] = useState(false); + const [loading, setLoading] = useState(true); + const [listError, setListError] = useState(null); + const [waitingForDiscovery, setWaitingForDiscovery] = useState(false); + const listRequest = useRef(0); + const listFilter = useRef({ category, query }); const [rescanning, setRescanning] = useState(false); - const [cleanupCandidates, setCleanupCandidates] = useState(null); + const [cleanupCandidates, setCleanupCandidates] = useState(null); const [showCleanupList, setShowCleanupList] = useState(false); - const [applyingCleanup, setApplyingCleanup] = useState(false); + const [cleanupPhase, setCleanupPhase] = useState<"preview" | "apply" | null>(null); + const cleanupInFlight = useRef(false); + const [cleanupCount, setCleanupCount] = useState(null); const [bulkArchiving, setBulkArchiving] = useState(false); const [bulkDeleting, setBulkDeleting] = useState(false); const [previewSession, setPreviewSession] = useState(null); @@ -575,47 +583,92 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { }, [previewSessionId, showSession]); const refresh = useCallback(async () => { + const { category, query } = listFilter.current; + const request = ++listRequest.current; setLoading(true); + setListError(null); try { const result = await listSessions( category === "ALL" ? { query: query || undefined } : { query: query || undefined, category }, ); + if (request !== listRequest.current) return; setSessions(result.sessions); setRelationships(result.relationships); + setWaitingForDiscovery((waiting) => + result.discovering && category === "ALL" && !query.trim() && (waiting || result.sessions.length === 0), + ); + } catch (error) { + if (request !== listRequest.current) return; + setWaitingForDiscovery(false); + setListError(`Could not load sessions: ${errorMessage(error)}`); } finally { - setLoading(false); + if (request === listRequest.current) setLoading(false); } - }, [listSessions, query, category]); + }, [listSessions]); + + useEffect(() => { + listFilter.current = { category, query }; + void refresh(); + return () => { + listRequest.current += 1; + }; + }, [category, query, refresh]); useEffect(() => { - refresh(); - }, [refresh]); + if (!waitingForDiscovery || loading) return; + const timer = setTimeout(refresh, 2000); + return () => clearTimeout(timer); + }, [waitingForDiscovery, loading, sessions, refresh]); const rescan = useCallback(async () => { setRescanning(true); + setActionError(null); try { await discoverSessions({}); - await refresh(); + } catch (error) { + setActionError(`Could not finish the rescan: ${errorMessage(error)}`); } finally { + await refresh(); setRescanning(false); } }, [discoverSessions, refresh]); const previewCleanup = useCallback(async () => { - const result = await cleanupSessions({ dryRun: true }); - setCleanupCandidates(result.candidates); + if (cleanupInFlight.current) return; + cleanupInFlight.current = true; + setCleanupPhase("preview"); + setCleanupCandidates(null); + setCleanupCount(null); + setActionError(null); + try { + const result = await cleanupSessions({ dryRun: true }); + setCleanupCandidates(result.candidates); + } catch (error) { + setActionError(`Could not preview cleanup: ${errorMessage(error)}`); + } finally { + cleanupInFlight.current = false; + setCleanupPhase(null); + } }, [cleanupSessions]); const closeCleanupList = useCallback(() => setShowCleanupList(false), []); const applyCleanup = useCallback(async () => { - setApplyingCleanup(true); + if (cleanupInFlight.current) return; + cleanupInFlight.current = true; + setCleanupPhase("apply"); + setActionError(null); + setCleanupCandidates(null); try { - await cleanupSessions({ dryRun: false }); - setCleanupCandidates(null); + const result = await cleanupSessions({ dryRun: false }); + await refresh(); + setCleanupCount(result.appliedCount); + } catch (error) { + setActionError(`Could not confirm the cleanup result: ${errorMessage(error)}. Preview cleanup again to see the current candidates.`); await refresh(); } finally { - setApplyingCleanup(false); + cleanupInFlight.current = false; + setCleanupPhase(null); } }, [cleanupSessions, refresh]); @@ -970,6 +1023,13 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { actionErrorText: { flex: 1, color: theme.colors.statusDanger, fontSize: FONT_SIZE.sm }, actionErrorDismiss: { paddingHorizontal: SPACING[2], paddingVertical: SPACING[1] }, actionErrorDismissText: { color: theme.colors.statusDanger, fontSize: FONT_SIZE.sm, fontWeight: "500" as const }, + statusBanner: { + flexDirection: "row" as const, + alignItems: "center" as const, + gap: SPACING[2], + paddingHorizontal: layout.compact ? SPACING[3] : SPACING[4], + paddingVertical: SPACING[2], + }, cleanupBanner: { padding: layout.compact ? SPACING[3] : SPACING[4], gap: SPACING[1], @@ -1156,6 +1216,12 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { [theme, layout.compact], ); + let progressMessage: string | null = null; + if (cleanupPhase === "preview") progressMessage = "Finding cleanup candidates…"; + else if (cleanupPhase === "apply") progressMessage = "Moving sessions to trash…"; + else if (rescanning || waitingForDiscovery) progressMessage = "Discovering sessions…"; + else if (loading) progressMessage = "Loading sessions…"; + return ( @@ -1173,11 +1239,17 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { {filter} ))} - + {rescanning ? "Scanning..." : "Rescan"} - - Preview cleanup + + {cleanupPhase === "preview" ? "Preparing preview…" : "Preview cleanup"} @@ -1201,6 +1273,28 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { + {progressMessage ? ( + + + {progressMessage} + + ) : cleanupCount !== null ? ( + + + {cleanupCount === 1 ? "Moved 1 session to trash." : `Moved ${cleanupCount} sessions to trash.`} + + + ) : null} + + {listError ? ( + + {listError} + + Retry + + + ) : null} + {actionError ? ( {actionError} @@ -1221,7 +1315,7 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { {cleanupCandidates.slice(0, CLEANUP_PREVIEW_LIMIT).map((candidate) => ( - • {candidate.title ?? candidate.firstUserMessage ?? "(untitled)"} — {candidate.classification?.reason} + • {candidate.label}{candidate.reason ? ` — ${candidate.reason}` : ""} ))} {cleanupCandidates.length > CLEANUP_PREVIEW_LIMIT ? ( @@ -1230,7 +1324,6 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { accessibilityHint="Opens the full cleanup preview" style={styles.cleanupMore} onPress={() => setShowCleanupList(true)} - disabled={applyingCleanup} > View {cleanupCandidates.length - CLEANUP_PREVIEW_LIMIT} more @@ -1241,8 +1334,8 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { )} {cleanupCandidates.length > 0 ? ( - - {applyingCleanup ? "Applying..." : "Move to trash"} + + Move to trash ) : null} @@ -1267,8 +1360,10 @@ export function SessionsSurface({ theme, layout }: PluginSurfaceProps) { ) : null} - {!loading && visibleSessions.length === 0 ? ( - No sessions found. Try Rescan. + {visibleSessions.length === 0 ? ( + loading || waitingForDiscovery || rescanning || listError ? null : ( + No sessions found. Try Rescan. + ) ) : viewMode === "timeline" ? ( ( - {item.title ?? item.firstUserMessage ?? "(untitled session)"} + {item.label} {agentLabel(item.agent)} · {item.project} · {formatDateTime(item.createdAt)} - {item.classification ? {item.classification.reason} : null} + {item.reason ? {item.reason} : null} )} /> diff --git a/docs/MANUAL.md b/docs/MANUAL.md index ed34948..13d99d5 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -140,11 +140,13 @@ actions in both views, a click-to-preview dialog showing detected related sessio by recommendation, rescan, dry-run cleanup preview with confirmation, archive/restore/delete, and per-session/per-provider on-disk size. It re-scans Claude Code, Codex, Gemini CLI, and OpenCode sessions every 5 minutes in the background (Aider is included in that rescan too, but only once -`AIDER_SEARCH_ROOTS` is set). +`AIDER_SEARCH_ROOTS` is set). Sessions load when the sidebar opens. An empty inventory refreshes +automatically during the first discovery. If loading fails, select **Retry**. **Preview cleanup** shows the first five recommendations. If there are more, select **View … more** to open the complete list and scroll through it. Each row shows why the session was recommended. Close the list to return to the preview. To apply cleanup, select **Move to trash** and confirm. +The preview and move each show a progress indicator, and the move reports how many sessions it changed. ## Staying up to date diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index c92b4a7..fba8094 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -127,6 +127,9 @@ npm). In the Paseo plugin, the cleanup banner shows the first five candidates from the dry-run result. The full preview opens the same result in a virtualized list that renders rows as the user scrolls. +The cleanup RPC returns lightweight candidates for preview and an applied count after confirmation. +Applying cleanup commits lifecycle and audit updates in one transaction. +The list RPC reports when discovery is running so a newly empty inventory can refresh automatically. Deferred to Phase 2 per GOAL.md: LLM-assisted classification, and true embedding-based semantic search (FTS5 above covers ranked lexical search; embeddings would be a separate, heavier addition). diff --git a/packages/cli/src/core/discover.server.test.ts b/packages/cli/src/core/discover.server.test.ts index c8299ed..ed52ccc 100644 --- a/packages/cli/src/core/discover.server.test.ts +++ b/packages/cli/src/core/discover.server.test.ts @@ -1,7 +1,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ClaudeCodeAdapter } from "./claude-adapter.server.js"; import { runDiscovery } from "./discover.server.js"; import { archiveSession, restoreSession, runCleanup } from "./lifecycle-actions.server.js"; @@ -108,6 +108,20 @@ describe("discover + lifecycle actions (integration)", () => { expect(audit.some((entry) => entry.action === "TRASH")).toBe(true); }); + it("rolls back lifecycle and audit changes when applying cleanup fails", async () => { + await runDiscovery(store, [new ClaudeCodeAdapter()]); + const recordAudit = store.recordAudit.bind(store); + vi.spyOn(store, "recordAudit").mockImplementationOnce((entry) => { + recordAudit(entry); + throw new Error("interrupted cleanup"); + }); + + expect(() => runCleanup(store, "test", false)).toThrow("interrupted cleanup"); + expect(store.listSessions({ lifecycle: "JUNK" })).toHaveLength(0); + expect(store.listAudit()).toHaveLength(0); + expect(runCleanup(store, "test", false).applied).toHaveLength(1); + }); + it("archive then restore round-trips cleanly", async () => { await runDiscovery(store, [new ClaudeCodeAdapter()]); const before = store.listSessions({ category: "KEEP" })[0]; diff --git a/packages/cli/src/core/lifecycle-actions.server.ts b/packages/cli/src/core/lifecycle-actions.server.ts index bb32412..37b937b 100644 --- a/packages/cli/src/core/lifecycle-actions.server.ts +++ b/packages/cli/src/core/lifecycle-actions.server.ts @@ -147,13 +147,15 @@ export interface CleanupResult { /** GOAL §11/§12: dry-run by default. Only trashes sessions when `dryRun` is explicitly false. */ export function runCleanup(store: SessionStore, actor: string, dryRun: boolean): CleanupResult { - const candidates = junkCandidates(store); if (dryRun) { - return { dryRun: true, candidates, applied: [] }; + return { dryRun: true, candidates: junkCandidates(store), applied: [] }; } - const applied = candidates.map((session) => - trashSession(store, session.id, actor, session.classification?.reason ?? null), - ); - return { dryRun: false, candidates, applied }; + return store.runInTransaction(() => { + const candidates = junkCandidates(store); + const applied = candidates.map((session) => + trashSession(store, session.id, actor, session.classification?.reason ?? null), + ); + return { dryRun: false, candidates, applied }; + }); } diff --git a/packages/cli/src/core/store.server.ts b/packages/cli/src/core/store.server.ts index 5c60ed8..fedcc09 100644 --- a/packages/cli/src/core/store.server.ts +++ b/packages/cli/src/core/store.server.ts @@ -193,6 +193,18 @@ export class SessionStore { this.db.close(); } + runInTransaction(operation: () => T): T { + this.runScript("BEGIN IMMEDIATE"); + try { + const result = operation(); + this.runScript("COMMIT"); + return result; + } catch (error) { + this.runScript("ROLLBACK"); + throw error; + } + } + getSession(id: string): Session | null { const row = this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id) as unknown as SessionRow | undefined; return row ? rowToSession(row) : null; diff --git a/server/session-handlers.ts b/server/session-handlers.ts index 2e55502..a3c9fc0 100644 --- a/server/session-handlers.ts +++ b/server/session-handlers.ts @@ -11,7 +11,7 @@ import { runCleanup, runDiscovery, } from "@aadaa88/sessionforge"; -import type { SessionFilter } from "@aadaa88/sessionforge"; +import type { DiscoverResult, SessionFilter } from "@aadaa88/sessionforge"; const ACTOR = "paseo-plugin"; const ADAPTERS = [new ClaudeCodeAdapter(), new CodexAdapter(), new GeminiCliAdapter(), new OpenCodeAdapter(), new AiderAdapter()]; @@ -19,6 +19,7 @@ const DISCOVERY_INTERVAL_MS = 5 * 60 * 1000; let storeSingleton: SessionStore | null = null; let backgroundInterval: ReturnType | null = null; +let discoveryInFlight: Promise | null = null; function store(): SessionStore { if (!storeSingleton) storeSingleton = new SessionStore(); @@ -28,11 +29,11 @@ function store(): SessionStore { function ensureBackgroundDiscovery(): void { if (backgroundInterval || !storeSingleton) return; - runDiscovery(storeSingleton, ADAPTERS).catch((error: unknown) => { + discoverSessions().catch((error: unknown) => { console.error("SessionForge: initial discovery failed", error); }); backgroundInterval = setInterval(() => { - runDiscovery(store(), ADAPTERS).catch((error: unknown) => { + discoverSessions().catch((error: unknown) => { console.error("SessionForge: periodic discovery failed", error); }); }, DISCOVERY_INTERVAL_MS); @@ -47,7 +48,12 @@ export function stopBackgroundDiscovery(): void { } export async function listSessions(input: SessionFilter) { - return { sessions: store().listSessions(input), relationships: store().listAllRelationships() }; + const inventory = store(); + return { + sessions: inventory.listSessions(input), + relationships: inventory.listAllRelationships(), + discovering: discoveryInFlight !== null, + }; } export async function showSession(input: { id: string }) { @@ -58,12 +64,33 @@ export async function searchSessions(input: { query: string }) { return { sessions: store().listSessions({ query: input.query }) }; } -export async function discoverSessions() { - return runDiscovery(store(), ADAPTERS); +export function discoverSessions(): Promise { + if (!discoveryInFlight) { + // Defer opening the store until discoveryInFlight is set, so the first manual and background + // requests share the same scan. + discoveryInFlight = Promise.resolve() + .then(() => runDiscovery(store(), ADAPTERS)) + .finally(() => { + discoveryInFlight = null; + }); + } + return discoveryInFlight; } export async function cleanupSessions(input: { dryRun: boolean }) { - return runCleanup(store(), ACTOR, input.dryRun); + const result = runCleanup(store(), ACTOR, input.dryRun); + if (!result.dryRun) return { candidates: [], appliedCount: result.applied.length }; + return { + candidates: result.candidates.map((session) => ({ + id: session.id, + agent: session.agent, + project: session.project, + createdAt: session.createdAt, + label: session.title ?? session.firstUserMessage ?? "(untitled session)", + reason: session.classification?.reason ?? null, + })), + appliedCount: 0, + }; } export async function archiveSessionHandler(input: { id: string; reason?: string }) { diff --git a/shared/session-contracts.ts b/shared/session-contracts.ts index 5210bf0..03039b6 100644 --- a/shared/session-contracts.ts +++ b/shared/session-contracts.ts @@ -76,7 +76,11 @@ export const SessionFilterSchema = z.object({ export const listSessionsRpc = defineRpc({ name: "session.list", input: SessionFilterSchema, - output: z.object({ sessions: z.array(SessionSchema), relationships: z.array(SessionRelationshipSchema) }), + output: z.object({ + sessions: z.array(SessionSchema), + relationships: z.array(SessionRelationshipSchema), + discovering: z.boolean(), + }), }); export const showSessionRpc = defineRpc({ @@ -97,10 +101,15 @@ export const discoverSessionsRpc = defineRpc({ output: z.object({ scanned: z.number(), created: z.number(), updated: z.number() }), }); +export const CleanupCandidateSchema = SessionSchema.pick({ id: true, agent: true, project: true, createdAt: true }).extend({ + label: z.string(), + reason: z.string().nullable(), +}); + export const cleanupSessionsRpc = defineRpc({ name: "session.cleanup", input: z.object({ dryRun: z.boolean().default(true) }), - output: z.object({ dryRun: z.boolean(), candidates: z.array(SessionSchema), applied: z.array(SessionSchema) }), + output: z.object({ candidates: z.array(CleanupCandidateSchema), appliedCount: z.number() }), }); export const archiveSessionRpc = defineRpc({