Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 type ModelSelection,
5 type ProviderInteractionMode,
6 type RuntimeMode,
7} from "@t3tools/contracts";
8import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 isAtomCommandInterrupted,
11 settlePromise,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import type {
16 EnvironmentProject,
17 EnvironmentThreadShell,
18} from "@t3tools/client-runtime/state/shell";
19import { scopedThreadKey } from "@t3tools/client-runtime/environment";
20import { truncate } from "@t3tools/shared/String";
21import { useNavigate } from "@tanstack/react-router";
22import type { Dispatch, SetStateAction } from "react";
23import { newMessageId, newThreadId } from "~/lib/utils";
24import { useComposerDraftStore } from "../../composerDraftStore";
25import type { ComposerHandleRef } from "../../composerHandleContext";
26import type { buildMessageContext } from "../../lib/composerContextRecords";
27import {
28 buildPlanImplementationPrompt,
29 buildPlanImplementationThreadTitle,
30} from "../../proposedPlan";
31import type { LatestProposedPlanState } from "../../session-logic";
32import { readEnvironmentScope } from "../../state/session";
33import { threadEnvironment } from "../../state/threads";
34import { useOrchestrationCommand } from "../../state/use-orchestration-command";
35import type { ChatMessage } from "../../types";
36import { stackedThreadToast, toastManager } from "../ui/toast";
37import {
38 formatOutgoingPrompt,
39 type makeThreadErrorSetter,
40 waitForStartedServerThread,
41} from "../ChatView.logic";
42import { draftSendState } from "./chatViewSend";
43import type { useLocalDispatchState } from "./useLocalDispatchState";
44import type { useTimelineFollow } from "./useTimelineFollow";
45
46type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
47
48interface PlanSendBase {
49 readonly environmentId: EnvironmentId;
50 readonly routeThreadKey: string;
51 readonly activeThread: EnvironmentThreadShell | undefined;
52 readonly activeThreadBranch: string | null;
53 readonly activeProposedPlan: LatestProposedPlanState | null;
54 readonly isServerThread: boolean;
55 readonly isSendBusy: boolean;
56 readonly isConnecting: boolean;
57 readonly composerRef: ComposerHandleRef;
58 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
59 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
60}
61
62interface PlanFollowUpSendInput extends PlanSendBase {
63 readonly runtimeMode: RuntimeMode;
64 readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null;
65 readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
66 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
67 readonly anchorNewTurn: ReturnType<typeof useTimelineFollow>["anchorNewTurn"];
68 readonly persistThreadSettingsForNextTurn: (input: {
69 threadId: EnvironmentThreadShell["id"];
70 createdAt: string;
71 branch?: string;
72 runtimeMode: RuntimeMode;
73 interactionMode: ProviderInteractionMode;
74 }) => Promise<AtomCommandResult<void, unknown>>;
75}
76
77/**
78 * Answers a proposed plan on this thread: refine it in plan mode, or implement it here
79 * (which links the turn to the plan). Resolves whether the turn started.
80 */
81export function usePlanFollowUpSend(input: PlanFollowUpSendInput) {
82 const {
83 environmentId,
84 routeThreadKey,
85 activeThread,
86 activeProposedPlan,
87 isServerThread,
88 isSendBusy,
89 isConnecting,
90 composerRef,
91 beginLocalDispatch,
92 resetLocalDispatch,
93 runtimeMode,
94 localCheckoutBranchMismatch,
95 setOptimisticUserMessages,
96 setThreadError,
97 anchorNewTurn,
98 persistThreadSettingsForNextTurn,
99 } = input;
100 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
101 reportFailure: false,
102 });
103 const setComposerDraftInteractionMode = useComposerDraftStore(
104 (store) => store.setInteractionMode,
105 );
106 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
107
108 return async function submitPlanFollowUp({
109 text,
110 context,
111 interactionMode: nextInteractionMode,
112 }: {
113 text: string;
114 context?: ReturnType<typeof buildMessageContext>;
115 interactionMode: "default" | "plan";
116 }) {
117 if (
118 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
119 !activeThread ||
120 !isServerThread ||
121 isSendBusy ||
122 isConnecting ||
123 sendInFlightRef.current
124 ) {
125 return false;
126 }
127
128 const trimmed = text.trim();
129 if (!trimmed) {
130 return false;
131 }
132
133 const sendCtx = composerRef.current?.getSendContext();
134 if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
135 return false;
136 }
137
138 const threadIdForSend = activeThread.id;
139 const messageIdForSend = newMessageId();
140 const messageCreatedAt = new Date().toISOString();
141 const outgoingMessageText = formatOutgoingPrompt({
142 provider: sendCtx.selectedProvider,
143 model: sendCtx.selectedModel,
144 models: sendCtx.selectedProviderModels,
145 effort: sendCtx.selectedPromptEffort,
146 text: trimmed,
147 });
148
149 sendInFlightRef.current = true;
150 beginLocalDispatch({ preparingWorktree: false });
151 setThreadError(threadIdForSend, null);
152
153 anchorNewTurn(
154 scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
155 messageIdForSend,
156 );
157
158 setOptimisticUserMessages((existing) => [
159 ...existing,
160 {
161 id: messageIdForSend,
162 role: "user",
163 text: outgoingMessageText,
164 ...(context ? { context } : {}),
165 runId: null,
166 createdAt: messageCreatedAt,
167 updatedAt: messageCreatedAt,
168 streaming: false,
169 },
170 ]);
171
172 const settingsResult = await persistThreadSettingsForNextTurn({
173 threadId: threadIdForSend,
174 createdAt: messageCreatedAt,
175 ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
176 runtimeMode,
177 interactionMode: nextInteractionMode,
178 });
179 let failure: AtomCommandResult<unknown, unknown> | null =
180 settingsResult._tag === "Failure" ? settingsResult : null;
181
182 if (failure === null) {
183 setComposerDraftInteractionMode(
184 scopeThreadRef(activeThread.environmentId, threadIdForSend),
185 nextInteractionMode,
186 );
187
188 const startResult = await startThreadTurn({
189 environmentId,
190 input: {
191 threadId: threadIdForSend,
192 message: {
193 messageId: messageIdForSend,
194 role: "user",
195 text: outgoingMessageText,
196 ...(context ? { context } : {}),
197 attachments: [],
198 },
199 modelSelection: sendCtx.selectedModelSelection,
200 titleSeed: activeThread.title,
201 runtimeMode,
202 interactionMode: nextInteractionMode,
203 ...(nextInteractionMode === "default" && activeProposedPlan
204 ? {
205 sourceProposedPlan: {
206 threadId: activeThread.id,
207 planId: activeProposedPlan.id,
208 },
209 }
210 : {}),
211 createdAt: messageCreatedAt,
212 },
213 });
214 failure = startResult._tag === "Failure" ? startResult : null;
215 }
216
217 if (failure === null) {
218 sendInFlightRef.current = false;
219 resetLocalDispatch();
220 return true;
221 }
222
223 setOptimisticUserMessages((existing) =>
224 existing.filter((message) => message.id !== messageIdForSend),
225 );
226 if (!isAtomCommandInterrupted(failure)) {
227 const error = squashAtomCommandFailure(failure);
228 setThreadError(
229 threadIdForSend,
230 error instanceof Error ? error.message : "Failed to send plan follow-up.",
231 );
232 }
233 sendInFlightRef.current = false;
234 resetLocalDispatch();
235 return false;
236 };
237}
238
239interface ImplementPlanInNewThreadInput extends PlanSendBase {
240 readonly activeProject: EnvironmentProject | null;
241 readonly activeEnvironmentUnavailable: boolean;
242 readonly defaultRuntimeMode: RuntimeMode;
243}
244
245/**
246 * Starts a fresh thread that implements the active proposed plan, then opens it. The new
247 * thread is deleted again if it cannot be started or opened.
248 */
249export function useImplementPlanInNewThread(input: ImplementPlanInNewThreadInput) {
250 const {
251 environmentId,
252 routeThreadKey,
253 activeThread,
254 activeThreadBranch,
255 activeProposedPlan,
256 isServerThread,
257 isSendBusy,
258 isConnecting,
259 composerRef,
260 beginLocalDispatch,
261 resetLocalDispatch,
262 activeProject,
263 activeEnvironmentUnavailable,
264 defaultRuntimeMode,
265 } = input;
266 const navigate = useNavigate();
267 const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
268 const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
269 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
270 reportFailure: false,
271 });
272 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
273
274 return async () => {
275 if (
276 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
277 !activeThread ||
278 !activeProject ||
279 !activeProposedPlan ||
280 !isServerThread ||
281 isSendBusy ||
282 isConnecting ||
283 activeEnvironmentUnavailable ||
284 sendInFlightRef.current
285 ) {
286 return;
287 }
288
289 const sendCtx = composerRef.current?.getSendContext();
290 if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
291 return;
292 }
293
294 const createdAt = new Date().toISOString();
295 const nextThreadId = newThreadId();
296 const planMarkdown = activeProposedPlan.planMarkdown;
297 const outgoingImplementationPrompt = formatOutgoingPrompt({
298 provider: sendCtx.selectedProvider,
299 model: sendCtx.selectedModel,
300 models: sendCtx.selectedProviderModels,
301 effort: sendCtx.selectedPromptEffort,
302 text: buildPlanImplementationPrompt(planMarkdown),
303 });
304 const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown));
305 const nextThreadModelSelection: ModelSelection = sendCtx.selectedModelSelection;
306
307 sendInFlightRef.current = true;
308 beginLocalDispatch({ preparingWorktree: false });
309
310 const createResult = await createThread({
311 environmentId,
312 input: {
313 threadId: nextThreadId,
314 projectId: activeProject.id,
315 title: nextThreadTitle,
316 modelSelection: nextThreadModelSelection,
317 runtimeMode: defaultRuntimeMode,
318 interactionMode: "default",
319 branch: activeThreadBranch,
320 worktreePath: activeThread.worktreePath,
321 createdAt,
322 },
323 });
324 let failure: AtomCommandResult<unknown, unknown> | null =
325 createResult._tag === "Failure" ? createResult : null;
326
327 if (failure === null) {
328 const startResult = await startThreadTurn({
329 environmentId,
330 input: {
331 threadId: nextThreadId,
332 message: {
333 messageId: newMessageId(),
334 role: "user",
335 text: outgoingImplementationPrompt,
336 attachments: [],
337 },
338 modelSelection: nextThreadModelSelection,
339 titleSeed: nextThreadTitle,
340 runtimeMode: defaultRuntimeMode,
341 interactionMode: "default",
342 sourceProposedPlan: {
343 threadId: activeThread.id,
344 planId: activeProposedPlan.id,
345 },
346 createdAt,
347 },
348 });
349 failure = startResult._tag === "Failure" ? startResult : null;
350 }
351
352 if (failure === null) {
353 const startedResult = await settlePromise(() =>
354 waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),
355 );
356 failure = startedResult._tag === "Failure" ? startedResult : null;
357 }
358
359 if (failure === null) {
360 const navigateResult = await settlePromise(() =>
361 navigate({
362 to: "/$environmentId/$threadId",
363 params: {
364 environmentId: activeThread.environmentId,
365 threadId: nextThreadId,
366 },
367 }),
368 );
369 failure = navigateResult._tag === "Failure" ? navigateResult : null;
370 }
371
372 if (failure !== null) {
373 const cleanupResult = await deleteThread({
374 environmentId,
375 input: {
376 threadId: nextThreadId,
377 },
378 });
379 if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) {
380 console.warn(
381 "Failed to clean up implementation thread after start failure.",
382 squashAtomCommandFailure(cleanupResult),
383 );
384 }
385 if (!isAtomCommandInterrupted(failure)) {
386 const error = squashAtomCommandFailure(failure);
387 toastManager.add(
388 stackedThreadToast({
389 type: "error",
390 title: "Could not start implementation thread",
391 description:
392 error instanceof Error
393 ? error.message
394 : "An error occurred while creating the new thread.",
395 }),
396 );
397 }
398 }
399 sendInFlightRef.current = false;
400 resetLocalDispatch();
401 };
402}