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 23, 05:30 UTC
perf(web): the open thread's chat chrome no longer re-renders on every streaming tick (#20860)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 08:41 UTC
4b1024dafe4766ea7c59546936c21ce0fab8acb3
18 files changed
+352
-195
apps/web/src/browserFaviconStore.test.ts
+1
-1
@@ -2,7 +2,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5
-vi.mock("~/state/entities", () => ({ useThreadShell: () => null }));
5
+vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => null }));
6
vi.mock("~/state/session", () => ({ usePreparedConnection: () => ({ _tag: "None" }) }));
7
8
import {
apps/web/src/browserFaviconStore.ts
+2
-2
@@ -9,7 +9,7 @@ import { create } from "zustand";
9
import { createJSONStorage, persist } from "zustand/middleware";
10
11
import { normalizeHostname } from "~/browser/browserTargetResolver";
12
-import { useThreadShell } from "~/state/entities";
12
+import { useQuietThreadShell } from "~/state/entities";
13
import { usePreparedConnection } from "~/state/session";
14
15
import {
@@ -196,7 +196,7 @@ export function registerFaviconProjectForThread(
196
}
197
198
export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
199
- const shell = useThreadShell(threadRef);
199
+ const shell = useQuietThreadShell(threadRef);
200
const shellProjectId = shell?.projectId ?? null;
201
const environmentId = threadRef.environmentId;
202
const shellProjectRef = shellProjectId ? scopeProjectRef(environmentId, shellProjectId) : null;
apps/web/src/components/BranchToolbar.panel.test.tsx
+1
-1
@@ -23,7 +23,7 @@ vi.mock("../composerDraftStore", () => ({
23
select({ getDraftThreadByRef: () => null, setDraftThreadContext: vi.fn() }),
24
}));
25
vi.mock("../state/entities", () => ({
26
- useThreadShell: () => ({
26
+ useQuietThreadShell: () => ({
27
environmentId: "local",
28
projectId: "project",
29
worktreePath: state.worktreePath,
apps/web/src/components/BranchToolbar.tsx
+2
-2
@@ -25,7 +25,7 @@ import {
25
26
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
27
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
28
-import { useProject, useThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
28
+import { useProject, useQuietThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
29
import {
30
type EnvMode,
31
type EnvironmentOption,
@@ -587,7 +587,7 @@ export const BranchToolbar = memo(function BranchToolbar({
587
const draftThread = useComposerDraftStore((store) =>
588
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
589
);
590
- const serverThread = useThreadShell(threadRef);
590
+ const serverThread = useQuietThreadShell(threadRef);
591
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
592
const activeProjectRef = serverThread
593
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
apps/web/src/components/BranchToolbarBranchSelector.tsx
+2
-2
@@ -33,7 +33,7 @@ import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
33
import { readLocalApi } from "../localApi";
34
import { useOpenPrLink } from "../lib/openPullRequestLink";
35
import { usePaginatedBranches } from "../state/queries";
36
-import { useProject, useThreadShell } from "../state/entities";
36
+import { useProject, useQuietThreadShell } from "../state/entities";
37
import { useEnvironmentQuery } from "../state/query";
38
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
39
import { threadEnvironment } from "../state/threads";
@@ -130,7 +130,7 @@ export function BranchToolbarBranchSelector({
130
reportFailure: false,
131
});
132
const threadRef = scopeThreadRef(environmentId, threadId);
133
- const serverThread = useThreadShell(threadRef);
133
+ const serverThread = useQuietThreadShell(threadRef);
134
const serverSession = serverThread?.runtime ?? null;
135
const draftThread = useComposerDraftStore((store) =>
136
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
apps/web/src/components/ChatView.tsx
+137
-169
@@ -23,6 +23,7 @@ import {
23
rememberCheckoutIsRepo,
24
} from "./ChatView.logic";
25
import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
26
+import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
27
import { useScratchProject } from "../hooks/useScratchProject";
28
import { useStableCallback } from "../hooks/useStableCallback";
29
import { useProjectScriptEditing } from "./chat/useProjectScriptEditing";
@@ -65,7 +66,6 @@ import {
66
type MessageId,
67
type ModelSelection,
68
type ProjectScript,
68
- type ProjectId,
69
type PreviewAnnotationPayload,
70
ProviderInstanceId,
71
type ServerProvider,
@@ -76,7 +76,6 @@ import {
76
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
77
ProviderInteractionMode,
78
ProviderDriverKind,
79
- resolveEnvironmentMachineKind,
79
resolveProjectProviderInstanceEnabled,
80
RuntimeMode,
81
} from "@t3tools/contracts";
@@ -376,6 +375,7 @@ import {
375
useThreadProjection,
376
useThreadStatus,
377
useThreadHistory,
378
+ useQuietThreadShell,
379
useThreadShell,
380
useChildThreadInputs,
381
useThreadRefs,
@@ -419,10 +419,9 @@ import {
419
RightPanelMaximizeControl,
420
} from "./chat/PanelLayoutControls";
421
import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview";
422
-import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel";
422
+import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel";
423
import { NoActiveThreadState } from "./NoActiveThreadState";
424
import {
425
- type EnvironmentOption,
425
resolveEffectiveEnvMode,
426
resolveLocalCheckoutBranchMismatch,
427
shouldShowComposerContextStrip,
@@ -1111,7 +1110,7 @@ export default function ChatView(props: ChatViewProps) {
1110
? store.getDraftSession(draftId)
1111
: null,
1112
);
1114
- const serverThread = useThreadShell(routeThreadRef);
1113
+ const serverThread = useQuietThreadShell(routeThreadRef);
1114
const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, {
1115
shellExists: serverThread !== null,
1116
waitForShell: draftThread !== null,
@@ -1176,13 +1175,6 @@ export default function ChatView(props: ChatViewProps) {
1175
}
1176
return ids;
1177
})();
1179
- const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
1180
- const activeThreadLocalLastVisitedAt = useUiStateStore(
1181
- (store) => store.threadLastVisitedAtById[routeThreadKey],
1182
- );
1183
- const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
1184
- const lastDispatchedVisitRef = useRef<string | null>(null);
1185
- const lastVisitDispatchAtRef = useRef(0);
1178
const settings = useEnvironmentSettings(environmentId);
1179
const clientSettingsHydrated = useClientSettingsHydrated();
1180
const setStickyComposerModelSelection = useComposerDraftStore(
@@ -1495,7 +1487,7 @@ export default function ChatView(props: ChatViewProps) {
1487
}
1488
return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId);
1489
})();
1498
- const parentSubagentThread = useThreadShell(parentSubagentThreadRef);
1490
+ const parentSubagentThread = useQuietThreadShell(parentSubagentThreadRef);
1491
const parentThreadLink =
1492
parentSubagentThreadRef === null
1493
? null
@@ -1572,7 +1564,7 @@ export default function ChatView(props: ChatViewProps) {
1564
container: workspaceLayoutElement,
1565
widthStorageKey: `t3code:preview-panel-width:${activeThreadKey}`,
1566
});
1575
- const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
1567
+ const activeThreadShell = useQuietThreadShell(isServerThread ? activeThreadRef : null);
1568
const timelineThreadError =
1569
serverRuntime?.status === "failed" &&
1570
serverRuntime.lastErrorClass === "usage_limit" &&
@@ -2014,60 +2006,17 @@ export default function ChatView(props: ChatViewProps) {
2006
const handleDisconnectActiveEnvironmentStable = useStableCallback(
2007
handleDisconnectActiveEnvironment,
2008
);
2017
- const { scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
2009
+ const { openScratchProject } = useScratchProject();
2010
const activeProjectIsScratch =
2011
activeProject !== null &&
2012
isScratchProject(
2013
activeProject,
2014
environmentById.get(activeProject.environmentId)?.serverConfig?.scratchWorkspaceRoot ?? null,
2015
);
2024
- const logicalProjectEnvironments = (() => {
2025
- if (!activeProject) return [];
2026
- const envs: EnvironmentOption[] = [];
2027
- const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
2028
- const environment = environmentById.get(environmentId) ?? null;
2029
- envs.push({
2030
- environmentId,
2031
- projectId,
2032
- label: environment?.label ?? environmentId,
2033
- isPrimary: environmentId === primaryEnvironmentId,
2034
- machine: resolveEnvironmentMachineKind(environment?.serverConfig ?? null),
2035
- });
2036
- };
2037
- if (activeProjectIsScratch && draftId) {
2038
- for (const environment of environments) {
2039
- const scratchRoot = scratchWorkspaceRootFor(environment.environmentId);
2040
- if (scratchRoot === null && environment.environmentId !== activeProject.environmentId)
2041
- continue;
2042
- const scratchProject =
2043
- environment.environmentId === activeProject.environmentId
2044
- ? activeProject
2045
- : allProjects.find(
2046
- (p) =>
2047
- p.environmentId === environment.environmentId && isScratchProject(p, scratchRoot),
2048
- );
2049
- pushEnvironment(environment.environmentId, scratchProject?.id ?? null);
2050
- }
2051
- } else {
2052
- const logicalKey = deriveLogicalProjectKeyFromSettings(
2053
- activeProject,
2054
- projectGroupingSettings,
2055
- );
2056
- const seen = new Set<string>();
2057
- for (const p of allProjects) {
2058
- if (seen.has(p.environmentId)) continue;
2059
- if (deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) !== logicalKey)
2060
- continue;
2061
- seen.add(p.environmentId);
2062
- pushEnvironment(p.environmentId, p.id);
2063
- }
2064
- }
2065
- envs.sort((a, b) => {
2066
- if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;
2067
- return a.label.localeCompare(b.label);
2068
- });
2069
- return envs;
2070
- })();
2016
+ const logicalProjectEnvironments = useLogicalProjectEnvironments(
2017
+ activeProject,
2018
+ activeProjectIsScratch && draftId !== null,
2019
+ );
2020
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
2021
const canAutoBalanceEnvironments = hasMultipleEnvironments && !activeProjectIsScratch;
2022
const activeEnvironmentOption =
@@ -2163,63 +2112,6 @@ export default function ChatView(props: ChatViewProps) {
2112
};
2113
const handlePreparedPullRequestThreadStable = useStableCallback(handlePreparedPullRequestThread);
2114
2166
- useEffect(() => {
2167
- if (!serverThread?.id) return;
2168
- const threadUpdatedAt = Date.parse(serverThread.updatedAt);
2169
- if (Number.isNaN(threadUpdatedAt)) return;
2170
- const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
2171
- serverThread.lastVisitedAt,
2172
- activeThreadLocalLastVisitedAt,
2173
- );
2174
- const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
2175
- if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
2176
-
2177
- if (serverThread.lastVisitedAt !== undefined) {
2178
- // Dedupe per watermark — the effect re-runs before the command's echo
2179
- // lands. The dedupe also keeps a mark-unread on the open thread sticky:
2180
- // the rewind leaves updatedAt untouched, so the already-dispatched key
2181
- // skips a fresh visit until new activity lands or the thread is reopened.
2182
- const dispatchKey = `${routeThreadKey}:${serverThread.updatedAt}`;
2183
- if (lastDispatchedVisitRef.current === dispatchKey) return;
2184
- const dispatch = () => {
2185
- lastDispatchedVisitRef.current = dispatchKey;
2186
- lastVisitDispatchAtRef.current = Date.now();
2187
- void visitThreadMutation({
2188
- environmentId: serverThread.environmentId,
2189
- input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
2190
- });
2191
- };
2192
- const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
2193
- ? Date.parse(serverThread.latestRun.completedAt)
2194
- : NaN;
2195
- const hasUnseenCompletion =
2196
- !Number.isNaN(latestRunCompletedAtMs) &&
2197
- (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
2198
- const elapsed = Date.now() - lastVisitDispatchAtRef.current;
2199
- if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
2200
- dispatch();
2201
- return;
2202
- }
2203
- const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
2204
- return () => clearTimeout(timer);
2205
- }
2206
-
2207
- markThreadVisited(
2208
- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
2209
- serverThread.updatedAt,
2210
- );
2211
- }, [
2212
- activeThreadLocalLastVisitedAt,
2213
- markThreadVisited,
2214
- routeThreadKey,
2215
- serverThread?.environmentId,
2216
- serverThread?.id,
2217
- serverThread?.lastVisitedAt,
2218
- serverThread?.latestRun?.completedAt,
2219
- serverThread?.updatedAt,
2220
- visitThreadMutation,
2221
- ]);
2222
-
2115
const serverConfig = activeThread
2116
? (activeEnvironment?.serverConfig ?? null)
2117
: (primaryEnvironment?.serverConfig ?? null);
@@ -7812,55 +7704,6 @@ export default function ChatView(props: ChatViewProps) {
7704
}}
7705
/>
7706
) : null;
7815
- const threadDetailsPanelProps: ThreadDetailsPanelProps = {
7816
- anchor: threadPanelPopoverAnchorRef,
7817
- handle: threadPanelPopoverHandle,
7818
- onPresentationChange: setThreadPanelPresentation,
7819
- forceNewWorktree: multipleModelSelections !== null,
7820
- environmentId: activeThread.environmentId,
7821
- threadId: activeThread.id,
7822
- ...(draftId ? { draftId } : {}),
7823
- activeProjectName: activeProject?.title,
7824
- activeProjectScripts: activeProject ? activeProjectScripts : undefined,
7825
- preferredScriptId: activeProject
7826
- ? (lastInvokedScriptByProjectId[activeProject.id] ?? null)
7827
- : null,
7828
- keybindings,
7829
- availableEditors,
7830
- showOpenInPicker,
7831
- gitCwd,
7832
- isGitRepo,
7833
- envLocked,
7834
- availableEnvironments: logicalProjectEnvironments,
7835
- autoEnvironmentLabel,
7836
- onAutoEnvironment:
7837
- draftId &&
7838
- !envLocked &&
7839
- canAutoBalanceEnvironments &&
7840
- loadBalancingSettings.loadBalancingEnabled
7841
- ? onAutoEnvironmentStable
7842
- : undefined,
7843
- onEnvironmentChange: onEnvironmentChangeStable,
7844
- onEnvModeChange: onEnvModeChangeStable,
7845
- envMode,
7846
- ...(canOverrideServerThreadEnvMode
7847
- ? {
7848
- activeThreadBranchOverride: activeThreadBranch,
7849
- onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
7850
- }
7851
- : {}),
7852
- startFromOrigin,
7853
- onStartFromOriginChange,
7854
- ...(canCheckoutPullRequestIntoThread
7855
- ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
7856
- : {}),
7857
- onComposerFocusRequest: scheduleComposerFocusStable,
7858
- ...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanelStable } : {}),
7859
- onRunProjectScript: runProjectScriptStable,
7860
- onAddProjectScript: saveProjectScriptStable,
7861
- onUpdateProjectScript: updateProjectScriptStable,
7862
- onDeleteProjectScript: deleteProjectScriptStable,
7863
- };
7707
const panelToggleControlProps = {
7708
terminalAvailable: activeProject !== null,
7709
terminalOpen: terminalUiState.terminalOpen,
@@ -8530,7 +8373,58 @@ export default function ChatView(props: ChatViewProps) {
8373
onConfirm={handleSwitchCheckoutToThreadStable}
8374
/>
8375
8533
- <ThreadDetailsPanel {...threadDetailsPanelProps} />
8376
+ <ThreadDetailsPanel
8377
+ anchor={threadPanelPopoverAnchorRef}
8378
+ handle={threadPanelPopoverHandle}
8379
+ onPresentationChange={setThreadPanelPresentation}
8380
+ forceNewWorktree={multipleModelSelections !== null}
8381
+ environmentId={activeThread.environmentId}
8382
+ threadId={activeThread.id}
8383
+ {...(draftId ? { draftId } : {})}
8384
+ activeProjectName={activeProject?.title}
8385
+ activeProjectScripts={activeProject ? activeProjectScripts : undefined}
8386
+ preferredScriptId={
8387
+ activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
8388
+ }
8389
+ keybindings={keybindings}
8390
+ availableEditors={availableEditors}
8391
+ showOpenInPicker={showOpenInPicker}
8392
+ gitCwd={gitCwd}
8393
+ isGitRepo={isGitRepo}
8394
+ envLocked={envLocked}
8395
+ availableEnvironments={logicalProjectEnvironments}
8396
+ autoEnvironmentLabel={autoEnvironmentLabel}
8397
+ onAutoEnvironment={
8398
+ draftId &&
8399
+ !envLocked &&
8400
+ canAutoBalanceEnvironments &&
8401
+ loadBalancingSettings.loadBalancingEnabled
8402
+ ? onAutoEnvironmentStable
8403
+ : undefined
8404
+ }
8405
+ onEnvironmentChange={onEnvironmentChangeStable}
8406
+ onEnvModeChange={onEnvModeChangeStable}
8407
+ envMode={envMode}
8408
+ {...(canOverrideServerThreadEnvMode
8409
+ ? {
8410
+ activeThreadBranchOverride: activeThreadBranch,
8411
+ onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
8412
+ }
8413
+ : {})}
8414
+ startFromOrigin={startFromOrigin}
8415
+ onStartFromOriginChange={onStartFromOriginChange}
8416
+ {...(canCheckoutPullRequestIntoThread
8417
+ ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
8418
+ : {})}
8419
+ onComposerFocusRequest={scheduleComposerFocusStable}
8420
+ {...(isServerThread && isGitRepo
8421
+ ? { onOpenChanges: openChangesFromThreadPanelStable }
8422
+ : {})}
8423
+ onRunProjectScript={runProjectScriptStable}
8424
+ onAddProjectScript={saveProjectScriptStable}
8425
+ onUpdateProjectScript={updateProjectScriptStable}
8426
+ onDeleteProjectScript={deleteProjectScriptStable}
8427
+ />
8428
8429
<PullRequestThreadDialogHost
8430
threadKey={activeThreadKey}
@@ -8667,6 +8561,7 @@ export default function ChatView(props: ChatViewProps) {
8561
8562
<RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />
8563
<LinkPullRequestDialogHost />
8564
+ <ThreadVisitWatermark threadRef={routeThreadRef} />
8565
<ExpandedImageDialogHost threadKey={routeThreadKey} />
8566
</div>
8567
);
@@ -8685,3 +8580,76 @@ function PreviewSessionSync(props: { readonly threadRef: ScopedThreadRef }) {
8580
usePreviewSession(props.threadRef);
8581
return null;
8582
}
8583
+
8584
+// The visit watermark is the one part of the chat view that follows the
8585
+// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
8586
+// ChatView read the quiet shell.
8587
+function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
8588
+ const serverThread = useThreadShell(props.threadRef);
8589
+ const threadKey = scopedThreadKey(props.threadRef);
8590
+ const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
8591
+ const activeThreadLocalLastVisitedAt = useUiStateStore(
8592
+ (store) => store.threadLastVisitedAtById[threadKey],
8593
+ );
8594
+ const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
8595
+ const lastDispatchedVisitRef = useRef<string | null>(null);
8596
+ const lastVisitDispatchAtRef = useRef(0);
8597
+
8598
+ useEffect(() => {
8599
+ if (!serverThread?.id) return;
8600
+ const threadUpdatedAt = Date.parse(serverThread.updatedAt);
8601
+ if (Number.isNaN(threadUpdatedAt)) return;
8602
+ const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
8603
+ serverThread.lastVisitedAt,
8604
+ activeThreadLocalLastVisitedAt,
8605
+ );
8606
+ const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
8607
+ if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
8608
+
8609
+ if (serverThread.lastVisitedAt !== undefined) {
8610
+ // Dedupe per watermark — the effect re-runs before the command's echo
8611
+ // lands. The dedupe also keeps a mark-unread on the open thread sticky:
8612
+ // the rewind leaves updatedAt untouched, so the already-dispatched key
8613
+ // skips a fresh visit until new activity lands or the thread is reopened.
8614
+ const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
8615
+ if (lastDispatchedVisitRef.current === dispatchKey) return;
8616
+ const dispatch = () => {
8617
+ lastDispatchedVisitRef.current = dispatchKey;
8618
+ lastVisitDispatchAtRef.current = Date.now();
8619
+ void visitThreadMutation({
8620
+ environmentId: serverThread.environmentId,
8621
+ input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
8622
+ });
8623
+ };
8624
+ const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
8625
+ ? Date.parse(serverThread.latestRun.completedAt)
8626
+ : NaN;
8627
+ const hasUnseenCompletion =
8628
+ !Number.isNaN(latestRunCompletedAtMs) &&
8629
+ (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
8630
+ const elapsed = Date.now() - lastVisitDispatchAtRef.current;
8631
+ if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
8632
+ dispatch();
8633
+ return;
8634
+ }
8635
+ const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
8636
+ return () => clearTimeout(timer);
8637
+ }
8638
+
8639
+ markThreadVisited(
8640
+ scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
8641
+ serverThread.updatedAt,
8642
+ );
8643
+ }, [
8644
+ activeThreadLocalLastVisitedAt,
8645
+ markThreadVisited,
8646
+ threadKey,
8647
+ serverThread?.environmentId,
8648
+ serverThread?.id,
8649
+ serverThread?.lastVisitedAt,
8650
+ serverThread?.latestRun?.completedAt,
8651
+ serverThread?.updatedAt,
8652
+ visitThreadMutation,
8653
+ ]);
8654
+ return null;
8655
+}
apps/web/src/components/DiffPanel.tsx
+2
-2
@@ -45,7 +45,7 @@ import {
45
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
46
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
47
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
48
-import { useProject, useThreadCheckpointSummaries, useThreadShell } from "../state/entities";
48
+import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";
49
import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";
50
import { formatShortTimestamp } from "../timestampFormat";
51
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
@@ -222,7 +222,7 @@ export default function DiffPanel({
222
223
const routeThreadRef = useThreadRouteRef();
224
const activeThreadId = routeThreadRef?.threadId ?? null;
225
- const activeThread = useThreadShell(routeThreadRef);
225
+ const activeThread = useQuietThreadShell(routeThreadRef);
226
const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null);
227
const { canReadFiles } = fileAccess;
228
const activeProjectId = activeThread?.projectId ?? null;
apps/web/src/components/GitActionsControl.lifecycle.test.ts
+1
-1
@@ -18,7 +18,7 @@ vi.mock("@effect/atom-react", () => ({
18
}));
19
vi.mock("~/state/entities", () => ({
20
useThreadProjection: () => null,
21
- useThreadShell: (ref: { threadId: string }) => ({ branch: "main", id: ref.threadId }),
21
+ useQuietThreadShell: (ref: { threadId: string }) => ({ branch: "main", id: ref.threadId }),
22
}));
23
vi.mock("~/state/session", () => ({
24
useEnvironmentScope: (environmentId: unknown, scope: string) =>
apps/web/src/components/GitActionsControl.test.ts
+1
-1
@@ -27,7 +27,7 @@ vi.mock("@effect/atom-react", () => ({
27
vi.mock("~/state/entities", () => ({
28
useThreadProjection: (ref: unknown) =>
29
ref === null || state.detail === null ? null : { projection: { thread: state.detail } },
30
- useThreadShell: () => state.shell,
30
+ useQuietThreadShell: () => state.shell,
31
}));
32
vi.mock("~/state/session", () => ({
33
useEnvironmentScope: (environmentId: unknown, scope: string) =>
apps/web/src/components/GitActionsControl.tsx
+2
-2
@@ -97,7 +97,7 @@ import {
97
useVcsInitAction,
98
useVcsPullAction,
99
} from "~/lib/sourceControlActions";
100
-import { useThreadProjection, useThreadShell } from "~/state/entities";
100
+import { useThreadProjection, useQuietThreadShell } from "~/state/entities";
101
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
102
import { useEnvironmentQuery } from "~/state/query";
103
import { serverEnvironment } from "~/state/server";
@@ -982,7 +982,7 @@ export default function GitActionsControl({
982
serverConfig?.availableEditors ?? [],
983
);
984
const threadToastData = activeThreadRef ? { threadRef: activeThreadRef } : undefined;
985
- const activeServerThreadShell = useThreadShell(activeThreadRef);
985
+ const activeServerThreadShell = useQuietThreadShell(activeThreadRef);
986
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
987
const activeDraftThread = useComposerDraftStore((store) =>
988
draftId
apps/web/src/components/PersistentThreadTerminals.tsx
+3
-3
@@ -18,7 +18,7 @@ import {
18
useRightPanelStore,
19
type RightPanelSurface,
20
} from "../rightPanelStore";
21
-import { useProject, useThreadShell } from "../state/entities";
21
+import { useProject, useQuietThreadShell } from "../state/entities";
22
import { useEnvironmentScope } from "../state/session";
23
import { useKnownTerminalSessions } from "../state/terminalSessions";
24
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
@@ -105,7 +105,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
105
}: PersistentThreadTerminalDrawerProps) {
106
const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
107
const terminalActions = useThreadTerminalActions(threadRef);
108
- const serverThread = useThreadShell(threadRef);
108
+ const serverThread = useQuietThreadShell(threadRef);
109
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
110
const projectRef = serverThread
111
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
@@ -330,7 +330,7 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
330
newShortcutLabel,
331
closeShortcutLabel,
332
}: PersistentThreadTerminalPanelProps) {
333
- const serverThread = useThreadShell(threadRef);
333
+ const serverThread = useQuietThreadShell(threadRef);
334
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
335
const projectRef = serverThread
336
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
apps/web/src/components/ThreadRouteView.tsx
+2
-2
@@ -14,7 +14,7 @@ import {
14
useComposerDraftStore,
15
} from "../composerDraftStore";
16
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
17
-import { useEnvironmentThreadRefs, useThreadRefs, useThreadShell } from "../state/entities";
17
+import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
18
import { useEnvironmentShellStatus } from "../state/shell";
19
import {
20
buildThreadRouteParams,
@@ -44,7 +44,7 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
44
: null;
45
const serverThreadRef: ScopedThreadRef | null =
46
target.kind === "server" ? target.threadRef : (draftSession?.promotedTo ?? inferredThreadRef);
47
- const serverThread = useThreadShell(serverThreadRef);
47
+ const serverThread = useQuietThreadShell(serverThreadRef);
48
const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
49
target.kind === "draft" ? serverThreadRef : null,
50
);
apps/web/src/components/terminal/useThreadTerminalActions.ts
+2
-2
@@ -11,7 +11,7 @@ import { useComposerDraftStore } from "../../composerDraftStore";
11
import { useStableCallback } from "../../hooks/useStableCallback";
12
import { randomUUID } from "~/lib/utils";
13
import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
14
-import { useProject, useThreadShell } from "../../state/entities";
14
+import { useProject, useQuietThreadShell } from "../../state/entities";
15
import { readEnvironmentScope } from "../../state/session";
16
import { terminalEnvironment } from "../../state/terminal";
17
import { useKnownTerminalSessions } from "../../state/terminalSessions";
@@ -34,7 +34,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
34
const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open");
35
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
36
const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close");
37
- const serverThread = useThreadShell(threadRef);
37
+ const serverThread = useQuietThreadShell(threadRef);
38
const draftThread = useComposerDraftStore((store) =>
39
threadRef ? store.getDraftThreadByRef(threadRef) : null,
40
);
apps/web/src/hooks/useHandleNewThread.ts
+2
-2
@@ -27,7 +27,7 @@ import {
27
readThreadShell,
28
readThreadShells,
29
useProjects,
30
- useThreadShell,
30
+ useQuietThreadShell,
31
} from "../state/entities";
32
import {
33
hasExplicitComposerModelSelection,
@@ -388,7 +388,7 @@ export function useHandleNewThread() {
388
const routeTarget = useThreadRouteTarget();
389
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
390
const routeDraftId = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
391
- const activeThread = useThreadShell(routeThreadRef);
391
+ const activeThread = useQuietThreadShell(routeThreadRef);
392
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
393
const activeDraftThread = useComposerDraftStore(() =>
394
routeTarget
apps/web/src/hooks/useLogicalProjectEnvironments.ts
new
+80
@@ -0,0 +1,80 @@
1
+import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
2
+import { isScratchProject } from "@t3tools/client-runtime/state/projects";
3
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4
+import {
5
+ type EnvironmentId,
6
+ type ProjectId,
7
+ resolveEnvironmentMachineKind,
8
+} from "@t3tools/contracts";
9
+
10
+import type { EnvironmentOption } from "../components/BranchToolbar.logic";
11
+import {
12
+ deriveLogicalProjectKeyFromSettings,
13
+ selectProjectGroupingSettings,
14
+} from "../logicalProject";
15
+import { useProjects } from "../state/entities";
16
+import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
17
+import { useClientSettings } from "./useSettings";
18
+
19
+/**
20
+ * The environments a project (or a scratch draft) can move between. It reads only the
21
+ * environment, project and grouping inputs, so the list keeps its identity while the thread
22
+ * streams and the chat chrome it feeds can skip those renders.
23
+ */
24
+export function useLogicalProjectEnvironments(
25
+ activeProject: EnvironmentProject | null,
26
+ scratchDraft: boolean,
27
+): readonly EnvironmentOption[] {
28
+ const { environments } = useEnvironments();
29
+ const allProjects = useProjects();
30
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
31
+ const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
32
+
33
+ if (!activeProject) return [];
34
+ const environmentById = new Map(
35
+ environments.map((environment) => [environment.environmentId, environment]),
36
+ );
37
+ const envs: EnvironmentOption[] = [];
38
+ const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
39
+ const environment = environmentById.get(environmentId) ?? null;
40
+ envs.push({
41
+ environmentId,
42
+ projectId,
43
+ label: environment?.label ?? environmentId,
44
+ isPrimary: environmentId === primaryEnvironmentId,
45
+ machine: resolveEnvironmentMachineKind(environment?.serverConfig ?? null),
46
+ });
47
+ };
48
+ if (scratchDraft) {
49
+ for (const environment of environments) {
50
+ const scratchRoot = availableScratchWorkspaceRoot(
51
+ environment.connection.phase,
52
+ environment.serverConfig,
53
+ );
54
+ if (scratchRoot === null && environment.environmentId !== activeProject.environmentId)
55
+ continue;
56
+ const scratchProject =
57
+ environment.environmentId === activeProject.environmentId
58
+ ? activeProject
59
+ : allProjects.find(
60
+ (p) =>
61
+ p.environmentId === environment.environmentId && isScratchProject(p, scratchRoot),
62
+ );
63
+ pushEnvironment(environment.environmentId, scratchProject?.id ?? null);
64
+ }
65
+ } else {
66
+ const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
67
+ const seen = new Set<string>();
68
+ for (const p of allProjects) {
69
+ if (seen.has(p.environmentId)) continue;
70
+ if (deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) !== logicalKey) continue;
71
+ seen.add(p.environmentId);
72
+ pushEnvironment(p.environmentId, p.id);
73
+ }
74
+ }
75
+ envs.sort((a, b) => {
76
+ if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;
77
+ return a.label.localeCompare(b.label);
78
+ });
79
+ return envs;
80
+}
apps/web/src/state/entities.ts
+7
@@ -132,6 +132,13 @@ export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadSh
132
);
133
}
134
135
+/** The shell without its streaming timestamps; see quietThreadShellAtom. */
136
+export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
137
+ return useAtomValue(
138
+ ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
139
+ );
140
+}
141
+
142
export function useChildThreadInputs(ref: ScopedThreadRef | null) {
143
return useAtomValue(
144
ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
packages/client-runtime/src/state/threadShell.test.ts
+51
@@ -5,7 +5,9 @@ import {
5
RuntimeRequestId,
6
ThreadId,
7
type OrchestrationV2ShellSnapshot,
8
+ type OrchestrationV2ThreadShell,
9
} from "@t3tools/contracts";
10
+import * as DateTime from "effect/DateTime";
11
import * as Option from "effect/Option";
12
import { Atom, AtomRegistry } from "effect/reactivity";
13
import { describe, expect, it } from "vite-plus/test";
@@ -332,4 +334,53 @@ describe("v2 thread shell lists", () => {
334
harness.registry.dispose();
335
}
336
});
337
+
338
+ it("keeps the quiet shell through streaming ticks and follows every change once the run stops", () => {
339
+ const harness = makeHarness();
340
+ const runId = RunId.make("streaming-run");
341
+ const running: OrchestrationV2ThreadShell = {
342
+ ...v2ThreadShell,
343
+ latestRunId: runId,
344
+ activeRunId: runId,
345
+ status: "running",
346
+ itemCount: 1,
347
+ visibleItemCount: 1,
348
+ };
349
+ const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
350
+ harness.registry.set(harness.snapshotAtom(environmentId), {
351
+ ...v2ShellSnapshot,
352
+ snapshotSequence: sequence,
353
+ threads: [thread],
354
+ });
355
+ const at = (seconds: number) => DateTime.add(v2Now, { seconds });
356
+ setThread(running, 1);
357
+ const ref = { environmentId, threadId: v2ThreadShell.id };
358
+ const quietAtom = harness.threads.quietThreadShellAtom(ref);
359
+ const dispose = harness.registry.mount(quietAtom);
360
+ try {
361
+ const first = harness.registry.get(quietAtom);
362
+ setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2);
363
+ expect(harness.registry.get(quietAtom)).toBe(first);
364
+ expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4);
365
+
366
+ setThread({ ...running, updatedAt: at(2), itemCount: 5, title: "Renamed" }, 3);
367
+ const renamed = harness.registry.get(quietAtom);
368
+ expect(renamed?.title).toBe("Renamed");
369
+
370
+ const stopped: OrchestrationV2ThreadShell = {
371
+ ...running,
372
+ activeRunId: null,
373
+ status: "completed",
374
+ };
375
+ setThread({ ...stopped, title: "Renamed", updatedAt: at(3) }, 4);
376
+ const completed = harness.registry.get(quietAtom);
377
+ expect(completed).not.toBe(renamed);
378
+ setThread({ ...stopped, title: "Renamed", updatedAt: at(4) }, 5);
379
+ expect(harness.registry.get(quietAtom)?.updatedAt).toBe(DateTime.formatIso(at(4)));
380
+ expect(harness.registry.get(quietAtom)).not.toBe(completed);
381
+ } finally {
382
+ dispose();
383
+ harness.registry.dispose();
384
+ }
385
+ });
386
});
packages/client-runtime/src/state/threadShell.ts
+54
-3
@@ -1,17 +1,17 @@
1
import type {
2
EnvironmentId,
3
OrchestrationV2ShellSnapshot,
4
- OrchestrationV2ThreadShell,
4
ProjectId,
5
ScopedProjectRef,
6
ScopedThreadRef,
7
ThreadId,
8
} from "@t3tools/contracts";
10
-import { isProviderNativeSubagentThread } from "@t3tools/contracts";
9
+import { isProviderNativeSubagentThread, OrchestrationV2ThreadShell } from "@t3tools/contracts";
10
+import * as Schema from "effect/Schema";
11
import { Atom } from "effect/reactivity";
12
13
import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
14
-import { presentThreadShell } from "./models.ts";
14
+import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
15
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
16
import {
17
arrayElementsEqual,
@@ -93,6 +93,41 @@ export function childThreadInputsTitle(
93
: `${children.length} subagents need ${need}`;
94
}
95
96
+const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
97
+
98
+// While a run streams, the server bumps the shell's timestamps, item counts and
99
+// latest message several times a second. Only the zero crossing of the counts
100
+// says anything (whether the thread has started). Once the run stops every
101
+// field counts again, so snooze wakes and failure times read the current value.
102
+function sameApartFromStreaming(
103
+ previous: EnvironmentThreadShell,
104
+ next: EnvironmentThreadShell,
105
+): boolean {
106
+ if (
107
+ previous.environmentId !== next.environmentId ||
108
+ previous.pendingSubagentRequest !== next.pendingSubagentRequest ||
109
+ !threadRuntimeIsActive(next.runtime)
110
+ ) {
111
+ return false;
112
+ }
113
+ const before = previous.source;
114
+ const after = next.source;
115
+ return (
116
+ before.itemCount > 0 === after.itemCount > 0 &&
117
+ before.visibleItemCount > 0 === after.visibleItemCount > 0 &&
118
+ sameWireThreadShell(
119
+ {
120
+ ...before,
121
+ updatedAt: after.updatedAt,
122
+ itemCount: after.itemCount,
123
+ visibleItemCount: after.visibleItemCount,
124
+ latestVisibleMessage: after.latestVisibleMessage,
125
+ },
126
+ after,
127
+ )
128
+ );
129
+}
130
+
131
export function createEnvironmentThreadShellAtoms(input: {
132
readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
133
readonly snapshotAtom: (
@@ -229,6 +264,21 @@ export function createEnvironmentThreadShellAtoms(input: {
264
}).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
265
});
266
267
+ // Keeps the previous shell while only streaming ticks changed. During a run,
268
+ // its timestamps, item counts and latest message are as of the last kept
269
+ // change; anything that needs them current reads threadShellAtom.
270
+ const quietThreadShellAtomFamily = Atom.family((key: string) => {
271
+ let previous: EnvironmentThreadShell | null = null;
272
+ return Atom.make((get) => {
273
+ const next = get(threadShellAtomFamily(key));
274
+ if (previous !== null && next !== null && sameApartFromStreaming(previous, next)) {
275
+ return previous;
276
+ }
277
+ previous = next;
278
+ return next;
279
+ }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`));
280
+ });
281
+
282
// Child approvals and questions are hidden with their sidebar rows. Read their
283
// shell summaries, without subscribing to every child transcript.
284
const childThreadInputsAtomFamily = Atom.family((key: string) => {
@@ -365,6 +415,7 @@ export function createEnvironmentThreadShellAtoms(input: {
415
threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
416
threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
417
threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
418
+ quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
419
childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
420
};
421
}