TypeScript
refactor(web): move worktree setup progress out of ChatView (#20316)
Julius Marminged3de2c17c0ce
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 6d2ff0ca77c..121e7f295a5 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -5,8 +5,6 @@ import {resolveBackgroundDraftWorkspaceOptions,resolveDraftHeroState,shouldDockDraftHeroForSubmission,- resolveVisibleWorktreeSetup,- resolveWorktreeSetupProgress,} from "./ChatView.logic";import * as DateTime from "effect/DateTime";import { restorePlanFollowUpComposer } from "./ChatView.logic";@@ -37,6 +35,7 @@ import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";import { feedbackBannerItem } from "./chat/ComposerFeedback";import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";+import { useWorktreeSetup } from "./chat/useWorktreeSetup";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import * as Schema from "effect/Schema";import {@@ -71,7 +70,6 @@ import {resolveEnvironmentMachineKind,resolveProjectProviderInstanceEnabled,RuntimeMode,- type WorktreeSetupSnapshot,} from "@t3tools/contracts";import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";@@ -389,7 +387,6 @@ import {serverEnvironment,} from "../state/server";import { threadEnvironment } from "../state/threads";-import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";import { vcsEnvironment } from "../state/vcs";import { sourceControlEnvironment } from "../state/sourceControl";@@ -421,7 +418,7 @@ import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";import { getTriggerDisplayModelName } from "./chat/providerIconUtils";-import { resolveTimelineIsAtEnd, worktreeSetupAgentStarted } from "./chat/MessagesTimeline.logic";+import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";import {overlayComposerIsResting,resolveComposerTimelineInset,@@ -901,8 +898,12 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | nreturn current.messageId === null ? current : { ...current, messageId: null };}-const retryingWorkspacePreparationRunIds = new Set<RunId>();+// The factories below build functions ChatView calls during render, or hands+// to ChatComposer, which can call them after an await. They live outside the+// component so each closure keeps only its inputs, not a whole render scope+// (see useStableCallback), while still acting on the render that made them.+/** Records a thread error in local state, keyed by the route the making render saw. */function makeThreadErrorSetter(input: {readonly routeThreadRef: ScopedThreadRef;readonly routeThreadKey: string;@@ -1235,15 +1236,10 @@ export default function ChatView(props: ChatViewProps) {return () => revokeBlobPreviewUrl(src);}, [expandedImage]);const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);- // Last live snapshot from the setup stream. The server drops a finished- // snapshot after a grace period and emits null; holding it here bridges the- // gap until the settled activity arrives on the thread projection.- const [worktreeSetupRef, setWorktreeSetupRef] = useState<{- environmentId: EnvironmentId;- threadId: ThreadId;- ownerKey: string;- } | null>(null);- const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);+ // Set by "Work locally": the draft whose restored message should be resent+ // once the cancelled dispatch has settled and the draft is in local mode.+ // Keyed by draft id so a bootstrap rotating the thread id keeps it, while+ // moving to another draft drops it without an effect.const [workLocallyResendDraftId, setWorkLocallyResendDraftId] = useState<DraftId | null>(null);useEffect(() => {if (workLocallyResendDraftId !== null && workLocallyResendDraftId !== draftId) {@@ -3028,98 +3024,29 @@ export default function ChatView(props: ChatViewProps) {activeThreadKey,);const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey);- const worktreeSetupOwnerKey = draftId ?? routeThreadKey;- const worktreeSetupActive =- worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey;- const setupTarget = worktreeSetupActive ? worktreeSetupRef : routeThreadRef;- const worktreeSetupQuery = useEnvironmentQuery(- worktreeSetupActive ||- (activeThread?.id === routeThreadRef.threadId &&- (isLocallyPreparingWorktree || activeRunPreparing || activeThread.worktreePath !== null))- ? vcsEnvironment.worktreeSetup({- environmentId: setupTarget.environmentId,- input: { threadId: setupTarget.threadId },- })- : null,- );- const latestWorktreeSetup = worktreeSetupQuery.data;- useEffect(() => {- if (!latestWorktreeSetup) return;- setHeldWorktreeSetup((current) =>- current?.threadId === latestWorktreeSetup.threadId &&- current.sequence > latestWorktreeSetup.sequence- ? current- : latestWorktreeSetup,- );- }, [latestWorktreeSetup]);- useEffect(() => {- setHeldWorktreeSetup(null);- }, [routeThreadKey]);- const { snapshot: liveWorktreeSetup, isPreparingWorktree } = resolveWorktreeSetupProgress({- threadId: setupTarget.threadId,+ const {+ worktreeSetup,+ isPreparingWorktree,+ blocksSend: worktreeSetupBlocksSend,+ retryableRunIds: retryableWorkspacePreparationRunIds,+ begin: beginWorktreeSetup,+ cancel: cancelWorktreeSetup,+ retryPreparation: onRetryWorkspacePreparationStable,+ openSetupTerminal: onOpenWorktreeSetupTerminal,+ } = useWorktreeSetup({+ routeThreadRef,+ ownerKey: draftId ?? routeThreadKey,+ activeThread,+ threadRef: activeThreadRef,+ serverProjection,+ activityRun: activeActivityRun,localPreparing: isLocallyPreparingWorktree,- runStatus: activeActivityRun?.status,- latest: latestWorktreeSetup,- held: heldWorktreeSetup,- });- const worktreeSetup = resolveVisibleWorktreeSetup({- live: liveWorktreeSetup,- recorded: null,- turnStarted: activeActivityRun?.startedAt != null,+ sendQueuesBehindSetup,+ // Counts the optimistic send too, so the row retires the moment the+ // follow-up is on screen rather than when the server echoes it back.followUpSent: timelineMessages.filter((message) => message.role === "user").length > 1,});- // Sends wait for the agent handoff, not for the setup script: an async script- // keeps the snapshot running while the agent already works, and a follow-up- // must not be held behind a slow install.- const worktreeSetupBlocksSend =- !sendQueuesBehindSetup &&- (worktreeSetup !== null- ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)- : isPreparingWorktree);- const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {- reportFailure: false,- });- const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);- const retryableRunIdsKey = useMemo(- () =>- [- ...workspacePreparationRetryRunIds(- serverProjection?.runs ?? [],- serverProjection?.turnItems ?? [],- ),- ].join("\n"),- [serverProjection?.runs, serverProjection?.turnItems],- );- const retryableWorkspacePreparationRunIds = useMemo(- () => new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),- [retryableRunIdsKey],- );- const onRetryWorkspacePreparation = (runId: RunId) => {- if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return;- retryingWorkspacePreparationRunIds.add(runId);- void retryWorkspacePreparation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, runId },- }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));- };- const onRetryWorkspacePreparationStable = useStableCallback(onRetryWorkspacePreparation);- const onCancelWorktreeSetup = () => {- if (!worktreeSetup || worktreeSetup.phase !== "running") return;- void cancelWorktreeSetup({- environmentId: setupTarget.environmentId,- input: { threadId: worktreeSetup.threadId },- });- };- const onCancelWorktreeSetupStable = useStableCallback(onCancelWorktreeSetup);- const onOpenWorktreeSetupTerminal = useMemo(() => {- if (!worktreeSetup || !activeThreadRef || worktreeSetup.threadId !== activeThreadRef.threadId) {- return null;- }- const setupThreadRef = activeThreadRef;- return (terminalId: string) => {- storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });- };- }, [activeThreadRef, storeEnsureTerminal, worktreeSetup]);+ const onCancelWorktreeSetupStable = useStableCallback(() => void cancelWorktreeSetup());const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);const draftHeroDockRequested =activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;@@ -7353,13 +7280,9 @@ export default function ChatView(props: ChatViewProps) {? "foreground": submissionIntent,});- setWorktreeSetupRef(+ beginWorktreeSetup(multipleModelSelections === null && baseBranchForWorktree- ? {- environmentId: activeThread.environmentId,- threadId: threadIdForSend,- ownerKey: worktreeSetupOwnerKey,- }+ ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }: null,);}@@ -8432,15 +8355,9 @@ export default function ChatView(props: ChatViewProps) {if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) {return;}- const target = {- environmentId: setupTarget.environmentId,- input: { threadId: worktreeSetup.threadId },- };- void (async () => {- const result = await cancelWorktreeSetup(target);- if (result._tag !== "Success" || !result.value.cancelled) return;- setWorkLocallyResendDraftId(draftId);- })();+ void cancelWorktreeSetup().then((cancelled) => {+ if (cancelled) setWorkLocallyResendDraftId(draftId);+ });};const onWorktreeSetupWorkLocallyStable = useStableCallback(onWorktreeSetupWorkLocally);const onSendRef = useRef(onSend);diff --git a/apps/web/src/components/chat/useWorktreeSetup.ts b/apps/web/src/components/chat/useWorktreeSetup.tsnew file mode 100644index 00000000000..6f8cb1269d5--- /dev/null+++ b/apps/web/src/components/chat/useWorktreeSetup.ts@@ -0,0 +1,191 @@+import type {+ EnvironmentId,+ OrchestrationV2ThreadProjection,+ RunId,+ ScopedThreadRef,+ ThreadId,+ WorktreeSetupSnapshot,+} from "@t3tools/contracts";+import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";+import { useState } from "react";+import { useStableCallback } from "../../hooks/useStableCallback";+import { useEnvironmentQuery } from "../../state/query";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { vcsEnvironment } from "../../state/vcs";+import { useTerminalUiStateStore } from "../../terminalUiStateStore";+import type { Thread } from "../../types";+import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";+import { worktreeSetupAgentStarted } from "./MessagesTimeline.logic";++/** Runs with a workspace preparation retry in flight, across ChatView instances. */+const retryingWorkspacePreparationRunIds = new Set<RunId>();++/**+ * Progress of the worktree a send is preparing for this route: the live setup+ * snapshot, whether it holds the composer, and the actions on its card.+ */+export function useWorktreeSetup(input: {+ readonly routeThreadRef: ScopedThreadRef;+ // The draft id for a draft route, else the route's thread key. A bootstrap+ // rotates the thread id, so setup started from a draft stays keyed by it.+ readonly ownerKey: string;+ readonly activeThread:+ | { readonly id: ThreadId; readonly worktreePath: string | null }+ | undefined;+ readonly threadRef: ScopedThreadRef | null;+ readonly serverProjection: OrchestrationV2ThreadProjection | null;+ readonly activityRun: Thread["latestRun"] | null;+ readonly localPreparing: boolean;+ // A send that the server queues behind the setup run is not held here.+ readonly sendQueuesBehindSetup: boolean;+ readonly followUpSent: boolean;+}) {+ const {+ routeThreadRef,+ ownerKey,+ activeThread,+ threadRef,+ serverProjection,+ activityRun,+ localPreparing,+ sendQueuesBehindSetup,+ followUpSent,+ } = input;+ const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {+ reportFailure: false,+ });+ const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);+ const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);+ // The thread a send is setting up, recorded by begin() before the server knows it.+ const [startedSetup, setStartedSetup] = useState<{+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly ownerKey: string;+ } | null>(null);+ // Last live snapshot from the setup stream. The server drops a finished+ // snapshot after a grace period and emits null; holding it here bridges the+ // gap until the settled activity arrives on the thread projection.+ const [heldSnapshot, setHeldSnapshot] = useState<WorktreeSetupSnapshot | null>(null);+ const started = startedSetup !== null && startedSetup.ownerKey === ownerKey;+ // Keep the sending environment during local draft setup; revisiting a+ // canonical thread subscribes by its durable identity.+ const target = started ? startedSetup : routeThreadRef;+ const runPreparing = activityRun?.status === "preparing";+ const snapshotQuery = useEnvironmentQuery(+ started ||+ (activeThread?.id === routeThreadRef.threadId &&+ (localPreparing || runPreparing || activeThread.worktreePath !== null))+ ? vcsEnvironment.worktreeSetup({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ })+ : null,+ );+ const latestSnapshot = snapshotQuery.data;+ // A newer snapshot replaces the held one; a late older one for the same+ // thread does not. Switching routes drops it.+ const [heldFor, setHeldFor] = useState<{+ readonly routeThreadRef: ScopedThreadRef;+ readonly latestSnapshot: WorktreeSetupSnapshot | null | undefined;+ }>({ routeThreadRef, latestSnapshot: null });+ if (heldFor.routeThreadRef !== routeThreadRef || heldFor.latestSnapshot !== latestSnapshot) {+ const routeChanged = heldFor.routeThreadRef !== routeThreadRef;+ setHeldFor({ routeThreadRef, latestSnapshot });+ if (routeChanged) {+ setHeldSnapshot(null);+ } else if (latestSnapshot) {+ setHeldSnapshot((current) =>+ current?.threadId === latestSnapshot.threadId && current.sequence > latestSnapshot.sequence+ ? current+ : latestSnapshot,+ );+ }+ }+ const { snapshot: liveSnapshot, isPreparingWorktree } = resolveWorktreeSetupProgress({+ threadId: target.threadId,+ localPreparing,+ runStatus: activityRun?.status,+ latest: latestSnapshot,+ held: heldSnapshot,+ });+ const worktreeSetup = resolveVisibleWorktreeSetup({+ live: liveSnapshot,+ recorded: null,+ turnStarted: activityRun?.startedAt != null,+ followUpSent,+ });+ // Sends wait for the agent handoff, not for the setup script: an async+ // script keeps the snapshot running while the agent already works, and a+ // follow-up must not be held behind a slow install. Before the first+ // snapshot arrives the starting session stands in for it. Once the server+ // has the thread, a send queues behind the setup run instead.+ const blocksSend =+ !sendQueuesBehindSetup &&+ (worktreeSetup !== null+ ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)+ : isPreparingWorktree);++ // Keyed by content so the timeline context only changes when a retry appears or clears.+ const retryableRunIdsKey = [+ ...workspacePreparationRetryRunIds(+ serverProjection?.runs ?? [],+ serverProjection?.turnItems ?? [],+ ),+ ].join("\n");+ const [retryableRunIds, setRetryableRunIds] = useState({+ key: retryableRunIdsKey,+ ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),+ });+ if (retryableRunIds.key !== retryableRunIdsKey) {+ setRetryableRunIds({+ key: retryableRunIdsKey,+ ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),+ });+ }++ /** Records the thread a send is about to set up; null when the send needs none. */+ const begin = useStableCallback(+ (thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null) =>+ setStartedSetup(thread === null ? null : { ...thread, ownerKey }),+ );+ /** Cancels a running setup. Resolves true once the server cancelled it. */+ const cancel = useStableCallback(async () => {+ if (!worktreeSetup || worktreeSetup.phase !== "running") return false;+ const result = await cancelWorktreeSetup({+ environmentId: target.environmentId,+ input: { threadId: worktreeSetup.threadId },+ });+ return result._tag === "Success" && result.value.cancelled;+ });+ const retryPreparation = useStableCallback((runId: RunId) => {+ // One retry per failed run: a second click lands after the run is preparing again.+ if (!threadRef || retryingWorkspacePreparationRunIds.has(runId)) return;+ retryingWorkspacePreparationRunIds.add(runId);+ void retryWorkspacePreparation({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId, runId },+ }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));+ });+ // The setup terminal belongs to the thread that was set up. A failed+ // bootstrap deletes that thread and closes its terminals, so only offer the+ // terminal while the setup thread is still the active one.+ const setupThreadRef =+ worktreeSetup && threadRef && worktreeSetup.threadId === threadRef.threadId ? threadRef : null;+ const openSetupTerminal = setupThreadRef+ ? (terminalId: string) => {+ storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });+ }+ : null;++ return {+ worktreeSetup,+ isPreparingWorktree,+ blocksSend,+ retryableRunIds: retryableRunIds.ids,+ begin,+ cancel,+ retryPreparation,+ openSetupTerminal,+ };+}diff --git a/vite.config.ts b/vite.config.tsindex 23f232b7ce9..d575a085a6d 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -330,6 +330,7 @@ export default defineConfig({"apps/web/src/components/chat/usePendingThreadRequests.ts","apps/web/src/components/chat/useQueuedRunEdit.ts","apps/web/src/components/chat/useUsageLimitsPanel.ts",+ "apps/web/src/components/chat/useWorktreeSetup.ts","apps/web/src/components/pullRequest/useThreadLinkedPullRequest.ts","apps/web/src/components/preview/useAgentOpenedPreviews.ts","apps/web/src/components/terminal/**",