@devries-cameron20 / t3code-1 / commits / 36d1e2fec5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(web): proposed-plan follow-ups and implement-in-new-thread live in their own hooks (#23091)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 14:25 UTC 36d1e2fec5881a19811c35c8a804c46c4ca2cea7
3 files changed +443 -295
apps/web/src/components/ChatView.tsx
+18 -2
@@ -16,6 +16,7 @@ import { useRightPanelActions } from "./chat/useRightPanelActions";
16 import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions";
17 import { useComposerSend } from "./chat/useComposerSend";
18 import { useComposerResume } from "./chat/useComposerResume";
19 +import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend";
20 import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
21 import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
22 import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
@@ -2945,7 +2946,23 @@ export default function ChatView(props: ChatViewProps) {
2946 scrollToEnd,
2947 setThreadError,
2948 });
2948 - const { onSend, onImplementPlanInNewThread } = useComposerSend({
2949 + const onImplementPlanInNewThread = useImplementPlanInNewThread({
2950 + environmentId,
2951 + routeThreadKey,
2952 + activeThread,
2953 + activeThreadBranch,
2954 + activeProposedPlan,
2955 + isServerThread,
2956 + isSendBusy,
2957 + isConnecting,
2958 + composerRef,
2959 + beginLocalDispatch,
2960 + resetLocalDispatch,
2961 + activeProject,
2962 + activeEnvironmentUnavailable,
2963 + defaultRuntimeMode,
2964 + });
2965 + const { onSend } = useComposerSend({
2966 environmentId,
2967 routeThreadKey,
2968 currentRouteThreadKeyRef,
@@ -2963,7 +2980,6 @@ export default function ChatView(props: ChatViewProps) {
2980 isGitRepo,
2981 phase,
2982 runtimeMode,
2966 - defaultRuntimeMode,
2983 sendEnvMode,
2984 startFromOrigin,
2985 localCheckoutBranchMismatch,
apps/web/src/components/chat/useComposerSend.ts
+23 -293
@@ -7,7 +7,6 @@ import {
7 deriveComposerSendState,
8 readFileAsDataUrl,
9 revokeUserMessagePreviewUrls,
10 - waitForStartedServerThread,
10 boundAttachmentIds,
11 formatOutgoingPrompt,
12 optimisticMessageAttachments,
@@ -42,7 +41,6 @@ import {
41 scopeThreadRef,
42 } from "@t3tools/client-runtime/environment";
43 import { createModelSelection } from "@t3tools/shared/model";
45 -import { truncate } from "@t3tools/shared/String";
44 import { type SetStateAction, useLayoutEffect, useRef } from "react";
45 import { flushSync } from "react-dom";
46 import { useNavigate } from "@tanstack/react-router";
@@ -57,11 +55,7 @@ import {
55 collapseExpandedComposerCursor,
56 parseStandaloneComposerSlashCommand,
57 } from "../../composer-logic";
60 -import {
61 - buildPlanImplementationThreadTitle,
62 - buildPlanImplementationPrompt,
63 - resolvePlanFollowUpSubmission,
64 -} from "../../proposedPlan";
58 +import { resolvePlanFollowUpSubmission } from "../../proposedPlan";
59 import { type ChatMessage } from "../../types";
60 import { stackedThreadToast, toastManager } from "../ui/toast";
61 import { newMessageId, newThreadId } from "~/lib/utils";
@@ -89,6 +83,7 @@ import {
83 import { environmentServerConfigsAtom } from "../../state/server";
84 import { threadEnvironment } from "../../state/threads";
85 import { runMobileComposerTransition } from "./draftHeroTransition";
86 +import { usePlanFollowUpSend } from "./useProposedPlanSend";
87 import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
88 import {
89 awaitAttachmentUploads,
@@ -163,7 +158,6 @@ interface ComposerSendInput {
158 readonly isGitRepo: boolean;
159 readonly phase: SessionPhase;
160 readonly runtimeMode: RuntimeMode;
166 - readonly defaultRuntimeMode: RuntimeMode;
161 readonly sendEnvMode: DraftThreadEnvMode;
162 readonly startFromOrigin: boolean;
163 readonly localCheckoutBranchMismatch: {
@@ -264,7 +258,6 @@ export function useComposerSend(input: ComposerSendInput) {
258 isGitRepo,
259 phase,
260 runtimeMode,
267 - defaultRuntimeMode,
261 sendEnvMode,
262 startFromOrigin,
263 localCheckoutBranchMismatch,
@@ -328,8 +321,6 @@ export function useComposerSend(input: ComposerSendInput) {
321 } = input;
322 const handleNewThread = useNewThreadHandler();
323 const navigate = useNavigate();
331 - const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
332 - const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
324 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
325 reportFailure: false,
326 });
@@ -345,10 +336,26 @@ export function useComposerSend(input: ComposerSendInput) {
336 );
337 const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);
338 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
348 - const setComposerDraftInteractionMode = useComposerDraftStore(
349 - (store) => store.setInteractionMode,
350 - );
339 const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
340 + const submitPlanFollowUp = usePlanFollowUpSend({
341 + environmentId,
342 + routeThreadKey,
343 + activeThread,
344 + activeThreadBranch,
345 + activeProposedPlan,
346 + isServerThread,
347 + isSendBusy,
348 + isConnecting,
349 + composerRef,
350 + beginLocalDispatch,
351 + resetLocalDispatch,
352 + runtimeMode,
353 + localCheckoutBranchMismatch,
354 + setOptimisticUserMessages,
355 + setThreadError,
356 + anchorNewTurn,
357 + persistThreadSettingsForNextTurn,
358 + });
359 const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
360 const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
361 const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
@@ -649,7 +656,7 @@ export function useComposerSend(input: ComposerSendInput) {
656 promptRef.current = "";
657 clearComposerDraftContent(composerDraftTarget);
658 composerRef.current?.resetCursorState();
652 - const followUpSent = await onSubmitPlanFollowUp({
659 + const followUpSent = await submitPlanFollowUp({
660 text: followUp.text,
661 context: buildMessageContext({
662 terminalContexts: sendableComposerTerminalContexts,
@@ -1542,282 +1549,5 @@ export function useComposerSend(input: ComposerSendInput) {
1549 }
1550 };
1551
1545 - async function onSubmitPlanFollowUp({
1546 - text,
1547 - context,
1548 - interactionMode: nextInteractionMode,
1549 - }: {
1550 - text: string;
1551 - context?: ReturnType<typeof buildMessageContext>;
1552 - interactionMode: "default" | "plan";
1553 - }) {
1554 - if (
1555 - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
1556 - !activeThread ||
1557 - !isServerThread ||
1558 - isSendBusy ||
1559 - isConnecting ||
1560 - sendInFlightRef.current
1561 - ) {
1562 - return false;
1563 - }
1564 -
1565 - const trimmed = text.trim();
1566 - if (!trimmed) {
1567 - return false;
1568 - }
1569 -
1570 - const sendCtx = composerRef.current?.getSendContext();
1571 - if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
1572 - return false;
1573 - }
1574 - const {
1575 - selectedProvider: ctxSelectedProvider,
1576 - selectedModel: ctxSelectedModel,
1577 - selectedProviderModels: ctxSelectedProviderModels,
1578 - selectedPromptEffort: ctxSelectedPromptEffort,
1579 - selectedModelSelection: ctxSelectedModelSelection,
1580 - } = sendCtx;
1581 -
1582 - const threadIdForSend = activeThread.id;
1583 - const messageIdForSend = newMessageId();
1584 - const messageCreatedAt = new Date().toISOString();
1585 - const outgoingMessageText = formatOutgoingPrompt({
1586 - provider: ctxSelectedProvider,
1587 - model: ctxSelectedModel,
1588 - models: ctxSelectedProviderModels,
1589 - effort: ctxSelectedPromptEffort,
1590 - text: trimmed,
1591 - });
1592 -
1593 - sendInFlightRef.current = true;
1594 - beginLocalDispatch({ preparingWorktree: false });
1595 - setThreadError(threadIdForSend, null);
1596 -
1597 - anchorNewTurn(
1598 - scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
1599 - messageIdForSend,
1600 - );
1601 -
1602 - setOptimisticUserMessages((existing) => [
1603 - ...existing,
1604 - {
1605 - id: messageIdForSend,
1606 - role: "user",
1607 - text: outgoingMessageText,
1608 - ...(context ? { context } : {}),
1609 - runId: null,
1610 - createdAt: messageCreatedAt,
1611 - updatedAt: messageCreatedAt,
1612 - streaming: false,
1613 - },
1614 - ]);
1615 -
1616 - const settingsResult = await persistThreadSettingsForNextTurn({
1617 - threadId: threadIdForSend,
1618 - createdAt: messageCreatedAt,
1619 - ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
1620 - runtimeMode,
1621 - interactionMode: nextInteractionMode,
1622 - });
1623 - let failure: AtomCommandResult<unknown, unknown> | null =
1624 - settingsResult._tag === "Failure" ? settingsResult : null;
1625 -
1626 - if (failure === null) {
1627 - setComposerDraftInteractionMode(
1628 - scopeThreadRef(activeThread.environmentId, threadIdForSend),
1629 - nextInteractionMode,
1630 - );
1631 -
1632 - const startResult = await startThreadTurn({
1633 - environmentId,
1634 - input: {
1635 - threadId: threadIdForSend,
1636 - message: {
1637 - messageId: messageIdForSend,
1638 - role: "user",
1639 - text: outgoingMessageText,
1640 - ...(context ? { context } : {}),
1641 - attachments: [],
1642 - },
1643 - modelSelection: ctxSelectedModelSelection,
1644 - titleSeed: activeThread.title,
1645 - runtimeMode,
1646 - interactionMode: nextInteractionMode,
1647 - ...(nextInteractionMode === "default" && activeProposedPlan
1648 - ? {
1649 - sourceProposedPlan: {
1650 - threadId: activeThread.id,
1651 - planId: activeProposedPlan.id,
1652 - },
1653 - }
1654 - : {}),
1655 - createdAt: messageCreatedAt,
1656 - },
1657 - });
1658 - failure = startResult._tag === "Failure" ? startResult : null;
1659 - }
1660 -
1661 - if (failure === null) {
1662 - sendInFlightRef.current = false;
1663 - resetLocalDispatch();
1664 - return true;
1665 - }
1666 -
1667 - setOptimisticUserMessages((existing) =>
1668 - existing.filter((message) => message.id !== messageIdForSend),
1669 - );
1670 - if (!isAtomCommandInterrupted(failure)) {
1671 - const error = squashAtomCommandFailure(failure);
1672 - setThreadError(
1673 - threadIdForSend,
1674 - error instanceof Error ? error.message : "Failed to send plan follow-up.",
1675 - );
1676 - }
1677 - sendInFlightRef.current = false;
1678 - resetLocalDispatch();
1679 - return false;
1680 - }
1681 -
1682 - const onImplementPlanInNewThread = async () => {
1683 - if (
1684 - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
1685 - !activeThread ||
1686 - !activeProject ||
1687 - !activeProposedPlan ||
1688 - !isServerThread ||
1689 - isSendBusy ||
1690 - isConnecting ||
1691 - activeEnvironmentUnavailable ||
1692 - sendInFlightRef.current
1693 - ) {
1694 - return;
1695 - }
1696 -
1697 - const sendCtx = composerRef.current?.getSendContext();
1698 - if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
1699 - return;
1700 - }
1701 - const {
1702 - selectedProvider: ctxSelectedProvider,
1703 - selectedModel: ctxSelectedModel,
1704 - selectedProviderModels: ctxSelectedProviderModels,
1705 - selectedPromptEffort: ctxSelectedPromptEffort,
1706 - selectedModelSelection: ctxSelectedModelSelection,
1707 - } = sendCtx;
1708 -
1709 - const createdAt = new Date().toISOString();
1710 - const nextThreadId = newThreadId();
1711 - const planMarkdown = activeProposedPlan.planMarkdown;
1712 - const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
1713 - const outgoingImplementationPrompt = formatOutgoingPrompt({
1714 - provider: ctxSelectedProvider,
1715 - model: ctxSelectedModel,
1716 - models: ctxSelectedProviderModels,
1717 - effort: ctxSelectedPromptEffort,
1718 - text: implementationPrompt,
1719 - });
1720 - const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown));
1721 - const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection;
1722 -
1723 - sendInFlightRef.current = true;
1724 - beginLocalDispatch({ preparingWorktree: false });
1725 - const finish = () => {
1726 - sendInFlightRef.current = false;
1727 - resetLocalDispatch();
1728 - };
1729 -
1730 - const createResult = await createThread({
1731 - environmentId,
1732 - input: {
1733 - threadId: nextThreadId,
1734 - projectId: activeProject.id,
1735 - title: nextThreadTitle,
1736 - modelSelection: nextThreadModelSelection,
1737 - runtimeMode: defaultRuntimeMode,
1738 - interactionMode: "default",
1739 - branch: activeThreadBranch,
1740 - worktreePath: activeThread.worktreePath,
1741 - createdAt,
1742 - },
1743 - });
1744 - let failure: AtomCommandResult<unknown, unknown> | null =
1745 - createResult._tag === "Failure" ? createResult : null;
1746 -
1747 - if (failure === null) {
1748 - const startResult = await startThreadTurn({
1749 - environmentId,
1750 - input: {
1751 - threadId: nextThreadId,
1752 - message: {
1753 - messageId: newMessageId(),
1754 - role: "user",
1755 - text: outgoingImplementationPrompt,
1756 - attachments: [],
1757 - },
1758 - modelSelection: ctxSelectedModelSelection,
1759 - titleSeed: nextThreadTitle,
1760 - runtimeMode: defaultRuntimeMode,
1761 - interactionMode: "default",
1762 - sourceProposedPlan: {
1763 - threadId: activeThread.id,
1764 - planId: activeProposedPlan.id,
1765 - },
1766 - createdAt,
1767 - },
1768 - });
1769 - failure = startResult._tag === "Failure" ? startResult : null;
1770 - }
1771 -
1772 - if (failure === null) {
1773 - const startedResult = await settlePromise(() =>
1774 - waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),
1775 - );
1776 - failure = startedResult._tag === "Failure" ? startedResult : null;
1777 - }
1778 -
1779 - if (failure === null) {
1780 - const navigateResult = await settlePromise(() =>
1781 - navigate({
1782 - to: "/$environmentId/$threadId",
1783 - params: {
1784 - environmentId: activeThread.environmentId,
1785 - threadId: nextThreadId,
1786 - },
1787 - }),
1788 - );
1789 - failure = navigateResult._tag === "Failure" ? navigateResult : null;
1790 - }
1791 -
1792 - if (failure !== null) {
1793 - const cleanupResult = await deleteThread({
1794 - environmentId,
1795 - input: {
1796 - threadId: nextThreadId,
1797 - },
1798 - });
1799 - if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) {
1800 - console.warn(
1801 - "Failed to clean up implementation thread after start failure.",
1802 - squashAtomCommandFailure(cleanupResult),
1803 - );
1804 - }
1805 - if (!isAtomCommandInterrupted(failure)) {
1806 - const error = squashAtomCommandFailure(failure);
1807 - toastManager.add(
1808 - stackedThreadToast({
1809 - type: "error",
1810 - title: "Could not start implementation thread",
1811 - description:
1812 - error instanceof Error
1813 - ? error.message
1814 - : "An error occurred while creating the new thread.",
1815 - }),
1816 - );
1817 - }
1818 - }
1819 - finish();
1820 - };
1821 -
1822 - return { onSend, onImplementPlanInNewThread };
1552 + return { onSend };
1553 }
apps/web/src/components/chat/useProposedPlanSend.ts new
+402
@@ -0,0 +1,402 @@
1 +import {
2 + AuthOrchestrationOperateScope,
3 + type EnvironmentId,
4 + type ModelSelection,
5 + type ProviderInteractionMode,
6 + type RuntimeMode,
7 +} from "@t3tools/contracts";
8 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9 +import {
10 + isAtomCommandInterrupted,
11 + settlePromise,
12 + squashAtomCommandFailure,
13 + type AtomCommandResult,
14 +} from "@t3tools/client-runtime/state/runtime";
15 +import type {
16 + EnvironmentProject,
17 + EnvironmentThreadShell,
18 +} from "@t3tools/client-runtime/state/shell";
19 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
20 +import { truncate } from "@t3tools/shared/String";
21 +import { useNavigate } from "@tanstack/react-router";
22 +import type { Dispatch, SetStateAction } from "react";
23 +import { newMessageId, newThreadId } from "~/lib/utils";
24 +import { useComposerDraftStore } from "../../composerDraftStore";
25 +import type { ComposerHandleRef } from "../../composerHandleContext";
26 +import type { buildMessageContext } from "../../lib/composerContextRecords";
27 +import {
28 + buildPlanImplementationPrompt,
29 + buildPlanImplementationThreadTitle,
30 +} from "../../proposedPlan";
31 +import type { LatestProposedPlanState } from "../../session-logic";
32 +import { readEnvironmentScope } from "../../state/session";
33 +import { threadEnvironment } from "../../state/threads";
34 +import { useOrchestrationCommand } from "../../state/use-orchestration-command";
35 +import type { ChatMessage } from "../../types";
36 +import { stackedThreadToast, toastManager } from "../ui/toast";
37 +import {
38 + formatOutgoingPrompt,
39 + type makeThreadErrorSetter,
40 + waitForStartedServerThread,
41 +} from "../ChatView.logic";
42 +import { draftSendState } from "./chatViewSend";
43 +import type { useLocalDispatchState } from "./useLocalDispatchState";
44 +import type { useTimelineFollow } from "./useTimelineFollow";
45 +
46 +type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
47 +
48 +interface 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 +
62 +interface 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 + */
81 +export 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 +
239 +interface 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 + */
249 +export 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 +}