Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions apps/web/src/components/ChatView.sidebar.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<HTMLElement>(`[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 {
Expand Down
71 changes: 35 additions & 36 deletions apps/web/src/hooks/useThreadActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,13 @@ async function confirmOrphanedWorktreeDeletion(worktreePath: string): Promise<bo
}

/**
* The threads a delete "with its threads" takes along: the thread's attached
* children that are not archived, as this device knows them. The server
* deletes exactly these and separates archived ones, so the count the user
* is shown and what goes are the same.
* The threads a delete "with its threads" should take along: the thread's
* attached children that are not archived, as this device knows them. The
* server applies the same rule to its own state, so the count the user is
* shown matches what goes. It can still differ when a child leaves the family
* in the meantime, so this list only decides the count and where to navigate.
* The server cleans up each thread it actually deletes (ThreadDeletionReactor)
* and each client forgets it when its removal arrives.
*/
function selectDeletableChildThreads(target: ScopedThreadRef): Thread[] {
return selectThreadsForEnvironment(useStore.getState(), target.environmentId).filter(
Expand All @@ -74,21 +77,23 @@ export function countAttachedChildThreads(target: ScopedThreadRef): number {
return selectDeletableChildThreads(target).length;
}

/** Stops each thread's session and closes its terminals before the server deletes it. */
async function windDownThreadsBeforeDelete(
/**
* Stops the named thread's session and closes its terminals before the server
* deletes it. Only for the thread the user named: its children are the
* server's call, and one it keeps must not lose its terminal history.
*/
async function windDownThreadBeforeDelete(
api: NonNullable<ReturnType<typeof readEnvironmentApi>>,
environmentId: ScopedThreadRef["environmentId"],
threads: ReadonlyArray<Pick<Thread, "id" | "session">>,
thread: Pick<Thread, "id" | "session">,
): Promise<void> {
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.
}
}

Expand Down Expand Up @@ -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<Pick<Thread, "id" | "projectId">>,
) => {
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<Thread, "id" | "projectId">) => {
const threadRef = scopeThreadRef(environmentId, thread.id);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(scopeProjectRef(environmentId, thread.projectId), threadRef);
clearTerminalState(threadRef);
},
[clearComposerDraftForThread, clearProjectDraftThreadById, clearTerminalState],
);
Expand Down Expand Up @@ -271,17 +271,16 @@ 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(),
threadId: target.threadId,
...(opts.withChildren ? { withChildren: true } : {}),
});
refreshArchivedThreadsForEnvironment(target.environmentId);
forgetDeletedThreads(target.environmentId, deletedChildren);
const currentRouteThreadRef = getCurrentRouteThreadRef();
if (
currentRouteThreadRef?.environmentId === target.environmentId &&
Expand Down Expand Up @@ -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<ThreadId>([
...(deletedIds ?? []),
Expand All @@ -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) {
Expand Down Expand Up @@ -397,7 +396,7 @@ export function useThreadActions() {
});
},
[
forgetDeletedThreads,
forgetDeletedThread,
getCurrentRouteThreadRef,
removeOrphanedWorktree,
router,
Expand Down
2 changes: 1 addition & 1 deletion docs/design/child-threads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading