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, 19:30 UTC
perf(web): streamed reply text no longer re-renders ChatView (#23117)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 22, 2026 at 01:11 UTC
83f118a4ac6c884601dbeb4c15b6c37d702bcb0a
23 files changed
+610
-119
apps/web/src/components/ChatView.logic.ts
+14
-9
@@ -15,6 +15,7 @@ import { getProviderModelCapabilities } from "../providerModels";
15
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
16
import type {
17
EnvironmentThread,
18
+ ThreadStructure,
19
EnvironmentThreadShell,
20
} from "@t3tools/client-runtime/state/shell";
21
import {
@@ -30,7 +31,6 @@ import {
31
type MessageId,
32
type ModelSelection,
33
type OrchestrationMessageContext,
33
- type OrchestrationV2ProjectedTurnItem,
34
type PreviewAnnotationPayload,
35
type ProviderInteractionMode,
36
ProviderDriverKind,
@@ -106,6 +106,7 @@ import {
106
} from "../providerInstances";
107
108
type ThreadProjection = EnvironmentThread["projection"];
109
+type ThreadStructureRow = ThreadStructure["visibleTurnItems"][number];
110
111
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
112
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
@@ -1198,7 +1199,7 @@ export function createLocalDispatchSnapshot(
1199
* turn items avoids dropping steer rows in that gap.
1200
*/
1201
export function deriveCommittedServerUserMessageIds(
1201
- visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1202
+ visibleTurnItems: ReadonlyArray<ThreadStructureRow>,
1203
): ReadonlySet<ChatMessage["id"]> {
1204
return new Set(
1205
visibleTurnItems.flatMap((row) =>
@@ -1626,14 +1627,18 @@ export function sendTitleFallbackLabels(snapshot: ComposerSendSnapshot) {
1627
];
1628
}
1629
1629
-/** A thread shell built from its loaded detail, for direct links that hydrate the detail first. */
1630
+/**
1631
+ * A thread shell built from its loaded detail, for direct links that hydrate the detail first.
1632
+ * `updatedAt` is passed live: the thread structure leaves it out.
1633
+ */
1634
export function presentThreadShellFromProjection(
1635
environmentId: EnvironmentId,
1636
threadId: ThreadId,
1633
- projection: ThreadProjection,
1637
+ projection: ThreadStructure,
1638
+ updatedAt: ThreadProjection["updatedAt"],
1639
) {
1640
const latestRun = deriveLatestThreadRun(projection);
1636
- const runtime = deriveThreadRuntime(projection);
1641
+ const runtime = deriveThreadRuntime({ ...projection, updatedAt });
1642
const pendingRuntimeRequest =
1643
projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null;
1644
// Direct links can hydrate detail before the thread enters the shell index.
@@ -1663,7 +1668,7 @@ export function presentThreadShellFromProjection(
1668
)?.goal ?? null,
1669
itemCount: projection.turnItems.length,
1670
visibleItemCount: projection.visibleTurnItems.length,
1666
- updatedAt: projection.updatedAt,
1671
+ updatedAt,
1672
}),
1673
latestRun,
1674
runtime,
@@ -1671,7 +1676,7 @@ export function presentThreadShellFromProjection(
1676
}
1677
1678
/** Background work the provider still runs after the latest run ended. */
1674
-export function deriveThreadPendingBackgroundTasks(projection: ThreadProjection | null) {
1679
+export function deriveThreadPendingBackgroundTasks(projection: ThreadStructure | null) {
1680
if (projection === null) return [];
1681
const sessionError =
1682
projection.providerSessions.findLast(
@@ -1697,7 +1702,7 @@ export function deriveThreadPendingBackgroundTasks(projection: ThreadProjection
1702
* active provider thread, plus 0 for the thread start. Empty without a live provider session
1703
* on the thread's selected instance.
1704
*/
1700
-export function deriveAvailableRevertTurnCounts(projection: ThreadProjection | null) {
1705
+export function deriveAvailableRevertTurnCounts(projection: ThreadStructure | null) {
1706
const available = new Set<number>();
1707
const providerThread = projection?.providerThreads.find(
1708
(candidate) => candidate.id === projection.thread.activeProviderThreadId,
@@ -1740,7 +1745,7 @@ export function deriveAvailableRevertTurnCounts(projection: ThreadProjection | n
1745
* without reporting the paths it touched.
1746
*/
1747
export function deriveWorkspaceMutationId(
1743
- visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1748
+ visibleTurnItems: ReadonlyArray<ThreadStructureRow>,
1749
latestCheckpointCompletedAt: string | null,
1750
) {
1751
let itemId: string | null = null;
apps/web/src/components/ChatView.tsx
+46
-34
@@ -26,9 +26,7 @@ import {
26
isPaintOnlyThreadTimeline,
27
peekHeldThreadTimeline,
28
peekRememberedThreadTimeline,
29
- rememberReadyThreadTimeline,
29
resolveThreadSwitchTimeline,
31
- timelineHasEphemeralPreviewUrls,
30
recallCheckoutIsRepo,
31
rememberCheckoutIsRepo,
32
} from "./ChatView.logic";
@@ -78,7 +76,7 @@ import {
76
deriveRunlessWorkStartedAt,
77
deriveThreadActivityRun,
78
deriveLatestThreadRun,
81
- deriveThreadRuntime,
79
+ deriveThreadStructureRuntime,
80
} from "@t3tools/client-runtime/state/thread-execution";
81
import {
82
resolveWorkflowOpening,
@@ -89,6 +87,7 @@ import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
87
import { HandoffRow } from "./chat/V2LifecycleRow";
88
import {
89
codexFeedbackMessage,
90
+ isCompleteTurnItemRow,
91
shouldShowLoadEarlierControl,
92
type CodexFeedbackSubmission,
93
} from "@t3tools/client-runtime/state/threads";
@@ -235,11 +234,12 @@ import {
234
resolveThreadDetailRef,
235
useEnvironmentSupportsServerBrowser,
236
useProject,
238
- useThreadProjection,
237
+ useQuietThreadProjection,
238
+ useThreadUpdatedAt,
239
+ useQuietThreadVisibleTurnItems,
240
useThreadStatus,
241
useThreadHistory,
242
useQuietThreadShell,
242
- useThreadVisibleTurnItems,
243
useThreadCheckpointSummaries,
244
} from "../state/entities";
245
import { useEnvironmentShellHasSnapshot } from "../state/shell";
@@ -254,7 +254,8 @@ import {
254
RevertConfirmHost,
255
} from "./chat/ChatOverlayHosts";
256
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
257
-import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
257
+import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
258
+import { ThreadTimeline } from "./chat/ThreadTimeline";
259
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
260
import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
261
import {
@@ -461,12 +462,21 @@ export default function ChatView(props: ChatViewProps) {
462
shellExists: serverThreadShell !== null,
463
waitForShell: draftThread !== null,
464
});
464
- const serverThreadProjection = useThreadProjection(routeThreadDetailRef);
465
+ const serverThreadProjection = useQuietThreadProjection(routeThreadDetailRef);
466
const serverProjection = serverThreadProjection?.projection ?? null;
467
+ // Only the shell-less fallback needs it; with a shell, the shell carries it.
468
+ const fallbackUpdatedAt = useThreadUpdatedAt(
469
+ serverThreadShell === null ? routeThreadDetailRef : null,
470
+ );
471
const serverThread =
467
- serverThreadShell !== null || serverProjection === null
472
+ serverThreadShell !== null || serverProjection === null || fallbackUpdatedAt === null
473
? serverThreadShell
469
- : presentThreadShellFromProjection(environmentId, threadId, serverProjection);
474
+ : presentThreadShellFromProjection(
475
+ environmentId,
476
+ threadId,
477
+ serverProjection,
478
+ fallbackUpdatedAt,
479
+ );
480
const promptRef = useRef("");
481
const localComposerRef = useRef<ChatComposerHandle | null>(null);
482
const composerRef = useComposerHandleContext() ?? localComposerRef;
@@ -498,7 +508,7 @@ export default function ChatView(props: ChatViewProps) {
508
serverProjection,
509
activeProviderThread,
510
);
501
- const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadDetailRef);
511
+ const serverVisibleTurnItems = useQuietThreadVisibleTurnItems(routeThreadDetailRef);
512
const serverThreadHistory = useThreadHistory(routeThreadDetailRef);
513
const threadHistoryControls = (() => {
514
if (routeThreadDetailRef === null || !shouldShowLoadEarlierControl(serverThreadHistory)) {
@@ -738,7 +748,8 @@ export default function ChatView(props: ChatViewProps) {
748
serverProjection === null ? null : deriveLatestThreadRun(serverProjection);
749
const serverActivityRun =
750
serverProjection === null ? null : deriveThreadActivityRun(serverProjection);
741
- const serverRuntime = serverProjection === null ? null : deriveThreadRuntime(serverProjection);
751
+ const serverRuntime =
752
+ serverProjection === null ? null : deriveThreadStructureRuntime(serverProjection);
753
const runlessWorkStartedAt =
754
serverProjection === null ? null : deriveRunlessWorkStartedAt(serverProjection);
755
const providerSubagentStatus =
@@ -784,7 +795,7 @@ export default function ChatView(props: ChatViewProps) {
795
thread: serverProjection.thread,
796
messages: serverProjection.messages,
797
});
787
- const workflowOpeningParentProjection = useThreadProjection(
798
+ const workflowOpeningParentProjection = useQuietThreadProjection(
799
workflowOpeningParentId === null || parentSubagentEnvironmentId === null
800
? null
801
: scopeThreadRef(parentSubagentEnvironmentId, workflowOpeningParentId),
@@ -1457,8 +1468,7 @@ export default function ChatView(props: ChatViewProps) {
1468
{ ...codexFeedbackMessage(submission, "assistant"), runId: null },
1469
],
1470
);
1460
- const serverTimelineEntries = useIncrementalTimelineEntries(activeThreadKey, {
1461
- visibleTurnItems: serverVisibleTurnItems,
1471
+ const timelineEntriesInput = {
1472
optimisticMessages: optimisticUserMessages,
1473
anchoredMessages: anchoredTimelineMessages,
1474
attachmentUrlById: timelineAttachmentUrlById,
@@ -1469,6 +1479,16 @@ export default function ChatView(props: ChatViewProps) {
1479
nodes: serverProjection.nodes,
1480
plans: serverProjection.plans,
1481
}),
1482
+ };
1483
+ // The structure has no assistant or reasoning text, so those rows stay out of
1484
+ // ChatView's own entries (anchoring, rewind, prompt history); ThreadTimeline
1485
+ // renders every row from the live turn items.
1486
+ const serverTimelineRows = serverVisibleTurnItems.filter(isCompleteTurnItemRow);
1487
+ const hasStreamedTimelineRows =
1488
+ isServerThread && serverTimelineRows.length !== serverVisibleTurnItems.length;
1489
+ const serverTimelineEntries = useIncrementalTimelineEntries(activeThreadKey, {
1490
+ ...timelineEntriesInput,
1491
+ visibleTurnItems: serverTimelineRows,
1492
});
1493
const draftTimelineEntries = optimisticUserMessages.map(
1494
(message) =>
@@ -1483,8 +1503,9 @@ export default function ChatView(props: ChatViewProps) {
1503
const timelineMessages = timelineEntries.flatMap((entry) =>
1504
entry.kind === "message" ? [entry.message] : [],
1505
);
1506
+ const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows;
1507
const displayedTimeline = resolveThreadSwitchTimeline({
1487
- loading: timelineEntries.length === 0 && threadSyncPhase !== null,
1508
+ loading: timelineEmpty && threadSyncPhase !== null,
1509
activeThreadKey,
1510
nextEntries: timelineEntries,
1511
rememberedForActive: peekRememberedThreadTimeline<typeof timelineEntries>(activeThreadKey),
@@ -1523,7 +1544,7 @@ export default function ChatView(props: ChatViewProps) {
1544
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
1545
const isDraftHeroState = resolveDraftHeroState({
1546
isLocalDraftThread,
1526
- hasTimelineEntries: timelineEntries.length > 0,
1547
+ hasTimelineEntries: !timelineEmpty,
1548
isWorking,
1549
draftHeroDockRequested,
1550
backgroundSubmissionPending,
@@ -1638,21 +1659,6 @@ export default function ChatView(props: ChatViewProps) {
1659
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
1660
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
1661
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
1641
- useLayoutEffect(() => {
1642
- if (
1643
- threadDetailLoading ||
1644
- timelineEntries.length === 0 ||
1645
- timelineHasEphemeralPreviewUrls(timelineEntries)
1646
- ) {
1647
- return;
1648
- }
1649
- rememberReadyThreadTimeline({
1650
- threadKey: activeThreadKey,
1651
- entries: timelineEntries,
1652
- markdownCwd: gitCwd,
1653
- workspaceRoot: activeWorkspaceRoot ?? null,
1654
- });
1655
- }, [activeThreadKey, activeWorkspaceRoot, gitCwd, threadDetailLoading, timelineEntries]);
1662
const heldPaintContext = paintOnlyDisplayedTimeline
1663
? peekHeldThreadTimeline<typeof timelineEntries>()
1664
: null;
@@ -3215,7 +3221,6 @@ export default function ChatView(props: ChatViewProps) {
3221
thread: activeThreadRef,
3222
enabled:
3223
isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline,
3218
- content: serverProjection ?? undefined,
3224
}}
3225
controlsRef={threadFindControlsRef}
3226
onOpenChange={setIsThreadFindActive}
@@ -3247,7 +3252,15 @@ export default function ChatView(props: ChatViewProps) {
3252
setThreadErrorBannerDismissTick={setThreadErrorBannerDismissTick}
3253
/>
3254
<div className="relative flex min-h-0 flex-1 flex-col bg-background">
3250
- <MessagesTimeline
3255
+ <ThreadTimeline
3256
+ threadDetailRef={routeThreadDetailRef}
3257
+ entriesInput={timelineEntriesInput}
3258
+ draftEntries={isServerThread ? null : draftTimelineEntries}
3259
+ activeThreadKey={activeThreadKey}
3260
+ syncing={threadSyncPhase !== null}
3261
+ detailLoading={threadDetailLoading}
3262
+ readyMarkdownCwd={gitCwd}
3263
+ readyWorkspaceRoot={activeWorkspaceRoot ?? null}
3264
citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest}
3265
citationHistoryLoading={threadDetailLoading}
3266
{...(!paintOnlyDisplayedTimeline
@@ -3301,7 +3314,6 @@ export default function ChatView(props: ChatViewProps) {
3314
)
3315
}
3316
listRef={legendListRef}
3304
- timelineEntries={displayedTimeline.entries}
3317
runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])}
3318
latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun}
3319
runningRunId={paintOnlyDisplayedTimeline ? null : activeRunningTurnId}
apps/web/src/components/chat/ThreadTimeline.tsx
new
+65
@@ -0,0 +1,65 @@
1
+import type { ScopedThreadRef } from "@t3tools/contracts";
2
+import { type ComponentProps, useLayoutEffect } from "react";
3
+import { useIncrementalTimelineEntries } from "../../hooks/useIncrementalTimelineEntries";
4
+import type { TimelineEntriesInput, TimelineEntry } from "../../session-logic";
5
+import { useThreadVisibleTurnItems } from "../../state/entities";
6
+import {
7
+ peekRememberedThreadTimeline,
8
+ rememberReadyThreadTimeline,
9
+ resolveThreadSwitchTimeline,
10
+ timelineHasEphemeralPreviewUrls,
11
+} from "../ChatView.logic";
12
+import { MessagesTimeline } from "./MessagesTimeline";
13
+
14
+/**
15
+ * The timeline with the streamed text. ChatView reads the thread through its quiet
16
+ * atoms, which hold through text deltas; this reads the live turn items, so a
17
+ * delta re-renders the timeline without re-rendering ChatView.
18
+ */
19
+export function ThreadTimeline({
20
+ threadDetailRef,
21
+ entriesInput,
22
+ draftEntries,
23
+ activeThreadKey,
24
+ syncing,
25
+ detailLoading,
26
+ readyMarkdownCwd,
27
+ readyWorkspaceRoot,
28
+ ...timelineProps
29
+}: Omit<ComponentProps<typeof MessagesTimeline>, "timelineEntries"> & {
30
+ /** Null until the thread's detail may load; see resolveThreadDetailRef. */
31
+ threadDetailRef: ScopedThreadRef | null;
32
+ entriesInput: Omit<TimelineEntriesInput, "visibleTurnItems">;
33
+ /** A local draft's optimistic rows; null for a server thread. */
34
+ draftEntries: ReadonlyArray<TimelineEntry> | null;
35
+ activeThreadKey: string | null;
36
+ syncing: boolean;
37
+ detailLoading: boolean;
38
+ readyMarkdownCwd: string | null;
39
+ readyWorkspaceRoot: string | null;
40
+}) {
41
+ const visibleTurnItems = useThreadVisibleTurnItems(threadDetailRef);
42
+ const serverEntries = useIncrementalTimelineEntries(activeThreadKey, {
43
+ ...entriesInput,
44
+ visibleTurnItems,
45
+ });
46
+ const entries = draftEntries ?? serverEntries;
47
+ const displayed = resolveThreadSwitchTimeline({
48
+ loading: entries.length === 0 && syncing,
49
+ activeThreadKey,
50
+ nextEntries: entries,
51
+ rememberedForActive: peekRememberedThreadTimeline<typeof entries>(activeThreadKey),
52
+ });
53
+ useLayoutEffect(() => {
54
+ if (detailLoading || entries.length === 0 || timelineHasEphemeralPreviewUrls(entries)) {
55
+ return;
56
+ }
57
+ rememberReadyThreadTimeline({
58
+ threadKey: activeThreadKey,
59
+ entries,
60
+ markdownCwd: readyMarkdownCwd,
61
+ workspaceRoot: readyWorkspaceRoot,
62
+ });
63
+ }, [activeThreadKey, detailLoading, entries, readyMarkdownCwd, readyWorkspaceRoot]);
64
+ return <MessagesTimeline {...timelineProps} timelineEntries={displayed.entries} />;
65
+}
apps/web/src/components/chat/useAttachmentPreviewHandoff.ts
+2
-2
@@ -3,12 +3,12 @@ import { type EnvironmentId, type MessageId } from "@t3tools/contracts";
3
import { useEffect, useLayoutEffect, useRef, useState } from "react";
4
import { selectHandoffImageResources } from "../../session-logic";
5
import { type ChatMessage } from "../../types";
6
-import type { useThreadVisibleTurnItems } from "../../state/entities";
6
+import type { useQuietThreadVisibleTurnItems } from "../../state/entities";
7
import { revokeBlobPreviewUrl, revokeUserMessagePreviewUrls } from "../ChatView.logic";
8
import { useAssetUrls } from "../../assets/assetUrls";
9
interface AttachmentPreviewHandoffInput {
10
readonly environmentId: EnvironmentId;
11
- readonly serverVisibleTurnItems: ReturnType<typeof useThreadVisibleTurnItems>;
11
+ readonly serverVisibleTurnItems: ReturnType<typeof useQuietThreadVisibleTurnItems>;
12
readonly optimisticUserMessages: ReadonlyArray<ChatMessage>;
13
}
14
apps/web/src/components/chat/useComposerSelection.ts
+2
-2
@@ -12,7 +12,7 @@ import {
12
ProviderInteractionMode,
13
RuntimeMode,
14
} from "@t3tools/contracts";
15
-import { deriveThreadRuntime } from "@t3tools/client-runtime/state/thread-execution";
15
+import type { deriveThreadStructureRuntime } from "@t3tools/client-runtime/state/thread-execution";
16
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
17
import { type SetStateAction } from "react";
18
import { useNavigate } from "@tanstack/react-router";
@@ -30,7 +30,7 @@ interface ComposerSelectionInput {
30
readonly composerDraftTarget: ComposerThreadTarget;
31
readonly draftThread: DraftSessionState | null;
32
readonly activeThread: EnvironmentThreadShell | undefined;
33
- readonly activeRuntime: ReturnType<typeof deriveThreadRuntime>;
33
+ readonly activeRuntime: ReturnType<typeof deriveThreadStructureRuntime>;
34
readonly activeProjectSettings: {
35
readonly settings: { readonly newWorktreesStartFromOrigin: boolean };
36
};
apps/web/src/components/chat/usePendingThreadRequests.ts
+2
-2
@@ -1,7 +1,7 @@
1
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2
import {
3
AuthOrchestrationOperateScope,
4
type EnvironmentId,
4
- type OrchestrationV2ThreadProjection,
5
type ProviderApprovalDecision,
6
type RuntimeRequestId,
7
type ScopedThreadRef,
@@ -110,7 +110,7 @@ export function usePendingThreadRequests(input: {
110
readonly environmentId: EnvironmentId;
111
readonly activeThreadId: ThreadId | null;
112
readonly activeThread: { readonly id: ThreadId } | undefined;
113
- readonly serverProjection: OrchestrationV2ThreadProjection | null;
113
+ readonly serverProjection: ThreadStructure | null;
114
readonly supportsQuestionAttachments: boolean;
115
readonly composerDraftTarget: ScopedThreadRef | DraftId;
116
readonly setComposerDraftPrompt: (target: ScopedThreadRef | DraftId, prompt: string) => void;
apps/web/src/components/chat/useQueuedRunEdit.ts
+2
-2
@@ -1,10 +1,10 @@
1
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2
import {
3
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4
type ChatAttachment,
5
type EnvironmentId,
6
type MessageId,
7
type OrchestrationMessageContext,
7
- type OrchestrationV2ThreadProjection,
8
type PreviewAnnotationPayload,
9
type RunId,
10
type ScopedThreadRef,
@@ -170,7 +170,7 @@ export function useQueuedRunEdit(input: {
170
readonly threadDraftTarget: ComposerThreadTarget;
171
// Null while the route has no thread yet; an edit needs one to target.
172
readonly activeThreadId: ThreadId | null;
173
- readonly serverProjection: OrchestrationV2ThreadProjection | null;
173
+ readonly serverProjection: ThreadStructure | null;
174
readonly promptRef: { current: string };
175
readonly composerRef: RefObject<ChatComposerHandle | null>;
176
}) {
apps/web/src/components/chat/useThreadFind.ts
+5
-7
@@ -1,13 +1,10 @@
1
import type { InlineSkill } from "@t3tools/shared/inlineSkills";
2
-import type {
3
- OrchestrationV2ThreadProjection,
4
- OrchestrationV2SearchThreadResult,
5
- ScopedThreadRef,
6
-} from "@t3tools/contracts";
2
+import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts";
3
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
5
import { useStableCallback } from "~/hooks/useStableCallback";
6
import { orchestrationEnvironment } from "~/state/orchestration";
7
+import { useThreadProjection } from "~/state/entities";
8
import { useEnvironmentQuery } from "~/state/query";
9
import { useDebouncedValue } from "~/state/queries";
10
import {
@@ -42,14 +39,15 @@ export function useThreadFind({
39
enabled,
40
progressive = false,
41
skills = EMPTY_SKILLS,
45
- content,
42
}: {
43
thread: ScopedThreadRef | null;
44
enabled: boolean;
45
progressive?: boolean;
46
skills?: readonly InlineSkill[];
51
- content: Pick<OrchestrationV2ThreadProjection, "visibleTurnItems" | "runs"> | undefined;
47
}) {
48
+ // Read here rather than passed in: a streamed delta re-renders only the find
49
+ // provider, which refreshes open results from it.
50
+ const content = useThreadProjection(enabled ? thread : null)?.projection;
51
// Held in state so the timeline props that carry it can be stored in state too.
52
const [positionReader] = useState<RefObject<ThreadFindPositionReader | null>>(() => ({
53
current: null,
apps/web/src/components/chat/useTimelineFollow.ts
+11
-2
@@ -31,7 +31,7 @@ import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
31
import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
32
import { releaseChatTimelineAnchor } from "../ChatView.logic";
33
import type { Dispatch, RefObject } from "react";
34
-import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
34
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
35
import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";
36
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
37
import type { TimelineEntry } from "../../session-logic";
@@ -52,7 +52,7 @@ interface TimelineFollowInput {
52
readonly activeThreadKey: string | null;
53
readonly activeThreadId: ThreadId | undefined;
54
readonly isServerThread: boolean;
55
- readonly serverProjection: EnvironmentThread["projection"] | null;
55
+ readonly serverProjection: ThreadStructure | null;
56
readonly threadStatus: EnvironmentThreadStatus;
57
readonly activeActivityRun: ReturnType<typeof deriveThreadActivityRun>;
58
readonly activeRunningTurnId: RunId | null;
@@ -586,9 +586,17 @@ export function useTimelineFollow(input: TimelineFollowInput) {
586
};
587
const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
588
589
+ // timelineEntries leave out reasoning rows (their text is not in the
590
+ // structure), and reasoning counts as tool activity, like any work row.
591
+ const runningTurnHasReasoning =
592
+ activeRunningTurnId !== null &&
593
+ serverProjection?.visibleTurnItems.some(
594
+ (row) => row.item.type === "reasoning" && row.item.runId === activeRunningTurnId,
595
+ ) === true;
596
useLayoutEffect(() => {
597
if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
598
if (
599
+ (runningTurnHasReasoning && timelineAnchorMessageId !== null && timelineLiveFollowEnabled) ||
600
shouldReleaseTimelineAnchorForToolActivity({
601
anchorMessageId: timelineAnchorMessageId,
602
liveFollowEnabled: timelineLiveFollowEnabled,
@@ -600,6 +608,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {
608
}
609
}, [
610
activeRunningTurnId,
611
+ runningTurnHasReasoning,
612
scrollToEndStable,
613
timelineAnchorMessageId,
614
timelineEntries,
apps/web/src/components/chat/useTimelineRewind.ts
+2
-3
@@ -1,5 +1,4 @@
1
-import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
2
-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
1
+import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
2
import type { ComposerThreadTarget } from "../../composerDraftStore";
3
import type { ComposerHandleRef } from "../../composerHandleContext";
4
import type { SessionPhase } from "../../types";
@@ -39,7 +38,7 @@ interface TimelineRewindInput {
38
readonly routeThreadRef: ScopedThreadRef;
39
readonly routeThreadKey: string;
40
readonly currentRouteThreadKeyRef: { readonly current: string | null };
42
- readonly serverProjection: EnvironmentThread["projection"] | null;
41
+ readonly serverProjection: ThreadStructure | null;
42
readonly activeThread: EnvironmentThreadShell | undefined;
43
readonly timelineMessages: ReadonlyArray<ChatMessage>;
44
readonly paintOnlyDisplayedTimeline: boolean;
apps/web/src/components/chat/useWorktreeSetup.ts
+2
-2
@@ -1,6 +1,6 @@
1
+import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2
import type {
3
EnvironmentId,
3
- OrchestrationV2ThreadProjection,
4
RunId,
5
ScopedThreadRef,
6
ThreadId,
@@ -34,7 +34,7 @@ export function useWorktreeSetup(input: {
34
| { readonly id: ThreadId; readonly worktreePath: string | null }
35
| undefined;
36
readonly threadRef: ScopedThreadRef | null;
37
- readonly serverProjection: OrchestrationV2ThreadProjection | null;
37
+ readonly serverProjection: ThreadStructure | null;
38
readonly activityRun: Thread["latestRun"] | null;
39
readonly localPreparing: boolean;
40
// A send that the server queues behind the setup run is not held here.
apps/web/src/lib/contextWindow.ts
+2
-2
@@ -1,9 +1,9 @@
1
+import type { ThreadStructureTurnItem } from "@t3tools/client-runtime/state/shell";
2
import type {
3
OrchestrationV2ProviderTurn,
4
OrchestrationV2ProviderTurnTokenUsage,
5
OrchestrationV2ProviderThread,
6
OrchestrationV2ThreadProjection,
6
- OrchestrationV2TurnItem,
7
ThreadTokenUsageSnapshot,
8
} from "@t3tools/contracts";
9
import * as DateTime from "effect/DateTime";
@@ -58,7 +58,7 @@ export function latestProviderTurnTokenUsage(
58
59
export function deriveLatestContextWindowSnapshot(
60
entries: ReadonlyArray<{
61
- readonly item: OrchestrationV2TurnItem;
61
+ readonly item: ThreadStructureTurnItem;
62
}>,
63
liveUsage?: OrchestrationV2ProviderTurnTokenUsage | null,
64
providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage" | "updatedAt"> | null,
apps/web/src/session-logic.ts
+23
-12
@@ -1,3 +1,4 @@
1
+import type { ThreadStructure, ThreadStructureRuntime } from "@t3tools/client-runtime/state/shell";
2
import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
3
import {
4
type AssetResource,
@@ -251,7 +252,7 @@ export function derivePendingUserInputs(
252
}
253
254
export function deriveActivePlanState(
254
- projection: OrchestrationV2ThreadProjection | null,
255
+ projection: ThreadStructure | null,
256
latestRunId: RunId | undefined,
257
): ActivePlanState | null {
258
if (projection === null) return null;
@@ -273,7 +274,7 @@ export function deriveActivePlanState(
274
);
275
if (plan === null || plan.steps.length === 0) return null;
276
return {
276
- createdAt: planItemTime(projection, plan.id),
277
+ createdAt: planItemTime(projection, plan),
278
runId: plan.runId,
279
explanation: plan.explanation ?? null,
280
steps: plan.steps.map(({ text, status, durationMs }) => ({
@@ -286,7 +287,7 @@ export function deriveActivePlanState(
287
288
// Claude's unfinished tasks belong to the provider session, not just the turn.
289
export function selectComposerTasksPlan(
289
- projection: OrchestrationV2ThreadProjection | null,
290
+ projection: ThreadStructure | null,
291
plan: ActivePlanState | null,
292
activeRunId: RunId | null,
293
activeRunSettled: boolean,
@@ -315,20 +316,30 @@ export function selectComposerTasksPlan(
316
return latestStartedRun?.providerThreadId === planProviderThreadId ? plan : null;
317
}
318
318
-function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
319
+function planItemTime(
320
+ projection: ThreadStructure,
321
+ plan: Pick<OrchestrationV2PlanArtifact, "id" | "runId">,
322
+): string {
323
const item = projection.turnItems.findLast(
324
(candidate) =>
325
(candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
322
- candidate.planId === planId,
326
+ candidate.planId === plan.id,
327
+ );
328
+ if (item?.type === "proposed_plan" || item?.type === "todo_list") {
329
+ return DateTime.formatIso(item.updatedAt);
330
+ }
331
+ // Without a plan item, the plan's run dates it; the thread's own timestamps move while a reply streams.
332
+ const run = projection.runs.find((candidate) => candidate.id === plan.runId);
333
+ return DateTime.formatIso(
334
+ run?.completedAt ?? run?.startedAt ?? run?.requestedAt ?? projection.thread.createdAt,
335
);
324
- return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
336
}
337
338
function toLatestProposedPlanState(
328
- projection: OrchestrationV2ThreadProjection,
339
+ projection: ThreadStructure,
340
plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
341
): LatestProposedPlanState {
331
- const updatedAt = planItemTime(projection, plan.id);
342
+ const updatedAt = planItemTime(projection, plan);
343
return {
344
id: plan.id,
345
createdAt: updatedAt,
@@ -340,7 +351,7 @@ function toLatestProposedPlanState(
351
}
352
353
export function findLatestProposedPlan(
343
- projection: OrchestrationV2ThreadProjection | null,
354
+ projection: ThreadStructure | null,
355
latestRunId: RunId | string | null | undefined,
356
): LatestProposedPlanState | null {
357
if (projection === null) return null;
@@ -349,7 +360,7 @@ export function findLatestProposedPlan(
360
const plan = [...(candidates.length > 0 ? candidates : plans)]
361
.toSorted(
362
(left, right) =>
352
- planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
363
+ planItemTime(projection, left).localeCompare(planItemTime(projection, right)) ||
364
left.id.localeCompare(right.id),
365
)
366
.at(-1);
@@ -1122,7 +1133,7 @@ export function findRevertCheckpoint(
1133
);
1134
}
1135
1125
-export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
1136
+export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1137
if (runtime === null) return "disconnected";
1138
if (
1139
runtime.status === "preparing" ||
@@ -1140,7 +1151,7 @@ export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase
1151
*/
1152
export function deriveCanInterruptRunningThread(
1153
hasActiveThread: boolean,
1143
- runtime: ThreadRuntimeSummary | null,
1154
+ runtime: ThreadStructureRuntime | null,
1155
): boolean {
1156
return (
1157
hasActiveThread &&
apps/web/src/state/entities.ts
+33
@@ -1,8 +1,11 @@
1
+import type * as DateTime from "effect/DateTime";
2
import { useAtomValue } from "@effect/atom-react";
3
import type {
4
EnvironmentProject,
5
EnvironmentThread,
6
EnvironmentThreadShell,
7
+ EnvironmentThreadStructure,
8
+ ThreadStructureVisibleTurnItem,
9
} from "@t3tools/client-runtime/state/shell";
10
import {
11
EMPTY_THREAD_HISTORY_META,
@@ -62,6 +65,9 @@ const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
65
const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(
66
Object.freeze([]),
67
).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));
68
+const EMPTY_UPDATED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
69
+ Atom.withLabel("web-thread-updated-at:empty"),
70
+);
71
const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HISTORY_META).pipe(
72
Atom.withLabel("web-thread-history:empty"),
73
);
@@ -156,6 +162,22 @@ export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThr
162
);
163
}
164
165
+/** The thread's structure, held through streamed assistant and reasoning text; see ThreadStructure. */
166
+export function useQuietThreadProjection(
167
+ ref: ScopedThreadRef | null,
168
+): EnvironmentThreadStructure | null {
169
+ return useAtomValue(
170
+ ref === null ? EMPTY_THREAD_PROJECTION_ATOM : environmentThreadDetails.quietThreadAtom(ref),
171
+ );
172
+}
173
+
174
+/** The detail's live `updatedAt`, which the thread structure leaves out. */
175
+export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
176
+ return useAtomValue(
177
+ ref === null ? EMPTY_UPDATED_AT_ATOM : environmentThreadDetails.updatedAtAtom(ref),
178
+ );
179
+}
180
+
181
export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
182
return useAtomValue(
183
ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),
@@ -188,6 +210,17 @@ export function useThreadVisibleTurnItems(
210
);
211
}
212
213
+/** Visible turn items without their streamed text; see ThreadStructure. */
214
+export function useQuietThreadVisibleTurnItems(
215
+ ref: ScopedThreadRef | null,
216
+): ReadonlyArray<ThreadStructureVisibleTurnItem> {
217
+ return useAtomValue(
218
+ ref === null
219
+ ? EMPTY_VISIBLE_TURN_ITEMS_ATOM
220
+ : environmentThreadDetails.quietVisibleTurnItemsAtom(ref),
221
+ );
222
+}
223
+
224
export function useThreadCheckpointSummaries(
225
ref: ScopedThreadRef | null,
226
): ReadonlyArray<ThreadCheckpointSummary> {
packages/client-runtime/src/handoff.ts
+3
-2
@@ -1,12 +1,13 @@
1
import type {
2
ModelSelection,
3
OrchestrationV2Run,
4
- OrchestrationV2ThreadProjection,
4
OrchestrationV2TurnItem,
5
ProviderInstanceId,
6
ServerProvider,
7
} from "@t3tools/contracts";
8
9
+import type { ThreadStructure } from "./state/models.ts";
10
+
11
export type HandoffTimelineRun = Pick<
12
OrchestrationV2Run,
13
"id" | "ordinal" | "providerInstanceId" | "modelSelection"
@@ -15,7 +16,7 @@ export type HandoffTimelineRun = Pick<
16
export type HandoffEndpoints = ReturnType<typeof resolveHandoffEndpoints>;
17
18
export function resolvePendingHandoff(
18
- projection: OrchestrationV2ThreadProjection | null | undefined,
19
+ projection: ThreadStructure | null | undefined,
20
selection: ModelSelection | null | undefined,
21
providers: ReadonlyArray<ServerProvider>,
22
): HandoffEndpoints | null {
packages/client-runtime/src/state/models.ts
+41
-1
@@ -34,6 +34,43 @@ export interface EnvironmentThread {
34
readonly projection: OrchestrationV2ThreadProjection;
35
}
36
37
+type ProjectionTurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
38
+type StreamedProjectionTurnItem = Extract<
39
+ ProjectionTurnItem,
40
+ { readonly type: "assistant_message" | "reasoning" }
41
+>;
42
+
43
+/** A turn item without the fields that move while it streams. */
44
+export type ThreadStructureTurnItem =
45
+ | Exclude<ProjectionTurnItem, StreamedProjectionTurnItem>
46
+ | Omit<Extract<ProjectionTurnItem, { readonly type: "assistant_message" }>, "text" | "updatedAt">
47
+ | Omit<Extract<ProjectionTurnItem, { readonly type: "reasoning" }>, "text" | "updatedAt">;
48
+
49
+export type ThreadStructureVisibleTurnItem = Omit<
50
+ OrchestrationV2ThreadProjection["visibleTurnItems"][number],
51
+ "item"
52
+> & {
53
+ readonly item: ThreadStructureTurnItem;
54
+};
55
+
56
+/**
57
+ * A thread projection without the fields that move while a reply streams, so a
58
+ * reader of the quiet thread cannot depend on them and go stale. A full
59
+ * projection is assignable to it.
60
+ */
61
+export type ThreadStructure = Omit<
62
+ OrchestrationV2ThreadProjection,
63
+ "turnItems" | "visibleTurnItems" | "updatedAt"
64
+> & {
65
+ readonly turnItems: ReadonlyArray<ThreadStructureTurnItem>;
66
+ readonly visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>;
67
+};
68
+
69
+export interface EnvironmentThreadStructure {
70
+ readonly environmentId: EnvironmentId;
71
+ readonly projection: ThreadStructure;
72
+}
73
+
74
export interface ThreadRunSummary {
75
readonly runId: RunId;
76
readonly status: OrchestrationV2RunStatus;
@@ -65,7 +102,10 @@ export interface ThreadRuntimeSummary {
102
readonly updatedAt: string;
103
}
104
68
-export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
105
+/** The runtime summary a thread's structure determines; see ThreadStructure. */
106
+export type ThreadStructureRuntime = Omit<ThreadRuntimeSummary, "updatedAt">;
107
+
108
+export function threadRuntimeIsActive(runtime: ThreadStructureRuntime | null | undefined): boolean {
109
return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
110
}
111
packages/client-runtime/src/state/threadDetail.test.ts
new
+136
@@ -0,0 +1,136 @@
1
+import {
2
+ EnvironmentId,
3
+ MessageId,
4
+ RunId,
5
+ TurnItemId,
6
+ type OrchestrationV2ThreadProjection,
7
+ type OrchestrationV2TurnItem,
8
+} from "@t3tools/contracts";
9
+import { describe, expect, it } from "@effect/vitest";
10
+import * as DateTime from "effect/DateTime";
11
+import * as Option from "effect/Option";
12
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
13
+
14
+import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
15
+import { createEnvironmentThreadDetailAtoms, sameThreadStructure } from "./threadDetail.ts";
16
+import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
17
+
18
+const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
19
+
20
+const assistant: OrchestrationV2TurnItem = {
21
+ id: TurnItemId.make("item-assistant"),
22
+ threadId: v2ThreadId,
23
+ runId: RunId.make("run-1"),
24
+ nodeId: null,
25
+ providerThreadId: null,
26
+ providerTurnId: null,
27
+ nativeItemRef: null,
28
+ parentItemId: null,
29
+ ordinal: 1,
30
+ status: "running",
31
+ title: null,
32
+ startedAt: v2Now,
33
+ completedAt: null,
34
+ updatedAt: v2Now,
35
+ type: "assistant_message",
36
+ messageId: MessageId.make("message-assistant"),
37
+ text: "Hel",
38
+ streaming: true,
39
+};
40
+
41
+function withItem(item: OrchestrationV2TurnItem, updatedAt = v2Now) {
42
+ return {
43
+ ...v2Projection,
44
+ turnItems: [item],
45
+ visibleTurnItems: [
46
+ {
47
+ position: 0,
48
+ visibility: "local" as const,
49
+ sourceThreadId: v2ThreadId,
50
+ sourceItemId: item.id,
51
+ item,
52
+ },
53
+ ],
54
+ updatedAt,
55
+ };
56
+}
57
+
58
+describe("sameThreadStructure", () => {
59
+ const before = withItem(assistant);
60
+
61
+ it("holds through streamed text", () => {
62
+ const next = withItem({ ...assistant, text: "Hello", updatedAt: later }, later);
63
+ expect(sameThreadStructure(before, next)).toBe(true);
64
+ });
65
+
66
+ it("sees the item finish streaming", () => {
67
+ const next = withItem({ ...assistant, text: "Hello", streaming: false, status: "completed" });
68
+ expect(sameThreadStructure(before, next)).toBe(false);
69
+ });
70
+
71
+ it("sees a new item", () => {
72
+ const next = { ...before, turnItems: [assistant, { ...assistant, id: TurnItemId.make("b") }] };
73
+ expect(sameThreadStructure(before, next)).toBe(false);
74
+ });
75
+
76
+ it("sees other fields change on a streaming item", () => {
77
+ const next = withItem({ ...assistant, text: "Hello", title: "Answer" });
78
+ expect(sameThreadStructure(before, next)).toBe(false);
79
+ });
80
+
81
+ it("sees changes outside the turn items", () => {
82
+ expect(sameThreadStructure(before, { ...before, runs: [] })).toBe(false);
83
+ });
84
+});
85
+
86
+describe("quietThreadAtom", () => {
87
+ const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
88
+
89
+ function setup(initial: OrchestrationV2ThreadProjection) {
90
+ const stateAtom = Atom.make(
91
+ AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(initial) }),
92
+ );
93
+ const quietAtom = createEnvironmentThreadDetailAtoms(() => stateAtom).quietThreadAtom(ref);
94
+ const registry = AtomRegistry.make();
95
+ registry.mount(quietAtom);
96
+ return {
97
+ read: () => registry.get(quietAtom),
98
+ push: (projection: OrchestrationV2ThreadProjection) =>
99
+ registry.set(
100
+ stateAtom,
101
+ AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
102
+ ),
103
+ };
104
+ }
105
+
106
+ it("keeps the same value through streamed text", () => {
107
+ const thread = setup(withItem(assistant));
108
+ const first = thread.read();
109
+ thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
110
+ thread.push(withItem({ ...assistant, text: "Hello there", updatedAt: later }, later));
111
+ expect(thread.read()).toBe(first);
112
+ });
113
+
114
+ it("passes a structure change on", () => {
115
+ const thread = setup(withItem(assistant));
116
+ const first = thread.read();
117
+ thread.push(withItem({ ...assistant, text: "Hello", updatedAt: later }, later));
118
+ thread.push(withItem({ ...assistant, text: "Hello", status: "completed", streaming: false }));
119
+ const next = thread.read();
120
+ expect(next).not.toBe(first);
121
+ expect(next?.projection.turnItems[0]).toMatchObject({ status: "completed", streaming: false });
122
+ });
123
+
124
+ it("leaves out the fields that streaming moves", () => {
125
+ const thread = setup(withItem(assistant));
126
+ const projection = thread.read()?.projection;
127
+ expect(projection).not.toHaveProperty("updatedAt");
128
+ expect(projection?.turnItems[0]).not.toHaveProperty("text");
129
+ expect(projection?.turnItems[0]).not.toHaveProperty("updatedAt");
130
+ expect(projection?.visibleTurnItems[0]?.item).not.toHaveProperty("text");
131
+ expect(projection?.visibleTurnItems[0]?.item).toMatchObject({
132
+ messageId: assistant.messageId,
133
+ streaming: true,
134
+ });
135
+ });
136
+});
packages/client-runtime/src/state/threadDetail.ts
+167
-2
@@ -1,5 +1,10 @@
1
-import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts";
1
+import {
2
+ OrchestrationV2TurnItem,
3
+ type OrchestrationV2ThreadProjection,
4
+ type ScopedThreadRef,
5
+} from "@t3tools/contracts";
6
import * as Option from "effect/Option";
7
+import * as Schema from "effect/Schema";
8
import { AsyncResult, Atom } from "effect/reactivity";
9
10
import {
@@ -12,7 +17,13 @@ import {
17
deriveThreadCheckpointSummaries,
18
type ThreadCheckpointSummary,
19
} from "./threadCheckpoints.ts";
15
-import type { EnvironmentThread } from "./models.ts";
20
+import type {
21
+ EnvironmentThread,
22
+ EnvironmentThreadStructure,
23
+ ThreadStructure,
24
+ ThreadStructureTurnItem,
25
+ ThreadStructureVisibleTurnItem,
26
+} from "./models.ts";
27
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
28
import {
29
createQuestionHistoryProjector,
@@ -24,8 +35,114 @@ import { arrayElementsEqual, parseThreadKey, threadKey } from "./entities.ts";
35
const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
36
[],
37
);
38
+const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray<ThreadStructureVisibleTurnItem> =
39
+ Object.freeze([]);
40
const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
41
42
+type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
43
+type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
44
+
45
+// Items are stripped once each: unchanged items keep their identity across
46
+// structure changes, which the incremental timeline relies on.
47
+const structureTurnItems = new WeakMap<TurnItem, ThreadStructureTurnItem>();
48
+const structureVisibleTurnItems = new WeakMap<VisibleTurnItem, ThreadStructureVisibleTurnItem>();
49
+
50
+function toThreadStructureTurnItem(item: TurnItem): ThreadStructureTurnItem {
51
+ if (item.type !== "assistant_message" && item.type !== "reasoning") return item;
52
+ let structure = structureTurnItems.get(item);
53
+ if (structure === undefined) {
54
+ const { text: _text, updatedAt: _updatedAt, ...rest } = item;
55
+ structure = rest;
56
+ structureTurnItems.set(item, structure);
57
+ }
58
+ return structure;
59
+}
60
+
61
+function toThreadStructureVisibleTurnItem(
62
+ visibleItem: VisibleTurnItem,
63
+): ThreadStructureVisibleTurnItem {
64
+ const item = toThreadStructureTurnItem(visibleItem.item);
65
+ if (item === visibleItem.item) return visibleItem;
66
+ let structure = structureVisibleTurnItems.get(visibleItem);
67
+ if (structure === undefined) {
68
+ structure = { ...visibleItem, item };
69
+ structureVisibleTurnItems.set(visibleItem, structure);
70
+ }
71
+ return structure;
72
+}
73
+
74
+/** Whether the structure kept every field of this row: true for all but streamed items. */
75
+export function isCompleteTurnItemRow(row: ThreadStructureVisibleTurnItem): row is VisibleTurnItem {
76
+ return row.item.type !== "assistant_message" && row.item.type !== "reasoning";
77
+}
78
+
79
+function toThreadStructure(projection: OrchestrationV2ThreadProjection): ThreadStructure {
80
+ const { updatedAt: _updatedAt, ...structure } = projection;
81
+ return {
82
+ ...structure,
83
+ turnItems: projection.turnItems.map(toThreadStructureTurnItem),
84
+ visibleTurnItems: projection.visibleTurnItems.map(toThreadStructureVisibleTurnItem),
85
+ };
86
+}
87
+
88
+const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
89
+
90
+// Compares through toThreadStructureTurnItem, so the fields it strips are
91
+// exactly the ones ignored here.
92
+function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {
93
+ if (previous === next) return true;
94
+ const structure = toThreadStructureTurnItem(previous);
95
+ if (previous.id !== next.id || previous.type !== next.type || structure === previous) {
96
+ return false;
97
+ }
98
+ return (
99
+ Object.keys(previous).length === Object.keys(next).length &&
100
+ sameTurnItem(Object.assign({}, next, structure), next)
101
+ );
102
+}
103
+
104
+/**
105
+ * Whether `previous` and `next` have the same ThreadStructure: they differ
106
+ * only by text streamed into existing assistant and reasoning items. The same
107
+ * items exist, with the same status, and every other field is unchanged.
108
+ */
109
+export function sameThreadStructure(
110
+ previous: OrchestrationV2ThreadProjection,
111
+ next: OrchestrationV2ThreadProjection,
112
+): boolean {
113
+ if (previous === next) return true;
114
+ for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
115
+ if (key === "turnItems" || key === "visibleTurnItems" || key === "updatedAt") continue;
116
+ if (previous[key] !== next[key]) return false;
117
+ }
118
+ if (
119
+ previous.turnItems.length !== next.turnItems.length ||
120
+ previous.visibleTurnItems.length !== next.visibleTurnItems.length
121
+ ) {
122
+ return false;
123
+ }
124
+ for (let index = 0; index < next.turnItems.length; index += 1) {
125
+ if (!sameTurnItemStructure(previous.turnItems[index]!, next.turnItems[index]!)) {
126
+ return false;
127
+ }
128
+ }
129
+ for (let index = 0; index < next.visibleTurnItems.length; index += 1) {
130
+ const before = previous.visibleTurnItems[index]!;
131
+ const after = next.visibleTurnItems[index]!;
132
+ if (before === after) continue;
133
+ if (
134
+ before.position !== after.position ||
135
+ before.visibility !== after.visibility ||
136
+ before.sourceThreadId !== after.sourceThreadId ||
137
+ before.sourceItemId !== after.sourceItemId ||
138
+ !sameTurnItemStructure(before.item, after.item)
139
+ ) {
140
+ return false;
141
+ }
142
+ }
143
+ return true;
144
+}
145
+
146
export function createEnvironmentThreadDetailAtoms<E>(
147
threadStateAtom: (
148
environmentId: ScopedThreadRef["environmentId"],
@@ -55,6 +172,32 @@ export function createEnvironmentThreadDetailAtoms<E>(
172
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread:${key}`));
173
});
174
175
+ // Streamed assistant and reasoning text replaces an item several times a
176
+ // second. Readers of the thread's structure (runs, requests, which items
177
+ // exist and their status) keep the previous value through those updates.
178
+ const quietThreadAtomFamily = Atom.family((key: string) => {
179
+ let previousProjection: OrchestrationV2ThreadProjection | null = null;
180
+ let previous: EnvironmentThreadStructure | null = null;
181
+ return Atom.make((get) => {
182
+ const next = get(threadAtomFamily(key));
183
+ if (next === null) {
184
+ previousProjection = null;
185
+ previous = null;
186
+ } else if (
187
+ previousProjection === null ||
188
+ !sameThreadStructure(previousProjection, next.projection)
189
+ ) {
190
+ previous = {
191
+ environmentId: next.environmentId,
192
+ projection: toThreadStructure(next.projection),
193
+ };
194
+ }
195
+ // Compared against the latest projection, a delta only compares the item it replaced.
196
+ previousProjection = next?.projection ?? null;
197
+ return previous;
198
+ }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));
199
+ });
200
+
201
const visibleTurnItemsAtomFamily = Atom.family((key: string) => {
202
const projectQuestionHistory = createQuestionHistoryProjector();
203
return Atom.make((get): OrchestrationV2ThreadProjection["visibleTurnItems"] => {
@@ -63,6 +206,19 @@ export function createEnvironmentThreadDetailAtoms<E>(
206
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`));
207
});
208
209
+ const quietVisibleTurnItemsAtomFamily = Atom.family((key: string) => {
210
+ const projectQuestionHistory = createQuestionHistoryProjector<ThreadStructureVisibleTurnItem>();
211
+ return Atom.make((get) => {
212
+ const thread = get(quietThreadAtomFamily(key));
213
+ return thread === null
214
+ ? EMPTY_THREAD_STRUCTURE_TURN_ITEMS
215
+ : projectQuestionHistory(thread.projection);
216
+ }).pipe(
217
+ Atom.setIdleTTL(0),
218
+ Atom.withLabel(`environment-quiet-thread-visible-turn-items:${key}`),
219
+ );
220
+ });
221
+
222
const queueWorkflowAtomFamily = Atom.family((key: string) => {
223
let previous: Pick<
224
OrchestrationV2ThreadProjection,
@@ -148,6 +304,11 @@ export function createEnvironmentThreadDetailAtoms<E>(
304
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoint-summaries:${key}`));
305
});
306
307
+ const updatedAtAtomFamily = Atom.family((key: string) =>
308
+ Atom.make(
309
+ (get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.updatedAt ?? null,
310
+ ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-updated-at:${key}`)),
311
+ );
312
const worktreePathAtomFamily = Atom.family((key: string) =>
313
Atom.make(
314
(get) =>
@@ -210,6 +371,7 @@ export function createEnvironmentThreadDetailAtoms<E>(
371
372
return {
373
worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
374
+ updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
375
pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
376
queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
377
queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),
@@ -218,7 +380,10 @@ export function createEnvironmentThreadDetailAtoms<E>(
380
checkpointSummariesAtomFamily(threadKey(ref)),
381
stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
382
threadAtom: (ref: ScopedThreadRef) => threadAtomFamily(threadKey(ref)),
383
+ quietThreadAtom: (ref: ScopedThreadRef) => quietThreadAtomFamily(threadKey(ref)),
384
visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
385
+ quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>
386
+ quietVisibleTurnItemsAtomFamily(threadKey(ref)),
387
statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),
388
errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),
389
historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)),
packages/client-runtime/src/state/threadExecution.ts
+23
-20
@@ -30,6 +30,8 @@ import {
30
threadRuntimeIsActive,
31
type ThreadRunSummary,
32
type ThreadRuntimeSummary,
33
+ type ThreadStructure,
34
+ type ThreadStructureRuntime,
35
} from "./models.ts";
36
import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
37
@@ -37,7 +39,7 @@ const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "wait
39
const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
40
41
function latestMatchingRun(
40
- projection: OrchestrationV2ThreadProjection,
42
+ projection: ThreadStructure,
43
predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean,
44
): OrchestrationV2ThreadProjection["runs"][number] | null {
45
return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | null>(
@@ -50,7 +52,7 @@ function latestMatchingRun(
52
}
53
54
function summarizeThreadRun(
53
- projection: OrchestrationV2ThreadProjection,
55
+ projection: ThreadStructure,
56
run: OrchestrationV2ThreadProjection["runs"][number],
57
): ThreadRunSummary {
58
const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)
@@ -74,7 +76,7 @@ function summarizeThreadRun(
76
}
77
78
function presentedUsageLimitRun(
77
- projection: OrchestrationV2ThreadProjection,
79
+ projection: ThreadStructure,
80
): OrchestrationV2ThreadProjection["runs"][number] | null {
81
const providerSession = projection.providerSessions.findLast(
82
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
@@ -87,21 +89,17 @@ function presentedUsageLimitRun(
89
}
90
91
function presentedLatestRun(
90
- projection: OrchestrationV2ThreadProjection,
92
+ projection: ThreadStructure,
93
): OrchestrationV2ThreadProjection["runs"][number] | null {
94
return presentedUsageLimitRun(projection) ?? latestUnheldRun(projection.runs);
95
}
96
95
-export function deriveLatestThreadRun(
96
- projection: OrchestrationV2ThreadProjection,
97
-): ThreadRunSummary | null {
97
+export function deriveLatestThreadRun(projection: ThreadStructure): ThreadRunSummary | null {
98
const run = presentedLatestRun(projection);
99
return run === null ? null : summarizeThreadRun(projection, run);
100
}
101
102
-export function deriveThreadActivityRun(
103
- projection: OrchestrationV2ThreadProjection,
104
-): ThreadRunSummary | null {
102
+export function deriveThreadActivityRun(projection: ThreadStructure): ThreadRunSummary | null {
103
const run =
104
latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
105
presentedLatestRun(projection);
@@ -112,9 +110,7 @@ export function deriveThreadActivityRun(
110
* Provider-native subagent threads never get app runs: their work is a runless
111
* root turn whose status follows the subagent.
112
*/
115
-export function deriveRunlessWorkStartedAt(
116
- projection: OrchestrationV2ThreadProjection,
117
-): string | null {
113
+export function deriveRunlessWorkStartedAt(projection: ThreadStructure): string | null {
114
const status = deriveProviderSubagentStatus(projection);
115
return status !== null && isOrchestrationV2WorkActive(status.status) ? status.startedAt : null;
116
}
@@ -126,7 +122,7 @@ export interface ProviderSubagentStatus {
122
}
123
124
export function deriveProviderSubagentStatus(
129
- projection: OrchestrationV2ThreadProjection,
125
+ projection: ThreadStructure,
126
): ProviderSubagentStatus | null {
127
if (!isProviderNativeSubagentThread(projection.thread)) return null;
128
const node = projection.nodes.findLast(
@@ -140,9 +136,7 @@ export function deriveProviderSubagentStatus(
136
};
137
}
138
143
-export function deriveReportedModelSelection(
144
- projection: OrchestrationV2ThreadProjection,
145
-): ModelSelection | null {
139
+export function deriveReportedModelSelection(projection: ThreadStructure): ModelSelection | null {
140
const providerThread = projection.providerThreads.find(
141
(candidate) =>
142
candidate.id === projection.thread.activeProviderThreadId &&
@@ -215,8 +209,18 @@ export function formatProviderSubagentStatus(
209
}
210
211
export function deriveThreadRuntime(
218
- projection: OrchestrationV2ThreadProjection,
212
+ projection: ThreadStructure & Pick<OrchestrationV2ThreadProjection, "updatedAt">,
213
): ThreadRuntimeSummary | null {
214
+ const runtime = deriveThreadStructureRuntime(projection);
215
+ return runtime === null
216
+ ? null
217
+ : { ...runtime, updatedAt: DateTime.formatIso(projection.updatedAt) };
218
+}
219
+
220
+/** The runtime summary a thread's structure determines: all of it but `updatedAt`. */
221
+export function deriveThreadStructureRuntime(
222
+ projection: ThreadStructure,
223
+): ThreadStructureRuntime | null {
224
const latestRun = deriveLatestThreadRun(projection);
225
const providerSession = projection.providerSessions.findLast(
226
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
@@ -264,12 +268,11 @@ export function deriveThreadRuntime(
268
latestRootProviderFailure(latestRunProjection, projection.turnItems),
269
providerSession?.lastError ?? null,
270
),
267
- updatedAt: DateTime.formatIso(projection.updatedAt),
271
};
272
}
273
274
export function threadRuntimeHasInterruptibleRun(
272
- runtime: ThreadRuntimeSummary | null | undefined,
275
+ runtime: ThreadStructureRuntime | null | undefined,
276
): boolean {
277
return (
278
threadRuntimeIsActive(runtime) &&
packages/client-runtime/src/state/threadRequests.ts
+13
-8
@@ -10,6 +10,7 @@ import type {
10
} from "@t3tools/contracts";
11
import * as DateTime from "effect/DateTime";
12
import type { AtomCommandResult } from "./runtime.ts";
13
+import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.ts";
14
15
export type ApprovalResponder = (
16
requestId: RuntimeRequestId,
@@ -93,7 +94,7 @@ export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?
94
}
95
96
export function derivePendingThreadRequests(
96
- projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests" | "turnItems">,
97
+ projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
98
): PendingThreadRequests {
99
const approvals: ThreadPendingApproval[] = [];
100
const userInputs: ThreadPendingUserInput[] = [];
@@ -147,21 +148,25 @@ export function derivePendingThreadRequests(
148
return { approvals, userInputs };
149
}
150
150
-export function createQuestionHistoryProjector() {
151
- type Rows = OrchestrationV2ThreadProjection["visibleTurnItems"];
151
+export function createQuestionHistoryProjector<
152
+ Row extends ThreadStructureVisibleTurnItem =
153
+ OrchestrationV2ThreadProjection["visibleTurnItems"][number],
154
+>() {
155
+ type Rows = ReadonlyArray<Row>;
156
type Requests = OrchestrationV2ThreadProjection["runtimeRequests"];
157
let previousRows: Rows | undefined;
158
let previousRequests: Requests | undefined;
159
let previousResult: Rows | undefined;
156
- const cache = new WeakMap<Rows[number], { request: Requests[number]; row: Rows[number] }>();
157
- return (
158
- projection: Pick<OrchestrationV2ThreadProjection, "visibleTurnItems" | "runtimeRequests">,
159
- ): Rows => {
160
+ const cache = new WeakMap<Row, { request: Requests[number]; row: Row }>();
161
+ return (projection: {
162
+ readonly visibleTurnItems: Rows;
163
+ readonly runtimeRequests: Requests;
164
+ }): Rows => {
165
const { visibleTurnItems: rows, runtimeRequests: requests } = projection;
166
if (rows === previousRows && requests === previousRequests && previousResult)
167
return previousResult;
168
const byId = new Map(requests.map((request) => [request.id, request]));
164
- let result: Rows[number][] | undefined;
169
+ let result: Row[] | undefined;
170
for (const [index, row] of rows.entries()) {
171
const item = row.item;
172
const request =
packages/client-runtime/src/state/threadWorkflows.ts
+3
-2
@@ -2,11 +2,12 @@ import type {
2
ChatAttachment,
3
OrchestrationV2ProjectedTurnItem,
4
OrchestrationV2ProviderCapabilities,
5
- OrchestrationV2ThreadProjection,
5
} from "@t3tools/contracts";
6
import { copySorted } from "@t3tools/shared/Array";
7
9
-type Projection = OrchestrationV2ThreadProjection;
8
+import type { ThreadStructure } from "./models.ts";
9
+
10
+type Projection = ThreadStructure;
11
type Run = Projection["runs"][number];
12
type Message = Projection["messages"][number];
13
type ProviderSession = Projection["providerSessions"][number];
packages/client-runtime/src/state/turnItemPresentation.ts
+3
-1
@@ -4,6 +4,8 @@ import {
4
type OrchestrationV2TurnItem,
5
} from "@t3tools/contracts";
6
7
+import type { ThreadStructureTurnItem } from "./models.ts";
8
+
9
const WORKSPACE_PREPARATION_INPUT = "Preparing workspace";
10
11
export function turnItemIsWorkspacePreparation(item: OrchestrationV2TurnItem): boolean {
@@ -17,7 +19,7 @@ export function turnItemIsWorkspacePreparation(item: OrchestrationV2TurnItem): b
19
20
export function workspacePreparationRetryRunIds(
21
runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "status" | "workspacePreparation">>,
20
- items: ReadonlyArray<OrchestrationV2TurnItem>,
22
+ items: ReadonlyArray<ThreadStructureTurnItem>,
23
): ReadonlySet<OrchestrationV2Run["id"]> {
24
const failedRuns = new Set(
25
runs.flatMap((run) =>
packages/shared/src/orchestrationV2ThreadError.ts
+10
-4
@@ -5,12 +5,18 @@ import type {
5
} from "@t3tools/contracts";
6
import * as DateTime from "effect/DateTime";
7
8
+type ErrorTurnItem = Extract<OrchestrationV2TurnItem, { type: "error" }>;
9
+/** Only error items are read, so callers may pass items stripped of other fields. */
10
+type FailureScanTurnItem =
11
+ | ErrorTurnItem
12
+ | { readonly type: Exclude<OrchestrationV2TurnItem["type"], "error"> };
13
+
14
export function latestRootProviderFailure(
15
run: OrchestrationV2Run | null,
10
- turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
16
+ turnItems: ReadonlyArray<FailureScanTurnItem>,
17
): OrchestrationV2ProviderFailure | null {
18
if (run?.status !== "failed") return null;
13
- let latest: Extract<OrchestrationV2TurnItem, { type: "error" }> | null = null;
19
+ let latest: ErrorTurnItem | null = null;
20
for (const item of turnItems) {
21
if (
22
item.type !== "error" ||
@@ -77,7 +83,7 @@ export function runRanAfter(
83
84
export function usageLimitBlockedRun(
85
runs: ReadonlyArray<OrchestrationV2Run>,
80
- turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
86
+ turnItems: ReadonlyArray<FailureScanTurnItem>,
87
sessionError: string | null,
88
): OrchestrationV2Run | null {
89
const executed = latestExecutedRun(runs);
@@ -93,7 +99,7 @@ export function usageLimitBlockedRun(
99
*/
100
export function usageLimitRunPresentedAsLatest(
101
runs: ReadonlyArray<OrchestrationV2Run>,
96
- turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
102
+ turnItems: ReadonlyArray<FailureScanTurnItem>,
103
sessionError: string | null,
104
): OrchestrationV2Run | null {
105
const blocked = usageLimitBlockedRun(runs, turnItems, sessionError);