A local-first multi-agent app development platform, built on PenguinHarness
fix(web): a refused model switch in a session keeps its reason in the card
lmliheng6e13c33f7db6
diff --git a/changelog/unreleased/2026-11-13-model-switch-refusal.md b/changelog/unreleased/2026-11-13-model-switch-refusal.mdnew file mode 100644index 00000000..1ef2a3f5--- /dev/null+++ b/changelog/unreleased/2026-11-13-model-switch-refusal.md@@ -0,0 +1,48 @@+# The in-session model switch keeps a refused switch's reason inside the card++- **Date:** 2026-11-13+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文版](2026-11-13-model-switch-refusal.zh.md)++The session toolbar's model picker asks before it writes — "compact on the current model, then+switch", with an optional escape hatch that drops the context when that compaction cannot complete.+The card closed itself on the answer either way, and a refusal (the session is busy, the target+model is not configured or unavailable, the Project has no compaction configured) was reported only+as a notification that dismissed itself after six seconds. The conversation stayed on the model it+was on, so what was left was a card that had vanished and a sentence nobody had time to read.++The card now stays open with the server's words inside it, in the shared card's `refusal` slot —+`操作被拒绝:<reason>` under the sentence it answered, above the same button that retries the very+same switch (the sentence, the target model and the escape hatch's tick are untouched: a refused+write changed nothing). The reason is cleared at the start of the next attempt, on a fresh pick, and+when the user closes the card.++## Details++- `packages/web/src/features/chat/chat-page.tsx`: a `modelSwitchRefusal` state beside+ `modelSwitchAsk`. `confirmModelSwitch` fills it from `apiErrorText` on a refusal instead of+ toasting, clears it when an attempt starts, and closes the card itself on the two success paths+ (it used to close in `finally`, i.e. whatever the answer). The card passes the state to `refusal`+ and clears it in `onClose`.+- Nothing else about the switch moved: the three shapes of its sentence, the discard checkbox, the+ busy/disabled rule, the request body, and the toasts that report a switch that started or landed.++## Tests++- `packages/web/e2e/model-switch-refusal.spec.mjs` (new, two cases, real server + the repository's+ mock model + a real browser): a refused switch keeps the card and the sentence in it past the six+ seconds a notification lived, nothing in the notification region, and the Session is still on the+ model the dialog promised to leave — then the same button retries and lands; and a 409 whose code+ the interface has its own words for reads those words, with cancel dropping the sentence for the+ next pick.+- Run against the page as it was before the change (`HEAD`'s source, rebuilt), both cases fail on+ the card's missing `role="alert"`.++## Compatibility++No wire change, no new dependency, no Project config change, no new copy: the sentence is the+existing app-wide `操作被拒绝:<reason>`. Successful switches, the compaction notices and every other+notification are untouched.diff --git a/changelog/unreleased/2026-11-13-model-switch-refusal.zh.md b/changelog/unreleased/2026-11-13-model-switch-refusal.zh.mdnew file mode 100644index 00000000..2cb02f26--- /dev/null+++ b/changelog/unreleased/2026-11-13-model-switch-refusal.zh.md@@ -0,0 +1,38 @@+# 会话里换模型被拒时,原因留在发问的那张卡片里++- **日期:** 2026-11-13+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 否++[English](2026-11-13-model-switch-refusal.md)++会话工具栏的模型选择器是「先问再写」的:先用当前模型压缩上下文、然后切换,另有一个可选项在压缩失败时直接+放弃摘要。这张卡片以前无论答案是什么都会自己关掉,而被拒的回话(会话正忙、目标模型没配置或暂不可用、项目没+配置压缩)只落在一条六秒后自己消失的通知里 —— 对话仍停在原来那个模型上,屏幕上留下的是凭空消失的卡片和一句+来不及读的字。++现在卡片留着,原因画在它里面:走共享卡片的 `refusal` 槽,`操作被拒绝:<原因>` 在被它回答的那句话下面、重试+同一次切换的那个按钮上面(上面那句话、目标模型、那个选项的勾选状态都原样不动 —— 被拒的写什么都没改)。这句话+在下次尝试开始、换一个模型、或用户关掉卡片时清掉。++## 细节++- `packages/web/src/features/chat/chat-page.tsx`:`modelSwitchAsk` 旁边新增 `modelSwitchRefusal`。+ `confirmModelSwitch` 在被拒时用 `apiErrorText` 填它、不再另弹通知;每次尝试开始先清掉;两条成功路径各自关掉+ 卡片(以前是在 `finally` 里关,也就是不问结果)。卡片把这个状态交给 `refusal`,并在 `onClose` 里清掉。+- 这次切换的其余部分一处未动:那句话的三种形态、放弃摘要的勾选框、忙碌即禁用的规则、请求体,以及「已经开始的+ 切换 / 已经落地的切换」那两条通知。++## 测试++- `packages/web/e2e/model-switch-refusal.spec.mjs`(新增,两条用例,真服务端 + 仓库自带的 mock 模型 + 真浏览器):+ 被拒的切换让卡片与它里面的那句话活过通知的六秒、通知区没有东西、会话仍在对话框说要离开的那个模型上 —— 随后+ 同一个按钮重试并落地;另一条是被拒的 409(接口对它有自己的说法)读出接口自己的话,取消之后下一次选择是一张+ 干净的卡片。+- 拿改动前的页面(`HEAD` 的源码重新构建)跑同一份用例,两条都死在卡片里找不到 `role="alert"`。++## 兼容性++线上接口没变、没有新依赖、Project 配置没变、没有新文案:那句话就是全应用既有的 `操作被拒绝:<原因>`。成功的切换、+压缩那几条通知与其余通知一字未改。diff --git a/packages/web/e2e/model-switch-refusal.spec.mjs b/packages/web/e2e/model-switch-refusal.spec.mjsnew file mode 100644index 00000000..cf6c89f7--- /dev/null+++ b/packages/web/e2e/model-switch-refusal.spec.mjs@@ -0,0 +1,175 @@+/**+ * Regression: a model switch the server refused keeps the confirm card open with the reason in it,+ * instead of closing the card and leaving a notification that dismisses itself after six seconds.+ *+ * The card is what asked for the write, and its button is the retry: the conversation is still on+ * the model it was on, so a card that closed itself plus a toast nobody read is the whole account of+ * a press that changed nothing. The sentence is drawn in the card's `refusal` slot (`role="alert"`,+ * the app's shared `操作被拒绝:<reason>` lead) and stays until the next attempt, a new pick, cancel.+ *+ * Both refusals here are stubbed with an English wire message: the first carries a code the+ * interface translates generically, the second a code it has its own words for (the target model is+ * unavailable) — so the test also pins that the user never reads the server's raw English.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const P = "password123";+const FROM = "claude-4-8";+const TO = "claude-4-7";+/** The mock's turn-2 answer (mock-llm.mjs): the conversation is over and the Session idle. */+const REPLY = "Command finished; the result looks as expected.";+/** A message that must not reach the page: only the interface's own words may. */+const RAW = "RAW ENGLISH SERVER MESSAGE";++const notifications = (page) => page.getByRole("region", { name: "通知" });++/** Log in, and give the new user's Project the two mock models this spec switches between. */+async function setUp(page, user) {+ await provisionAndLogin(page.request, user, P);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: FROM },+ models: [+ {+ provider: "custom",+ modelId: FROM,+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ {+ provider: "custom",+ modelId: TO,+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 100000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ return projectId;+}++async function createSession(page, projectId) {+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: FROM, approvalMode: "allow-all" },+ })+ ).json();+ return sess.session.sessionId;+}++/** A Session with one finished round, so a switch has something to compact. */+async function sessionWithConversation(page, projectId) {+ const sessionId = await createSession(page, projectId);+ await page.goto(`${BASE}/chat/${sessionId}`);+ const composer = page.getByPlaceholder(/输入消息/);+ await composer.waitFor();+ await composer.fill("hello");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(page.getByText(REPLY).first()).toBeVisible();+ return sessionId;+}++/** Open the composer's model picker, pick the other model, and hand back the confirm dialog. */+async function askToSwitch(page) {+ const trigger = page.getByRole("button", { name: "选择模型" }).first();+ await expect(trigger).toBeEnabled();+ await trigger.click();+ const picker = page.getByRole("dialog", { name: "选择模型" });+ await expect(picker).toBeVisible();+ await picker.locator('li[role="option"]').filter({ hasText: TO }).locator("button").click();+ const dialog = page.getByRole("dialog", { name: "切换模型" });+ await expect(dialog).toBeVisible();+ return dialog;+}++/** The Session's own model, read from the server rather than from the page. */+async function sessionModel(page, projectId, sessionId) {+ const body = await (+ await page.request.get(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`)+ ).json();+ const row = body.sessions.find((s) => s.sessionId === sessionId);+ return row?.modelId ?? null;+}++test("a refused switch keeps the card and the reason inside it, and the retry is the same button", async ({+ page,+}) => {+ const projectId = await setUp(page, "swrefusal1");+ const sessionId = await sessionWithConversation(page, projectId);++ const posted = [];+ let refuse = true;+ await page.route("**/api/sessions/*/switch-model", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ posted.push(route.request().postDataJSON());+ if (!refuse) return route.fallback();+ return route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "internal", message: RAW } }),+ });+ });++ const dialog = await askToSwitch(page);+ await dialog.getByRole("button", { name: "压缩并切换" }).click();++ const reason = "操作被拒绝:服务器内部错误,请稍后重试。";+ const line = dialog.getByRole("alert");+ await expect(line).toBeVisible();+ await expect(line).toHaveText(reason);+ // The interface's words for that code, never the server's English — and in the card, not in+ // the notification region.+ await expect(line).not.toContainText("RAW ENGLISH");+ await expect(notifications(page)).not.toContainText("RAW ENGLISH");++ // Past the six seconds an error notification lived, the card and its sentence are still there.+ await page.waitForTimeout(7500);+ await expect(dialog).toBeVisible();+ await expect(line).toHaveText(reason);+ // Nothing moved: the Session is still on the model the dialog promised to leave.+ expect(await sessionModel(page, projectId, sessionId)).toBe(FROM);++ // The retry is the same button: the sentence of the attempt before it goes, this one lands.+ refuse = false;+ await dialog.getByRole("button", { name: "压缩并切换" }).click();+ await expect(page.getByText(`正在用「${FROM}」压缩上下文`).first()).toBeVisible();+ await expect(page.getByRole("dialog", { name: "切换模型" })).toHaveCount(0);+ expect(posted).toHaveLength(2);+});++test("the refusal names the target model, and cancel takes it away for the next pick", async ({+ page,+}) => {+ const projectId = await setUp(page, "swrefusal2");+ await sessionWithConversation(page, projectId);++ await page.route("**/api/sessions/*/switch-model", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ return route.fulfill({+ status: 409,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "model_unavailable", message: RAW } }),+ });+ });++ const dialog = await askToSwitch(page);+ await dialog.getByRole("button", { name: "压缩并切换" }).click();+ await expect(dialog.getByRole("alert")).toHaveText(+ "操作被拒绝:所选模型暂不可用(例如还没有 API key),请先在「模型」页配置。",+ );++ // Cancel closes it, and the next pick opens a clean card: that sentence answered that attempt.+ await dialog.getByRole("button", { name: "取消" }).click();+ await expect(page.getByRole("dialog", { name: "切换模型" })).toHaveCount(0);+ const again = await askToSwitch(page);+ await expect(again.getByRole("alert")).toHaveCount(0);+ await expect(again.getByRole("button", { name: "压缩并切换" })).toBeEnabled();+});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 54b00f98..857b8130 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -383,6 +383,10 @@ export function ChatPage() {// The dialog stays open (its buttons busy) until the switch request answers, so a double// click cannot post the switch twice.const [modelSwitchPosting, setModelSwitchPosting] = useState(false);+ // A switch the server refused, in its own words, drawn inside the dialog that asked for it+ // (see confirmModelSwitch): a toast says the same thing but dismisses itself out of a card the+ // user is still looking at, six seconds before they read why the conversation stayed put.+ const [modelSwitchRefusal, setModelSwitchRefusal] = useState<string | null>(null);const routeSessionId = params.sessionId ?? null;// The docks' arrangement lives in the dock store (features/dock) — tabs, active tab,@@ -1900,6 +1904,9 @@ export function ChatPage() {// Read at pick time: the model's items mutate in place. The live tail decides, behind// whatever window was backfilled above it.const shape = switchContextShape([...stream.prefixItems, ...stream.model.items]);+ // A fresh pick answers the last attempt: whatever it was refused for was about the model+ // that pick asked for, not this one.+ setModelSwitchRefusal(null);setModelSwitchAsk({ to: ref, shape, discardIfCompactionFails: false });},[selected, stream.taskState, stream.prefixItems, stream.model],@@ -1911,11 +1918,15 @@ export function ChatPage() {// never ran and switched inside the request: the row comes back with the response — under a// new id when the server had to rebuild a Session that left no Trace, which the page follows.// A refusal (409 busy / same model / not configured / unavailable / compaction not configured)- // is a toast.+ // keeps this dialog and draws the sentence inside it: the card is what asked for the write, its+ // button is the retry, and the conversation is still on the model it named before — a toast+ // would be gone six seconds before the user looks back at a card that had closed itself.const confirmModelSwitch = useCallback(async () => {const ask = modelSwitchAsk;if (!selected || ask === null || modelSwitchPosting) return;setModelSwitchPosting(true);+ // Another attempt answers the previous one, whatever it says.+ setModelSwitchRefusal(null);const from = modelDisplay({ provider: selected.provider, modelId: selected.modelId });const to = modelDisplay(ask.to);try {@@ -1930,10 +1941,12 @@ export function ChatPage() {});if ("session" in res) {applySessionRow(res.session);+ setModelSwitchAsk(null);toastSuccess(S.chat.modelSwitchInSessionApplied(to));await syncHealedSessionId(selected.sessionId, res.session.sessionId);return;}+ setModelSwitchAsk(null);// Only a switch that compacts may say so; one that continues from a held summary runs// no compaction and must not promise one.toastInfo(@@ -1944,10 +1957,9 @@ export function ChatPage() {} catch (e) {// The codes that take a model name are about the model the Session is on (its loader's// missing credential); a refusal of the target names it in its own message.- toastError(apiErrorText(e, { modelId: selected.modelId }));+ setModelSwitchRefusal(apiErrorText(e, { modelId: selected.modelId }));} finally {setModelSwitchPosting(false);- setModelSwitchAsk(null);}}, [modelSwitchAsk,@@ -2905,7 +2917,9 @@ export function ChatPage() {is immediate) and a transcript ending in a completed compaction or a model switch (nocompaction runs; the conversation continues from what is already held). The sessioncan start running while the dialog is up (a queued follow-up, a schedule): the confirm- is then disabled and the body says why, exactly like the thinking dialog. */}+ is then disabled and the body says why, exactly like the thinking dialog. A refused+ switch keeps this card and shows the server's sentence in it, under the sentence and+ the box whose button retries the same switch. */}<ConfirmModalopen={modelSwitchAsk !== null}title={S.chat.modelSwitchInSessionTitle}@@ -2918,9 +2932,13 @@ export function ChatPage() {cancelLabel={S.common.cancel}confirmDisabled={stream.taskState !== "idle"}busy={modelSwitchPosting}+ refusal={modelSwitchRefusal === null ? undefined : S.common.refused(modelSwitchRefusal)}onConfirm={() => void confirmModelSwitch()}onClose={() => {- if (!modelSwitchPosting) setModelSwitchAsk(null);+ if (modelSwitchPosting) return;+ setModelSwitchAsk(null);+ // A card closed by its user takes its last answer with it: the next pick asks anew.+ setModelSwitchRefusal(null);}}><p className="text-sm text-gray-600 dark:text-gray-300">{modelSwitchBody}</p>