Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(session): add /fast for OpenAI's priority service tier

zszz3cac8e168bbc5
diff --git a/apps/desktop/electron/main/builtin-commands.ts b/apps/desktop/electron/main/builtin-commands.ts
index 28ca880c8..e84cf36a3 100644
--- a/apps/desktop/electron/main/builtin-commands.ts
+++ b/apps/desktop/electron/main/builtin-commands.ts
@@ -15,6 +15,7 @@ export const BUILTIN_COMMANDS: BuiltinCommandDef[] = [
{ id: "builtin.mode.agent", title: "Switch to Agent mode", category: "Session", keywords: ["mode", "agent"], source: "builtin", slash: "agent-mode" },
{ id: "builtin.mode.plan", title: "Switch to Plan mode", category: "Session", keywords: ["mode", "plan", "planning"], source: "builtin", slash: "plan-mode" },
{ id: "builtin.mode.goal", title: "Switch to Goal mode", category: "Session", keywords: ["mode", "goal", "objective", "autonomous"], source: "builtin", slash: "goal-mode" },
+ { id: "builtin.session.fast", title: "Toggle Fast mode", category: "Session", keywords: ["fast", "speed", "priority", "service tier"], source: "builtin", slash: "fast" },
];
/** Palette-shaped items (no slash field leaks into the palette contract). */
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index f62be5b1e..1fb56753a 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -603,6 +603,7 @@ export function registerSessionIpc({
modelId?: string;
thinkingLevel?: SessionThinkingLevel;
permissionMode?: "inherit" | "ask" | "accept-edits" | "auto";
+ fastMode?: boolean;
},
) => {
rejectNativeMutation(id, "configuration");
diff --git a/apps/desktop/electron/main/remote/remote-backend.ts b/apps/desktop/electron/main/remote/remote-backend.ts
index 0fc5d91c7..dd17b5029 100644
--- a/apps/desktop/electron/main/remote/remote-backend.ts
+++ b/apps/desktop/electron/main/remote/remote-backend.ts
@@ -269,9 +269,14 @@ export function createRemoteBackend(options: RemoteBackendOptions): RemoteBacken
case IPC.invoke.sessionConfigure: {
const remoteSessionId = remoteIdFor(args);
const config = (args[1] ?? {}) as Partial<
- Pick<SessionSummary, "mode" | "providerId" | "modelId" | "thinkingLevel" | "permissionMode">
+ Pick<SessionSummary, "mode" | "providerId" | "modelId" | "thinkingLevel" | "permissionMode" | "fastMode">
>;
- if (config.providerId !== undefined || config.modelId !== undefined || config.thinkingLevel !== undefined) {
+ if (
+ config.providerId !== undefined ||
+ config.modelId !== undefined ||
+ config.thinkingLevel !== undefined ||
+ config.fastMode !== undefined
+ ) {
throw capabilityUnavailable("remote sessions use the Host model configuration");
}
const { session } = await client.request<{ session: RacpSession }>("session/configure", {
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index 3461c2e70..0b82b13da 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -706,6 +706,9 @@ export function createSessionLaunchRuntime({
...(overrides.turnId ? { turnId: overrides.turnId } : {}),
thinkingLevel,
infiniteProviderRetry: settings.infiniteProviderRetry === true,
+ // The session `/fast` switch only reaches a model the user allowed it
+ // for in model settings (ADR 0332).
+ fastMode: session.fastMode === true && storedModel?.fastModeAllowed === true,
...(jevApiKey ? { jevApiKey } : {}),
commandShell,
scratchDir: join(dataDir, "scratch", sessionId),
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index c9baf395d..10f9b244d 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -25,6 +25,7 @@ import { isActivePlanExecution } from "../lib/plan-mode-state";
import { headAsk, queuedAskCount } from "../lib/pending-asks";
import type { QueuedPrompt } from "../lib/queued-prompts";
import { composerModelDisplayName, sameComposerModelId } from "../lib/composer-models";
+import { sessionFastModeActive } from "../lib/fast-mode-command";
import {
resolveComposerThinkingProvider,
} from "../lib/session-thinking";
@@ -626,6 +627,7 @@ export function Composer({
modelMenu={modelMenu}
modelLabel={modelLabel}
thinkingLabel={thinkingLabel}
+ modelFastMode={sessionFastModeActive(provider, modelId, activeSession ?? draftConfiguration)}
contextUsage={composerContextUsage ?? null}
value={value}
modelReady={modelReady}
diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx
index 13f39d92c..08337551f 100644
--- a/apps/desktop/src/components/icons.tsx
+++ b/apps/desktop/src/components/icons.tsx
@@ -101,6 +101,7 @@ import {
Workflow,
Wrench,
X,
+ Zap,
type LucideIcon,
type LucideProps,
} from "lucide-react";
@@ -192,6 +193,7 @@ export const IconDatabase = icon(Database);
export const IconCheck = icon(Check);
export const IconBell = icon(Bell);
export const IconBot = icon(Bot);
+export const IconZap = icon(Zap);
export const IconCheckCheck = icon(CheckCheck);
export const IconShield = icon(Shield);
export const IconChevronDown = icon(ChevronDown);
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index 668a838b2..8b0192d9a 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -16,6 +16,7 @@ import {
bindingForCustomModel,
bindingForCustomModelInfo,
bindingFromModelInfo,
+ fastModeBillingOn,
formatTokenCount,
modelMatchesFilter,
nativeWebSearchSupportedOn,
@@ -307,6 +308,14 @@ export function ModelSelectionPanes({
// Use the same published endpoint routing as the runtime. A disabled control
// means this connection is not integrated, not that the vendor cannot search.
const nativeWebSearchWireCapable = nativeWebSearchSupportedOn(apiStyle, lookupContext?.baseUrl);
+ // Fast mode rides the Responses `service_tier` field; the hint names what
+ // the priority tier costs on this wire (ADR 0332).
+ const fastModeBilling = fastModeBillingOn(apiStyle);
+ const fastModeHint = fastModeBilling === "subscription"
+ ? "settings.fastModeAllowedSubscriptionHint"
+ : fastModeBilling === "usage"
+ ? "settings.fastModeAllowedUsageHint"
+ : "settings.fastModeAllowedUnsupported";
/**
* The chosen list narrows with the discovered list's rule plus the binding's
@@ -1032,6 +1041,28 @@ export function ModelSelectionPanes({
<IconHelp size={13} />
</Tooltip>
</span>
+ <span className="provider-chosen-delegation">
+ <label className="provider-chosen-capability">
+ <input
+ type="checkbox"
+ checked={binding.fastModeAllowed === true}
+ disabled={!fastModeBilling}
+ onChange={(event) =>
+ updateBinding(binding.id, {
+ fastModeAllowed: event.target.checked || undefined,
+ })
+ }
+ />
+ <span>{t("settings.fastModeAllowed")}</span>
+ </label>
+ <Tooltip
+ className="provider-chosen-delegation-help"
+ label={t(fastModeHint)}
+ ariaLabel={t(fastModeHint)}
+ >
+ <IconHelp size={13} />
+ </Tooltip>
+ </span>
</div>
</div>
</div>
diff --git a/apps/desktop/src/components/settings/provider-copy.ts b/apps/desktop/src/components/settings/provider-copy.ts
index 54b06748b..eb3805547 100644
--- a/apps/desktop/src/components/settings/provider-copy.ts
+++ b/apps/desktop/src/components/settings/provider-copy.ts
@@ -47,6 +47,7 @@ export function copyProviderConfiguration(provider: ProviderPublic, name: string
...(model.supportsDocuments !== undefined ? { supportsDocuments: model.supportsDocuments } : {}),
...(model.availableForSubagents !== undefined ? { availableForSubagents: model.availableForSubagents } : {}),
...(model.nativeWebSearch !== undefined ? { nativeWebSearch: model.nativeWebSearch } : {}),
+ ...(model.fastModeAllowed !== undefined ? { fastModeAllowed: model.fastModeAllowed } : {}),
})),
};
}
diff --git a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
index 05a89f815..d9e943198 100644
--- a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
@@ -2,7 +2,7 @@ import type { TFunction } from "i18next";
import type { ReactNode } from "react";
import { ComposerModelList } from "./ComposerModelList";
import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
-import { IconBot, IconChevronDown } from "../../../components/icons";
+import { IconBot, IconChevronDown, IconZap } from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
import { ThinkingLevelSlider } from "./ThinkingLevelSlider";
@@ -15,6 +15,8 @@ export type ComposerModelPickerProps = {
modelLabel: string;
thinkingLabel: string;
thinkingLevel: string;
+ /** The selected model asks for OpenAI's priority tier (ADR 0332). */
+ fastMode?: boolean;
selectedProviderId?: string;
selectedModelId?: string;
controlsBlocked: boolean;
@@ -29,6 +31,7 @@ export function ComposerModelPicker({
modelLabel,
thinkingLabel,
thinkingLevel,
+ fastMode = false,
selectedProviderId,
selectedModelId,
controlsBlocked,
@@ -54,6 +57,7 @@ export function ComposerModelPicker({
commitThinkingLevel,
onMenuKeyDown,
} = controller;
+ const fastSuffix = fastMode ? ` · ${t("chat.fastModeBadge")}` : "";
return (
<AnchoredMenu
@@ -72,8 +76,8 @@ export function ComposerModelPicker({
ref={ref}
type="button"
className={`icon-btn composer-model-thinking-chip ${open ? "active" : ""}`}
- tooltip={`${modelLabel} · ${t("chat.reasoningLevel")}: ${thinkingLabel}`}
- ariaLabel={`${t("chat.model")}: ${modelLabel}. ${t("chat.reasoningLevel")}: ${thinkingLabel}`}
+ tooltip={`${modelLabel} · ${t("chat.reasoningLevel")}: ${thinkingLabel}${fastSuffix}`}
+ ariaLabel={`${t("chat.model")}: ${modelLabel}. ${t("chat.reasoningLevel")}: ${thinkingLabel}${fastSuffix}`}
aria-haspopup="menu"
aria-expanded={open}
disabled={controlsBlocked}
@@ -94,6 +98,11 @@ export function ComposerModelPicker({
{thinkingLevel !== "off" ? (
<span className="composer-model-thinking-level">{thinkingLabel}</span>
) : null}
+ {fastMode ? (
+ <span className="composer-model-thinking-fast" aria-hidden="true">
+ <IconZap size={12} />
+ </span>
+ ) : null}
<IconChevronDown size={12} aria-hidden="true" className="composer-model-thinking-chevron" />
</TooltipButton>
)}
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 2b04f19f8..526ab6400 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -51,6 +51,8 @@ export type ComposerToolbarProps = {
modelMenu: ModelMenuController;
modelLabel: string;
thinkingLabel: string;
+ /** The selected model asks for OpenAI's priority tier (ADR 0332). */
+ modelFastMode?: boolean;
contextUsage: ContextUsage | null;
value: string;
modelReady: boolean;
@@ -92,6 +94,7 @@ export function ComposerToolbar({
modelMenu,
modelLabel,
thinkingLabel,
+ modelFastMode = false,
contextUsage,
value,
modelReady,
@@ -189,6 +192,7 @@ export function ComposerToolbar({
controller={modelMenu}
modelLabel={modelLabel}
thinkingLabel={thinkingLabel}
+ fastMode={modelFastMode}
thinkingLevel={thinkingLevel}
selectedProviderId={providerId}
selectedModelId={modelId}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index a23632a11..5d43fb639 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -760,7 +760,7 @@ export const api = {
configureSession: (
id: string,
config: Pick<SessionSummary, "mode" | "providerId" | "modelId"> &
- Partial<Pick<SessionSummary, "thinkingLevel" | "permissionMode">>,
+ Partial<Pick<SessionSummary, "thinkingLevel" | "permissionMode" | "fastMode">>,
) =>
invoke<{ session: SessionSummary }>(
IPC.invoke.sessionConfigure,
diff --git a/apps/desktop/src/lib/commands.ts b/apps/desktop/src/lib/commands.ts
index f399cdb8d..081016e12 100644
--- a/apps/desktop/src/lib/commands.ts
+++ b/apps/desktop/src/lib/commands.ts
@@ -1,6 +1,7 @@
import i18n from "i18next";
import { api } from "./api";
import { useAppStore } from "../stores/app-store";
+import { toggleSessionFastMode } from "./fast-mode-command";
import { trustedExtensionCommandName, type Mode } from "@pi-desktop/shared";
/**
@@ -17,6 +18,9 @@ export async function runPaletteCommand(commandId: string): Promise<void> {
case "builtin.agent.compact":
await store.compactContext();
break;
+ case "builtin.session.fast":
+ await toggleSessionFastMode();
+ break;
case "builtin.mode.agent":
case "builtin.mode.plan":
case "builtin.mode.goal": {
diff --git a/apps/desktop/src/lib/fast-mode-command.ts b/apps/desktop/src/lib/fast-mode-command.ts
new file mode 100644
index 000000000..6fefb5763
--- /dev/null
+++ b/apps/desktop/src/lib/fast-mode-command.ts
@@ -0,0 +1,78 @@
+import i18n from "i18next";
+import { fastModeBillingOn, type ProviderPublic } from "@pi-desktop/shared";
+import { useAppStore } from "../stores/app-store";
+import { sameComposerModelId } from "./composer-models";
+import { isRemoteSession } from "./remote-session-safety";
+import { inheritedSessionModelBinding } from "./session-model";
+
+/**
+ * The `/fast` builtin (ADR 0332): a per-session switch for OpenAI's priority
+ * service tier. Model settings decide which models may use it.
+ */
+
+type FastModeProvider = Pick<ProviderPublic, "apiStyle" | "models"> | undefined | null;
+
+function fastModeAllowed(provider: FastModeProvider, modelId: string | undefined): boolean {
+ return !!modelId && provider?.models.some(
+ (binding) => sameComposerModelId(binding.id, modelId) && binding.fastModeAllowed === true,
+ ) === true;
+}
+
+/** Whether the Composer should mark the selected model as running in Fast mode. */
+export function sessionFastModeActive(
+ provider: FastModeProvider,
+ modelId: string | undefined,
+ target: { fastMode?: boolean } | null | undefined,
+): boolean {
+ return target?.fastMode === true && !!fastModeBillingOn(provider?.apiStyle) &&
+ fastModeAllowed(provider, modelId);
+}
+
+export async function toggleSessionFastMode(): Promise<void> {
+ const store = useAppStore.getState();
+ const activeSession = store.sessions.find((session) => session.id === store.activeSessionId);
+ if (store.activeSessionId && !activeSession) return;
+ if (activeSession && isRemoteSession(activeSession)) {
+ store.showToast(i18n.t("chat.fastModeRemote"), { variant: "warning" });
+ return;
+ }
+ const target = activeSession ?? store.draftConfiguration;
+ const enabled = target?.fastMode !== true;
+ const selected = inheritedSessionModelBinding({
+ draft: target,
+ settings: store.settings,
+ providers: store.providers,
+ recentModels: store.recentModels,
+ });
+ const provider = store.providers.find((candidate) => candidate.id === selected.providerId);
+ const billing = fastModeBillingOn(provider?.apiStyle);
+ // Without a configured model the switch does nothing, so `/fast` only
+ // points to the setting; a stale stored switch stays inert at launch.
+ if (!billing) {
+ store.showToast(i18n.t("chat.fastModeUnsupported"), { variant: "warning" });
+ return;
+ }
+ if (!fastModeAllowed(provider, selected.modelId)) {
+ store.showToast(i18n.t("chat.fastModeNotAllowed"), { variant: "warning" });
+ return;
+ }
+
+ if (activeSession) {
+ await store.configureActiveSession({
+ mode: activeSession.mode,
+ providerId: activeSession.providerId,
+ modelId: activeSession.modelId,
+ thinkingLevel: activeSession.thinkingLevel,
+ fastMode: enabled,
+ });
+ // A pending plan review or a read-only session leaves the switch as is.
+ const after = useAppStore.getState().sessions.find((session) => session.id === activeSession.id);
+ if ((after?.fastMode === true) !== enabled) return;
+ } else {
+ useAppStore.setState((state) => ({
+ draftConfiguration: { ...state.draftConfiguration, fastMode: enabled },
+ }));
+ }
+ const message = !enabled ? "chat.fastModeOff" : billing === "usage" ? "chat.fastModeOnUsage" : "chat.fastModeOn";
+ store.showToast(i18n.t(message), { variant: "info" });
+}
diff --git a/apps/desktop/src/lib/session-thinking.ts b/apps/desktop/src/lib/session-thinking.ts
index d4b4655e7..a9294f6d5 100644
--- a/apps/desktop/src/lib/session-thinking.ts
+++ b/apps/desktop/src/lib/session-thinking.ts
@@ -26,6 +26,7 @@ export type OptimisticSessionConfiguration = {
thinkingLevel?: SessionThinkingLevel;
mode?: unknown;
permissionMode?: unknown;
+ fastMode?: boolean;
};
export type ThinkingProviderLike = {
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 21b76b5b9..3319a148b 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -104,13 +104,18 @@ export type RefreshSessionsOptions = {
revealImportedProjects?: boolean;
};
-/** Toolbar selections retained on the unpersisted new-task draft. */
+/**
+ * Toolbar selections retained on the unpersisted new-task draft. An absent
+ * field keeps the default the new session would otherwise start with.
+ */
export type DraftSessionConfiguration = {
- mode: Mode;
- thinkingLevel: SessionThinkingLevel;
+ mode?: Mode;
+ thinkingLevel?: SessionThinkingLevel;
providerId?: string;
modelId?: string;
permissionMode?: PermissionMode;
+ /** Session `/fast` switch carried into the created session (ADR 0332). */
+ fastMode?: boolean;
};
@@ -228,6 +233,7 @@ export type AppState = {
modelId?: string;
thinkingLevel: SessionThinkingLevel;
permissionMode?: PermissionMode;
+ fastMode?: boolean;
}) => Promise<void>;
/** Returns true once accepted unless concurrent smart Stop restores it. */
sendPrompt: (
diff --git a/apps/desktop/src/stores/runtime/session-coordination.ts b/apps/desktop/src/stores/runtime/session-coordination.ts
index 3e9fefe36..c79d263fd 100644
--- a/apps/desktop/src/stores/runtime/session-coordination.ts
+++ b/apps/desktop/src/stores/runtime/session-coordination.ts
@@ -319,6 +319,7 @@ export function createSessionCoordination({
mode: draftConfig?.mode ?? normalizeMode(settings?.defaultMode),
thinkingLevel: draftConfig?.thinkingLevel ?? defaultThinkingLevel,
permissionMode: draftConfig?.permissionMode,
+ ...(draftConfig?.fastMode ? { fastMode: true } : {}),
providerId: inherited.providerId,
modelId: inherited.modelId,
projectPath: projectPath ?? undefined,
diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.ts
index 26dbb620e..b879617d9 100644
--- a/apps/desktop/src/stores/runtime/session-runtime.ts
+++ b/apps/desktop/src/stores/runtime/session-runtime.ts
@@ -43,7 +43,7 @@ export type SessionConfiguration = Pick<
SessionSummary,
"mode" | "providerId" | "modelId" | "thinkingLevel"
> &
- Partial<Pick<SessionSummary, "permissionMode">>;
+ Partial<Pick<SessionSummary, "permissionMode" | "fastMode">>;
export type SessionSelection = { id: string; intent: number };
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index e1c41d699..5da762f07 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -790,6 +790,7 @@ export function createSessionSlice({
modelId: config.modelId ?? state.draftConfiguration?.modelId,
permissionMode:
config.permissionMode ?? state.draftConfiguration?.permissionMode,
+ fastMode: config.fastMode ?? state.draftConfiguration?.fastMode,
},
}));
return;
diff --git a/apps/desktop/src/styles/composer-menus.css b/apps/desktop/src/styles/composer-menus.css
index 5fdfe01df..2c67aec38 100644
--- a/apps/desktop/src/styles/composer-menus.css
+++ b/apps/desktop/src/styles/composer-menus.css
@@ -189,6 +189,14 @@
line-height: var(--leading-compact);
}
+/* Fast mode stays visible at every width: it changes what each turn costs. */
+.composer-model-thinking-fast {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ color: var(--ds-text-secondary);
+}
+
.composer-model-thinking-chevron {
flex: 0 0 auto;
color: var(--ds-text-faint);
diff --git a/apps/desktop/test/builtin-commands.test.mjs b/apps/desktop/test/builtin-commands.test.mjs
index 477cd6c7f..9e69d7734 100644
--- a/apps/desktop/test/builtin-commands.test.mjs
+++ b/apps/desktop/test/builtin-commands.test.mjs
@@ -17,9 +17,10 @@ const coreIds = [
"builtin.mode.agent",
"builtin.mode.plan",
"builtin.mode.goal",
+ "builtin.session.fast",
];
-const coreAliases = ["new", "compact", "agent-mode", "plan-mode", "goal-mode"];
+const coreAliases = ["new", "compact", "agent-mode", "plan-mode", "goal-mode", "fast"];
const removedIds = [
"builtin.session.delete",
@@ -38,7 +39,7 @@ const removedIds = [
"builtin.app.toggleDevtools",
];
-test("builtin registry exposes exactly the five core commands and aliases", () => {
+test("builtin registry exposes exactly the six core commands and aliases", () => {
const ids = [...registry.matchAll(/\bid: "([^"]+)"/g)].map((match) => match[1]);
const aliases = [...registry.matchAll(/slash: "([^"]+)"/g)].map((match) => match[1]);
diff --git a/apps/desktop/test/fast-mode-command.test.mjs b/apps/desktop/test/fast-mode-command.test.mjs
new file mode 100644
index 000000000..63bd460f4
--- /dev/null
+++ b/apps/desktop/test/fast-mode-command.test.mjs
@@ -0,0 +1,155 @@
+import i18n from "i18next";
+import { en } from "@pi-desktop/i18n";
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { useAppStore, materializeDraftSession } = await import("../src/stores/app-store.ts");
+const { api } = await import("../src/lib/api.ts");
+const { runPaletteCommand } = await import("../src/lib/commands.ts");
+const { sessionFastModeActive } = await import("../src/lib/fast-mode-command.ts");
+
+// ADR 0332: `/fast` is a per-session switch, and model settings decide which
+// models may use it.
+
+await i18n.init({ lng: "en", keySeparator: false, resources: { en: { translation: flatten(en) } } });
+
+function flatten(catalog, prefix = "", out = {}) {
+ for (const [key, value] of Object.entries(catalog)) {
+ if (value && typeof value === "object") flatten(value, `${prefix}${key}.`, out);
+ else out[`${prefix}${key}`] = value;
+ }
+ return out;
+}
+
+const codex = {
+ id: "codex", name: "ChatGPT", enabled: true, hasSecret: true, authKind: "oauth", apiStyle: "openai_codex_responses",
+ models: [{ id: "gpt-codex", fastModeAllowed: true }, { id: "gpt-mini" }],
+};
+const relay = {
+ id: "relay", name: "Relay", enabled: true, hasSecret: true, authKind: "api_key", apiStyle: "responses",
+ models: [{ id: "gpt-relay", fastModeAllowed: true }],
+};
+const completions = {
+ id: "completions", name: "Gateway", enabled: true, hasSecret: true, authKind: "api_key", apiStyle: "chat_completions",
+ models: [{ id: "chat", fastModeAllowed: true }],
+};
+const session = (provider, modelId, extra = {}) => ({
+ id: "s1", title: "Task", messageCount: 0, mode: "agent", thinkingLevel: "medium", permissionMode: "inherit",
+ providerId: provider.id, modelId, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", ...extra,
+});
+
+function setup(t, state) {
+ const toasts = [];
+ const configures = [];
+ const creates = [];
+ t.mock.method(api, "configureSession", async (id, config) => {
+ configures.push(config);
+ return { session: { ...useAppStore.getState().sessions.find((item) => item.id === id), ...config, id } };
+ });
+ t.mock.method(api, "createSession", async (config) => {
+ creates.push(config);
+ return { session: { ...config, id: "created", title: "New task", messageCount: 0, messages: [] } };
+ });
+ useAppStore.setState({
+ providers: [codex, relay, completions],
+ sessions: [],
+ activeSessionId: null,
+ runningSessions: {},
+ pendingPlans: {},
+ recentModels: [],
+ draftConfiguration: null,
+ workspace: null,
+ settings: { defaultProviderId: codex.id, defaultModelId: "gpt-codex", defaultMode: "agent" },
+ showToast: (message, options) => { toasts.push({ message, variant: options?.variant }); },
+ ...state,
+ });
+ return { toasts, configures, creates };
+}
+
+test("/fast toggles an allowed subscription model's session through session.configure", async (t) => {
+ const { toasts, configures } = setup(t, { sessions: [session(codex, "gpt-codex")], activeSessionId: "s1" });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures.length, 1);
+ assert.equal(configures[0].fastMode, true);
+ assert.equal(configures[0].thinkingLevel, "medium", "other selections are resent unchanged");
+ assert.equal(useAppStore.getState().sessions[0].fastMode, true);
+ assert.equal(toasts[0].message, en.chat.fastModeOn);
+
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures[1].fastMode, false);
+ assert.equal(useAppStore.getState().sessions[0].fastMode, false);
+ assert.equal(toasts[1].message, en.chat.fastModeOff);
+});
+
+test("/fast on a per-token Responses model warns about the price", async (t) => {
+ const { toasts, configures } = setup(t, { sessions: [session(relay, "gpt-relay")], activeSessionId: "s1" });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures[0].fastMode, true);
+ assert.equal(toasts[0].message, en.chat.fastModeOnUsage);
+});
+
+test("/fast refuses a model the user has not allowed, and a wire without the tier", async (t) => {
+ const notAllowed = setup(t, { sessions: [session(codex, "gpt-mini")], activeSessionId: "s1" });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(notAllowed.configures.length, 0);
+ assert.deepEqual(notAllowed.toasts, [{ message: en.chat.fastModeNotAllowed, variant: "warning" }]);
+
+ const unsupported = setup(t, { sessions: [session(completions, "chat")], activeSessionId: "s1" });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(unsupported.configures.length, 0);
+ assert.deepEqual(unsupported.toasts, [{ message: en.chat.fastModeUnsupported, variant: "warning" }]);
+});
+
+test("/fast points to model settings instead of toggling a stale switch on an unconfigured model", async (t) => {
+ const { configures, toasts } = setup(t, {
+ sessions: [session(codex, "gpt-mini", { fastMode: true })],
+ activeSessionId: "s1",
+ });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures.length, 0);
+ assert.deepEqual(toasts, [{ message: en.chat.fastModeNotAllowed, variant: "warning" }]);
+});
+
+test("/fast refuses remote sessions", async (t) => {
+ const { configures, toasts } = setup(t, {
+ sessions: [session(codex, "gpt-codex", { id: "remote:host:s1", source: "remote" })],
+ activeSessionId: "remote:host:s1",
+ });
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures.length, 0);
+ assert.equal(toasts[0].message, en.chat.fastModeRemote);
+});
+
+test("/fast on the new-task draft carries the switch into the created session", async (t) => {
+ const { configures, creates } = setup(t, {});
+ await runPaletteCommand("builtin.session.fast");
+ assert.equal(configures.length, 0);
+ assert.deepEqual(useAppStore.getState().draftConfiguration, { fastMode: true });
+
+ // Choosing a model on the draft keeps the switch.
+ await useAppStore.getState().configureActiveSession({
+ mode: "agent", providerId: codex.id, modelId: "gpt-codex", thinkingLevel: "high",
+ });
+ assert.equal(useAppStore.getState().draftConfiguration.fastMode, true);
+
+ await materializeDraftSession();
+ assert.equal(creates.length, 1);
+ assert.equal(creates[0].fastMode, true);
+ assert.equal(creates[0].thinkingLevel, "high");
+});
+
+test("a draft without /fast creates a session on the default tier and default thinking", async (t) => {
+ const { creates } = setup(t, {});
+ await materializeDraftSession();
+ assert.equal(creates.length, 1);
+ assert.equal("fastMode" in creates[0], false);
+});
+
+test("the Composer marks Fast only when the switch is on for an allowed model", () => {
+ assert.equal(sessionFastModeActive(codex, "gpt-codex", { fastMode: true }), true);
+ assert.equal(sessionFastModeActive(codex, "gpt-codex", { fastMode: false }), false);
+ assert.equal(sessionFastModeActive(codex, "gpt-mini", { fastMode: true }), false);
+ assert.equal(sessionFastModeActive(completions, "chat", { fastMode: true }), false);
+ assert.equal(sessionFastModeActive(undefined, undefined, { fastMode: true }), false);
+});
diff --git a/apps/desktop/test/fast-mode-session-launch.test.mjs b/apps/desktop/test/fast-mode-session-launch.test.mjs
new file mode 100644
index 000000000..139955ffb
--- /dev/null
+++ b/apps/desktop/test/fast-mode-session-launch.test.mjs
@@ -0,0 +1,89 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { mkdtemp, rm } from "node:fs/promises";
+import { join } from "node:path";
+import test from "node:test";
+import { pathToFileURL } from "node:url";
+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+test("session launch sends Fast mode only for a model the user allowed it on (ADR 0332)", async () => {
+ const temp = await mkdtemp(join(root, "apps/desktop/.fast-mode-launch-test-"));
+ const priorHome = process.env.HOME;
+ process.env.HOME = temp;
+ try {
+ const bundle = join(temp, "session-launch.mjs");
+ await build({
+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],
+ outfile: bundle,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ packages: "external",
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);
+ const provider = {
+ id: "openai-provider",
+ name: "OpenAI",
+ authKind: "none",
+ apiStyle: "responses",
+ baseUrl: "http://127.0.0.1:11434/v1",
+ enabled: true,
+ defaultModelId: "allowed-model",
+ models: [],
+ };
+ const allowed = new Set(["allowed-model"]);
+ const host = {
+ isAvailable: () => true,
+ async call(method) {
+ if (method === "commandShells.list") {
+ const shell = { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };
+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };
+ }
+ if (method === "providers.list") return { providers: [provider] };
+ if (method === "providers.getSecret") return { value: "" };
+ if (method === "skills.disabledBuiltins") return { disabled: [] };
+ if (method === "skills.active") return { skills: [] };
+ if (method === "mcp.active") return { servers: [] };
+ if (method === "agents.active") return { subagents: [] };
+ if (method === "agents.disabledBuiltins") return { disabled: [] };
+ throw new Error("Unexpected fixture Host method: " + method);
+ },
+ };
+ const launchRuntime = createSessionLaunchRuntime({
+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },
+ logger: { app() {} },
+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },
+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },
+ sessionProjects: new Map(),
+ dataDir: temp,
+ vendorOAuth: { async bindingFor() { return undefined; } },
+ modelsDevCatalog: { async ensureLoaded() {}, configureAccount() {}, findModel() { return undefined; } },
+ getWorkspacePath: () => null,
+ pluginActiveInProject: () => true,
+ bindingForModel: (_provider, modelId) =>
+ allowed.has(modelId) ? { id: modelId, fastModeAllowed: true } : { id: modelId },
+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),
+ normalizeThinkingLevel: () => "off",
+ });
+ const launch = async (modelId, fastMode) => {
+ const { sidecarParams } = await launchRuntime.resolveAgentRuntimeLaunch(
+ "session-fixture",
+ { providerId: provider.id, modelId, ...(fastMode === undefined ? {} : { fastMode }) },
+ { defaultProviderId: provider.id, defaultModelId: modelId, defaultMode: "agent" },
+ );
+ return sidecarParams.fastMode;
+ };
+
+ assert.equal(await launch("allowed-model", true), true);
+ assert.equal(await launch("allowed-model", false), false);
+ assert.equal(await launch("allowed-model", undefined), false);
+ assert.equal(await launch("other-model", true), false);
+ } finally {
+ process.env.HOME = priorHome;
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/test/model-advanced-capabilities.test.mjs b/apps/desktop/test/model-advanced-capabilities.test.mjs
index 8e1010564..fb2ab6284 100644
--- a/apps/desktop/test/model-advanced-capabilities.test.mjs
+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs
@@ -285,3 +285,15 @@ test("the offered default and the saved default use one order", () => {
/resolveBindingDefaultThinkingLevel\(\s*binding\.defaultThinkingLevel,\s*sortThinkingLevels\(next\),/,
);
});
+
+test("model settings let the user allow Fast mode per model on Responses wires", () => {
+ // ADR 0332: the opt-in lives on the binding; `/fast` is the per-session switch.
+ assert.match(pickerSource, /const fastModeBilling = fastModeBillingOn\(apiStyle\);/);
+ assert.match(pickerSource, /checked=\{binding\.fastModeAllowed === true\}/);
+ assert.match(pickerSource, /disabled=\{!fastModeBilling\}/);
+ assert.match(pickerSource, /fastModeAllowed: event\.target\.checked \|\| undefined/);
+ // Plan limits and per-token billing are different costs, so the hint differs.
+ assert.match(pickerSource, /"settings\.fastModeAllowedSubscriptionHint"/);
+ assert.match(pickerSource, /"settings\.fastModeAllowedUsageHint"/);
+ assert.match(pickerSource, /"settings\.fastModeAllowedUnsupported"/);
+});
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 518e0005a..7511d4ae7 100644
--- a/crates/host-core/src/db.rs
+++ b/crates/host-core/src/db.rs
@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;
pub(crate) use std::path::{Path, PathBuf};
/// Current SQLite schema version.
-pub const SCHEMA_VERSION: i64 = 24;
+pub const SCHEMA_VERSION: i64 = 25;
/// Absolute approval deadline for a newly submitted Plan or Goal proposal.
pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;
@@ -22,6 +22,7 @@ mod project_groups;
mod repositories;
mod schema;
mod session_collaboration_migration;
+mod session_fast_mode_migration;
mod session_title_source_migration;
mod worktree_migration;
pub(crate) use migrations::{
@@ -43,6 +44,7 @@ pub(crate) use repositories::{
OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE,
};
pub(crate) use schema::{PLAN_APPROVALS_SCHEMA, SCHEMA_LATEST, SESSION_TODO_DDL};
+pub(crate) use session_fast_mode_migration::migrate_v24_to_v25;
pub(crate) use session_title_source_migration::migrate_v22_to_v23;
pub(crate) use worktree_migration::{migrate_v23_to_v24, WORKTREE_DDL};
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 30bc39d30..2f5ee3a0f 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -207,6 +207,9 @@ impl Database {
23 => {
migrate_v23_to_v24(&conn, path)?;
}
+ 24 => {
+ migrate_v24_to_v25(&conn, path)?;
+ }
legacy @ 1..=6 => {
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
drop(conn);
@@ -257,6 +260,10 @@ impl Database {
}
if migrated_version == 23 {
migrate_v23_to_v24(&conn, path)?;
+ migrated_version = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
+ }
+ if migrated_version == 24 {
+ migrate_v24_to_v25(&conn, path)?;
}
let db = Self { conn, data_dir };
db.boot_maintenance()?;
diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rs
index 2237f0519..8023a534f 100644
--- a/crates/host-core/src/db/schema.rs
+++ b/crates/host-core/src/db/schema.rs
@@ -98,6 +98,7 @@ CREATE TABLE sessions (
'high', 'xhigh', 'max', 'omit')),
permission_mode TEXT NOT NULL DEFAULT 'inherit'
CHECK (permission_mode IN ('inherit', 'ask', 'accept-edits', 'auto')),
+ fast_mode INTEGER NOT NULL DEFAULT 0 CHECK (fast_mode IN (0, 1)),
source TEXT,
deleted_at INTEGER,
pinned INTEGER NOT NULL DEFAULT 0,
diff --git a/crates/host-core/src/db/session_fast_mode_migration.rs b/crates/host-core/src/db/session_fast_mode_migration.rs
new file mode 100644
index 000000000..e24503e6f
--- /dev/null
+++ b/crates/host-core/src/db/session_fast_mode_migration.rs
@@ -0,0 +1,33 @@
+use super::{create_migration_backup, Connection, Context, Path, Result};
+use rusqlite::Transaction;
+
+/// v25 stores the per-session `/fast` switch (ADR 0332). Every existing
+/// session keeps the default service tier.
+fn migrate_v24_to_v25_tx(tx: &Transaction<'_>) -> Result<()> {
+ let has_fast_mode: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'fast_mode')",
+ [],
+ |row| row.get(0),
+ )?;
+ if !has_fast_mode {
+ tx.execute_batch(
+ "ALTER TABLE sessions ADD COLUMN fast_mode INTEGER NOT NULL DEFAULT 0
+ CHECK (fast_mode IN (0, 1));",
+ )?;
+ }
+ tx.pragma_update(None, "user_version", 25i64)?;
+ Ok(())
+}
+
+pub(crate) fn migrate_v24_to_v25(conn: &Connection, path: &Path) -> Result<()> {
+ let backup = create_migration_backup(conn, path, 24)?;
+ let tx = conn.unchecked_transaction()?;
+ migrate_v24_to_v25_tx(&tx)?;
+ tx.commit().with_context(|| {
+ format!(
+ "commit schema v24 to v25 migration; backup {} remains",
+ backup.display()
+ )
+ })?;
+ Ok(())
+}
diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rs
index 8f5ed4f1e..bcfb8e1ad 100644
--- a/crates/host-core/src/db/tests.rs
+++ b/crates/host-core/src/db/tests.rs
@@ -294,6 +294,43 @@ fn worktree_registry_enforces_one_row_per_owner_and_unique_ports() {
/// `sessions` stamps nor the `session_todo` table, so the upgrade must add
/// both, keep the v20 rows, leave a readable pre-migration backup, and stay
/// idempotent when a fixture downgrades the same file in place.
+/// v25 adds the per-session `/fast` column (ADR 0332). Existing sessions keep
+/// their configuration, default to the normal tier, and a backup remains.
+#[test]
+fn v24_database_gains_session_fast_mode_defaulting_off() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ let session_id = {
+ let db = Database::open(&path).unwrap();
+ let session = crate::sessions::create_session_with_thinking(
+ &db,
+ Some("Kept".into()),
+ None,
+ None,
+ None,
+ None,
+ Some("high".into()),
+ )
+ .unwrap();
+ db.conn()
+ .execute_batch("ALTER TABLE sessions DROP COLUMN fast_mode;")
+ .unwrap();
+ db.conn().pragma_update(None, "user_version", 24).unwrap();
+ session.id
+ };
+
+ let db = Database::open(&path).unwrap();
+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
+ assert!(migration_backup_path(&path, 24).exists());
+ let summary = crate::sessions::get_session(&db, &session_id)
+ .unwrap()
+ .unwrap()
+ .summary;
+ assert_eq!(summary.title, "Kept");
+ assert_eq!(summary.thinking_level, "high");
+ assert!(!summary.fast_mode);
+}
+
#[test]
fn v20_database_migrates_the_session_checklist_with_a_backup() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/host-core/src/plugins/providers.rs b/crates/host-core/src/plugins/providers.rs
index 2fa9ed15d..4f4f2469e 100644
--- a/crates/host-core/src/plugins/providers.rs
+++ b/crates/host-core/src/plugins/providers.rs
@@ -186,6 +186,7 @@ pub(crate) fn declared_providers(manifest: &PluginManifest) -> Vec<DeclaredPlugi
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
})
})
.collect::<Vec<_>>()
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index bab05ca21..433aa876c 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -99,10 +99,10 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {
let (_dir, db, _secrets) = test_context();
// v17 added the owner column, v18 the turn-queue priority column,
// v19 session omit, v21 the session Todo checklist, and v22 the
- // session-list index, v23 the session title source, and v24 the worktree
- // registry. A fresh database is stamped with the newest version, so the
- // column set is the current one.
- assert_eq!(SCHEMA_VERSION, 24);
+ // session-list index, v23 the session title source, v24 the worktree
+ // registry, and v25 the session Fast mode switch. A fresh database is
+ // stamped with the newest version, so the column set is the current one.
+ assert_eq!(SCHEMA_VERSION, 25);
let version: i64 = db
.conn()
.query_row("PRAGMA user_version", [], |row| row.get(0))
diff --git a/crates/host-core/src/providers/catalog.rs b/crates/host-core/src/providers/catalog.rs
index 76472dfd6..2df72fe64 100644
--- a/crates/host-core/src/providers/catalog.rs
+++ b/crates/host-core/src/providers/catalog.rs
@@ -81,6 +81,7 @@ pub(crate) fn normalize_model_bindings(bindings: &[ModelBinding]) -> Vec<ModelBi
supports_documents: binding.supports_documents,
available_for_subagents: binding.available_for_subagents,
native_web_search: binding.native_web_search,
+ fast_mode_allowed: binding.fast_mode_allowed,
})
})
.collect()
@@ -104,6 +105,7 @@ fn legacy_model_binding(model_id: Option<String>) -> Vec<ModelBinding> {
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
}]
})
.unwrap_or_default()
@@ -490,6 +492,7 @@ mod tests {
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
}
}
diff --git a/crates/host-core/src/providers/model.rs b/crates/host-core/src/providers/model.rs
index 40f590012..fa980ae3f 100644
--- a/crates/host-core/src/providers/model.rs
+++ b/crates/host-core/src/providers/model.rs
@@ -170,6 +170,10 @@ pub struct ModelBinding {
/// default because models.dev does not publish hosted-tool capability.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_web_search: Option<bool>,
+ /// Opt-in that lets the session `/fast` switch request OpenAI's priority
+ /// service tier for this model (ADR 0332). None/false keeps the default.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fast_mode_allowed: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs
index 7dc2ed4b3..6ca8a8e26 100644
--- a/crates/host-core/src/providers/repository.rs
+++ b/crates/host-core/src/providers/repository.rs
@@ -111,6 +111,7 @@ fn hydrate_dynamic_plugin_models(db: &Database, provider: &mut ProviderPublic) -
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
}
})
.collect();
diff --git a/crates/host-core/src/providers/tests.rs b/crates/host-core/src/providers/tests.rs
index 6e953e1fd..660cbc461 100644
--- a/crates/host-core/src/providers/tests.rs
+++ b/crates/host-core/src/providers/tests.rs
@@ -253,6 +253,7 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {
supports_documents: None,
available_for_subagents: Some(true),
native_web_search: None,
+ fast_mode_allowed: Some(true),
},
ModelBinding {
id: "plain-model".into(),
@@ -268,6 +269,7 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {
supports_documents: Some(false),
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
},
]),
default_model_id: None,
@@ -295,6 +297,8 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {
assert_eq!(provider.models[1].default_thinking_level, None);
assert_eq!(provider.models[0].available_for_subagents, Some(true));
assert_eq!(provider.models[1].available_for_subagents, None);
+ assert_eq!(provider.models[0].fast_mode_allowed, Some(true));
+ assert_eq!(provider.models[1].fast_mode_allowed, None);
let raw: String = db
.conn()
@@ -318,6 +322,8 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {
assert_eq!(config["models"][1]["supportsDocuments"], false);
assert!(config["models"][1].get("availableForSubagents").is_none());
assert!(config["models"][1].get("supportsImages").is_none());
+ assert_eq!(config["models"][0]["fastModeAllowed"], true);
+ assert!(config["models"][1].get("fastModeAllowed").is_none());
assert_eq!(provider.models[0].supports_images, Some(true));
assert_eq!(provider.models[1].supports_documents, Some(false));
@@ -377,6 +383,7 @@ fn binding_with_alias(id: &str, alias: Option<&str>) -> ModelBinding {
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
}
}
@@ -1560,6 +1567,7 @@ fn binding_with_limits(id: &str, context_window: u32, max_tokens: u32) -> ModelB
supports_documents: None,
available_for_subagents: None,
native_web_search: None,
+ fast_mode_allowed: None,
}
}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 4f86af66b..10bb144b1 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -719,6 +719,20 @@ fn plugin_session_rpc_err(error: impl ToString) -> JsonRpcError {
rpc_err(rpc_code, message, &code)
}
+/// Optional session `/fast` switch (ADR 0332). Absent or null leaves the
+/// stored value; anything but a boolean is rejected rather than coerced.
+fn fast_mode_param(params: &Value) -> Result<Option<bool>, JsonRpcError> {
+ match params.get("fastMode") {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::Bool(value)) => Ok(Some(*value)),
+ Some(_) => Err(rpc_err(
+ 1002,
+ "fastMode must be a boolean",
+ "INVALID_PARAMS",
+ )),
+ }
+}
+
/// Parse the optional session thinking selector at the RPC boundary. A
/// missing/null value keeps the backwards-compatible default; present values
/// must be strings from the host's allowlist rather than being silently
@@ -2555,6 +2569,7 @@ async fn handle_request(
}
"session.create" => {
let thinking_level = thinking_level_param(&params)?;
+ let fast_mode = fast_mode_param(&params)?.unwrap_or(false);
let permission_parent = permission_parent_param(&params)?;
// ADR 0329: an isolated session gets its own git worktree.
let isolated = params
@@ -2616,6 +2631,7 @@ async fn handle_request(
.map(str::to_string),
thinking_level,
permission_mode,
+ fast_mode,
},
)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
@@ -2782,8 +2798,9 @@ async fn handle_request(
.and_then(|v| v.as_str())
.ok_or_else(|| rpc_err(1002, "mode required", "INVALID_PARAMS"))?;
let thinking_level = thinking_level_param(&params)?;
+ let fast_mode = fast_mode_param(&params)?;
let st = state.lock().await;
- let session = sessions::configure_session_with_thinking(
+ let session = sessions::configure_session_with_fast_mode(
&st.db,
id,
mode,
@@ -2791,6 +2808,7 @@ async fn handle_request(
params.get("modelId").and_then(|v| v.as_str()),
thinking_level.as_deref(),
params.get("permissionMode").and_then(|v| v.as_str()),
+ fast_mode,
)
.map_err(|e| {
let message = e.to_string();
@@ -6682,6 +6700,58 @@ mod tests {
);
}
+ /// ADR 0332: `fastMode` is an optional boolean on create and configure;
+ /// an absent value keeps the stored switch and a non-boolean is rejected.
+ #[tokio::test]
+ async fn session_fast_mode_rpc_is_optional_boolean_and_preserved() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let mut app_state = AppState::open(data_dir.path()).unwrap();
+ app_state.handshook = true;
+ let state = Arc::new(Mutex::new(app_state));
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let call = |method: &'static str, params: Value| {
+ handle_request(state.clone(), method, params, tx.clone())
+ };
+
+ let legacy = call("session.create", json!({ "mode": "agent" }))
+ .await
+ .unwrap();
+ assert_eq!(legacy["session"]["fastMode"], false);
+ let created = call(
+ "session.create",
+ json!({ "mode": "agent", "fastMode": true }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(created["session"]["fastMode"], true);
+ let id = created["session"]["id"].as_str().unwrap().to_string();
+
+ let kept = call(
+ "session.configure",
+ json!({ "id": id, "mode": "plan", "thinkingLevel": "high" }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(kept["session"]["fastMode"], true);
+ let off = call(
+ "session.configure",
+ json!({ "id": id, "mode": "agent", "fastMode": false }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(off["session"]["fastMode"], false);
+
+ for method in ["session.create", "session.configure"] {
+ let error = call(
+ method,
+ json!({ "id": id, "mode": "agent", "fastMode": "yes" }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ }
+ }
+
#[tokio::test]
async fn session_create_rpc_inherits_optional_permission_mode() {
let data_dir = tempfile::tempdir().unwrap();
diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rs
index 7e043f47a..f86ca943a 100644
--- a/crates/host-core/src/rpc/scheduled_rpc.rs
+++ b/crates/host-core/src/rpc/scheduled_rpc.rs
@@ -192,6 +192,8 @@ fn handle_with_workspace_policy(
.permission_mode
.clone()
.or_else(|| automatic.then(|| "ask".into())),
+ // Unattended runs keep the default tier (ADR 0332).
+ fast_mode: false,
};
let uses_task_execution_settings = task.permission_mode.is_some()
|| task.thinking_level.is_some()
diff --git a/crates/host-core/src/session_collaboration/mod.rs b/crates/host-core/src/session_collaboration/mod.rs
index 50077ead6..dac851691 100644
--- a/crates/host-core/src/session_collaboration/mod.rs
+++ b/crates/host-core/src/session_collaboration/mod.rs
@@ -167,6 +167,8 @@ fn spawn(db: &Database, input: &Value) -> Result<Value> {
project_path: parent.summary.project_path,
thinking_level: Some(parent.summary.thinking_level),
permission_mode: Some(parent.summary.permission_mode),
+ // Delegated workers keep the default tier (ADR 0332).
+ fast_mode: false,
},
)?;
db.conn().execute("INSERT INTO session_collaboration_links(session_id,created_by_session_id,plugin_id,created_at) VALUES(?1,?2,?3,?4)",params![created.id,source,plugin,now_ms()])?;
diff --git a/crates/host-core/src/session_search.rs b/crates/host-core/src/session_search.rs
index f291265f1..a1aac3775 100644
--- a/crates/host-core/src/session_search.rs
+++ b/crates/host-core/src/session_search.rs
@@ -107,7 +107,8 @@ pub fn search(db: &Database, query: &str, offset: i64, limit: i64) -> Result<Sea
p.name, COALESCE(matched.count, 0),
(pi_search_contains(s.title, ?1) OR pi_search_contains(p.name, ?1)
OR pi_search_contains(p.path, ?1)) AS metadata_match,
- EXISTS (SELECT 1 FROM task_runs r WHERE r.session_id = s.id) AS scheduled_run
+ EXISTS (SELECT 1 FROM task_runs r WHERE r.session_id = s.id) AS scheduled_run,
+ s.fast_mode
FROM sessions s LEFT JOIN projects p ON p.id = s.project_id
LEFT JOIN matched ON matched.session_id = s.id
WHERE s.deleted_at IS NULL AND (matched.count > 0 OR metadata_match)
diff --git a/crates/host-core/src/session_worktrees/delegate/tests.rs b/crates/host-core/src/session_worktrees/delegate/tests.rs
index 88c5e8de0..f66ab539f 100644
--- a/crates/host-core/src/session_worktrees/delegate/tests.rs
+++ b/crates/host-core/src/session_worktrees/delegate/tests.rs
@@ -40,6 +40,7 @@ async fn env() -> Env {
project_path: Some(project.to_string_lossy().into_owned()),
thinking_level: None,
permission_mode: None,
+ fast_mode: false,
},
)
.unwrap()
diff --git a/crates/host-core/src/session_worktrees/lifecycle/tests.rs b/crates/host-core/src/session_worktrees/lifecycle/tests.rs
index 708d6855c..6868ba08f 100644
--- a/crates/host-core/src/session_worktrees/lifecycle/tests.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle/tests.rs
@@ -41,6 +41,7 @@ async fn new_session(env: &Env, project: &Path) -> String {
project_path: Some(project.to_string_lossy().into_owned()),
thinking_level: None,
permission_mode: None,
+ fast_mode: false,
},
)
.unwrap()
@@ -259,6 +260,7 @@ fn new_session_blocking(db: &Database, project: &Path) -> String {
project_path: Some(project.to_string_lossy().into_owned()),
thinking_level: None,
permission_mode: None,
+ fast_mode: false,
},
)
.unwrap()
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index df89a3dcc..57f63bc55 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -128,6 +128,10 @@ pub struct SessionSummary {
pub thinking_level: String,
#[serde(default = "default_permission_mode")]
pub permission_mode: String,
+ /// The `/fast` switch for this session's main turns (ADR 0332). Requests
+ /// use the priority tier only when the model binding also allows it.
+ #[serde(default)]
+ pub fast_mode: bool,
pub updated_at: String,
pub created_at: String,
/// True when this session is the transcript owned by a scheduled-task run.
@@ -1290,7 +1294,8 @@ fn session_created_at(db: &Database, session_id: &str) -> Result<String> {
const SUMMARY_SELECT: &str =
"SELECT s.id, s.title, s.last_seq, p.path, s.model_id, s.provider_id, s.mode,
s.thinking_level, s.permission_mode, s.updated_at, s.created_at,
- EXISTS (SELECT 1 FROM task_runs r WHERE r.session_id = s.id) AS scheduled_run
+ EXISTS (SELECT 1 FROM task_runs r WHERE r.session_id = s.id) AS scheduled_run,
+ s.fast_mode
FROM sessions s LEFT JOIN projects p ON p.id = s.project_id
WHERE s.deleted_at IS NULL";
@@ -1310,6 +1315,7 @@ pub(crate) fn summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Sess
// Read by name: search and listing build their own column lists, so the
// alias keeps this mapper independent of any one query's column order.
scheduled_run: row.get("scheduled_run")?,
+ fast_mode: row.get("fast_mode")?,
worktree: None,
})
}
@@ -1365,6 +1371,8 @@ pub struct SessionCreateOptions {
pub project_path: Option<String>,
pub thinking_level: Option<String>,
pub permission_mode: Option<String>,
+ /// The `/fast` switch (ADR 0332); false keeps the default service tier.
+ pub fast_mode: bool,
}
pub fn create_session_with_thinking(
@@ -1386,6 +1394,7 @@ pub fn create_session_with_thinking(
project_path,
thinking_level,
permission_mode: None,
+ fast_mode: false,
},
)
}
@@ -1407,6 +1416,7 @@ pub fn create_session_with_options(
project_path,
thinking_level,
permission_mode,
+ fast_mode,
} = options;
let now = now_ms();
let id = Uuid::new_v4().to_string();
@@ -1436,8 +1446,8 @@ pub fn create_session_with_options(
.prepare_cached(
"INSERT INTO sessions (
id, title, project_id, provider_id, model_id, mode, thinking_level,
- permission_mode, title_source, created_at, updated_at
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",
+ permission_mode, title_source, fast_mode, created_at, updated_at
+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11)",
)?
.execute(params![
id,
@@ -1449,6 +1459,7 @@ pub fn create_session_with_options(
thinking_level,
permission_mode,
title_source,
+ fast_mode,
now
])?;
Ok(SessionSummary {
@@ -1461,6 +1472,7 @@ pub fn create_session_with_options(
mode,
thinking_level,
permission_mode,
+ fast_mode,
updated_at: ms_to_ts(now),
created_at: ms_to_ts(now),
// The run row that owns this transcript is written after creation.
@@ -1793,10 +1805,11 @@ pub fn fork_session_through(
.prepare_cached(
"INSERT INTO sessions (
id, title, project_id, provider_id, model_id, mode, thinking_level,
- permission_mode, source, pinned, last_seq, created_at, updated_at
+ permission_mode, fast_mode, source, pinned, last_seq, created_at,
+ updated_at
)
SELECT ?1, ?2, project_id, provider_id, model_id, mode, thinking_level,
- permission_mode, NULL, 0, ?3, ?4, ?4
+ permission_mode, fast_mode, NULL, 0, ?3, ?4, ?4
FROM sessions WHERE id = ?5",
)?
.execute(params![id, title, records.len() as i64, now, source_id])?;
@@ -1825,6 +1838,7 @@ pub fn fork_session_through(
mode: source.summary.mode,
thinking_level: source.summary.thinking_level,
permission_mode: source.summary.permission_mode,
+ fast_mode: source.summary.fast_mode,
updated_at: created_at.clone(),
created_at,
// A fork is the user's own conversation, not the automation's transcript.
@@ -1869,6 +1883,31 @@ pub fn configure_session_with_thinking(
model_id: Option<&str>,
thinking_level: Option<&str>,
permission_mode: Option<&str>,
+) -> Result<Option<SessionSummary>> {
+ configure_session_with_fast_mode(
+ db,
+ id,
+ mode,
+ provider_id,
+ model_id,
+ thinking_level,
+ permission_mode,
+ None,
+ )
+}
+
+/// Full configurator. Every `None` preserves the persisted value, including
+/// the `/fast` switch (ADR 0332).
+#[allow(clippy::too_many_arguments)]
+pub fn configure_session_with_fast_mode(
+ db: &Database,
+ id: &str,
+ mode: &str,
+ provider_id: Option<&str>,
+ model_id: Option<&str>,
+ thinking_level: Option<&str>,
+ permission_mode: Option<&str>,
+ fast_mode: Option<bool>,
) -> Result<Option<SessionSummary>> {
if !(is_valid_mode(mode) || mode == "chat") {
return Err(anyhow!("mode must be plan or agent"));
@@ -1896,7 +1935,8 @@ pub fn configure_session_with_thinking(
SET mode = ?2, provider_id = COALESCE(?3, provider_id),
model_id = COALESCE(?4, model_id),
thinking_level = COALESCE(?5, thinking_level),
- permission_mode = COALESCE(?6, permission_mode), updated_at = ?7
+ permission_mode = COALESCE(?6, permission_mode),
+ fast_mode = COALESCE(?8, fast_mode), updated_at = ?7
WHERE id = ?1",
)?
.execute(params![
@@ -1906,7 +1946,8 @@ pub fn configure_session_with_thinking(
model_id,
thinking_level,
permission_mode,
- now_ms()
+ now_ms(),
+ fast_mode
])?;
if changed == 0 {
return Ok(None);
@@ -4746,6 +4787,76 @@ mod tests {
assert_eq!(omitted.thinking_level, "omit");
}
+ /// ADR 0332: `/fast` is stored per session, survives configures that do
+ /// not mention it, and is copied by a fork.
+ #[test]
+ fn session_fast_mode_is_persisted_preserved_and_forked() {
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ assert!(!session.fast_mode);
+
+ let set = |enabled: Option<bool>, mode: &str| {
+ configure_session_with_fast_mode(
+ &db,
+ &session.id,
+ mode,
+ None,
+ None,
+ None,
+ None,
+ enabled,
+ )
+ .unwrap()
+ .unwrap()
+ };
+ assert!(set(Some(true), "agent").fast_mode);
+ assert!(set(None, "plan").fast_mode);
+ let kept = configure_session(&db, &session.id, "agent", None, None)
+ .unwrap()
+ .unwrap();
+ assert!(kept.fast_mode);
+ assert!(
+ get_session(&db, &session.id)
+ .unwrap()
+ .unwrap()
+ .summary
+ .fast_mode
+ );
+
+ let ForkSessionResult::Created(fork) =
+ fork_session_through(&db, &session.id, None, None).unwrap()
+ else {
+ panic!("expected fork");
+ };
+ assert!(fork.summary.fast_mode);
+ assert!(
+ get_session(&db, &fork.summary.id)
+ .unwrap()
+ .unwrap()
+ .summary
+ .fast_mode
+ );
+
+ assert!(!set(Some(false), "agent").fast_mode);
+
+ let created = create_session_with_options(
+ &db,
+ SessionCreateOptions {
+ fast_mode: true,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert!(created.fast_mode);
+ assert!(
+ get_session(&db, &created.id)
+ .unwrap()
+ .unwrap()
+ .summary
+ .fast_mode
+ );
+ }
+
#[test]
fn create_session_permission_mode_is_optional_and_validated() {
let db = test_db();
@@ -5038,6 +5149,7 @@ mod tests {
permission_mode: "inherit".into(),
// Ownership is derived from `task_runs`, so an import is never one.
scheduled_run: false,
+ fast_mode: false,
worktree: None,
created_at: "2025-01-01T00:00:00Z".into(),
updated_at: "2025-01-02T00:00:00Z".into(),
@@ -5091,6 +5203,7 @@ mod tests {
permission_mode: "inherit".into(),
// Ownership is derived from `task_runs`, so an import is never one.
scheduled_run: false,
+ fast_mode: false,
worktree: None,
created_at: "2025-01-01T00:00:00Z".into(),
updated_at: "2025-01-01T00:00:00Z".into(),
@@ -6033,6 +6146,7 @@ mod tests {
permission_mode: "inherit".into(),
// Ownership is derived from `task_runs`, so an import is never one.
scheduled_run: false,
+ fast_mode: false,
worktree: None,
created_at: "2025-01-01T00:00:00Z".into(),
updated_at: "2025-01-01T00:00:00Z".into(),
diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rs
index 92e9b3733..6ca93814e 100644
--- a/crates/host-core/src/turn_queue.rs
+++ b/crates/host-core/src/turn_queue.rs
@@ -532,7 +532,7 @@ mod tests {
assert_eq!(entries[0].content, "existing");
assert!(entries[0].user_message_id.is_none());
assert!(entries[0].voice_origin.is_none());
- assert_eq!(crate::db::SCHEMA_VERSION, 24);
+ assert_eq!(crate::db::SCHEMA_VERSION, 25);
}
#[test]
diff --git a/docs/adr/0332-openai-fast-mode.md b/docs/adr/0332-openai-fast-mode.md
new file mode 100644
index 000000000..1c1a47cec
--- /dev/null
+++ b/docs/adr/0332-openai-fast-mode.md
@@ -0,0 +1,69 @@
+# ADR 0332: OpenAI Fast mode as a per-session switch gated by model settings
+
+- Status: Accepted
+- Date: 2026-10-17
+- Deciders: PI-Desktop maintainers
+- Related: [ADR 0329](0329-session-worktree-isolation.md) ·
+ [03-runtime/11-provider-model-system](../spec/03-runtime/11-provider-model-system.md) ·
+ [04-ux/04-builtin-commands](../spec/04-ux/04-builtin-commands.md) ·
+ issue #1657 · E2E-FAST-MODE
+
+## Context
+
+OpenAI serves a faster priority tier that Codex CLI and the OpenAI API call
+Fast mode. On the wire it is the Responses body field `service_tier:
+"priority"`; the Codex backend rejects `"fast"`. The tier costs more: a ChatGPT
+subscription spends its plan limits faster, and the OpenAI API bills a higher
+per-token price. PI-Desktop never asked for a tier, and pi-ai's `streamSimple`
+does not forward one.
+
+The cost is a decision about one conversation, while whether an endpoint
+honors the field is something only the user knows for a relay. Issue #1657 asks
+for the subscription speed-up; maintainers asked that capability be configured
+in model settings.
+
+## Decision
+
+1. **Model settings own capability.** `ModelBinding.fastModeAllowed` is an
+ opt-in, stored in the existing provider `config_json` like
+ `nativeWebSearch`, so it needs no migration. The checkbox is enabled only
+ for Responses wires (`openai_codex_responses`, `responses`), including
+ relays; its hint names the cost on that wire.
+2. **`/fast` owns the session switch.** A new builtin `builtin.session.fast`
+ (`/fast`) toggles a persisted `sessions.fast_mode` column (schema v25,
+ additive, v24 backup). `session.create` and `session.configure` accept an
+ optional boolean `fastMode`; omission keeps the stored value. Forks copy it;
+ scheduled runs and delegated workers start off. A draft carries it into the
+ session its first prompt creates. Remote sessions refuse it.
+3. **`/fast` only works on a configured model.** When the selected model's
+ wire cannot carry the tier or the model is not allowed, `/fast` stores
+ nothing and points to Settings → Models → Advanced, in either direction. A
+ stale stored switch on such a model is inert because launch also requires
+ the opt-in.
+4. **The launcher resolves; the runtime only stamps the wire.** Session launch
+ sends `fastMode: true` to the sidecar only when the session switch is on and
+ the user's stored binding allows it. The runtime chains a payload hook on
+ main turns that adds `service_tier: "priority"` when the resolved wire is
+ `openai-codex-responses` or `openai-responses`. Subagents, compaction, and
+ one-shot plugin requests build their own options and keep the default tier.
+
+## Alternatives
+
+- **Per-model switch only (no session state).** Avoids a migration, but turns
+ a per-conversation cost into a global one: enabling Fast for one task speeds
+ up and costs every conversation on that model.
+- **Hard-coded capability rule (official OpenAI host only).** Removes a
+ setting, but excludes relays the user knows support the field and hides the
+ decision in code.
+- **Generic request-parameter injection with presets.** More flexible, but an
+ arbitrary body-field channel needs its own validation and permission story,
+ which is larger than this need.
+
+## Consequences
+
+- Schema v25 adds one column; older apps opening a v25 database refuse it as
+ newer, the existing downgrade behavior.
+- The capability can be wrong for a relay that ignores or rebills the field;
+ the settings hint states that risk, and the user owns the opt-in.
+- The Composer model chip shows a Fast mark while the switch is on for an
+ allowed model, so the cost is visible at send time.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 728f4e585..922f4a80c 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -377,6 +377,7 @@ Each ADR includes:
| 0329 | [Isolate parallel sessions of one project in git worktrees](0329-session-worktree-isolation.md) | Accepted (Windows E2E pending) |
| 0330 | [Open scoped HTML files in the work-panel Browser from plugins](0330-open-html-files-in-work-panel-browser-from-plugins.md) | Accepted |
| 0331 | [Plugin session follow and host-owned work-panel reveal](0331-plugin-session-follow-and-work-panel-reveal.md) | Accepted |
+| 0332 | [OpenAI Fast mode as a per-session switch gated by model settings](0332-openai-fast-mode.md) | Accepted |
| plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) |
| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index 367d66664..69b504767 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1 +1,7 @@
# Unreleased changes
+
+- Add OpenAI Fast mode (#1657). Allow it per model in Settings → Models for a
+ ChatGPT subscription or an OpenAI Responses connection, then type `/fast` to
+ turn it on for the current conversation. Requests ask for the priority
+ service tier, which replies faster and spends plan limits faster or bills
+ more per token; the Composer model chip shows a Fast mark while it is on.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 64c0fa905..29d19104f 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -188,6 +188,8 @@ type SessionConfigureRequest = {
providerId?: string;
modelId?: string;
thinkingLevel: SessionThinkingLevel;
+ /** Session `/fast` switch (ADR 0332); omitted keeps the stored value. */
+ fastMode?: boolean;
};
```
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index df5d9d2aa..b0b740862 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1,4 +1,4 @@
-# 04. Data Storage (Schema v23)
+# 04. Data Storage (Schema v25)
## 0. Ownership decision
@@ -585,6 +585,8 @@ CREATE TABLE sessions (
'high', 'xhigh', 'max', 'omit')),
permission_mode TEXT NOT NULL DEFAULT 'inherit' -- D115: inherit follows settings
CHECK (permission_mode IN ('inherit', 'ask', 'accept-edits', 'auto')),
+ fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0332: session /fast switch
+ CHECK (fast_mode IN (0, 1)),
source TEXT, -- import origin: claude-code | codex | opencode | pi
deleted_at INTEGER, -- plugin trash marker; null means active
pinned INTEGER NOT NULL DEFAULT 0,
@@ -1544,7 +1546,7 @@ truncating at a guessed position.
- JSON columns are read blind on hot paths (shipped to the renderer as-is);
anything filtered or summed is a promoted column by rule.
-## 7. Versioning, v7 reset, and v8-to-v23 migration
+## 7. Versioning, v7 reset, and v8-to-v25 migration
- `PRAGMA user_version` stays the schema authority; future structural changes
add ordered Rust migration fns again, each in one transaction, with a
@@ -1555,7 +1557,7 @@ truncating at a guessed position.
Sessions, providers, and settings from the old file are not carried over;
the archive remains for manual recovery. All pre-v7 migration code
(v1 `settings.sqlite` import, v2→v6 chain) is deleted.
-- Fresh installs run the full v23 DDL directly.
+- Fresh installs run the full v25 DDL directly.
- **Schema v7 first reaches v8, then uses the guarded path.** The v7→v8
migration is followed by the same guarded v8→v15 migration; schema-v9 and
schema-v10 databases take the same guarded path and receive an exact readable
@@ -1619,6 +1621,13 @@ truncating at a guessed position.
- **Schema v23 is additive.** It adds `sessions.title_source` and classifies
existing placeholder titles as `default`; every other existing title is
preserved and classified as `manual`. The migration keeps a v22 backup.
+- **Schema v24 is additive.** It adds the `worktrees` registry and
+ `projects.worktree_setup_command` for isolated sessions (ADR 0329). The
+ migration keeps a v23 backup.
+- **Schema v25 is additive.** It adds `sessions.fast_mode` (ADR 0332), the
+ session `/fast` switch, defaulting to `0` for every existing session. Forks
+ copy it; scheduled runs and delegated workers start at `0`. The migration
+ keeps a v24 backup.
- **Schema v14 is additive.** It adds nullable `sessions.deleted_at`, the
partial deletion index, and `session_import_origins`. Existing sessions stay
active and have no origin rows. The migration runs in the same guarded
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index e03cfbd78..c103419bb 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -296,6 +296,8 @@ to later refresh and inference; the vendor picker does not collect them.
`inheritPermissionFromSessionId`; when present, the host copies the existing
session's persisted permission mode atomically, while omission preserves the
existing `inherit` default. Missing/null thinking level defaults to `off`.
+ Optional boolean `fastMode` (ADR 0332) stores the session `/fast` switch;
+ missing/null means `false` and a non-boolean returns `INVALID_PARAMS`.
Optional `isolated: true` (ADR 0329) also requires `projectPath` and gives
the new session its own git worktree before it returns; if the worktree
cannot be created the session is deleted again and the call fails with a
@@ -352,7 +354,9 @@ to later refresh and inference; the vendor picker does not collect them.
- `session.configure` — atomically persists `mode`, `providerId`, `modelId`,
and optional `thinkingLevel` (`off|minimal|low|medium|high|xhigh|max|omit`)
for the next pi turn; omitting/null
- `thinkingLevel` preserves the current value; invalid modes or levels return
+ `thinkingLevel` preserves the current value; optional boolean `fastMode`
+ (ADR 0332) follows the same rule, and a non-boolean is `INVALID_PARAMS`;
+ invalid modes or levels return
`INVALID_PARAMS`; mode is `plan | goal | agent` and changing any session
configuration is allowed only while idle and without a pending/queued/running
Plan or Goal record
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index 30f0f76f8..dbf505947 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -351,6 +351,7 @@ type ModelBinding = {
defaultThinkingLevel: SessionThinkingLevel | null
thinkingProtocol?: "legacy" | "adaptive"
availableForSubagents?: boolean // opt-in for AI-driven delegation
+ fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0332)
}
type SelectedModelRef = {
@@ -383,6 +384,17 @@ array remain future work. A legacy provider with only `defaultModelId` is
materialized as one fallback binding on host read and upgraded to `models` on
the next provider write.
+`ModelBinding.fastModeAllowed` (boolean, default false, ADR 0332): lets the
+session `/fast` switch request OpenAI's priority service tier
+(`service_tier: "priority"`) for this model. Model settings enable the checkbox
+only for Responses wires: `openai_codex_responses` (ChatGPT subscription; the
+tier spends plan limits faster) and `responses` (billed per token at the tier's
+higher price; a relay may ignore or rebill the field). The launcher sends
+`fastMode: true` to the sidecar only when the session switch is on and the
+stored binding allows it; the runtime adds the field to main-turn requests whose
+resolved wire is `openai-codex-responses` or `openai-responses`. Subagents,
+compaction, and one-shot requests keep the default tier.
+
`ModelBinding.availableForSubagents` (boolean, default false): opt-in flag that
makes the model available for AI-driven subagent delegation. When enabled, the
model appears in the delegation catalog injected into the parent agent's system
diff --git a/docs/spec/04-ux/04-builtin-commands.md b/docs/spec/04-ux/04-builtin-commands.md
index 3b00e5779..05c462326 100644
--- a/docs/spec/04-ux/04-builtin-commands.md
+++ b/docs/spec/04-ux/04-builtin-commands.md
@@ -2,7 +2,7 @@
## 1. Goal
-Define the five first-party command palette entries available without plugins.
+Define the six first-party command palette entries available without plugins.
The same entries are available in the composer `/` menu.
Shortcut: **Cmd/Ctrl + Shift + P** (D014)
@@ -15,7 +15,7 @@ builtin.<domain>.<action>
## 3. Core builtin catalog
-The builtin registry intentionally contains exactly these five commands. Plugin
+The builtin registry intentionally contains exactly these six commands. Plugin
commands extend the searchable command list dynamically; app navigation,
project management, settings, plugin management, and diagnostics are not
builtin command contracts.
@@ -27,10 +27,11 @@ builtin command contracts.
| `builtin.mode.agent` | Switch to Agent | mode, agent | Session | low | set the idle session mode to Agent |
| `builtin.mode.plan` | Switch to Plan | mode, plan, planning | Session | low | set the idle session mode to Plan |
| `builtin.mode.goal` | Switch to Goal | mode, goal, objective, autonomous | Session | low | set the idle session mode to Goal |
+| `builtin.session.fast` | Toggle Fast mode | fast, speed, priority, service tier | Session | medium | toggle the session's OpenAI priority service tier (ADR 0332) |
## 4. Visibility and execution rules
-- The five IDs are the complete first-party registry. Removed IDs are not
+- The six IDs are the complete first-party registry. Removed IDs are not
palette results and are not renderer dispatch cases; plugin commands remain
independently discoverable.
- `New Task` uses the current project or temporary group. It selects the
@@ -44,6 +45,15 @@ builtin command contracts.
Agent/Plan/Goal chip. They update an idle session immediately. With no active
session, they update the persisted default for the next session; a running
session or pending approval is not changed.
+- `Toggle Fast mode` flips the session's persisted `fastMode` through the same
+ configuration path (ADR 0332). With no active session it records the switch on
+ the new-task draft, and the created session starts with it. The selected
+ model must allow Fast mode in Settings → Models → Advanced on a Responses
+ wire (Codex subscription or OpenAI Responses); otherwise, in either
+ direction, a warning toast points to that setting and nothing is stored. A
+ stored switch on an unconfigured model has no effect at launch. Remote
+ sessions refuse it. The risk is medium because the priority tier
+ spends plan limits faster or bills more per token.
- `SubmitPlan` and `SubmitGoal` are model tools, not palette commands. There is
no Chat mode or request-changes alias.
- The former app/project/settings/plugin/log commands remain available through
@@ -62,7 +72,7 @@ type CommandExecutionResult =
## 6. Acceptance
-1. The builtin registry contains exactly five unique, prefixed IDs.
+1. The builtin registry contains exactly six unique, prefixed IDs.
2. Palette search matches each title and keyword set.
3. Mode switch commands update the idle session mode immediately; Plan, Goal,
and Agent refer to the same pi Agent.
@@ -84,11 +94,12 @@ in the same registry that feeds palette search
| `/agent-mode` | `builtin.mode.agent` |
| `/plan-mode` | `builtin.mode.plan` |
| `/goal-mode` | `builtin.mode.goal` |
+| `/fast` | `builtin.session.fast` |
Aliases share one namespace with template and plugin command names; builtin
aliases win collisions, then project templates, then user templates, then
-plugin commands. Selecting an alias inserts `/alias `; sending `/new` or
-`/compact` alone executes locally without creating an empty prompt. The
+plugin commands. Selecting an alias inserts `/alias `; sending `/new`,
+`/compact`, or `/fast` alone executes locally without creating an empty prompt. The
Agent/Plan/Goal aliases also support a prompt body:
`/agent-mode <prompt>`, `/plan-mode <prompt>`, or `/goal-mode <prompt>` switches
the idle session (or the next-session default) and sends `<prompt>` through the
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index fc3b8c260..a5192c175 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18217,3 +18217,34 @@ host-created files. The full app's file-preview viewer is covered separately.
`ui.view` gating, panel-bridge channel) and the wiring contract in
`apps/desktop/test/main-wiring-contract.test.mjs`; the interactive Electron
scenario remains a manual validation run.
+
+### E2E-FAST-MODE: `/fast` asks for the priority tier only on an allowed model
+
+- **Preconditions**: A ChatGPT subscription (Codex) account and a Responses
+ API-key provider, each with two configured models. No real provider is
+ required for the automated path; the manual path uses a capturing local
+ endpoint or the user's authorized account.
+- **Steps**:
+ 1. In Settings → Models, check **Fast mode** on one model of each provider.
+ Confirm the checkbox is disabled on a Chat Completions provider.
+ 2. Start a new task on the allowed Codex model, type `/fast`, send a prompt.
+ 3. Send `/fast` again, then send another prompt.
+ 4. Switch the session to the model without the opt-in and send `/fast`.
+ 5. Fork the session while Fast is on; restart the app and reopen both.
+- **Expected**: Step 1 persists `fastModeAllowed` on the binding only. Step 2
+ shows the Fast mark on the model chip and the request body carries
+ `service_tier: "priority"`; a Responses API-key model shows the per-token
+ price toast instead. Step 3 clears the mark and the field. Step 4 refuses
+ with the model-settings hint and stores nothing. Step 5 keeps the switch on
+ the fork and across restart. Subagent and compaction requests never carry
+ the field. Remote sessions refuse `/fast`.
+- **Specs linked**: `03-runtime/11-provider-model-system.md`,
+ `03-runtime/04-data-storage.md` (v25), `04-ux/04-builtin-commands.md`,
+ ADR 0332, issue #1657.
+- **Status**: Automated coverage: `apps/desktop/test/fast-mode-command.test.mjs`
+ (draft → created session, toggle, refusals, remote, chip),
+ `apps/desktop/test/fast-mode-session-launch.test.mjs` (launch resolution),
+ `packages/agent-runtime/src/fast-mode.test.ts` (request body through the real
+ pi-ai Responses and Completions adapters), host-core migration, RPC and fork
+ tests. The full settings → `/fast` → captured request path is a manual
+ validation scenario.
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 79a7716a2..b3a25113a 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -158,6 +158,8 @@ type SessionConfigureRequest = {
providerId?: string;
modelId?: string;
thinkingLevel: SessionThinkingLevel;
+ /** Session `/fast` switch (ADR 0332); omitted keeps the stored value. */
+ fastMode?: boolean;
};
```
diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.md
index 5b8bc49f7..33c9c1711 100644
--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md
+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md
@@ -1,4 +1,4 @@
-# 04. 数据存储(架构 v23)
+# 04. 数据存储(架构 v25)
> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/04-data-storage) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。
@@ -362,6 +362,8 @@ CREATE TABLE sessions (
'high', 'xhigh', 'max', 'omit')),
permission_mode TEXT NOT NULL DEFAULT 'inherit' -- D115: inherit follows settings
CHECK (permission_mode IN ('inherit', 'ask', 'accept-edits', 'auto')),
+ fast_mode INTEGER NOT NULL DEFAULT 0 -- ADR 0332: session /fast switch
+ CHECK (fast_mode IN (0, 1)),
source TEXT, -- import origin: claude-code | codex | opencode | pi
deleted_at INTEGER, -- plugin trash marker; null means active
pinned INTEGER NOT NULL DEFAULT 0,
@@ -1160,7 +1162,7 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录
- JSON 列在热路径上盲读(按原样发送到渲染器);
任何过滤或求和的内容都是按规则提升的列。
-## 7. 版本控制、v7 重置和 v8 到 v23 迁移
+## 7. 版本控制、v7 重置和 v8 到 v25 迁移
- `PRAGMA user_version` 保留模式权限;未来的结构性变化
再次添加有序的 Rust 迁移 fns,每个都在一个事务中,并带有一个
@@ -1171,7 +1173,7 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录
旧文件中的会话、提供程序和设置不会保留;
存档仍保留以供手动恢复。所有 v7 之前的迁移代码
(v1 `settings.sqlite` 导入,v2→v6 链)被删除。
-- 全新安装直接运行完整的 v23 DDL。
+- 全新安装直接运行完整的 v25 DDL。
- **架构 v15 是增量的。** 它增加 `turn_queue` 表及其两个索引(D386 / ADR 0213),使 Host
拥有的回合队列在重启后存活;不改动任何已有行,迁移前保留 `pi.sqlite.v14.bak`。
- **架构 v16 是增量的。** 它增加会话协作 link 和投递表、生命周期索引,以及可为空的
@@ -1184,6 +1186,11 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录
`default`;其余现有标题保持原样并归类为 `manual`。迁移前保留 v22 备份。
v15→v16 会话协作步骤现在写入 `16`(它自己的版本)而不是最新的架构常量,
因此 v15 文件可以在一次启动中走完两个步骤。
+- **架构 v24 是增量的。** 它为隔离会话增加 `worktrees` 登记表和
+ `projects.worktree_setup_command`(ADR 0329)。迁移前保留 v23 备份。
+- **架构 v25 是增量的。** 它增加 `sessions.fast_mode`(ADR 0332),即会话的 `/fast`
+ 开关,所有已有会话默认为 `0`。fork 会复制该值;定时任务运行和委托子会话从 `0` 开始。
+ 迁移前保留 v24 备份。
- **架构 v7 首先到达 v8,然后使用受保护的路径。** v7→v8
迁移之后是相同的受保护的 v8→v15 迁移;架构-v9 和
schema-v10 数据库采用相同的受保护路径并接收精确的可读数据
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index b47139846..fa7897617 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -226,7 +226,8 @@ type ToolBudgetHealth = {
### 会议
- `session.list`
- `session.create` — 接受可选的 `thinkingLevel`; missing/null 默认值
-至 `off`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话
+至 `off`。可选布尔值 `fastMode`(ADR 0332)保存会话的 `/fast` 开关;缺省/null 表示
+`false`,非布尔值返回 `INVALID_PARAMS`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话
创建专属 git worktree;无法创建时会话会被删除,调用以 `WORKTREE_*` 错误(§7)失败。
- `session.fork` — accepts `sessionId`, an optional caller-provided display
`title`, and optional `throughMessageId`; creates
@@ -252,7 +253,8 @@ type ToolBudgetHealth = {
并且不更新 `updated_at`、转录内容或消息数。
- `session.configure` — 以原子方式持久保存 `mode`、`providerId`、`modelId`,
以及可选的 `thinkingLevel` 用于下一个 pi 回合; omitting/null
- `thinkingLevel` 保留当前值;返回无效模式或级别
+ `thinkingLevel` 保留当前值;可选布尔值 `fastMode`(ADR 0332)遵循同一规则,
+ 非布尔值返回 `INVALID_PARAMS`;返回无效模式或级别
`INVALID_PARAMS`;模式为 `plan | goal | agent` 并更改任何会话
仅在空闲且没有 pending/queued/running 时才允许配置
Plan 或 Goal 记录
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index dec4160c9..b97b73211 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -295,6 +295,7 @@ type ModelBinding = {
thinkingLevels: ThinkingLevel[]
defaultThinkingLevel: SessionThinkingLevel | null
availableForSubagents?: boolean // opt-in for AI-driven delegation
+ fastModeAllowed?: boolean // opt-in for the session /fast switch (ADR 0332)
}
type SelectedModelRef = {
@@ -323,6 +324,14 @@ type ThinkingLevel =
后续工作。只有 `defaultModelId` 的旧版提供商,在主机读取时会被具体化为一条
回退 binding,并在下一次提供商写入时升级为 `models`。
+`ModelBinding.fastModeAllowed`(布尔值,默认 false,ADR 0332):允许会话的 `/fast`
+开关为该模型请求 OpenAI 优先服务档位(`service_tier: "priority"`)。模型设置只在
+Responses 协议上启用该勾选框:`openai_codex_responses`(ChatGPT 订阅,优先档位会更快
+消耗订阅额度)和 `responses`(按优先档位更高的 token 单价计费;中转服务可能忽略或
+另行计费)。只有当会话开关打开且保存的 binding 允许时,启动器才向 sidecar 发送
+`fastMode: true`;运行时只在解析后的协议为 `openai-codex-responses` 或
+`openai-responses` 的主回合请求中加入该字段。子代理、压缩和一次性请求保持默认档位。
+
`ModelBinding.availableForSubagents`(布尔值,默认 false):这是一个选择加入
的标志,让该模型可用于 AI 驱动的子代理委托。启用后,该模型会出现在注入父
agent 系统提示的委托目录中。父 agent 随后就能通过 Task 工具的 `model` 参数
diff --git a/docs/zh-CN/spec/04-ux/04-builtin-commands.md b/docs/zh-CN/spec/04-ux/04-builtin-commands.md
index 331ee02c8..1403d9266 100644
--- a/docs/zh-CN/spec/04-ux/04-builtin-commands.md
+++ b/docs/zh-CN/spec/04-ux/04-builtin-commands.md
@@ -4,7 +4,7 @@
## 1. 目标
-定义无需插件即可使用的五条第一方命令。它们也会出现在输入框的 `/` 菜单中。
+定义无需插件即可使用的六条第一方命令。它们也会出现在输入框的 `/` 菜单中。
快捷键:**Cmd/Ctrl + Shift + P**(D014)
@@ -16,7 +16,7 @@ builtin.<domain>.<action>
## 3. 核心内置目录
-内置 registry 有意只包含以下五条命令。插件命令会动态扩展可搜索的命令列表;
+内置 registry 有意只包含以下六条命令。插件命令会动态扩展可搜索的命令列表;
应用导航、项目管理、设置、插件管理和诊断不属于内置命令契约。
| id | 标题 | 关键词 | 类别 | 风险 | 行为 |
@@ -26,10 +26,11 @@ builtin.<domain>.<action>
| `builtin.mode.agent` | 切换到 Agent | mode、agent | Session | 低 | 将空闲会话模式设为 Agent |
| `builtin.mode.plan` | 切换到 Plan | mode、plan、planning | Session | 低 | 将空闲会话模式设为 Plan |
| `builtin.mode.goal` | 切换到 Goal | mode、goal、objective、autonomous | Session | 低 | 将空闲会话模式设为 Goal |
+| `builtin.session.fast` | 切换 Fast 模式 | fast、speed、priority、service tier | Session | 中 | 切换会话的 OpenAI 优先服务档位(ADR 0332) |
## 4. 可见性与执行规则
-- 五个 ID 构成完整的第一方 registry。移除的 ID 不会出现在命令面板结果中,
+- 六个 ID 构成完整的第一方 registry。移除的 ID 不会出现在命令面板结果中,
也不再有渲染器 dispatch case;插件命令仍可独立发现。
- `New Task` 使用当前项目或临时分组。若该组最新会话为空则选中复用;否则
在第一帧露出空首页并创建持久空会话。同一分组内该操作是幂等的。
@@ -38,6 +39,12 @@ builtin.<domain>.<action>
- 模式命令使用与 Composer Agent/Plan/Goal 芯片相同的活动会话配置路径,立即更新
空闲会话。没有活动会话时,它们更新下一个会话使用的持久化默认值;正在运行的会话
或待审批会话不会被修改。
+- `Toggle Fast mode` 通过同一条配置路径翻转会话持久化的 `fastMode`(ADR 0332)。
+ 没有活动会话时,它记录在新任务草稿上,创建出的会话会带上该开关。所选模型必须在
+ 「设置 → 模型 → 高级」中允许 Fast 模式,且走 Responses 协议(Codex 订阅或 OpenAI
+ Responses);否则无论开启还是关闭,都只弹出警告指向该设置,不保存任何状态。未配置
+ 模型上残留的开关在启动时不生效。远程会话拒绝该命令。风险为中,
+ 因为优先档位会更快消耗订阅额度,或按更高的 token 单价计费。
- `SubmitPlan` 和 `SubmitGoal` 是模型工具,不是命令面板命令。没有 Chat 模式或
request-changes 别名。
- 原有的应用、项目、设置、插件和日志操作(仍适用时)通过各自的专用界面提供,
@@ -55,7 +62,7 @@ type CommandExecutionResult =
## 6. 验收
-1. 内置 registry 恰好包含五个唯一且带前缀的 ID。
+1. 内置 registry 恰好包含六个唯一且带前缀的 ID。
2. 命令面板搜索可匹配每条命令的标题和关键词。
3. 模式切换命令立即更新空闲会话模式;Plan、Goal 和 Agent 使用同一个 pi Agent。
4. Compact 在空闲时可用,在活动回合/检查点期间返回 `AGENT_BUSY`。
@@ -74,9 +81,10 @@ type CommandExecutionResult =
| `/agent-mode` | `builtin.mode.agent` |
| `/plan-mode` | `builtin.mode.plan` |
| `/goal-mode` | `builtin.mode.goal` |
+| `/fast` | `builtin.session.fast` |
别名与模板和插件命令名称共享一个命名空间;冲突时优先使用内置别名,其次是项目模板、
-用户模板和插件命令。选择别名会插入 `/alias `;单独发送 `/new` 或 `/compact` 时,
+用户模板和插件命令。选择别名会插入 `/alias `;单独发送 `/new`、`/compact` 或 `/fast` 时,
会在本地执行,不会创建空提示。Agent/Plan/Goal 别名支持附带提示词:
`/agent-mode <prompt>`、`/plan-mode <prompt>` 或 `/goal-mode <prompt>` 会切换空闲会话
(或下一个会话默认值),并通过正常提示路径发送 `<prompt>`。不带正文的模式别名仍然
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 6783212d8..492b10952 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -9765,3 +9765,21 @@ host-created files. The full app's file-preview viewer is covered separately.
- **关联规格**:`04-ux/01-ui-ia.md` §3.2、`04-ux/06-settings-ia.md`(常规 → 侧边栏卡片)。
- **验收**:项目折叠时仍能回答“这里是否有正在运行的工作”,且两种提示可从持久化设置独立控制。
- **状态**:草稿。现有 `apps/desktop/test/sidebar-project-runs.test.mjs` 覆盖数量分类、总开关与子开关门控、两种渲染入口,以及主题令牌和减少动态效果保证;它不覆盖设置 API 缺省值规范化或完整交互,相关场景仍需在可用环境手动验证。
+
+### E2E-FAST-MODE:`/fast` 只在允许的模型上请求优先档位
+
+- **前置条件**:一个 ChatGPT 订阅(Codex)账号和一个 Responses API key 提供商,各配置两个模型。
+ 自动化路径不需要真实提供商;手动路径使用可捕获请求的本地端点或用户授权的账号。
+- **步骤**:
+ 1. 在「设置 → 模型」中为每个提供商的一个模型勾选 **Fast 模式**;确认 Chat Completions 提供商上该勾选框不可用。
+ 2. 在允许的 Codex 模型上新建任务,输入 `/fast`,发送一条提示。
+ 3. 再次发送 `/fast`,然后再发送一条提示。
+ 4. 把会话切换到未允许的模型,发送 `/fast`。
+ 5. 在 Fast 开启时 fork 会话;重启应用后重新打开两个会话。
+- **预期**:第 1 步只在 binding 上保存 `fastModeAllowed`。第 2 步模型芯片显示 Fast 标识,请求体带有
+ `service_tier: "priority"`;Responses API key 模型改为提示按 token 计费的价格。第 3 步清除标识和该字段。
+ 第 4 步给出模型设置提示并拒绝,不保存任何状态。第 5 步 fork 和重启后开关保持开启。子代理和压缩请求
+ 从不携带该字段。远程会话拒绝 `/fast`。
+- **关联规格**:`03-runtime/11-provider-model-system.md`、`03-runtime/04-data-storage.md`(v25)、
+ `04-ux/04-builtin-commands.md`、ADR 0332、issue #1657。
+- **状态**:自动化覆盖见英文版。完整的设置 → `/fast` → 捕获请求路径为手动验证场景。
diff --git a/packages/agent-runtime/src/fast-mode.test.ts b/packages/agent-runtime/src/fast-mode.test.ts
new file mode 100644
index 000000000..0bf505f49
--- /dev/null
+++ b/packages/agent-runtime/src/fast-mode.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import type { Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
+import { streamSimple as completionsStreamSimple } from "@earendil-works/pi-ai/api/openai-completions";
+import { streamSimple as responsesStreamSimple } from "@earendil-works/pi-ai/api/openai-responses";
+import { withFastModeOptions } from "./fast-mode.js";
+
+const RELAY = "https://relay.example.com/v1";
+
+const responsesModel = {
+ id: "gpt-test",
+ name: "GPT Test",
+ api: "openai-responses",
+ provider: "relay-uuid",
+ baseUrl: RELAY,
+ reasoning: false,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 128_000,
+ maxTokens: 8_192,
+} as Model<"openai-responses">;
+
+function capture() {
+ const bodies: Array<Record<string, unknown>> = [];
+ const fetch: typeof globalThis.fetch = async (_url, init) => {
+ bodies.push(JSON.parse(String(init?.body)) as Record<string, unknown>);
+ return new Response(JSON.stringify({ error: { message: "fixture response" } }), {
+ status: 502,
+ headers: { "content-type": "application/json" },
+ });
+ };
+ return { bodies, options: { apiKey: "sk-test", fetch } satisfies SimpleStreamOptions };
+}
+
+const context = { messages: [{ role: "user", content: "hi", timestamp: 1 }] } as never;
+
+describe("withFastModeOptions", () => {
+ it("sends the priority tier on the Responses wire when allowed and switched on", async () => {
+ const { bodies, options } = capture();
+ await responsesStreamSimple(
+ responsesModel,
+ context,
+ withFastModeOptions(options, true),
+ ).result();
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].service_tier).toBe("priority");
+ });
+
+ it("keeps the default tier when Fast mode is off", async () => {
+ const { bodies, options } = capture();
+ const hooked = withFastModeOptions(options, false);
+ expect(hooked).toBe(options);
+ await responsesStreamSimple(responsesModel, context, hooked).result();
+ expect(bodies[0].service_tier).toBeUndefined();
+ });
+
+ it("leaves a Chat Completions request untouched even when switched on", async () => {
+ const { bodies, options } = capture();
+ const model = { ...responsesModel, api: "openai-completions" } as Model<"openai-completions">;
+ await completionsStreamSimple(
+ model,
+ context,
+ withFastModeOptions(options, true),
+ ).result();
+ expect(bodies[0].service_tier).toBeUndefined();
+ });
+
+ it("chains after an earlier payload hook and keeps its replacement", async () => {
+ const options: SimpleStreamOptions = {
+ onPayload: async (payload) => ({ ...(payload as object), prompt_cache_key: "kept" }),
+ };
+ const hooked = withFastModeOptions(options, true);
+ const payload = await hooked.onPayload?.({ model: "gpt-test" }, responsesModel);
+ expect(payload).toEqual({ model: "gpt-test", prompt_cache_key: "kept", service_tier: "priority" });
+ });
+});
diff --git a/packages/agent-runtime/src/fast-mode.ts b/packages/agent-runtime/src/fast-mode.ts
new file mode 100644
index 000000000..893bc58a1
--- /dev/null
+++ b/packages/agent-runtime/src/fast-mode.ts
@@ -0,0 +1,34 @@
+/**
+ * OpenAI Fast mode on the request body (ADR 0332).
+ *
+ * pi-ai's `streamSimple` does not forward a service tier, so the priority tier
+ * is set through the payload hook, the same channel the session-affinity body
+ * key uses. The launcher has already combined the session `/fast` switch with
+ * the model binding's opt-in; the hook still reads the wire of the model being
+ * called, so a request that does not travel on a Responses wire keeps its bytes.
+ */
+
+import type { SimpleStreamOptions } from "@earendil-works/pi-ai";
+import { FAST_MODE_SERVICE_TIER, fastModeSupportedOn } from "@pi-desktop/shared";
+
+/** Chain a payload hook that asks for the priority tier when Fast mode is on. */
+export function withFastModeOptions(
+ options: SimpleStreamOptions,
+ fastMode: boolean,
+): SimpleStreamOptions {
+ if (fastMode !== true) return options;
+ const previous = options.onPayload;
+ return {
+ ...options,
+ onPayload: async (payload, model) => {
+ const replacement = await previous?.(payload, model);
+ const base = replacement === undefined ? payload : replacement;
+ if (!isRecord(base) || !fastModeSupportedOn(model.api)) return replacement;
+ return { ...base, service_tier: FAST_MODE_SERVICE_TIER };
+ },
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index aeeeedb62..5c576855a 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -240,6 +240,7 @@ import {
openCodeEndpointFromProvider,
withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
+import { withFastModeOptions } from "./fast-mode.js";
import { withSessionAffinityOptions } from "./session-affinity.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
import type { CompactionRequestShape } from "./compaction-diagnostics.js";
@@ -978,6 +979,11 @@ export type AgentRuntimeOptions = {
thinkingLevel: SessionThinkingLevel;
/** Persisted opt-in for retrying transient provider failures until success. */
infiniteProviderRetry?: boolean;
+ /**
+ * Fast mode for main turns, already resolved by the launcher from the
+ * session `/fast` switch and the model binding's opt-in (ADR 0332).
+ */
+ fastMode?: boolean;
/** TypeSafe Jev credential, resolved by Electron main only when enabled. */
jevApiKey?: string;
systemPrompt?: string;
@@ -1920,6 +1926,7 @@ export class DesktopAgentRuntime {
private providerRateLimitRetryAttempt = 0;
/** Opt-in mode removes only the retry-count ceiling; abort and backoff stay intact. */
private infiniteProviderRetry = false;
+ private fastMode = false;
private jevApiKey?: string;
private activeProviderRetryAttempt = 0;
private providerRetryInProgress = false;
@@ -2023,6 +2030,7 @@ export class DesktopAgentRuntime {
this.provider = opts.provider;
this.thinkingLevel = clampThinkingLevel(opts.provider, opts.thinkingLevel);
this.infiniteProviderRetry = opts.infiniteProviderRetry === true;
+ this.fastMode = opts.fastMode === true;
this.jevApiKey = opts.jevApiKey;
this.host = opts.host;
this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
@@ -2183,14 +2191,19 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
),
m.api,
);
- const hookedOptions = withSessionAffinityOptions(
- this.withExtensionProviderHooks(requestOptions, m),
- {
- provider: this.provider,
- api: m.api,
- baseUrl: m.baseUrl,
- sessionId: this.sessionId,
- },
+ // Only main turns ask for the priority tier: subagents, compaction and
+ // one-shot requests build their own options and keep the default.
+ const hookedOptions = withFastModeOptions(
+ withSessionAffinityOptions(
+ this.withExtensionProviderHooks(requestOptions, m),
+ {
+ provider: this.provider,
+ api: m.api,
+ baseUrl: m.baseUrl,
+ sessionId: this.sessionId,
+ },
+ ),
+ this.fastMode,
);
// The watchdog must be able to *stop* what it abandons. It wraps the
// retry adapter, so draining alone would let the adapter wake from its
@@ -2329,6 +2342,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.infiniteProviderRetry = enabled;
}
+ /** Apply the session `/fast` switch to the next turn of a reused runtime. */
+ setFastMode(enabled: boolean): void {
+ if (this.disposed) throw new Error("runtime disposed");
+ this.fastMode = enabled;
+ }
+
/** Refresh catalog instructions without changing the running session owner. */
setPluginSkills(skills: PluginSkillDef[]): void {
if (this.disposed) throw new Error("runtime disposed");
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index c591dabaf..9ed694ee0 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -106,6 +106,8 @@ type RuntimeParams = {
turnId?: string;
thinkingLevel?: SessionThinkingLevel;
infiniteProviderRetry?: boolean;
+ /** Session `/fast` switch AND the model's opt-in, resolved by main (ADR 0332). */
+ fastMode?: boolean;
/** Opt-in TypeSafe classifier credential resolved by Electron main. */
jevApiKey?: string;
provider: RuntimeProviderConfig;
@@ -253,6 +255,7 @@ async function runtimeFor(
reusable.setPluginSkills(pluginSkills);
reusable.setCompactionSettings(params.compactionSettings);
reusable.setInfiniteProviderRetry(params.infiniteProviderRetry === true);
+ reusable.setFastMode(params.fastMode === true);
reusable.setMode(mode);
return reusable;
}
@@ -301,6 +304,7 @@ async function runtimeFor(
commandShell: params.commandShell,
thinkingLevel,
infiniteProviderRetry: params.infiniteProviderRetry === true,
+ fastMode: params.fastMode === true,
jevApiKey: params.jevApiKey,
history,
compaction,
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 0fa00141c..5be755158 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -645,6 +645,13 @@ export const de = {
"modelBadgeVision": "Vision",
"permissionMode": "Berechtigungsmodus",
"reasoningLevel": "Argumentationsebene",
+ "fastModeBadge": "Fast",
+ "fastModeOn": "Fast-Modus für diese Sitzung an. Antworten kommen schneller und verbrauchen mehr Nutzungslimit deines Abos.",
+ "fastModeOnUsage": "Fast-Modus für diese Sitzung an. Dieses Modell wird pro Token zum höheren Preis der Prioritätsstufe abgerechnet.",
+ "fastModeOff": "Fast-Modus für diese Sitzung aus.",
+ "fastModeUnsupported": "Der Fast-Modus braucht ein Modell über die OpenAI Responses API oder ein ChatGPT-Abo.",
+ "fastModeNotAllowed": "Für dieses Modell ist der Fast-Modus nicht eingerichtet. Aktiviere ihn unter Einstellungen → Modelle → Erweitert.",
+ "fastModeRemote": "Remote-Sitzungen nutzen die Modellkonfiguration des Hosts, daher ist der Fast-Modus nicht verfügbar.",
"permissionInherit": "Standard",
"permissionAsk": "Immer nachfragen",
"permissionAcceptEdits": "Änderungen akzeptieren",
@@ -1712,6 +1719,10 @@ sklm: {
"nativeWebSearch": "Native Websuche",
"nativeWebSearchHint": "Hängt das vom Anbieter gehostete Websuche-Tool an Anfragen für dieses Modell an. Erfordert einen Endpunkt, der dies unterstützt; die Abrechnung erfolgt pro Suche beim Anbieter.",
nativeWebSearchUnsupported: "Diese Verbindung unterstützt in der App noch keine native Suche. Die Website oder eine andere API kann Suche anbieten.",
+ fastModeAllowed: "Fast-Modus",
+ fastModeAllowedSubscriptionHint: "Erlaubt /fast, für dieses Modell die Prioritätsstufe von OpenAI anzufordern. Antworten kommen schneller und verbrauchen mehr Nutzungslimit deines ChatGPT-Abos.",
+ fastModeAllowedUsageHint: "Erlaubt /fast, für dieses Modell die Prioritätsstufe von OpenAI (service_tier) anzufordern. OpenAI berechnet dafür einen höheren Preis pro Token; ein Relay kann das Feld ignorieren oder anders abrechnen.",
+ fastModeAllowedUnsupported: "Der Fast-Modus braucht die OpenAI Responses API oder ein ChatGPT-Abo.",
"searchModelId": "Modell-ID suchen…",
"searchChosenModels": "Hinzugefügte Modelle suchen…",
"noChosenModelMatches": "Keine passenden hinzugefügten Modelle.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 7b16fca98..f6987ac41 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -657,6 +657,13 @@ export const en = {
modelBadgeVision: "vision",
permissionMode: "Permission mode",
reasoningLevel: "Reasoning level",
+ fastModeBadge: "Fast",
+ fastModeOn: "Fast mode on for this session. Replies come faster and use more of your plan's usage limits.",
+ fastModeOnUsage: "Fast mode on for this session. This model is billed per token at the priority tier's higher price.",
+ fastModeOff: "Fast mode off for this session.",
+ fastModeUnsupported: "Fast mode needs a model on the OpenAI Responses API or a ChatGPT subscription.",
+ fastModeNotAllowed: "Fast mode is not configured for this model. Turn it on in Settings → Models → Advanced.",
+ fastModeRemote: "Remote sessions use the Host's model configuration, so Fast mode is not available.",
permissionInherit: "Default",
permissionAsk: "Ask every time",
permissionAcceptEdits: "Accept edits",
@@ -1732,6 +1739,10 @@ sklm: {
nativeWebSearch: "Native web search",
nativeWebSearchHint: "Attach the provider-hosted web search tool to requests for this model. Requires an endpoint that supports it; billed by the provider per search.",
nativeWebSearchUnsupported: "This app has not integrated native search for this connection. Website search or another API may still be available.",
+ fastModeAllowed: "Fast mode",
+ fastModeAllowedSubscriptionHint: "Let /fast request OpenAI's priority tier for this model. Replies come faster and use more of your ChatGPT plan's usage limits.",
+ fastModeAllowedUsageHint: "Let /fast request OpenAI's priority tier (service_tier) for this model. OpenAI bills the tier at a higher per-token price; a relay may ignore the field or bill it differently.",
+ fastModeAllowedUnsupported: "Fast mode needs the OpenAI Responses API or a ChatGPT subscription.",
searchModelId: "Search model ID…",
searchChosenModels: "Search added models…",
noChosenModelMatches: "No matching added models.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 205a5595a..353b5ca8a 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -645,6 +645,13 @@ export const es = {
"modelBadgeVision": "visión",
"permissionMode": "Modo de permiso",
"reasoningLevel": "Nivel de razonamiento",
+ "fastModeBadge": "Fast",
+ "fastModeOn": "Modo Fast activado en esta sesión. Las respuestas llegan antes y consumen más del límite de uso de tu plan.",
+ "fastModeOnUsage": "Modo Fast activado en esta sesión. Este modelo se factura por token al precio más alto del nivel prioritario.",
+ "fastModeOff": "Modo Fast desactivado en esta sesión.",
+ "fastModeUnsupported": "El modo Fast necesita un modelo de la API Responses de OpenAI o una suscripción a ChatGPT.",
+ "fastModeNotAllowed": "El modo Fast no está configurado para este modelo. Actívalo en Ajustes → Modelos → Avanzado.",
+ "fastModeRemote": "Las sesiones remotas usan la configuración de modelos del host, así que el modo Fast no está disponible.",
"permissionInherit": "Predeterminado",
"permissionAsk": "Preguntar siempre",
"permissionAcceptEdits": "Aceptar ediciones",
@@ -1712,6 +1719,10 @@ sklm: {
"nativeWebSearch": "Búsqueda web nativa",
"nativeWebSearchHint": "Adjunta la herramienta de búsqueda web alojada por el proveedor a las solicitudes de este modelo. Requiere un punto de conexión que la admita; el proveedor la factura por búsqueda.",
nativeWebSearchUnsupported: "La aplicación aún no integra búsqueda nativa para esta conexión. El sitio web u otra API pueden ofrecerla.",
+ fastModeAllowed: "Modo Fast",
+ fastModeAllowedSubscriptionHint: "Permite que /fast pida el nivel prioritario de OpenAI para este modelo. Las respuestas llegan antes y consumen más del límite de uso de tu plan de ChatGPT.",
+ fastModeAllowedUsageHint: "Permite que /fast pida el nivel prioritario de OpenAI (service_tier) para este modelo. OpenAI lo factura a un precio por token más alto; un relay puede ignorar el campo o facturarlo de otra forma.",
+ fastModeAllowedUnsupported: "El modo Fast necesita la API Responses de OpenAI o una suscripción a ChatGPT.",
"searchModelId": "ID de modelo de búsqueda…",
"searchChosenModels": "Buscar modelos añadidos…",
"noChosenModelMatches": "No hay modelos añadidos que coincidan.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index f015a5604..d591515ff 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -645,6 +645,13 @@ export const fr = {
"modelBadgeVision": "vision",
"permissionMode": "Mode d'autorisation",
"reasoningLevel": "Niveau de raisonnement",
+ "fastModeBadge": "Fast",
+ "fastModeOn": "Mode Fast activé pour cette session. Les réponses arrivent plus vite et consomment davantage les limites d'utilisation de votre abonnement.",
+ "fastModeOnUsage": "Mode Fast activé pour cette session. Ce modèle est facturé au token, au tarif plus élevé du niveau prioritaire.",
+ "fastModeOff": "Mode Fast désactivé pour cette session.",
+ "fastModeUnsupported": "Le mode Fast nécessite un modèle sur l'API Responses d'OpenAI ou un abonnement ChatGPT.",
+ "fastModeNotAllowed": "Le mode Fast n'est pas configuré pour ce modèle. Activez-le dans Réglages → Modèles → Avancé.",
+ "fastModeRemote": "Les sessions distantes utilisent la configuration des modèles de l'hôte : le mode Fast n'est pas disponible.",
"permissionInherit": "Par défaut",
"permissionAsk": "Demander à chaque fois",
"permissionAcceptEdits": "Accepter les modifications",
@@ -1712,6 +1719,10 @@ sklm: {
"nativeWebSearch": "Recherche web native",
"nativeWebSearchHint": "Attache l'outil de recherche web hébergé par le fournisseur aux requêtes pour ce modèle. Nécessite un point de terminaison qui le prend en charge ; facturé par le fournisseur à chaque recherche.",
nativeWebSearchUnsupported: "La recherche native n’est pas encore intégrée pour cette connexion. Le site web ou une autre API peut la proposer.",
+ fastModeAllowed: "Mode Fast",
+ fastModeAllowedSubscriptionHint: "Autorise /fast à demander le niveau prioritaire d'OpenAI pour ce modèle. Les réponses arrivent plus vite et consomment davantage les limites de votre abonnement ChatGPT.",
+ fastModeAllowedUsageHint: "Autorise /fast à demander le niveau prioritaire d'OpenAI (service_tier) pour ce modèle. OpenAI le facture à un prix par token plus élevé ; un relais peut ignorer ce champ ou le facturer autrement.",
+ fastModeAllowedUnsupported: "Le mode Fast nécessite l'API Responses d'OpenAI ou un abonnement ChatGPT.",
"searchModelId": "ID de modèle de recherche…",
"searchChosenModels": "Rechercher les modèles ajoutés…",
"noChosenModelMatches": "Aucun modèle ajouté correspondant.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 5c5b1723f..b22559848 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -654,6 +654,13 @@ export const ko = {
modelBadgeVision: "비전",
permissionMode: "권한 모드",
reasoningLevel: "추론 수준",
+ fastModeBadge: "Fast",
+ fastModeOn: "이 세션에서 Fast 모드를 켰습니다. 응답이 더 빨라지고 구독 사용 한도를 더 많이 소모합니다.",
+ fastModeOnUsage: "이 세션에서 Fast 모드를 켰습니다. 이 모델은 우선 등급의 더 높은 토큰 단가로 청구됩니다.",
+ fastModeOff: "이 세션에서 Fast 모드를 껐습니다.",
+ fastModeUnsupported: "Fast 모드는 OpenAI Responses API 또는 ChatGPT 구독 모델에서만 사용할 수 있습니다.",
+ fastModeNotAllowed: "이 모델에는 Fast 모드가 설정되어 있지 않습니다. 설정 → 모델 → 고급에서 켜세요.",
+ fastModeRemote: "원격 세션은 호스트의 모델 구성을 사용하므로 Fast 모드를 사용할 수 없습니다.",
permissionInherit: "기본값",
permissionAsk: "매번 묻기",
permissionAcceptEdits: "편집 허용",
@@ -1728,6 +1735,10 @@ sklm: {
nativeWebSearch: "네이티브 웹 검색",
nativeWebSearchHint: "이 모델에 대한 요청에 공급자 호스팅 웹 검색 도구를 첨부합니다. 이를 지원하는 엔드포인트가 필요하며, 검색 건수로 공급자에게 과금됩니다.",
nativeWebSearchUnsupported: "이 연결의 네이티브 검색은 아직 앱에 통합되지 않았습니다. 웹사이트나 다른 API에서는 검색을 지원할 수 있습니다.",
+ fastModeAllowed: "Fast 모드",
+ fastModeAllowedSubscriptionHint: "/fast가 이 모델에 OpenAI 우선 등급을 요청하도록 허용합니다. 응답이 더 빨라지고 ChatGPT 구독 사용 한도를 더 많이 소모합니다.",
+ fastModeAllowedUsageHint: "/fast가 이 모델에 OpenAI 우선 등급(service_tier)을 요청하도록 허용합니다. OpenAI는 더 높은 토큰 단가로 청구하며, 중계 서비스는 이 필드를 무시하거나 다르게 청구할 수 있습니다.",
+ fastModeAllowedUnsupported: "Fast 모드는 OpenAI Responses API 또는 ChatGPT 구독이 필요합니다.",
searchModelId: "모델 ID 검색…",
searchChosenModels: "추가된 모델 검색…",
noChosenModelMatches: "일치하는 추가된 모델이 없습니다.",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 48036f423..5c544db87 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -644,6 +644,13 @@ export const ptBR = {
modelBadgeVision: "Visão",
permissionMode: "Modo de permissão",
reasoningLevel: "Nível de raciocínio",
+ fastModeBadge: "Fast",
+ fastModeOn: "Modo Fast ativado nesta sessão. As respostas chegam mais rápido e consomem mais do limite de uso do seu plano.",
+ fastModeOnUsage: "Modo Fast ativado nesta sessão. Este modelo é cobrado por token no preço mais alto do nível prioritário.",
+ fastModeOff: "Modo Fast desativado nesta sessão.",
+ fastModeUnsupported: "O modo Fast precisa de um modelo na API Responses da OpenAI ou de uma assinatura do ChatGPT.",
+ fastModeNotAllowed: "O modo Fast não está configurado para este modelo. Ative em Configurações → Modelos → Avançado.",
+ fastModeRemote: "Sessões remotas usam a configuração de modelos do host, então o modo Fast não está disponível.",
permissionInherit: "Herdar",
permissionAsk: "Perguntar",
permissionAcceptEdits: "Aceitar edições",
@@ -1682,6 +1689,10 @@ export const ptBR = {
nativeWebSearch: "Pesquisa nativa na web",
nativeWebSearchHint: "Anexa às solicitações deste modelo a ferramenta de pesquisa na web do provedor. Exige um endpoint compatível; o provedor cobra por pesquisa.",
nativeWebSearchUnsupported: "O aplicativo ainda não integra pesquisa nativa para esta conexão. O site ou outra API ainda pode oferecer pesquisa.",
+ fastModeAllowed: "Modo Fast",
+ fastModeAllowedSubscriptionHint: "Permite que /fast peça o nível prioritário da OpenAI para este modelo. As respostas chegam mais rápido e consomem mais do limite de uso do seu plano do ChatGPT.",
+ fastModeAllowedUsageHint: "Permite que /fast peça o nível prioritário da OpenAI (service_tier) para este modelo. A OpenAI cobra um preço por token mais alto; um relay pode ignorar o campo ou cobrar de outra forma.",
+ fastModeAllowedUnsupported: "O modo Fast precisa da API Responses da OpenAI ou de uma assinatura do ChatGPT.",
searchModelId: "ID de modelo de pesquisa…",
searchChosenModels: "Pesquisar modelos adicionados…",
noChosenModelMatches: "Nenhum modelo escolhido corresponde à busca.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 10d7331cf..8f2cf24ba 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -654,6 +654,13 @@ export const tr = {
modelBadgeVision: "görüntü",
permissionMode: "İzin kipi",
reasoningLevel: "Akıl yürütme düzeyi",
+ fastModeBadge: "Fast",
+ fastModeOn: "Bu oturumda Fast modu açık. Yanıtlar daha hızlı gelir ve planınızın kullanım sınırından daha fazla harcar.",
+ fastModeOnUsage: "Bu oturumda Fast modu açık. Bu model, öncelikli katmanın daha yüksek token fiyatıyla ücretlendirilir.",
+ fastModeOff: "Bu oturumda Fast modu kapalı.",
+ fastModeUnsupported: "Fast modu, OpenAI Responses API'sindeki bir model veya ChatGPT aboneliği gerektirir.",
+ fastModeNotAllowed: "Bu model için Fast modu yapılandırılmadı. Ayarlar → Modeller → Gelişmiş bölümünden açın.",
+ fastModeRemote: "Uzak oturumlar ana makinenin model yapılandırmasını kullanır, bu yüzden Fast modu kullanılamaz.",
permissionInherit: "Varsayılan",
permissionAsk: "Her seferinde sor",
permissionAcceptEdits: "Düzenlemeleri kabul et",
@@ -1722,6 +1729,10 @@ sklm: {
nativeWebSearch: "Yerel web araması",
nativeWebSearchHint: "Bu modele yapılan isteklere sağlayıcının barındırdığı web arama aracını ekler. Bunu destekleyen bir uç nokta gerekir; arama başına sağlayıcı tarafından faturalandırılır.",
nativeWebSearchUnsupported: "Bu bağlantı için yerel arama henüz uygulamaya entegre edilmedi. Web sitesi veya başka bir API aramayı destekleyebilir.",
+ fastModeAllowed: "Fast modu",
+ fastModeAllowedSubscriptionHint: "/fast komutunun bu model için OpenAI öncelikli katmanını istemesine izin verir. Yanıtlar daha hızlı gelir ve ChatGPT planınızın kullanım sınırından daha fazla harcar.",
+ fastModeAllowedUsageHint: "/fast komutunun bu model için OpenAI öncelikli katmanını (service_tier) istemesine izin verir. OpenAI bunu daha yüksek token fiyatıyla ücretlendirir; bir aktarıcı alanı yok sayabilir veya farklı ücretlendirebilir.",
+ fastModeAllowedUnsupported: "Fast modu, OpenAI Responses API'si veya ChatGPT aboneliği gerektirir.",
searchModelId: "Model kimliği ara…",
searchChosenModels: "Eklenen modellerde ara…",
noChosenModelMatches: "Eşleşen eklenen model yok.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index b193bfda2..1bcbc7820 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -650,6 +650,13 @@ export const zhCN = {
modelBadgeVision: "视觉",
permissionMode: "权限模式",
reasoningLevel: "推理等级",
+ fastModeBadge: "Fast",
+ fastModeOn: "已为当前会话开启 Fast 模式:回复更快,但会更快消耗订阅额度。",
+ fastModeOnUsage: "已为当前会话开启 Fast 模式:该模型按优先档位的更高单价按 token 计费。",
+ fastModeOff: "已为当前会话关闭 Fast 模式。",
+ fastModeUnsupported: "Fast 模式需要使用 OpenAI Responses 接口或 ChatGPT 订阅的模型。",
+ fastModeNotAllowed: "该模型未配置 Fast 模式,请到「设置 → 模型 → 高级」中开启。",
+ fastModeRemote: "远程会话使用远程主机的模型配置,无法开启 Fast 模式。",
permissionInherit: "跟随默认",
permissionAsk: "每次询问",
permissionAcceptEdits: "允许编辑",
@@ -1707,6 +1714,10 @@ sklm: {
nativeWebSearch: "原生联网搜索",
nativeWebSearchHint: "为该模型的请求附加提供商托管的联网搜索工具。需要端点实际支持;按次计费由提供商收取。",
nativeWebSearchUnsupported: "应用尚未适配此连接的原生搜索;不代表厂商官网或其他 API 不支持搜索。",
+ fastModeAllowed: "Fast 模式",
+ fastModeAllowedSubscriptionHint: "允许 /fast 为该模型请求 OpenAI 优先档位:回复更快,但会更快消耗 ChatGPT 订阅额度。",
+ fastModeAllowedUsageHint: "允许 /fast 为该模型请求 OpenAI 优先档位(service_tier)。OpenAI 按更高的 token 单价计费;中转服务可能忽略该字段或另行计费。",
+ fastModeAllowedUnsupported: "Fast 模式需要 OpenAI Responses 接口或 ChatGPT 订阅。",
searchModelId: "搜索模型 ID…",
searchChosenModels: "搜索已添加模型…",
noChosenModelMatches: "没有匹配的已添加模型",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index a954bec61..6c3d4db80 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -650,6 +650,13 @@ export const zhTW = {
modelBadgeVision: "視覺",
permissionMode: "許可權模式",
reasoningLevel: "推理等級",
+ fastModeBadge: "Fast",
+ fastModeOn: "已為目前工作階段開啟 Fast 模式:回覆更快,但會更快消耗訂閱額度。",
+ fastModeOnUsage: "已為目前工作階段開啟 Fast 模式:此模型依優先層級的較高單價按 token 計費。",
+ fastModeOff: "已為目前工作階段關閉 Fast 模式。",
+ fastModeUnsupported: "Fast 模式需要使用 OpenAI Responses 介面或 ChatGPT 訂閱的模型。",
+ fastModeNotAllowed: "此模型未設定 Fast 模式,請到「設定 → 模型 → 高階」中開啟。",
+ fastModeRemote: "遠端工作階段使用遠端主機的模型設定,無法開啟 Fast 模式。",
permissionInherit: "跟隨預設",
permissionAsk: "每次詢問",
permissionAcceptEdits: "允許編輯",
@@ -1707,6 +1714,10 @@ sklm: {
nativeWebSearch: "原生網路搜尋",
nativeWebSearchHint: "為該模型的請求附加提供商託管的網路搜尋工具。需要端點實際支援;按次計費由提供商收取。",
nativeWebSearchUnsupported: "應用程式尚未整合此連線的原生搜尋;不代表廠商官網或其他 API 不支援搜尋。",
+ fastModeAllowed: "Fast 模式",
+ fastModeAllowedSubscriptionHint: "允許 /fast 為此模型請求 OpenAI 優先層級:回覆更快,但會更快消耗 ChatGPT 訂閱額度。",
+ fastModeAllowedUsageHint: "允許 /fast 為此模型請求 OpenAI 優先層級(service_tier)。OpenAI 以較高的 token 單價計費;中轉服務可能忽略此欄位或另行計費。",
+ fastModeAllowedUnsupported: "Fast 模式需要 OpenAI Responses 介面或 ChatGPT 訂閱。",
searchModelId: "搜尋模型 ID…",
searchChosenModels: "搜尋已新增模型…",
noChosenModelMatches: "沒有符合的已新增模型",
diff --git a/packages/shared/src/fast-mode.test.ts b/packages/shared/src/fast-mode.test.ts
new file mode 100644
index 000000000..50604ab78
--- /dev/null
+++ b/packages/shared/src/fast-mode.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { fastModeBillingOn, fastModeSupportedOn } from "./fast-mode.js";
+
+describe("fast mode wire rule", () => {
+ it("prices the Codex backend on plan limits and Responses per token", () => {
+ expect(fastModeBillingOn("openai_codex_responses")).toBe("subscription");
+ expect(fastModeBillingOn("openai-codex-responses")).toBe("subscription");
+ expect(fastModeBillingOn("responses")).toBe("usage");
+ expect(fastModeBillingOn(" Responses ")).toBe("usage");
+ expect(fastModeBillingOn("openai-responses")).toBe("usage");
+ });
+
+ it("rejects wires that do not carry service_tier", () => {
+ for (const api of ["chat_completions", "openai-completions", "anthropic_messages",
+ "azure-openai-responses", "opencode_go", "", undefined, null]) {
+ expect(fastModeSupportedOn(api)).toBe(false);
+ }
+ });
+});
diff --git a/packages/shared/src/fast-mode.ts b/packages/shared/src/fast-mode.ts
new file mode 100644
index 000000000..d6d4078ac
--- /dev/null
+++ b/packages/shared/src/fast-mode.ts
@@ -0,0 +1,26 @@
+/**
+ * OpenAI Fast mode (ADR 0332): the Responses body field
+ * `service_tier: "priority"`. A request asks for it only when the model
+ * binding's `fastModeAllowed` and the session `/fast` switch are both on.
+ */
+export const FAST_MODE_SERVICE_TIER = "priority";
+
+/** `subscription` spends ChatGPT plan limits; `usage` is billed per token. */
+export type FastModeBilling = "subscription" | "usage";
+
+/** Stored apiStyle and resolved wire spellings of the wires that carry the tier. */
+const FAST_MODE_BILLING: Record<string, FastModeBilling> = {
+ openai_codex_responses: "subscription",
+ "openai-codex-responses": "subscription",
+ responses: "usage",
+ "openai-responses": "usage",
+};
+
+/** How the tier is paid for on this apiStyle or wire, or undefined when it cannot carry it. */
+export function fastModeBillingOn(api: string | undefined | null): FastModeBilling | undefined {
+ return FAST_MODE_BILLING[(api ?? "").trim().toLowerCase()];
+}
+
+export function fastModeSupportedOn(api: string | undefined | null): boolean {
+ return fastModeBillingOn(api) !== undefined;
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 9ad014dc8..1e65c72bc 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -68,6 +68,7 @@ export * from "./session-presentation.js";
export * from "./session-outcomes.js";
export * from "./tray-sessions.js";
export * from "./window-chrome.js";
+export * from "./fast-mode.js";
export * from "./native-web-search.js";
export * from "./native-web-search-transport.js";
export * from "./header-value.js";
diff --git a/packages/shared/src/model-config-import.ts b/packages/shared/src/model-config-import.ts
index 02c30e445..88fd99784 100644
--- a/packages/shared/src/model-config-import.ts
+++ b/packages/shared/src/model-config-import.ts
@@ -839,6 +839,9 @@ function bindingFromGenericModel(
...(record?.nativeWebSearch === true || record?.native_web_search === true
? { nativeWebSearch: true }
: {}),
+ ...(record?.fastModeAllowed === true || record?.fast_mode_allowed === true
+ ? { fastModeAllowed: true }
+ : {}),
};
}
diff --git a/packages/shared/src/provider-sync.ts b/packages/shared/src/provider-sync.ts
index 60a9fb1ea..467f1064f 100644
--- a/packages/shared/src/provider-sync.ts
+++ b/packages/shared/src/provider-sync.ts
@@ -23,7 +23,7 @@ const API_STYLES = new Set(["auto", "chat_completions", "responses", "anthropic_
const EXCLUDED_VENDORS = new Set(["claude-cli", "codex", "openai-codex", "github-copilot", "google-antigravity", "google-gemini-cli", "ollama", "lmstudio", "lm-studio", "local"]);
const RESERVED_HEADERS = new Set(["authorization", "proxy-authorization", "x-api-key", "api-key", "x-goog-api-key", "cookie", "set-cookie", "host", "content-type", "content-length", "connection", "transfer-encoding", "te", "trailer", "upgrade", "keep-alive", "chatgpt-account-id", "x-opencode-session"]);
const INPUT_FIELDS = ["name", "vendorKey", "type", "protocol", "baseUrl", "authKind", "models", "defaultModelId", "secretValue", "apiStyle", "headers", "supportsReasoning", "supportedThinkingLevels", "contextWindow", "maxOutputTokens", "temperature"];
-const MODEL_FIELDS = ["id", "alias", "contextWindow", "contextWindowSource", "maxTokens", "maxTokensSource", "thinkingLevels", "defaultThinkingLevel", "thinkingProtocol", "supportsImages", "supportsDocuments", "availableForSubagents", "nativeWebSearch"];
+const MODEL_FIELDS = ["id", "alias", "contextWindow", "contextWindowSource", "maxTokens", "maxTokensSource", "thinkingLevels", "defaultThinkingLevel", "thinkingProtocol", "supportsImages", "supportsDocuments", "availableForSubagents", "nativeWebSearch", "fastModeAllowed"];
function invalid(): never {
// Never include input values, unknown field names, parser diagnostics or causes.
@@ -85,7 +85,7 @@ function validateModel(value: unknown): ModelBinding {
for (const key of ["supportsImages", "supportsDocuments"] as const) {
if (value[key] !== undefined && value[key] !== null && typeof value[key] !== "boolean") invalid();
}
- for (const key of ["availableForSubagents", "nativeWebSearch"] as const) {
+ for (const key of ["availableForSubagents", "nativeWebSearch", "fastModeAllowed"] as const) {
if (value[key] !== undefined && typeof value[key] !== "boolean") invalid();
}
return value as ModelBinding;
diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.ts
index 47d436f6b..856c94cc8 100644
--- a/packages/shared/src/types/models.ts
+++ b/packages/shared/src/types/models.ts
@@ -254,6 +254,12 @@ export type ModelBinding = {
* knowledge of the endpoint is the only source.
*/
nativeWebSearch?: boolean;
+ /**
+ * Opt-in that lets the session `/fast` switch ask OpenAI for the priority
+ * service tier on this model (ADR 0332). Absent/false keeps the default
+ * tier; only Responses wires carry it (`fastModeSupportedOn`).
+ */
+ fastModeAllowed?: boolean;
};
export const MODEL_MODALITIES = ["text", "image", "audio", "video", "pdf"] as const;
diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.ts
index a76795597..69ff8a78d 100644
--- a/packages/shared/src/types/sessions.ts
+++ b/packages/shared/src/types/sessions.ts
@@ -57,6 +57,12 @@ export type SessionSummary = {
thinkingLevel: SessionThinkingLevel;
/** Per-session permission mode; `inherit` follows the global default (D115). */
permissionMode: PermissionMode;
+ /**
+ * Session `/fast` switch (ADR 0332). Requests use the priority tier only
+ * when the selected model also allows it. Older hosts and remote sessions
+ * omit it, meaning off.
+ */
+ fastMode?: boolean;
/** Effective capability for this session's exact provider/model pair. */
supportsReasoning?: boolean;
/** Effective image-input capability for this session's exact model. */