Skip to content

Commit dfded9d

Browse files
ScottN-PVmaria-rcksjuliusmarminge
authored
fix(web): keep the child thread open when its remote parent was deleted (pingdotgg#27436)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent fbd77b9 commit dfded9d

3 files changed

Lines changed: 167 additions & 6 deletions

File tree

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
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 { act, 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+
threadTitlesRead: {
31+
label: "thread-titles-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: { "parent-thread": "Parent" } };
57+
const deleted = { _tag: "Success", value: {} };
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
66+
environmentId={childEnvironmentId}
67+
threadId={childThreadId}
68+
showLineage
69+
showSideChats={false}
70+
/>,
71+
{ router: childPath },
72+
);
73+
}
74+
75+
const parentRow = (screen: Screen) => screen.getByRole("button", { name: /Parent/ });
76+
77+
it.each([
78+
{
79+
parent: "deleted there",
80+
reply: deleted,
81+
feedback: { type: "info", title: "The parent thread was deleted" },
82+
},
83+
{
84+
parent: "unreadable",
85+
reply: {
86+
_tag: "Failure",
87+
cause: Cause.fail(new Error("Failed to load orchestration V2 thread")),
88+
},
89+
feedback: { type: "error", title: "Could not open the parent thread" },
90+
},
91+
])("keeps the child open with feedback when its remote parent is $parent", async (row) => {
92+
await using screen = await renderChild(row.reply);
93+
await parentRow(screen).click();
94+
await vi.waitFor(() => expect(toast).toHaveBeenCalledWith(row.feedback));
95+
expect(read).toHaveBeenCalledWith({
96+
environmentId: parentEnvironmentId,
97+
input: { threadIds: ["parent-thread"] },
98+
});
99+
expect(screen.router?.state.location.pathname).toBe(childPath);
100+
});
101+
102+
it("opens a remote parent this client has not loaded", async () => {
103+
await using screen = await renderChild(live);
104+
await parentRow(screen).click();
105+
await vi.waitFor(() => expect(screen.router?.state.location.pathname).toBe(parentPath));
106+
expect(toast).not.toHaveBeenCalled();
107+
});
108+
109+
it("leaves the user where they went when the parent read answers late", async () => {
110+
let answerLate!: (reply: unknown) => void;
111+
const late = new Promise((resolve) => {
112+
answerLate = resolve;
113+
});
114+
await using screen = await renderChild(late, deleted);
115+
await parentRow(screen).click();
116+
await screen.router?.navigate({ to: "/new" });
117+
await act(async () => {
118+
answerLate(live);
119+
await late;
120+
});
121+
expect(toast).not.toHaveBeenCalled();
122+
expect(screen.router?.latestLocation.pathname).toBe("/new");
123+
await parentRow(screen).click();
124+
await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2));
125+
await vi.waitFor(() => expect(toast).toHaveBeenCalledOnce());
126+
expect(screen.router?.latestLocation.pathname).toBe("/new");
127+
});

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

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ import {
4343
import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
4444
import { groupBy } from "effect/Array";
4545
import * as DateTime from "effect/DateTime";
46-
import { useNavigate } from "@tanstack/react-router";
46+
import { useNavigate, useRouter } from "@tanstack/react-router";
4747
import {
4848
ArrowRightIcon,
4949
BotIcon,
@@ -75,7 +75,7 @@ import {
7575
deriveProviderInstanceEntries,
7676
} from "../../providerInstances";
7777
import { threadEnvironment } from "../../state/threads";
78-
import { orchestrationEnvironment } from "../../state/orchestration";
78+
import { orchestrationEnvironment, threadTitlesRead } from "../../state/orchestration";
7979
import { useAtomCommand } from "../../state/use-atom-command";
8080
import { useEnvironmentQuery } from "../../state/query";
8181
import { AgentElapsed } from "./AgentElapsed";
@@ -339,13 +339,43 @@ function DelegatedFromRow(props: {
339339
readonly fallbackLabel: string | undefined;
340340
}) {
341341
const navigate = useNavigate();
342+
const router = useRouter();
342343
const { delegatedFrom } = props;
343344
const environment = useEnvironment(delegatedFrom.environmentId);
344345
const parentRef = scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
345346
// The title it had at delegation, until this client sees the parent itself.
346347
const parent = useQuietThreadShell(parentRef);
348+
const readParent = useAtomCommand(threadTitlesRead);
349+
const [opening, setOpening] = useState(false);
347350
const label = environment?.label ?? props.fallbackLabel;
348351
const title = parent?.title ?? delegatedFrom.title;
352+
// The parent may have been deleted there since delegation, and the shell can't
353+
// tell a deleted parent from one this client never loaded, so ask its environment.
354+
const openParent = async () => {
355+
if (opening) return;
356+
setOpening(true);
357+
const location = router.latestLocation;
358+
const result = await readParent({
359+
environmentId: delegatedFrom.environmentId,
360+
input: { threadIds: [delegatedFrom.threadId] },
361+
});
362+
setOpening(false);
363+
// The read can outlast the user's stay on this thread; a late answer must not pull them back.
364+
if (router.latestLocation !== location) return;
365+
if (result._tag === "Failure") {
366+
toastManager.add({ type: "error", title: "Could not open the parent thread" });
367+
return;
368+
}
369+
// Deleted and unknown threads are absent from the titles.
370+
if (result.value[delegatedFrom.threadId] === undefined) {
371+
toastManager.add({ type: "info", title: "The parent thread was deleted" });
372+
return;
373+
}
374+
void navigate({
375+
to: "/$environmentId/$threadId",
376+
params: buildThreadRouteParams(parentRef),
377+
});
378+
};
349379
return (
350380
<li className="group relative flex h-8 items-center rounded-lg">
351381
<Tooltip>
@@ -359,10 +389,7 @@ function DelegatedFromRow(props: {
359389
aria-disabled={environment === null || undefined}
360390
onClick={() => {
361391
if (environment === null) return;
362-
void navigate({
363-
to: "/$environmentId/$threadId",
364-
params: buildThreadRouteParams(parentRef),
365-
});
392+
void openParent();
366393
}}
367394
/>
368395
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
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
import { environmentShell } from "./shell";
57

68
export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime, {
79
shellState: environmentShell.stateValueAtom,
810
});
11+
12+
export const threadTitlesRead = createEnvironmentRpcCommand(connectionAtomRuntime, {
13+
label: "environment-data:orchestration:thread-titles-read",
14+
tag: ORCHESTRATION_V2_WS_METHODS.getThreadTitles,
15+
});

0 commit comments

Comments
 (0)