Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): 员工手册保存被拒时,原因留在草稿上方,不再只活六秒

lmliheng28b3362b0222
diff --git a/changelog/unreleased/2026-11-05-handbook-save-refusal.md b/changelog/unreleased/2026-11-05-handbook-save-refusal.md
new file mode 100644
index 00000000..023a1c2d
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-handbook-save-refusal.md
@@ -0,0 +1,52 @@
+# A refused handbook save says why above the draft, not in a six-second toast
+
+- **Date:** 2026-11-05
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-05-handbook-save-refusal.zh.md)
+
+The organization handbook's editor (`/org/<project>/<org>/handbook`) is a textarea with Save and
+Cancel in the document's header. A save the server refused changed nothing on screen — the editor
+stayed open with the draft in it and Save stayed where it was — and the reason arrived as one
+notification that dismissed itself after six seconds. Afterwards the page looked exactly as it had
+before the press: same text, same button, no word about why the file was untouched. Save is the
+retry, and it was the only thing on screen that could say so.
+
+The reason now stays above the draft (`role="alert"`, danger colour, two lines with the whole text
+on hover) until the text is edited, Save is pressed again, the edit is cancelled or another
+document is selected — so it always describes the last attempt. While the editor holds text the
+file does not, the sentence says so too: nothing typed was lost, and nothing typed was written.
+
+Whose words: `refusalText`, the rule every refusal slot in the app follows (7.19) — a request the
+server answered is read through its code's own localized sentence, and a value this codebase raised
+itself is shown as it wrote it.
+
+## Details
+
+- `packages/web/src/features/company/handbook-save-refusal.ts` (new): `handbookSaveRefusal(error,
+ draft, stored)` — the line, and the decision whether it also says the edits stayed in the editor
+ (the two texts differ) or is just the reason (Save pressed on a document nobody edited).
+- `packages/web/src/features/company/handbook-page.tsx`: `saveRefusal` state, written in `save`'s
+ catch (where `toastError` used to be), cleared by `startEdit`, `cancelEdit`, the draft's
+ `onChange`, another document's load and the next Save; the line is drawn between the document's
+ header and the textarea. The success toast is unchanged.
+- `packages/web/src/lib/strings.ts`, `strings-en.ts`: `saveRefused` and `saveRefusedDraftKept`.
+
+## Tests
+
+- `packages/web/test/handbook-save-refusal.test.ts` (new, 5): a refused write reads its code's
+ localized sentence rather than the server's English; a client-raised error keeps its own message;
+ the line says the edits were not written only when the draft differs from the file; the interface
+ language is respected.
+- `packages/web/e2e/handbook-save-refusal.spec.mjs` (new, real server + real browser, 1 test over
+ the whole flow): a refused save draws the sentence above the draft, the notification region never
+ carries the server's words, the file still holds the old text and the editor still holds the
+ draft; the line is still there after 7 seconds; editing clears it; the retry closes the editor and
+ the file has the new text; cancelling after a refusal drops the draft and the line together.
+
+## Compatibility
+
+No interface change, no new dependency, no Project configuration change. The route, the payload and
+the document's other writes (create, delete) are untouched.
diff --git a/changelog/unreleased/2026-11-05-handbook-save-refusal.zh.md b/changelog/unreleased/2026-11-05-handbook-save-refusal.zh.md
new file mode 100644
index 00000000..4f174582
--- /dev/null
+++ b/changelog/unreleased/2026-11-05-handbook-save-refusal.zh.md
@@ -0,0 +1,43 @@
+# 员工手册保存被拒时,原因留在草稿上方,不再只活六秒
+
+- **日期:** 2026-11-05
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 否
+
+[English](2026-11-05-handbook-save-refusal.md)
+
+组织的员工手册页(`/org/<项目>/<组织>/handbook`)是一个编辑器:文档标题右边是「保存」与「取消」,
+下面是等宽文本框。保存被服务端拒了的时候,屏幕上什么都没变 —— 编辑器还开着、草稿还在、保存按钮
+也在原地 —— 而理由只落进一条六秒后自己消失的通知。六秒之后页面与按下之前一模一样:同样的文字、
+同一颗按钮,没有一句话说清文件为什么没被写入。而那颗按钮正是重试。
+
+那句话现在留在草稿上方(`role="alert"`、危险色、限两行、整句挂悬停),直到文字被改动、再次按下
+保存、取消编辑或换到另一篇文档 —— 所以它说的总是最近一次尝试。当编辑器里的文字与文件里那份不同时,
+句子会一并说出来:改动仍在编辑器里,既没丢,也没写进文件。
+
+用谁的措辞:`refusalText` —— 全应用拒绝位都按这条规则走(7.19)。服务端答过的请求念它的错误码
+对应的本地化句子,本仓库自己抛出的值按它写好的原话显示。
+
+## 明细
+
+- `packages/web/src/features/company/handbook-save-refusal.ts`(新):`handbookSaveRefusal(error,
+ draft, stored)` —— 那一行,以及「要不要一并说改动没写进去」的判定(两份文字不同才说;对一篇没人
+ 改过的文档按保存,就只念原因)。
+- `packages/web/src/features/company/handbook-page.tsx`:新增 `saveRefusal` 状态,写在 `save` 的
+ `catch` 里(原来走 `toastError` 的那一处),由「编辑」开始、取消、草稿的 `onChange`、另一篇文档的
+ 载入与下一次保存清掉;那一行画在文档标题行与文本框之间。成功的那条通知不变。
+- `packages/web/src/lib/strings.ts`、`strings-en.ts`:`saveRefused` 与 `saveRefusedDraftKept`。
+
+## 测试
+
+- `packages/web/test/handbook-save-refusal.test.ts`(新,5 条):被拒的请求念错误码的本地化句子而
+ 不是服务端的英文原文;客户端自己抛的错误保留原话;只有草稿与文件不同时才说改动没写进去;界面语言
+ 跟着切换。
+- `packages/web/e2e/handbook-save-refusal.spec.mjs`(新,真服务端 + 真浏览器,1 条走完整流程):被拒的
+ 保存把句子画在草稿上方、通知区里没有它、文件仍是旧内容而编辑器仍留着草稿;**7 秒后**仍在;改动文字
+ 它就消失;重试后编辑器关闭且文件里是新内容;被拒之后按取消,草稿与句子一起走。
+
+## 兼容性
+
+不碰接口、不引入新依赖、不改 Project 配置。路由、请求体与这篇文档的另外两个写入(新建、删除)都没动。
diff --git a/packages/web/e2e/handbook-save-refusal.spec.mjs b/packages/web/e2e/handbook-save-refusal.spec.mjs
new file mode 100644
index 00000000..e9d3c21b
--- /dev/null
+++ b/packages/web/e2e/handbook-save-refusal.spec.mjs
@@ -0,0 +1,165 @@
+/**
+ * Regression: a handbook edit the server refuses keeps its reason above the draft, inside the
+ * editor that holds the text and the Save button that retries it — instead of leaving only a
+ * toast behind.
+ *
+ * `features/company/handbook-page.tsx` closed nothing on a refused save (the editor stayed open
+ * with the draft in it), but the reason fell into a notification that dismissed itself after a
+ * few seconds: afterwards the editor looked exactly as it had before the press, with the same
+ * draft and the same button, and no word about why nothing was written. The line now stays above
+ * the draft until the text is edited, Save is pressed again or the edit is cancelled.
+ *
+ * The organization and the document are made through the API rather than through the dialogs.
+ * Company mode is off on a fresh server, so the test turns the admin master switch on first
+ * (idempotent), and the Project gets the mock as its model so the onboarding overlay stays off
+ * the page.
+ */
+import { test, expect, request } from "@playwright/test";
+import { ADMIN_ID, ADMIN_PASSWORD, login, provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+const ORG = "orgsaverefuse";
+const MISSION = "把插件市场上线,做到搜索前三。";
+const DOC = "decisions/2026-10-25-hire-plan.md";
+const DOC_BODY = "# 招聘计划\n\n先招两名工程师。\n";
+const DRAFT = "# 招聘计划\n\n先招三名工程师,九月前到岗。\n";
+
+/** The refusal the page paints; a 500 with its own words proves those words came back. */
+const REFUSAL = {
+ code: "org_store_locked",
+ message: "the organization store is mid-rewrite",
+};
+
+/** The admin master switch, off by default: turned on server-wide before the flow starts. */
+async function enableCompanyMode() {
+ const adminCtx = await request.newContext();
+ try {
+ await login(adminCtx, ADMIN_ID, ADMIN_PASSWORD);
+ const res = await adminCtx.put(`${BASE}/api/admin/settings`, { data: { companyMode: true } });
+ if (!res.ok()) {
+ throw new Error(`enable company mode failed: ${res.status()} ${await res.text()}`);
+ }
+ } finally {
+ await adminCtx.dispose();
+ }
+}
+
+/** A fresh user with mock-model credentials, an organization, and one handbook document. */
+async function setUp(page, tag) {
+ await enableCompanyMode();
+ const user = `${tag}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
+ await provisionAndLogin(page.request, user, P);
+ const project = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0];
+ const projectId = project.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,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), `put models ${projectId}`).toBeTruthy();
+
+ const orgBase = `${BASE}/api/projects/${projectId}/organizations`;
+ const created = await page.request.post(orgBase, { data: { orgId: ORG, mission: MISSION } });
+ expect(created.ok(), "create organization").toBeTruthy();
+ const docUrl = `${orgBase}/${ORG}/handbook/files/${DOC}`;
+ const written = await page.request.put(docUrl, { data: { content: DOC_BODY } });
+ expect(written.ok(), "write the handbook document").toBeTruthy();
+
+ /** The document as the server has it. */
+ const read = async () => (await (await page.request.get(docUrl)).json()).content;
+ return { projectId, docUrl, read };
+}
+
+/** The document's row selected, its Edit pressed, and the draft typed over. */
+async function openEditor(page, projectId) {
+ await page.goto(`/org/${projectId}/${ORG}/handbook`);
+ // Folders start closed: the document's own folder is opened by hand, as a reader would.
+ await page.locator('[data-tree-path="decisions"]').click();
+ const row = page.locator(`[data-tree-path="${DOC}"]`);
+ await expect(row).toBeVisible();
+ await row.click();
+ const pane = page.getByRole("region", { name: DOC });
+ await expect(pane).toBeVisible();
+ await pane.getByRole("button", { name: "编辑", exact: true }).click();
+ const editor = pane.getByRole("textbox", { name: DOC });
+ await expect(editor).toBeVisible();
+ await editor.fill(DRAFT);
+ return { pane, editor };
+}
+
+test("a refused handbook save keeps its reason above the draft", async ({ page }) => {
+ const { projectId, docUrl, read } = await setUp(page, "r198hbsave");
+ expect(await read()).toBe(DOC_BODY);
+
+ const { pane, editor } = await openEditor(page, projectId);
+
+ const saves = [];
+ await page.route(docUrl, async (route) => {
+ if (route.request().method() !== "PUT") return route.fallback();
+ saves.push(route.request().postData());
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+
+ await pane.getByRole("button", { name: "保存", exact: true }).click();
+
+ // The reason is above the draft, and it is not a toast: the notification region (which may
+ // still hold the company beta's own notice) never carries the server's words.
+ const line = pane.getByRole("alert");
+ await expect(line).toContainText(REFUSAL.message);
+ await expect(line).toContainText("编辑器里的改动没有写进文件");
+ await expect(page.getByRole("region", { name: "通知" })).not.toContainText(REFUSAL.message);
+ expect(saves).toHaveLength(1);
+
+ // Nothing was written and nothing was lost: the file still holds the old text, while the
+ // editor still holds the draft and is still open — Save is the retry.
+ expect(await read()).toBe(DOC_BODY);
+ await expect(editor).toHaveValue(DRAFT);
+ await expect(pane.getByRole("button", { name: "保存", exact: true })).toBeVisible();
+
+ // Still there after the toast would have gone.
+ await page.waitForTimeout(7000);
+ await expect(line).toContainText(REFUSAL.message);
+
+ // Editing the draft answers a new question: the line goes with the text it described.
+ await editor.fill(`${DRAFT}再补一条备选方案。\n`);
+ await expect(pane.getByRole("alert")).toHaveCount(0);
+
+ // The retry lands: the editor closes, the rendered document is the new text, and the file has it.
+ await page.unroute(docUrl);
+ await pane.getByRole("button", { name: "保存", exact: true }).click();
+ await expect(pane.getByRole("textbox", { name: DOC })).toHaveCount(0);
+ await expect(pane).toContainText("再补一条备选方案");
+ await expect(editor).toHaveCount(0);
+ expect(await read()).toBe(`${DRAFT}再补一条备选方案。\n`);
+
+ // And cancelling after a refusal drops the draft and the line together.
+ const again = await openEditor(page, projectId);
+ await page.route(docUrl, async (route) => {
+ if (route.request().method() !== "PUT") return route.fallback();
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+ await again.pane.getByRole("button", { name: "保存", exact: true }).click();
+ await expect(again.pane.getByRole("alert")).toContainText(REFUSAL.message);
+ await again.pane.getByRole("button", { name: "取消", exact: true }).click();
+ await expect(again.pane.getByRole("alert")).toHaveCount(0);
+ await expect(again.pane.getByRole("textbox", { name: DOC })).toHaveCount(0);
+});
diff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsx
index 610744ff..da131350 100644
--- a/packages/web/src/features/company/handbook-page.tsx
+++ b/packages/web/src/features/company/handbook-page.tsx
@@ -5,8 +5,9 @@
* index (`README.md`, the page every trigger makes the employee read first) leading the rows,
* then folders and documents nested as they are on disk, with one button that collapses them
* all. Right, the selected document rendered as Markdown (anything else preformatted),
- * edited in place through a monospace textarea with save and cancel, and — for every document
- * but the index — deleted behind the shared confirmation, which closes only once its own delete
+ * edited in place through a monospace textarea with save and cancel — a save the server refuses
+ * keeps its reason above the draft, where the button that retries it is — and, for every document
+ * but the index, deleted behind the shared confirmation, which closes only once its own delete
* landed: a refusal keeps the card standing with the server's words inside it, where the button
* that retries them is. The new-document dialog refuses a path the server would, starts from
* the selected document's own folder so a document lands beside its siblings, then creates the
@@ -35,13 +36,13 @@ import {
RuledSection,
Skeleton,
Textarea,
- toastError,
toastSuccess,
} from "@adelie/ui";
import type { TreeToggle } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
+import { toneInk } from "../../lib/tone";
import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";
import { isShortcut } from "../../lib/shortcuts/match";
import { currentPlatform } from "../../lib/shortcuts/platform";
@@ -52,6 +53,7 @@ import { useLocale } from "../../state/locale";
import { OrgEmptyLine, OrgPage, useOrg } from "./org-layout";
import { ErrorLine } from "./shared";
import { COLLAPSE_ALL_ICON, HandbookExplorer } from "./handbook-explorer";
+import { handbookSaveRefusal } from "./handbook-save-refusal";
import {
HANDBOOK_INDEX,
ancestorFolders,
@@ -88,6 +90,8 @@ export function HandbookPage() {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState("");
const [saving, setSaving] = useState(false);
+ /** The words of a save the server refused, kept above the draft whose save button retries it. */
+ const [saveRefusal, setSaveRefusal] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -124,6 +128,8 @@ export function HandbookPage() {
setDoc(null);
setDocError(null);
setEditing(false);
+ // Another document is another draft: the last one's refusal is not about this text.
+ setSaveRefusal(null);
api
.getOrgHandbookFile(projectId, orgId, selected)
.then((res) => {
@@ -184,11 +190,20 @@ export function HandbookPage() {
if (doc === null) return;
setDraft(doc.content);
setEditing(true);
+ setSaveRefusal(null);
+ };
+
+ /** Leaving the editor drops the draft, and with it the answer about the draft's save. */
+ const cancelEdit = () => {
+ setEditing(false);
+ setSaveRefusal(null);
};
const save = async () => {
if (doc === null || saving) return;
setSaving(true);
+ // The last answer is not this attempt's: the line goes when Save is pressed again.
+ setSaveRefusal(null);
try {
const res = await api.putOrgHandbookFile(projectId, orgId, doc.path, draft);
setDoc(res);
@@ -201,7 +216,9 @@ export function HandbookPage() {
toastSuccess(S.common.saved);
void loadList();
} catch (e) {
- toastError(apiErrorText(e));
+ // The editor stays open with the draft in it, so the reason stays where the draft and the
+ // button that retries it are (7.19's rule) rather than in a toast that outlives nothing.
+ setSaveRefusal(handbookSaveRefusal(e, draft, doc.content));
} finally {
setSaving(false);
}
@@ -381,7 +398,7 @@ export function HandbookPage() {
<span className="hidden text-xs text-gray-400 sm:inline dark:text-gray-500">
{S.company.handbook.editorHint(saveShortcut)}
</span>
- <Button size="sm" disabled={saving} onClick={() => setEditing(false)}>
+ <Button size="sm" disabled={saving} onClick={cancelEdit}>
{S.common.cancel}
</Button>
<Button size="sm" variant="primary" disabled={saving} onClick={() => void save()}>
@@ -411,6 +428,16 @@ export function HandbookPage() {
)}
</div>
</div>
+ {editing && saveRefusal !== null && (
+ <p
+ role="alert"
+ data-tooltip={saveRefusal}
+ data-tooltip-content="text"
+ className={`mb-2 line-clamp-2 break-words text-xs ${toneInk.danger}`}
+ >
+ {saveRefusal}
+ </p>
+ )}
{docError !== null ? (
<EmptyState
title={S.company.handbook.documentLoadFailed}
@@ -430,7 +457,11 @@ export function HandbookPage() {
autoFocus
disabled={saving}
className="min-h-[50vh]"
- onChange={(e) => setDraft(e.target.value)}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ // A new draft has not been refused yet: the line described the text as it was.
+ setSaveRefusal(null);
+ }}
onKeyDown={onEditorKey}
/>
) : doc.content.trim() === "" ? (
diff --git a/packages/web/src/features/company/handbook-save-refusal.ts b/packages/web/src/features/company/handbook-save-refusal.ts
new file mode 100644
index 00000000..0fe86910
--- /dev/null
+++ b/packages/web/src/features/company/handbook-save-refusal.ts
@@ -0,0 +1,35 @@
+/**
+ * The handbook editor's Save button: the sentence a refused write leaves above the draft, and why
+ * that sentence is drawn on the page instead of arriving as a toast.
+ *
+ * A refused save changes nothing else on screen — the editor stays open, the draft stays in it,
+ * and Save is the retry — so the reason used to live only in a notification that dismissed itself
+ * after six seconds, leaving an editor that looked like it had simply not been pressed. The
+ * sentence now stays above the draft until the text is edited, the save is pressed again or the
+ * edit is cancelled: while the words in the editor are still the ones that were not written.
+ *
+ * The draft being different from the file is worth saying out loud, because that is the state the
+ * reader is left in: the file still holds what it held, and what they typed is still on screen
+ * but nowhere else. When the two are equal (Save pressed on a document nobody edited) there is
+ * nothing lost, so the sentence is just the reason.
+ *
+ * Which words: `refusalText`, the rule every refusal slot in the app follows (7.19) — a request
+ * the server answered is read through its code's own localized sentence, a value this codebase
+ * raised itself is shown as it wrote it.
+ */
+import { refusalText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+
+/**
+ * The line the editor draws above the draft after a refused save.
+ *
+ * `draft` and `stored` are the text in the editor and the text the server last returned for the
+ * document; they are compared rather than trusted to differ, because cancelling an edit and
+ * starting a new one leaves the editor open with nothing changed.
+ */
+export function handbookSaveRefusal(error: unknown, draft: string, stored: string): string {
+ const reason = refusalText(error);
+ return draft === stored
+ ? S.company.handbook.saveRefused(reason)
+ : S.company.handbook.saveRefusedDraftKept(reason);
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 07fcdfe1..a2e9f7d3 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -5687,6 +5687,11 @@ export const en: Strings = {
documentDeleted: "Document deleted",
loadFailed: "Could not load the handbook",
documentLoadFailed: "Could not load the document",
+ /** Above the editor after a refused save: the server's reason, and that Save is the retry. */
+ saveRefused: (reason: string) => `Could not save: ${reason}`,
+ /** The same refusal while the editor holds text the file does not: nothing typed was lost. */
+ saveRefusedDraftKept: (reason: string) =>
+ `Could not save: ${reason} (what you edited is still in the editor, not in the file)`,
/** A row's tooltip: when the file was last written, and its size. */
updatedAt: (time: string, size: string): string => `Updated ${time} · ${size}`,
/** Beside the editor's buttons: what the text is, and the save shortcut (null while unbound). */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 8e4ff73b..a7810174 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -5732,6 +5732,10 @@ export const zh = {
documentDeleted: "文档已删除",
loadFailed: "手册加载失败",
documentLoadFailed: "文档加载失败",
+ /** Above the editor after a refused save: the server's reason, and that Save is the retry. */
+ saveRefused: (reason: string) => `保存失败:${reason}`,
+ /** The same refusal while the editor holds text the file does not: nothing typed was lost. */
+ saveRefusedDraftKept: (reason: string) => `保存失败:${reason}(编辑器里的改动没有写进文件)`,
/** A row's tooltip: when the file was last written, and its size. */
updatedAt: (time: string, size: string): string => `更新于 ${time} · ${size}`,
/** Beside the editor's buttons: what the text is, and the save shortcut (null while unbound). */
diff --git a/packages/web/test/handbook-save-refusal.test.ts b/packages/web/test/handbook-save-refusal.test.ts
new file mode 100644
index 00000000..8388f56b
--- /dev/null
+++ b/packages/web/test/handbook-save-refusal.test.ts
@@ -0,0 +1,57 @@
+/**
+ * The handbook editor's refusal line (src/features/company/handbook-save-refusal.ts): whose words
+ * the sentence uses, and when it also says the draft never left the editor.
+ *
+ * A refused save leaves the editor open with the draft in it, so this line is the only thing on
+ * screen that accounts for the failure once the six-second toast is gone. Two facts have to hold:
+ * the reason is the localized one (never the server's English), and the line says the typed text
+ * was not written only when the editor actually holds text the file does not.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { en as EN } from "../src/lib/strings-en";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { handbookSaveRefusal } from "../src/features/company/handbook-save-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("handbookSaveRefusal", () => {
+ it("reads a refused write through its code, so the line is the localized one", () => {
+ const line = handbookSaveRefusal(
+ new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"),
+ "draft",
+ "stored",
+ );
+ expect(line).toContain(S.errors.byCode["internal"] as string);
+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ });
+
+ it("keeps the message of an error the client itself raised", () => {
+ // `refusalText`'s rule: only an ApiError goes through the code table.
+ expect(handbookSaveRefusal(new Error("disk full"), "draft", "stored")).toContain("disk full");
+ expect(handbookSaveRefusal(undefined, "draft", "stored")).toContain(S.common.unknownError);
+ });
+
+ it("says the edits were not written while the editor holds text the file does not", () => {
+ const line = handbookSaveRefusal(new Error("disk full"), "edited", "stored");
+ expect(line).toBe(S.company.handbook.saveRefusedDraftKept("disk full"));
+ expect(line).toContain("编辑器里的改动没有写进文件");
+ });
+
+ it("leaves that half out when the draft is exactly what the file holds", () => {
+ // Save pressed on a document nobody edited: nothing was lost, so the line is just the reason.
+ const line = handbookSaveRefusal(new Error("disk full"), "same", "same");
+ expect(line).toBe(S.company.handbook.saveRefused("disk full"));
+ expect(line).not.toContain("编辑器里的改动");
+ });
+
+ it("speaks the interface language", () => {
+ setActiveStrings(EN);
+ expect(handbookSaveRefusal(new Error("disk full"), "edited", "stored")).toBe(
+ S.company.handbook.saveRefusedDraftKept("disk full"),
+ );
+ expect(S.company.handbook.saveRefusedDraftKept("disk full")).toContain("still in the editor");
+ });
+});