Skip to content

Commit 0c0de57

Browse files
Yuruzuuclaude
andauthored
perf(web): terminal updates no longer re-render every sidebar row and chat (#28563)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 6ef66b6 commit 0c0de57

4 files changed

Lines changed: 122 additions & 13 deletions

File tree

‎apps/web/src/state/terminalSessions.test.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
import { describe, expect, it, vi } from "vite-plus/test";
22
import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";
33
import { selectRunningSubprocessTerminalIds } from "@t3tools/client-runtime/state/terminal";
4-
import { AtomRegistry } from "effect/reactivity";
4+
import * as Cause from "effect/Cause";
5+
import * as Option from "effect/Option";
6+
import { AsyncResult, AtomRegistry } from "effect/reactivity";
57

6-
import { attachedTerminalSessionAtom, selectKnownTerminalSessions } from "./terminalSessions";
8+
import {
9+
attachedTerminalSessionAtom,
10+
knownTerminalSessionsAtom,
11+
selectKnownTerminalSessions,
12+
} from "./terminalSessions";
713

814
const attachCalls = vi.hoisted(() => [] as unknown[]);
15+
const metadataAtom = await vi.hoisted(async () => {
16+
const { AsyncResult, Atom } = await import("effect/reactivity");
17+
return Atom.make<AsyncResult.AsyncResult<ReadonlyArray<TerminalSummary>>>(
18+
AsyncResult.initial(true),
19+
);
20+
});
921
vi.mock("./terminal", async () => {
1022
const { AsyncResult, Atom } = await import("effect/reactivity");
1123
return {
@@ -14,7 +26,7 @@ vi.mock("./terminal", async () => {
1426
attachCalls.push(request);
1527
return Atom.make(AsyncResult.initial(true));
1628
},
17-
metadata: () => Atom.make(AsyncResult.initial(true)),
29+
metadata: () => metadataAtom,
1830
},
1931
};
2032
});
@@ -100,6 +112,37 @@ describe("selectKnownTerminalSessions", () => {
100112
});
101113
});
102114

115+
describe("knownTerminalSessionsAtom", () => {
116+
const metadataResult = (...terminals: ReadonlyArray<TerminalSummary>) =>
117+
AsyncResult.success<ReadonlyArray<TerminalSummary>>(terminals);
118+
119+
it("notifies only when the thread's own terminals change", () => {
120+
const registry = AtomRegistry.make();
121+
const sessions = knownTerminalSessionsAtom(environmentA, threadA);
122+
expect(registry.get(sessions)).toBeNull();
123+
124+
const first = summary(threadA, "terminal-1");
125+
const other = summary(threadB, "terminal-1");
126+
registry.set(metadataAtom, metadataResult(first));
127+
const notified: unknown[] = [];
128+
const unsubscribe = registry.subscribe(sessions, (value) => notified.push(value));
129+
const before = registry.get(sessions);
130+
131+
registry.set(metadataAtom, metadataResult(first, other));
132+
registry.set(metadataAtom, metadataResult(first, { ...other, label: "Renamed" }));
133+
expect(notified).toEqual([]);
134+
expect(registry.get(sessions)).toBe(before);
135+
136+
registry.set(metadataAtom, metadataResult({ ...first, label: "Renamed" }, other));
137+
expect(notified).toHaveLength(1);
138+
139+
const previousSuccess = Option.some(metadataResult(first));
140+
registry.set(metadataAtom, AsyncResult.failure(Cause.die("unavailable"), { previousSuccess }));
141+
expect(registry.get(sessions)).toBeNull();
142+
unsubscribe();
143+
});
144+
});
145+
103146
describe("attachedTerminalSessionAtom", () => {
104147
it("attaches with the launch input it was keyed by", () => {
105148
attachCalls.length = 0;

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

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useAtomValue } from "@effect/atom-react";
12
import {
23
combineTerminalSessionState,
34
EMPTY_TERMINAL_BUFFER_STATE,
@@ -19,7 +20,7 @@ import * as Option from "effect/Option";
1920
import * as Schema from "effect/Schema";
2021
import { AsyncResult, Atom } from "effect/reactivity";
2122

22-
import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
23+
import { formatEnvironmentQueryError } from "./query";
2324
import { terminalEnvironment } from "./terminal";
2425
import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session";
2526

@@ -194,22 +195,40 @@ export function attachedTerminalSessionAtom(
194195
return attachedTerminalSessionFamily(JSON.stringify([environmentId, terminal]));
195196
}
196197

198+
const NO_KNOWN_TERMINAL_SESSIONS_ATOM = Atom.make<ReadonlyArray<KnownTerminalSession> | null>(null);
199+
200+
const decodeKnownSessionsKey = Schema.decodeUnknownOption(
201+
Schema.fromJsonString(Schema.Tuple([EnvironmentId, Schema.NullOr(ThreadId)])),
202+
);
203+
204+
// Derived per thread, so a terminal update elsewhere in the environment notifies no one here.
205+
const knownTerminalSessionsFamily = Atom.family((key: string) => {
206+
const [environmentId, threadId] = Option.getOrThrow(decodeKnownSessionsKey(key));
207+
return Atom.make((get) => {
208+
const metadata = get(terminalEnvironment.metadata({ environmentId, input: null }));
209+
return metadata._tag === "Success"
210+
? selectKnownTerminalSessions(metadata.value, environmentId, threadId)
211+
: null;
212+
}).pipe(Atom.withLabel(`web-known-terminal-sessions:${key}`));
213+
});
214+
215+
export function knownTerminalSessionsAtom(
216+
environmentId: EnvironmentId,
217+
threadId: ThreadId | null,
218+
): Atom.Atom<ReadonlyArray<KnownTerminalSession> | null> {
219+
return knownTerminalSessionsFamily(JSON.stringify([environmentId, threadId]));
220+
}
221+
197222
export function useKnownTerminalSessions(input: {
198223
readonly environmentId: EnvironmentId | null;
199224
readonly threadId: ThreadId | null;
200225
}): ReadonlyArray<KnownTerminalSession> | null {
201226
const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
202-
const metadata = useEnvironmentQuery(
227+
return useAtomValue(
203228
input.environmentId === null || !canRead
204-
? null
205-
: terminalEnvironment.metadata({
206-
environmentId: input.environmentId,
207-
input: null,
208-
}),
229+
? NO_KNOWN_TERMINAL_SESSIONS_ATOM
230+
: knownTerminalSessionsAtom(input.environmentId, input.threadId),
209231
);
210-
return metadata.data === null || metadata.error !== null
211-
? null
212-
: selectKnownTerminalSessions(metadata.data, input.environmentId, input.threadId);
213232
}
214233

215234
export function useThreadRunningTerminalIds(input: {

‎apps/web/test/appScenarios.renders.tsx‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { getRouter, type AppRouter } from "~/router";
1717
import {
1818
ENVIRONMENT_ID,
1919
assistantItem,
20+
emitTerminalMetadata,
2021
emitThreadEvent,
2122
installFakeEnvironment,
2223
isThreadSubscribed,
@@ -50,6 +51,7 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
5051
const HISTORY_TURNS = 20;
5152
const STREAM_DELTAS = 30;
5253
const TYPED_TEXT = "fix the flaky tests!";
54+
const TERMINAL_UPDATES = 20;
5355
// The stream scenario leaves a turn on its thread, so it streams into one no other scenario opens.
5456
const THREADS = ["thread-warm", "thread-a", "thread-b", "thread-live"].map((name) =>
5557
threadWithHistory(name, HISTORY_TURNS),
@@ -211,6 +213,37 @@ it("app-stream-assistant-turn", async () => {
211213
await report("app-stream-assistant-turn", [counted], { commits: false });
212214
});
213215

216+
it("app-terminal-updates-in-other-thread", async () => {
217+
using _clock = frozenClock();
218+
await using _app = (await openThread(A)).screen;
219+
const counted = await measure(async () => {
220+
for (let update = 0; update < TERMINAL_UPDATES; update++) {
221+
await act(() =>
222+
emitTerminalMetadata({
223+
type: "upsert",
224+
terminal: {
225+
threadId: B,
226+
terminalId: "default",
227+
cwd: "/repo",
228+
worktreePath: null,
229+
status: "running",
230+
pid: 42,
231+
exitCode: null,
232+
exitSignal: null,
233+
hasRunningSubprocess: true,
234+
label: `command ${update}`,
235+
updatedAt: `2026-03-18T09:01:${String(update).padStart(2, "0")}.000Z`,
236+
},
237+
}),
238+
);
239+
}
240+
});
241+
// Only thread B's sidebar row shows these updates.
242+
expect(counted.components.ChatView).toBeUndefined();
243+
expect(counted.components.SidebarThreadRow).toBe(TERMINAL_UPDATES);
244+
await report("app-terminal-updates-in-other-thread", [counted]);
245+
});
246+
214247
it("app-type-in-composer", async () => {
215248
using _clock = frozenClock();
216249
await using _app = (await openThread(A)).screen;

‎apps/web/test/fakeEnvironment.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
type OrchestrationV2ThreadShell,
2626
type OrchestrationV2ThreadStreamItem,
2727
type OrchestrationV2TurnItem,
28+
type TerminalMetadataStreamEvent,
2829
} from "@t3tools/contracts";
2930
import type {
3031
ConnectionAttemptError,
@@ -307,6 +308,7 @@ const json = (body: unknown, status = 200) =>
307308

308309
// Keyed by thread id: a live thread subscription's queue, for pushing events to it.
309310
const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
311+
let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
310312
let threads: ReadonlyArray<FakeThread> = [];
311313
let sequence = 1;
312314

@@ -324,6 +326,13 @@ const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>
324326
);
325327

326328
const handlers: Record<string, (input: never) => unknown> = {
329+
[WS_METHODS.subscribeTerminalMetadata]: () =>
330+
subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
331+
terminalMetadataSubscriber = queue;
332+
return () => {
333+
if (terminalMetadataSubscriber === queue) terminalMetadataSubscriber = null;
334+
};
335+
}),
327336
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
328337
subscribe<OrchestrationV2ShellStreamItem>([
329338
{
@@ -437,6 +446,11 @@ export function installFakeEnvironment(fixtures: ReadonlyArray<FakeThread>): Dis
437446

438447
type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
439448

449+
export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> {
450+
if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription");
451+
await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event));
452+
}
453+
440454
/** Whether the app holds a live subscription to the thread, so events reach it. */
441455
export function isThreadSubscribed(threadId: ThreadId): boolean {
442456
return threadSubscribers.has(threadId);

0 commit comments

Comments
 (0)