@devries-cameron20 / t3code Mirror · read-only / commits / 0c0de57dfd
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 07:00 UTC

perf(web): terminal updates no longer re-render every sidebar row and chat (#28563)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Andrei committed Nov 2, 2026 at 05:55 UTC 0c0de57dfd695e836ceeaa6856698ffdd8059c60
4 files changed +122 -13
apps/web/src/state/terminalSessions.test.ts
+46 -3
@@ -1,11 +1,23 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2 import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";
3 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";
7
6 -import { attachedTerminalSessionAtom, selectKnownTerminalSessions } from "./terminalSessions";
8 +import {
9 + attachedTerminalSessionAtom,
10 + knownTerminalSessionsAtom,
11 + selectKnownTerminalSessions,
12 +} from "./terminalSessions";
13
14 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 +});
21 vi.mock("./terminal", async () => {
22 const { AsyncResult, Atom } = await import("effect/reactivity");
23 return {
@@ -14,7 +26,7 @@ vi.mock("./terminal", async () => {
26 attachCalls.push(request);
27 return Atom.make(AsyncResult.initial(true));
28 },
17 - metadata: () => Atom.make(AsyncResult.initial(true)),
29 + metadata: () => metadataAtom,
30 },
31 };
32 });
@@ -100,6 +112,37 @@ describe("selectKnownTerminalSessions", () => {
112 });
113 });
114
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 +
146 describe("attachedTerminalSessionAtom", () => {
147 it("attaches with the launch input it was keyed by", () => {
148 attachCalls.length = 0;
apps/web/src/state/terminalSessions.ts
+29 -10
@@ -1,3 +1,4 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import {
3 combineTerminalSessionState,
4 EMPTY_TERMINAL_BUFFER_STATE,
@@ -19,7 +20,7 @@ import * as Option from "effect/Option";
20 import * as Schema from "effect/Schema";
21 import { AsyncResult, Atom } from "effect/reactivity";
22
22 -import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
23 +import { formatEnvironmentQueryError } from "./query";
24 import { terminalEnvironment } from "./terminal";
25 import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session";
26
@@ -194,22 +195,40 @@ export function attachedTerminalSessionAtom(
195 return attachedTerminalSessionFamily(JSON.stringify([environmentId, terminal]));
196 }
197
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 +
222 export function useKnownTerminalSessions(input: {
223 readonly environmentId: EnvironmentId | null;
224 readonly threadId: ThreadId | null;
225 }): ReadonlyArray<KnownTerminalSession> | null {
226 const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
202 - const metadata = useEnvironmentQuery(
227 + return useAtomValue(
228 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),
231 );
210 - return metadata.data === null || metadata.error !== null
211 - ? null
212 - : selectKnownTerminalSessions(metadata.data, input.environmentId, input.threadId);
232 }
233
234 export function useThreadRunningTerminalIds(input: {
apps/web/test/appScenarios.renders.tsx
+33
@@ -17,6 +17,7 @@ import { getRouter, type AppRouter } from "~/router";
17 import {
18 ENVIRONMENT_ID,
19 assistantItem,
20 + emitTerminalMetadata,
21 emitThreadEvent,
22 installFakeEnvironment,
23 isThreadSubscribed,
@@ -50,6 +51,7 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
51 const HISTORY_TURNS = 20;
52 const STREAM_DELTAS = 30;
53 const TYPED_TEXT = "fix the flaky tests!";
54 +const TERMINAL_UPDATES = 20;
55 // The stream scenario leaves a turn on its thread, so it streams into one no other scenario opens.
56 const THREADS = ["thread-warm", "thread-a", "thread-b", "thread-live"].map((name) =>
57 threadWithHistory(name, HISTORY_TURNS),
@@ -211,6 +213,37 @@ it("app-stream-assistant-turn", async () => {
213 await report("app-stream-assistant-turn", [counted], { commits: false });
214 });
215
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 +
247 it("app-type-in-composer", async () => {
248 using _clock = frozenClock();
249 await using _app = (await openThread(A)).screen;
apps/web/test/fakeEnvironment.ts
+14
@@ -25,6 +25,7 @@ import {
25 type OrchestrationV2ThreadShell,
26 type OrchestrationV2ThreadStreamItem,
27 type OrchestrationV2TurnItem,
28 + type TerminalMetadataStreamEvent,
29 } from "@t3tools/contracts";
30 import type {
31 ConnectionAttemptError,
@@ -307,6 +308,7 @@ const json = (body: unknown, status = 200) =>
308
309 // Keyed by thread id: a live thread subscription's queue, for pushing events to it.
310 const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
311 +let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
312 let threads: ReadonlyArray<FakeThread> = [];
313 let sequence = 1;
314
@@ -324,6 +326,13 @@ const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>
326 );
327
328 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 + }),
336 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
337 subscribe<OrchestrationV2ShellStreamItem>([
338 {
@@ -437,6 +446,11 @@ export function installFakeEnvironment(fixtures: ReadonlyArray<FakeThread>): Dis
446
447 type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
448
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 +
454 /** Whether the app holds a live subscription to the thread, so events reach it. */
455 export function isThreadSubscribed(threadId: ThreadId): boolean {
456 return threadSubscribers.has(threadId);