From 779baa006544f64be69b4e5f250e5b75c6b084d4 Mon Sep 17 00:00:00 2001 From: Mantas Kantautas Date: Sun, 22 Nov 2026 00:00:16 +0200 Subject: [PATCH 1/3] fix(composer): persist permission mode picks without sending a message --- .../threads/ManagedRuntimeModeNotice.tsx | 26 +- .../features/threads/ThreadDetailScreen.tsx | 3 +- .../features/threads/ThreadRouteScreen.tsx | 14 +- .../features/threads/ThreadSettingsSheet.tsx | 11 +- .../src/features/threads/resume-thread.ts | 2 + apps/mobile/src/i18n/translations/de.json | 4 +- apps/mobile/src/i18n/translations/en.json | 4 +- apps/mobile/src/i18n/translations/es.json | 4 +- apps/mobile/src/i18n/translations/fr.json | 4 +- apps/mobile/src/i18n/translations/ja.json | 4 +- apps/mobile/src/i18n/translations/ko.json | 4 +- apps/mobile/src/i18n/translations/pt-BR.json | 4 +- apps/mobile/src/i18n/translations/ru.json | 4 +- apps/mobile/src/i18n/translations/sv.json | 4 +- apps/mobile/src/i18n/translations/zh.json | 4 +- .../src/state/thread-runtime-mode.test.ts | 260 +++++++++++++++++ apps/mobile/src/state/thread-runtime-mode.ts | 127 +++++++++ .../threadOutboxDelivery.permissions.test.ts | 2 + apps/mobile/src/state/threadOutboxDelivery.ts | 20 +- apps/mobile/src/state/use-composer-drafts.ts | 10 + .../Orchestrator.control-reads.test.ts | 140 +++++++++ .../src/orchestration-v2/Orchestrator.ts | 29 +- apps/server/src/ws.ts | 3 + .../ChatView.runtimeModePick.browser.test.tsx | 194 +++++++++++++ apps/web/src/components/ChatView.tsx | 22 +- .../useComposerSelection.browser.test.tsx | 268 +++++++++++++++++- .../components/chat/useComposerSelection.ts | 86 +++++- apps/web/src/composerDraftStore.test.ts | 13 + apps/web/src/composerDraftStore.ts | 22 ++ apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- apps/web/test/fakeEnvironment.ts | 11 +- .../client-runtime/src/operations/commands.ts | 3 + .../src/state/threadCommands.test.ts | 42 +++ .../src/state/threadCommands.ts | 5 + .../src/state/threadWorkflows.test.ts | 92 ++++++ .../src/state/threadWorkflows.ts | 72 ++++- packages/contracts/src/orchestrationV2.ts | 3 + 46 files changed, 1512 insertions(+), 48 deletions(-) create mode 100644 apps/mobile/src/state/thread-runtime-mode.test.ts create mode 100644 apps/mobile/src/state/thread-runtime-mode.ts create mode 100644 apps/web/src/components/ChatView.runtimeModePick.browser.test.tsx diff --git a/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx b/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx index 408288ccd284e..65c76287db6a3 100644 --- a/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx +++ b/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx @@ -1,34 +1,37 @@ import { managedRuntimeModeDenial } from "@t3tools/client-runtime/contract-labels"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; import { clampManagedRuntimeMode, type ManagedPolicySummary, type RuntimeMode, + type ScopedThreadRef, } from "@t3tools/contracts"; import { useGT, useMessages } from "gt-react-native"; import { View } from "react-native"; import { AppText } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; -import { - updateComposerDraftSettings, - useComposerDraftSettings, -} from "../../state/use-composer-drafts"; +import { selectThreadRuntimeMode } from "../../state/thread-runtime-mode"; +import { useComposerDraftSettings } from "../../state/use-composer-drafts"; +import { useQuietThreadStructure } from "../../state/use-thread-detail"; import { runtimeModeChoicesForSupportedModes } from "./thread-settings-options"; /** * Shown while a thread's mode is above its environment's managed ceiling, where the server - * refuses every turn. Switching sets the draft's mode, which the next send applies first. + * refuses every turn. Switching updates the thread's mode right away when safe. */ export function ManagedRuntimeModeNotice(props: { + readonly thread: EnvironmentThreadShell; + readonly selectedThreadDetailRef: ScopedThreadRef | null; readonly threadKey: string; - readonly threadRuntimeMode: RuntimeMode; readonly supportedRuntimeModes: ReadonlyArray | undefined; readonly policy: ManagedPolicySummary | undefined; }) { const gt = useGT(); const messages = useMessages(); const draftSettings = useComposerDraftSettings(props.threadKey); - const runtimeMode = draftSettings.runtimeMode ?? props.threadRuntimeMode; + const structure = useQuietThreadStructure(props.selectedThreadDetailRef); + const runtimeMode = draftSettings.runtimeMode ?? props.thread.runtimeMode; const denial = managedRuntimeModeDenial(props.policy, runtimeMode, messages); if (denial === undefined) return null; const choices = runtimeModeChoicesForSupportedModes(props.supportedRuntimeModes); @@ -46,7 +49,14 @@ export function ManagedRuntimeModeNotice(props: { {target === undefined || targetLabel === undefined ? null : ( + + + + ); + } + + function threadWithMode(id: string, runtimeMode: RuntimeMode): EnvironmentThreadShell { + return { + environmentId, + id: ThreadId.make(id), + modelSelection: stored, + runtimeMode, + } as EnvironmentThreadShell; + } + + it("persists immediately on an existing thread and releases the draft override on success", async () => { + setup(); + const setThreadRuntimeMode = vi.fn< + Parameters[0]["setThreadRuntimeMode"] + >(async () => AsyncResult.success(undefined)); + const thread = threadWithMode("thread-mode-persist", "auto"); + const target = scopeThreadRef(environmentId, thread.id); + await using _screen = await render( + , + ); + + await page.getByRole("button", { name: "Full access" }).click(); + + await vi.waitFor(() => + expect(setThreadRuntimeMode).toHaveBeenCalledWith( + expect.objectContaining({ + environmentId, + input: expect.objectContaining({ + threadId: thread.id, + runtimeMode: "full-access", + preserveActiveSession: true, + }), + }), + ), + ); + await vi.waitFor(() => { + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode ?? null).toBe( + null, + ); + }); + }); + + it("persists against the thread ref instead of a queued-message edit draft and preserves draft on busy rejection", async () => { + setup(); + const setThreadRuntimeMode = vi + .fn[0]["setThreadRuntimeMode"]>() + .mockResolvedValueOnce( + AsyncResult.failure( + Cause.fail({ code: "provider_selection_busy", message: "Thread has an active turn." }), + ), + ); + const thread = threadWithMode("thread-mode-queued-edit", "auto"); + const threadTarget = scopeThreadRef(environmentId, thread.id); + const editDraftId = DraftId.make("queued-edit-draft"); + await using _screen = await render( + , + ); + + await page.getByRole("button", { name: "Full access" }).click(); + + await vi.waitFor(() => + expect(setThreadRuntimeMode).toHaveBeenCalledWith( + expect.objectContaining({ + environmentId, + input: expect.objectContaining({ + threadId: thread.id, + runtimeMode: "full-access", + preserveActiveSession: true, + }), + }), + ), + ); + // Busy rejection keeps the pick on the thread's own draft, never the queued edit draft. + expect(useComposerDraftStore.getState().getComposerDraft(threadTarget)?.runtimeMode).toBe( + "full-access", + ); + expect( + useComposerDraftStore.getState().getComposerDraft(editDraftId)?.runtimeMode ?? null, + ).toBe(null); + }); + + it("keeps the pick in draft without saving when active work forbids immediate switch, and clears draft when reverted", async () => { + setup(); + const setThreadRuntimeMode = vi.fn< + Parameters[0]["setThreadRuntimeMode"] + >(async () => AsyncResult.success(undefined)); + const thread = threadWithMode("thread-mode-defer", "auto"); + const target = scopeThreadRef(environmentId, thread.id); + await using screen = await render( + , + ); + + await page.getByRole("button", { name: "Full access" }).click(); + expect(setThreadRuntimeMode).not.toHaveBeenCalled(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( + "full-access", + ); + + await screen.rerender( + , + ); + await page.getByRole("button", { name: "Auto" }).click(); + expect(setThreadRuntimeMode).not.toHaveBeenCalled(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode ?? null).toBe( + null, + ); + }); + + it("clears the draft override on failure and ignores superseded overlapping saves", async () => { + setup(); + let resolveFirst!: (value: AtomCommandResult) => void; + let resolveSecond!: (value: AtomCommandResult) => void; + const setThreadRuntimeMode = vi + .fn[0]["setThreadRuntimeMode"]>() + .mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve))) + .mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve))); + const thread = threadWithMode("thread-mode-overlap", "auto"); + const target = scopeThreadRef(environmentId, thread.id); + await using screen = await render( + , + ); + + await page.getByRole("button", { name: "Full access" }).click(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( + "full-access", + ); + + await screen.rerender( + , + ); + await page.getByRole("button", { name: "Supervised" }).click(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( + "approval-required", + ); + + // An older reply (even a failure) must not clobber the newer pick. + resolveFirst(AsyncResult.failure(Cause.fail(new Error("stale failure")))); + await Promise.resolve(); + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( + "approval-required", + ); + + // Failure of the latest pick clears its optimistic draft override. + resolveSecond(AsyncResult.failure(Cause.fail(new Error("policy ceiling")))); + await vi.waitFor(() => { + expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode ?? null).toBe( + null, + ); + }); + }); + + it("does not dispatch to the server for a local draft thread", async () => { + setup(); + const setThreadRuntimeMode = vi.fn< + Parameters[0]["setThreadRuntimeMode"] + >(async () => AsyncResult.success(undefined)); + const draftTarget = DraftId.make("draft-runtime-mode"); + await using _screen = await render( + , + ); + + await page.getByRole("button", { name: "Full access" }).click(); + expect(setThreadRuntimeMode).not.toHaveBeenCalled(); + expect(useComposerDraftStore.getState().getComposerDraft(draftTarget)?.runtimeMode).toBe( + "full-access", + ); + }); +}); diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index 77fdd4a459df2..82f027b57abf7 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -1,7 +1,15 @@ +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { isRuntimeModeSelectionBusyError } from "@t3tools/client-runtime/state/thread-workflows"; import type { UnifiedSettings } from "@t3tools/contracts"; -import { useMessages } from "gt-react"; +import { msg, useMessages } from "gt-react"; import type { Dispatch } from "react"; +import { m } from "~/i18n/messages"; import type { ComposerThreadTarget, DraftSessionState } from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; import { useApplyThreadModelPick } from "./useApplyThreadModelPick"; @@ -15,9 +23,9 @@ import { } from "@t3tools/contracts"; import type { deriveThreadStructureRuntime } from "@t3tools/client-runtime/state/thread-execution"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { type SetStateAction } from "react"; +import { type SetStateAction, useRef } from "react"; import { useNavigate } from "@tanstack/react-router"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { resolveAppModelSelectionForInstance } from "../../modelSelection"; import { draftModelSelectionApplies, @@ -25,6 +33,7 @@ import { threadHasStarted, } from "../../lib/chatThreadActions"; import { + composerTargetKey, type DraftThreadEnvMode, isSameModel, useComposerDraftStore, @@ -58,6 +67,17 @@ interface ComposerSelectionInput { SetStateAction> >; readonly scheduleComposerFocus: () => void; + readonly setThreadRuntimeMode: (input: { + readonly environmentId: EnvironmentId; + readonly input: { + readonly threadId: ThreadId; + readonly runtimeMode: RuntimeMode; + readonly createdAt?: string; + readonly preserveActiveSession?: boolean; + }; + }) => Promise>; + /** False while active work runs on a provider whose session detaches on mode change. */ + readonly canPersistRuntimeModeImmediately: boolean; } /** @@ -83,6 +103,8 @@ export function useComposerSelection(input: ComposerSelectionInput) { setPendingServerThreadEnvModeEntry, setPendingServerThreadStartFromOriginByThreadId, scheduleComposerFocus, + setThreadRuntimeMode, + canPersistRuntimeModeImmediately, } = input; const messages = useMessages(); const navigate = useNavigate(); @@ -93,12 +115,66 @@ export function useComposerSelection(input: ComposerSelectionInput) { const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const applyThreadModelPick = useApplyThreadModelPick(); + const runtimeModeSelectionSeqRef = useRef(new Map()); const handleRuntimeModeChange = (mode: RuntimeMode) => { if (mode === runtimeMode) return; - setComposerDraftRuntimeMode(composerDraftTarget, mode); + // Permissions belong to the thread, not a queued-message edit draft. + const target = + !isLocalDraftThread && activeThread + ? scopeThreadRef(activeThread.environmentId, activeThread.id) + : composerDraftTarget; + const targetKey = composerTargetKey(target); + const seq = (runtimeModeSelectionSeqRef.current.get(targetKey) ?? 0) + 1; + runtimeModeSelectionSeqRef.current.set(targetKey, seq); if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); + setComposerDraftRuntimeMode(target, mode); + setDraftThreadContext(target, { runtimeMode: mode }); + } else if (activeThread && canPersistRuntimeModeImmediately && typeof target !== "string") { + setComposerDraftRuntimeMode(target, mode); + const threadId = activeThread.id; + void setThreadRuntimeMode({ + environmentId: activeThread.environmentId, + input: { + threadId, + runtimeMode: mode, + createdAt: new Date().toISOString(), + preserveActiveSession: true, + }, + }).then((result) => { + if (runtimeModeSelectionSeqRef.current.get(targetKey) !== seq) { + return; + } + if (result._tag === "Success") { + useComposerDraftStore.getState().releaseRuntimeMode(target, mode); + return; + } + if (isAtomCommandInterrupted(result)) { + return; + } + const error = squashAtomCommandFailure(result); + // Another client may have started a turn first; keep the pick in draft for the next send. + if (isRuntimeModeSelectionBusyError(error)) { + return; + } + useComposerDraftStore.getState().releaseRuntimeMode(target, mode); + toastManager.add( + stackedThreadToast({ + type: "error", + title: m(msg("Could not apply permission mode")), + description: m( + msg("This permission mode was not saved. {detail}", { + detail: thrownErrorMessage(error, m) ?? m(msg("Try again.")), + }), + ), + }), + ); + }); + } else { + setComposerDraftRuntimeMode( + target, + activeThread && mode === activeThread.runtimeMode ? null : mode, + ); } scheduleComposerFocus(); }; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c6942b7e01c88..2da366cb6bfc4 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1676,6 +1676,19 @@ describe("composerDraftStore modelSelection", () => { }, ); + it("releases a runtime mode pick only when the draft still holds that mode", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(threadRef, "keep this follow-up"); + store.setRuntimeMode(threadRef, "auto"); + + store.releaseRuntimeMode(threadRef, "full-access"); + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.runtimeMode).toBe("auto"); + + store.releaseRuntimeMode(threadRef, "auto"); + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.runtimeMode).toBeNull(); + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("keep this follow-up"); + }); + it("releases an inactive thread pick only after its queued model becomes durable", () => { const store = useComposerDraftStore.getState(); const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false }); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 07eca76db05f3..674a61097c889 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -670,6 +670,8 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, runtimeMode: RuntimeMode | null | undefined, ) => void; + /** Lets the thread's permission mode show again once this pick settled on the server. */ + releaseRuntimeMode: (threadRef: ScopedThreadRef, runtimeMode: RuntimeMode) => void; setInteractionMode: ( threadRef: ComposerThreadTarget, interactionMode: ProviderInteractionMode | null | undefined, @@ -3569,6 +3571,26 @@ const composerDraftStore = create()( return { draftsByThreadKey: nextDraftsByThreadKey }; }); }, + releaseRuntimeMode: (threadRef, runtimeMode) => { + const threadKey = scopedThreadKey(threadRef); + set((state) => { + const draft = state.draftsByThreadKey[threadKey]; + if (draft?.runtimeMode !== runtimeMode) { + return state; + } + const nextDraft: ComposerThreadDraftState = { + ...draft, + runtimeMode: null, + }; + const nextDraftsByThreadKey = { ...state.draftsByThreadKey }; + if (shouldRemoveDraft(nextDraft)) { + delete nextDraftsByThreadKey[threadKey]; + } else { + nextDraftsByThreadKey[threadKey] = nextDraft; + } + return { draftsByThreadKey: nextDraftsByThreadKey }; + }); + }, setInteractionMode: (threadRef, interactionMode) => { const threadKey = resolveComposerDraftKey(get(), threadRef) ?? ""; if (threadKey.length === 0) { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..f31489ece911d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12460,5 +12460,7 @@ "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", - "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben", + "b62b5c8ef10071e1": "Berechtigungsmodus konnte nicht angewendet werden", + "f597860c2939672e": "Dieser Berechtigungsmodus wurde nicht gespeichert. {detail}" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..5fc4b54cf01b5 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12469,5 +12469,7 @@ "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", - "425ab15036aec8a4": "Move this command to the front of the queue" + "425ab15036aec8a4": "Move this command to the front of the queue", + "b62b5c8ef10071e1": "Could not apply permission mode", + "f597860c2939672e": "This permission mode was not saved. {detail}" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..08c8e3e57ed5c 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12455,5 +12455,7 @@ "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", - "425ab15036aec8a4": "Mover este comando al principio de la cola" + "425ab15036aec8a4": "Mover este comando al principio de la cola", + "b62b5c8ef10071e1": "No se pudo aplicar el modo de permisos", + "f597860c2939672e": "No se guardó este modo de permisos. {detail}" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..9f1a2534ce396 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12460,5 +12460,7 @@ "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", - "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente", + "b62b5c8ef10071e1": "Impossible d’appliquer le mode d’autorisation", + "f597860c2939672e": "Ce mode d’autorisation n’a pas été enregistré. {detail}" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..5ec0ca381d9dd 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12409,5 +12409,7 @@ "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動" + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", + "b62b5c8ef10071e1": "権限モードを適用できませんでした", + "f597860c2939672e": "この権限モードは保存されませんでした。{detail}" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..d7fe782d93247 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12404,5 +12404,7 @@ "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", + "b62b5c8ef10071e1": "권한 모드를 적용할 수 없습니다", + "f597860c2939672e": "이 권한 모드는 저장되지 않았습니다. {detail}" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..63d4dbfe99c67 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12460,5 +12460,7 @@ "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", - "425ab15036aec8a4": "Mover este comando para o início da fila" + "425ab15036aec8a4": "Mover este comando para o início da fila", + "b62b5c8ef10071e1": "Não foi possível aplicar o modo de permissão", + "f597860c2939672e": "Este modo de permissão não foi salvo. {detail}" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..3f1908cbd7c3d 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12460,5 +12460,7 @@ "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди" + "425ab15036aec8a4": "Переместить эту команду в начало очереди", + "b62b5c8ef10071e1": "Не удалось применить режим разрешений", + "f597860c2939672e": "Этот режим разрешений не сохранён. {detail}" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..690d4d7e07a11 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12467,5 +12467,7 @@ "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", - "425ab15036aec8a4": "Flytta det här kommandot först i kön" + "425ab15036aec8a4": "Flytta det här kommandot först i kön", + "b62b5c8ef10071e1": "Kunde inte tillämpa behörighetsläget", + "f597860c2939672e": "Det här behörighetsläget sparades inte. {detail}" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..661f628aa2258 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12486,5 +12486,7 @@ "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面" + "425ab15036aec8a4": "将此命令移到队列最前面", + "b62b5c8ef10071e1": "无法应用权限模式", + "f597860c2939672e": "此权限模式未保存。{detail}" } diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 71e8875bb56db..d9d7296315480 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -235,8 +235,11 @@ export interface FakeThread { readonly title: string; /** Defaults to GPT-5.4 on Codex. */ readonly modelSelection?: ModelSelection; + /** Defaults to `"full-access"`. */ + readonly runtimeMode?: OrchestrationV2ThreadShell["runtimeMode"]; /** The first is the thread's active provider thread. */ readonly providerThreads?: ReadonlyArray; + readonly providerSessions?: OrchestrationV2ThreadProjection["providerSessions"]; readonly issues?: OrchestrationV2ThreadShell["issues"]; readonly runs: ReadonlyArray; readonly items: ReadonlyArray; @@ -322,7 +325,7 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { title: thread.title, providerInstanceId: modelSelection.instanceId, modelSelection, - runtimeMode: "full-access", + runtimeMode: thread.runtimeMode ?? "full-access", interactionMode: "default", branch: "main", worktreePath: null, @@ -338,9 +341,9 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { createdBy: thread.providerSubagentOf ? "agent" : "user", creationSource: thread.providerSubagentOf ? "provider" : "web", latestRunId: latest?.id ?? null, - activeRunId: null, + activeRunId: latest && latest.status === "running" ? latest.id : null, // Idle reads as waiting on the user, which shows a per-second duration in the sidebar. - status: latest ? "completed" : "idle", + status: latest ? latest.status : "idle", pendingRuntimeRequest: null, latestVisibleMessage: null, latestUserMessageAt: AT, @@ -396,7 +399,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { attempts: [], nodes: [], subagents: [], - providerSessions: [], + providerSessions: [...(thread.providerSessions ?? [])], providerThreads: [...(thread.providerThreads ?? [])], providerTurns: [], runtimeRequests: [...(thread.runtimeRequests ?? [])], diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..e3aaa81e4c2fa 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -161,6 +161,8 @@ export interface UpdateThreadMetadataInput extends ThreadCommandInput { export interface SetThreadRuntimeModeInput extends ThreadCommandInput { readonly runtimeMode: RuntimeMode; + /** Refuse to detach a live session that has active work, so picker picks stay in draft. */ + readonly preserveActiveSession?: boolean; } export interface SetThreadInteractionModeInput extends ThreadCommandInput { @@ -751,6 +753,7 @@ export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRunt commandId: yield* allocateCommandId(input), threadId: input.threadId, runtimeMode: input.runtimeMode, + ...(input.preserveActiveSession === true ? { preserveActiveSession: true } : {}), }); }, ); diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index c01450353457e..26790cb5a4f30 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -755,4 +755,46 @@ describe("remote thread lifecycle commands", () => { expect((yield* Fiber.join(result))._tag).toBe("Success"); }), ); + + it.effect("shows a picked runtime mode optimistically and rolls back when rejected", () => + Effect.gen(function* () { + const h = yield* makeHarness(); + h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), SNAPSHOT); + + const ok = yield* Effect.forkChild( + Effect.exit( + h.commands.setRuntimeMode.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, runtimeMode: "auto" }, + }), + ), + { startImmediately: true }, + ); + const firstRequest = yield* Queue.take(h.requests); + expect(firstRequest.command).toMatchObject({ + type: "thread.runtime-mode.set", + threadId: THREAD_ID, + runtimeMode: "auto", + }); + expect(h.registry.get(h.visibleAtom)?.threads[0]?.runtimeMode).toBe("auto"); + yield* Deferred.succeed(firstRequest.reply, { sequence: 2 }); + expect((yield* Fiber.join(ok))._tag).toBe("Success"); + expect(h.registry.get(h.visibleAtom)?.threads[0]?.runtimeMode).toBe("auto"); + + const rejected = yield* Effect.forkChild( + Effect.exit( + h.commands.setRuntimeMode.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID, runtimeMode: "approval-required" }, + }), + ), + { startImmediately: true }, + ); + const secondRequest = yield* Queue.take(h.requests); + expect(h.registry.get(h.visibleAtom)?.threads[0]?.runtimeMode).toBe("approval-required"); + yield* Deferred.fail(secondRequest.reply, new Error("policy ceiling")); + expect((yield* Fiber.join(rejected))._tag).toBe("Failure"); + expect(h.registry.get(h.visibleAtom)?.threads[0]?.runtimeMode).toBe("auto"); + }), + ); }); diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 98d88407b85b4..de0035c48b9c0 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -531,6 +531,7 @@ export function createThreadEnvironmentAtoms( rowActionsAtom, mcpSignedInAtom, snapshotAtom: optimistic.snapshotAtom, + durableSnapshotAtom: snapshotAtom, pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom, settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) => !accepted && @@ -617,5 +618,9 @@ export function createThreadEnvironmentAtoms( ...thread, modelSelection: input.modelSelection, })), + setRuntimeMode: optimistic.wrap(commands.setRuntimeMode, (thread, input) => ({ + ...thread, + runtimeMode: input.runtimeMode, + })), }; } diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..f1ec1d47f570d 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -3,10 +3,12 @@ import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { canForkProjectedAssistantItem, + canPersistThreadRuntimeModeImmediately, deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, threadSupportsProviderHandoff, + threadSupportsRuntimeModeSwitchInSession, } from "./threadWorkflows.ts"; const capabilities = (input?: { @@ -85,6 +87,96 @@ describe("thread workflows", () => { expect(threadSupportsProviderHandoff({ ...projection, providerThreads: [] })).toBe(false); }); + it("persists runtime mode switches immediately when idle or when every live session switches in place", () => { + const idleThread = { + runtime: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + pendingBackgroundTasks: [], + }; + const runningThread = { + ...idleThread, + runtime: { status: "running", activeRunId: "run" } as never, + }; + const session = (status: string, supportsRuntimeModeSwitchInSession: boolean) => ({ + id: `session-${status}-${String(supportsRuntimeModeSwitchInSession)}`, + status, + capabilities: { sessions: { supportsRuntimeModeSwitchInSession } }, + }); + const projectionWith = (input: { + readonly providerSessions?: ReadonlyArray; + readonly runs?: ReadonlyArray; + readonly runtimeRequests?: ReadonlyArray; + }) => + ({ + thread: { id: "thread", activeProviderThreadId: null }, + runs: input.runs ?? [], + providerSessions: input.providerSessions ?? [], + providerThreads: [], + runtimeRequests: input.runtimeRequests ?? [], + }) as unknown as OrchestrationV2ThreadProjection; + + const inSessionLive = projectionWith({ + runs: [{ id: "run", status: "running" }], + providerSessions: [session("ready", true)], + }); + const restartRequiredLive = projectionWith({ + runs: [{ id: "run", status: "running" }], + providerSessions: [session("ready", false)], + }); + const mixedLive = projectionWith({ + runs: [{ id: "run", status: "running" }], + providerSessions: [session("ready", true), session("ready", false)], + }); + const stoppedAndLiveInSession = projectionWith({ + runs: [{ id: "run", status: "running" }], + providerSessions: [session("stopped", false), session("ready", true)], + }); + + expect(threadSupportsRuntimeModeSwitchInSession(null)).toBe(false); + expect(threadSupportsRuntimeModeSwitchInSession(inSessionLive)).toBe(true); + expect(threadSupportsRuntimeModeSwitchInSession(restartRequiredLive)).toBe(false); + expect(threadSupportsRuntimeModeSwitchInSession(mixedLive)).toBe(false); + expect(threadSupportsRuntimeModeSwitchInSession(stoppedAndLiveInSession)).toBe(true); + + // Idle threads persist regardless of session capability. + expect( + canPersistThreadRuntimeModeImmediately({ + thread: idleThread, + projection: projectionWith({ providerSessions: [session("ready", false)] }), + }), + ).toBe(true); + // Active turns / open approvals on in-session providers (Antigravity, Codex, OpenCode v2) persist right away. + expect( + canPersistThreadRuntimeModeImmediately({ + thread: { ...runningThread, hasPendingApprovals: true }, + projection: inSessionLive, + isWorking: true, + }), + ).toBe(true); + // Active turns / open prompts on providers that detach on mode change defer to the next send. + expect( + canPersistThreadRuntimeModeImmediately({ + thread: runningThread, + projection: restartRequiredLive, + isWorking: true, + }), + ).toBe(false); + expect( + canPersistThreadRuntimeModeImmediately({ + thread: { ...idleThread, hasPendingUserInput: true }, + projection: projectionWith({ providerSessions: [session("ready", false)] }), + }), + ).toBe(false); + expect( + canPersistThreadRuntimeModeImmediately({ + thread: runningThread, + projection: null, + isWorking: true, + }), + ).toBe(false); + }); + it("sorts queued messages and gates promotion from capabilities", () => { const state = deriveThreadQueueWorkflowState({ thread: { id: "thread", activeProviderThreadId: "provider-thread" }, diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..2fd914aa062d0 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,7 +8,11 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; -import type { ThreadStructure } from "./models.ts"; +import { + type EnvironmentThreadShell, + type ThreadStructure, + threadRuntimeIsActive, +} from "./models.ts"; type Projection = ThreadStructure; type Run = Projection["runs"][number]; @@ -122,6 +126,72 @@ export function threadSupportsProviderHandoff(projection: Projection | null | un ); } +/** + * True when every live provider session attached to this thread can switch runtime modes + * without detaching, so `thread.runtime-mode.set` is safe while a run is active. + */ +export function threadSupportsRuntimeModeSwitchInSession( + projection: Projection | null | undefined, +): boolean { + if (projection == null) return false; + const liveSessions = projection.providerSessions.filter( + (session) => session.status !== "stopped" && session.status !== "error", + ); + return ( + liveSessions.length > 0 && + liveSessions.every( + (session) => session.capabilities.sessions.supportsRuntimeModeSwitchInSession, + ) + ); +} + +/** + * True when `thread.runtime-mode.set` can be sent straight away without risking an active + * turn or open prompt on a provider whose session detaches on mode change. + */ +export function canPersistThreadRuntimeModeImmediately(input: { + readonly thread: Pick< + EnvironmentThreadShell, + "runtime" | "hasPendingApprovals" | "hasPendingUserInput" | "pendingBackgroundTasks" + >; + readonly projection: Projection | null | undefined; + readonly isWorking?: boolean; +}): boolean { + const hasActiveWork = + input.isWorking === true || + threadRuntimeIsActive(input.thread.runtime) || + input.thread.hasPendingApprovals || + input.thread.hasPendingUserInput || + input.thread.pendingBackgroundTasks.length > 0 || + (input.projection != null && + (resolveActiveThreadRun(input.projection) !== null || + input.projection.runtimeRequests.some((request) => request.status === "pending"))); + if (!hasActiveWork) return true; + return threadSupportsRuntimeModeSwitchInSession(input.projection); +} + +/** True when the server refused a picker mode save because a live session became busy. */ +export function isRuntimeModeSelectionBusyError(error: unknown): boolean { + const seen = new Set(); + let current = error; + while (typeof current === "object" && current !== null && !seen.has(current)) { + seen.add(current); + const candidate = current as { + readonly code?: unknown; + readonly _tag?: unknown; + readonly cause?: unknown; + }; + if ( + candidate.code === "provider_selection_busy" || + candidate._tag === "OrchestratorProviderSelectionBusyError" + ) { + return true; + } + current = candidate.cause; + } + return false; +} + export function getUserQueuedThreadRuns( projection: Pick, ): ReadonlyArray { diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 51d762d77c14f..b5201e048ca97 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3500,6 +3500,8 @@ export const OrchestrationV2Command = Schema.Union([ commandId: CommandId, threadId: ThreadId, runtimeMode: RuntimeMode, + /** Refuses to detach a live session that has active work, so picker saves can stay in draft. */ + preserveActiveSession: Schema.optional(Schema.Boolean), }), Schema.Struct({ type: Schema.Literal("thread.interaction-mode.set"), @@ -4383,6 +4385,7 @@ export class OrchestrationV2DispatchCommandError extends Schema.TaggedError Date: Sat, 21 Nov 2026 22:10:46 +0000 Subject: [PATCH 2/3] test: cut runtime mode pick tests to the ones that catch regressions Drop the ChatView integration browser test (and the fake environment changes it needed) and web hook cases already covered by the shared gate and mobile unit tests. Co-Authored-By: Claude Opus 5.5 --- .../ChatView.runtimeModePick.browser.test.tsx | 194 ------------------ .../useComposerSelection.browser.test.tsx | 113 ---------- apps/web/test/fakeEnvironment.ts | 11 +- 3 files changed, 4 insertions(+), 314 deletions(-) delete mode 100644 apps/web/src/components/ChatView.runtimeModePick.browser.test.tsx diff --git a/apps/web/src/components/ChatView.runtimeModePick.browser.test.tsx b/apps/web/src/components/ChatView.runtimeModePick.browser.test.tsx deleted file mode 100644 index 8983aff2d6205..0000000000000 --- a/apps/web/src/components/ChatView.runtimeModePick.browser.test.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { createMemoryHistory } from "@tanstack/react-router"; -import { ProviderSessionId, type OrchestrationV2ProviderSession } from "@t3tools/contracts"; -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; -import type * as Context from "effect/Context"; -import * as DateTime from "effect/DateTime"; -import { expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; - -import { AppRoot } from "~/AppRoot"; -// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines) -// takes 6-11s; importing it here keeps that out of the test's timeout. -import "~/components/ChatView"; -import { __setClientSettingsForTests } from "~/hooks/useSettings"; -import { getRouter } from "~/router"; -import { - CODEX_PROVIDER, - ENVIRONMENT_ID, - dispatchedCommands, - installFakeEnvironment, - threadWithHistory, - type FakeDriver, -} from "../../test/fakeEnvironment"; -import { render } from "../../test/render"; - -// The socket is the only fake layer; see test/appScenarios.renders.tsx. -vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { - const [actual, { fakeDriver }, Layer] = await Promise.all([ - importOriginal<{ readonly ConnectionDriver: Context.Key }>(), - import("../../test/fakeEnvironment"), - import("effect/Layer"), - ]); - return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; -}); - -vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ - ...(await original()), - trackRpcRequestSent: () => {}, -})); - -const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z"); - -function liveInSessionCapableSession(): OrchestrationV2ProviderSession { - return { - id: ProviderSessionId.make("session-codex-live"), - driver: "codex" as never, - providerInstanceId: "codex" as never, - status: "ready", - cwd: "/workspace/render", - model: "gpt-5.4", - capabilities: { - sessions: { - supportsMultipleProviderThreadsPerSession: false, - supportsModelSwitchInSession: true, - supportsProviderSwitchingViaHandoff: true, - supportsRuntimeModeSwitchInSession: true, - pendingRequestsSurviveRestart: false, - }, - threads: { - canCreateEmptyThread: true, - canReadThreadSnapshot: true, - canRollbackThread: false, - canForkThread: false, - canForkFromTurn: false, - canForkFromSubagentThread: false, - exposesNativeThreadId: true, - }, - turns: { - emitsTurnStarted: true, - emitsTurnCompleted: true, - supportsInterrupt: true, - supportsNativeResume: false, - supportsActiveSteering: true, - supportsSteeringByInterruptRestart: true, - supportsQueuedMessages: true, - exposesNativeTurnId: true, - terminalStatusQuality: "strong", - }, - streaming: { - streamsAssistantText: true, - streamsReasoning: true, - streamsToolOutput: true, - streamsPlanText: false, - emitsMessageCompleted: true, - }, - tools: { - exposesToolItemIds: true, - emitsToolStarted: true, - emitsToolCompleted: true, - emitsToolOutput: true, - supportsMcpTools: true, - supportsDynamicToolCallbacks: false, - }, - approvals: { - supportsCommandApproval: true, - supportsFileReadApproval: true, - supportsFileChangeApproval: true, - supportsApplyPatchApproval: false, - approvalsHaveNativeRequestIds: false, - approvalCallbacksAreLiveOnly: true, - approvalsCanOriginateFromSubagents: false, - }, - planning: { - emitsPlanUpdated: false, - emitsTodoList: false, - emitsProposedPlan: false, - supportsStructuredQuestions: false, - planDeltasHaveItemIds: false, - }, - subagents: { - supportsSubagents: false, - exposesSubagentThreadIds: false, - emitsSubagentLifecycle: false, - canWaitForSubagents: false, - canCloseSubagents: false, - canForkSubagentThread: false, - }, - context: { - acceptsSystemContext: false, - acceptsDeveloperContext: false, - acceptsSyntheticUserContext: true, - canGenerateSummaries: false, - canConsumeHandoffSummaries: false, - supportsDeltaHandoff: false, - supportsFullThreadHandoff: false, - maxRecommendedHandoffChars: null, - }, - checkpointing: { - appCanCheckpointFilesystem: false, - supportsNestedCheckpointScopes: false, - providerCanRollbackConversation: false, - providerRollbackReturnsSnapshot: false, - providerCanReadConversationSnapshot: false, - }, - identity: { - nativeThreadIds: "strong", - nativeTurnIds: "weak", - nativeItemIds: "weak", - nativeRequestIds: "weak", - }, - runtimePolicy: { enforcement: "client-boundary" }, - }, - extensionStatuses: [], - createdAt: AT, - updatedAt: AT, - lastError: null, - }; -} - -// Its own file: the app's shell subscription outlives a test, and it must list this thread. -it("a permission mode picked during an active in-session run reaches the server without sending a message", async () => { - const baseThread = threadWithHistory("thread-runtime-mode-pick", 1); - const runningThread = { - ...baseThread, - runtimeMode: "auto" as const, - runs: [{ ...baseThread.runs[0]!, status: "running" as const, completedAt: null }], - providerSessions: [liveInSessionCapableSession()], - }; - using _environment = installFakeEnvironment([runningThread], { - acceptCommands: true, - providers: [ - { - ...CODEX_PROVIDER, - supportedRuntimeModes: ["approval-required", "auto", "full-access"], - }, - ], - }); - __setClientSettingsForTests({ - ...DEFAULT_CLIENT_SETTINGS, - onboardingCompletedAt: "2026-01-01T00:00:00.000Z", - }); - const router = getRouter( - createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${runningThread.id}`] }), - ); - await router.load(); - await using _app = await render(, { - router: false, - }); - await expect.element(page.getByText("Answer 0 for thread-runtime-mode-pick.")).toBeVisible(); - - await page.getByRole("button", { name: "GPT-5.4", exact: true }).click(); - await page.getByRole("button", { name: "Permissions: Auto" }).click(); - await page.getByRole("menuitemradio", { name: "Full access" }).click(); - - await vi.waitFor(() => - expect( - dispatchedCommands().filter((command) => command.type === "thread.runtime-mode.set"), - ).toEqual([ - expect.objectContaining({ - threadId: runningThread.id, - runtimeMode: "full-access", - }), - ]), - ); -}); diff --git a/apps/web/src/components/chat/useComposerSelection.browser.test.tsx b/apps/web/src/components/chat/useComposerSelection.browser.test.tsx index f4e8e7f02ed63..5317f3ce8cd52 100644 --- a/apps/web/src/components/chat/useComposerSelection.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerSelection.browser.test.tsx @@ -356,117 +356,4 @@ describe("runtime mode persistence", () => { useComposerDraftStore.getState().getComposerDraft(editDraftId)?.runtimeMode ?? null, ).toBe(null); }); - - it("keeps the pick in draft without saving when active work forbids immediate switch, and clears draft when reverted", async () => { - setup(); - const setThreadRuntimeMode = vi.fn< - Parameters[0]["setThreadRuntimeMode"] - >(async () => AsyncResult.success(undefined)); - const thread = threadWithMode("thread-mode-defer", "auto"); - const target = scopeThreadRef(environmentId, thread.id); - await using screen = await render( - , - ); - - await page.getByRole("button", { name: "Full access" }).click(); - expect(setThreadRuntimeMode).not.toHaveBeenCalled(); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( - "full-access", - ); - - await screen.rerender( - , - ); - await page.getByRole("button", { name: "Auto" }).click(); - expect(setThreadRuntimeMode).not.toHaveBeenCalled(); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode ?? null).toBe( - null, - ); - }); - - it("clears the draft override on failure and ignores superseded overlapping saves", async () => { - setup(); - let resolveFirst!: (value: AtomCommandResult) => void; - let resolveSecond!: (value: AtomCommandResult) => void; - const setThreadRuntimeMode = vi - .fn[0]["setThreadRuntimeMode"]>() - .mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve))) - .mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve))); - const thread = threadWithMode("thread-mode-overlap", "auto"); - const target = scopeThreadRef(environmentId, thread.id); - await using screen = await render( - , - ); - - await page.getByRole("button", { name: "Full access" }).click(); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( - "full-access", - ); - - await screen.rerender( - , - ); - await page.getByRole("button", { name: "Supervised" }).click(); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( - "approval-required", - ); - - // An older reply (even a failure) must not clobber the newer pick. - resolveFirst(AsyncResult.failure(Cause.fail(new Error("stale failure")))); - await Promise.resolve(); - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode).toBe( - "approval-required", - ); - - // Failure of the latest pick clears its optimistic draft override. - resolveSecond(AsyncResult.failure(Cause.fail(new Error("policy ceiling")))); - await vi.waitFor(() => { - expect(useComposerDraftStore.getState().getComposerDraft(target)?.runtimeMode ?? null).toBe( - null, - ); - }); - }); - - it("does not dispatch to the server for a local draft thread", async () => { - setup(); - const setThreadRuntimeMode = vi.fn< - Parameters[0]["setThreadRuntimeMode"] - >(async () => AsyncResult.success(undefined)); - const draftTarget = DraftId.make("draft-runtime-mode"); - await using _screen = await render( - , - ); - - await page.getByRole("button", { name: "Full access" }).click(); - expect(setThreadRuntimeMode).not.toHaveBeenCalled(); - expect(useComposerDraftStore.getState().getComposerDraft(draftTarget)?.runtimeMode).toBe( - "full-access", - ); - }); }); diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index d9d7296315480..71e8875bb56db 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -235,11 +235,8 @@ export interface FakeThread { readonly title: string; /** Defaults to GPT-5.4 on Codex. */ readonly modelSelection?: ModelSelection; - /** Defaults to `"full-access"`. */ - readonly runtimeMode?: OrchestrationV2ThreadShell["runtimeMode"]; /** The first is the thread's active provider thread. */ readonly providerThreads?: ReadonlyArray; - readonly providerSessions?: OrchestrationV2ThreadProjection["providerSessions"]; readonly issues?: OrchestrationV2ThreadShell["issues"]; readonly runs: ReadonlyArray; readonly items: ReadonlyArray; @@ -325,7 +322,7 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { title: thread.title, providerInstanceId: modelSelection.instanceId, modelSelection, - runtimeMode: thread.runtimeMode ?? "full-access", + runtimeMode: "full-access", interactionMode: "default", branch: "main", worktreePath: null, @@ -341,9 +338,9 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { createdBy: thread.providerSubagentOf ? "agent" : "user", creationSource: thread.providerSubagentOf ? "provider" : "web", latestRunId: latest?.id ?? null, - activeRunId: latest && latest.status === "running" ? latest.id : null, + activeRunId: null, // Idle reads as waiting on the user, which shows a per-second duration in the sidebar. - status: latest ? latest.status : "idle", + status: latest ? "completed" : "idle", pendingRuntimeRequest: null, latestVisibleMessage: null, latestUserMessageAt: AT, @@ -399,7 +396,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { attempts: [], nodes: [], subagents: [], - providerSessions: [...(thread.providerSessions ?? [])], + providerSessions: [], providerThreads: [...(thread.providerThreads ?? [])], providerTurns: [], runtimeRequests: [...(thread.runtimeRequests ?? [])], From ff79ab79dae89fe82c72ca8c3513e80d83875133 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 00:14:02 +0000 Subject: [PATCH 3/3] fix(composer): resume saves a deferred permission pick before releasing held turns Resume with no run to continue released the held queue without saving the composer's permission mode, so held turns started in the thread's old mode. Web and mobile now save it first. A mobile pick of the saved mode made while another mode is still saving now stays in the draft. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/resume-thread.test.ts | 12 ++++++++++++ .../src/features/threads/resume-thread.ts | 18 +++++++++--------- apps/mobile/src/state/thread-runtime-mode.ts | 5 ++--- .../src/components/chat/useComposerResume.ts | 8 ++++++++ 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/apps/mobile/src/features/threads/resume-thread.test.ts b/apps/mobile/src/features/threads/resume-thread.test.ts index 3520f72293f89..d88046c40f85d 100644 --- a/apps/mobile/src/features/threads/resume-thread.test.ts +++ b/apps/mobile/src/features/threads/resume-thread.test.ts @@ -87,4 +87,16 @@ describe("resumeThread", () => { expect(calls.map((call) => call.command)).toEqual(["resumeQueue"]); }); + + it("saves a picked permission mode before releasing a held queue", async () => { + const { calls, base } = setup(); + await resumeThread({ + ...base, + runtimeMode: "approval-required", + resumableRunId: null, + queueHeld: true, + }); + + expect(calls.map((call) => call.command)).toEqual(["setRuntimeMode", "resumeQueue"]); + }); }); diff --git a/apps/mobile/src/features/threads/resume-thread.ts b/apps/mobile/src/features/threads/resume-thread.ts index a024c43526b63..ee0046c280e84 100644 --- a/apps/mobile/src/features/threads/resume-thread.ts +++ b/apps/mobile/src/features/threads/resume-thread.ts @@ -43,17 +43,17 @@ export async function resumeThread(input: { }): Promise> { const { thread, runtimeMode, interactionMode, createdAt } = input; const environmentId = thread.environmentId; + // A turn on an existing thread, held queued ones included, runs with the thread's saved modes. + if (runtimeMode !== thread.runtimeMode) { + const saved = await input.setRuntimeMode({ + environmentId, + input: { threadId: thread.id, runtimeMode, createdAt }, + }); + if (saved._tag === "Failure") return saved; + } + input.onRuntimeModePersisted?.(runtimeMode); // The server holds the queue behind a stopped or usage-limited run until that run is continued. if (input.resumableRunId !== null) { - // A turn on an existing thread runs with the thread's saved modes, not the turn's. - if (runtimeMode !== thread.runtimeMode) { - const saved = await input.setRuntimeMode({ - environmentId, - input: { threadId: thread.id, runtimeMode, createdAt }, - }); - if (saved._tag === "Failure") return saved; - } - input.onRuntimeModePersisted?.(runtimeMode); if (interactionMode !== thread.interactionMode) { const saved = await input.setInteractionMode({ environmentId, diff --git a/apps/mobile/src/state/thread-runtime-mode.ts b/apps/mobile/src/state/thread-runtime-mode.ts index 3b137f61f7dac..831e689e38372 100644 --- a/apps/mobile/src/state/thread-runtime-mode.ts +++ b/apps/mobile/src/state/thread-runtime-mode.ts @@ -76,9 +76,8 @@ export function selectThreadRuntimeMode(input: SelectThreadRuntimeModeInput): vo canPersistThreadRuntimeModeImmediately({ thread, projection }); if (!canPersistImmediately) { - updateComposerDraftSettings(threadKey, { - runtimeMode: runtimeMode === durableRuntimeMode ? undefined : runtimeMode, - }); + // A saved-mode pick only gets here while another mode is saving; keep it so the next send restores it. + updateComposerDraftSettings(threadKey, { runtimeMode }); return; } diff --git a/apps/web/src/components/chat/useComposerResume.ts b/apps/web/src/components/chat/useComposerResume.ts index a38800c38ecbf..b4920fc3f8dce 100644 --- a/apps/web/src/components/chat/useComposerResume.ts +++ b/apps/web/src/components/chat/useComposerResume.ts @@ -108,6 +108,14 @@ export function useComposerResume(input: ComposerResumeInput) { // Commands settle into a result, so this always runs. const resume = async () => { if (resumableRunId === null) { + // Held turns start with the thread's saved mode, so a deferred pick is saved first. + const settingsResult = await persistThreadSettingsForNextTurn({ + threadId, + createdAt: new Date().toISOString(), + runtimeMode, + interactionMode: activeThread.interactionMode, + }); + if (settingsResult._tag === "Failure") return settingsResult; return resumeThreadQueue({ environmentId, input: { threadId } }); } // Read before the first await: the composer follows the route, so after the user switches