Skip to content

Commit 14754e0

Browse files
perf(web): another thread streaming no longer re-renders the app root and thread panels
FirstRunGate, ThreadRelationshipsPanel, useThreadVisitedMigration (in AppSidebarLayout) and usePullRequestStack subscribed to the whole thread shell list, so every shell update of any thread re-rendered them. Each now reads only the fact it needs through an atom that keeps its value while that fact is unchanged, or subscribes outside render. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b987b57 commit 14754e0

7 files changed

Lines changed: 218 additions & 42 deletions

File tree

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ const state = vi.hoisted(() => ({
2525
vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));
2626
vi.mock("../../state/entities", () => ({
2727
useThreadProjection: () => ({ projection: state.projection }),
28-
useThreadShells: () => state.shells,
28+
useThreadRelationshipShells: (ref: { readonly environmentId: string }) =>
29+
(state.shells as ReadonlyArray<{ readonly environmentId: string; readonly source: unknown }>)
30+
.filter((shell) => shell.environmentId === ref.environmentId)
31+
.map((shell) => shell.source),
2932
useProjects: () => state.projects,
3033
useServerConfigs: () => state.configs,
3134
}));

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

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ import {
5656
useProjects,
5757
useServerConfigs,
5858
useThreadProjection,
59-
useThreadShells,
59+
useThreadRelationshipShells,
6060
} from "../../state/entities";
6161
import { threadEnvironment } from "../../state/threads";
6262
import { orchestrationEnvironment } from "../../state/orchestration";
@@ -211,7 +211,7 @@ export function ThreadRelationshipsPanel(props: {
211211
const ref = scopeThreadRef(props.environmentId, props.threadId);
212212
const projection = useThreadProjection(ref)?.projection ?? null;
213213
const serverConfigs = useServerConfigs();
214-
const threadShells = useThreadShells();
214+
const relationshipShells = useThreadRelationshipShells(ref);
215215
const allProjects = useProjects();
216216
const archived = useArchivedThreadSnapshots([props.environmentId]);
217217
const navigate = useNavigate();
@@ -257,9 +257,7 @@ export function ThreadRelationshipsPanel(props: {
257257
deriveWorkflowGroups(runtimeSubagents).map((group) => [group.workflow.id, group]),
258258
);
259259
const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
260-
...threadShells
261-
.filter((thread) => thread.environmentId === props.environmentId)
262-
.map((thread) => thread.source),
260+
...relationshipShells,
263261
...(archivedShells ?? []),
264262
];
265263
const graph = deriveThreadRelationshipGraph({ threads: shells, projection });

‎apps/web/src/components/onboarding/FirstRunGate.tsx‎

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,7 @@ import {
1919
transitionFirstRunGateState,
2020
type FirstRunGateState,
2121
} from "../../onboarding/firstRun.logic";
22-
import {
23-
useAllEnvironmentShellsBootstrapped,
24-
useProjects,
25-
useThreadShells,
26-
} from "../../state/entities";
22+
import { useAllEnvironmentShellsBootstrapped, useProjects } from "../../state/entities";
2723
import { useEnvironments } from "../../state/environments";
2824
import { environmentProjects } from "../../state/projects";
2925
import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";
@@ -61,6 +57,18 @@ const workspaceEvidenceLiveAtom = Atom.make((get) => {
6157
return true;
6258
}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));
6359

60+
// The gate only needs how many threads exist and, while there is at most one,
61+
// that thread; a shell update of any thread in a populated workspace must not
62+
// re-render the app root.
63+
const threadCountAtom = Atom.make(
64+
(get) => get(environmentThreadShells.threadShellsAtom).length,
65+
).pipe(Atom.withLabel("web-onboarding-thread-count"));
66+
67+
const soleThreadAtom = Atom.make((get) => {
68+
const threads = get(environmentThreadShells.threadShellsAtom);
69+
return threads.length === 1 ? threads[0]! : null;
70+
}).pipe(Atom.withLabel("web-onboarding-sole-thread"));
71+
6472
export function FirstRunGate({
6573
enabled,
6674
hostedStatic,
@@ -79,7 +87,8 @@ export function FirstRunGate({
7987
const bootstrapped = useAllEnvironmentShellsBootstrapped();
8088
const { environments, isReady: environmentCatalogReady } = useEnvironments();
8189
const projects = useProjects();
82-
const threads = useThreadShells();
90+
const threadCount = useAtomValue(threadCountAtom);
91+
const soleThread = useAtomValue(soleThreadAtom);
8392
const serverConfig = useAtomValue(primaryServerConfigAtom);
8493
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
8594
const primaryShellLive = useAtomValue(primaryShellLiveAtom);
@@ -99,16 +108,18 @@ export function FirstRunGate({
99108
// would mean `npx t3` users never see the wizard.
100109
const serverCwd = serverConfig?.cwd ?? null;
101110
const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
102-
const workspaceFresh = isFreshFirstRunWorkspace({
103-
primaryEnvironmentId,
104-
serverCwd,
105-
bootstrapProjectId: serverWelcome?.bootstrapProjectId,
106-
bootstrapThreadId: serverWelcome?.bootstrapThreadId,
107-
bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
108-
bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
109-
projects,
110-
threads,
111-
});
111+
const workspaceFresh =
112+
threadCount <= 1 &&
113+
isFreshFirstRunWorkspace({
114+
primaryEnvironmentId,
115+
serverCwd,
116+
bootstrapProjectId: serverWelcome?.bootstrapProjectId,
117+
bootstrapThreadId: serverWelcome?.bootstrapThreadId,
118+
bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
119+
bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
120+
projects,
121+
threads: soleThread === null ? [] : [soleThread],
122+
});
112123

113124
const { decision: nextDecision, persistCompletion } = hostedStatic
114125
? resolveHostedFirstRunDecision({
@@ -133,7 +144,7 @@ export function FirstRunGate({
133144
serverConfigAvailable: serverConfig !== null,
134145
workspaceFresh,
135146
projectCount: projects.length,
136-
threadCount: threads.length,
147+
threadCount,
137148
});
138149

139150
if (decision !== "wizard" && hydrated) {

‎apps/web/src/hooks/useThreadVisitedMigration.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
1+
import { RegistryContext } from "@effect/atom-react";
12
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2-
import { useEffect } from "react";
3+
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4+
import { useContext, useEffect, useEffectEvent } from "react";
35

4-
import { useThreadShells } from "../state/entities";
5-
import { threadEnvironment } from "../state/threads";
6+
import { environmentThreadShells, threadEnvironment } from "../state/threads";
67
import { useAtomCommand } from "../state/use-atom-command";
78
import { useUiStateStore } from "../uiStateStore";
89

910
const migratedThreadKeys = new Set<string>();
1011

12+
// Subscribes outside render: the migration only acts on threads it has not
13+
// seen, so a shell update must not re-render the layout that mounts it.
1114
export function useThreadVisitedMigration(): void {
12-
const threads = useThreadShells();
15+
const registry = useContext(RegistryContext);
1316
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
14-
useEffect(() => {
17+
const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {
1518
for (const thread of threads) {
1619
// Field absent → the environment's server has no visited tracking; keep
1720
// the local value in play and reconsider if the server upgrades.
@@ -30,5 +33,10 @@ export function useThreadVisitedMigration(): void {
3033
input: { threadId: thread.id, visitedAt: local },
3134
});
3235
}
33-
}, [threads, visitThreadMutation]);
36+
});
37+
useEffect(
38+
() =>
39+
registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),
40+
[registry],
41+
);
3442
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import type {
2+
OrchestrationV2ThreadProjection,
3+
OrchestrationV2ThreadShell,
4+
} from "@t3tools/contracts";
5+
import { describe, expect, it } from "vite-plus/test";
6+
7+
import { selectThreadRelationshipShells } from "./entities";
8+
9+
type Projection = Parameters<typeof selectThreadRelationshipShells>[1];
10+
11+
const shell = (id: string, parentThreadId: string | null = null) =>
12+
({
13+
id,
14+
forkedFrom: null,
15+
lineage: { parentThreadId, relationshipToParent: parentThreadId === null ? null : "fork" },
16+
}) as unknown as OrchestrationV2ThreadShell;
17+
18+
const threadId = "current" as OrchestrationV2ThreadShell["id"];
19+
20+
describe("selectThreadRelationshipShells", () => {
21+
it("keeps the thread, its parent, its children and the threads its projection names", () => {
22+
const threads = [
23+
shell("current", "parent"),
24+
shell("parent"),
25+
shell("child", "current"),
26+
shell("subagent-child"),
27+
shell("workflow-member"),
28+
shell("transfer-source"),
29+
shell("unrelated"),
30+
shell("grandchild", "child"),
31+
];
32+
const projection = {
33+
thread: threads[0],
34+
subagents: [
35+
{
36+
childThreadId: "subagent-child",
37+
workflow: { agents: [{ childThreadId: "workflow-member" }, {}] },
38+
},
39+
{ childThreadId: null },
40+
],
41+
contextTransfers: [{ sourceThreadId: "transfer-source", targetThreadId: "current" }],
42+
} as unknown as Pick<
43+
OrchestrationV2ThreadProjection,
44+
"thread" | "subagents" | "contextTransfers"
45+
>;
46+
47+
expect(
48+
selectThreadRelationshipShells(threadId, projection, threads).map((thread) => thread.id),
49+
).toEqual([
50+
"current",
51+
"parent",
52+
"child",
53+
"subagent-child",
54+
"workflow-member",
55+
"transfer-source",
56+
]);
57+
});
58+
59+
it("finds the parent from the shell before the projection loads", () => {
60+
const threads = [shell("current", "parent"), shell("parent"), shell("unrelated")];
61+
expect(
62+
selectThreadRelationshipShells(threadId, null as Projection, threads).map(
63+
(thread) => thread.id,
64+
),
65+
).toEqual(["current", "parent"]);
66+
});
67+
});

‎apps/web/src/state/entities.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,19 @@ import {
99
type EnvironmentThreadStatus,
1010
type ThreadHistoryMeta,
1111
} from "@t3tools/client-runtime/state/threads";
12+
import {
13+
arrayElementsEqual,
14+
parseThreadKey,
15+
threadKey,
16+
} from "@t3tools/client-runtime/state/entities";
1217
import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
13-
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
18+
import type {
19+
EnvironmentId,
20+
OrchestrationV2ProjectedTurnItem,
21+
OrchestrationV2ThreadProjection,
22+
OrchestrationV2ThreadShell,
23+
ThreadId,
24+
} from "@t3tools/contracts";
1425
import { Atom } from "effect/reactivity";
1526
import { appAtomRegistry } from "../rpc/atomRegistry";
1627
import { environmentProjects } from "./projects";
@@ -298,3 +309,70 @@ export function readEnvironmentThreadRefs(
298309
export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
299310
return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
300311
}
312+
313+
function shellParentThreadId(
314+
thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
315+
): ThreadId | null {
316+
return thread.forkedFrom?.type === "run"
317+
? thread.forkedFrom.threadId
318+
: thread.lineage.parentThreadId;
319+
}
320+
321+
/**
322+
* The live shells the panel's immediate relationships can reach: the thread,
323+
* its parent, its children, and the threads its subagents, workflow members and
324+
* context transfers name. Keeps its array while those shells are unchanged, so
325+
* another thread streaming in the same environment does not re-render the panel.
326+
*/
327+
/** Exported for tests. */
328+
export function selectThreadRelationshipShells(
329+
threadId: ThreadId,
330+
projection: Pick<
331+
OrchestrationV2ThreadProjection,
332+
"thread" | "subagents" | "contextTransfers"
333+
> | null,
334+
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
335+
): ReadonlyArray<OrchestrationV2ThreadShell> {
336+
const named = new Set<string>([threadId]);
337+
if (projection !== null) {
338+
const parentThreadId = shellParentThreadId(projection.thread);
339+
if (parentThreadId !== null) named.add(parentThreadId);
340+
for (const subagent of projection.subagents) {
341+
if (subagent.childThreadId !== null) named.add(subagent.childThreadId);
342+
for (const agent of subagent.workflow?.agents ?? []) {
343+
if (agent.childThreadId !== undefined) named.add(agent.childThreadId);
344+
}
345+
}
346+
for (const transfer of projection.contextTransfers) {
347+
named.add(transfer.sourceThreadId);
348+
named.add(transfer.targetThreadId);
349+
}
350+
}
351+
const current = threads.find((thread) => thread.id === threadId);
352+
const currentParentId = current === undefined ? null : shellParentThreadId(current);
353+
if (currentParentId !== null) named.add(currentParentId);
354+
return threads.filter(
355+
(thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId,
356+
);
357+
}
358+
359+
const relationshipShellsAtomFamily = Atom.family((key: string) => {
360+
const ref = parseThreadKey(key);
361+
let previous: ReadonlyArray<OrchestrationV2ThreadShell> = [];
362+
return Atom.make((get) => {
363+
const next = selectThreadRelationshipShells(
364+
ref.threadId,
365+
get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
366+
get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
367+
);
368+
if (arrayElementsEqual(previous, next)) return previous;
369+
previous = next;
370+
return next;
371+
}).pipe(Atom.withLabel(`web-thread-relationship-shells:${key}`));
372+
});
373+
374+
export function useThreadRelationshipShells(
375+
ref: ScopedThreadRef,
376+
): ReadonlyArray<OrchestrationV2ThreadShell> {
377+
return useAtomValue(relationshipShellsAtomFamily(threadKey(ref)));
378+
}
Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,39 @@
1-
import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
1+
import { useAtomValue } from "@effect/atom-react";
2+
import { ThreadPullRequestLink, type EnvironmentId, type PullRequestRef } from "@t3tools/contracts";
3+
import { Atom } from "effect/reactivity";
4+
import * as Schema from "effect/Schema";
25
import {
36
savedPullRequestStack,
47
pullRequestStackView,
58
} from "../components/pullRequest/pullRequestStackSnapshot";
6-
import { useThreadShells } from "./entities";
79
import { pullRequestStackAtom } from "./pullRequests";
810
import { useEnvironmentQuery } from "./query";
11+
import { environmentThreadShells } from "./threads";
12+
13+
const sameLinks = Schema.toEquivalence(Schema.Array(ThreadPullRequestLink));
14+
15+
// A shell update re-sends a thread's links as a new array, so equal links keep
16+
// the previous list and a streaming thread does not re-render the stack.
17+
const environmentPullRequestLinksAtom = Atom.family((environmentId: EnvironmentId) => {
18+
let previous: ReadonlyArray<ThreadPullRequestLink> = [];
19+
return Atom.make((get) => {
20+
const next = get(environmentThreadShells.environmentThreadsAtom(environmentId)).flatMap(
21+
(thread) => thread.pullRequests ?? [],
22+
);
23+
if (sameLinks(previous, next)) return previous;
24+
previous = next;
25+
return next;
26+
}).pipe(Atom.withLabel(`web-environment-pull-request-links:${environmentId}`));
27+
});
928

1029
export function usePullRequestStack(
1130
environmentId: EnvironmentId,
1231
reference: PullRequestRef | null,
1332
) {
14-
const threads = useThreadShells();
33+
const links = useAtomValue(environmentPullRequestLinksAtom(environmentId));
34+
const saved = reference === null ? null : savedPullRequestStack(links, reference);
1535
const query = useEnvironmentQuery(
1636
reference === null ? null : pullRequestStackAtom({ environmentId, input: reference }),
1737
);
18-
const saved =
19-
reference === null
20-
? null
21-
: savedPullRequestStack(
22-
threads
23-
.filter((thread) => thread.environmentId === environmentId)
24-
.flatMap((thread) => thread.pullRequests ?? []),
25-
reference,
26-
);
2738
return { ...query, ...pullRequestStackView(query, saved) };
2839
}

0 commit comments

Comments
 (0)