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

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

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

Synced Nov 23, 08:00 UTC

refactor(web): move worktree setup progress out of ChatView (#20316)

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

Julius Marminge committed Oct 16, 2026 at 17:39 UTC d3de2c17c0ce086aab482a219c89c1ed5d6f5cb4
3 files changed +228 -119
apps/web/src/components/ChatView.tsx
+36 -119
@@ -5,8 +5,6 @@ import {
5 resolveBackgroundDraftWorkspaceOptions,
6 resolveDraftHeroState,
7 shouldDockDraftHeroForSubmission,
8 - resolveVisibleWorktreeSetup,
9 - resolveWorktreeSetupProgress,
8 } from "./ChatView.logic";
9 import * as DateTime from "effect/DateTime";
10 import { restorePlanFollowUpComposer } from "./ChatView.logic";
@@ -37,6 +35,7 @@ import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
35 import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
36 import { feedbackBannerItem } from "./chat/ComposerFeedback";
37 import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
38 +import { useWorktreeSetup } from "./chat/useWorktreeSetup";
39 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
40 import * as Schema from "effect/Schema";
41 import {
@@ -71,7 +70,6 @@ import {
70 resolveEnvironmentMachineKind,
71 resolveProjectProviderInstanceEnabled,
72 RuntimeMode,
74 - type WorktreeSetupSnapshot,
73 } from "@t3tools/contracts";
74 import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
75 import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
@@ -389,7 +387,6 @@ import {
387 serverEnvironment,
388 } from "../state/server";
389 import { threadEnvironment } from "../state/threads";
392 -import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";
390 import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
391 import { vcsEnvironment } from "../state/vcs";
392 import { sourceControlEnvironment } from "../state/sourceControl";
@@ -421,7 +418,7 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
418 import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
419 import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
420 import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
424 -import { resolveTimelineIsAtEnd, worktreeSetupAgentStarted } from "./chat/MessagesTimeline.logic";
421 +import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";
422 import {
423 overlayComposerIsResting,
424 resolveComposerTimelineInset,
@@ -901,8 +898,12 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | n
898 return current.messageId === null ? current : { ...current, messageId: null };
899 }
900
904 -const retryingWorkspacePreparationRunIds = new Set<RunId>();
901 +// The factories below build functions ChatView calls during render, or hands
902 +// to ChatComposer, which can call them after an await. They live outside the
903 +// component so each closure keeps only its inputs, not a whole render scope
904 +// (see useStableCallback), while still acting on the render that made them.
905
906 +/** Records a thread error in local state, keyed by the route the making render saw. */
907 function makeThreadErrorSetter(input: {
908 readonly routeThreadRef: ScopedThreadRef;
909 readonly routeThreadKey: string;
@@ -1235,15 +1236,10 @@ export default function ChatView(props: ChatViewProps) {
1236 return () => revokeBlobPreviewUrl(src);
1237 }, [expandedImage]);
1238 const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
1238 - // Last live snapshot from the setup stream. The server drops a finished
1239 - // snapshot after a grace period and emits null; holding it here bridges the
1240 - // gap until the settled activity arrives on the thread projection.
1241 - const [worktreeSetupRef, setWorktreeSetupRef] = useState<{
1242 - environmentId: EnvironmentId;
1243 - threadId: ThreadId;
1244 - ownerKey: string;
1245 - } | null>(null);
1246 - const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);
1239 + // Set by "Work locally": the draft whose restored message should be resent
1240 + // once the cancelled dispatch has settled and the draft is in local mode.
1241 + // Keyed by draft id so a bootstrap rotating the thread id keeps it, while
1242 + // moving to another draft drops it without an effect.
1243 const [workLocallyResendDraftId, setWorkLocallyResendDraftId] = useState<DraftId | null>(null);
1244 useEffect(() => {
1245 if (workLocallyResendDraftId !== null && workLocallyResendDraftId !== draftId) {
@@ -3028,98 +3024,29 @@ export default function ChatView(props: ChatViewProps) {
3024 activeThreadKey,
3025 );
3026 const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey);
3031 - const worktreeSetupOwnerKey = draftId ?? routeThreadKey;
3032 - const worktreeSetupActive =
3033 - worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey;
3034 - const setupTarget = worktreeSetupActive ? worktreeSetupRef : routeThreadRef;
3035 - const worktreeSetupQuery = useEnvironmentQuery(
3036 - worktreeSetupActive ||
3037 - (activeThread?.id === routeThreadRef.threadId &&
3038 - (isLocallyPreparingWorktree || activeRunPreparing || activeThread.worktreePath !== null))
3039 - ? vcsEnvironment.worktreeSetup({
3040 - environmentId: setupTarget.environmentId,
3041 - input: { threadId: setupTarget.threadId },
3042 - })
3043 - : null,
3044 - );
3045 - const latestWorktreeSetup = worktreeSetupQuery.data;
3046 - useEffect(() => {
3047 - if (!latestWorktreeSetup) return;
3048 - setHeldWorktreeSetup((current) =>
3049 - current?.threadId === latestWorktreeSetup.threadId &&
3050 - current.sequence > latestWorktreeSetup.sequence
3051 - ? current
3052 - : latestWorktreeSetup,
3053 - );
3054 - }, [latestWorktreeSetup]);
3055 - useEffect(() => {
3056 - setHeldWorktreeSetup(null);
3057 - }, [routeThreadKey]);
3058 - const { snapshot: liveWorktreeSetup, isPreparingWorktree } = resolveWorktreeSetupProgress({
3059 - threadId: setupTarget.threadId,
3027 + const {
3028 + worktreeSetup,
3029 + isPreparingWorktree,
3030 + blocksSend: worktreeSetupBlocksSend,
3031 + retryableRunIds: retryableWorkspacePreparationRunIds,
3032 + begin: beginWorktreeSetup,
3033 + cancel: cancelWorktreeSetup,
3034 + retryPreparation: onRetryWorkspacePreparationStable,
3035 + openSetupTerminal: onOpenWorktreeSetupTerminal,
3036 + } = useWorktreeSetup({
3037 + routeThreadRef,
3038 + ownerKey: draftId ?? routeThreadKey,
3039 + activeThread,
3040 + threadRef: activeThreadRef,
3041 + serverProjection,
3042 + activityRun: activeActivityRun,
3043 localPreparing: isLocallyPreparingWorktree,
3061 - runStatus: activeActivityRun?.status,
3062 - latest: latestWorktreeSetup,
3063 - held: heldWorktreeSetup,
3064 - });
3065 - const worktreeSetup = resolveVisibleWorktreeSetup({
3066 - live: liveWorktreeSetup,
3067 - recorded: null,
3068 - turnStarted: activeActivityRun?.startedAt != null,
3044 + sendQueuesBehindSetup,
3045 + // Counts the optimistic send too, so the row retires the moment the
3046 + // follow-up is on screen rather than when the server echoes it back.
3047 followUpSent: timelineMessages.filter((message) => message.role === "user").length > 1,
3048 });
3071 - // Sends wait for the agent handoff, not for the setup script: an async script
3072 - // keeps the snapshot running while the agent already works, and a follow-up
3073 - // must not be held behind a slow install.
3074 - const worktreeSetupBlocksSend =
3075 - !sendQueuesBehindSetup &&
3076 - (worktreeSetup !== null
3077 - ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
3078 - : isPreparingWorktree);
3079 - const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
3080 - reportFailure: false,
3081 - });
3082 - const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);
3083 - const retryableRunIdsKey = useMemo(
3084 - () =>
3085 - [
3086 - ...workspacePreparationRetryRunIds(
3087 - serverProjection?.runs ?? [],
3088 - serverProjection?.turnItems ?? [],
3089 - ),
3090 - ].join("\n"),
3091 - [serverProjection?.runs, serverProjection?.turnItems],
3092 - );
3093 - const retryableWorkspacePreparationRunIds = useMemo(
3094 - () => new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
3095 - [retryableRunIdsKey],
3096 - );
3097 - const onRetryWorkspacePreparation = (runId: RunId) => {
3098 - if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
3099 - retryingWorkspacePreparationRunIds.add(runId);
3100 - void retryWorkspacePreparation({
3101 - environmentId: activeThreadRef.environmentId,
3102 - input: { threadId: activeThreadRef.threadId, runId },
3103 - }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
3104 - };
3105 - const onRetryWorkspacePreparationStable = useStableCallback(onRetryWorkspacePreparation);
3106 - const onCancelWorktreeSetup = () => {
3107 - if (!worktreeSetup || worktreeSetup.phase !== "running") return;
3108 - void cancelWorktreeSetup({
3109 - environmentId: setupTarget.environmentId,
3110 - input: { threadId: worktreeSetup.threadId },
3111 - });
3112 - };
3113 - const onCancelWorktreeSetupStable = useStableCallback(onCancelWorktreeSetup);
3114 - const onOpenWorktreeSetupTerminal = useMemo(() => {
3115 - if (!worktreeSetup || !activeThreadRef || worktreeSetup.threadId !== activeThreadRef.threadId) {
3116 - return null;
3117 - }
3118 - const setupThreadRef = activeThreadRef;
3119 - return (terminalId: string) => {
3120 - storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
3121 - };
3122 - }, [activeThreadRef, storeEnsureTerminal, worktreeSetup]);
3049 + const onCancelWorktreeSetupStable = useStableCallback(() => void cancelWorktreeSetup());
3050 const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
3051 const draftHeroDockRequested =
3052 activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
@@ -7353,13 +7280,9 @@ export default function ChatView(props: ChatViewProps) {
7280 ? "foreground"
7281 : submissionIntent,
7282 });
7356 - setWorktreeSetupRef(
7283 + beginWorktreeSetup(
7284 multipleModelSelections === null && baseBranchForWorktree
7358 - ? {
7359 - environmentId: activeThread.environmentId,
7360 - threadId: threadIdForSend,
7361 - ownerKey: worktreeSetupOwnerKey,
7362 - }
7285 + ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }
7286 : null,
7287 );
7288 }
@@ -8432,15 +8355,9 @@ export default function ChatView(props: ChatViewProps) {
8355 if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) {
8356 return;
8357 }
8435 - const target = {
8436 - environmentId: setupTarget.environmentId,
8437 - input: { threadId: worktreeSetup.threadId },
8438 - };
8439 - void (async () => {
8440 - const result = await cancelWorktreeSetup(target);
8441 - if (result._tag !== "Success" || !result.value.cancelled) return;
8442 - setWorkLocallyResendDraftId(draftId);
8443 - })();
8358 + void cancelWorktreeSetup().then((cancelled) => {
8359 + if (cancelled) setWorkLocallyResendDraftId(draftId);
8360 + });
8361 };
8362 const onWorktreeSetupWorkLocallyStable = useStableCallback(onWorktreeSetupWorkLocally);
8363 const onSendRef = useRef(onSend);
apps/web/src/components/chat/useWorktreeSetup.ts new
+191
@@ -0,0 +1,191 @@
1 +import type {
2 + EnvironmentId,
3 + OrchestrationV2ThreadProjection,
4 + RunId,
5 + ScopedThreadRef,
6 + ThreadId,
7 + WorktreeSetupSnapshot,
8 +} from "@t3tools/contracts";
9 +import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";
10 +import { useState } from "react";
11 +import { useStableCallback } from "../../hooks/useStableCallback";
12 +import { useEnvironmentQuery } from "../../state/query";
13 +import { threadEnvironment } from "../../state/threads";
14 +import { useAtomCommand } from "../../state/use-atom-command";
15 +import { vcsEnvironment } from "../../state/vcs";
16 +import { useTerminalUiStateStore } from "../../terminalUiStateStore";
17 +import type { Thread } from "../../types";
18 +import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";
19 +import { worktreeSetupAgentStarted } from "./MessagesTimeline.logic";
20 +
21 +/** Runs with a workspace preparation retry in flight, across ChatView instances. */
22 +const retryingWorkspacePreparationRunIds = new Set<RunId>();
23 +
24 +/**
25 + * Progress of the worktree a send is preparing for this route: the live setup
26 + * snapshot, whether it holds the composer, and the actions on its card.
27 + */
28 +export function useWorktreeSetup(input: {
29 + readonly routeThreadRef: ScopedThreadRef;
30 + // The draft id for a draft route, else the route's thread key. A bootstrap
31 + // rotates the thread id, so setup started from a draft stays keyed by it.
32 + readonly ownerKey: string;
33 + readonly activeThread:
34 + | { readonly id: ThreadId; readonly worktreePath: string | null }
35 + | undefined;
36 + readonly threadRef: ScopedThreadRef | null;
37 + readonly serverProjection: OrchestrationV2ThreadProjection | 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.
41 + readonly sendQueuesBehindSetup: boolean;
42 + readonly followUpSent: boolean;
43 +}) {
44 + const {
45 + routeThreadRef,
46 + ownerKey,
47 + activeThread,
48 + threadRef,
49 + serverProjection,
50 + activityRun,
51 + localPreparing,
52 + sendQueuesBehindSetup,
53 + followUpSent,
54 + } = input;
55 + const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
56 + reportFailure: false,
57 + });
58 + const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);
59 + const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
60 + // The thread a send is setting up, recorded by begin() before the server knows it.
61 + const [startedSetup, setStartedSetup] = useState<{
62 + readonly environmentId: EnvironmentId;
63 + readonly threadId: ThreadId;
64 + readonly ownerKey: string;
65 + } | null>(null);
66 + // Last live snapshot from the setup stream. The server drops a finished
67 + // snapshot after a grace period and emits null; holding it here bridges the
68 + // gap until the settled activity arrives on the thread projection.
69 + const [heldSnapshot, setHeldSnapshot] = useState<WorktreeSetupSnapshot | null>(null);
70 + const started = startedSetup !== null && startedSetup.ownerKey === ownerKey;
71 + // Keep the sending environment during local draft setup; revisiting a
72 + // canonical thread subscribes by its durable identity.
73 + const target = started ? startedSetup : routeThreadRef;
74 + const runPreparing = activityRun?.status === "preparing";
75 + const snapshotQuery = useEnvironmentQuery(
76 + started ||
77 + (activeThread?.id === routeThreadRef.threadId &&
78 + (localPreparing || runPreparing || activeThread.worktreePath !== null))
79 + ? vcsEnvironment.worktreeSetup({
80 + environmentId: target.environmentId,
81 + input: { threadId: target.threadId },
82 + })
83 + : null,
84 + );
85 + const latestSnapshot = snapshotQuery.data;
86 + // A newer snapshot replaces the held one; a late older one for the same
87 + // thread does not. Switching routes drops it.
88 + const [heldFor, setHeldFor] = useState<{
89 + readonly routeThreadRef: ScopedThreadRef;
90 + readonly latestSnapshot: WorktreeSetupSnapshot | null | undefined;
91 + }>({ routeThreadRef, latestSnapshot: null });
92 + if (heldFor.routeThreadRef !== routeThreadRef || heldFor.latestSnapshot !== latestSnapshot) {
93 + const routeChanged = heldFor.routeThreadRef !== routeThreadRef;
94 + setHeldFor({ routeThreadRef, latestSnapshot });
95 + if (routeChanged) {
96 + setHeldSnapshot(null);
97 + } else if (latestSnapshot) {
98 + setHeldSnapshot((current) =>
99 + current?.threadId === latestSnapshot.threadId && current.sequence > latestSnapshot.sequence
100 + ? current
101 + : latestSnapshot,
102 + );
103 + }
104 + }
105 + const { snapshot: liveSnapshot, isPreparingWorktree } = resolveWorktreeSetupProgress({
106 + threadId: target.threadId,
107 + localPreparing,
108 + runStatus: activityRun?.status,
109 + latest: latestSnapshot,
110 + held: heldSnapshot,
111 + });
112 + const worktreeSetup = resolveVisibleWorktreeSetup({
113 + live: liveSnapshot,
114 + recorded: null,
115 + turnStarted: activityRun?.startedAt != null,
116 + followUpSent,
117 + });
118 + // Sends wait for the agent handoff, not for the setup script: an async
119 + // script keeps the snapshot running while the agent already works, and a
120 + // follow-up must not be held behind a slow install. Before the first
121 + // snapshot arrives the starting session stands in for it. Once the server
122 + // has the thread, a send queues behind the setup run instead.
123 + const blocksSend =
124 + !sendQueuesBehindSetup &&
125 + (worktreeSetup !== null
126 + ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
127 + : isPreparingWorktree);
128 +
129 + // Keyed by content so the timeline context only changes when a retry appears or clears.
130 + const retryableRunIdsKey = [
131 + ...workspacePreparationRetryRunIds(
132 + serverProjection?.runs ?? [],
133 + serverProjection?.turnItems ?? [],
134 + ),
135 + ].join("\n");
136 + const [retryableRunIds, setRetryableRunIds] = useState({
137 + key: retryableRunIdsKey,
138 + ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
139 + });
140 + if (retryableRunIds.key !== retryableRunIdsKey) {
141 + setRetryableRunIds({
142 + key: retryableRunIdsKey,
143 + ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
144 + });
145 + }
146 +
147 + /** Records the thread a send is about to set up; null when the send needs none. */
148 + const begin = useStableCallback(
149 + (thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null) =>
150 + setStartedSetup(thread === null ? null : { ...thread, ownerKey }),
151 + );
152 + /** Cancels a running setup. Resolves true once the server cancelled it. */
153 + const cancel = useStableCallback(async () => {
154 + if (!worktreeSetup || worktreeSetup.phase !== "running") return false;
155 + const result = await cancelWorktreeSetup({
156 + environmentId: target.environmentId,
157 + input: { threadId: worktreeSetup.threadId },
158 + });
159 + return result._tag === "Success" && result.value.cancelled;
160 + });
161 + const retryPreparation = useStableCallback((runId: RunId) => {
162 + // One retry per failed run: a second click lands after the run is preparing again.
163 + if (!threadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
164 + retryingWorkspacePreparationRunIds.add(runId);
165 + void retryWorkspacePreparation({
166 + environmentId: threadRef.environmentId,
167 + input: { threadId: threadRef.threadId, runId },
168 + }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
169 + });
170 + // The setup terminal belongs to the thread that was set up. A failed
171 + // bootstrap deletes that thread and closes its terminals, so only offer the
172 + // terminal while the setup thread is still the active one.
173 + const setupThreadRef =
174 + worktreeSetup && threadRef && worktreeSetup.threadId === threadRef.threadId ? threadRef : null;
175 + const openSetupTerminal = setupThreadRef
176 + ? (terminalId: string) => {
177 + storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
178 + }
179 + : null;
180 +
181 + return {
182 + worktreeSetup,
183 + isPreparingWorktree,
184 + blocksSend,
185 + retryableRunIds: retryableRunIds.ids,
186 + begin,
187 + cancel,
188 + retryPreparation,
189 + openSetupTerminal,
190 + };
191 +}
vite.config.ts
+1
@@ -330,6 +330,7 @@ export default defineConfig({
330 "apps/web/src/components/chat/usePendingThreadRequests.ts",
331 "apps/web/src/components/chat/useQueuedRunEdit.ts",
332 "apps/web/src/components/chat/useUsageLimitsPanel.ts",
333 + "apps/web/src/components/chat/useWorktreeSetup.ts",
334 "apps/web/src/components/pullRequest/useThreadLinkedPullRequest.ts",
335 "apps/web/src/components/preview/useAgentOpenedPreviews.ts",
336 "apps/web/src/components/terminal/**",