Skip to content

Commit 9c7a742

Browse files
refactor(web): resuming an interrupted run lives in its own hook
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 322d08d commit 9c7a742

3 files changed

Lines changed: 192 additions & 100 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { useThreadLifecycle } from "./chat/useThreadLifecycle";
1515
import { useRightPanelActions } from "./chat/useRightPanelActions";
1616
import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions";
1717
import { useComposerSend } from "./chat/useComposerSend";
18+
import { useComposerResume } from "./chat/useComposerResume";
1819
import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
1920
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
2021
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
@@ -2923,7 +2924,28 @@ export default function ChatView(props: ChatViewProps) {
29232924
setPendingServerThreadStartFromOriginByThreadId,
29242925
scheduleComposerFocus,
29252926
});
2926-
const { onSend, onResume, onImplementPlanInNewThread, isResuming } = useComposerSend({
2927+
const { onResume, isResuming } = useComposerResume({
2928+
environmentId,
2929+
routeThreadKey,
2930+
currentRouteThreadKeyRef,
2931+
activeThread,
2932+
resumableRunId,
2933+
hasHeldQueuedRuns,
2934+
isSendBusy,
2935+
isConnecting,
2936+
isRevertingCheckpoint,
2937+
threadDetailLoading,
2938+
activeEnvironmentUnavailable,
2939+
runtimeMode,
2940+
interactionMode,
2941+
localCheckoutBranchMismatch,
2942+
composerRef,
2943+
persistThreadSettingsForNextTurn,
2944+
clearUsageLimitsFor,
2945+
scrollToEnd,
2946+
setThreadError,
2947+
});
2948+
const { onSend, onImplementPlanInNewThread } = useComposerSend({
29272949
environmentId,
29282950
routeThreadKey,
29292951
currentRouteThreadKeyRef,
@@ -2939,12 +2961,9 @@ export default function ChatView(props: ChatViewProps) {
29392961
isServerThread,
29402962
isLocalDraftThread,
29412963
isGitRepo,
2942-
hasHeldQueuedRuns,
2943-
resumableRunId,
29442964
phase,
29452965
runtimeMode,
29462966
defaultRuntimeMode,
2947-
interactionMode,
29482967
sendEnvMode,
29492968
startFromOrigin,
29502969
localCheckoutBranchMismatch,
@@ -3000,7 +3019,6 @@ export default function ChatView(props: ChatViewProps) {
30003019
setMultipleModelSelections,
30013020
setThreadError,
30023021
setKeepFullHistory,
3003-
scrollToEnd,
30043022
anchorNewTurn,
30053023
acknowledgeActiveThreadWoke,
30063024
handleInteractionModeChange,
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import {
2+
type EnvironmentId,
3+
type ProviderInteractionMode,
4+
type RunId,
5+
type RuntimeMode,
6+
} from "@t3tools/contracts";
7+
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
8+
import {
9+
isAtomCommandInterrupted,
10+
squashAtomCommandFailure,
11+
type AtomCommandResult,
12+
} from "@t3tools/client-runtime/state/runtime";
13+
import { useState } from "react";
14+
import { newMessageId } from "~/lib/utils";
15+
import type { ComposerHandleRef } from "../../composerHandleContext";
16+
import { threadEnvironment } from "../../state/threads";
17+
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18+
import type { makeThreadErrorSetter } from "../ChatView.logic";
19+
import { draftSendState } from "./chatViewSend";
20+
import type { useTimelineFollow } from "./useTimelineFollow";
21+
import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
22+
23+
interface ComposerResumeInput {
24+
readonly environmentId: EnvironmentId;
25+
readonly routeThreadKey: string;
26+
readonly currentRouteThreadKeyRef: { readonly current: string | null };
27+
readonly activeThread: EnvironmentThreadShell | undefined;
28+
readonly resumableRunId: RunId | null;
29+
readonly hasHeldQueuedRuns: boolean;
30+
readonly isSendBusy: boolean;
31+
readonly isConnecting: boolean;
32+
readonly isRevertingCheckpoint: boolean;
33+
readonly threadDetailLoading: boolean;
34+
readonly activeEnvironmentUnavailable: boolean;
35+
readonly runtimeMode: RuntimeMode;
36+
readonly interactionMode: ProviderInteractionMode;
37+
readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null;
38+
readonly composerRef: ComposerHandleRef;
39+
readonly persistThreadSettingsForNextTurn: (input: {
40+
threadId: EnvironmentThreadShell["id"];
41+
createdAt: string;
42+
branch?: string;
43+
runtimeMode: RuntimeMode;
44+
interactionMode: ProviderInteractionMode;
45+
}) => Promise<AtomCommandResult<void, unknown>>;
46+
readonly clearUsageLimitsFor: ReturnType<typeof useUsageLimitsPanel>["clearFor"];
47+
readonly scrollToEnd: ReturnType<typeof useTimelineFollow>["scrollToEnd"];
48+
readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
49+
}
50+
51+
/**
52+
* Resumes an interrupted run ("Continue where you left off.") and/or releases the turns held
53+
* in its queue. Shares the per-route send lock with the composer's send paths.
54+
*/
55+
export function useComposerResume(input: ComposerResumeInput) {
56+
const {
57+
environmentId,
58+
routeThreadKey,
59+
currentRouteThreadKeyRef,
60+
activeThread,
61+
resumableRunId,
62+
hasHeldQueuedRuns,
63+
isSendBusy,
64+
isConnecting,
65+
isRevertingCheckpoint,
66+
threadDetailLoading,
67+
activeEnvironmentUnavailable,
68+
runtimeMode,
69+
interactionMode,
70+
localCheckoutBranchMismatch,
71+
composerRef,
72+
persistThreadSettingsForNextTurn,
73+
clearUsageLimitsFor,
74+
scrollToEnd,
75+
setThreadError,
76+
} = input;
77+
const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
78+
reportFailure: false,
79+
});
80+
const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
81+
reportFailure: false,
82+
});
83+
const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
84+
() => new Set(),
85+
);
86+
const isResuming = resumingThreadKeys.has(routeThreadKey);
87+
const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
88+
89+
const onResume = async () => {
90+
if (
91+
!activeThread ||
92+
(resumableRunId === null && !hasHeldQueuedRuns) ||
93+
isSendBusy ||
94+
isResuming ||
95+
isConnecting ||
96+
isRevertingCheckpoint ||
97+
threadDetailLoading ||
98+
activeEnvironmentUnavailable ||
99+
sendInFlightRef.current
100+
) {
101+
return;
102+
}
103+
const threadId = activeThread.id;
104+
sendInFlightRef.current = true;
105+
setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
106+
setThreadError(threadId, null);
107+
// Commands settle into a result, so this always runs.
108+
const resume = async () => {
109+
if (resumableRunId === null) {
110+
return resumeThreadQueue({ environmentId, input: { threadId } });
111+
}
112+
const createdAt = new Date().toISOString();
113+
const settingsResult = await persistThreadSettingsForNextTurn({
114+
threadId,
115+
createdAt,
116+
...(localCheckoutBranchMismatch
117+
? { branch: localCheckoutBranchMismatch.currentBranch }
118+
: {}),
119+
runtimeMode,
120+
interactionMode,
121+
});
122+
if (settingsResult._tag === "Failure") return settingsResult;
123+
const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
124+
const turnResult = await startThreadTurn({
125+
environmentId,
126+
input: {
127+
threadId,
128+
manualContinuationOfRunId: resumableRunId,
129+
...(modelSelection ? { modelSelection } : {}),
130+
message: {
131+
messageId: newMessageId(),
132+
role: "user",
133+
text: "Continue where you left off.",
134+
attachments: [],
135+
},
136+
runtimeMode,
137+
interactionMode,
138+
dispatchMode: "start",
139+
},
140+
});
141+
if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
142+
clearUsageLimitsFor(routeThreadKey);
143+
return resumeThreadQueue({ environmentId, input: { threadId } });
144+
};
145+
const result = await resume();
146+
if (result._tag === "Failure") {
147+
if (!isAtomCommandInterrupted(result)) {
148+
const error = squashAtomCommandFailure(result);
149+
setThreadError(
150+
threadId,
151+
error instanceof Error ? error.message : "Could not resume thread.",
152+
);
153+
}
154+
} else {
155+
clearUsageLimitsFor(routeThreadKey);
156+
if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
157+
}
158+
sendInFlightRef.current = false;
159+
setResumingThreadKeys((current) => {
160+
const next = new Set(current);
161+
next.delete(routeThreadKey);
162+
return next;
163+
});
164+
};
165+
166+
return { onResume, isResuming };
167+
}

‎apps/web/src/components/chat/useComposerSend.ts‎

Lines changed: 2 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import {
2525
type ModelSelection,
2626
type PreviewAnnotationPayload,
2727
type ThreadId,
28-
type RunId,
2928
ProviderInteractionMode,
3029
RuntimeMode,
3130
} from "@t3tools/contracts";
@@ -44,7 +43,7 @@ import {
4443
} from "@t3tools/client-runtime/environment";
4544
import { createModelSelection } from "@t3tools/shared/model";
4645
import { truncate } from "@t3tools/shared/String";
47-
import { type SetStateAction, useLayoutEffect, useRef, useState } from "react";
46+
import { type SetStateAction, useLayoutEffect, useRef } from "react";
4847
import { flushSync } from "react-dom";
4948
import { useNavigate } from "@tanstack/react-router";
5049
import {
@@ -162,12 +161,9 @@ interface ComposerSendInput {
162161
readonly isServerThread: boolean;
163162
readonly isLocalDraftThread: boolean;
164163
readonly isGitRepo: boolean;
165-
readonly hasHeldQueuedRuns: boolean;
166-
readonly resumableRunId: RunId | null;
167164
readonly phase: SessionPhase;
168165
readonly runtimeMode: RuntimeMode;
169166
readonly defaultRuntimeMode: RuntimeMode;
170-
readonly interactionMode: ProviderInteractionMode;
171167
readonly sendEnvMode: DraftThreadEnvMode;
172168
readonly startFromOrigin: boolean;
173169
readonly localCheckoutBranchMismatch: {
@@ -230,7 +226,6 @@ interface ComposerSendInput {
230226
) => void;
231227
readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
232228
readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void;
233-
readonly scrollToEnd: TimelineFollow["scrollToEnd"];
234229
readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
235230
readonly acknowledgeActiveThreadWoke: () => void;
236231
readonly handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
@@ -267,12 +262,9 @@ export function useComposerSend(input: ComposerSendInput) {
267262
isServerThread,
268263
isLocalDraftThread,
269264
isGitRepo,
270-
hasHeldQueuedRuns,
271-
resumableRunId,
272265
phase,
273266
runtimeMode,
274267
defaultRuntimeMode,
275-
interactionMode,
276268
sendEnvMode,
277269
startFromOrigin,
278270
localCheckoutBranchMismatch,
@@ -328,7 +320,6 @@ export function useComposerSend(input: ComposerSendInput) {
328320
setMultipleModelSelections,
329321
setThreadError,
330322
setKeepFullHistory,
331-
scrollToEnd,
332323
anchorNewTurn,
333324
acknowledgeActiveThreadWoke,
334325
handleInteractionModeChange,
@@ -342,9 +333,6 @@ export function useComposerSend(input: ComposerSendInput) {
342333
const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
343334
reportFailure: false,
344335
});
345-
const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
346-
reportFailure: false,
347-
});
348336
const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, {
349337
reportFailure: false,
350338
});
@@ -365,10 +353,6 @@ export function useComposerSend(input: ComposerSendInput) {
365353
const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
366354
const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
367355
draftSendState(routeThreadKey);
368-
const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
369-
() => new Set(),
370-
);
371-
const isResuming = resumingThreadKeys.has(routeThreadKey);
372356
const composerSendGenerationRef = useRef(0);
373357
const environmentUnavailableSendToastSlotRef = useRef(0);
374358
// A send awaits uploads before it declines, so it reads the approvals pending by then.
@@ -379,83 +363,6 @@ export function useComposerSend(input: ComposerSendInput) {
379363
respondingRequestIdsRef.current = respondingRequestIds;
380364
}, [pendingApprovals, respondingRequestIds]);
381365

382-
const onResume = async () => {
383-
if (
384-
!activeThread ||
385-
(resumableRunId === null && !hasHeldQueuedRuns) ||
386-
isSendBusy ||
387-
isResuming ||
388-
isConnecting ||
389-
isRevertingCheckpoint ||
390-
threadDetailLoading ||
391-
activeEnvironmentUnavailable ||
392-
sendInFlightRef.current
393-
) {
394-
return;
395-
}
396-
const threadId = activeThread.id;
397-
sendInFlightRef.current = true;
398-
setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
399-
setThreadError(threadId, null);
400-
// Commands settle into a result, so this always runs.
401-
const resume = async () => {
402-
if (resumableRunId === null) {
403-
return resumeThreadQueue({ environmentId, input: { threadId } });
404-
}
405-
const createdAt = new Date().toISOString();
406-
const settingsResult = await persistThreadSettingsForNextTurn({
407-
threadId,
408-
createdAt,
409-
...(localCheckoutBranchMismatch
410-
? { branch: localCheckoutBranchMismatch.currentBranch }
411-
: {}),
412-
runtimeMode,
413-
interactionMode,
414-
});
415-
if (settingsResult._tag === "Failure") return settingsResult;
416-
const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
417-
const turnResult = await startThreadTurn({
418-
environmentId,
419-
input: {
420-
threadId,
421-
manualContinuationOfRunId: resumableRunId,
422-
...(modelSelection ? { modelSelection } : {}),
423-
message: {
424-
messageId: newMessageId(),
425-
role: "user",
426-
text: "Continue where you left off.",
427-
attachments: [],
428-
},
429-
runtimeMode,
430-
interactionMode,
431-
dispatchMode: "start",
432-
},
433-
});
434-
if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
435-
clearUsageLimitsFor(routeThreadKey);
436-
return resumeThreadQueue({ environmentId, input: { threadId } });
437-
};
438-
const result = await resume();
439-
if (result._tag === "Failure") {
440-
if (!isAtomCommandInterrupted(result)) {
441-
const error = squashAtomCommandFailure(result);
442-
setThreadError(
443-
threadId,
444-
error instanceof Error ? error.message : "Could not resume thread.",
445-
);
446-
}
447-
} else {
448-
clearUsageLimitsFor(routeThreadKey);
449-
if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
450-
}
451-
sendInFlightRef.current = false;
452-
setResumingThreadKeys((current) => {
453-
const next = new Set(current);
454-
next.delete(routeThreadKey);
455-
return next;
456-
});
457-
};
458-
459366
const onSend = async (
460367
e?: { preventDefault: () => void },
461368
dispatchMode: ComposerDispatchMode = "auto",
@@ -1912,5 +1819,5 @@ export function useComposerSend(input: ComposerSendInput) {
19121819
finish();
19131820
};
19141821

1915-
return { onSend, onResume, onImplementPlanInNewThread, isResuming };
1822+
return { onSend, onImplementPlanInNewThread };
19161823
}

0 commit comments

Comments
 (0)