A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 分叉对话被拒时,原因留在框里
lmliheng21384e461497
diff --git a/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.md b/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.mdnew file mode 100644index 00000000..451ab117--- /dev/null+++ b/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.md@@ -0,0 +1,48 @@+# A refused fork keeps the dialog open, with the reason inside it++- **Date:** 2026-10-28+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-10-28-fork-refusal-keeps-dialog.zh.md)++A reply's footer forks the conversation from that reply, behind a confirmation. Pressing Confirm+used to close the dialog first and fire the request afterwards: if the fork did not happen, the+only report was a toast — which dismisses itself after six seconds and sits over a dialog that is+no longer there — while the conversation stayed exactly as it was. The one place the user was+looking said nothing about what went wrong or whether anything had happened at all.++The dialog now settles from the answer. It stays up, disabled with its spinner, until the fork+request returns; a fork that happened closes it (the app is already navigating to the new+conversation), and one that did not keeps it, with the server's own sentence in the refusal slot —+`操作被拒绝:` followed by the reason, the same rule every other confirm dialog in the app follows.+The button is clickable again, so a retry is one click from the reason.++## Details++- `packages/web/src/features/chat/task-stats-line.tsx`: the dialog owns the outcome. A new+ `forkNow()` awaits `onFork`, closes the dialog only on success, and renders the failure through+ the `refusal` slot; the state is cleared whenever the dialog is opened, so an old reason never+ greets a new attempt.+- `packages/web/src/features/chat/chat-page.tsx`: `onFork` no longer toasts — it **rejects**, so+ the caller can decide where the reason belongs. The "reply cannot be located" branch (the+ position is not in history yet) now throws an `Error` carrying the localized sentence already+ written for it (`S.chat.forkSessionFailed`) rather than toasting it.+- `packages/web/src/lib/api-error.ts`: new `refusalText()` — `apiErrorText` for anything the+ server answered (localized by code), the thrown message for a condition this codebase raised+ itself, and the generic failure only for a value with nothing to say. Kept in one place because+ every refusal slot wants the same rule.+- `packages/web/test/api-error-text.test.ts`: three cases for `refusalText` — a mapped server+ code stays localized, an unmapped one still falls through to the server's sentence, a+ self-raised `Error` shows its own text, and a value with nothing to say reads as the generic+ failure.+- `packages/web/e2e/session-fork.spec.mjs`: a second test in the fork spec. The fork request is+ answered with the server's own stale-position refusal (`invalid_fork_position`, 400) and the+ test asserts the question stays up, the reason is inside it, exactly one request was made, the+ page did not move — then removes the refusal and confirms again, which forks and navigates.++## Compatibility++- No API, on-disk or protocol change. A fork that succeeds behaves exactly as before; a fork that+ fails is now reported in the dialog instead of a toast.diff --git a/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.zh.md b/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.zh.mdnew file mode 100644index 00000000..1d097ad5--- /dev/null+++ b/changelog/unreleased/2026-10-28-fork-refusal-keeps-dialog.zh.md@@ -0,0 +1,37 @@+# 分叉被拒绝时,对话框留着、原因也留在框里++- **日期:** 2026-10-28+- **类型:** 修复+- **范围:** `web`+- **破坏性:** 否++[English](2026-10-28-fork-refusal-keeps-dialog.md)++一条回复的脚注里可以从那条回复分叉对话,点击后先确认。过去按下「分叉」会**先把对话框收起**、+再发请求:分叉没成时唯一的告知是一枚 toast —— 六秒后自己消失、还浮在已经不在的对话框上面,+而对话本身一点没变。用户当时唯一在看的地方,既没说哪里错了,也没说有没有发生任何事。++现在对话框由这次请求的结果来决定去留:请求返回之前它一直开着(确认按钮按下、显示转圈);+成了就收起(这时界面已经在跳到新对话),没成就留着,把服务端自己的那句话放进「拒绝」那一栏+——「操作被拒绝:」加原因,与应用里其他确认框同一条规则。按钮随即恢复可点,重试离原因只有一次点击。++## 细节++- `packages/web/src/features/chat/task-stats-line.tsx`:对话框掌握结果。新增的 `forkNow()` 等+ `onFork` 落地,只有成功才收起对话框,失败则经 `refusal` 那一栏显示原因;每次打开对话框都清掉旧原因,+ 不让上一次的失败迎接下一次尝试。+- `packages/web/src/features/chat/chat-page.tsx`:`onFork` 不再自己弹 toast,改为**抛出** —— 由调用方+ 决定原因该出现在哪里。「定位不到这条回复」(历史里还没有它的位置)这一支改成抛出一个携带既有中文+ 文案(`S.chat.forkSessionFailed`)的 `Error`,而不是把它当 toast 弹掉。+- `packages/web/src/lib/api-error.ts`:新增 `refusalText()` —— 服务端答过的走 `apiErrorText`(按码本地化),+ 本仓自己判定的走抛出时的文案,什么也没有的才落到通用失败提示。放在一处,是因为每一处「拒绝」栏+ 都要同一条规则。+- `packages/web/test/api-error-text.test.ts`:`refusalText` 三条用例 —— 已映射的服务端码保持本地化、+ 没映射的仍退回服务端原话、本仓自判的 `Error` 显示自己的句子、无话可说的落到通用失败提示。+- `packages/web/e2e/session-fork.spec.mjs`:分叉用例文件里加了第二条。分叉请求被回答成服务端自己的+ 「位置失效」拒绝(`invalid_fork_position`,400),断言:问题还开着、原因在框里、只发了一次请求、+ 页面没动;随后撤掉这条拒绝再确认一次,分叉成立并跳到新对话。++## 兼容性++- 不改接口、不改落盘、不改协议。分叉成功的行为与过去完全一致;失败的告知从 toast 换成对话框里的原因。diff --git a/packages/web/e2e/session-fork.spec.mjs b/packages/web/e2e/session-fork.spec.mjsindex 8c196dfd..197d8542 100644--- a/packages/web/e2e/session-fork.spec.mjs+++ b/packages/web/e2e/session-fork.spec.mjs@@ -171,3 +171,98 @@ test("fork from reply: button order + confirm gate + clean fork deletion", async0,);});++/**+ * A refused fork keeps the question up, with the reason inside it.+ *+ * The dialog used to close the instant Confirm was pressed and report a failure as a toast: the+ * toast dismisses itself after six seconds, sits over the dialog that is no longer there, and the+ * conversation stays exactly as it was — so the one place the user was looking said nothing about+ * what went wrong (7.19 / 7.20's rule, app-wide: the card that asked the question keeps it and+ * shows why the write did not happen).+ *+ * The refusal replayed here is the server's own stale-position answer — `invalid_fork_position`,+ * "The selected reply no longer exists in this Session.", the 400 a Session whose Trace moved on+ * really returns. This client resolves the position from history immediately before asking, so+ * the condition cannot be staged from the outside; the second half (route removed, same button+ * pressed again) proves the dialog is not a dead end after one.+ */+test("a refused fork keeps the dialog up and the reason inside it", async ({ page }) => {+ const STALE = "The selected reply no longer exists in this Session.";+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);++ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8" },+ })+ ).json();+ const sourceId = sess.session.sessionId;++ let forkRequests = 0;+ page.on("request", (r) => {+ if (/\/api\/sessions\/[^/]+\/fork$/.test(r.url())) forkRequests += 1;+ });++ await page.goto(`${BASE}/chat/${sourceId}`);+ const ta = page.getByPlaceholder(/输入消息/);+ await ta.waitFor();+ await ta.fill("Fork refusal e2e message");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible({+ timeout: 30_000,+ });++ // Ask, then answer the fork request with the server's refusal.+ await page.getByText("Command finished; the result looks as expected.").first().hover();+ await page.getByRole("button", { name: "从这里分叉对话" }).first().click();+ const question = page.getByText("将把这段对话(截至这条回复)复制为一个新对话");+ await expect(question).toBeVisible();++ await page.route("**/api/sessions/*/fork", (route) =>+ route.fulfill({+ status: 400,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "invalid_fork_position", message: STALE } }),+ }),+ );+ await page.getByRole("button", { name: "分叉", exact: true }).click();++ // The question stays, and the server's sentence is inside it.+ await expect(question).toBeVisible();+ await expect(page.getByText(/操作被拒绝:/)).toBeVisible();+ await expect(page.getByText(STALE, { exact: false })).toBeVisible();+ // Nothing was created and the page did not move.+ expect(forkRequests, "exactly one fork request").toBe(1);+ expect(page.url()).toContain(sourceId);+ // The dialog settled: the confirm button is clickable again, so the reason above is not a+ // dead end sitting behind a spinner.+ await expect(page.getByRole("button", { name: "分叉", exact: true })).toBeEnabled();++ // Same button, no refusal this time: the fork goes through and the app follows it.+ await page.unroute("**/api/sessions/*/fork");+ await page.getByRole("button", { name: "分叉", exact: true }).click();+ await page.waitForURL(+ (u) => /\/chat\/session-/.test(u.pathname) && !u.pathname.includes(sourceId),+ { timeout: 15_000 },+ );+ expect(page.url()).not.toContain(sourceId);+});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 1db3443c..2315b730 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -1914,40 +1914,41 @@ export function ChatPage() {// Auth-dead notice primary CTA: the Models page is where the credential is actually fixed.+ /**+ * Forks the open Session at `target`. **Rejects when the fork did not happen** — the dialog+ * that asked owns the outcome, so the reason belongs in that dialog rather than in a toast+ * that dismisses itself over it (7.19's rule, app-wide). Nothing is toasted here at all:+ * a caller that ever wants a toast can wrap it.+ */const onFork = useCallback(async (target: ForkTarget): Promise<void> => {if (!selected) return;- try {- let position = target.position;- // Live SSE messages do not carry disk coordinates. Once the Task is idle, one history- // read resolves the just-finished footer onto the immutable Trace position; the fork- // request itself always sends that position, never display text or a timestamp.- if (position === undefined) {- const history = await api.getMessages(selected.sessionId);- const model = createStreamModel();- for (const message of history.messages) pushMessage(model, message);- finalizeHistory(model);- const match = [...model.items]- .reverse()- .find(- (item) =>- item.kind === "task_stats" &&- item.assistantText === target.assistantText &&- item.atMs === target.atMs &&- item.forkPosition !== undefined,- );- position = match?.kind === "task_stats" ? match.forkPosition : undefined;- }- if (position === undefined) {- toastError(S.chat.forkSessionFailed);- return;- }- const created = await api.forkSession(selected.sessionId, { position });- addSession(created.session);- navigate(`/chat/${created.session.sessionId}`);- } catch (e) {- toastError(apiErrorText(e, { modelId: selected.modelId }));+ let position = target.position;+ // Live SSE messages do not carry disk coordinates. Once the Task is idle, one history+ // read resolves the just-finished footer onto the immutable Trace position; the fork+ // request itself always sends that position, never display text or a timestamp.+ if (position === undefined) {+ const history = await api.getMessages(selected.sessionId);+ const model = createStreamModel();+ for (const message of history.messages) pushMessage(model, message);+ finalizeHistory(model);+ const match = [...model.items]+ .reverse()+ .find(+ (item) =>+ item.kind === "task_stats" &&+ item.assistantText === target.assistantText &&+ item.atMs === target.atMs &&+ item.forkPosition !== undefined,+ );+ position = match?.kind === "task_stats" ? match.forkPosition : undefined;}+ // Not an ApiError: this one never reached the server. `refusalText` shows the sentence+ // as written, which is why it is an `Error` carrying the localized text.+ if (position === undefined) throw new Error(S.chat.forkSessionFailed);+ const created = await api.forkSession(selected.sessionId, { position });+ addSession(created.session);+ navigate(`/chat/${created.session.sessionId}`);},[selected, addSession, navigate],);diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsxindex 3812eaee..fd3e066d 100644--- a/packages/web/src/features/chat/task-stats-line.tsx+++ b/packages/web/src/features/chat/task-stats-line.tsx@@ -48,6 +48,7 @@ import {humanizeTokens,} from "../../lib/format";import { STAT_ICONS } from "../../lib/stat-icons";+import { refusalText } from "../../lib/api-error";import { S } from "../../lib/strings";import { useTheme } from "../../state/theme";import { useLocale } from "../../state/locale";@@ -84,6 +85,11 @@ export function TaskStatsLine({// conversation is a heavier action than the neighboring copy button suggests, so a stray// click must not silently create a Session. Plain copy stays unconfirmed.const [confirmingFork, setConfirmingFork] = useState(false);+ // Why the last fork attempt did not happen. A refused fork leaves the conversation exactly+ // as it was, so the question stays up and the reason lands inside it: the same rule the+ // other confirm dialogs follow (7.19 / 7.20), instead of a toast that dismisses itself over+ // the dialog the user is still reading. Cleared whenever the dialog is (re)opened.+ const [forkRefusal, setForkRefusal] = useState<string | null>(null);// This turn's usage (not a context snapshot): input = this Task's cached + uncached input.const b = stats?.tokensByBucket;@@ -103,6 +109,30 @@ export function TaskStatsLine({parenClose: S.chat.statParenClose,});+ /**+ * Runs the fork the dialog asks about, and settles the dialog from the answer: a fork that+ * happened closes it (the caller has already navigated to the new Session), one that did not+ * keeps it open with the reason. `onFork` rejects rather than toasting precisely so this+ * decision can be made here.+ */+ const forkNow = async (): Promise<void> => {+ if (!onFork) return;+ setForking(true);+ setForkRefusal(null);+ try {+ await onFork({+ assistantText: assistantText ?? "",+ ...(atMs !== undefined ? { atMs } : {}),+ ...(forkPosition !== undefined ? { position: forkPosition } : {}),+ });+ setConfirmingFork(false);+ } catch (err) {+ setForkRefusal(refusalText(err));+ } finally {+ setForking(false);+ }+ };+// ≥sm: invisible but **space-reserved** by default (sm:opacity-0, not hidden) — the user// footer's hover-reveal convention; because the space is always reserved, appearing never// pushes content below it down. Below sm the line is ALWAYS visible: hover doesn't exist on@@ -183,7 +213,10 @@ export function TaskStatsLine({disabled={forking}data-tooltip={S.chat.forkSession}aria-label={S.chat.forkSession}- onClick={() => setConfirmingFork(true)}+ onClick={() => {+ setForkRefusal(null);+ setConfirmingFork(true);+ }}className="flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 disabled:cursor-wait disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:text-gray-300">{forking ? (@@ -214,16 +247,9 @@ export function TaskStatsLine({confirmLabel={S.chat.forkSessionConfirmAction}cancelLabel={S.common.cancel}busy={forking}+ refusal={forkRefusal === null ? undefined : S.common.refused(forkRefusal)}onClose={() => setConfirmingFork(false)}- onConfirm={() => {- setConfirmingFork(false);- setForking(true);- void onFork({- assistantText,- ...(atMs !== undefined ? { atMs } : {}),- ...(forkPosition !== undefined ? { position: forkPosition } : {}),- }).finally(() => setForking(false));- }}+ onConfirm={() => void forkNow()}><p className="text-sm text-gray-600 dark:text-gray-300">{S.chat.forkSessionConfirmBody}diff --git a/packages/web/src/lib/api-error.ts b/packages/web/src/lib/api-error.tsindex 62e0ef62..e541a0ff 100644--- a/packages/web/src/lib/api-error.ts+++ b/packages/web/src/lib/api-error.ts@@ -24,3 +24,20 @@ export function apiErrorText(err: unknown, ctx?: { modelId?: string }): string {const byCode = S.errors.byCode as Record<string, string | undefined>;return byCode[err.code] ?? err.message;}++/**+ * The sentence a dialog puts in its `refusal` slot when the write it asked about failed.+ *+ * `apiErrorText` is right for anything the server answered, but it reads every other value as+ * `S.common.unknownError` — and a dialog can stop before the request is even sent (the fork's+ * position could not be located, say), which is a condition that codebase raises itself with+ * its own localized sentence. Those are `Error`s whose message is already meant for the user,+ * so they are shown as they are; only a value with nothing to say falls back to the generic+ * text. Which words appear is decided in one place because every refusal slot wants the same+ * rule (7.19's rule, app-wide).+ */+export function refusalText(err: unknown): string {+ if (err instanceof ApiError) return apiErrorText(err);+ if (err instanceof Error && err.message.trim() !== "") return err.message;+ return S.common.unknownError;+}diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.tsindex b38774cb..4080d558 100644--- a/packages/web/test/api-error-text.test.ts+++ b/packages/web/test/api-error-text.test.ts@@ -11,7 +11,7 @@*/import { afterEach, describe, expect, it } from "vitest";import { ApiError, apiFetch } from "../src/api/client";-import { apiErrorText } from "../src/lib/api-error";+import { apiErrorText, refusalText } from "../src/lib/api-error";import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";import { en as EN } from "../src/lib/strings-en";import { apiError, stubFetch } from "./helpers/fetch";@@ -106,3 +106,41 @@ describe("apiErrorText", () => {});});});++describe("refusalText (what a dialog puts in its refusal slot)", () => {+ afterEach(() => {+ setActiveStrings(ZH);+ });++ it("localizes a server refusal by code, exactly as apiErrorText does", () => {+ for (const dict of [ZH, EN]) {+ setActiveStrings(dict);+ // Mapped code: the server's English sentence never reaches the user.+ expect(refusalText(serverError("nothing_to_compact"))).toBe(+ apiErrorText(serverError("nothing_to_compact")),+ );+ expect(refusalText(serverError("nothing_to_compact"))).not.toBe("RAW ENGLISH SERVER MESSAGE");+ // Unmapped code still falls through to the server's own words.+ expect(refusalText(serverError("some_code_from_the_future"))).toBe(+ "RAW ENGLISH SERVER MESSAGE",+ );+ }+ });++ it("shows a sentence this codebase raised itself, instead of the generic failure", () => {+ // The fork dialog stops before the request when the reply's Trace position cannot be+ // resolved; that condition carries its own localized text, and it is the whole reason+ // refusalText exists — apiErrorText would flatten it into `unknownError` and tell the+ // user nothing about what to do next.+ setActiveStrings(ZH);+ expect(S.chat.forkSessionFailed).not.toBe(S.common.unknownError);+ expect(refusalText(new Error(S.chat.forkSessionFailed))).toBe(S.chat.forkSessionFailed);+ });++ it("falls back to the generic failure when there is nothing to say", () => {+ setActiveStrings(ZH);+ expect(refusalText(new Error(" "))).toBe(S.common.unknownError);+ expect(refusalText("not even an error")).toBe(S.common.unknownError);+ expect(refusalText(undefined)).toBe(S.common.unknownError);+ });+});