Skip to content

Commit 0ccac99

Browse files
ScottN-PVclaude
andcommitted
fix(web): keep the child open when its remote parent was deleted
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent da8cc59 commit 0ccac99

3 files changed

Lines changed: 160 additions & 8 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import { EnvironmentId, ThreadId, type OrchestrationV2ThreadShell } from "@t3tools/contracts";
2+
import * as Cause from "effect/Cause";
3+
import { expect, it, vi } from "vite-plus/test";
4+
5+
import { render, type Screen } from "../../../test/render";
6+
7+
const { read, toast } = vi.hoisted(() => ({
8+
read: vi.fn<(input: unknown) => Promise<unknown>>(),
9+
toast: vi.fn(),
10+
}));
11+
12+
const childEnvironmentId = EnvironmentId.make("child-environment");
13+
const childThreadId = ThreadId.make("child-thread");
14+
const parentEnvironmentId = EnvironmentId.make("parent-environment");
15+
// The panel reads only identity, lineage and delegation from the current thread.
16+
const child = {
17+
id: childThreadId,
18+
title: "Child",
19+
lineage: { rootThreadId: childThreadId, parentThreadId: null, relationshipToParent: null },
20+
forkedFrom: null,
21+
delegatedFrom: {
22+
environmentId: parentEnvironmentId,
23+
threadId: ThreadId.make("parent-thread"),
24+
title: "Parent",
25+
},
26+
} as Partial<OrchestrationV2ThreadShell> as OrchestrationV2ThreadShell;
27+
28+
vi.mock(import("../../state/orchestration"), async (original) => ({
29+
...(await original()),
30+
threadProjectionRead: {
31+
label: "thread-projection-read",
32+
run: (_registry: unknown, input: unknown) => read(input),
33+
} as never,
34+
}));
35+
vi.mock(import("../../state/entities"), async (original) => ({
36+
...(await original()),
37+
useThreadProjection: () => null,
38+
useThreadRelationshipShells: () => [child],
39+
// The parent is absent from this client's shell, as for a parent never loaded here.
40+
useQuietThreadShell: () => null,
41+
}));
42+
vi.mock(import("../../state/environments"), async (original) => ({
43+
...(await original()),
44+
useEnvironment: (() => ({ label: "Linked" })) as never,
45+
}));
46+
vi.mock(import("../ui/toast"), async (original) => {
47+
const actual = await original();
48+
return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
49+
});
50+
51+
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
52+
53+
const childPath = `/${childEnvironmentId}/${childThreadId}`;
54+
const parentPath = `/${parentEnvironmentId}/parent-thread`;
55+
56+
const live = { _tag: "Success", value: { thread: { deletedAt: null } } };
57+
const deleted = { _tag: "Success", value: { thread: { deletedAt: "2026-10-30T06:20:20.897Z" } } };
58+
59+
// Renders the child's panel; each read of its parent answers with the next of `replies`.
60+
function renderChild(...replies: ReadonlyArray<unknown>) {
61+
read.mockReset();
62+
for (const reply of replies) read.mockImplementationOnce(async () => reply);
63+
toast.mockReset();
64+
return render(
65+
<ThreadRelationshipsPanel environmentId={childEnvironmentId} threadId={childThreadId} />,
66+
{ router: childPath },
67+
);
68+
}
69+
70+
const parentRow = (screen: Screen) => screen.getByRole("button", { name: /Parent/ });
71+
72+
it.each([
73+
{
74+
parent: "deleted there",
75+
reply: deleted,
76+
feedback: { type: "info", title: "The parent thread was deleted" },
77+
},
78+
{
79+
parent: "unreadable",
80+
reply: {
81+
_tag: "Failure",
82+
cause: Cause.fail(new Error("Failed to load orchestration V2 thread")),
83+
},
84+
feedback: { type: "error", title: "Could not open the parent thread" },
85+
},
86+
])("keeps the child open with feedback when its remote parent is $parent", async (row) => {
87+
await using screen = await renderChild(row.reply);
88+
await parentRow(screen).click();
89+
await vi.waitFor(() => expect(toast).toHaveBeenCalledWith(row.feedback));
90+
expect(read).toHaveBeenCalledWith({
91+
environmentId: parentEnvironmentId,
92+
input: { threadId: "parent-thread" },
93+
});
94+
expect(screen.router?.state.location.pathname).toBe(childPath);
95+
});
96+
97+
it("opens a remote parent this client has not loaded", async () => {
98+
await using screen = await renderChild(live);
99+
await parentRow(screen).click();
100+
await vi.waitFor(() => expect(screen.router?.state.location.pathname).toBe(parentPath));
101+
expect(toast).not.toHaveBeenCalled();
102+
});
103+
104+
it("leaves the user where they went when the parent read answers late", async () => {
105+
let answerLate!: (reply: unknown) => void;
106+
const late = new Promise((resolve) => {
107+
answerLate = resolve;
108+
});
109+
await using screen = await renderChild(late, deleted);
110+
await parentRow(screen).click();
111+
await screen.router?.navigate({ to: "/new" });
112+
answerLate(live);
113+
// The row takes a second click only after the first one has finished.
114+
await vi.waitFor(async () => {
115+
await parentRow(screen).click();
116+
expect(read).toHaveBeenCalledTimes(2);
117+
});
118+
await vi.waitFor(() => expect(toast).toHaveBeenCalledOnce());
119+
expect(screen.router?.latestLocation.pathname).toBe("/new");
120+
});

‎apps/web/src/components/chat/ThreadRelationshipsControl.tsx‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import {
4242
import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
4343
import { groupBy } from "effect/Array";
4444
import * as DateTime from "effect/DateTime";
45-
import { useNavigate } from "@tanstack/react-router";
45+
import { useNavigate, useRouter } from "@tanstack/react-router";
4646
import {
4747
ArrowRightIcon,
4848
BotIcon,
@@ -66,7 +66,7 @@ import {
6666
} from "../../state/entities";
6767
import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
6868
import { threadEnvironment } from "../../state/threads";
69-
import { orchestrationEnvironment } from "../../state/orchestration";
69+
import { orchestrationEnvironment, threadProjectionRead } from "../../state/orchestration";
7070
import { useAtomCommand } from "../../state/use-atom-command";
7171
import { AgentElapsed } from "./AgentElapsed";
7272
import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
@@ -299,13 +299,42 @@ function DelegatedFromRow(props: {
299299
readonly fallbackLabel: string | undefined;
300300
}) {
301301
const navigate = useNavigate();
302+
const router = useRouter();
302303
const { delegatedFrom } = props;
303304
const environment = useEnvironment(delegatedFrom.environmentId);
304305
const parentRef = scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
305306
// The title it had at delegation, until this client sees the parent itself.
306307
const parent = useQuietThreadShell(parentRef);
308+
const readParent = useAtomCommand(threadProjectionRead);
309+
const [opening, setOpening] = useState(false);
307310
const label = environment?.label ?? props.fallbackLabel;
308311
const title = parent?.title ?? delegatedFrom.title;
312+
// The parent may have been deleted there since delegation, and the shell can't
313+
// tell a deleted parent from one this client never loaded, so ask its environment.
314+
const openParent = async () => {
315+
if (opening) return;
316+
setOpening(true);
317+
const location = router.latestLocation;
318+
const result = await readParent({
319+
environmentId: delegatedFrom.environmentId,
320+
input: { threadId: delegatedFrom.threadId },
321+
});
322+
setOpening(false);
323+
// The read can outlast the user's stay on this thread; a late answer must not pull them back.
324+
if (router.latestLocation !== location) return;
325+
if (result._tag === "Failure") {
326+
toastManager.add({ type: "error", title: "Could not open the parent thread" });
327+
return;
328+
}
329+
if (result.value.thread.deletedAt !== null) {
330+
toastManager.add({ type: "info", title: "The parent thread was deleted" });
331+
return;
332+
}
333+
void navigate({
334+
to: "/$environmentId/$threadId",
335+
params: buildThreadRouteParams(parentRef),
336+
});
337+
};
309338
return (
310339
<li className="group relative flex h-8 items-center rounded-lg">
311340
<Tooltip>
@@ -317,12 +346,7 @@ function DelegatedFromRow(props: {
317346
variant="ghost"
318347
part="row"
319348
disabled={environment === null}
320-
onClick={() =>
321-
void navigate({
322-
to: "/$environmentId/$threadId",
323-
params: buildThreadRouteParams(parentRef),
324-
})
325-
}
349+
onClick={() => void openParent()}
326350
/>
327351
}
328352
>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
1+
import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts";
12
import { createOrchestrationEnvironmentAtoms } from "@t3tools/client-runtime/state/orchestration";
3+
import { createEnvironmentRpcCommand } from "@t3tools/client-runtime/state/runtime";
24

35
import { connectionAtomRuntime } from "../connection/runtime";
46

57
export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime);
8+
9+
/** One fresh read of a thread, for checking it still exists before opening it. */
10+
export const threadProjectionRead = createEnvironmentRpcCommand(connectionAtomRuntime, {
11+
label: "environment-data:orchestration-v2:thread-projection-read",
12+
tag: ORCHESTRATION_V2_WS_METHODS.getThreadProjection,
13+
});

0 commit comments

Comments
 (0)