A local-first multi-agent app development platform, built on PenguinHarness
fix(web): a batch archive refused in part says which chats did not move
lmliheng364ea59846c7
diff --git a/changelog/unreleased/2026-11-13-batch-archive-refusal.md b/changelog/unreleased/2026-11-13-batch-archive-refusal.mdnew file mode 100644index 00000000..543a39d2--- /dev/null+++ b/changelog/unreleased/2026-11-13-batch-archive-refusal.md@@ -0,0 +1,65 @@+# A batch archive that was refused in part says which chats did not move++- **Date:** 2026-11-13+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文版](2026-11-13-batch-archive-refusal.zh.md)++The sidebar's batch bar has no bulk route: 批量归档 / 批量取消归档 send one PATCH per ticked+conversation, so a batch can land halfway. Their outcomes were read as a whole (`Promise.all`), and+a refusal was reported with a notification. Two things went wrong at once. The first refused row+threw away every other row's answer, so rows the server HAD archived stayed on screen exactly as+they were — the list disagreed with the server about conversations nobody could see were already+gone, and the 已归档 folder never appeared. And the reason lived in a toast that dismissed itself+after six seconds, above a list that looked untouched; every tick stayed on, including the rows+that had already moved.++Both actions now read their outcomes per row — through the new `lib/batch-outcome.ts`, the same+rule the batch delete already followed — so the rows that landed take the server's own copy and+move into the 已归档 folder, the refused ones stay ticked (they are exactly what a retry would act+on), and the bar keeps the count of what is still left plus the server's words:+`还有 1 个对话没有归档:<原因>`. The two buttons above it are the retry, which is why the sentence+belongs in the bar: nothing asked a question first, so there is no card to keep. A batch that went+through whole still just says so in a toast and drops every tick.++## Details++- `packages/web/src/lib/batch-outcome.ts` (new): `splitBatchOutcome(targets, results)` — what+ landed (the row plus whatever its request answered), what was refused, and the first refusal's+ reason (a host shows one reason; the rows say which of them did not go).+- `packages/web/src/components/layout/sidebar.tsx`: `batchSetArchived` runs `Promise.allSettled`+ and reads it through the splitter; the landed rows go through `replace(row.value.session)`, the+ refused ones become the selection; the `已归档` folder is opened only when the archiving of the+ open conversation actually landed. A new `batchArchiveRefusal` state is drawn by the bar+ (`role="alert"`, red ink, whole-row width) and cleared at the start of every attempt, when a tick+ changes, when the selection is cleared and when the mode is left — the sentence counts the ticks+ it was about. `confirmBatchDelete` now uses the same splitter (behaviour unchanged).+- `packages/web/src/lib/strings.ts` / `strings-en.ts`: `batchArchiveRefused` and+ `batchUnarchiveRefused`, in both dictionaries.++## Tests++- `packages/web/test/batch-outcome.test.ts` (new, 6 cases): each row gets its own answer, a refusal+ in the middle keeps the rows that landed after it, the first reason is the one kept, a batch+ refused whole leaves every row, a short result list invents nothing, and a result with no row is+ ignored.+- `packages/web/test/sidebar-batch-sessions.test.ts`: the two new dictionary strings, the bar's+ refusal slot, and that both actions read their outcomes through the one splitter (the delete's+ three assertions were updated for the shared helper).+- `packages/web/e2e/session-batch-archive-refusal.spec.mjs` (new, 2 cases, real server + the+ repository's mock model + a real browser): two ticked chats, one PATCH refused — the sentence is+ in the bar, nothing in the notification region, still there after seven seconds, the refused row+ still ticked while the landed one is archived for real and has moved into 已归档 — then the same+ button retries and the bar goes; and a batch refused whole keeps both ticks until 取消选择 takes+ the sentence with them.+- `packages/web/e2e/session-batch-delete-refusal.spec.mjs` (existing, unchanged) still passes —+ the delete path moved onto the shared splitter.+- Against the page as it was before the change (rebuilt from `HEAD`'s `sidebar.tsx`), both new+ cases fail on the missing refusal line.++## Compatibility++No API change, no new dependency, no stored format change. A batch that goes through behaves+exactly as before; what changed is a batch that does not — it can no longer look as if it did.diff --git a/changelog/unreleased/2026-11-13-batch-archive-refusal.zh.md b/changelog/unreleased/2026-11-13-batch-archive-refusal.zh.mdnew file mode 100644index 00000000..37781c4a--- /dev/null+++ b/changelog/unreleased/2026-11-13-batch-archive-refusal.zh.md@@ -0,0 +1,51 @@+# 批量归档只成功一半时,说清哪些对话没有动++- **日期:** 2026-11-13+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 否++[English](2026-11-13-batch-archive-refusal.md)++侧栏的批量栏没有批量接口:批量归档 / 批量取消归档给每条勾选的对话各发一个 PATCH,所以一批可以只成一半。+这两处的回话过去是整体读的(`Promise.all`),被拒时用一条通知汇报。于是两件事一起出错:第一个被拒的行把+其余每一行的回话都丢掉了,服务端**已经归档**的行照样原样留在列表里 —— 列表与服务器对这些人已经搬走的对话+说法不一,`已归档` 文件夹也根本没出现;而原因落在一条六秒后自己消失的通知里、飘在看起来没被碰过的列表之上,+所有勾选都还留着,包括已经搬走的那些。++现在两个动作都逐行读回话 —— 走新增的 `lib/batch-outcome.ts`,也就是批量删除早就在用的那条规则 ——+落地的行拿服务端自己的那一份、搬进 `已归档` 文件夹,被拒的行保持勾选(它们正是重试要作用的对象),+批量栏留着「还有几个没改」加上服务端自己的话:`还有 1 个对话没有归档:<原因>`。栏里那两颗按钮就是重试,+所以这句话归批量栏:这两颗按钮动手之前不问任何问题,因此没有卡片可以承接它。整批都成功时仍然只是一条+成功通知,勾选照旧清空。++## 细节++- `packages/web/src/lib/batch-outcome.ts`(新增):`splitBatchOutcome(targets, results)` —— 哪些落地了+ (行本身加上它那次请求的回话)、哪些被拒了、以及第一个被拒的原因(一个宿主只画一句话,哪些行没动由行自己说)。+- `packages/web/src/components/layout/sidebar.tsx`:`batchSetArchived` 改走 `Promise.allSettled` 并经那个+ 拆分函数读结果;落地的行交给 `replace(row.value.session)`,被拒的行成为新的勾选;`已归档` 文件夹只在+ 「正在看的那条对话真的归档了」时才展开。新增 `batchArchiveRefusal` 状态,由批量栏画出来(`role="alert"`、+ 危险色、占满一整行),在每次尝试开始时、勾选变化时、取消选择时、离开批量模式时清掉 —— 这句话数的是+ 它当时那些勾选。`confirmBatchDelete` 也改用同一个拆分函数(行为不变)。+- `packages/web/src/lib/strings.ts` / `strings-en.ts`:`batchArchiveRefused` / `batchUnarchiveRefused`,+ 中英各一对。++## 测试++- `packages/web/test/batch-outcome.test.ts`(新增,6 条):每一行对自己的回话;夹在中间的拒绝不影响它后面+ 落地的行;只保留第一个原因;整批被拒时每一行都还在;结果比行短时不凭空造出结果;没有对应行的结果被忽略。+- `packages/web/test/sidebar-batch-sessions.test.ts`:两条新文案、批量栏的拒绝槽,以及两个动作都走同一个+ 拆分函数(删除那边三条断言因共用而改写)。+- `packages/web/e2e/session-batch-archive-refusal.spec.mjs`(新增,2 条,真服务端 + 仓库自带 mock 模型 ++ 真浏览器):勾两条、其中一条的 PATCH 被拒 —— 那句话在批量栏里、通知区什么都没有、七秒后仍在、被拒的行+ 仍勾选而落地的那条真的归档并搬进「已归档」—— 随后同一个按钮重试、批量栏带着这句话一起消失;另一条是整批+ 被拒时两个勾选都留着,直到「取消选择」把那句话一并带走。+- `packages/web/e2e/session-batch-delete-refusal.spec.mjs`(既有、未改)仍然通过 —— 删除那条路改用了同一个+ 拆分函数。+- 拿改动前的页面(`HEAD` 的 `sidebar.tsx` 重新构建)跑同一份新用例,两条都死在找不到那行拒绝句。++## 兼容性++线上接口没变、没有新依赖、已存数据格式没变。整批成功的批次与以前一模一样;变的是没整批成功的那一种 ——+它再也不能看起来像成功过。diff --git a/packages/web/e2e/session-batch-archive-refusal.spec.mjs b/packages/web/e2e/session-batch-archive-refusal.spec.mjsnew file mode 100644index 00000000..55b58f98--- /dev/null+++ b/packages/web/e2e/session-batch-archive-refusal.spec.mjs@@ -0,0 +1,191 @@+/**+ * Regression: a batch archive is N writes, so it can land halfway — and the bar that sent it must+ * say which rows did not go instead of leaving a six-second toast behind.+ *+ * Before: `batchSetArchived` ran `Promise.all` and answered a refusal with `toastError`. The first+ * refused PATCH threw away every other row's outcome, so rows that HAD been archived stayed on+ * screen (the list disagreed with the server), every row stayed ticked, and the reason lived in a+ * toast over a list that looked untouched. Now the outcomes are collected per row+ * (`splitBatchOutcome`, the batch delete's own rule): the landed rows take the server's copy and+ * move into the archived folder, the refused ones stay ticked, and the bar keeps the count of what+ * is still left to change plus the server's words — so the retry is the same button, on exactly+ * the rows that did not go.+ *+ * Both tests run against the real server; only the PATCH is taken over, because a refusal has to+ * be produced and the rest of the contract (what moves, what stays, what is still ticked) is what+ * is measured.+ */+import { test, expect } from "@playwright/test";+import { login, ADMIN_ID, ADMIN_PASSWORD } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;++/** The archive call the page makes; a 500 with its own words proves the reason came back. */+const REFUSAL = { code: "session_store_read_only", message: "session store is read-only" };++/** Configure the mock model and create one titled conversation; returns its id. */+async function seedSession(page, projectId, title) {+ 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 created = await page.request.post(+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,+ { data: { provider: "custom", modelId: "claude-4-8" } },+ );+ expect(created.ok(), "create session").toBeTruthy();+ const sessionId = (await created.json()).session.sessionId;++ const renamed = await page.request.patch(`${BASE}/api/sessions/${sessionId}`, {+ data: { title },+ });+ expect(renamed.ok(), "rename session").toBeTruthy();+ return sessionId;+}++/**+ * Take over the PATCH per conversation id: `state.refuseFor` holds the ids that are refused and+ * every attempt is recorded; anything else falls through to the real server (so a retry archives+ * for real — and a landed row in the same batch is a real archive too).+ */+async function stubArchive(page, state) {+ await page.route("**/api/sessions/*", async (route) => {+ const req = route.request();+ if (req.method() !== "PATCH") return route.fallback();+ const id = new URL(req.url()).pathname.split("/").pop();+ state.patches.push(id);+ if (!state.refuseFor.has(id)) return route.fallback();+ return route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });+}++/** Tick the given conversations, then ask for the batch archive. */+async function askBatchArchive(page, titles) {+ const sidebar = page.getByRole("complementary");+ await sidebar.getByRole("button", { name: "批量处理" }).click();+ for (const title of titles) {+ const box = sidebar.getByRole("checkbox", { name: `选中「${title}」` });+ await expect(box).toBeVisible();+ await box.check();+ }+ await page.getByRole("button", { name: "批量归档", exact: true }).click();+}++test("a batch archive refused in part keeps the reason in the bar, over exactly the rows that did not go", async ({+ page,+}) => {+ 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 stamp = Date.now();+ const kept = `e2e archive kept ${stamp}`;+ const gone = `e2e archive gone ${stamp}`;+ const keptId = await seedSession(page, projectId, kept);+ const goneId = await seedSession(page, projectId, gone);+ const state = { patches: [], refuseFor: new Set([keptId]) };+ await stubArchive(page, state);++ await page.goto("/chat");+ const sidebar = page.getByRole("complementary");+ await expect(sidebar.locator("li", { hasText: gone }).first()).toBeVisible();+ await askBatchArchive(page, [kept, gone]);++ // The reason is inside the bar that sent the request, and nothing is reported through a toast.+ const refusal = page.getByTestId("batch-archive-refusal");+ await expect(refusal).toBeVisible();+ await expect(refusal).toHaveText("还有 1 个对话没有归档:session store is read-only");+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);+ expect(state.patches.sort()).toEqual([keptId, goneId].sort());++ // Seven seconds later the sentence is still there: nothing here dismisses itself.+ await page.waitForTimeout(7000);+ await expect(refusal).toBeVisible();++ // The half that landed is archived for real — its row has moved into the 已归档 folder — while+ // the refused row is still in the list and still ticked: the ticks now name exactly what a+ // retry would act on, and the archived row is not one of them.+ const archivedFolder = sidebar.getByRole("button", { name: /^已归档/ });+ await expect(archivedFolder).toBeVisible();+ if ((await archivedFolder.getAttribute("aria-expanded")) === "false")+ await archivedFolder.click();+ await expect(sidebar.locator("li", { hasText: gone })).toHaveCount(1);+ await expect(sidebar.getByRole("checkbox", { name: `选中「${gone}」` })).not.toBeChecked();+ await expect(sidebar.locator("li", { hasText: kept }).first()).toBeVisible();+ await expect(sidebar.getByRole("checkbox", { name: `选中「${kept}」` })).toBeChecked();+ const archived = await (await page.request.get(`${BASE}/api/sessions/${goneId}`)).json();+ expect(archived.session.archived).toBe(true);+ const refused = await (await page.request.get(`${BASE}/api/sessions/${keptId}`)).json();+ expect(refused.session.archived).toBe(false);++ // The same button retries: the row lands, so the ticks empty and the bar — with its reason —+ // goes with them.+ state.refuseFor.clear();+ await page.getByRole("button", { name: "批量归档", exact: true }).click();+ await expect(refusal).toHaveCount(0);+ await expect(sidebar.getByText(/已选 \d+ 条/)).toHaveCount(0);+ // Both rows are archived now, so the group holds nothing active and folds away by the sidebar's+ // own rule (its rows are only reachable through the 已归档 folder inside it). What a retry has to+ // prove is that it landed: the bar went with its reason, and the server has the row.+ const retried = await (await page.request.get(`${BASE}/api/sessions/${keptId}`)).json();+ expect(retried.session.archived).toBe(true);+ expect(+ (await (await page.request.get(`${BASE}/api/sessions/${goneId}`)).json()).session.archived,+ ).toBe(true);+ expect(state.patches.filter((id) => id === keptId)).toHaveLength(2);+ expect(state.patches.filter((id) => id === goneId)).toHaveLength(1);+});++test("a batch archive refused whole keeps every tick, and clearing the selection takes the reason with it", async ({+ page,+}) => {+ 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 stamp = Date.now();+ const first = `e2e archive refused 1 ${stamp}`;+ const second = `e2e archive refused 2 ${stamp}`;+ const firstId = await seedSession(page, projectId, first);+ const secondId = await seedSession(page, projectId, second);+ const state = { patches: [], refuseFor: new Set([firstId, secondId]) };+ await stubArchive(page, state);++ await page.goto("/chat");+ const sidebar = page.getByRole("complementary");+ await askBatchArchive(page, [first, second]);++ const refusal = page.getByTestId("batch-archive-refusal");+ await expect(refusal).toHaveText("还有 2 个对话没有归档:session store is read-only");+ expect(state.patches).toHaveLength(2);+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);++ // Nothing went: both rows and both ticks are still there.+ await expect(sidebar.locator("li", { hasText: first }).first()).toBeVisible();+ await expect(sidebar.locator("li", { hasText: second }).first()).toBeVisible();+ await expect(sidebar.getByRole("checkbox", { name: `选中「${first}」` })).toBeChecked();+ await expect(sidebar.getByRole("checkbox", { name: `选中「${second}」` })).toBeChecked();++ // 取消选择 drops the ticks — and the sentence that counted them.+ await page.getByRole("button", { name: "取消选择", exact: true }).click();+ await expect(refusal).toHaveCount(0);+ // Asking again on a fresh selection starts without the last attempt's reason.+ await sidebar.getByRole("checkbox", { name: `选中「${first}」` }).check();+ await expect(page.getByTestId("batch-archive-refusal")).toHaveCount(0);+});diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 6396a185..79d21f50 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -83,7 +83,6 @@ import {SkeletonList,UpdateDot,UserAvatar,- toastError,toastInfo,toastSuccess,} from "@adelie/ui";@@ -101,6 +100,8 @@ import {import type { SessionActivity } from "../../lib/session-activity";import { forgetSession, noteSessionSeen, useSessionSeen } from "../../lib/session-seen";import { apiErrorText } from "../../lib/api-error";+import { splitBatchOutcome } from "../../lib/batch-outcome";+import { toneInk } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";@@ -655,6 +656,12 @@ export function Sidebar({* ticked is exactly what did not go.*/const [batchDeleteRefusal, setBatchDeleteRefusal] = useState<string | null>(null);+ /**+ * Why the last batch archive / unarchive did not finish — the same rule, one host further out:+ * those two act straight from the bar (no card asks first), so the bar is what a refusal has to+ * be read from, under the buttons that sent it. The ticks it left behind are the retry.+ */+ const [batchArchiveRefusal, setBatchArchiveRefusal] = useState<string | null>(null);/** Parked draft conversation pending delete confirmation (null = none). */const [deletingDraft, setDeletingDraft] = useState<DraftSessionEntry | null>(null);/** Parked draft conversations of this user × Project, newest first (reactive module store). */@@ -1389,12 +1396,16 @@ export function Sidebar({if (batchMode) {setBatchMode(false);setBatchSelected(new Set());+ // The bar is gone with the mode, and so is any meaning its last refusal had.+ setBatchArchiveRefusal(null);return;}setBatchMode(true);};const toggleBatchRow = (sessionId: string) => {+ // The bar's refusal counts the rows it refused; ticks that no longer match it make it untrue.+ setBatchArchiveRefusal(null);setBatchSelected((prev) => {const next = new Set(prev);if (next.has(sessionId)) next.delete(sessionId);@@ -1411,30 +1422,46 @@ export function Sidebar({* menu runs — the server has no bulk route, and a batch that fails halfway must not hide which* rows landed. Archiving the conversation on screen opens the archived folder, or its row would* vanish from the list with no way back (the row menu's toggle does the same).+ *+ * The outcomes are read per row (`splitBatchOutcome`, the same rule the batch delete follows):+ * the rows that landed take the server's own copy, the refused ones stay ticked — they are the+ * rows still there — and the bar keeps the count of what is left plus the server's words. That+ * bar is the retry, so this reason cannot live in a toast over it.*/- const batchSetArchived = async (archived: boolean) => {+ const batchSetArchived = async (archived: boolean): Promise<void> => {const targets = batchTargets();if (targets.length === 0) return;setBatchBusy(true);+ // Another attempt answers the previous one, whatever it says.+ setBatchArchiveRefusal(null);try {- const results = await Promise.all(+ const results = await Promise.allSettled(targets.map((s) => api.patchSession(s.sessionId, { archived })),);- for (const res of results) replace(res.session);- const openOne = targets.find((s) => s.sessionId === activeSessionId);+ const { landed, refused, firstReason } = splitBatchOutcome(targets, results);+ // The rows that landed now hold the server's version of themselves (including the archived+ // flag that moves them into the folder) — the refused ones are left exactly as they were.+ for (const row of landed) replace(row.value.session);+ setBatchSelected(new Set(refused.map((s) => s.sessionId)));+ const openOne = landed.find((row) => row.target.sessionId === activeSessionId);if (archived && openOne !== undefined) {setOpenFolders((prev) =>- new Set(prev).add(folderKey(sessionGroupKey(openOne), "archived")),+ new Set(prev).add(folderKey(sessionGroupKey(openOne.target), "archived")),+ );+ }+ if (refused.length === 0) {+ toastSuccess(+ archived+ ? S.chat.batchArchiveDone(landed.length)+ : S.chat.batchUnarchiveDone(landed.length),);+ return;}- toastSuccess(+ setBatchArchiveRefusal(archived- ? S.chat.batchArchiveDone(targets.length)- : S.chat.batchUnarchiveDone(targets.length),+ ? S.chat.batchArchiveRefused(refused.length, apiErrorText(firstReason))+ : S.chat.batchUnarchiveRefused(refused.length, apiErrorText(firstReason)),);- setBatchSelected(new Set());- } catch (e) {- toastError(apiErrorText(e));} finally {setBatchBusy(false);}@@ -1458,22 +1485,11 @@ export function Sidebar({setBatchDeleteRefusal(null);try {const results = await Promise.allSettled(targets.map((s) => api.deleteSession(s.sessionId)));- const landed: SessionInfo[] = [];- const refused: SessionInfo[] = [];// The card shows ONE reason under its sentence, so the first refusal's words are the ones// kept — the rows themselves say which of them is still there to retry.- let firstReason: unknown;- results.forEach((result, i) => {- const target = targets[i];- if (target === undefined) return;- if (result.status === "fulfilled") {- landed.push(target);- return;- }- if (refused.length === 0) firstReason = result.reason;- refused.push(target);- });- forgetDeletedSessions(landed);+ const { landed, refused, firstReason } = splitBatchOutcome(targets, results);+ const landedRows = landed.map((row) => row.target);+ forgetDeletedSessions(landedRows);setBatchSelected(new Set(refused.map((s) => s.sessionId)));if (refused.length === 0) {setBatchConfirmDelete(false);@@ -1482,9 +1498,9 @@ export function Sidebar({}// Only a conversation that actually went away is left for: when the open one was one of the// refused rows it is still on screen, so there is nowhere to go.- const openOne = landed.find((s) => s.sessionId === activeSessionId);+ const openOne = landedRows.find((s) => s.sessionId === activeSessionId);if (openOne !== undefined) {- const deleted = new Set(landed.map((s) => s.sessionId));+ const deleted = new Set(landedRows.map((s) => s.sessionId));const rest = (byAgent.get(openOne.agentId) ?? []).filter((s) => !deleted.has(s.sessionId) && sessionCategory(s) === "active",);@@ -1496,7 +1512,10 @@ export function Sidebar({};/** Clear the ticks, staying in the mode (the bar's own control — leaving is the header's toggle). */- const clearBatchSelection = () => setBatchSelected(new Set());+ const clearBatchSelection = () => {+ setBatchArchiveRefusal(null);+ setBatchSelected(new Set());+ };/*** New chat: enters draft state (/chat/new) without creating a Session — Model / Workspace /@@ -2751,7 +2770,8 @@ export function Sidebar({loses no row to a control that has nothing to act on — the same rule the requirementbox's batch bar follows. Every action goes through the route the row's own menualready uses (one PATCH or DELETE per conversation), and the delete keeps its- confirmation, now asked once for the whole selection. */}+ confirmation, now asked once for the whole selection. A refused archive / unarchive+ answers in the bar itself: it acts without asking, so there is no card to keep. */}{batchMode && batchSelected.size > 0 && (<div className="mt-2 flex flex-wrap items-center gap-1 rounded-md border border-line-emphasis px-2 py-1.5"><span className="mr-auto px-0.5 text-xs text-fg-muted">@@ -2788,6 +2808,20 @@ export function Sidebar({<Button size="xs" variant="link" disabled={batchBusy} onClick={clearBatchSelection}>{S.chat.batchClear}</Button>+ {/* An archive / unarchive the server refused: nothing else on screen moved, the refused+ rows are still ticked right below, and the two buttons above are the retry — so the+ reason stays in the bar that sent it (the delete's own card is not involved). */}+ {batchArchiveRefusal !== null && (+ <p+ role="alert"+ data-testid="batch-archive-refusal"+ data-tooltip={batchArchiveRefusal}+ data-tooltip-content="text"+ className={`w-full line-clamp-2 break-words px-0.5 text-xs ${toneInk.danger}`}+ >+ {batchArchiveRefusal}+ </p>+ )}</div>)}diff --git a/packages/web/src/lib/batch-outcome.ts b/packages/web/src/lib/batch-outcome.tsnew file mode 100644index 00000000..c1b8eae8--- /dev/null+++ b/packages/web/src/lib/batch-outcome.ts@@ -0,0 +1,55 @@+/**+ * What a batch action on the conversation list came back with.+ *+ * A batch is N writes, not one: the server has no bulk route, so the batch bar sends one request+ * per ticked conversation and each of them can answer on its own. Reading the outcomes as a whole+ * (`Promise.all`) would therefore drop the rows that DID land behind the first one that did not —+ * the list would then disagree with the server about rows nobody touched — and the refusal would+ * have nowhere to say which rows are still there to retry.+ *+ * So they are read per row (`Promise.allSettled`), here, once: what landed, what was refused, and+ * the first refusal's words (the host shows ONE reason; the rows themselves say which of them did+ * not go).+ */+import type { SessionInfo } from "@adelie/server/api";++/** A row that landed, with whatever its request answered (the archive's PATCH carries the row back). */+export interface BatchLanded<T> {+ target: SessionInfo;+ value: T;+}++export interface BatchOutcome<T> {+ landed: BatchLanded<T>[];+ /** Exactly the rows a retry would still act on, in the order they were ticked. */+ refused: SessionInfo[];+ /** The first refusal's reason, as the request threw it; `undefined` when nothing was refused. */+ firstReason: unknown;+}++/**+ * Splits settled per-row results against the rows they were sent for.+ *+ * `targets[i]` is `results[i]`'s row: both lists come from the same `targets.map(...)`, so a result+ * without its row (or the reverse) is not something to guess about — that pair is skipped rather+ * than counted as either outcome.+ */+export function splitBatchOutcome<T>(+ targets: readonly SessionInfo[],+ results: readonly PromiseSettledResult<T>[],+): BatchOutcome<T> {+ const landed: BatchLanded<T>[] = [];+ const refused: SessionInfo[] = [];+ let firstReason: unknown;+ results.forEach((result, i) => {+ const target = targets[i];+ if (target === undefined) return;+ if (result.status === "fulfilled") {+ landed.push({ target, value: result.value });+ return;+ }+ if (refused.length === 0) firstReason = result.reason;+ refused.push(target);+ });+ return { landed, refused, firstReason };+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e07d05d2..d9756a26 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4027,6 +4027,15 @@ export const en: Strings = {batchClear: "Clear selection",batchArchiveDone: (n: number) => `Archived ${n} chats`,batchUnarchiveDone: (n: number) => `Unarchived ${n} chats`,+ /**+ * A batch archive / unarchive the server refused (wholly or in part): how many of the ticked+ * chats did not change, then the server's words. Neither action asks first, so this sentence+ * stays in the bar that holds their buttons — the ticks left behind are what a retry acts on.+ */+ batchArchiveRefused: (n: number, reason: string) =>+ `${n} of the selected chats were not archived: ${reason}`,+ batchUnarchiveRefused: (n: number, reason: string) =>+ `${n} of the selected chats were not unarchived: ${reason}`,batchDeleteTitle: "Delete selected chats",batchDeleteConfirm: (n: number) =>`Delete the ${n} selected chats? Their messages and Trace will be removed permanently.`,diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 40f625e5..07162994 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4119,6 +4119,12 @@ export const zh = {batchClear: "取消选择",batchArchiveDone: (n: number) => `已归档 ${n} 个对话`,batchUnarchiveDone: (n: number) => `已取消归档 ${n} 个对话`,+ /**+ * 批量归档 / 批量取消归档被拒(全部或一部分):几个没改成,然后是服务端自己说的话。归档与取消归档没有+ * 确认卡片,因此这句话留在它们的按钮所在的那条栏目里 —— 留下来的勾选就是重试的对象。+ */+ batchArchiveRefused: (n: number, reason: string) => `还有 ${n} 个对话没有归档:${reason}`,+ batchUnarchiveRefused: (n: number, reason: string) => `还有 ${n} 个对话没有取消归档:${reason}`,batchDeleteTitle: "删除选中的对话",batchDeleteConfirm: (n: number) =>`确定删除选中的 ${n} 个对话?其消息与 Trace 将被移除,且不可恢复。`,diff --git a/packages/web/test/batch-outcome.test.ts b/packages/web/test/batch-outcome.test.tsnew file mode 100644index 00000000..c5b5e624--- /dev/null+++ b/packages/web/test/batch-outcome.test.ts@@ -0,0 +1,82 @@+/**+ * `lib/batch-outcome.ts` — how a batch action's per-row outcomes are read.+ *+ * The batch bar has no bulk route: it sends one request per ticked conversation, so a batch can+ * land halfway. Reading those as a whole (`Promise.all`) would drop the rows that did land behind+ * the first one that did not, and the list would then disagree with the server about rows nobody+ * touched. The splitter is what both the archive and the delete read their outcome through, so it+ * is pinned here: which rows landed (with what their request answered), which did not, and the one+ * reason a host has room for.+ */+import { describe, expect, it } from "vitest";+import { splitBatchOutcome } from "../src/lib/batch-outcome";+import type { SessionInfo } from "@adelie/server/api";++/** A row of the sidebar list, as far as a batch is concerned: only the id is read. */+const row = (sessionId: string): SessionInfo => ({ sessionId }) as SessionInfo;++const targets = [row("a"), row("b"), row("c")];++describe("splitBatchOutcome", () => {+ it("gives each row the answer its own request produced", () => {+ const outcome = splitBatchOutcome(targets, [+ { status: "fulfilled", value: "A" },+ { status: "fulfilled", value: "B" },+ { status: "fulfilled", value: "C" },+ ]);+ expect(outcome.landed.map((entry) => entry.target.sessionId)).toEqual(["a", "b", "c"]);+ expect(outcome.landed.map((entry) => entry.value)).toEqual(["A", "B", "C"]);+ expect(outcome.refused).toEqual([]);+ expect(outcome.firstReason).toBeUndefined();+ });++ it("keeps the landed rows of a batch a refusal cut in half", () => {+ const refusedReason = new Error("session store is read-only");+ const outcome = splitBatchOutcome(targets, [+ { status: "fulfilled", value: "A" },+ { status: "rejected", reason: refusedReason },+ { status: "fulfilled", value: "C" },+ ]);+ // The one that landed AFTER the refusal is still a landed row: its write already happened.+ expect(outcome.landed.map((entry) => entry.target.sessionId)).toEqual(["a", "c"]);+ expect(outcome.refused.map((entry) => entry.sessionId)).toEqual(["b"]);+ expect(outcome.firstReason).toBe(refusedReason);+ });++ it("keeps the FIRST refusal's reason — the one reason a host has room for", () => {+ const first = new Error("first");+ const outcome = splitBatchOutcome(targets, [+ { status: "rejected", reason: first },+ { status: "rejected", reason: new Error("second") },+ { status: "rejected", reason: new Error("third") },+ ]);+ expect(outcome.landed).toEqual([]);+ expect(outcome.refused.map((entry) => entry.sessionId)).toEqual(["a", "b", "c"]);+ expect(outcome.firstReason).toBe(first);+ });++ it("treats a batch refused whole as every row still there", () => {+ const outcome = splitBatchOutcome([row("only")], [{ status: "rejected", reason: "nope" }]);+ expect(outcome.refused.map((entry) => entry.sessionId)).toEqual(["only"]);+ expect(outcome.firstReason).toBe("nope");+ });++ it("counts a short result list as only what it answers for (no invented outcome)", () => {+ const outcome = splitBatchOutcome(targets, [{ status: "fulfilled", value: "A" }]);+ expect(outcome.landed.map((entry) => entry.target.sessionId)).toEqual(["a"]);+ expect(outcome.refused).toEqual([]);+ expect(outcome.firstReason).toBeUndefined();+ });++ it("does nothing with a result that has no row to belong to", () => {+ const outcome = splitBatchOutcome(targets, [+ { status: "fulfilled", value: "A" },+ { status: "fulfilled", value: "B" },+ { status: "fulfilled", value: "C" },+ { status: "rejected", reason: new Error("stray") },+ ]);+ expect(outcome.landed).toHaveLength(3);+ expect(outcome.refused).toEqual([]);+ expect(outcome.firstReason).toBeUndefined();+ });+});diff --git a/packages/web/test/sidebar-batch-sessions.test.ts b/packages/web/test/sidebar-batch-sessions.test.tsindex 4aafcbb5..f301d002 100644--- a/packages/web/test/sidebar-batch-sessions.test.ts+++ b/packages/web/test/sidebar-batch-sessions.test.ts@@ -69,6 +69,21 @@ describe("the batch bar's words", () => {);});+ it("says how many of a refused archive did not change, in both dictionaries", () => {+ expect(zh.chat.batchArchiveRefused(2, "session store is read-only")).toBe(+ "还有 2 个对话没有归档:session store is read-only",+ );+ expect(zh.chat.batchUnarchiveRefused(1, "session store is read-only")).toBe(+ "还有 1 个对话没有取消归档:session store is read-only",+ );+ expect(en.chat.batchArchiveRefused(1, "session store is read-only")).toBe(+ "1 of the selected chats were not archived: session store is read-only",+ );+ expect(en.chat.batchUnarchiveRefused(2, "session store is read-only")).toBe(+ "2 of the selected chats were not unarchived: session store is read-only",+ );+ });+it("names each row's box after the conversation it stands for", () => {expect(zh.chat.batchSelectRow("修构建")).toBe("选中「修构建」");expect(en.chat.batchSelectRow("Fix the build")).toBe('Select "Fix the build"');@@ -119,7 +134,10 @@ describe("the batch wiring", () => {// A batch is N writes, so its outcomes are read per row — `all` would drop the rows that did// land, and only the landed ones may be forgotten.expect(SIDEBAR).toContain("await Promise.allSettled(");- expect(SIDEBAR).toContain("forgetDeletedSessions(landed);");+ expect(SIDEBAR).toContain("forgetDeletedSessions(landedRows);");+ // Both actions read their outcomes through the one splitter, so neither can drift from the+ // rule that a batch is N writes (lib/batch-outcome.ts).+ expect(SIDEBAR.match(/splitBatchOutcome\(targets, results\)/g)).toHaveLength(2);});it("keeps the delete's confirmation, asked once for the whole selection", () => {@@ -135,14 +153,44 @@ describe("the batch wiring", () => {);});- it("drops the ticks when the mode is left, and clears them after an action lands", () => {+ it("drops the ticks when the mode is left, and leaves only the rows that did not go", () => {expect(TOGGLE).toContain("setBatchMode(false)");expect(TOGGLE).toContain("setBatchSelected(new Set())");- expect(SIDEBAR).toContain("const clearBatchSelection = () => setBatchSelected(new Set());");- // Archived rows are no longer the ones the reader picked, and a delete clears a fully landed- // batch — but a refused one keeps exactly the rows that did not go ticked for the retry.- expect(SIDEBAR.match(/setBatchSelected\(new Set\(\)\)/g)?.length).toBeGreaterThanOrEqual(3);- expect(SIDEBAR).toContain("setBatchSelected(new Set(refused.map((s) => s.sessionId)));");+ // Neither action clears the selection outright: both keep exactly the refused rows ticked, so+ // a fully landed batch clears them by itself and a partial one leaves the retry's rows.+ expect(+ SIDEBAR.match(/setBatchSelected\(new Set\(refused\.map\(\(s\) => s\.sessionId\)\)\);/g),+ ).toHaveLength(2);+ // "取消选择" is the explicit way out, and it takes the bar's last refusal with it.+ const clear = SIDEBAR.slice(+ SIDEBAR.indexOf("const clearBatchSelection = () => {"),+ SIDEBAR.indexOf("/**", SIDEBAR.indexOf("const clearBatchSelection = () => {")),+ );+ expect(clear).toContain("setBatchArchiveRefusal(null);");+ expect(clear).toContain("setBatchSelected(new Set());");+ });++ it("keeps a refused archive in the bar, over exactly the rows a retry would act on", () => {+ const bar = SIDEBAR.slice(+ SIDEBAR.indexOf("{batchMode && batchSelected.size > 0 && ("),+ SIDEBAR.indexOf("unsent new chats, newest first"),+ );+ // No card asks before an archive, so the bar that holds its two buttons is where its refusal+ // has to be read — not a toast above a list that looks untouched.+ expect(bar).toContain("batchArchiveRefusal !== null");+ expect(bar).toContain('data-testid="batch-archive-refusal"');+ expect(bar).toContain("{batchArchiveRefusal}");+ expect(SIDEBAR).toContain(+ "S.chat.batchArchiveRefused(refused.length, apiErrorText(firstReason))",+ );+ expect(SIDEBAR).toContain(+ "S.chat.batchUnarchiveRefused(refused.length, apiErrorText(firstReason))",+ );+ // Rows that landed take the server's own copy (the archived flag that moves them into the+ // folder); the refused ones stay ticked, and a fully landed batch still just says so.+ expect(SIDEBAR).toContain("for (const row of landed) replace(row.value.session);");+ expect(SIDEBAR).toContain("if (refused.length === 0) {");+ expect(SIDEBAR).toContain("S.chat.batchArchiveDone(landed.length)");});it("stops reordering rows while they are being picked", () => {