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

useProposedPlanSend.ts

397 lines12.7 KB

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