diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index 8dd8072b6..cfdbdc9ae 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -24,6 +24,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { render } from "vitest-browser-react"; import { CLIENT_SETTINGS_STORAGE_KEY } from "../clientPersistenceStorage"; +import { useComposerDraftStore } from "../composerDraftStore"; import type { SidebarThreadSummary } from "../types"; import { makeBrowserTab, @@ -542,6 +543,69 @@ describe("ChatView (full app): sidebar", () => { } }); + it("deleting a thread with its threads leaves a child's terminal and draft to the server's answer", async () => { + const childId = "thread-lead-child" as ThreadId; + const childRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, childId); + const mounted = await mountFamily(null); + try { + useComposerDraftStore.getState().setPrompt(childRef, "half-written reply"); + const row = await waitForElement( + () => document.querySelector(`[data-testid="thread-row-${THREAD_ID}"]`), + "The parent's sidebar row should be on screen.", + ); + const rect = row.getBoundingClientRect(); + row.dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: rect.left + 20, + clientY: rect.top + 8, + }), + ); + await page.getByRole("button", { name: "Delete", exact: true }).click(); + await page.getByTestId("thread-delete-with-children").click(); + await page.getByTestId("thread-delete-confirm").click(); + await vi.waitFor(() => { + expect( + wsRequests.some( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.delete" && + request.threadId === THREAD_ID && + request.withChildren === true, + ), + ).toBe(true); + }); + + // The server decides which children go. This one is still here (it was + // separated in the meantime), so nothing of it may be wiped locally. + await new Promise((resolve) => setTimeout(resolve, 100)); + expect( + wsRequests.filter( + (request) => + request.threadId === childId && + (request._tag === WS_METHODS.terminalClose || + (request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.session.stop")), + ), + ).toEqual([]); + expect(useComposerDraftStore.getState().getComposerDraft(childRef)?.prompt).toBe( + "half-written reply", + ); + // The thread the user named is wound down here as before. + expect( + wsRequests.some( + (request) => + request._tag === WS_METHODS.terminalClose && + request.threadId === THREAD_ID && + request.deleteHistory === true, + ), + ).toBe(true); + } finally { + await mounted.cleanup(); + } + }); + it("keeps the lead suggestion away from a project once it is closed", async () => { const mounted = await mountFamily(null); try { diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index cfc9f4394..3e81a9908 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -55,10 +55,13 @@ async function confirmOrphanedWorktreeDeletion(worktreePath: string): Promise>, environmentId: ScopedThreadRef["environmentId"], - threads: ReadonlyArray>, + thread: Pick, ): Promise { - for (const doomed of threads) { - if (doomed.session && doomed.session.status !== "closed") { - await stopThreadSession(scopeThreadRef(environmentId, doomed.id)).catch(() => undefined); - } - try { - await api.terminal.close({ threadId: doomed.id, deleteHistory: true }); - } catch { - // Terminal may already be closed. - } + if (thread.session && thread.session.status !== "closed") { + await stopThreadSession(scopeThreadRef(environmentId, thread.id)).catch(() => undefined); + } + try { + await api.terminal.close({ threadId: thread.id, deleteHistory: true }); + } catch { + // Terminal may already be closed. } } @@ -220,18 +225,13 @@ export function useThreadActions() { [queryClient], ); - /** Drops what this device keeps for deleted threads: drafts and terminal state. */ - const forgetDeletedThreads = useCallback( - ( - environmentId: ScopedThreadRef["environmentId"], - threads: ReadonlyArray>, - ) => { - for (const doomed of threads) { - const doomedRef = scopeThreadRef(environmentId, doomed.id); - clearComposerDraftForThread(doomedRef); - clearProjectDraftThreadById(scopeProjectRef(environmentId, doomed.projectId), doomedRef); - clearTerminalState(doomedRef); - } + /** Drops what this device keeps for the deleted thread the user named: drafts and terminal state. */ + const forgetDeletedThread = useCallback( + (environmentId: ScopedThreadRef["environmentId"], thread: Pick) => { + const threadRef = scopeThreadRef(environmentId, thread.id); + clearComposerDraftForThread(threadRef); + clearProjectDraftThreadById(scopeProjectRef(environmentId, thread.projectId), threadRef); + clearTerminalState(threadRef); }, [clearComposerDraftForThread, clearProjectDraftThreadById, clearTerminalState], ); @@ -271,9 +271,9 @@ export function useThreadActions() { projectCwd !== undefined && (await confirmOrphanedWorktreeDeletion(orphanedWorktreePath)); - // An archived parent can still have live threads in its family. + // An archived parent can still have live threads in its family. The + // server winds down and deletes the ones it takes along. const deletedChildren = opts.withChildren ? selectDeletableChildThreads(target) : []; - await windDownThreadsBeforeDelete(api, target.environmentId, deletedChildren); await api.orchestration.dispatchCommand({ type: "thread.delete", commandId: newCommandId(), @@ -281,7 +281,6 @@ export function useThreadActions() { ...(opts.withChildren ? { withChildren: true } : {}), }); refreshArchivedThreadsForEnvironment(target.environmentId); - forgetDeletedThreads(target.environmentId, deletedChildren); const currentRouteThreadRef = getCurrentRouteThreadRef(); if ( currentRouteThreadRef?.environmentId === target.environmentId && @@ -335,10 +334,10 @@ export function useThreadActions() { threadProject !== undefined && (await confirmOrphanedWorktreeDeletion(orphanedWorktreePath)); - // Its family goes with it when asked: each child is wound down the way - // the thread itself is, before the server deletes them together. + // Its family goes with it when asked. The server decides which children + // that is and winds each one down; this device only steers away from them. const deletedChildren = opts.withChildren ? selectDeletableChildThreads(threadRef) : []; - await windDownThreadsBeforeDelete(api, threadRef.environmentId, [thread, ...deletedChildren]); + await windDownThreadBeforeDelete(api, threadRef.environmentId, thread); const deletedThreadIds = new Set([ ...(deletedIds ?? []), @@ -361,7 +360,7 @@ export function useThreadActions() { ...(opts.withChildren ? { withChildren: true } : {}), }); refreshArchivedThreadsForEnvironment(threadRef.environmentId); - forgetDeletedThreads(threadRef.environmentId, [thread, ...deletedChildren]); + forgetDeletedThread(threadRef.environmentId, thread); if (shouldNavigateToFallback) { if (fallbackThreadId) { @@ -397,7 +396,7 @@ export function useThreadActions() { }); }, [ - forgetDeletedThreads, + forgetDeletedThread, getCurrentRouteThreadRef, removeOrphanedWorktree, router, diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 2a9dd7737..dab329a20 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -363,7 +363,7 @@ Each of these settles open requests and also unqueues the matching queued report Nothing is restored. Later sends report back again. -- **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command carries `withChildren: true`, in which case they're deleted. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. +- **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command carries `withChildren: true`, in which case they're deleted. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. The client winds down only the thread the user named. The server decides which children go, and a child can leave the family between the dialog and the delete, so the cleanup for each deleted child runs off its own `thread.deleted` event: `ThreadDeletionReactor` stops its runtime and deletes its terminal history, and each client drops its draft and terminal state when the removal arrives. A child the server keeps loses nothing. - **Archive the parent.** The cascade is decided on the server: - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal) are archived and stamped `archivedWithParentAt`; - live attached children are separated first.