Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerResume.ts

167 lines5.9 KB

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 { DEFAULT_INTERACTION_MODE } from "../../types";
17import { threadEnvironment } from "../../state/threads";
18import { useOrchestrationCommand } from "../../state/use-orchestration-command";
19import type { makeThreadErrorSetter } from "../ChatView.logic";
20import { draftSendState } from "./chatViewSend";
21import type { useTimelineFollow } from "./useTimelineFollow";
22import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
23​
24interface ComposerResumeInput {
25 readonly environmentId: EnvironmentId;
26 readonly routeThreadKey: string;
27 readonly currentRouteThreadKeyRef: { readonly current: string | null };
28 readonly activeThread: EnvironmentThreadShell | undefined;
29 readonly resumableRunId: RunId | null;
30 readonly hasHeldQueuedRuns: boolean;
31 readonly canResume: boolean;
32 readonly isSendBusy: boolean;
33 readonly isRevertingCheckpoint: boolean;
34 readonly threadDetailLoading: boolean;
35 readonly activeEnvironmentUnavailable: boolean;
36 readonly runtimeMode: RuntimeMode;
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>;
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 */
55export function useComposerResume(input: ComposerResumeInput) {
56 const {
57 environmentId,
58 routeThreadKey,
59 currentRouteThreadKeyRef,
60 activeThread,
61 resumableRunId,
62 hasHeldQueuedRuns,
63 canResume,
64 isSendBusy,
65 isRevertingCheckpoint,
66 threadDetailLoading,
67 activeEnvironmentUnavailable,
68 runtimeMode,
69 localCheckoutBranchMismatch,
70 composerRef,
71 persistThreadSettingsForNextTurn,
72 clearUsageLimitsFor,
73 scrollToEnd,
74 setThreadError,
75 } = input;
76 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
77 reportFailure: false,
78 });
79 const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
80 reportFailure: false,
81 });
82 const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
83 () => new Set(),
84 );
85 const isResuming = resumingThreadKeys.has(routeThreadKey);
86 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
87​
88 const onResume = async () => {
89 if (
90 !activeThread ||
91 !canResume ||
92 isSendBusy ||
93 isResuming ||
94 isRevertingCheckpoint ||
95 threadDetailLoading ||
96 activeEnvironmentUnavailable ||
97 sendInFlightRef.current
98 ) {
99 return;
100 }
101 const threadId = activeThread.id;
102 sendInFlightRef.current = true;
103 setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
104 setThreadError(threadId, null);
105 // Commands settle into a result, so this always runs.
106 const resume = async () => {
107 if (resumableRunId === null) {
108 return resumeThreadQueue({ environmentId, input: { threadId } });
109 }
110 // Read before the first await: the composer follows the route, so after the user switches
111 // threads it holds the other thread's model.
112 const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
113 const createdAt = new Date().toISOString();
114 const settingsResult = await persistThreadSettingsForNextTurn({
115 threadId,
116 createdAt,
117 ...(localCheckoutBranchMismatch
118 ? { branch: localCheckoutBranchMismatch.currentBranch }
119 : {}),
120 runtimeMode,
121 interactionMode: DEFAULT_INTERACTION_MODE,
122 });
123 if (settingsResult._tag === "Failure") return settingsResult;
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: DEFAULT_INTERACTION_MODE,
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 };