@devries-cameron20 / t3code Mirror · read-only / commits / 4c2f04d35d
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 21, 16:00 UTC

fix(web): queued runs, relationships and changed files no longer re-render on every streamed token (#24055)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Batuhan1999 committed Nov 14, 2026 at 11:24 UTC 4c2f04d35d371c2b2ecb04b283e282325026be8a
9 files changed +155 -27
apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+89 -8
@@ -1,3 +1,5 @@
1 +import { RegistryContext } from "@effect/atom-react";
2 +import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads";
3 import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
4 import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
5 import {
@@ -5,12 +7,14 @@ import {
7 toComposerContextId,
8 } from "@t3tools/shared/composerContextReferences";
9 import * as DateTime from "effect/DateTime";
8 -import type { ComponentProps } from "react";
10 +import * as Option from "effect/Option";
11 +import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity";
12 +import { Profiler, type ComponentProps } from "react";
13 import { expect, it, vi } from "vite-plus/test";
14 import { page } from "vite-plus/test/browser";
15
16 const state = vi.hoisted(() => ({
13 - projection: null as unknown,
17 + threadState: null as unknown as Atom.Writable<AsyncResult.AsyncResult<EnvironmentThreadState>>,
18 workflow: null as unknown,
19 }));
20
@@ -21,7 +25,6 @@ vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importO
25
26 vi.mock(import("../../state/entities"), async (importOriginal) => ({
27 ...(await importOriginal()),
24 - useThreadProjection: (() => state.projection) as never,
28 // The linked environment is connected, but its thread is not in the loaded shell.
29 useQuietThreadShell: ((target: { readonly environmentId: string } | null) =>
30 target === null || target.environmentId === "environment:linked"
@@ -42,6 +45,25 @@ vi.mock(import("../../state/query"), async (importOriginal) => ({
45 })) as never,
46 }));
47
48 +// The thread detail atoms are real, fed by one state atom the test writes.
49 +vi.mock(import("../../state/threads"), async (importOriginal) => {
50 + const { createEnvironmentThreadDetailAtoms, EMPTY_ENVIRONMENT_THREAD_STATE } =
51 + await import("@t3tools/client-runtime/state/threads");
52 + const { AsyncResult, Atom } = await import("effect/reactivity");
53 + const Option = await import("effect/Option");
54 + const { makeThreadProjectionFixture } = await import("../../test-fixtures");
55 + state.threadState = Atom.make<AsyncResult.AsyncResult<EnvironmentThreadState>>(
56 + AsyncResult.success({
57 + ...EMPTY_ENVIRONMENT_THREAD_STATE,
58 + data: Option.some(makeThreadProjectionFixture()),
59 + }),
60 + ).pipe(Atom.keepAlive);
61 + return {
62 + ...(await importOriginal()),
63 + environmentThreadDetails: createEnvironmentThreadDetailAtoms(() => state.threadState),
64 + };
65 +});
66 +
67 vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
68 ...(await importOriginal()),
69 useAtomCommand: (() => async () => undefined) as never,
@@ -54,11 +76,13 @@ vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
76 }));
77
78 import "~/index.css";
57 -import { render as renderUi } from "../../../test/render";
79 +import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
80 +
81 +import { act, render as renderUi } from "../../../test/render";
82 +import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures";
83 import { QueuedRunsControl } from "./QueuedRunsControl";
84
85 function setup() {
61 - state.projection = null;
86 state.workflow = null;
87 }
88
@@ -98,7 +122,6 @@ it("previews assistant quotes as readable text and preserves the citation when e
122 contextId: toComposerContextId("header"),
123 label: "header.png",
124 });
101 - state.projection = { projection: { messages: [] } };
125 state.workflow = {
126 activeRun: { id: "run:active" },
127 canPromoteToSteer: true,
@@ -147,7 +170,6 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
170 createdAt: DateTime.makeUnsafe("2026-10-27T12:00:00.000Z"),
171 ...fields,
172 });
150 - state.projection = { projection: { messages: [] } };
173 state.workflow = {
174 activeRun: { id: "run:active" },
175 canPromoteToSteer: true,
@@ -223,7 +245,6 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
245
246 it("stays inside the timeline scroller instead of growing the chat column", async () => {
247 setup();
226 - state.projection = { projection: { messages: [] } };
248 state.workflow = {
249 activeRun: { id: "run:active" },
250 canPromoteToSteer: true,
@@ -250,3 +271,63 @@ it("stays inside the timeline scroller instead of growing the chat column", asyn
271 const column = screen.getByTestId("column").element();
272 expect(column.scrollHeight).toBe(column.clientHeight);
273 });
274 +
275 +it("does not re-render while assistant text streams into the thread", async () => {
276 + setup();
277 + state.workflow = {
278 + activeRun: { id: "run:active" },
279 + canPromoteToSteer: true,
280 + canReorder: true,
281 + queuedRuns: [
282 + {
283 + run: { id: "run:queued", userMessageId: "message:queued" },
284 + text: "Run the tests next",
285 + attachments: [],
286 + },
287 + ],
288 + };
289 + const base = makeThreadProjectionFixture();
290 + // Each delta replaces only the streaming reply; every other item keeps its identity.
291 + const timeline = makeStreamingTimelineFixture().visibleTurnItems;
292 + const thread = (text: string, done = false) => {
293 + const items = timeline.map((entry) =>
294 + entry.item.type === "assistant_message" && entry.item.streaming
295 + ? {
296 + ...entry,
297 + item: done
298 + ? { ...entry.item, text, streaming: false, status: "completed" as const }
299 + : { ...entry.item, text },
300 + }
301 + : entry,
302 + );
303 + return AsyncResult.success<EnvironmentThreadState>({
304 + ...EMPTY_ENVIRONMENT_THREAD_STATE,
305 + data: Option.some({
306 + ...base,
307 + turnItems: items.map(({ item }) => item),
308 + visibleTurnItems: items,
309 + }),
310 + });
311 + };
312 + const registry = AtomRegistry.make();
313 + await using stack = new AsyncDisposableStack();
314 + stack.defer(() => registry.dispose());
315 + registry.set(state.threadState, thread("Hel"));
316 + let renders = 0;
317 + await using _screen = await renderUi(
318 + <RegistryContext.Provider value={registry}>
319 + <Profiler id="queue" onRender={() => (renders += 1)}>
320 + <QueuedRunsControl {...baseProps} />
321 + </Profiler>
322 + </RegistryContext.Provider>,
323 + );
324 + await expect.element(page.getByText("Run the tests next", { exact: true })).toBeVisible();
325 + const settled = renders;
326 +
327 + await act(() => registry.set(state.threadState, thread("Hello")));
328 + await act(() => registry.set(state.threadState, thread("Hello there")));
329 + expect(renders).toBe(settled);
330 +
331 + await act(() => registry.set(state.threadState, thread("Hello there", true)));
332 + expect(renders).toBeGreaterThan(settled);
333 +});
apps/web/src/components/chat/QueuedRunsControl.tsx
+2 -2
@@ -28,7 +28,7 @@ import { useId, useImperativeHandle, useRef, useState, type ReactNode, type Ref
28
29 import { useAssetUrls } from "../../assets/assetUrls";
30 import { threadEnvironment } from "../../state/threads";
31 -import { useQuietThreadShell, useThreadProjection } from "../../state/entities";
31 +import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities";
32 import { useEnvironment } from "../../state/environments";
33 import { useAtomCommand } from "../../state/use-atom-command";
34 import { isImageAttachment, type ChatMessage } from "../../types";
@@ -94,7 +94,7 @@ export function QueuedRunsControl({
94 readonly timestampFormat: TimestampFormat;
95 readonly onOpenThread: (threadId: ThreadId, environmentId?: EnvironmentId) => void;
96 }) {
97 - const projection = useThreadProjection(
97 + const projection = useQuietThreadProjection(
98 scopeThreadRef(props.environmentId, props.threadId),
99 )?.projection;
100 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
+1 -1
@@ -30,7 +30,7 @@ vi.mock(import("@effect/atom-react"), async (original) => ({
30
31 vi.mock(import("../../state/entities"), () => ({
32 useQuietThreadShell: (() => null) as never,
33 - useThreadProjection: ((ref: unknown) =>
33 + useQuietThreadProjection: ((ref: unknown) =>
34 ref === null ? null : { projection: state.projection }) as never,
35 useThreadRelationshipShells: (() =>
36 state.projection === null
apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+3 -3
@@ -62,8 +62,8 @@ import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
62 import { buildThreadRouteParams } from "../../threadRoutes";
63 import {
64 useProjects,
65 + useQuietThreadProjection,
66 useQuietThreadShell,
66 - useThreadProjection,
67 useThreadRelationshipShells,
68 useHiddenThreadKeys,
69 useAnyEnvironmentHiding,
@@ -428,7 +428,7 @@ export function ThreadRelationshipsPanel(props: {
428 readonly showSideChats: boolean;
429 }) {
430 const ref = scopeThreadRef(props.environmentId, props.threadId);
431 - const projection = useThreadProjection(ref)?.projection ?? null;
431 + const projection = useQuietThreadProjection(ref)?.projection ?? null;
432 const providersByEnvironment = useEnvironmentProviders();
433 const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId));
434 const relationshipShells = useThreadRelationshipShells(ref);
@@ -455,7 +455,7 @@ export function ThreadRelationshipsPanel(props: {
455 parentShell && isProviderNativeSubagentThread(parentShell)
456 ? scopeThreadRef(props.environmentId, parentShell.id)
457 : null;
458 - const parentProjection = useThreadProjection(parentRef)?.projection;
458 + const parentProjection = useQuietThreadProjection(parentRef)?.projection;
459 const navigate = useNavigate();
460 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
461 const stopSession = useAtomCommand(threadEnvironment.stopSession);
apps/web/src/components/chat/TimelineAssistantRows.tsx
+2 -2
@@ -19,7 +19,7 @@ import {
19 readResponseSubagents,
20 useAssistantMessageText,
21 useProject,
22 - useThreadShell,
22 + useQuietThreadShell,
23 } from "../../state/entities";
24 import { MessageCopyButton } from "./MessageCopyButton";
25 import { AssistantCitationSource } from "./AssistantCitationSource";
@@ -444,7 +444,7 @@ function AssistantChangedFilesSectionInner({
444 const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
445 const allDirectoriesExpanded = persistedExpanded ?? false;
446
447 - const thread = useThreadShell(ctx.threadRef);
447 + const thread = useQuietThreadShell(ctx.threadRef);
448 const activeProject = useProject(
449 thread && thread.projectId
450 ? { environmentId: thread.environmentId, projectId: thread.projectId }
apps/web/src/state/entities.ts
+11 -6
@@ -5,6 +5,7 @@ import type {
5 EnvironmentThread,
6 EnvironmentThreadShell,
7 EnvironmentThreadStructure,
8 + ThreadStructure,
9 ThreadStructureVisibleTurnItem,
10 } from "@t3tools/client-runtime/state/shell";
11 import {
@@ -22,7 +23,6 @@ import type {
23 EnvironmentId,
24 OrchestrationV2ProjectedTurnItem,
25 OrchestrationV2RemoteTaskChild,
25 - OrchestrationV2ThreadProjection,
26 OrchestrationV2ThreadShell,
27 NodeId,
28 ThreadId,
@@ -396,10 +396,7 @@ function shellParentThreadId(
396 /** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */
397 export function selectThreadRelationshipShells(
398 threadId: ThreadId,
399 - projection: Pick<
400 - OrchestrationV2ThreadProjection,
401 - "thread" | "subagents" | "contextTransfers"
402 - > | null,
399 + projection: Pick<ThreadStructure, "thread" | "subagents" | "contextTransfers"> | null,
400 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
401 ): ReadonlyArray<OrchestrationV2ThreadShell> {
402 const named = new Set<string>([threadId]);
@@ -431,8 +428,16 @@ const relationshipShellsAtomFamily = Atom.family((key: string) => {
428 return Atom.make((get) => {
429 const next = selectThreadRelationshipShells(
430 ref.threadId,
434 - get(environmentThreadDetails.threadAtom(ref))?.projection ?? null,
431 + get(environmentThreadDetails.quietThreadAtom(ref))?.projection ?? null,
432 get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)),
433 + ).map(
434 + (thread) =>
435 + get(
436 + environmentThreadShells.quietThreadShellAtom({
437 + environmentId: ref.environmentId,
438 + threadId: thread.id,
439 + }),
440 + )?.source ?? thread,
441 );
442 if (arrayElementsEqual(previous, next)) return previous;
443 previous = next;
packages/client-runtime/src/state/threadDetail.test.ts
+28 -2
@@ -53,9 +53,29 @@ const assistant: OrchestrationV2TurnItem = {
53 streaming: true,
54 };
55
56 -function withItem(item: OrchestrationV2TurnItem, updatedAt = v2Now) {
56 +const assistantMessage: OrchestrationV2ConversationMessage = {
57 + createdBy: "agent",
58 + creationSource: "provider",
59 + id: MessageId.make("message-assistant"),
60 + threadId: v2ThreadId,
61 + runId: RunId.make("run-1"),
62 + nodeId: null,
63 + role: "assistant",
64 + text: "Hel",
65 + attachments: [],
66 + streaming: true,
67 + createdAt: v2Now,
68 + updatedAt: v2Now,
69 +};
70 +
71 +function withItem(
72 + item: OrchestrationV2TurnItem,
73 + updatedAt = v2Now,
74 + message: OrchestrationV2ConversationMessage = assistantMessage,
75 +) {
76 return {
77 ...v2Projection,
78 + messages: [message],
79 turnItems: [item],
80 visibleTurnItems: [
81 {
@@ -74,13 +94,19 @@ describe("sameThreadStructure", () => {
94 const before = withItem(assistant);
95
96 it("holds through streamed text", () => {
77 - const next = withItem({ ...assistant, text: "Hello", updatedAt: later }, later);
97 + const next = withItem({ ...assistant, text: "Hello", updatedAt: later }, later, {
98 + ...assistantMessage,
99 + text: "Hello",
100 + updatedAt: later,
101 + });
102 expect(sameThreadStructure(before, next)).toBe(true);
103 });
104
105 it("sees the item finish streaming", () => {
106 const next = withItem({ ...assistant, text: "Hello", streaming: false, status: "completed" });
107 expect(sameThreadStructure(before, next)).toBe(false);
108 + const message = { ...assistantMessage, text: "Hello", streaming: false };
109 + expect(sameThreadStructure(before, withItem(assistant, v2Now, message))).toBe(false);
110 });
111
112 it("sees a new item", () => {
packages/client-runtime/src/state/threadDetail.ts
+15
@@ -1,5 +1,6 @@
1 import {
2 OrchestrationV2AppThread,
3 + OrchestrationV2ConversationMessage,
4 OrchestrationV2TurnItem,
5 type OrchestrationV2ThreadProjection,
6 type ScopedThreadRef,
@@ -159,6 +160,7 @@ function toThreadStructure(projection: OrchestrationV2ThreadProjection): ThreadS
160
161 const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
162 const sameAppThread = Schema.toEquivalence(OrchestrationV2AppThread);
163 +const sameMessage = Schema.toEquivalence(OrchestrationV2ConversationMessage);
164
165 // Overlays previous's structure on next, so the fields the strip functions
166 // remove are exactly the ones ignored here.
@@ -183,6 +185,17 @@ function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {
185 return sameApartFromStripped(sameTurnItem, previous, structure, next);
186 }
187
188 +// A streaming reply's text also lands on its message; readers of that text read the live thread.
189 +function sameMessageStructure(
190 + previous: OrchestrationV2ConversationMessage,
191 + next: OrchestrationV2ConversationMessage,
192 +): boolean {
193 + if (previous === next) return true;
194 + if (!previous.streaming || !next.streaming || previous.id !== next.id) return false;
195 + const { text: _text, updatedAt: _updatedAt, ...structure } = previous;
196 + return sameApartFromStripped(sameMessage, previous, structure, next);
197 +}
198 +
199 function sameProjectionArray<T>(
200 previous: ReadonlyArray<T>,
201 next: ReadonlyArray<T>,
@@ -240,6 +253,7 @@ export function sameThreadStructure(
253 for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
254 if (
255 key === "thread" ||
256 + key === "messages" ||
257 key === "turnItems" ||
258 key === "visibleTurnItems" ||
259 key === "updatedAt"
@@ -260,6 +274,7 @@ export function sameThreadStructure(
274 return false;
275 }
276 return (
277 + sameProjectionArray(previous.messages, next.messages, sameMessageStructure) &&
278 sameProjectionArray(previous.turnItems, next.turnItems, sameTurnItemStructure) &&
279 sameProjectionArray(
280 previous.visibleTurnItems,
packages/client-runtime/src/state/threadRelationships.ts
+4 -3
@@ -1,11 +1,12 @@
1 import {
2 isOrchestrationV2WorkActive,
3 - type OrchestrationV2ThreadProjection,
3 type OrchestrationV2ThreadShell,
4 type ThreadId,
5 } from "@t3tools/contracts";
6 import * as DateTime from "effect/DateTime";
7
8 +import type { ThreadStructure } from "./models.ts";
9 +
10 export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer";
11
12 export interface ThreadRelationshipNode {
@@ -34,7 +35,7 @@ export interface ThreadRelationshipWalkRow {
35 }
36
37 export function resolveMergeBackTargetThreadId(
37 - projection: Pick<OrchestrationV2ThreadProjection, "thread"> | null,
38 + projection: Pick<ThreadStructure, "thread"> | null,
39 ): ThreadId | null {
40 if (projection?.thread.lineage.relationshipToParent !== "fork") return null;
41 return projection.thread.forkedFrom?.type === "run"
@@ -48,7 +49,7 @@ function edgeKey(edge: ThreadRelationshipEdge): string {
49
50 export function deriveThreadRelationshipGraph(input: {
51 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
51 - readonly projection: OrchestrationV2ThreadProjection | null;
52 + readonly projection: ThreadStructure | null;
53 }): ThreadRelationshipGraph {
54 const threadsById = new Map<ThreadId, OrchestrationV2ThreadShell>();
55 for (const thread of input.threads) {