diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 57bda9aa98c9b..ae5c020e2ea28 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -81,7 +81,11 @@ import { VideoPreviewModal, type VideoPreviewSource } from "../../components/Vid import { GlassSurface } from "../../components/ui/GlassSurface"; import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor"; import { fileRoutePathSegments } from "../files/filePath"; -import { ComposerActionButton, ComposerToolbarRow } from "../../components/ComposerToolbar"; +import { + ComposerActionButton, + ComposerInlineControl, + ComposerToolbarRow, +} from "../../components/ComposerToolbar"; import { ComposerModelControl } from "../../components/ComposerModelControl"; import { composerStripAttachments, @@ -254,6 +258,7 @@ export interface ThreadComposerProps { readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void; readonly canSwitchProvider: boolean; readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void; + readonly persistedInteractionMode?: ProviderInteractionMode; readonly onHeightChange?: (height: number) => void; readonly onEditorFocusChange?: (focused: boolean) => void; } @@ -539,6 +544,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps return report !== null; }; + const onUpdateInteractionMode = + selectedProviderStatus?.showInteractionModeToggle === false + ? undefined + : props.onUpdateInteractionMode; + const mentionableEnvironments = useMentionableEnvironments(); const composerMenu = useComposerCommandMenu({ draftMessage: draftMessage, @@ -558,10 +568,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps hasThread: !props.isDraft, hasCompactableConversation: props.hasCompactableConversation, onChangeDraftMessage: props.onChangeDraftMessage, - onUpdateInteractionMode: - selectedProviderStatus?.showInteractionModeToggle === false - ? undefined - : props.onUpdateInteractionMode, + onUpdateInteractionMode, offersUsageLimits: usageLimitsOffered, onUsageLimits: usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined, @@ -813,6 +820,31 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ); + // A thread already in Plan keeps the control with the Plan Mode setting off, so it can leave Plan. + const interactionMode = props.selectedThread.interactionMode; + const modeControl = + !props.isDraft && + props.persistedInteractionMode === "plan" && + onUpdateInteractionMode && + queuedEdit === null ? ( + onUpdateInteractionMode(interactionMode === "plan" ? "default" : "plan")} + showChevron={false} + /> + ) : null; + return ( props.onHeightChange?.(event.nativeEvent.layout.height)} @@ -1093,6 +1125,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined } > + {modeControl} {modelControl} void; readonly canSwitchThreadProvider: boolean; readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void; + readonly persistedInteractionMode?: ProviderInteractionMode; readonly onRespondToApproval: ApprovalResponder; readonly onSelectUserInputOption: ( requestId: RuntimeRequestId, @@ -1934,6 +1935,7 @@ function ThreadDetailBody( onShowUsageLimits={showUsageLimits} canSwitchProvider={props.canSwitchThreadProvider} onUpdateInteractionMode={props.onUpdateThreadInteractionMode} + persistedInteractionMode={props.persistedInteractionMode} onHeightChange={handleComposerHeightChange} onEditorFocusChange={handleOwnedInputFocusChange} /> diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 80a3e8643a567..4c4c9f43ac360 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -974,6 +974,7 @@ function ThreadRouteContent( } canOperateThread={canOperateThread} selectedThread={selectedThreadWithDraftSettings ?? selectedThread} + persistedInteractionMode={selectedThread.interactionMode} selectedThreadDetailRef={selectedThreadDetailRef} contentPresentation={contentPresentation} screenTone={connectionTone(routeConnectionState)} diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 2e772cc0998c0..2ddd9327824bd 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -39,6 +39,7 @@ import type { Thread } from "../types"; import { makeThreadFixture, makeThreadProjectionFixture } from "../test-fixtures"; import { getAntigravitySendBlockReason, + resolveComposerInteractionMode, resolveComposerProviderSelection, resolveWorktreeSetupProgress, peekRememberedThreadTimeline, @@ -670,6 +671,58 @@ describe("resolveComposerProviderSelection", () => { }); }); +describe("resolveComposerInteractionMode", () => { + const toggle = { showInteractionModeToggle: true }; + const hidden = { showInteractionModeToggle: false }; + it.each([ + { + name: "setting off, stale plan draft on a new thread", + on: false, + provider: toggle, + draft: "plan", + persisted: undefined, + enabled: false, + mode: "default", + }, + { + name: "setting off, persisted plan thread", + on: false, + provider: toggle, + draft: "plan", + persisted: "plan", + enabled: true, + mode: "plan", + }, + { + name: "setting off, persisted plan thread switched to default", + on: false, + provider: toggle, + draft: "default", + persisted: "plan", + enabled: true, + mode: "default", + }, + { + name: "setting off, persisted plan thread, provider hides the toggle", + on: false, + provider: hidden, + draft: "plan", + persisted: "plan", + enabled: false, + mode: "default", + }, + ] as const)("$name", ({ on, provider, draft, persisted, enabled, mode }) => { + expect( + resolveComposerInteractionMode({ + planModeEnabled: on, + provider, + interactionMode: draft, + persistedInteractionMode: persisted, + }), + ).toEqual({ enabled, interactionMode: mode }); + }); +}); + describe("checkout Git memory", () => { it("does not confuse an environment id containing the separator with a path", () => { rememberCheckoutIsRepo(EnvironmentId.make("env"), "a:b", false); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index d4b54a7e5a848..99a5e33670e95 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -543,9 +543,11 @@ export function resolveComposerInteractionMode(input: { planModeEnabled: boolean; provider: Pick | null | undefined; interactionMode: ProviderInteractionMode; + /** The server thread's mode. A thread already in plan keeps its mode controls so it can leave plan. */ + persistedInteractionMode: ProviderInteractionMode | undefined; }): { enabled: boolean; interactionMode: ProviderInteractionMode } { const enabled = - input.planModeEnabled && + (input.planModeEnabled || input.persistedInteractionMode === "plan") && input.provider != null && input.provider.showInteractionModeToggle !== false; return { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ff4a642b5c31d..294f392ac7534 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -28,7 +28,7 @@ import { useRightPanelActions } from "./chat/useRightPanelActions"; import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions"; import { useComposerSend } from "./chat/useComposerSend"; import { useComposerResume } from "./chat/useComposerResume"; -import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend"; +import { useImplementPlanInNewThread, useThreadInteractionMode } from "./chat/useProposedPlanSend"; import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider"; import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; @@ -797,6 +797,7 @@ export default function ChatView(props: ChatViewProps) { ) : undefined; const isServerThread = serverThread !== null; + const serverThreadInteractionMode = useThreadInteractionMode(serverThread); const activeThread = isServerThread ? serverThread : localDraftThread; const serverLatestRun = serverProjection === null ? null : deriveLatestThreadRun(serverProjection); @@ -1316,7 +1317,11 @@ export default function ChatView(props: ChatViewProps) { planModeEnabled: settings.planModeEnabled, provider: activeProviderStatus, interactionMode: - composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE, + composerInteractionMode ?? + serverThreadInteractionMode ?? + activeThread?.interactionMode ?? + DEFAULT_INTERACTION_MODE, + persistedInteractionMode: serverThreadInteractionMode, }); const conversationProviderStatus = providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ?? @@ -2926,6 +2931,7 @@ export default function ChatView(props: ChatViewProps) { draftId, draftThread, activeThread, + activeLatestRun, activeThreadKey, activeThreadBranch, activeProject, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index be106a251592e..af87df0b7beed 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -283,6 +283,7 @@ import { usePreparingComposerImages, } from "./preparingComposerImages"; import { ComposerControlsBar } from "./ComposerControlsBar"; +import { useThreadInteractionMode } from "./useProposedPlanSend"; import { composerCommandKeyHandler } from "./composerCommandKey"; function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -970,10 +971,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const selectedPromptEffort = composerProviderState.promptEffort; const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; + const activeThreadInteractionMode = useThreadInteractionMode(props.activeThreadShell); const { enabled: planModeUiEnabled, interactionMode } = resolveComposerInteractionMode({ planModeEnabled: settings.planModeEnabled, provider: selectedProviderStatus, interactionMode: requestedInteractionMode, + persistedInteractionMode: activeThreadInteractionMode, }); const selectedModelSelection: ModelSelection = createModelSelection( selectedInstanceId, diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index 81a00823a98be..658a74bf5eb37 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -325,6 +325,7 @@ export function resolveMultipleModelTargets(input: { planModeEnabled, provider: provider.snapshot, interactionMode: input.interactionMode, + persistedInteractionMode: undefined, }).interactionMode, }; }); diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 7e0b410134c5e..65315f3910db2 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -172,6 +172,7 @@ interface ComposerSendInput { readonly draftId: DraftId | null; readonly draftThread: DraftSessionState | null; readonly activeThread: EnvironmentThreadShell | undefined; + readonly activeLatestRun: EnvironmentThreadShell["latestRun"] | null; readonly activeThreadKey: string | null; readonly activeThreadBranch: string | null; readonly activeProject: EnvironmentProject | null; @@ -272,6 +273,7 @@ export function useComposerSend(input: ComposerSendInput) { draftId, draftThread, activeThread, + activeLatestRun, activeThreadKey, activeThreadBranch, activeProject, @@ -380,6 +382,7 @@ export function useComposerSend(input: ComposerSendInput) { environmentId, routeThreadKey, activeThread, + activeLatestRun, activeThreadBranch, activeProposedPlan, isServerThread, diff --git a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx new file mode 100644 index 0000000000000..bd3edcb7fd055 --- /dev/null +++ b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx @@ -0,0 +1,295 @@ +import { + CommandId, + EnvironmentId, + OrchestrationV2DispatchCommandError, + type ProviderInteractionMode, + ProviderInstanceId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; +import * as Cause from "effect/Cause"; +import { AsyncResult } from "effect/reactivity"; +import { RpcClientError } from "effect/rpc"; +import { expect, it, vi } from "vite-plus/test"; + +const state = vi.hoisted(() => ({ + startTurnErrors: [] as unknown[], + startTurnModes: [] as string[], + otherCommands: [] as string[], + settingsModes: [] as string[], +})); + +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + readEnvironmentScope: () => true, +})); + +vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({ + ...(await importOriginal()), + useOrchestrationCommand: ((command: { readonly label: string }) => + async ({ input }: { input: { interactionMode: string } }) => { + if (command.label.endsWith(":start-turn")) { + state.startTurnModes.push(input.interactionMode); + const error = state.startTurnErrors.shift(); + return error === undefined + ? AsyncResult.success(undefined) + : AsyncResult.failure(Cause.fail(error)); + } + state.otherCommands.push(command.label); + return AsyncResult.success(undefined); + }) as never, +})); + +import { render } from "../../../test/render"; +import { partializeComposerDraftStoreState, useComposerDraftStore } from "../../composerDraftStore"; +import { resolveComposerInteractionMode } from "../ChatView.logic"; +import { usePlanFollowUpSend, useThreadInteractionMode } from "./useProposedPlanSend"; + +const environmentId = EnvironmentId.make("environment:test"); +const threadId = ThreadId.make("thread:plan"); +const threadRef = scopeThreadRef(environmentId, threadId); + +const refused = new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:refused"), + commandType: "message.dispatch", + message: "Refused", +}); +const lost = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: "socket closed", + cause: new Error("socket closed"), + }), +}); + +function setup(startTurnErrors: unknown[]) { + state.startTurnErrors = startTurnErrors; + state.startTurnModes = []; + state.otherCommands = []; + state.settingsModes = []; + const store = useComposerDraftStore.getState(); + store.setInteractionMode(threadRef, null); + store.setFailedPlanFollowUpRunId(threadRef, undefined); +} + +function serverThread( + interactionMode: ProviderInteractionMode, + runId: RunId | null, +): EnvironmentThreadShell { + return { + id: threadId, + environmentId, + interactionMode, + title: "Plan", + latestRun: runId === null ? null : { runId }, + } as never; +} + +function persistedFailure() { + const persisted = JSON.parse( + JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), + ); + return persisted.draftsByThreadKey[scopedThreadKey(threadRef)]?.failedPlanFollowUpRunId; +} + +function PlanThread(props: { + readonly thread: ReturnType; + readonly onSettled: (sent: boolean) => void; + readonly detailRunId?: RunId | null; + readonly interactionMode?: "default" | "plan"; +}) { + const submitPlanFollowUp = usePlanFollowUpSend({ + environmentId, + routeThreadKey: scopedThreadKey(threadRef), + activeThread: props.thread, + activeLatestRun: + props.detailRunId === null + ? null + : ({ runId: props.detailRunId ?? props.thread.latestRun?.runId } as never), + activeThreadBranch: null, + activeProposedPlan: { id: "plan:1", planMarkdown: "# Plan" } as never, + isServerThread: true, + isSendBusy: false, + composerRef: { + current: { + getSendContext: () => ({ + providerAvailable: true, + interactionModeEnabled: true, + selectedProvider: "codex", + selectedModel: "gpt-5.5", + selectedProviderModels: [], + selectedPromptEffort: null, + selectedModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.5", + }, + }), + }, + } as never, + beginLocalDispatch: () => undefined, + resetLocalDispatch: () => undefined, + runtimeMode: "full-access", + localCheckoutBranchMismatch: null, + setOptimisticUserMessages: () => undefined, + setThreadError: () => undefined, + anchorNewTurn: () => undefined, + persistThreadSettingsForNextTurn: async ({ + interactionMode, + }): Promise> => { + state.settingsModes.push(interactionMode); + return AsyncResult.success(undefined); + }, + }); + const threadMode = useThreadInteractionMode(props.thread); + const draftMode = useComposerDraftStore( + (store) => store.getComposerDraft(threadRef)?.interactionMode ?? null, + ); + // Mirrors ChatView with the plan mode setting off. + const composer = resolveComposerInteractionMode({ + planModeEnabled: false, + provider: { showInteractionModeToggle: true }, + interactionMode: draftMode ?? threadMode ?? "default", + persistedInteractionMode: threadMode, + }); + return ( + <> + + + {composer.enabled ? composer.interactionMode : "controls hidden"} + + + ); +} + +function settlements() { + const queue: ((sent: boolean) => void)[] = []; + return { + onSettled: (sent: boolean) => queue.shift()?.(sent), + next: () => new Promise((resolve) => queue.push(resolve)), + }; +} + +it.each([ + { name: "refused by the server", planRunId: RunId.make("run:plan-refused"), error: refused }, + { name: "lost in transport", planRunId: RunId.make("run:plan-lost"), error: lost }, +])( + "an Implement send $name keeps the plan controls until another run starts, without writing the thread mode", + async ({ error, planRunId }) => { + setup([error]); + const send = settlements(); + await using screen = await render( + , + ); + const composerMode = screen.getByRole("status", { name: "composer mode" }); + + const settled = send.next(); + await screen.getByRole("button", { name: "Implement" }).click(); + expect(await settled).toBe(false); + + // The settings save already moved the server thread out of plan. + await screen.rerender( + , + ); + await expect.element(composerMode).toHaveTextContent("plan"); + expect(state.otherCommands).toEqual([]); + + expect(persistedFailure()).toBe(planRunId); + const persisted = JSON.parse( + JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), + ); + const merge = useComposerDraftStore.persist.getOptions().merge!; + useComposerDraftStore.setState(merge(persisted, useComposerDraftStore.getInitialState())); + await expect.element(composerMode).toHaveTextContent("plan"); + + // A run from this send or another client means the thread really left plan. + await screen.rerender( + , + ); + await expect.element(composerMode).toHaveTextContent("controls hidden"); + }, +); + +it("a refused Implement can be retried, and an accepted retry is not offered again", async () => { + const planRunId = RunId.make("run:plan-retry"); + setup([refused]); + const send = settlements(); + await using screen = await render( + , + ); + const implement = screen.getByRole("button", { name: "Implement" }); + + let settled = send.next(); + await implement.click(); + expect(await settled).toBe(false); + + // The first save moved the thread to default; recovery keeps Implement reachable. + await screen.rerender( + , + ); + settled = send.next(); + await implement.click(); + expect(await settled).toBe(true); + expect(state.startTurnModes).toEqual(["default", "default"]); + expect(persistedFailure()).toBeUndefined(); + // Before the accepted run reaches the shell, Implement must not be offered a second time. + await expect + .element(screen.getByRole("status", { name: "composer mode" })) + .toHaveTextContent("controls hidden"); +}); + +const detailPlanRunId = RunId.make("run:detail-plan"); +it.each([ + { name: "missing shell run", shellRunId: null, detailRunId: detailPlanRunId }, + { + name: "different shell run", + shellRunId: RunId.make("run:stale-shell"), + detailRunId: detailPlanRunId, + }, + { name: "missing detail run", shellRunId: detailPlanRunId, detailRunId: null }, +])("does not save Implement mode with a $name", async ({ shellRunId, detailRunId }) => { + setup([refused]); + const send = settlements(); + await using screen = await render( + , + ); + const settled = send.next(); + await screen.getByRole("button", { name: "Implement" }).click(); + expect(await settled).toBe(false); + expect(state.settingsModes).toEqual([]); +}); + +it("allows refinement while the shell run catches up", async () => { + setup([refused]); + const send = settlements(); + await using screen = await render( + , + ); + const settled = send.next(); + await screen.getByRole("button", { name: "Implement" }).click(); + expect(await settled).toBe(false); + expect(state.settingsModes).toEqual(["plan"]); +}); diff --git a/apps/web/src/components/chat/useProposedPlanSend.ts b/apps/web/src/components/chat/useProposedPlanSend.ts index eb945e3e056a4..15dc94dfab3e5 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -45,6 +45,22 @@ import type { useTimelineFollow } from "./useTimelineFollow"; type LocalDispatchState = ReturnType; +/** The thread's interaction mode, or plan while a failed Implement awaits a retry. */ +export function useThreadInteractionMode( + thread: EnvironmentThreadShell | null | undefined, +): ProviderInteractionMode | undefined { + const failedRunId = useComposerDraftStore((store) => + thread + ? store.getComposerDraft(scopeThreadRef(thread.environmentId, thread.id)) + ?.failedPlanFollowUpRunId + : undefined, + ); + if (!thread) return undefined; + return failedRunId !== undefined && failedRunId === thread.latestRun?.runId + ? "plan" + : thread.interactionMode; +} + interface PlanSendBase { readonly environmentId: EnvironmentId; readonly routeThreadKey: string; @@ -59,6 +75,7 @@ interface PlanSendBase { } interface PlanFollowUpSendInput extends PlanSendBase { + readonly activeLatestRun: EnvironmentThreadShell["latestRun"] | null; readonly runtimeMode: RuntimeMode; readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null; readonly setOptimisticUserMessages: Dispatch>; @@ -83,6 +100,7 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { routeThreadKey, activeThread, activeProposedPlan, + activeLatestRun, isServerThread, isSendBusy, composerRef, @@ -132,7 +150,18 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { return false; } + const implementing = nextInteractionMode === "default"; + const planRunId = activeThread.latestRun?.runId; + // The recovery marker keys on the shell run, the plan on the detail run: wait until they agree. + if (implementing && planRunId !== activeLatestRun?.runId) { + return false; + } + const threadIdForSend = activeThread.id; + const threadRefForSend = scopeThreadRef(activeThread.environmentId, threadIdForSend); + const previousDraftInteractionMode = useComposerDraftStore + .getState() + .getComposerDraft(threadRefForSend)?.interactionMode; const messageIdForSend = newMessageId(); const messageCreatedAt = new Date().toISOString(); const outgoingMessageText = formatOutgoingPrompt({ @@ -177,10 +206,7 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { settingsResult._tag === "Failure" ? settingsResult : null; if (failure === null) { - setComposerDraftInteractionMode( - scopeThreadRef(activeThread.environmentId, threadIdForSend), - nextInteractionMode, - ); + setComposerDraftInteractionMode(threadRefForSend, nextInteractionMode); const startResult = await startThreadTurn({ environmentId, @@ -209,14 +235,22 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { }, }); failure = startResult._tag === "Failure" ? startResult : null; + if (failure !== null) { + setComposerDraftInteractionMode(threadRefForSend, previousDraftInteractionMode); + } } if (failure === null) { + useComposerDraftStore.getState().setFailedPlanFollowUpRunId(threadRefForSend, undefined); sendInFlightRef.current = false; resetLocalDispatch(); return true; } + // No mode write-back: the failure may follow acceptance, and another client may have moved on. + if (implementing && planRunId !== undefined) { + useComposerDraftStore.getState().setFailedPlanFollowUpRunId(threadRefForSend, planRunId); + } setOptimisticUserMessages((existing) => existing.filter((message) => message.id !== messageIdForSend), ); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index aef9e88a38572..e4328307a93a2 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -19,6 +19,7 @@ import { PastedTextAttachmentSource, type PreviewAnnotationPayload, RuntimeMode, + RunId, ThreadContextRecord, EnvironmentContextRecord, type ServerProvider, @@ -103,6 +104,7 @@ import { UnifiedSettings } from "@t3tools/contracts/settings"; const isElementContextDetails = Schema.is(ElementContextDetails); import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext"; const isRuntimeMode = Schema.is(RuntimeMode); +const isRunId = Schema.is(RunId); const isProviderDriverKind = Schema.is(ProviderDriverKind); const isReviewCommentContext = Schema.is(ReviewCommentContextSchema); const isThreadContextRecord = Schema.is(ThreadContextRecord); @@ -253,6 +255,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({ modelSelectionExplicit: Schema.optionalKey(Schema.Boolean), runtimeMode: Schema.optionalKey(RuntimeMode), interactionMode: Schema.optionalKey(ProviderInteractionMode), + failedPlanFollowUpRunId: Schema.optionalKey(RunId), }); type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type; @@ -377,6 +380,8 @@ export interface ComposerThreadDraftState { modelSelectionExplicit?: boolean; runtimeMode: RuntimeMode | null; interactionMode: ProviderInteractionMode | null; + /** The run whose plan a failed Implement answered; the thread reads as plan until a newer run. */ + failedPlanFollowUpRunId?: RunId; } export function composerDraftHasUserContent( @@ -538,6 +543,7 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, interactionMode: ProviderInteractionMode | null | undefined, ) => void; + setFailedPlanFollowUpRunId: (threadRef: ScopedThreadRef, runId: RunId | undefined) => void; addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => boolean; addImages: ( threadRef: ComposerThreadTarget, @@ -882,7 +888,8 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean { Object.keys(draft.modelSelectionByProvider).length === 0 && draft.activeProvider === null && draft.runtimeMode === null && - draft.interactionMode === null + draft.interactionMode === null && + draft.failedPlanFollowUpRunId === undefined ); } @@ -1893,6 +1900,9 @@ function normalizePersistedDraftsByThreadId( draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default" ? draftCandidate.interactionMode : null; + const failedPlanFollowUpRunId = isRunId(draftCandidate.failedPlanFollowUpRunId) + ? draftCandidate.failedPlanFollowUpRunId + : undefined; const contextIds = new Map(); for (const [kind, entries] of [ ["image", attachments], @@ -1983,7 +1993,8 @@ function normalizePersistedDraftsByThreadId( environmentContexts.length === 0 && !hasModelData && !runtimeMode && - !interactionMode + !interactionMode && + failedPlanFollowUpRunId === undefined ) { continue; } @@ -2017,6 +2028,7 @@ function normalizePersistedDraftsByThreadId( : {}), ...(runtimeMode ? { runtimeMode } : {}), ...(interactionMode ? { interactionMode } : {}), + ...(failedPlanFollowUpRunId ? { failedPlanFollowUpRunId } : {}), }; } @@ -2114,7 +2126,8 @@ export function partializeComposerDraftStoreState( draft.environmentContexts.length === 0 && !hasModelData && draft.runtimeMode === null && - draft.interactionMode === null + draft.interactionMode === null && + draft.failedPlanFollowUpRunId === undefined ) { continue; } @@ -2181,6 +2194,9 @@ export function partializeComposerDraftStoreState( : {}), ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}), ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}), + ...(draft.failedPlanFollowUpRunId + ? { failedPlanFollowUpRunId: draft.failedPlanFollowUpRunId } + : {}), }; persistedDraftsByThreadKey[threadKey] = persistedDraft; } @@ -2450,6 +2466,9 @@ function toHydratedThreadDraft( ...(persistedDraft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}), runtimeMode: persistedDraft.runtimeMode ?? null, interactionMode: persistedDraft.interactionMode ?? null, + ...(persistedDraft.failedPlanFollowUpRunId + ? { failedPlanFollowUpRunId: persistedDraft.failedPlanFollowUpRunId } + : {}), }; } @@ -3226,6 +3245,25 @@ const composerDraftStore = create()( return { draftsByThreadKey: nextDraftsByThreadKey }; }); }, + setFailedPlanFollowUpRunId: (threadRef, runId) => { + const threadKey = resolveComposerDraftKey(get(), threadRef); + if (!threadKey) return; + set((state) => { + const existing = state.draftsByThreadKey[threadKey]; + if (existing?.failedPlanFollowUpRunId === runId) return state; + const { failedPlanFollowUpRunId: _previous, ...base } = + existing ?? createEmptyThreadDraft(); + const nextDraft: ComposerThreadDraftState = + runId === undefined ? base : { ...base, failedPlanFollowUpRunId: runId }; + const nextDraftsByThreadKey = { ...state.draftsByThreadKey }; + if (shouldRemoveDraft(nextDraft)) { + delete nextDraftsByThreadKey[threadKey]; + } else { + nextDraftsByThreadKey[threadKey] = nextDraft; + } + return { draftsByThreadKey: nextDraftsByThreadKey }; + }); + }, addImage: (threadRef, image) => { const threadKey = resolveComposerDraftKey(get(), threadRef); const threadId = resolveComposerThreadId(get(), threadRef);