From a28135afb147d93a16cd72701f0f71385eeddf96 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:51:58 +0000 Subject: [PATCH 1/8] fix: plan-mode threads keep a mode control when plan mode is off A thread an agent started in plan mode stayed in plan with no way out when the user's plan mode setting was off: web hid the mode control and Implement, and mobile showed no mode at all. Web now treats the server thread's own plan mode like the setting for that thread, so the mode control, Implement, slash commands and Shift+Tab return until a send moves it out of plan. New threads and drafts stay gated by the setting. Mobile shows a Build/Plan control in the composer for a thread already in plan, using the existing draft mode path that a send persists. Providers without the mode toggle keep it hidden on both. Fixes #29250 Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadComposer.tsx | 39 ++++++++- .../mobile/src/state/legacy-plan-mode.test.ts | 67 ++++++++++++++++ apps/mobile/src/state/legacy-plan-mode.ts | 18 +++++ .../web/src/components/ChatView.logic.test.ts | 80 +++++++++++++++++++ apps/web/src/components/ChatView.logic.ts | 4 +- apps/web/src/components/ChatView.tsx | 1 + apps/web/src/components/chat/ChatComposer.tsx | 1 + apps/web/src/components/chat/chatViewSend.ts | 1 + 8 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/src/state/legacy-plan-mode.test.ts diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 57bda9aa98c9b..97fc887e7aa5a 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -63,7 +63,9 @@ import { composerContextImportsAtom, countComposerDraftAttachmentsAfterSelection, useComposerDraft, + useComposerDraftSettings, } from "../../state/use-composer-drafts"; +import { resolvePlanThreadModeControl } from "../../state/legacy-plan-mode"; import { appAtomRegistry } from "../../state/atom-registry"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useVisibleThreadShells } from "../../state/entities"; @@ -81,7 +83,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, @@ -453,6 +459,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerDraftKey = props.draftKey ?? composerOwnerKey; const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey); + const draftInteractionMode = useComposerDraftSettings(composerOwnerKey).interactionMode; const queuedEdit = props.queuedEdit ?? null; const hasContent = draftMessage.trim().length > 0 || @@ -505,6 +512,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ) ?? null ); })(); + const planThreadMode = props.onUpdateInteractionMode + ? resolvePlanThreadModeControl({ + isDraft: props.isDraft === true, + persistedInteractionMode: props.selectedThread.interactionMode, + draftInteractionMode, + provider: selectedProviderStatus, + }) + : null; const openDraftDocument = (attachment: ComposerDocumentAttachment) => { Keyboard.dismiss(); navigation.navigate("ThreadAttachment", { @@ -813,6 +828,27 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ); + const modeControl = + planThreadMode !== null ? ( + + props.onUpdateInteractionMode?.(planThreadMode === "plan" ? "default" : "plan") + } + showChevron={false} + /> + ) : null; + return ( props.onHeightChange?.(event.nativeEvent.layout.height)} @@ -1093,6 +1129,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined } > + {modeControl} {modelControl} { + const toggle = { showInteractionModeToggle: true }; + const hidden = { showInteractionModeToggle: false }; + it.each([ + { + name: "persisted plan thread", + isDraft: false, + persisted: "plan", + draft: undefined, + provider: toggle, + expected: "plan", + }, + { + name: "persisted plan thread switched to Build", + isDraft: false, + persisted: "plan", + draft: "default", + provider: toggle, + expected: "default", + }, + { + name: "default thread with a stale plan draft", + isDraft: false, + persisted: "default", + draft: "plan", + provider: toggle, + expected: null, + }, + { + name: "new task draft in plan", + isDraft: true, + persisted: "plan", + draft: "plan", + provider: toggle, + expected: null, + }, + { + name: "provider hides the toggle", + isDraft: false, + persisted: "plan", + draft: undefined, + provider: hidden, + expected: null, + }, + { + name: "provider unknown", + isDraft: false, + persisted: "plan", + draft: undefined, + provider: null, + expected: null, + }, + ] as const)("$name", ({ isDraft, persisted, draft, provider, expected }) => { + expect( + resolvePlanThreadModeControl({ + isDraft, + persistedInteractionMode: persisted, + draftInteractionMode: draft, + provider, + }), + ).toBe(expected); + }); +}); diff --git a/apps/mobile/src/state/legacy-plan-mode.ts b/apps/mobile/src/state/legacy-plan-mode.ts index f4ab2f8c681c2..f5e9eda9fface 100644 --- a/apps/mobile/src/state/legacy-plan-mode.ts +++ b/apps/mobile/src/state/legacy-plan-mode.ts @@ -32,3 +32,21 @@ export function resolvePendingTaskInteractionMode(input: { } return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; } + +/** The Build/Plan control a thread already in plan keeps, so it can leave plan with the setting off. */ +export function resolvePlanThreadModeControl(input: { + readonly isDraft: boolean; + readonly persistedInteractionMode: ProviderInteractionMode; + readonly draftInteractionMode: ProviderInteractionMode | undefined; + readonly provider: InteractionModeProvider | null | undefined; +}): ProviderInteractionMode | null { + if ( + input.isDraft || + input.persistedInteractionMode !== "plan" || + input.provider == null || + input.provider.showInteractionModeToggle === false + ) { + return null; + } + return input.draftInteractionMode ?? input.persistedInteractionMode; +} diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 2e772cc0998c0..18702239e2e09 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,85 @@ describe("resolveComposerProviderSelection", () => { }); }); +describe("resolveComposerInteractionMode", () => { + const toggle = { showInteractionModeToggle: true }; + const hidden = { showInteractionModeToggle: false }; + it.each([ + { + name: "setting on, new draft in plan", + on: true, + provider: toggle, + draft: "plan", + persisted: undefined, + enabled: true, + mode: "plan", + }, + { + 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, plan draft on a default thread", + on: false, + provider: toggle, + draft: "plan", + persisted: "default", + 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", + }, + { + name: "setting off, persisted plan thread, provider unknown", + on: false, + provider: null, + 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 d49030e6f8877..56685a85ea71c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1316,6 +1316,7 @@ export default function ChatView(props: ChatViewProps) { provider: activeProviderStatus, interactionMode: composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE, + persistedInteractionMode: serverThread?.interactionMode, }); const conversationProviderStatus = providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ?? diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 69022a93fbeea..f25011ec2b1e2 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -974,6 +974,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) planModeEnabled: settings.planModeEnabled, provider: selectedProviderStatus, interactionMode: requestedInteractionMode, + persistedInteractionMode: props.activeThreadShell?.interactionMode, }); 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, }; }); From 05dea4ec72c8fc6a1098abccd3a1100eb3d0f33d Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:01:37 +0000 Subject: [PATCH 2/8] fix(mobile): retain the plan control while editing the draft --- .../src/features/threads/ThreadComposer.tsx | 18 ++++++++++-------- .../features/threads/ThreadDetailScreen.tsx | 2 ++ .../src/features/threads/ThreadRouteScreen.tsx | 1 + apps/mobile/src/state/legacy-plan-mode.ts | 2 +- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 97fc887e7aa5a..3c9175502dd0e 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -260,6 +260,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; } @@ -512,14 +513,15 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ) ?? null ); })(); - const planThreadMode = props.onUpdateInteractionMode - ? resolvePlanThreadModeControl({ - isDraft: props.isDraft === true, - persistedInteractionMode: props.selectedThread.interactionMode, - draftInteractionMode, - provider: selectedProviderStatus, - }) - : null; + const planThreadMode = + props.onUpdateInteractionMode && queuedEdit === null + ? resolvePlanThreadModeControl({ + isDraft: props.isDraft === true, + persistedInteractionMode: props.persistedInteractionMode, + draftInteractionMode, + provider: selectedProviderStatus, + }) + : null; const openDraftDocument = (attachment: ComposerDocumentAttachment) => { Keyboard.dismiss(); navigation.navigate("ThreadAttachment", { diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index f8d2e3b5c7698..b3e1c9d13a340 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -299,6 +299,7 @@ export interface ThreadDetailScreenProps { readonly onReconnectEnvironment: () => void; readonly canSwitchThreadProvider: boolean; readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void; + readonly persistedInteractionMode?: ProviderInteractionMode; readonly onRespondToApproval: ApprovalResponder; readonly onSelectUserInputOption: ( requestId: RuntimeRequestId, @@ -1906,6 +1907,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 62c1b039540de..7030ef2a79ad5 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -973,6 +973,7 @@ function ThreadRouteContent( } canOperateThread={canOperateThread} selectedThread={selectedThreadWithDraftSettings ?? selectedThread} + persistedInteractionMode={selectedThread.interactionMode} selectedThreadDetailRef={selectedThreadDetailRef} contentPresentation={contentPresentation} screenTone={connectionTone(routeConnectionState)} diff --git a/apps/mobile/src/state/legacy-plan-mode.ts b/apps/mobile/src/state/legacy-plan-mode.ts index f5e9eda9fface..e7fc452169fe5 100644 --- a/apps/mobile/src/state/legacy-plan-mode.ts +++ b/apps/mobile/src/state/legacy-plan-mode.ts @@ -36,7 +36,7 @@ export function resolvePendingTaskInteractionMode(input: { /** The Build/Plan control a thread already in plan keeps, so it can leave plan with the setting off. */ export function resolvePlanThreadModeControl(input: { readonly isDraft: boolean; - readonly persistedInteractionMode: ProviderInteractionMode; + readonly persistedInteractionMode: ProviderInteractionMode | undefined; readonly draftInteractionMode: ProviderInteractionMode | undefined; readonly provider: InteractionModeProvider | null | undefined; }): ProviderInteractionMode | null { From f27d650ef11ec198c49f61ba1ce2ddaf6dd99121 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:04:03 +0000 Subject: [PATCH 3/8] fix(web): a refused Implement keeps the plan ready to retry Implement moved the thread out of plan before sending. When the server refused the send, the thread stayed in Build with its plan still active, so with the plan mode setting off the Implement control disappeared and could not come back. When the server refuses the send, the composer and the thread return to the mode they had before, so Implement can be retried and still links the plan. A send lost in transport may have started the turn, so it is left alone. Co-Authored-By: Claude Opus 5.5 --- .../chat/useProposedPlanSend.browser.test.tsx | 137 ++++++++++++++++++ .../components/chat/useProposedPlanSend.ts | 33 ++++- 2 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx 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..76017bc395fa6 --- /dev/null +++ b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx @@ -0,0 +1,137 @@ +import { + CommandId, + EnvironmentId, + OrchestrationV2DispatchCommandError, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +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(() => ({ + startTurnError: null as unknown, + modeSets: [] as unknown[], +})); + +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 (value: { readonly input: unknown }) => { + if (command.label.endsWith(":start-turn")) { + return AsyncResult.failure(Cause.fail(state.startTurnError)); + } + if (command.label.endsWith(":set-interaction-mode")) state.modeSets.push(value.input); + return AsyncResult.success(undefined); + }) as never, +})); + +import { render } from "../../../test/render"; +import { useComposerDraftStore } from "../../composerDraftStore"; +import { usePlanFollowUpSend } from "./useProposedPlanSend"; + +const environmentId = EnvironmentId.make("environment:test"); +const threadId = ThreadId.make("thread:plan"); +const threadRef = scopeThreadRef(environmentId, threadId); + +function setup(startTurnError: unknown) { + state.startTurnError = startTurnError; + state.modeSets = []; + useComposerDraftStore.getState().setInteractionMode(threadRef, "plan"); +} + +function ImplementButton(props: { readonly onSettled: (sent: boolean) => void }) { + const submitPlanFollowUp = usePlanFollowUpSend({ + environmentId, + routeThreadKey: "environment:test:thread:plan", + activeThread: { id: threadId, environmentId, interactionMode: "plan", title: "Plan" } 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 (): Promise> => + AsyncResult.success(undefined), + }); + return ( + + ); +} + +it.each([ + { + name: "a refused send returns the thread to plan so Implement can be retried", + error: new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:refused"), + commandType: "message.dispatch", + message: "Refused", + }), + draftMode: "plan", + modeSets: [{ threadId, interactionMode: "plan" }], + }, + { + name: "a send lost in transport may have started, so the thread stays out of plan", + error: new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: "socket closed", + cause: new Error("socket closed"), + }), + }), + draftMode: "default", + modeSets: [], + }, +])("$name", async ({ error, draftMode, modeSets }) => { + setup(error); + let onSettled!: (sent: boolean) => void; + const settled = new Promise((resolve) => { + onSettled = resolve; + }); + await using screen = await render(); + + await screen.getByRole("button", { name: "Implement" }).click(); + + expect(await settled).toBe(false); + expect(useComposerDraftStore.getState().getComposerDraft(threadRef)?.interactionMode).toBe( + draftMode, + ); + expect(state.modeSets).toMatchObject(modeSets); +}); diff --git a/apps/web/src/components/chat/useProposedPlanSend.ts b/apps/web/src/components/chat/useProposedPlanSend.ts index eb945e3e056a4..92e5490f8862b 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -1,6 +1,7 @@ import { AuthOrchestrationOperateScope, type EnvironmentId, + OrchestrationV2DispatchCommandError, type ModelSelection, type ProviderInteractionMode, type RuntimeMode, @@ -19,6 +20,7 @@ import type { import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { truncate } from "@t3tools/shared/String"; import { useNavigate } from "@tanstack/react-router"; +import * as Schema from "effect/Schema"; import type { Dispatch, SetStateAction } from "react"; import { newMessageId, newThreadId } from "~/lib/utils"; import { useComposerDraftStore } from "../../composerDraftStore"; @@ -45,6 +47,9 @@ import type { useTimelineFollow } from "./useTimelineFollow"; type LocalDispatchState = ReturnType; +// The server answered and committed nothing; a transport failure may still have started the turn. +const isDispatchRefusal = Schema.is(OrchestrationV2DispatchCommandError); + interface PlanSendBase { readonly environmentId: EnvironmentId; readonly routeThreadKey: string; @@ -98,6 +103,9 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false, }); + const setThreadInteractionMode = useOrchestrationCommand(threadEnvironment.setInteractionMode, { + reportFailure: false, + }); const setComposerDraftInteractionMode = useComposerDraftStore( (store) => store.setInteractionMode, ); @@ -133,6 +141,11 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { } const threadIdForSend = activeThread.id; + const threadRefForSend = scopeThreadRef(activeThread.environmentId, threadIdForSend); + const previousInteractionMode = activeThread.interactionMode; + const previousDraftInteractionMode = useComposerDraftStore + .getState() + .getComposerDraft(threadRefForSend)?.interactionMode; const messageIdForSend = newMessageId(); const messageCreatedAt = new Date().toISOString(); const outgoingMessageText = formatOutgoingPrompt({ @@ -177,10 +190,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,6 +219,21 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { }, }); failure = startResult._tag === "Failure" ? startResult : null; + + // A thread left out of plan without a turn would hide Implement when the plan mode setting is off. + if (failure !== null && isDispatchRefusal(squashAtomCommandFailure(failure))) { + setComposerDraftInteractionMode(threadRefForSend, previousDraftInteractionMode); + if (previousInteractionMode !== nextInteractionMode) { + await setThreadInteractionMode({ + environmentId, + input: { + threadId: threadIdForSend, + interactionMode: previousInteractionMode, + createdAt: new Date().toISOString(), + }, + }); + } + } } if (failure === null) { From 2d68e2d992ab4cbb38a3cf473d102d8dfb29fee5 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:26:39 +0000 Subject: [PATCH 4/8] fix(web): a failed Implement keeps the plan controls without rewriting the thread mode The previous fix wrote the old mode back to the server after a typed dispatch error. That error does not prove the send was refused, the write could clobber a mode or turn another client chose in the meantime, and a failed write still lost the controls. Now nothing is written back. When a plan follow-up fails, this client remembers the thread's latest run and keeps treating the thread as in plan, so Implement and the mode control stay available for a retry. Once any run starts, from this send or another client, the thread shows its real mode again. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 10 +- apps/web/src/components/chat/ChatComposer.tsx | 4 +- .../chat/useProposedPlanSend.browser.test.tsx | 133 ++++++++++++------ .../components/chat/useProposedPlanSend.ts | 44 +++--- 4 files changed, 121 insertions(+), 70 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 56685a85ea71c..c82f967044d82 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"; @@ -796,6 +796,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); @@ -1315,8 +1316,11 @@ export default function ChatView(props: ChatViewProps) { planModeEnabled: settings.planModeEnabled, provider: activeProviderStatus, interactionMode: - composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE, - persistedInteractionMode: serverThread?.interactionMode, + composerInteractionMode ?? + serverThreadInteractionMode ?? + activeThread?.interactionMode ?? + DEFAULT_INTERACTION_MODE, + persistedInteractionMode: serverThreadInteractionMode, }); const conversationProviderStatus = providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ?? diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f25011ec2b1e2..6a826a113ee87 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,11 +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: props.activeThreadShell?.interactionMode, + persistedInteractionMode: activeThreadInteractionMode, }); const selectedModelSelection: ModelSelection = createModelSelection( selectedInstanceId, diff --git a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx index 76017bc395fa6..83733767fbb8d 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx +++ b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx @@ -2,7 +2,9 @@ import { CommandId, EnvironmentId, OrchestrationV2DispatchCommandError, + type ProviderInteractionMode, ProviderInstanceId, + RunId, ThreadId, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; @@ -14,7 +16,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ startTurnError: null as unknown, - modeSets: [] as unknown[], + otherCommands: [] as string[], })); vi.mock(import("../../state/session"), async (importOriginal) => ({ @@ -24,19 +26,19 @@ vi.mock(import("../../state/session"), async (importOriginal) => ({ vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({ ...(await importOriginal()), - useOrchestrationCommand: ((command: { readonly label: string }) => - async (value: { readonly input: unknown }) => { - if (command.label.endsWith(":start-turn")) { - return AsyncResult.failure(Cause.fail(state.startTurnError)); - } - if (command.label.endsWith(":set-interaction-mode")) state.modeSets.push(value.input); - return AsyncResult.success(undefined); - }) as never, + useOrchestrationCommand: ((command: { readonly label: string }) => async () => { + if (command.label.endsWith(":start-turn")) { + return AsyncResult.failure(Cause.fail(state.startTurnError)); + } + state.otherCommands.push(command.label); + return AsyncResult.success(undefined); + }) as never, })); import { render } from "../../../test/render"; import { useComposerDraftStore } from "../../composerDraftStore"; -import { usePlanFollowUpSend } from "./useProposedPlanSend"; +import { resolveComposerInteractionMode } from "../ChatView.logic"; +import { usePlanFollowUpSend, useThreadInteractionMode } from "./useProposedPlanSend"; const environmentId = EnvironmentId.make("environment:test"); const threadId = ThreadId.make("thread:plan"); @@ -44,15 +46,28 @@ const threadRef = scopeThreadRef(environmentId, threadId); function setup(startTurnError: unknown) { state.startTurnError = startTurnError; - state.modeSets = []; - useComposerDraftStore.getState().setInteractionMode(threadRef, "plan"); + state.otherCommands = []; + useComposerDraftStore.getState().setInteractionMode(threadRef, null); } -function ImplementButton(props: { readonly onSettled: (sent: boolean) => void }) { +function serverThread(interactionMode: ProviderInteractionMode, runId: RunId) { + return { + id: threadId, + environmentId, + interactionMode, + title: "Plan", + latestRun: { runId }, + } as never; +} + +function PlanThread(props: { + readonly thread: ReturnType; + readonly onSettled: (sent: boolean) => void; +}) { const submitPlanFollowUp = usePlanFollowUpSend({ environmentId, - routeThreadKey: "environment:test:thread:plan", - activeThread: { id: threadId, environmentId, interactionMode: "plan", title: "Plan" } as never, + routeThreadKey: `${threadRef.environmentId}:${threadRef.threadId}`, + activeThread: props.thread, activeThreadBranch: null, activeProposedPlan: { id: "plan:1", planMarkdown: "# Plan" } as never, isServerThread: true, @@ -83,55 +98,83 @@ function ImplementButton(props: { readonly onSettled: (sent: boolean) => void }) persistThreadSettingsForNextTurn: async (): Promise> => 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"} + + ); } it.each([ { - name: "a refused send returns the thread to plan so Implement can be retried", + name: "refused by the server", + planRunId: RunId.make("run:plan-refused"), error: new OrchestrationV2DispatchCommandError({ commandId: CommandId.make("command:refused"), commandType: "message.dispatch", message: "Refused", }), - draftMode: "plan", - modeSets: [{ threadId, interactionMode: "plan" }], }, { - name: "a send lost in transport may have started, so the thread stays out of plan", + name: "lost in transport", + planRunId: RunId.make("run:plan-lost"), error: new RpcClientError.RpcClientError({ reason: new RpcClientError.RpcClientDefect({ message: "socket closed", cause: new Error("socket closed"), }), }), - draftMode: "default", - modeSets: [], }, -])("$name", async ({ error, draftMode, modeSets }) => { - setup(error); - let onSettled!: (sent: boolean) => void; - const settled = new Promise((resolve) => { - onSettled = resolve; - }); - await using screen = await render(); +])( + "an Implement send $name keeps the plan controls until another run starts, without writing the thread mode", + async ({ error, planRunId }) => { + setup(error); + let onSettled!: (sent: boolean) => void; + const settled = new Promise((resolve) => { + onSettled = resolve; + }); + await using screen = await render( + , + ); + const composerMode = screen.getByRole("status", { name: "composer mode" }); - await screen.getByRole("button", { name: "Implement" }).click(); + await screen.getByRole("button", { name: "Implement" }).click(); + expect(await settled).toBe(false); - expect(await settled).toBe(false); - expect(useComposerDraftStore.getState().getComposerDraft(threadRef)?.interactionMode).toBe( - draftMode, - ); - expect(state.modeSets).toMatchObject(modeSets); -}); + // The settings save already moved the server thread out of plan. + await screen.rerender( + , + ); + await expect.element(composerMode).toHaveTextContent("plan"); + expect(state.otherCommands).toEqual([]); + + // A run from this send or another client means the thread really left plan. + await screen.rerender( + , + ); + await expect.element(composerMode).toHaveTextContent("controls hidden"); + }, +); diff --git a/apps/web/src/components/chat/useProposedPlanSend.ts b/apps/web/src/components/chat/useProposedPlanSend.ts index 92e5490f8862b..6ed298d296fb0 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -1,9 +1,9 @@ import { AuthOrchestrationOperateScope, type EnvironmentId, - OrchestrationV2DispatchCommandError, type ModelSelection, type ProviderInteractionMode, + type RunId, type RuntimeMode, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; @@ -20,8 +20,8 @@ import type { import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { truncate } from "@t3tools/shared/String"; import { useNavigate } from "@tanstack/react-router"; -import * as Schema from "effect/Schema"; import type { Dispatch, SetStateAction } from "react"; +import { create } from "zustand"; import { newMessageId, newThreadId } from "~/lib/utils"; import { useComposerDraftStore } from "../../composerDraftStore"; import type { ComposerHandleRef } from "../../composerHandleContext"; @@ -47,8 +47,22 @@ import type { useTimelineFollow } from "./useTimelineFollow"; type LocalDispatchState = ReturnType; -// The server answered and committed nothing; a transport failure may still have started the turn. -const isDispatchRefusal = Schema.is(OrchestrationV2DispatchCommandError); +// The latest run of each thread whose plan follow-up failed. The server may have left plan +// without a turn, so the thread keeps its plan controls until another run starts. +const useFailedPlanFollowUpRuns = create>>()(() => ({})); + +/** The thread's interaction mode, or plan while a failed plan follow-up awaits a retry. */ +export function useThreadInteractionMode( + thread: EnvironmentThreadShell | null | undefined, +): ProviderInteractionMode | undefined { + const failedRunId = useFailedPlanFollowUpRuns((runs) => + thread ? runs[scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))] : undefined, + ); + if (!thread) return undefined; + return failedRunId !== undefined && failedRunId === thread.latestRun?.runId + ? "plan" + : thread.interactionMode; +} interface PlanSendBase { readonly environmentId: EnvironmentId; @@ -103,9 +117,6 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false, }); - const setThreadInteractionMode = useOrchestrationCommand(threadEnvironment.setInteractionMode, { - reportFailure: false, - }); const setComposerDraftInteractionMode = useComposerDraftStore( (store) => store.setInteractionMode, ); @@ -142,7 +153,6 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { const threadIdForSend = activeThread.id; const threadRefForSend = scopeThreadRef(activeThread.environmentId, threadIdForSend); - const previousInteractionMode = activeThread.interactionMode; const previousDraftInteractionMode = useComposerDraftStore .getState() .getComposerDraft(threadRefForSend)?.interactionMode; @@ -219,20 +229,8 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { }, }); failure = startResult._tag === "Failure" ? startResult : null; - - // A thread left out of plan without a turn would hide Implement when the plan mode setting is off. - if (failure !== null && isDispatchRefusal(squashAtomCommandFailure(failure))) { + if (failure !== null) { setComposerDraftInteractionMode(threadRefForSend, previousDraftInteractionMode); - if (previousInteractionMode !== nextInteractionMode) { - await setThreadInteractionMode({ - environmentId, - input: { - threadId: threadIdForSend, - interactionMode: previousInteractionMode, - createdAt: new Date().toISOString(), - }, - }); - } } } @@ -242,6 +240,10 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { return true; } + const failedRunId = activeThread.latestRun?.runId; + if (failedRunId !== undefined) { + useFailedPlanFollowUpRuns.setState({ [scopedThreadKey(threadRefForSend)]: failedRunId }); + } setOptimisticUserMessages((existing) => existing.filter((message) => message.id !== messageIdForSend), ); From 796e976051467a4d4af485f00f339d27754e8ef6 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:41:33 +0000 Subject: [PATCH 5/8] fix(web): preserve failed plan recovery across reloads Keep the failed follow-up run in the existing persisted composer draft, so reopening the client preserves Implement recovery. A newer run still invalidates the override without changing server state. --- .../chat/useProposedPlanSend.browser.test.tsx | 15 +++++++- .../components/chat/useProposedPlanSend.ts | 15 +++----- apps/web/src/composerDraftStore.ts | 38 +++++++++++++++++-- 3 files changed, 54 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx index 83733767fbb8d..7c7fd60167c11 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx +++ b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx @@ -7,7 +7,7 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; @@ -36,7 +36,7 @@ vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) })); import { render } from "../../../test/render"; -import { useComposerDraftStore } from "../../composerDraftStore"; +import { partializeComposerDraftStoreState, useComposerDraftStore } from "../../composerDraftStore"; import { resolveComposerInteractionMode } from "../ChatView.logic"; import { usePlanFollowUpSend, useThreadInteractionMode } from "./useProposedPlanSend"; @@ -171,6 +171,17 @@ it.each([ await expect.element(composerMode).toHaveTextContent("plan"); expect(state.otherCommands).toEqual([]); + const persisted = JSON.parse( + JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), + ); + expect(persisted.draftsByThreadKey[scopedThreadKey(threadRef)]).toHaveProperty( + "failedPlanFollowUpRunId", + planRunId, + ); + 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( , diff --git a/apps/web/src/components/chat/useProposedPlanSend.ts b/apps/web/src/components/chat/useProposedPlanSend.ts index 6ed298d296fb0..a9f1e226c7fbb 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -3,7 +3,6 @@ import { type EnvironmentId, type ModelSelection, type ProviderInteractionMode, - type RunId, type RuntimeMode, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; @@ -21,7 +20,6 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { truncate } from "@t3tools/shared/String"; import { useNavigate } from "@tanstack/react-router"; import type { Dispatch, SetStateAction } from "react"; -import { create } from "zustand"; import { newMessageId, newThreadId } from "~/lib/utils"; import { useComposerDraftStore } from "../../composerDraftStore"; import type { ComposerHandleRef } from "../../composerHandleContext"; @@ -47,16 +45,15 @@ import type { useTimelineFollow } from "./useTimelineFollow"; type LocalDispatchState = ReturnType; -// The latest run of each thread whose plan follow-up failed. The server may have left plan -// without a turn, so the thread keeps its plan controls until another run starts. -const useFailedPlanFollowUpRuns = create>>()(() => ({})); - /** The thread's interaction mode, or plan while a failed plan follow-up awaits a retry. */ export function useThreadInteractionMode( thread: EnvironmentThreadShell | null | undefined, ): ProviderInteractionMode | undefined { - const failedRunId = useFailedPlanFollowUpRuns((runs) => - thread ? runs[scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))] : 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 @@ -242,7 +239,7 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { const failedRunId = activeThread.latestRun?.runId; if (failedRunId !== undefined) { - useFailedPlanFollowUpRuns.setState({ [scopedThreadKey(threadRefForSend)]: failedRunId }); + useComposerDraftStore.getState().setFailedPlanFollowUpRunId(threadRefForSend, failedRunId); } setOptimisticUserMessages((existing) => existing.filter((message) => message.id !== messageIdForSend), diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index aef9e88a38572..3bc41e7e0c7ad 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,7 @@ export interface ComposerThreadDraftState { modelSelectionExplicit?: boolean; runtimeMode: RuntimeMode | null; interactionMode: ProviderInteractionMode | null; + failedPlanFollowUpRunId?: RunId; } export function composerDraftHasUserContent( @@ -538,6 +542,7 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, interactionMode: ProviderInteractionMode | null | undefined, ) => void; + setFailedPlanFollowUpRunId: (threadRef: ScopedThreadRef, runId: RunId) => void; addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => boolean; addImages: ( threadRef: ComposerThreadTarget, @@ -882,7 +887,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 +1899,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 +1992,8 @@ function normalizePersistedDraftsByThreadId( environmentContexts.length === 0 && !hasModelData && !runtimeMode && - !interactionMode + !interactionMode && + failedPlanFollowUpRunId === undefined ) { continue; } @@ -2017,6 +2027,7 @@ function normalizePersistedDraftsByThreadId( : {}), ...(runtimeMode ? { runtimeMode } : {}), ...(interactionMode ? { interactionMode } : {}), + ...(failedPlanFollowUpRunId ? { failedPlanFollowUpRunId } : {}), }; } @@ -2114,7 +2125,8 @@ export function partializeComposerDraftStoreState( draft.environmentContexts.length === 0 && !hasModelData && draft.runtimeMode === null && - draft.interactionMode === null + draft.interactionMode === null && + draft.failedPlanFollowUpRunId === undefined ) { continue; } @@ -2181,6 +2193,9 @@ export function partializeComposerDraftStoreState( : {}), ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}), ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}), + ...(draft.failedPlanFollowUpRunId + ? { failedPlanFollowUpRunId: draft.failedPlanFollowUpRunId } + : {}), }; persistedDraftsByThreadKey[threadKey] = persistedDraft; } @@ -2450,6 +2465,9 @@ function toHydratedThreadDraft( ...(persistedDraft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}), runtimeMode: persistedDraft.runtimeMode ?? null, interactionMode: persistedDraft.interactionMode ?? null, + ...(persistedDraft.failedPlanFollowUpRunId + ? { failedPlanFollowUpRunId: persistedDraft.failedPlanFollowUpRunId } + : {}), }; } @@ -3226,6 +3244,20 @@ const composerDraftStore = create()( return { draftsByThreadKey: nextDraftsByThreadKey }; }); }, + setFailedPlanFollowUpRunId: (threadRef, runId) => { + const threadKey = resolveComposerDraftKey(get(), threadRef); + if (!threadKey) return; + set((state) => { + const base = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft(); + if (base.failedPlanFollowUpRunId === runId) return state; + return { + draftsByThreadKey: { + ...state.draftsByThreadKey, + [threadKey]: { ...base, failedPlanFollowUpRunId: runId }, + }, + }; + }); + }, addImage: (threadRef, image) => { const threadKey = resolveComposerDraftKey(get(), threadRef); const threadId = resolveComposerThreadId(get(), threadRef); From 3f85092889437a358c489cef58720234d98545eb Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:45:07 +0000 Subject: [PATCH 6/8] fix(web): wait for plan run agreement before Implement --- apps/web/src/components/ChatView.tsx | 1 + .../src/components/chat/useComposerSend.ts | 3 + .../chat/useProposedPlanSend.browser.test.tsx | 77 +++++++++++++++++-- .../components/chat/useProposedPlanSend.ts | 9 +++ 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c82f967044d82..998208aaf40e2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2920,6 +2920,7 @@ export default function ChatView(props: ChatViewProps) { draftId, draftThread, activeThread, + activeLatestRun, activeThreadKey, activeThreadBranch, activeProject, 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 index 7c7fd60167c11..78b3370802bfc 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx +++ b/apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx @@ -8,6 +8,7 @@ import { 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"; @@ -17,6 +18,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ startTurnError: null as unknown, otherCommands: [] as string[], + settingsModes: [] as string[], })); vi.mock(import("../../state/session"), async (importOriginal) => ({ @@ -47,27 +49,37 @@ const threadRef = scopeThreadRef(environmentId, threadId); function setup(startTurnError: unknown) { state.startTurnError = startTurnError; state.otherCommands = []; + state.settingsModes = []; useComposerDraftStore.getState().setInteractionMode(threadRef, null); } -function serverThread(interactionMode: ProviderInteractionMode, runId: RunId) { +function serverThread( + interactionMode: ProviderInteractionMode, + runId: RunId | null, +): EnvironmentThreadShell { return { id: threadId, environmentId, interactionMode, title: "Plan", - latestRun: { runId }, + latestRun: runId === null ? null : { runId }, } as never; } function PlanThread(props: { readonly thread: ReturnType; readonly onSettled: (sent: boolean) => void; + readonly detailRunId?: RunId | null; + readonly interactionMode?: "default" | "plan"; }) { const submitPlanFollowUp = usePlanFollowUpSend({ environmentId, routeThreadKey: `${threadRef.environmentId}:${threadRef.threadId}`, 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, @@ -95,8 +107,12 @@ function PlanThread(props: { setOptimisticUserMessages: () => undefined, setThreadError: () => undefined, anchorNewTurn: () => undefined, - persistThreadSettingsForNextTurn: async (): Promise> => - AsyncResult.success(undefined), + persistThreadSettingsForNextTurn: async ({ + interactionMode, + }): Promise> => { + state.settingsModes.push(interactionMode); + return AsyncResult.success(undefined); + }, }); const threadMode = useThreadInteractionMode(props.thread); const draftMode = useComposerDraftStore( @@ -114,9 +130,10 @@ function PlanThread(props: { - - {composer.enabled ? composer.interactionMode : "controls hidden"} - - - ); -} - -it.each([ - { - name: "refused by the server", - planRunId: RunId.make("run:plan-refused"), - error: new OrchestrationV2DispatchCommandError({ - commandId: CommandId.make("command:refused"), - commandType: "message.dispatch", - message: "Refused", - }), - }, - { - name: "lost in transport", - planRunId: RunId.make("run:plan-lost"), - error: new RpcClientError.RpcClientError({ - reason: new RpcClientError.RpcClientDefect({ - message: "socket closed", - cause: new Error("socket closed"), - }), - }), - }, -])( - "an Implement send $name keeps the plan controls until another run starts, without writing the thread mode", - async ({ error, planRunId }) => { - setup(error); - let onSettled!: (sent: boolean) => void; - const settled = new Promise((resolve) => { - onSettled = resolve; - }); - await using screen = await render( - , - ); - const composerMode = screen.getByRole("status", { name: "composer mode" }); - - 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([]); - - const persisted = JSON.parse( - JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), - ); - expect(persisted.draftsByThreadKey[scopedThreadKey(threadRef)]).toHaveProperty( - "failedPlanFollowUpRunId", - planRunId, - ); - 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"); - }, -); - -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(new Error("Refused")); - let onSettled!: (sent: boolean) => void; - const settled = new Promise((resolve) => { - onSettled = resolve; - }); - await using screen = await render( - , - ); - 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(new Error("Refused")); - let onSettled!: (sent: boolean) => void; - const settled = new Promise((resolve) => { - onSettled = resolve; - }); - await using screen = await render( - , - ); - 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 3683e361e4fbd..eb945e3e056a4 100644 --- a/apps/web/src/components/chat/useProposedPlanSend.ts +++ b/apps/web/src/components/chat/useProposedPlanSend.ts @@ -45,22 +45,6 @@ import type { useTimelineFollow } from "./useTimelineFollow"; type LocalDispatchState = ReturnType; -/** The thread's interaction mode, or plan while a failed plan follow-up 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; @@ -75,7 +59,6 @@ interface PlanSendBase { } interface PlanFollowUpSendInput extends PlanSendBase { - readonly activeLatestRun: EnvironmentThreadShell["latestRun"] | null; readonly runtimeMode: RuntimeMode; readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null; readonly setOptimisticUserMessages: Dispatch>; @@ -100,7 +83,6 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { routeThreadKey, activeThread, activeProposedPlan, - activeLatestRun, isServerThread, isSendBusy, composerRef, @@ -150,18 +132,7 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { return false; } - if ( - nextInteractionMode === "default" && - activeThread.latestRun?.runId !== 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({ @@ -206,7 +177,10 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { settingsResult._tag === "Failure" ? settingsResult : null; if (failure === null) { - setComposerDraftInteractionMode(threadRefForSend, nextInteractionMode); + setComposerDraftInteractionMode( + scopeThreadRef(activeThread.environmentId, threadIdForSend), + nextInteractionMode, + ); const startResult = await startThreadTurn({ environmentId, @@ -235,9 +209,6 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { }, }); failure = startResult._tag === "Failure" ? startResult : null; - if (failure !== null) { - setComposerDraftInteractionMode(threadRefForSend, previousDraftInteractionMode); - } } if (failure === null) { @@ -246,10 +217,6 @@ export function usePlanFollowUpSend(input: PlanFollowUpSendInput) { return true; } - const failedRunId = activeThread.latestRun?.runId; - if (failedRunId !== undefined) { - useComposerDraftStore.getState().setFailedPlanFollowUpRunId(threadRefForSend, failedRunId); - } setOptimisticUserMessages((existing) => existing.filter((message) => message.id !== messageIdForSend), ); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 3bc41e7e0c7ad..aef9e88a38572 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -19,7 +19,6 @@ import { PastedTextAttachmentSource, type PreviewAnnotationPayload, RuntimeMode, - RunId, ThreadContextRecord, EnvironmentContextRecord, type ServerProvider, @@ -104,7 +103,6 @@ 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); @@ -255,7 +253,6 @@ 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; @@ -380,7 +377,6 @@ export interface ComposerThreadDraftState { modelSelectionExplicit?: boolean; runtimeMode: RuntimeMode | null; interactionMode: ProviderInteractionMode | null; - failedPlanFollowUpRunId?: RunId; } export function composerDraftHasUserContent( @@ -542,7 +538,6 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, interactionMode: ProviderInteractionMode | null | undefined, ) => void; - setFailedPlanFollowUpRunId: (threadRef: ScopedThreadRef, runId: RunId) => void; addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => boolean; addImages: ( threadRef: ComposerThreadTarget, @@ -887,8 +882,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean { Object.keys(draft.modelSelectionByProvider).length === 0 && draft.activeProvider === null && draft.runtimeMode === null && - draft.interactionMode === null && - draft.failedPlanFollowUpRunId === undefined + draft.interactionMode === null ); } @@ -1899,9 +1893,6 @@ 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], @@ -1992,8 +1983,7 @@ function normalizePersistedDraftsByThreadId( environmentContexts.length === 0 && !hasModelData && !runtimeMode && - !interactionMode && - failedPlanFollowUpRunId === undefined + !interactionMode ) { continue; } @@ -2027,7 +2017,6 @@ function normalizePersistedDraftsByThreadId( : {}), ...(runtimeMode ? { runtimeMode } : {}), ...(interactionMode ? { interactionMode } : {}), - ...(failedPlanFollowUpRunId ? { failedPlanFollowUpRunId } : {}), }; } @@ -2125,8 +2114,7 @@ export function partializeComposerDraftStoreState( draft.environmentContexts.length === 0 && !hasModelData && draft.runtimeMode === null && - draft.interactionMode === null && - draft.failedPlanFollowUpRunId === undefined + draft.interactionMode === null ) { continue; } @@ -2193,9 +2181,6 @@ export function partializeComposerDraftStoreState( : {}), ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}), ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}), - ...(draft.failedPlanFollowUpRunId - ? { failedPlanFollowUpRunId: draft.failedPlanFollowUpRunId } - : {}), }; persistedDraftsByThreadKey[threadKey] = persistedDraft; } @@ -2465,9 +2450,6 @@ function toHydratedThreadDraft( ...(persistedDraft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}), runtimeMode: persistedDraft.runtimeMode ?? null, interactionMode: persistedDraft.interactionMode ?? null, - ...(persistedDraft.failedPlanFollowUpRunId - ? { failedPlanFollowUpRunId: persistedDraft.failedPlanFollowUpRunId } - : {}), }; } @@ -3244,20 +3226,6 @@ const composerDraftStore = create()( return { draftsByThreadKey: nextDraftsByThreadKey }; }); }, - setFailedPlanFollowUpRunId: (threadRef, runId) => { - const threadKey = resolveComposerDraftKey(get(), threadRef); - if (!threadKey) return; - set((state) => { - const base = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft(); - if (base.failedPlanFollowUpRunId === runId) return state; - return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [threadKey]: { ...base, failedPlanFollowUpRunId: runId }, - }, - }; - }); - }, addImage: (threadRef, image) => { const threadKey = resolveComposerDraftKey(get(), threadRef); const threadId = resolveComposerThreadId(get(), threadRef); From 23db8c0f941313a1d4ec70953911396a60e4971e Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:06:30 +0000 Subject: [PATCH 8/8] fix(web): a failed Implement keeps the plan ready to retry Implement saves the thread as Build before it sends. When the send failed, the thread stayed in Build with its plan, and with the plan mode setting off both the mode control and Implement disappeared. A failed Implement now records the run it answered in the thread's persisted composer draft, so the thread reads as plan until a newer run lands, across reloads too. Nothing is written back to the server: the failure may follow acceptance, and another client may have moved on. The draft's local mode is restored and a success clears the marker, so an accepted Implement is not offered again before its run arrives. Implement also waits until the shell and detail agree on the latest run, so the marker and the plan match. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 11 +- apps/web/src/components/chat/ChatComposer.tsx | 4 +- .../src/components/chat/useComposerSend.ts | 3 + .../chat/useProposedPlanSend.browser.test.tsx | 295 ++++++++++++++++++ .../components/chat/useProposedPlanSend.ts | 42 ++- apps/web/src/composerDraftStore.ts | 44 ++- 6 files changed, 388 insertions(+), 11 deletions(-) create mode 100644 apps/web/src/components/chat/useProposedPlanSend.browser.test.tsx diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9642606ab19a1..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,8 +1317,11 @@ export default function ChatView(props: ChatViewProps) { planModeEnabled: settings.planModeEnabled, provider: activeProviderStatus, interactionMode: - composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE, - persistedInteractionMode: serverThread?.interactionMode, + composerInteractionMode ?? + serverThreadInteractionMode ?? + activeThread?.interactionMode ?? + DEFAULT_INTERACTION_MODE, + persistedInteractionMode: serverThreadInteractionMode, }); const conversationProviderStatus = providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ?? @@ -2927,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 824d01341142a..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,11 +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: props.activeThreadShell?.interactionMode, + persistedInteractionMode: activeThreadInteractionMode, }); const selectedModelSelection: ModelSelection = createModelSelection( selectedInstanceId, 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);