Skip to content
TypeScript

perf(web): the open thread's chat chrome no longer re-renders on every streaming tick (#20860)

Julius Marminge4b1024dafe47
diff --git a/apps/web/src/browserFaviconStore.test.ts b/apps/web/src/browserFaviconStore.test.ts
index 8aef763ddd4..1f2bc2bd7c0 100644
--- a/apps/web/src/browserFaviconStore.test.ts
+++ b/apps/web/src/browserFaviconStore.test.ts
@@ -2,7 +2,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
-vi.mock("~/state/entities", () => ({ useThreadShell: () => null }));
+vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => null }));
vi.mock("~/state/session", () => ({ usePreparedConnection: () => ({ _tag: "None" }) }));
import {
diff --git a/apps/web/src/browserFaviconStore.ts b/apps/web/src/browserFaviconStore.ts
index 4c332bfbd29..4051b4ebfbf 100644
--- a/apps/web/src/browserFaviconStore.ts
+++ b/apps/web/src/browserFaviconStore.ts
@@ -9,7 +9,7 @@ import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { normalizeHostname } from "~/browser/browserTargetResolver";
-import { useThreadShell } from "~/state/entities";
+import { useQuietThreadShell } from "~/state/entities";
import { usePreparedConnection } from "~/state/session";
import {
@@ -196,7 +196,7 @@ export function registerFaviconProjectForThread(
}
export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
- const shell = useThreadShell(threadRef);
+ const shell = useQuietThreadShell(threadRef);
const shellProjectId = shell?.projectId ?? null;
const environmentId = threadRef.environmentId;
const shellProjectRef = shellProjectId ? scopeProjectRef(environmentId, shellProjectId) : null;
diff --git a/apps/web/src/components/BranchToolbar.panel.test.tsx b/apps/web/src/components/BranchToolbar.panel.test.tsx
index 5a43c2131de..6b73fdc615e 100644
--- a/apps/web/src/components/BranchToolbar.panel.test.tsx
+++ b/apps/web/src/components/BranchToolbar.panel.test.tsx
@@ -23,7 +23,7 @@ vi.mock("../composerDraftStore", () => ({
select({ getDraftThreadByRef: () => null, setDraftThreadContext: vi.fn() }),
}));
vi.mock("../state/entities", () => ({
- useThreadShell: () => ({
+ useQuietThreadShell: () => ({
environmentId: "local",
projectId: "project",
worktreePath: state.worktreePath,
diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx
index 3a9f2e1b116..20bf1403e79 100644
--- a/apps/web/src/components/BranchToolbar.tsx
+++ b/apps/web/src/components/BranchToolbar.tsx
@@ -25,7 +25,7 @@ import {
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
-import { useProject, useThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
+import { useProject, useQuietThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
import {
type EnvMode,
type EnvironmentOption,
@@ -587,7 +587,7 @@ export const BranchToolbar = memo(function BranchToolbar({
const draftThread = useComposerDraftStore((store) =>
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
);
- const serverThread = useThreadShell(threadRef);
+ const serverThread = useQuietThreadShell(threadRef);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const activeProjectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx
index cd2f128eb24..4bf687fb5bf 100644
--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx
+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx
@@ -33,7 +33,7 @@ import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { readLocalApi } from "../localApi";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { usePaginatedBranches } from "../state/queries";
-import { useProject, useThreadShell } from "../state/entities";
+import { useProject, useQuietThreadShell } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { threadEnvironment } from "../state/threads";
@@ -130,7 +130,7 @@ export function BranchToolbarBranchSelector({
reportFailure: false,
});
const threadRef = scopeThreadRef(environmentId, threadId);
- const serverThread = useThreadShell(threadRef);
+ const serverThread = useQuietThreadShell(threadRef);
const serverSession = serverThread?.runtime ?? null;
const draftThread = useComposerDraftStore((store) =>
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 6710aedd7fa..10baf8ec91b 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -23,6 +23,7 @@ import {
rememberCheckoutIsRepo,
} from "./ChatView.logic";
import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
+import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
import { useScratchProject } from "../hooks/useScratchProject";
import { useStableCallback } from "../hooks/useStableCallback";
import { useProjectScriptEditing } from "./chat/useProjectScriptEditing";
@@ -65,7 +66,6 @@ import {
type MessageId,
type ModelSelection,
type ProjectScript,
- type ProjectId,
type PreviewAnnotationPayload,
ProviderInstanceId,
type ServerProvider,
@@ -76,7 +76,6 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ProviderInteractionMode,
ProviderDriverKind,
- resolveEnvironmentMachineKind,
resolveProjectProviderInstanceEnabled,
RuntimeMode,
} from "@t3tools/contracts";
@@ -376,6 +375,7 @@ import {
useThreadProjection,
useThreadStatus,
useThreadHistory,
+ useQuietThreadShell,
useThreadShell,
useChildThreadInputs,
useThreadRefs,
@@ -419,10 +419,9 @@ import {
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview";
-import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel";
+import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel";
import { NoActiveThreadState } from "./NoActiveThreadState";
import {
- type EnvironmentOption,
resolveEffectiveEnvMode,
resolveLocalCheckoutBranchMismatch,
shouldShowComposerContextStrip,
@@ -1111,7 +1110,7 @@ export default function ChatView(props: ChatViewProps) {
? store.getDraftSession(draftId)
: null,
);
- const serverThread = useThreadShell(routeThreadRef);
+ const serverThread = useQuietThreadShell(routeThreadRef);
const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, {
shellExists: serverThread !== null,
waitForShell: draftThread !== null,
@@ -1176,13 +1175,6 @@ export default function ChatView(props: ChatViewProps) {
}
return ids;
})();
- const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
- const activeThreadLocalLastVisitedAt = useUiStateStore(
- (store) => store.threadLastVisitedAtById[routeThreadKey],
- );
- const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
- const lastDispatchedVisitRef = useRef<string | null>(null);
- const lastVisitDispatchAtRef = useRef(0);
const settings = useEnvironmentSettings(environmentId);
const clientSettingsHydrated = useClientSettingsHydrated();
const setStickyComposerModelSelection = useComposerDraftStore(
@@ -1495,7 +1487,7 @@ export default function ChatView(props: ChatViewProps) {
}
return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId);
})();
- const parentSubagentThread = useThreadShell(parentSubagentThreadRef);
+ const parentSubagentThread = useQuietThreadShell(parentSubagentThreadRef);
const parentThreadLink =
parentSubagentThreadRef === null
? null
@@ -1572,7 +1564,7 @@ export default function ChatView(props: ChatViewProps) {
container: workspaceLayoutElement,
widthStorageKey: `t3code:preview-panel-width:${activeThreadKey}`,
});
- const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
+ const activeThreadShell = useQuietThreadShell(isServerThread ? activeThreadRef : null);
const timelineThreadError =
serverRuntime?.status === "failed" &&
serverRuntime.lastErrorClass === "usage_limit" &&
@@ -2014,60 +2006,17 @@ export default function ChatView(props: ChatViewProps) {
const handleDisconnectActiveEnvironmentStable = useStableCallback(
handleDisconnectActiveEnvironment,
);
- const { scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
+ const { openScratchProject } = useScratchProject();
const activeProjectIsScratch =
activeProject !== null &&
isScratchProject(
activeProject,
environmentById.get(activeProject.environmentId)?.serverConfig?.scratchWorkspaceRoot ?? null,
);
- const logicalProjectEnvironments = (() => {
- if (!activeProject) return [];
- const envs: EnvironmentOption[] = [];
- const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
- const environment = environmentById.get(environmentId) ?? null;
- envs.push({
- environmentId,
- projectId,
- label: environment?.label ?? environmentId,
- isPrimary: environmentId === primaryEnvironmentId,
- machine: resolveEnvironmentMachineKind(environment?.serverConfig ?? null),
- });
- };
- if (activeProjectIsScratch && draftId) {
- for (const environment of environments) {
- const scratchRoot = scratchWorkspaceRootFor(environment.environmentId);
- if (scratchRoot === null && environment.environmentId !== activeProject.environmentId)
- continue;
- const scratchProject =
- environment.environmentId === activeProject.environmentId
- ? activeProject
- : allProjects.find(
- (p) =>
- p.environmentId === environment.environmentId && isScratchProject(p, scratchRoot),
- );
- pushEnvironment(environment.environmentId, scratchProject?.id ?? null);
- }
- } else {
- const logicalKey = deriveLogicalProjectKeyFromSettings(
- activeProject,
- projectGroupingSettings,
- );
- const seen = new Set<string>();
- for (const p of allProjects) {
- if (seen.has(p.environmentId)) continue;
- if (deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) !== logicalKey)
- continue;
- seen.add(p.environmentId);
- pushEnvironment(p.environmentId, p.id);
- }
- }
- envs.sort((a, b) => {
- if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;
- return a.label.localeCompare(b.label);
- });
- return envs;
- })();
+ const logicalProjectEnvironments = useLogicalProjectEnvironments(
+ activeProject,
+ activeProjectIsScratch && draftId !== null,
+ );
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
const canAutoBalanceEnvironments = hasMultipleEnvironments && !activeProjectIsScratch;
const activeEnvironmentOption =
@@ -2163,63 +2112,6 @@ export default function ChatView(props: ChatViewProps) {
};
const handlePreparedPullRequestThreadStable = useStableCallback(handlePreparedPullRequestThread);
- useEffect(() => {
- if (!serverThread?.id) return;
- const threadUpdatedAt = Date.parse(serverThread.updatedAt);
- if (Number.isNaN(threadUpdatedAt)) return;
- const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
- serverThread.lastVisitedAt,
- activeThreadLocalLastVisitedAt,
- );
- const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
- if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
-
- if (serverThread.lastVisitedAt !== undefined) {
- // Dedupe per watermark — the effect re-runs before the command's echo
- // lands. The dedupe also keeps a mark-unread on the open thread sticky:
- // the rewind leaves updatedAt untouched, so the already-dispatched key
- // skips a fresh visit until new activity lands or the thread is reopened.
- const dispatchKey = `${routeThreadKey}:${serverThread.updatedAt}`;
- if (lastDispatchedVisitRef.current === dispatchKey) return;
- const dispatch = () => {
- lastDispatchedVisitRef.current = dispatchKey;
- lastVisitDispatchAtRef.current = Date.now();
- void visitThreadMutation({
- environmentId: serverThread.environmentId,
- input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
- });
- };
- const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
- ? Date.parse(serverThread.latestRun.completedAt)
- : NaN;
- const hasUnseenCompletion =
- !Number.isNaN(latestRunCompletedAtMs) &&
- (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
- const elapsed = Date.now() - lastVisitDispatchAtRef.current;
- if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
- dispatch();
- return;
- }
- const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
- return () => clearTimeout(timer);
- }
-
- markThreadVisited(
- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
- serverThread.updatedAt,
- );
- }, [
- activeThreadLocalLastVisitedAt,
- markThreadVisited,
- routeThreadKey,
- serverThread?.environmentId,
- serverThread?.id,
- serverThread?.lastVisitedAt,
- serverThread?.latestRun?.completedAt,
- serverThread?.updatedAt,
- visitThreadMutation,
- ]);
-
const serverConfig = activeThread
? (activeEnvironment?.serverConfig ?? null)
: (primaryEnvironment?.serverConfig ?? null);
@@ -7812,55 +7704,6 @@ export default function ChatView(props: ChatViewProps) {
}}
/>
) : null;
- const threadDetailsPanelProps: ThreadDetailsPanelProps = {
- anchor: threadPanelPopoverAnchorRef,
- handle: threadPanelPopoverHandle,
- onPresentationChange: setThreadPanelPresentation,
- forceNewWorktree: multipleModelSelections !== null,
- environmentId: activeThread.environmentId,
- threadId: activeThread.id,
- ...(draftId ? { draftId } : {}),
- activeProjectName: activeProject?.title,
- activeProjectScripts: activeProject ? activeProjectScripts : undefined,
- preferredScriptId: activeProject
- ? (lastInvokedScriptByProjectId[activeProject.id] ?? null)
- : null,
- keybindings,
- availableEditors,
- showOpenInPicker,
- gitCwd,
- isGitRepo,
- envLocked,
- availableEnvironments: logicalProjectEnvironments,
- autoEnvironmentLabel,
- onAutoEnvironment:
- draftId &&
- !envLocked &&
- canAutoBalanceEnvironments &&
- loadBalancingSettings.loadBalancingEnabled
- ? onAutoEnvironmentStable
- : undefined,
- onEnvironmentChange: onEnvironmentChangeStable,
- onEnvModeChange: onEnvModeChangeStable,
- envMode,
- ...(canOverrideServerThreadEnvMode
- ? {
- activeThreadBranchOverride: activeThreadBranch,
- onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
- }
- : {}),
- startFromOrigin,
- onStartFromOriginChange,
- ...(canCheckoutPullRequestIntoThread
- ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
- : {}),
- onComposerFocusRequest: scheduleComposerFocusStable,
- ...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanelStable } : {}),
- onRunProjectScript: runProjectScriptStable,
- onAddProjectScript: saveProjectScriptStable,
- onUpdateProjectScript: updateProjectScriptStable,
- onDeleteProjectScript: deleteProjectScriptStable,
- };
const panelToggleControlProps = {
terminalAvailable: activeProject !== null,
terminalOpen: terminalUiState.terminalOpen,
@@ -8530,7 +8373,58 @@ export default function ChatView(props: ChatViewProps) {
onConfirm={handleSwitchCheckoutToThreadStable}
/>
- <ThreadDetailsPanel {...threadDetailsPanelProps} />
+ <ThreadDetailsPanel
+ anchor={threadPanelPopoverAnchorRef}
+ handle={threadPanelPopoverHandle}
+ onPresentationChange={setThreadPanelPresentation}
+ forceNewWorktree={multipleModelSelections !== null}
+ environmentId={activeThread.environmentId}
+ threadId={activeThread.id}
+ {...(draftId ? { draftId } : {})}
+ activeProjectName={activeProject?.title}
+ activeProjectScripts={activeProject ? activeProjectScripts : undefined}
+ preferredScriptId={
+ activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
+ }
+ keybindings={keybindings}
+ availableEditors={availableEditors}
+ showOpenInPicker={showOpenInPicker}
+ gitCwd={gitCwd}
+ isGitRepo={isGitRepo}
+ envLocked={envLocked}
+ availableEnvironments={logicalProjectEnvironments}
+ autoEnvironmentLabel={autoEnvironmentLabel}
+ onAutoEnvironment={
+ draftId &&
+ !envLocked &&
+ canAutoBalanceEnvironments &&
+ loadBalancingSettings.loadBalancingEnabled
+ ? onAutoEnvironmentStable
+ : undefined
+ }
+ onEnvironmentChange={onEnvironmentChangeStable}
+ onEnvModeChange={onEnvModeChangeStable}
+ envMode={envMode}
+ {...(canOverrideServerThreadEnvMode
+ ? {
+ activeThreadBranchOverride: activeThreadBranch,
+ onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
+ }
+ : {})}
+ startFromOrigin={startFromOrigin}
+ onStartFromOriginChange={onStartFromOriginChange}
+ {...(canCheckoutPullRequestIntoThread
+ ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
+ : {})}
+ onComposerFocusRequest={scheduleComposerFocusStable}
+ {...(isServerThread && isGitRepo
+ ? { onOpenChanges: openChangesFromThreadPanelStable }
+ : {})}
+ onRunProjectScript={runProjectScriptStable}
+ onAddProjectScript={saveProjectScriptStable}
+ onUpdateProjectScript={updateProjectScriptStable}
+ onDeleteProjectScript={deleteProjectScriptStable}
+ />
<PullRequestThreadDialogHost
threadKey={activeThreadKey}
@@ -8667,6 +8561,7 @@ export default function ChatView(props: ChatViewProps) {
<RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />
<LinkPullRequestDialogHost />
+ <ThreadVisitWatermark threadRef={routeThreadRef} />
<ExpandedImageDialogHost threadKey={routeThreadKey} />
</div>
);
@@ -8685,3 +8580,76 @@ function PreviewSessionSync(props: { readonly threadRef: ScopedThreadRef }) {
usePreviewSession(props.threadRef);
return null;
}
+
+// The visit watermark is the one part of the chat view that follows the
+// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
+// ChatView read the quiet shell.
+function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
+ const serverThread = useThreadShell(props.threadRef);
+ const threadKey = scopedThreadKey(props.threadRef);
+ const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
+ const activeThreadLocalLastVisitedAt = useUiStateStore(
+ (store) => store.threadLastVisitedAtById[threadKey],
+ );
+ const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
+ const lastDispatchedVisitRef = useRef<string | null>(null);
+ const lastVisitDispatchAtRef = useRef(0);
+
+ useEffect(() => {
+ if (!serverThread?.id) return;
+ const threadUpdatedAt = Date.parse(serverThread.updatedAt);
+ if (Number.isNaN(threadUpdatedAt)) return;
+ const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
+ serverThread.lastVisitedAt,
+ activeThreadLocalLastVisitedAt,
+ );
+ const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
+ if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
+
+ if (serverThread.lastVisitedAt !== undefined) {
+ // Dedupe per watermark — the effect re-runs before the command's echo
+ // lands. The dedupe also keeps a mark-unread on the open thread sticky:
+ // the rewind leaves updatedAt untouched, so the already-dispatched key
+ // skips a fresh visit until new activity lands or the thread is reopened.
+ const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
+ if (lastDispatchedVisitRef.current === dispatchKey) return;
+ const dispatch = () => {
+ lastDispatchedVisitRef.current = dispatchKey;
+ lastVisitDispatchAtRef.current = Date.now();
+ void visitThreadMutation({
+ environmentId: serverThread.environmentId,
+ input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
+ });
+ };
+ const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
+ ? Date.parse(serverThread.latestRun.completedAt)
+ : NaN;
+ const hasUnseenCompletion =
+ !Number.isNaN(latestRunCompletedAtMs) &&
+ (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
+ const elapsed = Date.now() - lastVisitDispatchAtRef.current;
+ if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
+ dispatch();
+ return;
+ }
+ const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
+ return () => clearTimeout(timer);
+ }
+
+ markThreadVisited(
+ scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
+ serverThread.updatedAt,
+ );
+ }, [
+ activeThreadLocalLastVisitedAt,
+ markThreadVisited,
+ threadKey,
+ serverThread?.environmentId,
+ serverThread?.id,
+ serverThread?.lastVisitedAt,
+ serverThread?.latestRun?.completedAt,
+ serverThread?.updatedAt,
+ visitThreadMutation,
+ ]);
+ return null;
+}
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx
index 747b3c8913a..085acf201a5 100644
--- a/apps/web/src/components/DiffPanel.tsx
+++ b/apps/web/src/components/DiffPanel.tsx
@@ -45,7 +45,7 @@ import {
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
-import { useProject, useThreadCheckpointSummaries, useThreadShell } from "../state/entities";
+import { useProject, useThreadCheckpointSummaries, useQuietThreadShell } from "../state/entities";
import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
@@ -222,7 +222,7 @@ export default function DiffPanel({
const routeThreadRef = useThreadRouteRef();
const activeThreadId = routeThreadRef?.threadId ?? null;
- const activeThread = useThreadShell(routeThreadRef);
+ const activeThread = useQuietThreadShell(routeThreadRef);
const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null);
const { canReadFiles } = fileAccess;
const activeProjectId = activeThread?.projectId ?? null;
diff --git a/apps/web/src/components/GitActionsControl.lifecycle.test.ts b/apps/web/src/components/GitActionsControl.lifecycle.test.ts
index 84d5b1b4271..1c8b014bb2c 100644
--- a/apps/web/src/components/GitActionsControl.lifecycle.test.ts
+++ b/apps/web/src/components/GitActionsControl.lifecycle.test.ts
@@ -18,7 +18,7 @@ vi.mock("@effect/atom-react", () => ({
}));
vi.mock("~/state/entities", () => ({
useThreadProjection: () => null,
- useThreadShell: (ref: { threadId: string }) => ({ branch: "main", id: ref.threadId }),
+ useQuietThreadShell: (ref: { threadId: string }) => ({ branch: "main", id: ref.threadId }),
}));
vi.mock("~/state/session", () => ({
useEnvironmentScope: (environmentId: unknown, scope: string) =>
diff --git a/apps/web/src/components/GitActionsControl.test.ts b/apps/web/src/components/GitActionsControl.test.ts
index 9da21b4de1a..964a4d45096 100644
--- a/apps/web/src/components/GitActionsControl.test.ts
+++ b/apps/web/src/components/GitActionsControl.test.ts
@@ -27,7 +27,7 @@ vi.mock("@effect/atom-react", () => ({
vi.mock("~/state/entities", () => ({
useThreadProjection: (ref: unknown) =>
ref === null || state.detail === null ? null : { projection: { thread: state.detail } },
- useThreadShell: () => state.shell,
+ useQuietThreadShell: () => state.shell,
}));
vi.mock("~/state/session", () => ({
useEnvironmentScope: (environmentId: unknown, scope: string) =>
diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx
index 04bd3a61cb3..ffea29c9bf6 100644
--- a/apps/web/src/components/GitActionsControl.tsx
+++ b/apps/web/src/components/GitActionsControl.tsx
@@ -97,7 +97,7 @@ import {
useVcsInitAction,
useVcsPullAction,
} from "~/lib/sourceControlActions";
-import { useThreadProjection, useThreadShell } from "~/state/entities";
+import { useThreadProjection, useQuietThreadShell } from "~/state/entities";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useEnvironmentQuery } from "~/state/query";
import { serverEnvironment } from "~/state/server";
@@ -982,7 +982,7 @@ export default function GitActionsControl({
serverConfig?.availableEditors ?? [],
);
const threadToastData = activeThreadRef ? { threadRef: activeThreadRef } : undefined;
- const activeServerThreadShell = useThreadShell(activeThreadRef);
+ const activeServerThreadShell = useQuietThreadShell(activeThreadRef);
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
const activeDraftThread = useComposerDraftStore((store) =>
draftId
diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx
index bdacfc53225..44b40f83e75 100644
--- a/apps/web/src/components/PersistentThreadTerminals.tsx
+++ b/apps/web/src/components/PersistentThreadTerminals.tsx
@@ -18,7 +18,7 @@ import {
useRightPanelStore,
type RightPanelSurface,
} from "../rightPanelStore";
-import { useProject, useThreadShell } from "../state/entities";
+import { useProject, useQuietThreadShell } from "../state/entities";
import { useEnvironmentScope } from "../state/session";
import { useKnownTerminalSessions } from "../state/terminalSessions";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
@@ -105,7 +105,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
}: PersistentThreadTerminalDrawerProps) {
const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
const terminalActions = useThreadTerminalActions(threadRef);
- const serverThread = useThreadShell(threadRef);
+ const serverThread = useQuietThreadShell(threadRef);
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const projectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
@@ -330,7 +330,7 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
newShortcutLabel,
closeShortcutLabel,
}: PersistentThreadTerminalPanelProps) {
- const serverThread = useThreadShell(threadRef);
+ const serverThread = useQuietThreadShell(threadRef);
const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));
const projectRef = serverThread
? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx
index bd77da3816e..12fbd0d5503 100644
--- a/apps/web/src/components/ThreadRouteView.tsx
+++ b/apps/web/src/components/ThreadRouteView.tsx
@@ -14,7 +14,7 @@ import {
useComposerDraftStore,
} from "../composerDraftStore";
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
-import { useEnvironmentThreadRefs, useThreadRefs, useThreadShell } from "../state/entities";
+import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
import { useEnvironmentShellStatus } from "../state/shell";
import {
buildThreadRouteParams,
@@ -44,7 +44,7 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
: null;
const serverThreadRef: ScopedThreadRef | null =
target.kind === "server" ? target.threadRef : (draftSession?.promotedTo ?? inferredThreadRef);
- const serverThread = useThreadShell(serverThreadRef);
+ const serverThread = useQuietThreadShell(serverThreadRef);
const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
target.kind === "draft" ? serverThreadRef : null,
);
diff --git a/apps/web/src/components/terminal/useThreadTerminalActions.ts b/apps/web/src/components/terminal/useThreadTerminalActions.ts
index 2b4b922a184..10d3a8e9e9b 100644
--- a/apps/web/src/components/terminal/useThreadTerminalActions.ts
+++ b/apps/web/src/components/terminal/useThreadTerminalActions.ts
@@ -11,7 +11,7 @@ import { useComposerDraftStore } from "../../composerDraftStore";
import { useStableCallback } from "../../hooks/useStableCallback";
import { randomUUID } from "~/lib/utils";
import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
-import { useProject, useThreadShell } from "../../state/entities";
+import { useProject, useQuietThreadShell } from "../../state/entities";
import { readEnvironmentScope } from "../../state/session";
import { terminalEnvironment } from "../../state/terminal";
import { useKnownTerminalSessions } from "../../state/terminalSessions";
@@ -34,7 +34,7 @@ export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {
const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open");
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close");
- const serverThread = useThreadShell(threadRef);
+ const serverThread = useQuietThreadShell(threadRef);
const draftThread = useComposerDraftStore((store) =>
threadRef ? store.getDraftThreadByRef(threadRef) : null,
);
diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts
index ef1b53ea86e..cfb98fc83bd 100644
--- a/apps/web/src/hooks/useHandleNewThread.ts
+++ b/apps/web/src/hooks/useHandleNewThread.ts
@@ -27,7 +27,7 @@ import {
readThreadShell,
readThreadShells,
useProjects,
- useThreadShell,
+ useQuietThreadShell,
} from "../state/entities";
import {
hasExplicitComposerModelSelection,
@@ -388,7 +388,7 @@ export function useHandleNewThread() {
const routeTarget = useThreadRouteTarget();
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const routeDraftId = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
- const activeThread = useThreadShell(routeThreadRef);
+ const activeThread = useQuietThreadShell(routeThreadRef);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const activeDraftThread = useComposerDraftStore(() =>
routeTarget
diff --git a/apps/web/src/hooks/useLogicalProjectEnvironments.ts b/apps/web/src/hooks/useLogicalProjectEnvironments.ts
new file mode 100644
index 00000000000..9c94a43148f
--- /dev/null
+++ b/apps/web/src/hooks/useLogicalProjectEnvironments.ts
@@ -0,0 +1,80 @@
+import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
+import { isScratchProject } from "@t3tools/client-runtime/state/projects";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+import {
+ type EnvironmentId,
+ type ProjectId,
+ resolveEnvironmentMachineKind,
+} from "@t3tools/contracts";
+
+import type { EnvironmentOption } from "../components/BranchToolbar.logic";
+import {
+ deriveLogicalProjectKeyFromSettings,
+ selectProjectGroupingSettings,
+} from "../logicalProject";
+import { useProjects } from "../state/entities";
+import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
+import { useClientSettings } from "./useSettings";
+
+/**
+ * The environments a project (or a scratch draft) can move between. It reads only the
+ * environment, project and grouping inputs, so the list keeps its identity while the thread
+ * streams and the chat chrome it feeds can skip those renders.
+ */
+export function useLogicalProjectEnvironments(
+ activeProject: EnvironmentProject | null,
+ scratchDraft: boolean,
+): readonly EnvironmentOption[] {
+ const { environments } = useEnvironments();
+ const allProjects = useProjects();
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
+
+ if (!activeProject) return [];
+ const environmentById = new Map(
+ environments.map((environment) => [environment.environmentId, environment]),
+ );
+ const envs: EnvironmentOption[] = [];
+ const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
+ const environment = environmentById.get(environmentId) ?? null;
+ envs.push({
+ environmentId,
+ projectId,
+ label: environment?.label ?? environmentId,
+ isPrimary: environmentId === primaryEnvironmentId,
+ machine: resolveEnvironmentMachineKind(environment?.serverConfig ?? null),
+ });
+ };
+ if (scratchDraft) {
+ for (const environment of environments) {
+ const scratchRoot = availableScratchWorkspaceRoot(
+ environment.connection.phase,
+ environment.serverConfig,
+ );
+ if (scratchRoot === null && environment.environmentId !== activeProject.environmentId)
+ continue;
+ const scratchProject =
+ environment.environmentId === activeProject.environmentId
+ ? activeProject
+ : allProjects.find(
+ (p) =>
+ p.environmentId === environment.environmentId && isScratchProject(p, scratchRoot),
+ );
+ pushEnvironment(environment.environmentId, scratchProject?.id ?? null);
+ }
+ } else {
+ const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
+ const seen = new Set<string>();
+ for (const p of allProjects) {
+ if (seen.has(p.environmentId)) continue;
+ if (deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) !== logicalKey) continue;
+ seen.add(p.environmentId);
+ pushEnvironment(p.environmentId, p.id);
+ }
+ }
+ envs.sort((a, b) => {
+ if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;
+ return a.label.localeCompare(b.label);
+ });
+ return envs;
+}
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 82de895d8ed..b456752cab0 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -132,6 +132,13 @@ export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadSh
);
}
+/** The shell without its streaming timestamps; see quietThreadShellAtom. */
+export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
+ return useAtomValue(
+ ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
+ );
+}
+
export function useChildThreadInputs(ref: ScopedThreadRef | null) {
return useAtomValue(
ref === null ? EMPTY_THREAD_SHELLS_ATOM : environmentThreadShells.childThreadInputsAtom(ref),
diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts
index b32169830f0..413a5c2b3f5 100644
--- a/packages/client-runtime/src/state/threadShell.test.ts
+++ b/packages/client-runtime/src/state/threadShell.test.ts
@@ -5,7 +5,9 @@ import {
RuntimeRequestId,
ThreadId,
type OrchestrationV2ShellSnapshot,
+ type OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import { Atom, AtomRegistry } from "effect/reactivity";
import { describe, expect, it } from "vite-plus/test";
@@ -332,4 +334,53 @@ describe("v2 thread shell lists", () => {
harness.registry.dispose();
}
});
+
+ it("keeps the quiet shell through streaming ticks and follows every change once the run stops", () => {
+ const harness = makeHarness();
+ const runId = RunId.make("streaming-run");
+ const running: OrchestrationV2ThreadShell = {
+ ...v2ThreadShell,
+ latestRunId: runId,
+ activeRunId: runId,
+ status: "running",
+ itemCount: 1,
+ visibleItemCount: 1,
+ };
+ const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
+ harness.registry.set(harness.snapshotAtom(environmentId), {
+ ...v2ShellSnapshot,
+ snapshotSequence: sequence,
+ threads: [thread],
+ });
+ const at = (seconds: number) => DateTime.add(v2Now, { seconds });
+ setThread(running, 1);
+ const ref = { environmentId, threadId: v2ThreadShell.id };
+ const quietAtom = harness.threads.quietThreadShellAtom(ref);
+ const dispose = harness.registry.mount(quietAtom);
+ try {
+ const first = harness.registry.get(quietAtom);
+ setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2);
+ expect(harness.registry.get(quietAtom)).toBe(first);
+ expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4);
+
+ setThread({ ...running, updatedAt: at(2), itemCount: 5, title: "Renamed" }, 3);
+ const renamed = harness.registry.get(quietAtom);
+ expect(renamed?.title).toBe("Renamed");
+
+ const stopped: OrchestrationV2ThreadShell = {
+ ...running,
+ activeRunId: null,
+ status: "completed",
+ };
+ setThread({ ...stopped, title: "Renamed", updatedAt: at(3) }, 4);
+ const completed = harness.registry.get(quietAtom);
+ expect(completed).not.toBe(renamed);
+ setThread({ ...stopped, title: "Renamed", updatedAt: at(4) }, 5);
+ expect(harness.registry.get(quietAtom)?.updatedAt).toBe(DateTime.formatIso(at(4)));
+ expect(harness.registry.get(quietAtom)).not.toBe(completed);
+ } finally {
+ dispose();
+ harness.registry.dispose();
+ }
+ });
});
diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts
index 1710eb38bfb..a462638144b 100644
--- a/packages/client-runtime/src/state/threadShell.ts
+++ b/packages/client-runtime/src/state/threadShell.ts
@@ -1,17 +1,17 @@
import type {
EnvironmentId,
OrchestrationV2ShellSnapshot,
- OrchestrationV2ThreadShell,
ProjectId,
ScopedProjectRef,
ScopedThreadRef,
ThreadId,
} from "@t3tools/contracts";
-import { isProviderNativeSubagentThread } from "@t3tools/contracts";
+import { isProviderNativeSubagentThread, OrchestrationV2ThreadShell } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
import { Atom } from "effect/reactivity";
import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
-import { presentThreadShell } from "./models.ts";
+import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import {
arrayElementsEqual,
@@ -93,6 +93,41 @@ export function childThreadInputsTitle(
: `${children.length} subagents need ${need}`;
}
+const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
+
+// While a run streams, the server bumps the shell's timestamps, item counts and
+// latest message several times a second. Only the zero crossing of the counts
+// says anything (whether the thread has started). Once the run stops every
+// field counts again, so snooze wakes and failure times read the current value.
+function sameApartFromStreaming(
+ previous: EnvironmentThreadShell,
+ next: EnvironmentThreadShell,
+): boolean {
+ if (
+ previous.environmentId !== next.environmentId ||
+ previous.pendingSubagentRequest !== next.pendingSubagentRequest ||
+ !threadRuntimeIsActive(next.runtime)
+ ) {
+ return false;
+ }
+ const before = previous.source;
+ const after = next.source;
+ return (
+ before.itemCount > 0 === after.itemCount > 0 &&
+ before.visibleItemCount > 0 === after.visibleItemCount > 0 &&
+ sameWireThreadShell(
+ {
+ ...before,
+ updatedAt: after.updatedAt,
+ itemCount: after.itemCount,
+ visibleItemCount: after.visibleItemCount,
+ latestVisibleMessage: after.latestVisibleMessage,
+ },
+ after,
+ )
+ );
+}
+
export function createEnvironmentThreadShellAtoms(input: {
readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
readonly snapshotAtom: (
@@ -229,6 +264,21 @@ export function createEnvironmentThreadShellAtoms(input: {
}).pipe(Atom.withLabel(`environment-thread-shell:${key}`));
});
+ // Keeps the previous shell while only streaming ticks changed. During a run,
+ // its timestamps, item counts and latest message are as of the last kept
+ // change; anything that needs them current reads threadShellAtom.
+ const quietThreadShellAtomFamily = Atom.family((key: string) => {
+ let previous: EnvironmentThreadShell | null = null;
+ return Atom.make((get) => {
+ const next = get(threadShellAtomFamily(key));
+ if (previous !== null && next !== null && sameApartFromStreaming(previous, next)) {
+ return previous;
+ }
+ previous = next;
+ return next;
+ }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`));
+ });
+
// Child approvals and questions are hidden with their sidebar rows. Read their
// shell summaries, without subscribing to every child transcript.
const childThreadInputsAtomFamily = Atom.family((key: string) => {
@@ -365,6 +415,7 @@ export function createEnvironmentThreadShellAtoms(input: {
threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>
threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),
threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),
+ quietThreadShellAtom: (ref: ScopedThreadRef) => quietThreadShellAtomFamily(threadKey(ref)),
childThreadInputsAtom: (ref: ScopedThreadRef) => childThreadInputsAtomFamily(threadKey(ref)),
};
}