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); + }); +}); 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/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