Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ProviderInteractionMode,
4 type RunId,
5 type RuntimeMode,
6} from "@t3tools/contracts";
7import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11 type AtomCommandResult,
12} from "@t3tools/client-runtime/state/runtime";
13import { useState } from "react";
14import { newMessageId } from "~/lib/utils";
15import type { ComposerHandleRef } from "../../composerHandleContext";
16import { threadEnvironment } from "../../state/threads";
17import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18import type { makeThreadErrorSetter } from "../ChatView.logic";
19import { draftSendState } from "./chatViewSend";
20import type { useTimelineFollow } from "./useTimelineFollow";
21import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
22
23interface 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 isRevertingCheckpoint: boolean;
32 readonly threadDetailLoading: boolean;
33 readonly activeEnvironmentUnavailable: boolean;
34 readonly runtimeMode: RuntimeMode;
35 readonly interactionMode: ProviderInteractionMode;
36 readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null;
37 readonly composerRef: ComposerHandleRef;
38 readonly persistThreadSettingsForNextTurn: (input: {
39 threadId: EnvironmentThreadShell["id"];
40 createdAt: string;
41 branch?: string;
42 runtimeMode: RuntimeMode;
43 interactionMode: ProviderInteractionMode;
44 }) => Promise<AtomCommandResult<void, unknown>>;
45 readonly clearUsageLimitsFor: ReturnType<typeof useUsageLimitsPanel>["clearFor"];
46 readonly scrollToEnd: ReturnType<typeof useTimelineFollow>["scrollToEnd"];
47 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
48}
49
50/**
51 * Resumes an interrupted run ("Continue where you left off.") and/or releases the turns held
52 * in its queue. Shares the per-route send lock with the composer's send paths.
53 */
54export function useComposerResume(input: ComposerResumeInput) {
55 const {
56 environmentId,
57 routeThreadKey,
58 currentRouteThreadKeyRef,
59 activeThread,
60 resumableRunId,
61 hasHeldQueuedRuns,
62 isSendBusy,
63 isRevertingCheckpoint,
64 threadDetailLoading,
65 activeEnvironmentUnavailable,
66 runtimeMode,
67 interactionMode,
68 localCheckoutBranchMismatch,
69 composerRef,
70 persistThreadSettingsForNextTurn,
71 clearUsageLimitsFor,
72 scrollToEnd,
73 setThreadError,
74 } = input;
75 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
76 reportFailure: false,
77 });
78 const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
79 reportFailure: false,
80 });
81 const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
82 () => new Set(),
83 );
84 const isResuming = resumingThreadKeys.has(routeThreadKey);
85 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
86
87 const onResume = async () => {
88 if (
89 !activeThread ||
90 (resumableRunId === null && !hasHeldQueuedRuns) ||
91 isSendBusy ||
92 isResuming ||
93 isRevertingCheckpoint ||
94 threadDetailLoading ||
95 activeEnvironmentUnavailable ||
96 sendInFlightRef.current
97 ) {
98 return;
99 }
100 const threadId = activeThread.id;
101 sendInFlightRef.current = true;
102 setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
103 setThreadError(threadId, null);
104 // Commands settle into a result, so this always runs.
105 const resume = async () => {
106 if (resumableRunId === null) {
107 return resumeThreadQueue({ environmentId, input: { threadId } });
108 }
109 const createdAt = new Date().toISOString();
110 const settingsResult = await persistThreadSettingsForNextTurn({
111 threadId,
112 createdAt,
113 ...(localCheckoutBranchMismatch
114 ? { branch: localCheckoutBranchMismatch.currentBranch }
115 : {}),
116 runtimeMode,
117 interactionMode,
118 });
119 if (settingsResult._tag === "Failure") return settingsResult;
120 const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
121 const turnResult = await startThreadTurn({
122 environmentId,
123 input: {
124 threadId,
125 manualContinuationOfRunId: resumableRunId,
126 ...(modelSelection ? { modelSelection } : {}),
127 message: {
128 messageId: newMessageId(),
129 role: "user",
130 text: "Continue where you left off.",
131 attachments: [],
132 },
133 runtimeMode,
134 interactionMode,
135 dispatchMode: "start",
136 },
137 });
138 if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
139 clearUsageLimitsFor(routeThreadKey);
140 return resumeThreadQueue({ environmentId, input: { threadId } });
141 };
142 const result = await resume();
143 if (result._tag === "Failure") {
144 if (!isAtomCommandInterrupted(result)) {
145 const error = squashAtomCommandFailure(result);
146 setThreadError(
147 threadId,
148 error instanceof Error ? error.message : "Could not resume thread.",
149 );
150 }
151 } else {
152 clearUsageLimitsFor(routeThreadKey);
153 if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
154 }
155 sendInFlightRef.current = false;
156 setResumingThreadKeys((current) => {
157 const next = new Set(current);
158 next.delete(routeThreadKey);
159 return next;
160 });
161 };
162
163 return { onResume, isResuming };
164}