feat(webui): add session-scoped reasoning effort (#6441)

* feat(webui): add session-scoped model options

Extend the composer preset menu with inherited reasoning effort and Codex Fast mode overrides. Persist choices with ordinary inputs, isolate captured runtimes, and restore browser preferences without changing shared presets.

Add regression coverage for pending preset ordering, settings initialization, session and host isolation, queue edits, Codex request mapping, and narrow-screen controls.

* feat(webui): refine session model options and add Codex Ultrafast

Fit the composer options into a compact single row and preview reasoning effort only during a drag. Add Fast/Ultrafast controls for eligible Codex models, preserve explicit session choices across reloads, and document the speed tiers.

* fix(webui): add Codex speed control to the component gallery

* fix(webui): preserve saved model options after preset rename

Use the session options for display when a browser preference no longer matches the preset. Omit model options from the next message unless the browser has a matching choice, so stale preferences cannot overwrite options the gateway already saved.
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 15:46:16 +08:00
1 parent 2b232c9133
commit 0f45d74fec
82 files changed
+2289 -113

No files matched your search

+5
View File
@@ -22,6 +22,11 @@ async function withClient(fixture: ReactElement, webuiCapabilities?: string[]) {
// Load and install only the selected scene's mocks before i18n and React mount.
async function loadFixture() {
switch (fixtureCase) {
case "model-options": {
const { ModelOptionsFixture, installModelOptionsPreviewApi } = await import("./model-options-fixture");
installModelOptionsPreviewApi();
return <ModelOptionsFixture />;
}
case "session-transition": {
const { installSessionTransitionPreviewApi, SessionTransitionFixture } = await import("./session-transition-fixture");
if (parameters.has("preview")) installSessionTransitionPreviewApi();
+164
View File
@@ -0,0 +1,164 @@
import { useState } from "react";
import { SettingsPage } from "@/components/settings/SettingsPage";
import { useSettingsController } from "@/components/settings/useSettingsController";
import { ThreadShell } from "@/components/thread/ThreadShell";
import { settings as baseSettings } from "@/dev/gallery/settings";
import type { ModelOptionsCapability, SessionModelOptions, SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
import { ClientProvider } from "@/providers/ClientProvider";
import { createStreamClient } from "@/tests/stream-client";
const params = new URLSearchParams(location.search);
const isChinese = params.get("lang")?.startsWith("zh");
const showSettings = params.has("settings");
const providers = {
openai_codex: { label: "OpenAI Codex", auth_type: "oauth", codex_fast_mode_supported: true, codex_ultrafast_models: ["gpt-6.2-sol"] },
github_copilot: { label: "GitHub Copilot", auth_type: "oauth" },
openai: { label: "OpenAI" },
anthropic: { label: "Anthropic" },
deepseek: { label: "DeepSeek" },
mistral: { label: "Mistral" },
openrouter: { label: "OpenRouter" },
orcarouter: { label: "OrcaRouter" },
azure_openai: { label: "Azure OpenAI" },
bedrock: { label: "AWS Bedrock" },
ollama: { label: "Ollama" },
vllm: { label: "vLLM" },
custom: { label: "Custom API" },
} satisfies Record<string, Partial<SettingsPayload["providers"][number]>>;
type Preset = SettingsPayload["model_presets"][number];
const codexEfforts = ["none", "low", "medium", "high", "xhigh"];
function preset(
name: string, provider: keyof typeof providers, model: string, effort: string | null = "medium",
values = ["low", "medium", "high"], speed?: ModelOptionsCapability["codex_fast_mode"],
): Preset {
return {
name, label: name, active: false, is_default: false, model, provider, resolved_provider: provider,
max_tokens: 8192, context_window_tokens: 200_000, temperature: 0.1,
reasoning_effort: effort, reasoning_effort_values: values,
model_options: { reasoning_effort: { default: effort, values }, ...(speed && { codex_fast_mode: speed }) },
};
}
const standardCodex = preset("Codex", "openai_codex", "gpt-5.5", "medium", codexEfforts, { default: false });
const ultrafastCodex = preset("Review", "openai_codex", "gpt-6.2-sol", "medium", codexEfforts, { default: false, ultrafast_supported: true });
const groups = [
{ id: "oauth", label: isChinese ? "登录授权" : "OAuth", presets: [
ultrafastCodex, standardCodex, preset("GitHub Copilot", "github_copilot", "github-copilot/gpt-5.4-mini", "low"),
] },
{ id: "direct", label: isChinese ? "直连 API" : "Direct APIs", presets: [
preset("DeepSeek", "deepseek", "deepseek-v4-pro", "high", ["none", "low", "high", "max"]),
preset("OpenAI", "openai", "gpt-5.4"),
preset("Anthropic", "anthropic", "claude-opus-4-7", "high"),
preset("Mistral", "mistral", "magistral-medium-latest", null, []),
] },
{ id: "gateway", label: isChinese ? "聚合网关" : "Gateways", presets: [
preset("OpenRouter", "openrouter", "openai/gpt-5.4", null),
preset("OrcaRouter", "orcarouter", "deepseek/deepseek-v4-pro", "high"),
] },
{ id: "cloud", label: isChinese ? "云平台" : "Cloud platforms", presets: [
preset("AWS Bedrock", "bedrock", "anthropic.claude-sonnet-4-6", "high"),
preset("Azure OpenAI", "azure_openai", "azure/gpt-5.4"),
] },
{ id: "local", label: isChinese ? "本地与自建" : "Local & self-hosted", presets: [
preset("Ollama", "ollama", "qwen3:8b", null),
preset("vLLM", "vllm", "Qwen/Qwen3-32B", "high"),
preset("Custom API", "custom", "team-assistant", "extended"),
] },
];
const group = groups.find(({ id }) => id === params.get("group")) ?? groups[0]!;
const base = group.id === "oauth" ? (params.has("ultrafast") ? ultrafastCodex : standardCodex) : group.presets[0]!;
const settings: SettingsPayload = {
...baseSettings,
agent: { ...baseSettings.agent, model: base.model, provider: base.provider, resolved_provider: base.provider,
reasoning_effort: base.reasoning_effort },
providers: Object.entries(providers).map(([name, provider]) => ({
name, configured: true, model_catalog: "unsupported", ...provider,
})),
model_presets: [{ ...base, name: "default", label: "Default", active: true, is_default: true }, ...group.presets],
model_call_order: group.presets.map(({ name }) => name),
};
function fixtureLink(groupId: string, settingsView: boolean) {
const url = new URL(location.href);
url.searchParams.set("group", groupId);
if (settingsView) url.searchParams.set("settings", "");
else url.searchParams.delete("settings");
return url.href;
}
function FixtureNav() {
return (
<nav aria-label={isChinese ? "提供商示例" : "Provider examples"}
className="flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border bg-background px-3 py-2 text-xs text-foreground">
{groups.map(({ id, label }) => (
<a key={id} href={fixtureLink(id, showSettings)} aria-current={group.id === id ? "page" : undefined}
className={cn("rounded-control px-2 py-1.5 hover:bg-muted", group.id === id && "bg-muted font-semibold")}>
{label}
</a>
))}
<a className="ml-auto rounded-control px-2 py-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
href={fixtureLink(group.id, !showSettings)}>
{showSettings ? (isChinese ? "会话菜单" : "Chat menu") : (isChinese ? "预设编辑" : "Preset settings")}
</a>
</nav>
);
}
/** Fully task-local fixture: no real gateway, authentication, or network mutations. */
export function installModelOptionsPreviewApi() {
window.fetch = async (input) => {
const url = String(input);
if (url.includes("/webui-thread")) return Response.json({ schemaVersion: 3, projection: "events", events: [] });
if (url.includes("/commands")) return Response.json({ commands: [] });
if (url.includes("/api/settings")) return Response.json(settings);
return Response.json({}, { status: 404 });
};
}
const noop = () => {};
function ModelSettingsFixture() {
const controller = useSettingsController({ initialSection: "models", initialSettings: settings, onModelNameChange: noop });
return <div className="flex min-h-0 flex-1 flex-col bg-settings-canvas">
<SettingsPage controller={controller} themePreference={params.has("dark") ? "dark" : "light"}
showSidebar mainNavigationExpanded={false} onChangeTheme={noop} onBackToChat={noop}
skills={[]} skillsLoading={false} skillsError={false} isRestarting={false} hostChromeInset={false} />
</div>;
}
export function ModelOptionsFixture() {
const [sent, setSent] = useState<SessionModelOptions | undefined>();
const [{ client }] = useState(() => {
const preview = createStreamClient((data) => {
const frame = JSON.parse(data);
if (frame.type !== "message") return;
if (!frame.content.startsWith("/")) setSent(frame.model_options);
queueMicrotask(() => {
preview.receive({ event: "message", chat_id: frame.chat_id, turn_id: frame.turn_id, text: "Fixture message accepted." });
preview.receive({ event: "turn_end", chat_id: frame.chat_id, turn_id: frame.turn_id });
});
});
return preview;
});
const temporary = params.has("temporary");
document.documentElement.classList.toggle("dark", params.has("dark"));
const chatId = `model-options-preview-${group.id}-${base.model}`;
return <ClientProvider client={client} token="fixture" webuiCapabilities={["webui.core.v1", "webui.model-options.v1"]}>
<div className="flex flex-col overflow-hidden" style={{ height: "100dvh" }}>
<FixtureNav />
{showSettings ? <ModelSettingsFixture /> : (
<main className="thread-workspace flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background text-foreground">
<ThreadShell session={{ key: `websocket:${chatId}`, channel: "websocket", chatId,
createdAt: null, updatedAt: null, preview: "" }} title={`${group.label} · ${base.model}`} temporary={temporary}
onToggleSidebar={noop} settingsSnapshot={settings}
onOpenModelSettings={() => location.assign(fixtureLink(group.id, true))} />
<output aria-label="Sent model options" className="shrink-0 px-4 py-2 text-xs text-muted-foreground">
{sent ? `Reasoning: ${sent.reasoning_effort ?? "unchanged"}; Codex Fast: ${typeof sent.codex_fast_mode === "boolean" ? (sent.codex_fast_mode ? "on" : "off") : sent.codex_fast_mode ?? "unchanged"}` : "No model options sent"}
</output>
</main>)}
</div>
</ClientProvider>;
}
+230
View File
@@ -0,0 +1,230 @@
import { expect, test } from "@playwright/test";
for (const width of [390, 1280]) {
test(`current-chat model options preserve the compact preset menu at ${width}px`, async ({ page }, testInfo) => {
await page.setViewportSize({ width, height: 900 });
await page.goto("/browser/fixture.html?case=model-options");
await page.getByRole("button", { name: "Default", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Switch model", exact: true });
const selected = dialog.getByRole("option", { name: "default", exact: true });
await expect(selected).toHaveAttribute("aria-selected", "true");
await dialog.evaluate((element) => Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)));
const selectedBefore = await selected.boundingBox();
const effort = dialog.getByRole("slider", { name: "Reasoning effort" });
const fast = dialog.getByRole("button", { name: "Fast", exact: true });
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await expect(fast).toHaveAttribute("aria-pressed", "false");
await effort.press("ArrowRight");
await expect(effort).toHaveAttribute("aria-valuetext", "high");
await fast.click();
await expect(page.getByLabel("Sent model options")).toHaveText("No model options sent");
const selectedAfter = await selected.boundingBox();
expect(selectedAfter?.height).toBe(selectedBefore?.height);
expect(selectedAfter?.x).toBe(selectedBefore?.x);
const row = (await dialog.locator(".model-options-row").boundingBox())!;
const list = (await dialog.getByRole("listbox").boundingBox())!;
expect(Math.abs(row.x - selectedAfter!.x)).toBeLessThan(1);
expect(Math.abs(row.width - list.width)).toBeLessThan(1);
const track = (await dialog.locator(".reasoning-effort-track").boundingBox())!;
const thumb = (await dialog.locator(".reasoning-effort-thumb").boundingBox())!;
expect(track.height).toBe(20);
expect(thumb.height).toBe(24);
const stops = await dialog.locator(".reasoning-effort-tick").evaluateAll((elements) =>
elements.map((element) => element.getBoundingClientRect().x),
);
expect(stops).toHaveLength(5);
for (let i = 1; i < stops.length; i++) {
expect(stops[i] - stops[i - 1]).toBeCloseTo(thumb.width);
}
const label = (await dialog.getByText("Reasoning effort", { exact: true }).boundingBox())!;
const icon = (await fast.boundingBox())!;
const centerY = ({ y, height }: { y: number; height: number }) => y + height / 2;
expect(label.x + label.width).toBeLessThan(track.x);
const speedGap = icon.x - track.x - track.width;
expect(speedGap).toBeGreaterThan(0);
expect(speedGap).toBeLessThanOrEqual(6);
expect(row.x + row.width - icon.x - icon.width).toBeLessThanOrEqual(12);
for (const item of [label, thumb, icon]) {
expect(Math.abs(centerY(item) - centerY(track))).toBeLessThan(1);
}
if (width === 390) {
expect((await effort.boundingBox())!.height).toBeGreaterThanOrEqual(44);
expect((await fast.boundingBox())!.height).toBeGreaterThanOrEqual(44);
expect(selectedBefore!.height).toBeGreaterThanOrEqual(44);
}
expect(await dialog.evaluate((element) => element.scrollWidth <= element.clientWidth + 1)).toBe(true);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await page.mouse.move(0, 0);
await dialog.evaluate((element) => Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)));
await page.screenshot({ path: testInfo.outputPath(`model-options-${width}.png`) });
await dialog.press("Escape");
await page.getByLabel("Message input").fill("Send with these options");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByLabel("Sent model options")).toHaveText("Reasoning: high; Codex Fast: on");
await page.reload();
await page.getByRole("button", { name: "Default", exact: true }).click();
await expect(effort).toHaveAttribute("aria-valuetext", "high");
await expect(fast).toHaveAttribute("aria-pressed", "true");
await dialog.getByRole("option", { name: "Review", exact: true }).click();
await page.getByRole("button", { name: "Review", exact: true }).click();
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await expect(fast).toHaveAttribute("aria-pressed", "false");
if (width === 1280) {
await fast.focus();
await expect(page.getByRole("tooltip")).toContainText("Faster responses, increased usage.");
}
});
}
test("Temporary Chats do not expose model option controls", async ({ page }) => {
await page.goto("/browser/fixture.html?case=model-options&temporary");
await page.getByRole("button", { name: "Default", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Switch model", exact: true })).toBeVisible();
await expect(page.getByRole("slider", { name: "Reasoning effort" })).toHaveCount(0);
await expect(page.getByRole("button", { name: "Fast", exact: true })).toHaveCount(0);
});
test("reselecting medium and choosing Ultrafast sends and remembers both concrete values", async ({ page }) => {
await page.setViewportSize({ width: 320, height: 800 });
await page.goto("/browser/fixture.html?case=model-options&ultrafast");
const open = page.getByRole("button", { name: "Default", exact: true });
await open.click();
const dialog = page.getByRole("dialog", { name: "Switch model", exact: true });
const speeds = dialog.getByRole("group", { name: "Fast" });
const fast = speeds.getByRole("button", { name: "Fast", exact: true });
const effort = dialog.getByRole("slider", { name: "Reasoning effort" });
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await dialog.evaluate((element) => Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)));
const ticks = dialog.locator(".reasoning-effort-tick");
const medium = (await ticks.nth(2).boundingBox())!;
const high = (await ticks.nth(3).boundingBox())!;
const sliderBefore = (await effort.boundingBox())!;
const speedBounds = (await speeds.boundingBox())!;
const speedGap = speedBounds.x - sliderBefore.x - sliderBefore.width;
expect(speedGap).toBeGreaterThan(0);
expect(speedGap).toBeLessThanOrEqual(6);
expect(Math.abs(speedBounds.y + speedBounds.height / 2 - sliderBefore.y - sliderBefore.height / 2)).toBeLessThan(1);
expect(await dialog.evaluate((element) => element.scrollWidth <= element.clientWidth + 1)).toBe(true);
const startX = medium.x + medium.width / 2;
const endX = high.x + high.width / 2;
const y = medium.y + medium.height / 2;
const hint = page.getByRole("tooltip");
await page.mouse.move(startX, y);
await expect(hint).toBeHidden();
await page.mouse.down();
await expect(hint).toHaveText("medium");
const pointerX = startX + 0.7 * (endX - startX);
await page.mouse.move(pointerX, y, { steps: 5 });
await expect(hint).toHaveText("high");
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
expect(await effort.boundingBox()).toEqual(sliderBefore);
const thumbCenter = async () => {
const thumb = (await dialog.locator(".reasoning-effort-thumb").boundingBox())!;
return thumb.x + thumb.width / 2;
};
await expect.poll(async () => Math.abs(await thumbCenter() - pointerX)).toBeLessThan(2);
await page.mouse.up();
await expect(hint).toBeHidden();
await expect(effort).toHaveAttribute("aria-valuetext", "high");
await expect.poll(async () => Math.abs(await thumbCenter() - endX)).toBeLessThan(1);
await effort.press("ArrowLeft");
const ultrafast = speeds.getByRole("button", { name: "Ultrafast" });
await fast.press("Space");
await expect(fast).toHaveAttribute("aria-pressed", "true");
await ultrafast.click();
await expect(ultrafast).toHaveAttribute("aria-pressed", "true");
await expect(fast).toHaveAttribute("aria-pressed", "false");
expect(await speeds.evaluate((group) => [...group.querySelectorAll("button")].every((button) =>
button.scrollWidth <= button.clientWidth + 1 && button.offsetWidth >= 44 && button.offsetHeight >= 44,
))).toBe(true);
await dialog.press("Escape");
await page.getByLabel("Message input").fill("Test this speed");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByLabel("Sent model options")).toHaveText("Reasoning: medium; Codex Fast: ultrafast");
await page.reload();
await open.click();
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await expect(ultrafast).toHaveAttribute("aria-pressed", "true");
await ultrafast.click();
await expect(ultrafast).toHaveAttribute("aria-pressed", "false");
await dialog.press("Escape");
await page.getByLabel("Message input").fill("Turn fast mode off");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByLabel("Sent model options")).toHaveText("Reasoning: medium; Codex Fast: off");
});
test("provider examples switch from Codex to direct API and gateway capabilities", async ({ page }) => {
await page.goto("/browser/fixture.html?case=model-options&ultrafast");
const navigation = page.getByRole("navigation", { name: "Provider examples" });
await navigation.getByRole("link", { name: "Direct APIs" }).click();
await page.getByRole("button", { name: "Default", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Switch model", exact: true });
const reasoning = dialog.getByRole("slider", { name: "Reasoning effort" });
await expect(reasoning).toHaveAttribute("aria-valuetext", "high");
await expect(dialog.getByRole("button", { name: "Fast", exact: true })).toHaveCount(0);
await reasoning.press("End");
await expect(reasoning).toHaveAttribute("aria-valuetext", "max");
await dialog.evaluate((element) => Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)));
const track = (await dialog.locator(".reasoning-effort-track").boundingBox())!;
const fill = (await dialog.locator(".reasoning-effort-fill").boundingBox())!;
const thumb = (await dialog.locator(".reasoning-effort-thumb").boundingBox())!;
expect(thumb.x + thumb.width).toBeGreaterThan(track.x + track.width);
expect(Math.abs(fill.x + fill.width - thumb.x - thumb.width / 2)).toBeLessThan(1);
await dialog.press("Escape");
await page.getByLabel("Message input").fill("Review direct API reasoning options");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByLabel("Sent model options")).toHaveText("Reasoning: max; Codex Fast: unchanged");
await navigation.getByRole("link", { name: "Gateways" }).click();
await page.getByRole("button", { name: "Default", exact: true }).click();
await expect(reasoning).toHaveAttribute("aria-valuetext", "Auto");
});
test("keeps the custom reasoning effort as a concrete value for a self-hosted preset", async ({ page }) => {
await page.goto("/browser/fixture.html?case=model-options&group=local");
await page.getByRole("button", { name: "Default", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Switch model", exact: true });
await dialog.getByRole("option", { name: "Custom API", exact: true }).click();
await page.getByRole("button", { name: "Custom API", exact: true }).click();
const effort = dialog.getByRole("combobox", { name: "Reasoning effort" });
await expect(effort.locator("option:checked")).toHaveText("extended");
await effort.selectOption({ label: "low" });
await dialog.press("Escape");
await page.getByLabel("Message input").fill("Review custom API reasoning options");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.getByLabel("Sent model options")).toHaveText("Reasoning: low; Codex Fast: unchanged");
});
test("touch drag previews the next effort without saving it until release", async ({ page }) => {
await page.setViewportSize({ width: 320, height: 800 });
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
await page.goto("/browser/fixture.html?case=model-options&ultrafast&dark");
await page.getByRole("button", { name: "Default", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Switch model", exact: true });
const effort = dialog.getByRole("slider", { name: "Reasoning effort" });
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await dialog.evaluate((element) => Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)));
const ticks = dialog.locator(".reasoning-effort-tick");
const medium = (await ticks.nth(2).boundingBox())!;
const high = (await ticks.nth(3).boundingBox())!;
const startX = medium.x + medium.width / 2;
const endX = high.x + high.width / 2;
const y = medium.y + medium.height / 2;
const touch = (type: "touchStart" | "touchMove" | "touchCancel" | "touchEnd", x?: number) =>
cdp.send("Input.dispatchTouchEvent", { type, touchPoints: x === undefined ? [] : [{ x, y }] });
const hint = page.getByRole("tooltip");
const previewHigh = async () => {
await touch("touchStart", startX);
await touch("touchMove", startX + 0.75 * (endX - startX));
await expect(hint).toHaveText("high");
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
};
await previewHigh();
await touch("touchCancel");
await expect(hint).toBeHidden();
await expect(effort).toHaveAttribute("aria-valuetext", "medium");
await previewHigh();
await touch("touchEnd");
await expect(hint).toBeHidden();
await expect(effort).toHaveAttribute("aria-valuetext", "high");
});