A local-first multi-agent app development platform, built on PenguinHarness
fix(core,server,web): compact a Session resumed after restart, and localize the 409 reasons (#342)
Yaowei Zheng7e0e0ef06c76
diff --git a/changelog/unreleased/2026-08-19-compact-after-restart.md b/changelog/unreleased/2026-08-19-compact-after-restart.mdnew file mode 100644index 00000000..3baee97f--- /dev/null+++ b/changelog/unreleased/2026-08-19-compact-after-restart.md@@ -0,0 +1,24 @@+# Compaction after a client restart, and localized reasons when it refuses++- **Date:** 2026-08-19+- **Type:** fix+- **Scope:** `core`, `server`, `web`, `docs`+- **PR:** [#342](https://github.com/Prism-Shadow/penguin-harness/pull/342)+- **Breaking:** yes — two of the three `POST /compact` refusals moved off the shared `nothing_to_compact` error code onto `compaction_not_configured` and `already_compacted`.++[中文版](2026-08-19-compact-after-restart.zh.md)++Asking a Session to compact right after restarting the client was refused with "The current context has nothing to compact (no completed conversation turns yet)", however long the conversation actually was. `Session.compactability()` delegated to the `ContextEngine`, which the first run's bootstrap builds — so between a process restart and the next Task there was no engine to ask, and the delegation fell back to a literal "empty". Availability is now answered from the state the Trace replay recovered, and the three reasons a compaction can be refused reach the UI in the reader's language instead of as English prose.++## Details++- `Session.compactability()` reads the replayed `sessionTurns` when no engine has been built yet, so a resumed conversation is compactable without running a Task first. A Session created in this process still reports `empty`, and one whose only request was interrupted still reports `empty` — those are the cases the reason exists for.+- `Session.compact()` builds the engine when compaction is available, letting the bootstrap seed the resumed history into the LLM, instead of returning an empty stream and leaving the caller waiting for a compaction banner that never arrived. A Session that has never run stays a strict no-op that writes no Trace records, so an untouched session does not become resumable by being compacted.+- The availability rule moved into an exported `compactAvailability` in `context-engine.ts`, shared by the engine and by a resumed Session, so the two answers cannot drift apart.+- Resume restores `fromCompaction` from the Trace's closing compaction (`EngineInitialState.fromCompaction`, derived from `contextClosed`). A restart immediately after compacting reports "just compacted" rather than telling the user they have not spoken yet — both states have zero turns and are not the same message.+- `POST /compact` gives each refusal its own error code instead of sharing one: `compaction_not_configured`, `nothing_to_compact` (no completed turn yet), and `already_compacted`. Clients localize by code, so a single shared code forced a choice between one vague sentence for three situations and untranslated English in a non-English UI.+- The Web's error-code table gained those three reasons plus the codes an ordinary session meets and had no translation for — stale-resource races (`session_not_found`, `approval_not_found`, `process_not_found`, `process_running`, `trace_not_found`, `memory_file_not_found`, `memory_scope_not_found`), Project membership and deletion refusals (`already_member`, `already_owner`, `project_not_found`, `cannot_delete_last_project`), shutdown and deletion races (`shutting_down`, `agent_deleting`, `session_deleting`), plus `workspace_not_found`, `skill_too_large` and the `internal` catch-all — in both locales.++## Compatibility++Two of the three `/compact` refusals changed error code: a 409 that used to arrive as `nothing_to_compact` now arrives as `compaction_not_configured` or `already_compacted` when that is the reason. `nothing_to_compact` keeps its meaning — no completed conversation turn yet — and its HTTP status is unchanged, as is the shape of the error body. A client that only rendered `error.message` needs no change.diff --git a/changelog/unreleased/2026-08-19-compact-after-restart.zh.md b/changelog/unreleased/2026-08-19-compact-after-restart.zh.mdnew file mode 100644index 00000000..9cc1d6d8--- /dev/null+++ b/changelog/unreleased/2026-08-19-compact-after-restart.zh.md@@ -0,0 +1,24 @@+# 重启客户端后的压缩,以及压缩被拒时的本地化原因++- **Date:** 2026-08-19+- **Type:** fix+- **Scope:** `core`, `server`, `web`, `docs`+- **PR:** [#342](https://github.com/Prism-Shadow/penguin-harness/pull/342)+- **Breaking:** yes — `POST /compact` 三种拒绝原因中的两种从共用的 `nothing_to_compact` 错误码移到了 `compaction_not_configured` 与 `already_compacted`。++[English](2026-08-19-compact-after-restart.md)++重启客户端后立刻请求压缩,无论对话实际有多长,都会被拒绝并提示「The current context has nothing to compact (no completed conversation turns yet)」。`Session.compactability()` 把问题转交给 `ContextEngine`,而这个引擎是由第一次 run 的 bootstrap 才创建的——于是在进程重启到下一个 Task 之间根本没有引擎可问,转交便退回到字面上的 "empty"。现在可压缩性依据 Trace 回放恢复出的状态来回答,压缩被拒的三种原因也以读者的语言抵达界面,而不再是一句英文散文。++## 细节++- 在引擎尚未创建时,`Session.compactability()` 读取回放得到的 `sessionTurns`,因此恢复出来的对话无需先跑一个 Task 就可以压缩。在本进程内新建的 Session 仍然报告 `empty`,唯一一次请求就被中断的 Session 也仍然报告 `empty`——这两种情况正是这个原因存在的意义。+- 当压缩确实可用时,`Session.compact()` 会创建引擎,让 bootstrap 把恢复出的历史注入 LLM,而不是返回一个空的流、把调用方晾在那里等一个永远不会出现的压缩横幅。从未运行过的 Session 依然是严格的空操作,不写入任何 Trace 记录,因此一个没被碰过的会话不会因为被压缩而变得可恢复。+- 可压缩性规则被提取为 `context-engine.ts` 中导出的 `compactAvailability`,由引擎和恢复出的 Session 共用,两处答案不会各自漂移。+- 恢复流程会从 Trace 收尾的那次压缩还原 `fromCompaction`(`EngineInitialState.fromCompaction`,源自 `contextClosed`)。刚压缩完就重启,得到的回答是「刚刚压缩过」,而不是告诉用户还没说过话——两种状态的轮次都是零,但它们不是同一句话。+- `POST /compact` 让每一种拒绝各自拥有错误码,而不再共用一个:`compaction_not_configured`、`nothing_to_compact`(尚未完成一轮对话)与 `already_compacted`。客户端按错误码做本地化,共用一个码就只剩两个选择:用一句含糊的话覆盖三种处境,或者让英文原文出现在非英文界面里。+- Web 的错误码表补齐了这三种原因,以及普通会话会真实遇到、却一直没有译文的那些码——资源失效的竞态(`session_not_found`、`approval_not_found`、`process_not_found`、`process_running`、`trace_not_found`、`memory_file_not_found`、`memory_scope_not_found`)、Project 成员与删除的拒绝(`already_member`、`already_owner`、`project_not_found`、`cannot_delete_last_project`)、关停与删除的竞态(`shutting_down`、`agent_deleting`、`session_deleting`),以及 `workspace_not_found`、`skill_too_large` 和兜底的 `internal`——两种语言都补上了。++## 兼容性++`/compact` 三种拒绝中的两种换了错误码:原本以 `nothing_to_compact` 抵达的 409,在原因对应时现在会以 `compaction_not_configured` 或 `already_compacted` 抵达。`nothing_to_compact` 的含义不变——尚未完成一轮对话——HTTP 状态码不变,错误体的结构也不变。只渲染 `error.message` 的客户端无需改动。diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 3e0d361a..aa5eb165 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -557,6 +557,10 @@ export class Agent {sessionTokens: resumed.sessionTokens,lastRequestTotal: resumed.lastRequestTotal,pendingTraceRotation: resumed.contextClosed,+ // A closed context is one a completed compaction opened: the same fact drives the+ // deferred Trace rotation above and the "just compacted" compaction reason, but they+ // are separate meanings and stay separate fields.+ fromCompaction: resumed.contextClosed,},resumedHistory: resumed.renderMessages,});diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex 8d2e64f4..726a1829 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -150,6 +150,13 @@ export interface EngineInitialState {pendingSummary?: OmniMessage;/** Carried-over Session cumulative turn count. */sessionTurns?: number;+ /**+ * The resumed context was opened by a **completed** compaction (the Trace's last record is a+ * completed `compaction_end`), so it is legitimately empty. Restores `fromCompaction`, which+ * is what keeps `compactability()` answering "just compacted" rather than "nothing said yet"+ * after a restart — both have zero turns and are not the same message to a user.+ */+ fromCompaction?: boolean;/** Carried-over Session cumulative token counts (handed to the new object when compaction swaps it in). */sessionTokens?: TokenCounts;/** Most recent token_usage's request.total (the context usage figure, keeps compaction threshold checks continuous). */@@ -245,6 +252,32 @@ const carriesSteering = (m: OmniMessage): boolean => {/** Whether compaction is possible; when not `ok`, `compact()` is a no-op and yields no messages (see ContextEngine.compactability). */export type CompactAvailability = "ok" | "unsupported" | "empty" | "just_compacted";+/** The context facts the availability rule reads (see `compactAvailability`). */+export interface CompactabilityState {+ /** Whether the compaction capability is configured at all (settings + the new-context LLM factory). */+ configured: boolean;+ /** Completed turns in the **current** context (reset by compaction, restored from Trace on resume). */+ sessionTurns: number;+ /** Whether the current context was opened by a completed compaction rather than by the user. */+ fromCompaction: boolean;+}++/**+ * The compaction-availability rule, stated once.+ *+ * Two callers answer the same question from different vantage points and must not drift apart:+ * a live `ContextEngine` reads its own counters, while a `Session` resumed after a process+ * restart has no engine yet (it is built by the first run's bootstrap) and answers from the+ * state its Trace replay recovered. Duplicating the rule is how "restart the client and it+ * claims there is nothing to compact" happens.+ */+export function compactAvailability(state: CompactabilityState): CompactAvailability {+ if (!state.configured) return "unsupported";+ if (state.sessionTurns > 0) return "ok";+ // Both remaining cases have zero turns and mean completely different things to the user.+ return state.fromCompaction ? "just_compacted" : "empty";+}+/*** Corrective note prepended to the re-sent compaction Prompt after a committed-but-unusable* response (empty summary, or tool calls — issues #83/#170). The unusable@@ -448,6 +481,7 @@ export class ContextEngine {this.pendingCarryOver = init.carryOver ?? [];this.pendingSummary = init.pendingSummary ?? null;this.sessionTurns = init.sessionTurns ?? 0;+ this.fromCompaction = init.fromCompaction ?? false;this.lastSessionTokens = init.sessionTokens ?? emptyTokenCounts();this.lastRequestTotal = init.lastRequestTotal ?? 0;this.pendingTraceRotation = init.pendingTraceRotation ?? false;@@ -850,11 +884,16 @@ export class ContextEngine {* - `just_compacted`: no new conversation since the last compaction. Both cases have* `sessionTurns` === 0, but they mean two completely different things to the user and must* not be conflated.+ *+ * The rule itself lives in `compactAvailability` so that a Session resumed after a restart —+ * which has no engine yet — answers identically from its replayed state.*/compactability(): CompactAvailability {- if (!this.deps.compaction || !this.deps.createLLM) return "unsupported";- if (this.sessionTurns > 0) return "ok";- return this.fromCompaction ? "just_compacted" : "empty";+ return compactAvailability({+ configured: Boolean(this.deps.compaction && this.deps.createLLM),+ sessionTurns: this.sessionTurns,+ fromCompaction: this.fromCompaction,+ });}async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {diff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex 27370918..0bbba59a 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -42,7 +42,7 @@ import type {} from "./interfaces.js";import { generateTitleWithLLM } from "./internal/session-title.js";import type { SessionTitleResult } from "./internal/session-title.js";-import { ContextEngine } from "./engine/context-engine.js";+import { compactAvailability, ContextEngine } from "./engine/context-engine.js";import type {CompactAvailability,CompactionSettings,@@ -584,11 +584,28 @@ export class Session {* Docs: /docs/agent-loop § "Compaction".*/async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {- // Before the first run there is no context to compact: stay a strict no-op, without- // bootstrapping — a session that never ran must not leave trace records (meta /- // tool_list_ready) behind, or an untouched session would look resumable.- if (!this.engine) return;- yield* this.engine.compact(opts);+ if (!this.engine) {+ // Nothing compactable and no engine: stay a strict no-op, without bootstrapping — a+ // session that never ran must not leave trace records (meta / tool_list_ready) behind,+ // or an untouched session would look resumable.+ if (this.compactability() !== "ok") return;+ // A Session resumed after a restart is the opposite case: its history is real and+ // already on disk, and the engine simply has not been built yet (that happens on the+ // first run). Build it here — the bootstrap injects the replayed history into the LLM,+ // so the compaction request folds the actual conversation — rather than silently doing+ // nothing and leaving the user waiting for a banner that never arrives.+ const ready = yield* this.ensureReady(opts?.signal);+ if (!ready) {+ // Aborted mid-bootstrap: no engine exists to write the records, so the Session writes+ // them itself (as runTask does), keeping the interruption visible in the Trace.+ for (const m of this.abortedBootstrapRecords) {+ await this.writeTrace(m, "aborted bootstrap record");+ }+ this.abortedBootstrapRecords = [];+ return;+ }+ }+ yield* this.engine!.compact(opts);}/**@@ -597,8 +614,18 @@ export class Session {* give feedback based on this rather than triggering a silent, fruitless compaction.*/compactability(): CompactAvailability {- // Before the first run's bootstrap there is no context at all — "empty" is the accurate answer.- return this.engine?.compactability() ?? "empty";+ if (this.engine) return this.engine.compactability();+ // No engine yet: it is built by the first run's bootstrap (ensureReady). For a Session+ // created in this process that genuinely means an empty context, but a Session **resumed**+ // after a process restart already carries what the Trace replay recovered — answer from+ // that, or a user who just restarted the client is told their whole conversation has+ // nothing to compact (the server renders this reason as a 409 `nothing_to_compact`).+ const init = this.engineDeps.initialState;+ return compactAvailability({+ configured: Boolean(this.engineDeps.compaction && this.engineDeps.createLLM),+ sessionTurns: init?.sessionTurns ?? 0,+ fromCompaction: init?.fromCompaction ?? false,+ });}/** Writes `session_meta` to the Trace before the first run/compaction; best-effort — failure doesn't interrupt the run. */diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.tsindex c79f41c2..1ae66e43 100644--- a/packages/core/test/compaction.test.ts+++ b/packages/core/test/compaction.test.ts@@ -55,6 +55,7 @@ import type {LLMOutcome,} from "../src/interfaces.js";import { ContextEngine, SUMMARY_RETRY_GUIDANCE } from "../src/engine/context-engine.js";+import { Session } from "../src/session.js";import type { CompactionSettings } from "../src/engine/context-engine.js";import { GenerativeModel } from "../src/llm/index.js";import type { UniConfig, UniEvent, UniMessage } from "@prismshadow/agenthub";@@ -1589,6 +1590,101 @@ describe("context compaction", () => {expect(engine.compactability()).toBe("ok");});+ it("a resumed engine restores the turn count and the just-compacted reason", async () => {+ // Trace replay hands these back through EngineInitialState. Without them the engine that a+ // restart rebuilds starts from zero and reports a conversation-less context.+ const withTurns = new ContextEngine({+ llm: new ScriptedLLM([]),+ environment: fakeEnvironment,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([]),+ initialState: { sessionTurns: 4 },+ });+ expect(withTurns.compactability()).toBe("ok");++ // Zero turns because the Trace ended on a completed compaction, not because nothing was said.+ const justCompacted = new ContextEngine({+ llm: new ScriptedLLM([]),+ environment: fakeEnvironment,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([]),+ initialState: { sessionTurns: 0, fromCompaction: true },+ });+ expect(justCompacted.compactability()).toBe("just_compacted");+ });++ it("a resumed Session compacts on request instead of silently doing nothing", async () => {+ // A restart leaves the Session with real history on disk but no engine — that is built by+ // the first run's bootstrap (ensureReady). A compaction asked for before anything has run+ // must build it and fold the conversation: the caller has already been told compaction is+ // available, so a silent no-op leaves it waiting for a banner that never arrives.+ const resumedLLM = new ScriptedLLM([{ messages: [assistantText("[summary]s[/summary]")] }]);+ const newContextLLM = new ScriptedLLM([]);+ const written: OmniMessage[] = [];+ const session = new Session({+ meta: metaMessage.payload,+ bootstrap: async () => ({ tools: [], llm: resumedLLM, mcp: [] }),+ mcpServers: [],+ environment: fakeEnvironment,+ trace: {+ write: async (msg) => {+ written.push(msg);+ },+ },+ createLLM: () => newContextLLM,+ compaction: settings(),+ // What agent.resumeSession derives from the Trace: three completed turns of history.+ metaAlreadyWritten: true,+ initialEngineState: { sessionTurns: 3, lastRequestTotal: 80 },+ imagesDir: "/tmp/penguin-test-scratch",+ modelHasVision: true,+ });++ expect(session.compactability()).toBe("ok");+ const events = compactionEvents(await collect(session.compact()));+ expect(events.map((e) => e.type)).toEqual(["compaction_begin", "compaction_end"]);+ expect(events[1]).toMatchObject({ status: "completed" });+ // The compaction request went to the LLM the bootstrap produced (the one resume seeds with+ // the replayed history), so the summary folds the actual conversation.+ expect(resumedLLM.calls).toHaveLength(1);+ // Compaction reset the context, and the reason stays specific rather than falling back to+ // "nothing said yet".+ expect(session.compactability()).toBe("just_compacted");+ session.dispose();+ });++ it("a never-run Session stays a strict no-op on compact, writing no Trace records", async () => {+ // The guard the fix above must not loosen: a Session created in this process has no+ // context, and compacting it must not bootstrap — trace records (session_meta /+ // tool_list_ready) would make an untouched session look resumable.+ let bootstrapped = false;+ const written: OmniMessage[] = [];+ const session = new Session({+ meta: metaMessage.payload,+ bootstrap: async () => {+ bootstrapped = true;+ return { tools: [], llm: new ScriptedLLM([]), mcp: [] };+ },+ mcpServers: [],+ environment: fakeEnvironment,+ trace: {+ write: async (msg) => {+ written.push(msg);+ },+ },+ createLLM: () => new ScriptedLLM([]),+ compaction: settings(),+ imagesDir: "/tmp/penguin-test-scratch",+ modelHasVision: true,+ });++ expect(session.compactability()).toBe("empty");+ expect(await collect(session.compact())).toHaveLength(0);+ expect(bootstrapped).toBe(false);+ expect(written).toHaveLength(0);+ session.dispose();+ });+it("user abort during the compaction request keeps the context and carries tool outputs over", async () => {const controller = new AbortController();const llm1 = new ScriptedLLM(diff --git a/packages/core/test/resume.test.ts b/packages/core/test/resume.test.tsindex ec3c4c08..d286e6a3 100644--- a/packages/core/test/resume.test.ts+++ b/packages/core/test/resume.test.ts@@ -17,6 +17,7 @@ import {abortEvent,assistantText,compactionBegin,+ compactionEnd,requestBegin,requestEnd,sessionMeta,@@ -384,6 +385,76 @@ describe("agent.resumeSession", () => {expect(messages).toHaveLength(0);expect(await agent.latestSessionId()).toBeNull();});++ it("compactability reflects the replayed turn count before the first run", async () => {+ // A process restart resumes a Session but does not run it, and the engine that holds+ // `sessionTurns` is built lazily by the first run. Availability therefore has to be+ // answered from the state the replay recovered, not from a not-yet-built engine —+ // otherwise a user with a full conversation is told there is nothing to compact+ // (the server turns this reason into a 409 `nothing_to_compact`).+ const agent = await createAgent({});+ await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ requestEnd("completed"),+ tokenUsage(usage(42), usage(42)),+ ]);++ const session = await agent.resumeSession({ sessionId: SID });+ expect(session.compactability()).toBe("ok");+ session.dispose();+ });++ it("compactability keeps the just-compacted reason across a restart", async () => {+ // The trace ends on a completed compaction: the resumed context is empty because it was+ // *just compacted*, not because the user has never spoken. Both have zero turns and they+ // must not collapse into the same explanation.+ const agent = await createAgent({});+ await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ requestEnd("completed"),+ tokenUsage(usage(150), usage(150)),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ assistantText("[summary]the story so far[/summary]"),+ requestEnd("completed"),+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),+ ]);++ const session = await agent.resumeSession({ sessionId: SID });+ expect(session.compactability()).toBe("just_compacted");+ session.dispose();+ });++ it("compactability stays empty for a resumed session whose context has no completed turn", async () => {+ // The genuine `empty` case survives the fix: the only request in the trace was interrupted,+ // so no turn ever completed and there is truly nothing to fold.+ const agent = await createAgent({});+ await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("q1"),+ requestBegin(),+ assistantText("half-writ"),+ abortEvent("user"),+ ]);++ const session = await agent.resumeSession({ sessionId: SID });+ expect(session.compactability()).toBe("empty");+ session.dispose();+ });++ it("compactability is empty on a brand-new session that has never run", async () => {+ const agent = await createAgent({});+ const session = await agent.createSession({ workspaceDir: workspace });+ expect(session.compactability()).toBe("empty");+ session.dispose();+ });});describe("setHistory injection", () => {diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 4fd9008b..f5a28204 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -193,7 +193,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 || POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle || POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error |-| POST | /compact | Trigger context compaction: 202; 409 `nothing_to_compact` when there is nothing to compact |+| POST | /compact | Trigger context compaction: 202; 409 when there is nothing to compact, the reason carried by the code — `compaction_not_configured` (this Agent has no compaction configured), `nothing_to_compact` (the context has no completed conversation turn yet), `already_compacted` (nothing new was said since the last compaction). A Session resumed after a server restart reports availability from its Trace, so an existing conversation stays compactable without running a Task first || GET | /processes | Background processes the conversation started (`exec_command`s promoted past their yield window). Served from the active runtime only — an evicted or never-loaded session truthfully reports an empty list || POST | /processes/:processId/kill | Stop one background process (SIGTERM to the whole process group, SIGKILL after a grace period); the entry drops from the list. 404 `process_not_found` when it is gone || DELETE | /processes/:processId | Remove one **exited** process entry from the list: 409 `process_running` while it still runs (stop it instead), 404 `process_not_found` when it is already gone. The entry leaves the runtime registry with the output captured from it, so `input_command` on that `process_id` fails afterwards |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 608427aa..be614fa2 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -193,7 +193,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 || POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 || POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) |-| POST | /compact | 触发上下文压缩:202;无可压缩内容返回 409 `nothing_to_compact` |+| POST | /compact | 触发上下文压缩:202;无可压缩内容返回 409,具体原因由 code 承载——`compaction_not_configured`(该 Agent 没有配置压缩)、`nothing_to_compact`(当前上下文尚未完成一轮对话)、`already_compacted`(上次压缩后还没有新的对话)。服务重启后恢复的 Session 依据 Trace 判断可压缩性,因此已有对话无需先跑一次 Task 即可压缩 || GET | /processes | 对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`)。仅来自活跃运行时——被回收或从未装载的会话如实返回空列表 || POST | /processes/:processId/kill | 停止一个后台进程(对整个进程组先 SIGTERM、宽限期后 SIGKILL),条目随之从列表消失;已不存在时 404 `process_not_found` || DELETE | /processes/:processId | 从列表移除一个**已退出**的进程条目:仍在运行时 409 `process_running`(应改用停止),已不存在时 404 `process_not_found`。条目连同该进程已捕获的输出一起离开运行时注册表,此后对该 `process_id` 调用 `input_command` 会失败 |diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex 9b646f5e..9789309b 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -71,15 +71,35 @@ import { StreamErrorWatcher } from "./stream-error-watcher.js";import type { TitleNotifier } from "./title-generator.js";import type { UsageContext } from "./usage-recorder.js";-/** 409 for when there's nothing to compact: give the specific reason rather than a one-size-fits-none message. */+/**+ * 409 for when there's nothing to compact: give the specific reason rather than a+ * one-size-fits-none message.+ *+ * Each reason carries its **own code**, not just its own message. Clients localize by code+ * (the Web's `apiErrorText` looks the code up in a table and falls back to the raw English+ * message), so one shared code leaves exactly two bad options: flatten three unrelated+ * explanations into one vague sentence, or let English prose reach a non-English UI. One code+ * per sub-reason is how the rest of this API splits a refusal — `dir_not_absolute` /+ * `dir_not_found` / `not_a_dir` are three codes for three ways of rejecting one directory.+ */function compactUnavailable(why: Exclude<CompactAvailability, "ok">): HttpError {- const messages: Record<typeof why, string> = {- unsupported: "This Agent does not have context compaction configured.",- empty: "The current context has nothing to compact (no completed conversation turns yet).",- just_compacted:- "The context was just compacted and there is no new conversation since; no need to compact again.",+ const reasons: Record<typeof why, { code: string; message: string }> = {+ unsupported: {+ code: "compaction_not_configured",+ message: "This Agent does not have context compaction configured.",+ },+ empty: {+ code: "nothing_to_compact",+ message: "The current context has nothing to compact (no completed conversation turns yet).",+ },+ just_compacted: {+ code: "already_compacted",+ message:+ "The context was just compacted and there is no new conversation since; no need to compact again.",+ },};- return new HttpError(409, "nothing_to_compact", messages[why]);+ const { code, message } = reasons[why];+ return new HttpError(409, code, message);}/** Minimal interface for a runtime Session (satisfied by core Session; tests may inject a fake implementation). */diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.tsindex b2da5552..a355cc84 100644--- a/packages/server/test/session-manager.test.ts+++ b/packages/server/test/session-manager.test.ts@@ -371,6 +371,30 @@ describe("session-manager", () => {await waitFor(() => manager.statusOf("session-1") === "idle");});+ it("compact refusal: each reason gets its own error code, not one shared code", async () => {+ // Clients localize by code (the Web looks it up in a table and falls back to the raw+ // English message), so the three reasons cannot share one code: that forces either a+ // single vague sentence for all three, or untranslated English in a non-English UI.+ const cases = [+ ["unsupported", "compaction_not_configured"],+ ["empty", "nothing_to_compact"],+ ["just_compacted", "already_compacted"],+ ] as const;++ for (const [why, code] of cases) {+ const session: RuntimeSession = {+ ...approvalFakeSession("session-1"),+ compactability: () => why,+ };+ const manager = makeManager(loaderOf(session));+ const err = await manager.startCompact("session-1").catch((e: unknown) => e);+ expect((err as { status: number }).status).toBe(409);+ expect((err as { code: string }).code).toBe(code);+ // The message still names the reason, for a client that has not mapped the code.+ expect((err as { message: string }).message).not.toBe("");+ }+ });+it("steer: forwards to the running session; idle / lost race → 409 not_running", async () => {const steered: string[] = [];const fake = approvalFakeSession("session-1");diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex b5249e61..479ef6b6 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1531,17 +1531,24 @@ Scenarios:admin_required: "Only an admin can perform this operation.",desktop_single_user: "The desktop app is single-user; user management is unavailable.",not_found: "This resource does not exist, or you do not have access.",+ internal: "The server hit an internal error. Please try again shortly.",agent_not_found: "This agent no longer exists.",unknown_agent: "That agent does not exist in this Project.",agent_exists: "This agent id is already taken.",+ agent_deleting: "This agent is being deleted.",project_exists: "This Project id is already taken.",+ project_not_found: "This Project no longer exists, or you do not have access.",+ cannot_delete_last_project: "This is the last Project and cannot be deleted.",user_exists: "This username is already taken.",user_not_found: "This user no longer exists.",cannot_delete_admin: "The built-in admin cannot be deleted.",member_not_found: "This user is not a member of the Project.",+ already_member: "This user is already a member of the Project.",+ already_owner: "This user is already an owner of the Project.",schedule_exists: "A scheduled task with this name already exists.",schedule_not_found: "This scheduled task no longer exists.",unknown_skill: "This skill is not in the library.",+ skill_too_large: "This skill directory exceeds the import limits.",file_not_found: "This file no longer exists.",not_pending: "This message already went out and can no longer be recalled.",file_too_large: "The file is too large.",@@ -1552,13 +1559,31 @@ Scenarios:not_a_dir: "That path is not a directory.",path_not_found: "That path does not exist.",workspace_missing: "This Session's Workspace no longer exists.",+ workspace_not_found: "That Workspace does not exist, or is not a directory.",+ session_not_found: "This Session no longer exists, or you do not have access.",+ session_deleting: "This Session is being deleted.",+ approval_not_found: "This approval request was already answered, or is no longer valid.",+ process_not_found: "This background process already exited, or was removed.",+ process_running: "This background process is still running — stop it before removing it.",+ memory_file_not_found: "This memory file no longer exists.",+ memory_scope_not_found: "This memory scope no longer exists.",task_in_progress: "This Session already has a task running.",compacting: "This Session is compacting its context and is not accepting new input.",+ shutting_down: "The server is shutting down. Please try again shortly.",+ // The three "cannot compact" reasons each have their own server code, so each keeps its+ // own explanation here — collapsing them into one sentence would tell a user who just+ // compacted that they have never spoken.+ compaction_not_configured: "This agent does not have context compaction configured.",+ nothing_to_compact:+ "There is nothing to compact in the current context yet (no completed conversation turn).",+ already_compacted:+ "The context was just compacted and nothing has been said since — no need to compact again.",version_conflict: "The snapshot's version is not newer than the current one.",invalid_title: "The title is invalid.",invalid_proxy_url:"Invalid proxy address — use an http(s):// or socks5:// proxy URL, or host[:port].",invalid_trace: "This file is not a valid Trace file.",+ trace_not_found: "This Trace file no longer exists.",trace_session_exists:"This agent already has a Session with that id; a duplicate Trace cannot be imported.",},diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex e07a3139..30745ccd 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1489,17 +1489,24 @@ Benchmark:admin_required: "仅管理员可执行此操作。",desktop_single_user: "桌面应用为单用户模式,用户管理不可用。",not_found: "资源不存在,或你没有访问权限。",+ internal: "服务器内部错误,请稍后重试。",agent_not_found: "该 Agent 已不存在。",unknown_agent: "该 Agent 不存在于本 Project。",agent_exists: "该 Agent id 已被占用。",+ agent_deleting: "该 Agent 正在删除中。",project_exists: "该 Project id 已被占用。",+ project_not_found: "该 Project 已不存在,或你没有访问权限。",+ cannot_delete_last_project: "这是最后一个 Project,不能删除。",user_exists: "该用户名已被占用。",user_not_found: "该用户已不存在。",cannot_delete_admin: "内置 admin 不可删除。",member_not_found: "该用户不是本 Project 的成员。",+ already_member: "该用户已是本 Project 的成员。",+ already_owner: "该用户已是本 Project 的所有者。",schedule_exists: "已存在同名定时任务。",schedule_not_found: "该定时任务已不存在。",unknown_skill: "该技能不在技能库中。",+ skill_too_large: "该技能目录过大,超出了导入限制。",file_not_found: "该文件已不存在。",not_pending: "该消息已发出,无法撤回。",file_too_large: "文件过大。",@@ -1510,13 +1517,28 @@ Benchmark:not_a_dir: "该路径不是目录。",path_not_found: "该路径不存在。",workspace_missing: "该 Session 的 Workspace 已不存在。",+ workspace_not_found: "该 Workspace 不存在或不是目录。",+ session_not_found: "该 Session 已不存在,或你没有访问权限。",+ session_deleting: "该 Session 正在删除中。",+ approval_not_found: "该授权请求已处理或已失效。",+ process_not_found: "该后台进程已结束或已被移除。",+ process_running: "该后台进程仍在运行,请先结束再移除。",+ memory_file_not_found: "该记忆文件已不存在。",+ memory_scope_not_found: "该记忆范围已不存在。",task_in_progress: "该 Session 已有任务在运行。",- /** `nothing_to_compact` is deliberately NOT mapped: the server sends three different specific reasons under that one code (not configured / no completed turn yet / just compacted), and a single localized sentence would flatten them into a wrong one. */compacting: "该 Session 正在压缩上下文,暂不接受新的输入。",+ shutting_down: "服务正在关闭,请稍后重试。",+ // The three "cannot compact" reasons each have their own server code, so each keeps its+ // own explanation here — collapsing them into one sentence would tell a user who just+ // compacted that they have never spoken.+ compaction_not_configured: "该 Agent 没有配置上下文压缩。",+ nothing_to_compact: "当前上下文还没有可压缩的内容(尚未完成一轮对话)。",+ already_compacted: "刚刚压缩过,之后还没有新的对话,无需重复压缩。",version_conflict: "快照版本不高于当前版本。",invalid_title: "标题无效。",invalid_proxy_url: "代理地址无效:应为 http(s):// 或 socks5:// 代理 URL,或 主机[:端口]。",invalid_trace: "该文件不是有效的 Trace 文件。",+ trace_not_found: "该 Trace 文件已不存在。",trace_session_exists: "该 Agent 已存在同名 Session,无法导入重复的 Trace。",},},diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.tsnew file mode 100644index 00000000..071d0a21--- /dev/null+++ b/packages/web/test/api-error-text.test.ts@@ -0,0 +1,82 @@+/**+ * Server error → localized display text (`apiErrorText`).+ *+ * The server's error messages are English-only by design, so the UI derives its text from the+ * error **code**. Any code missing from the table falls through to the raw English message —+ * which is how English prose ends up in a Chinese UI. These tests pin the codes a user actually+ * meets, and pin that the three "cannot compact" reasons stay three distinct explanations+ * rather than collapsing into one.+ */+import { afterEach, describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { apiErrorText } from "../src/lib/api-error";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { en as EN } from "../src/lib/strings-en";++/** The English message the server actually sends, so an unmapped code is visibly distinguishable. */+const serverError = (code: string): ApiError =>+ new ApiError(409, code, "RAW ENGLISH SERVER MESSAGE");++afterEach(() => setActiveStrings(ZH));++describe("apiErrorText", () => {+ it("localizes each compaction refusal separately in both locales", () => {+ const codes = ["compaction_not_configured", "nothing_to_compact", "already_compacted"];++ for (const dict of [ZH, EN]) {+ setActiveStrings(dict);+ const texts = codes.map((c) => apiErrorText(serverError(c)));+ // Mapped, so the raw server message never reaches the user.+ for (const t of texts) expect(t).not.toBe("RAW ENGLISH SERVER MESSAGE");+ // Three reasons, three explanations: telling someone who just compacted that they have+ // not spoken yet is the regression this guards.+ expect(new Set(texts).size).toBe(3);+ }+ });++ it("gives the Chinese UI Chinese text for the errors it can surface", () => {+ setActiveStrings(ZH);+ // A representative slice of the codes an ordinary session can produce: compaction refusals,+ // stale-resource races, and the catch-all a server bug returns.+ const reachable = [+ "compaction_not_configured",+ "nothing_to_compact",+ "already_compacted",+ "session_not_found",+ "approval_not_found",+ "process_not_found",+ "process_running",+ "memory_file_not_found",+ "memory_scope_not_found",+ "trace_not_found",+ "internal",+ ];+ for (const code of reachable) {+ const text = apiErrorText(serverError(code));+ expect(text, `${code} is not localized`).not.toBe("RAW ENGLISH SERVER MESSAGE");+ expect(text, `${code} has no Chinese text`).toMatch(/[一-鿿]/);+ }+ });++ it("still falls back to the server message for a code nobody has mapped", () => {+ setActiveStrings(ZH);+ expect(apiErrorText(serverError("some_code_from_the_future"))).toBe(+ "RAW ENGLISH SERVER MESSAGE",+ );+ });++ it("keeps the zh and en code tables in step", () => {+ // A code localized in one language and not the other is the same bug in the other+ // direction; the Strings type pins the key set, this pins that neither side is empty.+ expect(Object.keys(EN.errors.byCode)).toEqual(Object.keys(ZH.errors.byCode));+ for (const [code, text] of Object.entries(EN.errors.byCode)) {+ expect(text, `${code} has no English text`).not.toBe("");+ expect(ZH.errors.byCode[code as keyof typeof ZH.errors.byCode]).not.toBe("");+ }+ });++ it("reports a non-ApiError as the generic failure, not a stray object", () => {+ setActiveStrings(ZH);+ expect(apiErrorText(new Error("boom"))).toBe(S.common.unknownError);+ });+});