Skip to content

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

Context panel: rank the top files beside the top tools (#584)

Yaowei Zheng47d182c49930
diff --git a/changelog/unreleased/2026-09-02-context-top-files.md b/changelog/unreleased/2026-09-02-context-top-files.md
new file mode 100644
index 00000000..f27a2d95
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-context-top-files.md
@@ -0,0 +1,136 @@
+# The context ring measures against compaction, its threshold becomes a draggable cutter, and the panel ranks files beside tools
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `web`, `server`, `core`
+- **PR:** [#584](https://github.com/Prism-Shadow/penguin-harness/pull/584)
+
+[中文版](2026-09-02-context-top-files.zh.md)
+
+The composer's context ring now fills against the point compaction fires rather than the model's
+context window, so a context half-way to being summarized reads as half full instead of nearly
+empty on a large-window model. The panel's bar keeps the window as its scale and marks that point
+with a dashed cutter — which is now also the control that moves it: drag the cutter, confirm the
+number, and the Agent's compaction threshold changes for the conversation you are looking at,
+immediately. That immediacy is a core change: compaction settings have left the strict tier and
+are re-read at every compaction checkpoint. The composition panel also gained a second Top 5: the
+files whose `read_file` / `edit_file` / `write_file` traffic occupies the most of the current
+context, beside the tool ranking it already had. A Tools / Files switch above the list picks the
+view, and the panel remembers the choice for the rest of the tab session.
+
+## The ring fills against the compaction threshold
+
+- The ring, its panel's header ratio and the panel's bar all use one basis: the **effective**
+ compaction threshold — `min(the Agent's compaction.max_context_length, the model's
+ context_window − the compaction headroom)`, the same derivation the Agent compacts at, with the
+ seeded default threshold filled in for an Agent that configures none and the assumed 128000
+ window for a model entry that declares none. 64k used against a 128k threshold on a 1M-window
+ model now reads 50%, where it read 6% before. Amber past 80% and red past 95% follow the same
+ basis.
+- The window has not disappeared from view: the bar names its own scale underneath itself, as
+ "Max context N", whenever the bar is drawn.
+- The panel's **bar** keeps the model window as its scale, because the two answer different
+ questions: the ring says how close compaction is, the bar says how much model there is and
+ where inside it the trigger sits. While the panel is open the server's own `compactionThreshold`
+ is preferred over the client's derivation — the same arithmetic, one of them read from disk a
+ moment ago — so an Agent-config edit shows up without a page reload.
+- Two fallbacks keep the ring honest where no threshold applies: compaction switched off (`<= 0`)
+ and the subagent composer, which has no Session-level Agent config to reason from, both keep the
+ old window basis.
+- The chat page re-reads the Agent's config on an Agent switch and when the tab regains focus, so
+ a threshold lowered on the settings page is reflected on the way back.
+
+## A notice when the model cannot hold the Agent's threshold
+
+- The composer raises a dismissible amber notice when the selected model's `context_window` is
+ below the Agent's **configured** `compaction.max_context_length` — the case where compaction
+ silently fires at the window's edge instead of at the number the user set. It names both
+ figures, says compaction therefore fires at the edge of the window, points at the two ways to
+ lower the threshold below it — the panel's cutter, or the Agent settings — and notes that either
+ applies immediately. It links to that Agent's settings.
+- Judged on the configured threshold, never the effective one, which is already capped by the
+ window and so could never disagree with it. It re-evaluates when the model changes and when the
+ Agent config is re-read; a dismissal is remembered per Session and model for the rest of the tab
+ session.
+
+## A new model's context window defaults to 1,000,000
+
+- The Web model dialog records 1,000,000, not 128000, when a custom or user-group model is saved
+ with its context-window field blank, and the field's hint says so. A model added by hand is a
+ known model, and today's hand-added models are large-window ones; guessing low costs real
+ capacity, guessing high costs one edit.
+- Core's assumption for an entry that carries **no** `context_window` at all is unchanged at
+ 128000 — that is the safety default for an unknown window, a different number for a different
+ question. `penguin config model add` still writes no default when `--context-window` is omitted.
+
+## The compaction threshold is a draggable cutter
+
+- The dashed cutter on the panel's bar sits at the effective compaction threshold and names it on
+ hover. Dragging it proposes a new threshold, snapped to the nearest 1,000 tokens and clamped to
+ the bar's own ends, with the proposed value shown beside it while the gesture runs.
+- It is a `role="slider"` and takes the keyboard too: ArrowLeft / ArrowRight move it by 1,000,
+ Shift by 10,000, Enter releases and Escape abandons the adjustment.
+- A release (or Enter) opens a confirmation naming the Agent and the threshold being replaced,
+ carrying a **number field prefilled with the proposal and still editable** — a gesture this
+ coarse must not write a configuration value on its own. The field takes any whole number above
+ zero; a value above the model window is allowed, and the hint then names the threshold that will
+ actually be in force. Cancel or Escape snaps the cutter back.
+- Confirming writes `compaction.max_context_length` through the same endpoint the Agent settings
+ page uses, sending only the compaction change, then re-reads the Agent config the chat page
+ holds — so the ring, the cutter and the small-window notice all move together — and a toast
+ says it applied.
+- A cutter is drawn whenever compaction is on. A threshold the model window cannot reach pins it
+ to the bar's right edge rather than removing it: the cutter is how such a threshold gets
+ lowered, so it is the last thing that may disappear when the threshold is wrong.
+
+## Compaction settings apply immediately, mid-conversation
+
+- `compaction.max_context_length`, `max_session_turns`, `mode` and `prompt` have left the strict
+ tier. The engine re-reads the section from the Agent's `system_config.yaml` at every compaction
+ checkpoint — after each request reports its token usage, and on a manual `/compact` — so a
+ change saved to an Agent is honoured by Sessions already running, without waiting for a
+ compaction to rotate the context. Compaction settings never belonged to the request prefix: they
+ decide when a context ends, not what it looks like.
+- `ContextEngineDeps` gained an optional `readCompaction` provider for this. It refreshes an
+ existing baseline and never creates one, so whether compaction is *configured* stays a constant
+ of the Session; an embedder that supplies only `compaction` keeps the previous
+ fixed-per-context behaviour, and `openNextContext`'s `compaction` still replaces the baseline at
+ a rotation. A read that throws leaves the settings already in force and warns once — a config
+ file that is momentarily unreadable must not end a run.
+- `Agent` supplies that provider for every Session, reading only the `compaction` section and
+ caching it by the config file's identity on disk, so an unchanged file costs one `stat` per
+ checkpoint. Everything else in the file stays strict tier and still belongs to the context that
+ was assembled from it.
+- The Agent settings page's save feedback follows: a save that changed **only** compaction fields
+ now says it takes effect immediately, including running conversations. Every other runtime field
+ keeps the existing wording.
+
+## Files beside tools in the composition panel
+
+- `GET /api/sessions/:sessionId/context` gained `topFiles`: at most five entries of
+ `{ path, tokens, ops: { read, edit, write } }`, ranked by the context each file's file-tool calls
+ and their results occupy — the same character heuristic and the same call-to-result pairing as
+ `topTools`, so both rankings are shares of the same estimate. A call is keyed by the file its
+ `file_path` resolves to, the way the file tools resolve it against the Workspace, so `a.ts`,
+ `./a.ts` and the absolute spelling are one row. A call with a missing or invalid `file_path` is
+ left out of the file ranking (the tool itself refuses such a call); it still counts as tool
+ traffic.
+- A file inside the Session's Workspace is shown Workspace-relative; any other file is absolute,
+ with the home directory shortened to `~`.
+- The Files view shows each file's name alone, in the same mono type as the Tools view; the full
+ path is the row's tooltip, which is what tells two files of the same name apart. Its token and
+ percent columns are the same shares of the whole context the Tools view shows. A context whose
+ tools never touched a file says "No file traffic in this context". The per-op counts stay in the
+ response and are not drawn.
+- The two views are picked by a pair of text buttons sitting on the ranking's heading line, sized
+ to it.
+- The six parts, `contextClosed` and `compactionThreshold` are unchanged.
+
+## Core
+
+- `DEFAULT_MAX_CONTEXT_LENGTH` moved from `state/default-config.ts` to `llm/context-limits.ts`,
+ beside the derivation that caps it, and core gained a `@prismshadow/penguin-core/context-limits`
+ subpath. Both halves of the threshold rule now reach a browser bundle through one
+ Node-free module, so the web app derives the ring's basis with core's arithmetic instead of a
+ second copy of it. The constant is still exported from the package root; nothing that imported
+ it needs to change.
diff --git a/changelog/unreleased/2026-09-02-context-top-files.zh.md b/changelog/unreleased/2026-09-02-context-top-files.zh.md
new file mode 100644
index 00000000..84fc1194
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-context-top-files.zh.md
@@ -0,0 +1,97 @@
+# 上下文圆环改按压缩阈值计量,阈值成为可拖动的切刀,面板在工具排行旁加上文件排行
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `web`, `server`, `core`
+- **PR:** [#584](https://github.com/Prism-Shadow/penguin-harness/pull/584)
+
+[English](2026-09-02-context-top-files.md)
+
+输入区的上下文圆环改以「压缩触发的那个点」为标尺,不再以模型的上下文窗口为标尺——大窗口模型上一段
+已经压缩过半的上下文,此前会被画成几乎空的圆环。面板条形仍以模型窗口为标尺,并用一道虚线切刀标出
+那个触发点——切刀同时也是移动它的控件:拖动切刀、确认数值,这个 Agent 的压缩阈值立刻改变,正在看的
+这段对话也立刻生效。这份「立刻」来自内核的改动:压缩配置离开严格层,改为在每个压缩检查点重读。构成
+面板另多了第二份 Top 5:`read_file` / `edit_file` / `write_file` 的流量在当前上下文里占得最多的文件,
+与原有的工具排行并列。列表上方的「工具 / 文件」开关切换视图,面板在本页签会话内记住上次的选择。
+
+## 圆环以压缩阈值为标尺
+
+- 圆环、面板表头的比值与面板条形统一用一个标尺:压缩阈值的**生效值**——`min(Agent 的
+ compaction.max_context_length, 模型 context_window − 压缩余量)`,与 Agent 实际压缩所用的推导
+ 同一份;Agent 未配置阈值时按缺省阈值、模型条目未声明窗口时按假定的 128000 推导。1M 窗口模型上
+ 128k 阈值、64k 占用现在显示 50%,此前显示 6%。>80% 转琥珀、>95% 转红同样按该标尺计。
+- 窗口并未从视野中消失:只要画出条形,其下方就以「最大上下文 N」淡显条形自身的标尺。
+- 面板**条形**仍以模型窗口为标尺,因为两者回答的是不同的问题:圆环答「离压缩还有多远」,条形答
+ 「这个模型还有多少地方、触发点落在其中何处」。面板打开期间优先采用服务端回报的
+ `compactionThreshold`——两者是同一套算术,只是服务端那份刚从磁盘读出——因此改过 Agent 配置后
+ 无需刷新页面。
+- 两处回退保证圆环不编造数字:压缩关闭(`<= 0`),以及没有 Session 级 Agent 配置可依据的子智能体
+ 输入区,二者仍以模型窗口为标尺。
+- 对话页在切换 Agent 与页签重新获得焦点时重新读取 Agent 配置,因此在设置页调低阈值后返回即可看到。
+
+## 模型窗口装不下 Agent 阈值时给出提示
+
+- 所选模型的 `context_window` 小于 Agent **配置的** `compaction.max_context_length` 时,输入区上方
+ 给出一条可关闭的琥珀色提示——这正是压缩会在窗口边缘悄悄触发、而不是在用户设定的那个数触发的情形。
+ 提示点名两个数值,说明压缩因此会在窗口边缘触发,并指出把阈值调到窗口以下的两条路径——面板里的
+ 切刀,或 Agent 设置——两者都立即生效;提示另附直达该 Agent 设置页的入口。
+- 判据取配置值而非生效值——生效值已被窗口钳住,用它永远不会成立。提示随所选模型的切换与 Agent 配置
+ 的重新读取复算;关闭按 Session + 模型记住,仅在本页签会话内有效。
+
+## 新增模型的上下文窗口缺省为 1000000
+
+- Web 的模型弹窗在自定义 / 自建分组模型留空上下文窗口时按 1000000 写入(此前为 128000),字段提示
+ 同步改写。手动新增的是已知模型,而今天手动新增的多是大窗口模型:猜小会白白损失容量,猜大只需
+ 用户改一次。
+- 核心对**根本没有** `context_window` 的条目的假定仍是 128000——那是「窗口未知」的安全缺省,与本项
+ 是两个问题的两个数。`penguin config model add` 省略 `--context-window` 时仍不写入任何缺省值。
+
+## 压缩阈值成为可拖动的切刀
+
+- 面板条形上的虚线切刀落在压缩阈值的生效值上,悬停即报出该值。拖动它提出一个新阈值:按最近的
+ 1,000 token 取整、在条形自身的两端之间钳住,拖动期间在旁浮出待定值。
+- 切刀是 `role="slider"`,也接受键盘:`←` / `→` 每次 1,000,配合 `Shift` 每次 10,000,`Enter`
+ 确认、`Esc` 放弃本次调节。
+- 松手(或 `Enter`)弹出确认卡片:点名 Agent 与被替换的阈值,并带一个**以待定值预填、仍可编辑的
+ 数字输入框**——这样粗的手势不该独自写入一项配置。输入框接受任意大于 0 的整数;填入超过模型窗口
+ 的值是允许的,此时提示行报出实际会生效的那个阈值。取消或 `Esc` 则切刀弹回。
+- 确认后经 Agent 设置页所用的同一接口写入 `compaction.max_context_length`(只发送压缩这一项改动),
+ 随后重读对话页持有的 Agent 配置——圆环、切刀与窗口过小提示一并更新——并以 toast 告知已生效。
+- 只要压缩是开着的就画切刀。模型窗口够不到的阈值把切刀钉在条形右端,而不是让它消失:切刀正是调低
+ 这类阈值的手段,阈值不合适的时候它最不该是消失的那一个。
+
+## 压缩配置立即生效,包括进行中的对话
+
+- `compaction.max_context_length`、`max_session_turns`、`mode`、`prompt` 离开严格层。引擎在每个
+ 压缩检查点——每次请求回报 token 用量之后,以及手动 `/compact`——从该 Agent 的 `system_config.yaml`
+ 重读该节,因此保存到 Agent 的修改被已在运行的 Session 采纳,不必等一次压缩轮换上下文。压缩配置
+ 本就不属于请求前缀:它决定的是上下文何时结束,不是上下文长什么样。
+- 为此 `ContextEngineDeps` 新增可选的 `readCompaction` 提供者。它只刷新既有基线、从不凭空造出一个,
+ 因此「压缩是否配置过」仍是 Session 的常量;只提供 `compaction` 的 SDK 宿主保持原有的「每上下文
+ 固定」行为,轮换时 `openNextContext` 的 `compaction` 依旧替换基线。读盘抛错时沿用已在生效的设置
+ 并只警告一次——一份一时读不出来的配置文件不该终结一次运行。
+- `Agent` 为每个 Session 提供该读取器:只取 `compaction` 一节,并按配置文件在磁盘上的身份缓存,
+ 文件未变时每个检查点只花一次 `stat`。文件里的其余部分仍属严格层,仍归属于当初据以装配的那个上下文。
+- Agent 设置页的保存反馈随之区分:**只**改动了压缩字段的保存改口为「立即生效(包括进行中的对话)」,
+ 其余运行参数保持原有措辞。
+
+## 面板在工具排行旁加上文件排行
+
+- `GET /api/sessions/:sessionId/context` 新增 `topFiles`:至多五条 `{ path, tokens, ops: { read, edit, write } }`,
+ 按每个文件的文件工具调用与其结果所占上下文排序——与 `topTools` 用同一套字符启发式、同一套调用与结果
+ 的配对,因此两份排行是同一份估算的占比。调用按其 `file_path` 解析到的文件归并,解析方式与文件工具
+ 对 Workspace 的解析一致,所以 `a.ts`、`./a.ts` 与绝对路径写法是同一行。`file_path` 缺失或无效的调用
+ 不进文件排行(工具本身也会拒绝这样的调用),但仍计入工具流量。
+- Session 的 Workspace 内的文件按相对路径显示;其余文件为绝对路径,home 目录缩写为 `~`。
+- 文件视图每行只显示文件名,字体与工具视图同为等宽;完整路径悬停可见,同名的两个文件因此仍能分辨。
+ token 与占比两列与工具视图同为占整个上下文的份额。工具没有碰过任何文件的上下文显示「本轮上下文
+ 没有文件读写」。各操作次数仍在接口返回中,只是不再画出。
+- 两个视图由排行标题行上的一对文字按钮切换,尺寸与该行齐平。
+- 六个分项、`contextClosed` 与 `compactionThreshold` 不变。
+
+## 核心
+
+- `DEFAULT_MAX_CONTEXT_LENGTH` 从 `state/default-config.ts` 移到 `llm/context-limits.ts`,与钳制它
+ 的那段推导放在一起;core 另新增 `@prismshadow/penguin-core/context-limits` 子路径导出。阈值规则的
+ 两半由此经同一个不依赖 Node 的模块进入浏览器打包,Web 端用 core 的算术推导圆环标尺,而不是另抄
+ 一份。该常量仍从包根导出,既有导入方无需改动。
diff --git a/packages/core/package.json b/packages/core/package.json
index 3983a491..8333920e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -33,6 +33,10 @@
"types": "./dist/extension/index.d.ts",
"import": "./dist/extension/index.js"
},
+ "./context-limits": {
+ "types": "./dist/llm/context-limits.d.ts",
+ "import": "./dist/llm/context-limits.js"
+ },
"./model-catalog": {
"types": "./dist/state/model-catalog.d.ts",
"import": "./dist/state/model-catalog.js"
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 505f660b..887e75f1 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -14,13 +14,13 @@
*/
import fs from "node:fs/promises";
import path from "node:path";
+import { parse as parseYaml } from "yaml";
import {
assertValidId,
assembleSystemPrompt,
buildToolConfig,
selectBuiltinToolsForModel,
DEFAULT_COMPACTION_PROMPT,
- DEFAULT_MAX_CONTEXT_LENGTH,
formatModelRef,
getModel,
listInstalledSkills,
@@ -36,11 +36,18 @@ import {
systemConfigPath,
tracesDir,
type AgentState,
+ type CompactionConfig,
type ModelRef,
type ModelEntry,
type ProjectConfig,
+ type SystemConfig,
} from "./state/index.js";
-import { GenerativeModel, ToolCallIdAllocator, effectiveMaxContextLength } from "./llm/index.js";
+import {
+ DEFAULT_MAX_CONTEXT_LENGTH,
+ GenerativeModel,
+ ToolCallIdAllocator,
+ effectiveMaxContextLength,
+} from "./llm/index.js";
import { Environment } from "./environment/index.js";
import {
Writer,
@@ -269,6 +276,31 @@ interface AssembledContext {
// Compaction-threshold derivation (`effectiveMaxContextLength`) lives with the rest of the
// window arithmetic in llm/context-limits.ts; re-exported by llm/index.js.
+/**
+ * The Session's compaction settings as they follow from a `compaction` section: defaults
+ * filled in, the threshold capped by what the model's window leaves room for, and an unknown
+ * mode read as the default `summarize`.
+ *
+ * Stated once because two callers need the same answer from the same input — the context
+ * assembly below, and the live re-reader every checkpoint calls (see `compactionReader`). Two
+ * copies of the rule would let a running Session compact at a threshold no rotation would
+ * have chosen.
+ */
+function resolveCompaction(
+ config: CompactionConfig | undefined,
+ contextWindow: number | undefined,
+): CompactionSettings {
+ return {
+ maxContextLength: effectiveMaxContextLength(
+ config?.max_context_length ?? DEFAULT_MAX_CONTEXT_LENGTH,
+ contextWindow,
+ ),
+ maxSessionTurns: config?.max_session_turns ?? -1,
+ mode: config?.mode === "discard" ? "discard" : "summarize",
+ prompt: config?.prompt ?? DEFAULT_COMPACTION_PROMPT,
+ };
+}
+
/**
* Output cap for meta requests (title generation / vision describing): these carry their own
* small hardcoded budget, tightened further by the entry's per-model `max_tokens` when that is
@@ -424,18 +456,13 @@ export class Agent {
const thinkingLevel =
pin === null ? undefined : (pin ?? this.configuredThinkingLevel(state, projectConfig));
- // Compaction config: defaults are filled in here; an unknown mode falls back to
- // summarize (the default).
- const compactionConfig = state.systemConfig.compaction;
- const compaction: CompactionSettings = {
- maxContextLength: effectiveMaxContextLength(
- compactionConfig?.max_context_length ?? DEFAULT_MAX_CONTEXT_LENGTH,
- spec.modelEntry.context_window,
- ),
- maxSessionTurns: compactionConfig?.max_session_turns ?? -1,
- mode: compactionConfig?.mode === "discard" ? "discard" : "summarize",
- prompt: compactionConfig?.prompt ?? DEFAULT_COMPACTION_PROMPT,
- };
+ // Compaction config: this context's baseline. It is no longer the last word — the engine
+ // re-reads the section at every compaction checkpoint through `compactionReader` — but a
+ // context still opens on the configuration that was on disk when it opened.
+ const compaction = resolveCompaction(
+ state.systemConfig.compaction,
+ spec.modelEntry.context_window,
+ );
// session_meta: this context's runtime configuration — the assembled prompt goes both to
// the LLM and in here, so the Trace can audit the actual effective value and a resume
@@ -735,6 +762,49 @@ export class Agent {
});
}
+ /**
+ * The Session's live compaction reader: what takes `compaction` out of the set of settings
+ * a model context freezes when it opens. The engine calls it at every compaction checkpoint,
+ * so a threshold, turn count, mode or prompt saved to the Agent's `system_config.yaml`
+ * reaches the conversation that is running instead of waiting for the next rotation.
+ *
+ * Cached by the file's identity on disk, so an unchanged file costs one `stat` per checkpoint
+ * and nothing else. Three fields, because no one of them is enough: the inode number changes
+ * whenever the config is saved through `atomicWriteFile` (a temp file renamed over the name,
+ * which is also why a reader never sees a half-written config), while an in-place rewrite
+ * keeps the inode and is caught by the nanosecond mtime — `mtimeMs` alone cannot separate two
+ * saves inside the same millisecond, and a threshold dragged in the Web App can produce
+ * exactly that. Size is the cheap third opinion for a filesystem with a coarse clock.
+ *
+ * Only the `compaction` section is honoured here. Everything else in the config is strict
+ * tier and belongs to the context that was assembled from it; reading the file is not
+ * licence to apply the rest of it mid-context.
+ *
+ * The model's context window comes from the Session's own entry, which is fixed at creation
+ * (a mid-conversation model change opens a new Session), so one reader serves every context
+ * the Session opens. A parse that fails throws: the engine keeps the settings in force and
+ * warns once, which is the right answer for a file being rewritten badly.
+ */
+ private compactionReader(spec: SessionSpec): () => Promise<CompactionSettings> {
+ const { root, projectId, agentId } = this.state;
+ const configPath = systemConfigPath(root, projectId, agentId);
+ const contextWindow = spec.modelEntry.context_window;
+ let cachedKey: string | null = null;
+ let cached: CompactionSettings | null = null;
+ return async (): Promise<CompactionSettings> => {
+ const stat = await fs.stat(configPath, { bigint: true });
+ const key = `${stat.mtimeNs}:${stat.size}:${stat.ino}`;
+ if (cached !== null && key === cachedKey) return cached;
+ const parsed = parseYaml(await fs.readFile(configPath, "utf8")) as unknown;
+ if (parsed === null || typeof parsed !== "object") {
+ throw new Error(`Invalid Agent State config: ${configPath} is empty or corrupted.`);
+ }
+ cached = resolveCompaction((parsed as SystemConfig).compaction, contextWindow);
+ cachedKey = key;
+ return cached;
+ };
+ }
+
/**
* Constructs the Session for `spec` running on `context` — the one assembly behind
* createSession and resumeSession, so initialization and resumption cannot drift apart.
@@ -759,6 +829,9 @@ export class Agent {
createBareLLM: rt.createBareLLM,
compaction: context.compaction,
+ // Live tier: the baseline above is what this context opened on, and this is how every
+ // checkpoint after it asks the disk again.
+ readCompaction: this.compactionReader(spec),
// Where an input image lands when it becomes a path line (see SessionConfig.imagesDir).
imagesDir: sessionScratchpadDir(root, projectId, agentId, spec.sessionId),
modelHasVision: spec.modelEntry.vision !== false,
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index d35a7d87..974b3028 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -256,6 +256,23 @@ export interface ContextEngineDeps {
openNextContext?: (opts: OpenContextOptions) => OpenedContext | Promise<OpenedContext>;
/** The first context's compaction settings; only takes effect if provided together with `openNextContext`. A context `openNextContext` opens may bring its own. */
compaction?: CompactionSettings;
+ /**
+ * Live compaction settings, re-read at every point the engine consults them for a decision:
+ * the post-request checkpoint (threshold and turn count), and the start of a compaction
+ * (mode and prompt). This is what takes compaction configuration out of the strict tier —
+ * an edit saved to the Agent's config reaches a running Session at its next checkpoint
+ * instead of waiting for a rotation.
+ *
+ * Refreshes an existing baseline; it never creates one. An embedder that supplies only
+ * `compaction` keeps today's fixed-per-context behaviour, and one that supplies neither has
+ * no compaction at all — so whether compaction is *configured* stays a constant of the
+ * Session, which is what `compactability()` may answer synchronously.
+ *
+ * The provider is expected to be cheap enough to call once per checkpoint (the Agent's caches
+ * by the config file's identity on disk). A read that throws leaves the previous settings in
+ * force and is logged once: a config file that briefly cannot be read must not end a run.
+ */
+ readCompaction?: () => CompactionSettings | Promise<CompactionSettings>;
/**
* The first context's session_meta message: written at the start of each Trace file a
* compaction's rotation opens, until an `openNextContext` result brings the meta of the context
@@ -431,7 +448,10 @@ export function reconnectDelayMs(base: number, max: number, attempt: number): nu
export class ContextEngine {
/** Per-context settings: the first context's from the deps, then whatever each opened context brings (see `startNewContext`). */
private maxTurns: number;
+ /** Compaction settings in force. Baseline per context (deps, then each opened context), and re-read from `deps.readCompaction` at every checkpoint in between. */
private compaction: CompactionSettings | undefined;
+ /** Whether a `readCompaction` failure has already been reported; one line per Session, not one per checkpoint. */
+ private compactionReadWarned = false;
private readonly maxReconnects: number;
private readonly maxTurnAttempts: number;
private readonly reconnectBackoffMs: number;
@@ -856,6 +876,11 @@ export class ContextEngine {
// applies mid-Task — when runTurn returns, all of this turn's
// tool results are ready and paired with their tool_call.
const midTask = turn.toolOutputs.length > 0;
+ // The checkpoint is where compaction configuration is consulted, so it is where it is
+ // re-read: the threshold and turn count `compactionTrigger` compares against, and the
+ // `mode` picked from the same settings immediately below, are the values on disk right
+ // now rather than the ones this context opened with.
+ await this.refreshCompaction();
const compactionReason = this.compactionTrigger();
if (compactionReason) {
const mode = this.compaction!.mode;
@@ -1001,6 +1026,9 @@ export class ContextEngine {
}
async *compact(opts?: { signal?: AbortSignal }): AsyncGenerator<OmniMessage> {
+ // The manual entry into a compaction, and the second place the live settings decide
+ // something: the `mode` below, and the prompt summarizeContext reads from them.
+ await this.refreshCompaction();
if (!this.compaction || !this.deps.openNextContext) return;
// The current context has no completed LLM turns: nothing to compact, return immediately.
// This also guards against two /compact calls in a row — the new context is empty right
@@ -1434,6 +1462,32 @@ export class ContextEngine {
// Context compaction
// -------------------------------------------------------------------------
+ /**
+ * Re-reads the live compaction settings, if the host supplies a provider. Called at every
+ * point the engine is about to decide something from them — the post-request checkpoint and
+ * the two entries into a compaction — so a threshold, turn count, mode or prompt edited on
+ * disk applies to the conversation that is running.
+ *
+ * Only refreshes an existing baseline: a Session with no `compaction` in its deps has no
+ * compaction capability, and a provider must not conjure one mid-run (see
+ * ContextEngineDeps.readCompaction). A read that throws keeps the settings already in force
+ * and warns once — the alternative, failing the run because a config file was momentarily
+ * unreadable, is worse than compacting at the previous threshold.
+ */
+ private async refreshCompaction(): Promise<void> {
+ if (!this.compaction || !this.deps.readCompaction) return;
+ try {
+ this.compaction = await this.deps.readCompaction();
+ } catch (e) {
+ if (this.compactionReadWarned) return;
+ this.compactionReadWarned = true;
+ const message = e instanceof Error ? e.message : String(e);
+ process.stderr.write(
+ `[penguin] compaction settings could not be re-read: ${message}; keeping the settings in force.\n`,
+ );
+ }
+ }
+
/**
* Checks the compaction threshold: triggers once context usage (the most recent
* token_usage's request.total) or the Session cumulative turn count **reaches** the threshold
@@ -1520,6 +1574,9 @@ export class ContextEngine {
pendingToolOutputs: OmniMessage[],
signal?: AbortSignal,
): AsyncGenerator<OmniMessage, CompactionResult> {
+ // Already refreshed: both entries into a compaction — the post-request checkpoint and
+ // `compact()` — re-read the live settings before choosing the mode that lands here, so the
+ // prompt below comes from the same read as that decision rather than a second one.
const settings = this.compaction!;
yield* this.emitCompactionBegin(reason, "summarize");
@@ -1886,6 +1943,9 @@ export class ContextEngine {
if (opened.sessionMeta) this.contextMeta = opened.sessionMeta;
if (records.length > 0) this.contextRecords = records;
if (opened.maxTurns !== undefined) this.maxTurns = opened.maxTurns;
+ // The new context's baseline. A `readCompaction` provider re-reads the same file at the
+ // next checkpoint and agrees with it; what this settles is the Session that has no
+ // provider, where the rotation is still the only way compaction settings change.
if (opened.compaction) this.compaction = opened.compaction;
this.sessionTurns = 0;
this.lastRequestTotal = 0;
diff --git a/packages/core/src/llm/context-limits.ts b/packages/core/src/llm/context-limits.ts
index 62cb60cc..1bee5ff7 100644
--- a/packages/core/src/llm/context-limits.ts
+++ b/packages/core/src/llm/context-limits.ts
@@ -13,8 +13,9 @@
*
* `OUTPUT_SAFETY_MARGIN` is the single tunable of the margin story: the output floor and
* the compaction headroom are derived from it (PR #235 review), so their invariants —
- * floor below margin, headroom above margin — cannot drift apart. The two remaining
- * independent facts are `DEFAULT_CONTEXT_WINDOW` and `IMAGE_TOKEN_ESTIMATE`.
+ * floor below margin, headroom above margin — cannot drift apart. The three remaining
+ * independent facts are `DEFAULT_CONTEXT_WINDOW`, `DEFAULT_MAX_CONTEXT_LENGTH` and
+ * `IMAGE_TOKEN_ESTIMATE`.
*
* Thinking-level interaction (considered, out of scope): on a high-reasoning session a
* small derived cap can be consumed by thinking tokens before any visible answer, ending
@@ -33,13 +34,34 @@ import type { OmniMessage } from "../omnimessage/index.js";
* Models with a *smaller* real window still need `context_window` set on their entry —
* no derivation can protect a window it doesn't know about.
*
- * Not the compaction-threshold default (`DEFAULT_MAX_CONTEXT_LENGTH` in
- * state/default-config.ts) — a separate number that happens to concern the same axis. The
- * seeded threshold sits above this assumption, so an entry without a usable `context_window`
- * effectively compacts at `DEFAULT_CONTEXT_WINDOW − COMPACTION_HEADROOM`.
+ * Not {@link DEFAULT_MAX_CONTEXT_LENGTH}, the compaction-threshold default below — a separate
+ * number that happens to concern the same axis. The seeded threshold sits above this
+ * assumption, so an entry without a usable `context_window` effectively compacts at
+ * `DEFAULT_CONTEXT_WINDOW − COMPACTION_HEADROOM`.
*/
export const DEFAULT_CONTEXT_WINDOW = 128000;
+/**
+ * Seeded `compaction.max_context_length`: the context-token threshold newly created Agents
+ * start with, and the value {@link effectiveMaxContextLength}'s callers substitute for an Agent
+ * whose config carries none. Set high on purpose, because the model's own `context_window` is
+ * the backstop: the effective threshold is the smaller of this value and the window minus
+ * {@link COMPACTION_HEADROOM}, taken at use. A window with no room for this value plus that
+ * headroom therefore decides the trigger point, so a small-window model still compacts inside
+ * its window rather than never; on a roomier window — nearly every built-in catalog entry —
+ * this value is what fires. A model entry with no usable `context_window` falls back to
+ * {@link DEFAULT_CONTEXT_WINDOW}, which is a different number from this one and must not be
+ * conflated with it.
+ *
+ * Lives beside the derivation rather than with the rest of the seeded config, so that both
+ * halves of the threshold rule — the default and the cap applied to it — reach a browser
+ * bundle through one dependency-free module: the web app draws the composer's context ring
+ * against this same effective threshold and must not re-derive either number.
+ *
+ * Persisted per-agent in system_config.yaml — existing agents keep their stored value.
+ */
+export const DEFAULT_MAX_CONTEXT_LENGTH = 256000;
+
/**
* Smallest `context_window` value taken at face value. Anything below is treated as
* unconfigured (no real model has a window under 4096; such values are typos or unit
@@ -76,7 +98,7 @@ export const MIN_OUTPUT_TOKENS = Math.floor(OUTPUT_SAFETY_MARGIN / 2);
* `COMPACTION_HEADROOM − OUTPUT_SAFETY_MARGIN` minus the compaction prompt; reserving less
* would clamp the summary to the floor and truncate it. On a 32768 window this makes
* compaction fire at ≈ 30720 instead of never — the seeded default threshold
- * (`DEFAULT_MAX_CONTEXT_LENGTH`, 256000) sits far outside such a window, so without this cap
+ * ({@link DEFAULT_MAX_CONTEXT_LENGTH}, 256000) sits far outside such a window, so without this cap
* the window's hard limit would always be hit first.
*/
export const COMPACTION_HEADROOM = OUTPUT_SAFETY_MARGIN * 2;
diff --git a/packages/core/src/llm/index.ts b/packages/core/src/llm/index.ts
index 3d5de546..7dcfa7d0 100644
--- a/packages/core/src/llm/index.ts
+++ b/packages/core/src/llm/index.ts
@@ -27,6 +27,7 @@ export type { ListEndpointModelsOptions } from "./list-models.js";
export { ToolCallIdAllocator, stripToolCallIdSuffix } from "./tool-call-ids.js";
export {
DEFAULT_CONTEXT_WINDOW,
+ DEFAULT_MAX_CONTEXT_LENGTH,
OUTPUT_SAFETY_MARGIN,
MIN_OUTPUT_TOKENS,
COMPACTION_HEADROOM,
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index 9abb7091..c37fb65f 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -102,6 +102,8 @@ export interface SessionConfig {
createBareLLM?: () => LLMInterface;
/** The first context's compaction settings (defaults are filled in by the composition layer); only takes effect when provided together with `openNextContext`, and a context that one opens brings its own. */
compaction?: CompactionSettings;
+ /** Live compaction settings, re-read at every compaction checkpoint (see ContextEngineDeps.readCompaction): what lets a threshold, mode or prompt edited on disk reach the conversation that is running. Session-lifetime, so a rotation does not replace it. */
+ readCompaction?: () => CompactionSettings | Promise<CompactionSettings>;
/** Session resume: `session_meta` is already in the original Trace file, so it isn't written again on the first run (avoids duplication). */
metaAlreadyWritten?: boolean;
/** Session resume: the engine's initial state derived from Trace replay (carry-over / accumulated stats, etc.). */
@@ -350,6 +352,7 @@ export class Session {
}
: {}),
...(config.compaction ? { compaction: config.compaction } : {}),
+ ...(config.readCompaction ? { readCompaction: config.readCompaction } : {}),
...(config.initialEngineState ? { initialState: config.initialEngineState } : {}),
// The engine assembles one input of its own — a steering message with images — and folds
// it through the same converter `runTask` uses, failures included: a scratchpad that
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 8b56339f..54f496c6 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -24,6 +24,9 @@ import type {
ToolDefinitionConfig,
} from "../interfaces/index.js";
import type { CompactionMode } from "../omnimessage/types.js";
+// The seeded compaction threshold is declared beside the derivation that caps it, so the
+// default and the cap cannot drift apart.
+import { DEFAULT_MAX_CONTEXT_LENGTH } from "../llm/context-limits.js";
import { KERNEL_VERSION } from "./kernel-history.js";
/** Docs: /docs/configuration § "System prompt placeholders". */
@@ -100,21 +103,6 @@ export const SCHEDULES_PLACEHOLDER = "{{SCHEDULES}}";
/** Inside `schedules.prompt` only: the current schedule-file names, one `- name` per line (SCHEDULE_LIST_EMPTY_NOTE when none exist). */
export const SCHEDULE_LIST_PLACEHOLDER = "{{SCHEDULE_LIST}}";
-/**
- * Seeded `compaction.max_context_length`: the context-token threshold newly created Agents
- * start with. Set high on purpose, because the model's own `context_window` is the backstop:
- * the effective threshold is the smaller of this value and the window minus
- * COMPACTION_HEADROOM, taken at use (see llm/context-limits.ts). A window with no room for
- * this value plus that headroom therefore decides the trigger point, so a small-window model
- * still compacts inside its window rather than never; on a roomier window — nearly every
- * built-in catalog entry — this value is what fires. A model entry with no usable
- * `context_window` falls back to the assumed window (128000), which is a different number
- * from this one and must not be conflated with it.
- *
- * Persisted per-agent in system_config.yaml — existing agents keep their stored value.
- */
-export const DEFAULT_MAX_CONTEXT_LENGTH = 256000;
-
/**
* Context compaction config (the `compaction` section of `system_config.yaml`).
* Docs: /docs/configuration § "Agent config".
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index ab5c3032..dbad9e87 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -922,6 +922,36 @@ describe("Agent model contexts are assembled from the Agent State on disk, at ev
}
});
+ it("the compaction section is re-read from disk on demand, so an edited threshold reaches a running Session", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-live-compaction");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ const readCompaction = (
+ session as unknown as {
+ engineDeps: {
+ readCompaction?: () => Promise<{ maxContextLength: number; mode: string }>;
+ };
+ }
+ ).engineDeps.readCompaction!;
+
+ await patchSystemConfig((cfg) => {
+ cfg.compaction = { ...(cfg.compaction ?? {}), max_context_length: 40000, mode: "discard" };
+ });
+ // No rotation, no new Session: the reader the engine calls at each checkpoint answers
+ // from the file as it is now.
+ expect(await readCompaction()).toMatchObject({ maxContextLength: 40000, mode: "discard" });
+
+ await patchSystemConfig((cfg) => {
+ cfg.compaction = { ...(cfg.compaction ?? {}), max_context_length: 199000 };
+ });
+ expect((await readCompaction()).maxContextLength).toBe(199000);
+ } finally {
+ session.dispose();
+ }
+ });
+
it("the context opened after compaction is rebuilt whole — prompt, toolset, vault, run settings — and its records describe it", async () => {
const agent = await createAgent();
const ws = path.join(tmpRoot, "ws-rebuild");
diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.ts
index bc3590a7..835f1fca 100644
--- a/packages/core/test/compaction.test.ts
+++ b/packages/core/test/compaction.test.ts
@@ -527,6 +527,71 @@ describe("context compaction", () => {
expect(llm2.calls).toHaveLength(1);
});
+ it("a live threshold lowered on disk compacts at the next checkpoint, with no rotation in between", async () => {
+ // Compaction configuration is live tier: the engine asks `readCompaction` at every
+ // checkpoint, so lowering the threshold under a running conversation takes effect on its
+ // next request instead of waiting for a context to rotate.
+ const llm1 = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(150, 150)] },
+ { messages: [assistantText("answer two"), usage(150, 300)] },
+ { messages: [assistantText("[summary]lowered[/summary]"), usage(10, 310)] },
+ ],
+ "llm1",
+ );
+ const llm2 = new ScriptedLLM([], "llm2");
+ let threshold = 1000;
+ const engine = new ContextEngine({
+ llm: llm1,
+ environment: fakeEnvironment,
+ compaction: settings({ maxContextLength: threshold }),
+ readCompaction: () => settings({ maxContextLength: threshold }),
+ openNextContext: () => ({ llm: llm2 }),
+ });
+
+ // 150 tokens against a 1000-token threshold: nothing fires, and the context stays open.
+ const out1 = await collect(engine.run([userText("task one")], { approve: allowAll }));
+ expect(compactionEvents(out1)).toEqual([]);
+
+ threshold = 100;
+ const out2 = await collect(engine.run([userText("task two")], { approve: allowAll }));
+ const events = compactionEvents(out2);
+ expect(events).toHaveLength(2);
+ expect(events[0]).toMatchObject({ type: "compaction_begin", reason: "context" });
+ expect(events[1]).toMatchObject({ type: "compaction_end", status: "completed" });
+ // Turn one, turn two, then the compaction request — all on the SAME context: the lowered
+ // threshold was picked up without an opener ever running before it.
+ expect(llm1.calls).toHaveLength(3);
+ });
+
+ it("a readCompaction that throws leaves the settings already in force", async () => {
+ const llm1 = new ScriptedLLM(
+ [
+ { messages: [assistantText("answer one"), usage(150, 150)] },
+ { messages: [assistantText("[summary]kept[/summary]"), usage(10, 160)] },
+ ],
+ "llm1",
+ );
+ const engine = new ContextEngine({
+ llm: llm1,
+ environment: fakeEnvironment,
+ compaction: settings(),
+ readCompaction: () => {
+ throw new Error("config unreadable");
+ },
+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),
+ });
+
+ const out = await collect(engine.run([userText("task one")], { approve: allowAll }));
+ // The failed read neither ends the run nor changes the threshold: 150 still reaches the
+ // static 100, and the static prompt is still what the compaction request carries.
+ expect(compactionEvents(out)).toMatchObject([
+ { type: "compaction_begin", reason: "context" },
+ { type: "compaction_end", status: "completed" },
+ ]);
+ expect(llm1.calls[1]!.map(textOf).join("\n")).toContain("COMPACT NOW");
+ });
+
it("summarize mid-task: tool outputs pair into the compaction request, summary alone feeds the new LLM", async () => {
const llm1 = new ScriptedLLM(
[
diff --git a/packages/core/test/context-limits.test.ts b/packages/core/test/context-limits.test.ts
index d1a64d00..6f5b4985 100644
--- a/packages/core/test/context-limits.test.ts
+++ b/packages/core/test/context-limits.test.ts
@@ -7,6 +7,7 @@ import { describe, expect, it } from "vitest";
import {
COMPACTION_HEADROOM,
DEFAULT_CONTEXT_WINDOW,
+ DEFAULT_MAX_CONTEXT_LENGTH,
MIN_OUTPUT_TOKENS,
MIN_USABLE_CONTEXT_WINDOW,
OUTPUT_SAFETY_MARGIN,
@@ -16,7 +17,6 @@ import {
effectiveMaxOutputTokens,
resolveContextWindow,
} from "../src/llm/context-limits.js";
-import { DEFAULT_MAX_CONTEXT_LENGTH } from "../src/state/default-config.js";
import { toolCallOutput, userText } from "../src/omnimessage/index.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts
index 61a0e356..5769bb42 100644
--- a/packages/core/tsup.config.ts
+++ b/packages/core/tsup.config.ts
@@ -16,6 +16,9 @@ export default defineConfig({
// without depending on whatever embeds it.
"src/extension/index.ts",
"src/state/model-catalog.ts",
+ // Window/threshold arithmetic plus its two defaults: pure numbers, no Node dependency, so
+ // the web app can bundle the compaction-threshold derivation its context ring fills against.
+ "src/llm/context-limits.ts",
// Hot-update kernel: zero-dependency subpath so web can bundle it directly.
"src/kernel/index.ts",
],
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index 6868449d..73b4d8e6 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -167,7 +167,7 @@ Every LLM-side failure except `auth` triggers an in-run reconnect — `timeout`
## Compaction
-Compaction does more than shorten the history: **every compaction rotates in a brand-new model context**. Once it completes, the Agent's entire runtime configuration is reassembled from the Agent State as it is at that moment — exactly like a new Session's first context — and the Trace starts a new file (one Trace file always equals one model context). An edit you (or the model itself) make to the Agent's configuration mid-conversation therefore takes effect after the next compaction.
+Compaction does more than shorten the history: **every compaction rotates in a brand-new model context**. Once it completes, the Agent's entire runtime configuration is reassembled from the Agent State as it is at that moment — exactly like a new Session's first context — and the Trace starts a new file (one Trace file always equals one model context). An edit you (or the model itself) make to the Agent's configuration mid-conversation therefore takes effect after the next compaction — with one exception: the `compaction` section itself, which the engine re-reads at every compaction checkpoint and applies to the running conversation at once.
Compaction settings are filled in from `system_config.yaml` by the composition layer:
@@ -190,7 +190,7 @@ Three triggers (`compaction_begin.reason`):
Two modes: `summarize` (default) appends the compaction Prompt to the old context, extracts the `[summary]`, wraps it as a `[context_summary]` user text and continues in a **fresh model context**; `discard` simply drops the old context. System markers are written as `[tag]…[/tag]`; the earlier angle-bracket form (`<summary>`, `<context_summary>`, …) is still recognized when reading old Traces and old persisted compaction prompts. Summary extraction applies a tolerance ladder: the first non-empty `[summary]` tag pair wins; when every pair is empty, the text left after stripping the tags is used instead (rescuing models that write the body after the closing tag); with no tags at all, the whole output is used verbatim. Compaction rotates the [Trace file](/sessions-and-traces) (`_002`, `_003`, …) — one Trace file always equals one complete model context. `compactability()` probes feasibility before `session.compact()` (`ok | unsupported | empty | just_compacted`).
-The new context is **assembled from the Agent State as it is at that moment**, exactly as a new Session's first context is: `system_config.yaml` in full (the prompt template with its section prompts and toggles, the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the model defaults), `AGENTS.md`, the vault, the installed Skills' metadata, the Memory indexes, the schedule roster and the Environment's date. So an edit made during the old context — by the model working on its own configuration, or by hand in the Agent settings — takes effect at the next compaction rather than the next Session. Runtime parameters fall into three tiers. **Strict** — the system prompt, the toolset (MCP included), the compaction settings and the model reference never change inside a running context: they shape the request prefix, and a context's prefix is fixed from open to close, so the provider's prompt cache stays valid across the whole Trace file (the vault, a tool's `r`/`rw` permission and the Project's command policy never reach the model, but are read once per context on the same rotation schedule). **Soft** — the thinking level: a purely per-request parameter — every LLM request takes the Session's pinned level (the Web App's in-chat picker, the CLI's `--thinking` / `/thinking`) or, unpinned, the Agent config default read when the context opened; changeable mid-context and never recorded in the Trace, at the cost of the provider's cached messages, which is why the pickers advise compacting first. **Unrestricted** — the approval mode: re-read from the database per decision, never touching the request, so an edit applies immediately. The Environment is re-equipped: the vault's values go straight into the command environment of every command spawned from then on (processes already running keep the environment they were started with); MCP Servers are cached by config — an entry that did not change keeps its live connection and discovered tools, a removed or changed one is closed, and only new, changed or previously failed ones connect, the wait streaming as the same `mcp_connect_begin` / `mcp_connect_end` pair the first run brackets it with — followed by the new `tool_list_ready`. The rotated Trace file opens with the `session_meta` recording the prompt this context runs with, then the connect pair (if any) and the toolset record. What stays fixed for the Session's lifetime is the Session itself: its id, Workspace, model entry (credentials, window and per-model annotations included) and origin. An Agent State that cannot be assembled (a config that no longer parses) fails the run with that error and the engine stays on the old context — the same error a new Session would hit. The same rule opens a context that resume finds closed by a completed compaction (see [Sessions & Traces](/sessions-and-traces)).
+The new context is **assembled from the Agent State as it is at that moment**, exactly as a new Session's first context is: `system_config.yaml` in full (the prompt template with its section prompts and toggles, the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the model defaults), `AGENTS.md`, the vault, the installed Skills' metadata, the Memory indexes, the schedule roster and the Environment's date. So an edit made during the old context — by the model working on its own configuration, or by hand in the Agent settings — takes effect at the next compaction rather than the next Session. Runtime parameters fall into three tiers. **Strict** — the system prompt, the toolset (MCP included) and the model reference never change inside a running context: they shape the request prefix, and a context's prefix is fixed from open to close, so the provider's prompt cache stays valid across the whole Trace file (the vault, a tool's `r`/`rw` permission and the Project's command policy never reach the model, but are read once per context on the same rotation schedule). **Soft** — the thinking level: a purely per-request parameter — every LLM request takes the Session's pinned level (the Web App's in-chat picker, the CLI's `--thinking` / `/thinking`) or, unpinned, the Agent config default read when the context opened; changeable mid-context and never recorded in the Trace, at the cost of the provider's cached messages, which is why the pickers advise compacting first. **Unrestricted** — the approval mode, re-read from the database per decision, never touching the request, so an edit applies immediately; and the `compaction` section (`max_context_length`, `max_session_turns`, `mode`, `prompt`), which the engine re-reads from `system_config.yaml` at every compaction checkpoint — after each request reports its token usage, and on a manual `/compact` — caching it by the file's mtime, so lowering an Agent's threshold applies to conversations already running instead of waiting for a rotation. Compaction settings never belonged to the request prefix: they decide when a context ends, not what it looks like. A read that fails keeps the settings already in force rather than failing the run. The Environment is re-equipped: the vault's values go straight into the command environment of every command spawned from then on (processes already running keep the environment they were started with); MCP Servers are cached by config — an entry that did not change keeps its live connection and discovered tools, a removed or changed one is closed, and only new, changed or previously failed ones connect, the wait streaming as the same `mcp_connect_begin` / `mcp_connect_end` pair the first run brackets it with — followed by the new `tool_list_ready`. The rotated Trace file opens with the `session_meta` recording the prompt this context runs with, then the connect pair (if any) and the toolset record. What stays fixed for the Session's lifetime is the Session itself: its id, Workspace, model entry (credentials, window and per-model annotations included) and origin. An Agent State that cannot be assembled (a config that no longer parses) fails the run with that error and the engine stays on the old context — the same error a new Session would hit. The same rule opens a context that resume finds closed by a completed compaction (see [Sessions & Traces](/sessions-and-traces)).
The compaction request keeps the session's toolset **unchanged** — the request prefix (tool list included) stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest. Compaction still succeeds only with a valid summary: a response that calls a tool or whose extracted summary is empty counts as one more failed attempt — any tool calls are answered with synthesized failed outputs (keeping `tool_use`/`tool_result` pairing intact), and the resent request carries a corrective note ahead of the compaction Prompt (committed history can only be appended to; rewriting it would invalidate the prompt cache). Every failure — unusable summaries and the `failed`/`timeout`/`malformed` transport statuses alike — draws on the one reconnect budget and backoff ladder described under "Automatic reconnect" above; only `auth` stops the compaction at once. Once the budget is exhausted the compaction ends `failed`, keeping the original context and Trace file until the next trigger; `compaction_end` reuses the unified retry detail block — `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_message` detail (shown on the chat banner and the CLI line) — and a failed compaction also lands in the cost center as a `compaction_failed` error record. The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request (mid-Task tool results, or the carry-over a manual `/compact` folds in) into the old context's history: retries resend only the repairs and the Prompt, and nothing resends the absorbed input afterwards.
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index 6017c91f..17df70a0 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -160,7 +160,7 @@ Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消
## 上下文压缩(Compaction)
-压缩不只是缩短历史:**每次压缩都会轮换出一个全新的模型上下文**。压缩完成后,Agent 的全部运行配置按此刻的 Agent State 重新装配——与新建 Session 的首个上下文完全相同——Trace 随之开启新文件(一个 Trace 文件恒等于一个模型上下文)。因此你(或模型自己)在对话进行中对 Agent 配置的修改,会在下一次压缩后生效。
+压缩不只是缩短历史:**每次压缩都会轮换出一个全新的模型上下文**。压缩完成后,Agent 的全部运行配置按此刻的 Agent State 重新装配——与新建 Session 的首个上下文完全相同——Trace 随之开启新文件(一个 Trace 文件恒等于一个模型上下文)。因此你(或模型自己)在对话进行中对 Agent 配置的修改,会在下一次压缩后生效——只有 `compaction` 一节例外,引擎在每个压缩检查点重读它,修改立即对进行中的对话生效。
压缩配置由组装层从 `system_config.yaml` 填充默认值:
@@ -183,7 +183,7 @@ interface CompactionSettings {
两种模式:`summarize`(默认)向旧上下文追加压缩 Prompt,提取 `[summary]` 后包装为 `[context_summary]` 用户文本,在**全新的模型上下文**中继续;`discard` 直接丢弃旧上下文。系统标记统一写作 `[tag]…[/tag]`;读取旧 Trace 与旧压缩 Prompt 时仍识别早期的尖括号形式(`<summary>`、`<context_summary>` 等)。摘要提取自带容忍阶梯:优先取第一个非空的 `[summary]` 标签对;标签对全为空时,改取剥离标签后剩余的全部文本(兼容把正文写在闭合标签之后的模型);完全没有标签则整段输出照用。压缩时 [Trace 文件随之轮转](/sessions-and-traces)(`_002`、`_003`……),一个 Trace 文件恒等于一个完整模型上下文。`session.compact()` 前可用 `compactability()` 探询可行性(`ok | unsupported | empty | just_compacted`)。
-新上下文**按此刻的 Agent State 整体装配**,与新建 Session 的首个上下文完全相同:整份 `system_config.yaml`(提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、`max_turns`、模型默认参数)、`AGENTS.md`、vault、已装 Skill 的元数据、Memory 索引、定时任务名单与环境字段中的日期。因此旧上下文期间的修改——模型改自己的配置,或用户在 Agent 设置里手改——在下一次压缩即生效,不必等下一个 Session。运行参数分三层。**严格层**:系统提示词、工具集(含 MCP)、压缩配置与模型引用在运行中的上下文内绝不改变——它们构成请求前缀,上下文的前缀自开启固定到关闭,整个 Trace 文件内提供商的提示词缓存始终有效(vault、工具的 `r`/`rw` 权限与 Project 的命令策略虽不进模型请求,也随同一轮换节奏在上下文开启时读取一次)。**软限制层**:思考等级——纯粹的每请求参数:每次 LLM 请求取 Session 钉住的等级(Web 对话内选择器、CLI 的 `--thinking` / `/thinking`),未钉住则取上下文开启时读到的 Agent 配置缺省;允许中途更换、不落 Trace,代价是提供商的消息缓存失效,因此选择器会提醒建议先压缩。**不限制层**:审批模式——逐次决策从数据库重读、从不进入请求,修改即刻生效。Environment 随之重新装备:vault 的值直接进入此后每条命令的子进程环境(已在运行的进程保留启动时的环境);MCP Server 按配置缓存——条目未变的保持连接与已发现的工具,被删除或改动的关闭,只有新增、改动或上次失败的才连接,等待期间流式发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对——随后是新的 `tool_list_ready`。轮转出的新 Trace 文件以记录本上下文实际所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。Agent State 装配失败(例如配置文件已无法解析)时本次运行以该错误结束、引擎保持旧上下文——与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启(见 [Session 与 Trace](/sessions-and-traces))。
+新上下文**按此刻的 Agent State 整体装配**,与新建 Session 的首个上下文完全相同:整份 `system_config.yaml`(提示词模板及各节提示词与开关、内置工具条目与 MCP Server、压缩配置、`max_turns`、模型默认参数)、`AGENTS.md`、vault、已装 Skill 的元数据、Memory 索引、定时任务名单与环境字段中的日期。因此旧上下文期间的修改——模型改自己的配置,或用户在 Agent 设置里手改——在下一次压缩即生效,不必等下一个 Session。运行参数分三层。**严格层**:系统提示词、工具集(含 MCP)与模型引用在运行中的上下文内绝不改变——它们构成请求前缀,上下文的前缀自开启固定到关闭,整个 Trace 文件内提供商的提示词缓存始终有效(vault、工具的 `r`/`rw` 权限与 Project 的命令策略虽不进模型请求,也随同一轮换节奏在上下文开启时读取一次)。**软限制层**:思考等级——纯粹的每请求参数:每次 LLM 请求取 Session 钉住的等级(Web 对话内选择器、CLI 的 `--thinking` / `/thinking`),未钉住则取上下文开启时读到的 Agent 配置缺省;允许中途更换、不落 Trace,代价是提供商的消息缓存失效,因此选择器会提醒建议先压缩。**不限制层**:审批模式——逐次决策从数据库重读、从不进入请求,修改即刻生效;`compaction` 一节(`max_context_length`、`max_session_turns`、`mode`、`prompt`)同属此层——引擎在每个压缩检查点(每次请求回报 token 用量之后,以及手动 `/compact`)从 `system_config.yaml` 重读该节并按文件 mtime 缓存,因此调低阈值对已在运行的对话立即生效,不必等轮换;压缩配置本就不属于请求前缀——它决定上下文何时结束,而非上下文长什么样。读盘失败时沿用上一次读到的值,绝不让本次运行失败。Environment 随之重新装备:vault 的值直接进入此后每条命令的子进程环境(已在运行的进程保留启动时的环境);MCP Server 按配置缓存——条目未变的保持连接与已发现的工具,被删除或改动的关闭,只有新增、改动或上次失败的才连接,等待期间流式发出与首次运行相同的 `mcp_connect_begin` / `mcp_connect_end` 事件对——随后是新的 `tool_list_ready`。轮转出的新 Trace 文件以记录本上下文实际所用提示词的 `session_meta` 开头,随后是连接事件对(如有)与工具集记录。整个 Session 生命周期内固定的只有 Session 自身:id、Workspace、模型条目(含凭据、窗口与逐模型标注)与来源。Agent State 装配失败(例如配置文件已无法解析)时本次运行以该错误结束、引擎保持旧上下文——与新建 Session 遇到的是同一个错误。恢复时发现上下文已被完成的压缩关闭,同样按此规则开启(见 [Session 与 Trace](/sessions-and-traces))。
压缩请求**保持会话工具集不变**——请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻提供商的提示词缓存依然有效。只有得到有效摘要,压缩才算成功:若响应中出现工具调用、或提取出的摘要为空,视同一次普通的失败尝试——工具调用先以合成的失败输出逐一应答(保持 `tool_use`/`tool_result` 配对完整),重发的请求在压缩 Prompt 前附加一条纠正说明(已提交的历史只能追加、不能改写,改写会使提示词缓存失效)。所有失败——无效摘要与 `failed`/`timeout`/`malformed` 传输失败——共用上文「自动重连」一节的同一重连预算与退避阶梯;只有 `auth` 会让压缩当场停止。预算耗尽后压缩以 `failed` 结束,保留原上下文与 Trace 文件,等待下次触发;`compaction_end` 复用统一的重试详情块——`attempt`(最终尝试序号,失败尝试也计入)与失败时的 `error_message` 详情(聊天横幅与 CLI 直接展示),压缩失败还会作为一条 `compaction_failed` 错误记录进入成本中心。首个**已提交**的尝试(无论被采纳还是被判无效)同时会把折叠进压缩请求的本轮输入(任务中途的工具结果、手动 `/compact` 折叠的补发内容)吸收进旧上下文:重试只重发修复输出与压缩 Prompt,此后也不再重发已吸收的输入。
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index eef9cfa6..54f3f36a 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -155,6 +155,8 @@ Manage it from the Security policy tab of Project Settings in the Web App (owner
| `compaction.max_session_turns` | `-1` | Cumulative Session turn threshold (`-1` = unlimited) |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
| `compaction.prompt` | built-in template | Prompt used for summarize compaction |
+
+The four `compaction.*` fields are the one part of this file a running conversation does not have to wait for: the engine re-reads the section at every compaction checkpoint (after each request reports its token usage, and on a manual `/compact`), so a saved change applies to Sessions already running. Everything else here is read when a model context opens and lands at the next compaction. The Web App can also change the threshold straight from the context panel — drag the dashed cutter on its bar.
| `memory.enabled` | `true` | Whether Memory enters the context and Memory directories are prepared |
| `memory.prompt` | built-in template | Always-injected half of the `{{MEMORY}}` block, editable on the Memory tab — carries `{{USER_MEMORY_INDEX}}` |
| `memory.workspace_prompt` | built-in template | Appended only in a persistent Workspace, editable on the Memory tab — carries `{{WORKSPACE_MEMORY_INDEX}}` and `{{WORKSPACE_MEMORY_DIR}}` |
@@ -236,7 +238,7 @@ For developers: `kernel_version` advances manually, and only on a substantive ch
On Windows, `{{PROJECT_DIR}}` and `{{CWD}}` are injected with forward slashes — like every other path core composes for the model (attachment lines, the goal-file line, truncated-output recovery paths). The model re-emits these spellings into JSON tool arguments and shell commands; forward slashes are accepted by Node's fs APIs and the package's (Git) Bash tool shell, and avoid JSON backslash-escaping mistakes.
-`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)). Like the rest of the Agent State — `system_config.yaml` included — it is read whenever a model context opens: at Session creation and again when a compaction opens the next context. An edit therefore takes effect at the next compaction of a running Session, not only in new Sessions, and never inside the context that is running (see [Compaction](/agent-loop)).
+`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)). Like the rest of the Agent State — `system_config.yaml` included — it is read whenever a model context opens: at Session creation and again when a compaction opens the next context. An edit therefore takes effect at the next compaction of a running Session, not only in new Sessions, and never inside the context that is running (the `compaction` section is the exception — see [Compaction](/agent-loop)).
The Vault / Skills / Memory / Schedules sections all follow the same placeholder + toggle + editable prompt pattern: the template holds only the `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` placeholders, the section text lives in the corresponding `*.prompt` config (edited on its settings tab), and turning `*.enabled` off empties the whole block. The four section placeholders are expanded **last, in a single pass** at assembly time: expansion products are never rescanned, so placeholder-looking text inside a memory index or a section prompt stays literal instead of triggering a second substitution.
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 46d3f92d..2d4b1111 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -155,6 +155,8 @@ enabled = false
| `compaction.max_session_turns` | `-1` | Session 累计轮数阈值(`-1` 不限制) |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
| `compaction.prompt` | 内置模板 | summarize 压缩使用的 Prompt |
+
+`compaction.*` 四项是本文件里唯一不必等待的部分:引擎在每个压缩检查点(每次请求回报 token 用量之后,以及手动 `/compact`)重读该节,保存后对已在运行的 Session 立即生效;其余各项都在模型上下文开启时读取,于下一次压缩生效。Web App 也可以直接在上下文构成面板里改阈值——拖动条形上的虚线切刀即可。
| `memory.enabled` | `true` | 记忆是否进入上下文、是否为持久 Workspace 准备记忆目录 |
| `memory.prompt` | 内置模板 | `{{MEMORY}}` 区块中恒注入的一半,可在记忆标签页编辑——含 `{{USER_MEMORY_INDEX}}` |
| `memory.workspace_prompt` | 内置模板 | 仅持久 Workspace 追加,可在记忆标签页编辑——含 `{{WORKSPACE_MEMORY_INDEX}}` 与 `{{WORKSPACE_MEMORY_DIR}}` |
@@ -236,7 +238,7 @@ compaction:
Windows 上注入的 `{{PROJECT_DIR}}` 与 `{{CWD}}` 统一使用正斜杠——与 core 产出的其他模型可见路径(附件行、Goal file 行、截断输出 recovery 路径)同一拼写。模型会把这些拼写原样带入 JSON 工具参数和 Shell 命令;正斜杠被 Node 的 fs API 与包内 (Git) Bash 工具 Shell 接受,也避免 JSON 反斜杠转义出错。
-`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。与 Agent State 的其余部分(含 `system_config.yaml`)一样,它在每次模型上下文开启时重新读取——Session 创建时一次,压缩开启下一个上下文时再一次——因此修改在运行中 Session 的下一次压缩即生效,不只作用于新 Session,也绝不会作用于正在运行的上下文(见[上下文压缩](/agent-loop))。
+`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。与 Agent State 的其余部分(含 `system_config.yaml`)一样,它在每次模型上下文开启时重新读取——Session 创建时一次,压缩开启下一个上下文时再一次——因此修改在运行中 Session 的下一次压缩即生效,不只作用于新 Session,也绝不会作用于正在运行的上下文(`compaction` 一节例外,见[上下文压缩](/agent-loop))。
Vault / 技能 / 记忆 / 定时任务四个小节均采用「段落占位符 + 开关 + 可编辑提示词」模式:模板只保留 `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` 占位符,小节文本存于各自的 `*.prompt` 配置、在对应设置标签页编辑,`*.enabled` 关闭即整段为空。四个段落占位符在装配时**最后单趟展开**:展开产物不再被扫描,因此记忆索引或提示词正文里出现的占位符字样只会保持字面原样,不会引发二次替换。
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index a0240319..77b30af2 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -21,7 +21,7 @@ Each Project's available models are recorded in the hidden `.project_config.toml
| --- | --- |
| `provider` | Config group name; paired with `model_id` it forms the unique key |
| `model_id` | Upstream request id |
-| `context_window` | Context window (tokens). Load-bearing, not just display: each request's effective output cap and the compaction threshold are derived from it, so requests never ask for more output than the window still fits. Unset (or implausibly small, under 4096): the output clamp turns off and compaction derives from an assumed 128000 — set the real value for models with smaller windows |
+| `context_window` | Context window (tokens). Load-bearing, not just display: each request's effective output cap and the compaction threshold are derived from it, so requests never ask for more output than the window still fits. Unset (or implausibly small, under 4096): the output clamp turns off and compaction derives from an assumed 128000 — set the real value for models with smaller windows. The Web dialog prefills 1,000,000 when a custom or user-group model leaves the field blank (a hand-added entry is a known model, not an unknown window); narrow it when the endpoint serves less. `penguin config model add` writes no default at all when `--context-window` is omitted |
| `max_tokens` | Optional per-model output cap (max output tokens per request). When set it overrides the Agent's `model.max_tokens`; unset inherits it. The cap is a ceiling, not the literal wire value: each request sends `min(max_tokens, context_window − estimated input − safety margin)`, so small-window models work without hand-tuning it. Omitting the field on a Web full-table save clears it |
| `client_type` | Protocol hint (`openai-chat` for Chat Completions, `openai-responses` for the Responses API, `ant-messages` for Anthropic Messages, …); inferred by AgentHub from the model id when omitted. Custom endpoints use one of those three generic protocol clients, and the Web dialog can detect which one a base URL serves. The pre-0.4.2 spelling `openai` is a deprecated alias and is normalized to `openai-chat` when the config is read |
| `display_name` | Display name |
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 4978ceff..a288c80c 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -21,7 +21,7 @@ description: 经 AgentHub 单一网关接入模型,以 (provider, model_id)
| --- | --- |
| `provider` | 配置分组名,与 `model_id` 成对构成唯一键 |
| `model_id` | 上游请求 id |
-| `context_window` | 上下文窗口(Token 数)。不只用于展示:每次请求的实际输出上限与压缩阈值都由它推导,请求不会索要超出窗口剩余空间的输出。缺省(或小于 4096 的非常规值)时输出收敛关闭、压缩按 128000 假定推导——窗口更小的模型务必填真实值 |
+| `context_window` | 上下文窗口(Token 数)。不只用于展示:每次请求的实际输出上限与压缩阈值都由它推导,请求不会索要超出窗口剩余空间的输出。缺省(或小于 4096 的非常规值)时输出收敛关闭、压缩按 128000 假定推导——窗口更小的模型务必填真实值。Web 的模型弹窗在自定义 / 自建分组模型留空该字段时按 1000000 写入(手动新增的条目是已知模型,不是未知窗口),上游窗口更小时自行调低;`penguin config model add` 省略 `--context-window` 时不写入任何缺省值 |
| `max_tokens` | 可选的按模型输出上限(单次请求最大输出 Token 数)。设置后覆盖 Agent 的 `model.max_tokens`,缺省沿用。该值是天花板而非逐字上线值:每次请求实际发送 `min(max_tokens, context_window − 估算输入 − 安全余量)`,小窗口模型无需手工调低。Web 整表保存时省略该字段即清除 |
| `client_type` | 协议提示(`openai-chat` 对应 Chat Completions、`openai-responses` 对应 Responses API、`ant-messages` 对应 Anthropic Messages 等);缺省由 AgentHub 按 model id 推断。自定义端点使用这三种通用协议客户端之一,Web 对话框可按 base URL 检测其中哪一种。0.4.2 之前的旧写法 `openai` 为已废弃别名,读取配置时归一化为 `openai-chat` |
| `display_name` | 显示名 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index a8441c87..29a09a70 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -77,6 +77,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to
- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled. When the run ends before a steering message was delivered — pressing Stop while a tool is still running is the usual way — you do not have to reach for that control: the message returns to the input box on its own, attachments and all, ready to edit and send again, so an interrupt never eats what you had already typed;
- **Goal mode** (the "+" menu, or `/goal`) turns the draft into an objective the system loops Tasks against. Attached images ride along and are always sent as scratchpad paths (a goal objective is re-injected as text every round — see [Goal mode](/goal-mode)); text is still required, since a picture alone states no objective, and file attachments are refused. Round 1's bubble shows the attachments in full, later rounds collapse them into a chip that expands on click;
- `/agent` and `/model` stage their pick instead of acting on it: the chosen Agent or model becomes a chip above the text body and nothing is sent yet, so you keep typing — Enter/Send is what hands the conversation over (a new chat for that Agent) or forks it onto the chosen model, carrying the text along; with an empty composer a default message is filled in, and the chip's × cancels. Both chips are cached with the draft, so they survive a reload or a trip to another conversation together with the text. A model fork additionally waits for the Session to be idle — it continues from the Session's Trace, which a running turn or a compaction is still writing — and a line above the composer says so while it waits;
+- The toolbar's right side carries a **context ring**: a single-colour gauge of how full the context is, measured against the point compaction fires (the Agent's `compaction.max_context_length`, capped by what the model window leaves room for), amber past 80% and red past 95%. Clicking it opens the **context panel** — the used/threshold figures, a bar that runs to the model's full window split into the six things the context is made of (system prompt, tool definitions, user messages, model messages, tool requests, tool results), with "Max context N" naming that scale underneath it, and a Top 5 of the tools, or of the files the file tools touched, switched by a pair of text buttons on the heading line and listing file names alone with the full path on hover. The dashed cutter on that bar is where compaction fires, and it is draggable: drag it (or focus it and use the arrow keys — Shift for a coarser step) and releasing asks to confirm the new threshold in a dialog whose number you can still edit. Confirming writes it to the Agent and it applies to this conversation immediately, mid-run included;
- When human approval is required, tool calls show inline allow/deny buttons in the message stream; the approval mode can be changed mid-Session;
- While the engine waits out a reconnect backoff (≥2s), the retry line shows a live countdown to the next attempt with inline **Retry now** (skips the remaining wait) and **Give up** (the ordinary abort) controls;
- When the model API rejects the Session's credentials (an authentication failure), the composer grays out and disables — recoverably: the Session pins only the model reference, and credentials come from the current Project config. The notice's primary button opens the Models page; saving a new API key there unlocks the composer by itself (open tabs unlock live via a `credentials_updated` event, and after a reload the composer stays unlocked because the credential update is newer than the recorded auth failure). A "Retry" button clears the state manually for another attempt (it re-arms if the key is still bad), a completed request always clears it, and "New Session" remains as the escape to a fresh draft. The disabled composer keeps its draft selectable, so a long message that failed to send can still be copied out.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 740c0587..ffaf12cf 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -76,6 +76,7 @@ penguin web
- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;
- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回。运行在插话送达之前结束时(工具跑着的时候按停止是最常见的情形)不用你动手:这条插话会自动回到输入框,附件一并还原,改完可以直接再发——打断不会吃掉已经打好的话;
- `/agent` 与 `/model` 都是暂存而非立即生效:选中的 Agent 或模型只在文本区上方留下一枚 chip,此时不发送任何内容,可以继续输入——按 Enter / 点发送才真正交接(为该 Agent 新开一个对话)或换用所选模型继续本对话,输入的文字随之带走;正文为空时自动填入默认消息,点 chip 上的 × 即可取消。两枚 chip 都随草稿缓存,刷新页面或切到别的会话再回来时与文字一同恢复;其中切换模型还需等待会话空闲——新会话要从本会话的 Trace 接续,而运行中的一轮或压缩仍在写入——等待期间输入框上方会给出说明;
+- 工具条右侧是**上下文占用圆环**:单色圆环,标尺是压缩真正触发的那个点(Agent 的 `compaction.max_context_length`,被模型窗口留出的余地钳住),>80% 转琥珀、>95% 转红。点击展开**上下文构成面板**:`已用 / 阈值` 数字、一条以模型完整窗口为标尺的条形(已填充部分按系统提示词、工具定义、用户消息、模型消息、工具请求、工具结果六项细分,条形下方以「最大上下文 N」标出该标尺),以及工具 / 文件两份 Top 5(标题行上的一对文字按钮切换,文件视图只列出 `read_file` / `edit_file` / `write_file` 触及的文件名,完整路径悬停可见)。条形上的虚线切刀标出压缩触发点,且可以拖动——拖动它(或聚焦后用方向键,按住 Shift 步长更大),松手即弹出确认框,框内的数值仍可编辑;确认后写入该 Agent,并对当前这段对话立即生效,运行中也不例外;
- 需要人工审批时,工具调用在消息流中内联显示“允许 / 拒绝”按钮;审批模式在会话中途可随时调整;
- 引擎在重连退避等待(≥2 秒)期间,重试提示行会实时倒计时到下一次尝试,并内联提供**立即重试**(跳过剩余等待)与**放弃**(普通中断)两个按钮;
- 模型 API 拒绝该 Session 的凭据(鉴权失败)时,输入框会置灰禁用——但可恢复:Session 锁定的只是模型引用,凭据取自当前 Project 配置。提示条的主按钮跳转到模型配置页;在那里保存新的 API key 后输入框会自动解锁(已打开的标签页经 `credentials_updated` 事件即时解锁;刷新后也保持解锁,因为凭据更新时间晚于记录的鉴权失败时间)。「重试」按钮可手动清除该状态再试一次(key 仍无效时会重新变灰),一次成功的请求总会清除该状态,「新建会话」仍作为跳到全新草稿的出口。禁用态的输入框保留草稿且可选中——发送失败的长消息仍能复制出来。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 0bee8ba2..f9c4ca6e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2355,6 +2355,21 @@ export interface ContextToolShare {
tokens: number;
}
+/**
+ * One file's share of the context: its `read_file` / `edit_file` / `write_file` calls plus their
+ * results, keyed by the file each call named.
+ */
+export interface ContextFileShare {
+ /**
+ * Workspace-relative when the file is inside the Session's Workspace; otherwise absolute, with
+ * the home directory shortened to `~`. Spellings that resolve to the same file are one row.
+ */
+ path: string;
+ tokens: number;
+ /** How many calls of each file tool named the file in this context. */
+ ops: { read: number; edit: number; write: number };
+}
+
/**
* What the Session's current model context is made of — the part derived from its messages.
*
@@ -2365,7 +2380,8 @@ export interface ContextToolShare {
*
* The six parts partition the context and sum to `total`; `topTools` is a ranking inside
* `toolRequests + toolResults` and can sum to less than those two (a result whose call was not
- * recorded in the same Trace shard has no tool to be attributed to).
+ * recorded in the same Trace shard has no tool to be attributed to). `topFiles` is the same
+ * ranking narrowed to the three file tools and keyed by the file each call named.
*/
export interface SessionContextParts {
systemPrompt: number;
@@ -2378,6 +2394,8 @@ export interface SessionContextParts {
total: number;
/** Tools ranked by the context their traffic occupies, descending; at most five. */
topTools: ContextToolShare[];
+ /** Files ranked by the context their file-tool traffic occupies, descending; at most five. */
+ topFiles: ContextFileShare[];
/**
* A completed compaction closed the context these figures describe, and the next one has not
* been written yet: the composition is of what was compacted away, not of what the model now
diff --git a/packages/server/src/services/context-breakdown.ts b/packages/server/src/services/context-breakdown.ts
index 3259d6d0..40c7f487 100644
--- a/packages/server/src/services/context-breakdown.ts
+++ b/packages/server/src/services/context-breakdown.ts
@@ -1,7 +1,8 @@
/**
* Context composition: what the Session's current model context is made of, split into the six
* parts a reader can act on — system prompt, tool definitions, user messages, model messages,
- * tool requests, tool results — plus the tools whose call traffic occupies the most of it.
+ * tool requests, tool results — plus the tools whose call traffic occupies the most of it, and
+ * the files the three file tools spent the most of it on.
*
* The basis is **one Trace shard**. A shard is one complete model context by construction: the
* writer rotates on compaction and opens the new file with `session_meta` followed by
@@ -19,6 +20,8 @@
* read off the provider's `token_usage`. Every figure here is therefore an estimate; what it is
* good for is **shares**, which is what its consumers spend it on.
*/
+import os from "node:os";
+import path from "node:path";
import {
DEFAULT_MAX_CONTEXT_LENGTH,
approximateMessagesTokens,
@@ -32,10 +35,21 @@ import type {
ToolCallPayload,
ToolListReadyPayload,
} from "@prismshadow/penguin-core";
-import type { SessionContextParts } from "../api/types.js";
+import type { ContextFileShare, SessionContextParts } from "../api/types.js";
-/** How many tools the ranking names before the tail is dropped. */
-const TOP_TOOLS = 5;
+/** How many entries each ranking — tools, files — names before the tail is dropped. */
+const RANKING_SIZE = 5;
+
+/**
+ * The file tools, each by the op a call of it counts as. A Map, not an object literal: the key
+ * is a tool name off the wire, and a model that hallucinates a call to `toString` would find
+ * `Object.prototype`'s member through an index signature.
+ */
+const FILE_TOOL_OPS = new Map<string, keyof ContextFileShare["ops"]>([
+ ["read_file", "read"],
+ ["edit_file", "edit"],
+ ["write_file", "write"],
+]);
/** The answer for a Session with no Trace yet: measured as empty, not unknown. */
export function emptyContextBreakdown(): SessionContextParts {
@@ -48,6 +62,7 @@ export function emptyContextBreakdown(): SessionContextParts {
toolResults: 0,
total: 0,
topTools: [],
+ topFiles: [],
contextClosed: false,
};
}
@@ -56,6 +71,63 @@ function bump(per: Map<string, number>, name: string, tokens: number): void {
per.set(name, (per.get(name) ?? 0) + tokens);
}
+type FileRow = Pick<ContextFileShare, "tokens" | "ops">;
+
+function fileRow(per: Map<string, FileRow>, file: string): FileRow {
+ let row = per.get(file);
+ if (row === undefined) {
+ row = { tokens: 0, ops: { read: 0, edit: 0, write: 0 } };
+ per.set(file, row);
+ }
+ return row;
+}
+
+/**
+ * The file a file-tool call names, spelled the way the ranking shows it — or null when the call
+ * carries no usable `file_path` (arguments that never became valid JSON, a missing, empty or
+ * non-string value), which is a call the tool itself refused.
+ *
+ * The argument is resolved the way the file tools resolve it, against the Workspace, so `a.ts`,
+ * `./a.ts` and `<workspace>/a.ts` are one file and one row. A file inside the Workspace is
+ * shown relative to it; anything else is absolute, with the home directory shortened to `~`.
+ * Without a Workspace to resolve against (a shard with no `session_meta`), a relative path is
+ * shown as written.
+ */
+function fileDisplayPath(argumentsJson: string, workspace: string | undefined): string | null {
+ let args: unknown;
+ try {
+ args = JSON.parse(argumentsJson);
+ } catch {
+ return null;
+ }
+ const filePath =
+ typeof args === "object" && args !== null
+ ? (args as Record<string, unknown>)["file_path"]
+ : undefined;
+ if (typeof filePath !== "string" || filePath.length === 0) return null;
+ if (workspace === undefined) {
+ return path.isAbsolute(filePath)
+ ? shortenHome(path.normalize(filePath))
+ : path.normalize(filePath);
+ }
+ const absolute = path.resolve(workspace, filePath);
+ const rel = path.relative(workspace, absolute);
+ return isInside(rel) ? rel : shortenHome(absolute);
+}
+
+/** `~` for the home directory, the way a shell prints a path under it. */
+function shortenHome(absolute: string): string {
+ const home = os.homedir();
+ if (home === "") return absolute;
+ const rel = path.relative(home, absolute);
+ return isInside(rel) ? `~${path.sep}${rel}` : absolute;
+}
+
+/** True when a `path.relative` result stays under its base: not the base itself, not above it, not on another drive. */
+function isInside(rel: string): boolean {
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
+}
+
/**
* True when this shard's context was closed by a completed compaction — the same test Trace
* replay uses: the file's last record is a `compaction_end` reporting `completed`. Anything
@@ -75,6 +147,12 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
const perTool = new Map<string, number>();
/** tool_call_id -> tool name, so a result can be attributed to the tool that produced it. */
const callName = new Map<string, string>();
+ /** display path -> its file-tool calls plus their results, and how many calls of each kind. */
+ const perFile = new Map<string, FileRow>();
+ /** tool_call_id -> the file its call named, so a file tool's result reaches the same row. */
+ const callFile = new Map<string, string>();
+ /** The Workspace file paths are resolved against; recorded by the shard's `session_meta`, which precedes every call. */
+ let workspace: string | undefined;
let compacting = false;
for (const msg of messages) {
@@ -82,7 +160,9 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
// A per-shard invariant, not an accumulation: a resumed process writes its own copy into
// the shard it continues, and a rotation writes one at the head of the new file. The
// newest wins; adding them would count one system prompt several times.
- out.systemPrompt = approximateTokens((msg.payload as SessionMetaPayload).system_prompt ?? "");
+ const meta = msg.payload as SessionMetaPayload;
+ out.systemPrompt = approximateTokens(meta.system_prompt ?? "");
+ workspace = meta.workspace || undefined;
continue;
}
const p = msg.payload as { type?: string; role?: string };
@@ -122,6 +202,16 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
out.toolRequests += size;
callName.set(tc.tool_call_id, tc.name);
bump(perTool, tc.name, size);
+ const op = FILE_TOOL_OPS.get(tc.name);
+ if (op !== undefined) {
+ const file = fileDisplayPath(tc.arguments, workspace);
+ if (file !== null) {
+ callFile.set(tc.tool_call_id, file);
+ const row = fileRow(perFile, file);
+ row.tokens += size;
+ row.ops[op] += 1;
+ }
+ }
break;
}
case "tool_call_output": {
@@ -132,6 +222,8 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
// `toolRequests + toolResults`.
const name = callName.get(result.tool_call_id);
if (name !== undefined) bump(perTool, name, size);
+ const file = callFile.get(result.tool_call_id);
+ if (file !== undefined) fileRow(perFile, file).tokens += size;
break;
}
}
@@ -147,8 +239,12 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
out.topTools = [...perTool]
// Name breaks ties so equal-sized tools keep a stable order across calls.
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
- .slice(0, TOP_TOOLS)
+ .slice(0, RANKING_SIZE)
.map(([name, tokens]) => ({ name, tokens }));
+ out.topFiles = [...perFile]
+ .sort((a, b) => b[1].tokens - a[1].tokens || a[0].localeCompare(b[0]))
+ .slice(0, RANKING_SIZE)
+ .map(([file, row]) => ({ path: file, tokens: row.tokens, ops: row.ops }));
out.contextClosed = endsWithCompletedCompaction(messages);
return out;
}
diff --git a/packages/server/test/context-breakdown.test.ts b/packages/server/test/context-breakdown.test.ts
index bb8d46ac..26463529 100644
--- a/packages/server/test/context-breakdown.test.ts
+++ b/packages/server/test/context-breakdown.test.ts
@@ -1,9 +1,12 @@
/**
* Unit tests for the context composition: how a Trace shard's messages are split across the six
- * parts, how tool traffic is attributed to tool names, and which shard the service reads.
+ * parts, how tool traffic is attributed to tool names and file paths, and which shard the
+ * service reads.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
import {
approximateTokens,
assistantText,
@@ -127,6 +130,101 @@ describe("buildContextBreakdown", () => {
);
});
+ it("ranks files by their file-tool calls plus results, merging every spelling of one path", () => {
+ const b = buildContextBreakdown([
+ sessionMeta(metaPayload("prompt")),
+ // Three spellings of one file: relative, explicitly relative, absolute inside the Workspace.
+ toolCall({ name: "read_file", arguments: '{"file_path":"src/a.ts"}', toolCallId: "a1" }),
+ toolCallOutput({ output: "x".repeat(4000), toolCallId: "a1" }),
+ toolCall({
+ name: "edit_file",
+ arguments: '{"file_path":"./src/a.ts","old_string":"1","new_string":"2"}',
+ toolCallId: "a2",
+ }),
+ toolCallOutput({ output: "edited", toolCallId: "a2" }),
+ toolCall({
+ name: "write_file",
+ arguments: '{"file_path":"/data/ws/src/a.ts","content":"3"}',
+ toolCallId: "a3",
+ }),
+ toolCallOutput({ output: "written", toolCallId: "a3" }),
+ toolCall({ name: "read_file", arguments: '{"file_path":"README.md"}', toolCallId: "r1" }),
+ toolCallOutput({ output: "y".repeat(400), toolCallId: "r1" }),
+ toolCall({ name: "read_file", arguments: '{"file_path":"README.md"}', toolCallId: "r2" }),
+ toolCallOutput({ output: "y".repeat(400), toolCallId: "r2" }),
+ ]);
+ expect(b.topFiles.map((f) => f.path)).toEqual([path.join("src", "a.ts"), "README.md"]);
+ expect(b.topFiles[0]!.ops).toEqual({ read: 1, edit: 1, write: 1 });
+ expect(b.topFiles[1]!.ops).toEqual({ read: 2, edit: 0, write: 0 });
+ expect(b.topFiles[0]!.tokens).toBeGreaterThan(b.topFiles[1]!.tokens);
+ // Calls and results both count, and the ranking never exceeds the two tool parts.
+ expect(b.topFiles.reduce((n, f) => n + f.tokens, 0)).toBeLessThanOrEqual(
+ b.toolRequests + b.toolResults,
+ );
+ });
+
+ it("shows a file relative to the Workspace, else absolute with the home directory as ~", () => {
+ const home = os.homedir();
+ const call = (id: string, filePath: string) => [
+ toolCall({
+ name: "read_file",
+ arguments: JSON.stringify({ file_path: filePath }),
+ toolCallId: id,
+ }),
+ toolCallOutput({ output: "1", toolCallId: id }),
+ ];
+ const b = buildContextBreakdown([
+ sessionMeta(metaPayload("prompt")),
+ ...call("in", "/data/ws/docs/../src/b.ts"),
+ ...call("home", path.join(home, "notes", "todo.md")),
+ ...call("abs", "/etc/hosts"),
+ // A sibling of the Workspace is outside it, however the call spells it.
+ ...call("sibling", "../other/c.ts"),
+ ]);
+ expect(new Set(b.topFiles.map((f) => f.path))).toEqual(
+ new Set([
+ path.join("src", "b.ts"),
+ `~${path.sep}${path.join("notes", "todo.md")}`,
+ path.resolve("/etc/hosts"),
+ path.resolve("/data/other/c.ts"),
+ ]),
+ );
+ });
+
+ it("skips a file-tool call with no usable file_path, and other tools' file_path", () => {
+ const b = buildContextBreakdown([
+ sessionMeta(metaPayload("prompt")),
+ toolCall({ name: "read_file", arguments: "{", toolCallId: "x1" }),
+ toolCallOutput({ output: "…", toolCallId: "x1" }),
+ toolCall({ name: "read_file", arguments: "{}", toolCallId: "x2" }),
+ toolCallOutput({ output: "…", toolCallId: "x2" }),
+ toolCall({ name: "edit_file", arguments: '{"file_path":""}', toolCallId: "x3" }),
+ toolCall({ name: "write_file", arguments: '{"file_path":7}', toolCallId: "x4" }),
+ toolCall({ name: "exec_command", arguments: '{"file_path":"src/a.ts"}', toolCallId: "x5" }),
+ toolCallOutput({ output: "…", toolCallId: "x5" }),
+ ]);
+ expect(b.topFiles).toEqual([]);
+ // The calls still count as tool traffic: only the file attribution is dropped.
+ expect(b.topTools.map((t) => t.name)).toContain("read_file");
+ expect(b.toolRequests).toBeGreaterThan(0);
+ });
+
+ it("names at most five files", () => {
+ const messages: OmniMessage[] = [sessionMeta(metaPayload("prompt"))];
+ for (let i = 0; i < 6; i++) {
+ messages.push(
+ toolCall({
+ name: "read_file",
+ arguments: JSON.stringify({ file_path: `f${i}.ts` }),
+ toolCallId: `f${i}`,
+ }),
+ toolCallOutput({ output: "z".repeat(100 * (i + 1)), toolCallId: `f${i}` }),
+ );
+ }
+ const b = buildContextBreakdown(messages);
+ expect(b.topFiles.map((f) => f.path)).toEqual(["f5.ts", "f4.ts", "f3.ts", "f2.ts", "f1.ts"]);
+ });
+
it("keeps the newest session_meta and tool_list_ready instead of adding a second copy", () => {
// A resumed process writes its own bootstrap pair into the shard it continues.
const once = buildContextBreakdown([sessionMeta(metaPayload("prompt")), toolListReady(TOOLS)]);
@@ -215,6 +313,7 @@ describe("TraceService.contextBreakdown", () => {
toolResults: 0,
total: 0,
topTools: [],
+ topFiles: [],
contextClosed: false,
});
});
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 2e92d1bc..320be96b 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -164,6 +164,16 @@ export function CloseButton({
/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */
export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";
+/**
+ * File glyphs, shared by every place a file operation is marked — the file summary card, the
+ * memory-changes card, the context panel's file ranking — so a read, an edit and a write look
+ * the same everywhere: a page with a folded corner, the same page with a plus (a full write),
+ * and a pencil (an in-place edit).
+ */
+export const FILE_ICON = "M6 3h8l4 4v14H6zM14 3v4h4";
+export const FILE_WRITE_ICON = "M6 3h8l4 4v14H6zM12 11v6M9 14h6";
+export const FILE_EDIT_ICON = "M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";
+
/**
* Activity trace (a flat line with one tall beat in it): work still going on behind the
* conversation — the background-task mark on a session row, the matching count in the chat
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index a7a2b762..fbb94bc3 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -211,7 +211,16 @@ export function AgentSettingsPage() {
try {
const res = await api.putAgentConfig(projectId, agentId, update);
setData(res);
- toastSuccess(S.agent.savedTakesEffect);
+ // Compaction is the one section core re-reads at every compaction checkpoint, so a save
+ // that changed nothing else lands on a running conversation right away; everything else
+ // still waits for that conversation's next context. The test is "only compaction", not
+ // "compaction among others" — a mixed save is only as immediate as its slowest field.
+ const changed = update.config ?? {};
+ const compactionOnly =
+ update.agentsMd === undefined &&
+ Object.keys(changed).length === 1 &&
+ changed.compaction !== undefined;
+ toastSuccess(compactionOnly ? S.agent.savedTakesEffectNow : S.agent.savedTakesEffect);
// Name/description changes affect the breadcrumb and list display; a builtin-tools
// change moves the card's tool count.
if (
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index b727faca..23a0d877 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -93,6 +93,7 @@ import { useLocale } from "../../state/locale";
import { useAuth } from "../../state/auth";
import { agentDisplayName } from "../../state/project";
import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
import { Dropdown } from "../../components/ui/dropdown";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { CheckIcon, ChevronDown } from "../../components/ui/icons";
@@ -124,6 +125,8 @@ import { isStopAction, midRunAction } from "./composer-send";
import { PAPERCLIP_ICON } from "./attached-files-banner";
import { FileDropZone } from "./drop-zone";
import { ContextGauge } from "./context-gauge";
+import { modelWindowBelowCompactionLimit } from "../../lib/context";
+import { toneStrip } from "../../lib/tone";
import { splitDroppedFiles } from "../../lib/file-drop";
import { splitBySize } from "../../lib/upload-limits";
@@ -762,6 +765,17 @@ export interface ComposerControl {
fillExample: (prompt: string, exampleSkills: readonly string[]) => void;
}
+/**
+ * Small-window notices already put down, keyed Session + model, for the rest of the tab session.
+ *
+ * Module state rather than storage: the notice reports a live mismatch between two settings, so
+ * a dismissal should not outlive the tab that saw it — reopening the app after changing either
+ * side deserves a fresh answer. Keyed by model as well as Session because switching the
+ * conversation onto another model is exactly the case where the mismatch may no longer hold, or
+ * may hold with different numbers.
+ */
+const dismissedWindowNotices = new Set<string>();
+
export function ChatInput({
status,
onSend,
@@ -786,6 +800,9 @@ export function ChatInput({
turnThinkingLevel,
onChangeTurnThinkingLevel,
contextWindow,
+ compactionLimit,
+ onChangeCompactionLimit,
+ onOpenAgentSettings,
contextNow,
contextStale = false,
sessionId,
@@ -929,6 +946,19 @@ export function ChatInput({
onChangeTurnThinkingLevel?: (level: string) => void;
/** Model's context window (from models config; when not configured, the ring's cap falls back to 128000 via resolveContextWindow). */
contextWindow?: number;
+ /**
+ * The Agent's CONFIGURED `compaction.max_context_length` (its seeded default when the config
+ * carries none), fetched by the parent alongside the Agent's thinking level. It gives the
+ * context ring the threshold it fills against, and it is the number the small-window notice
+ * below is judged against. Absent where no Agent config is at hand (the draft and subagent
+ * composers, and the moment before the fetch lands): the ring then falls back to the model
+ * window and the notice cannot be raised at all.
+ */
+ compactionLimit?: number;
+ /** Writes a new compaction threshold to the Session's Agent and re-reads `compactionLimit` from it: what the context panel's threshold cutter commits through. Absent wherever no Agent config is at hand, leaving the cutter a readout. */
+ onChangeCompactionLimit?: (maxContextLength: number) => Promise<void>;
+ /** Opens the Session Agent's settings, where the compaction threshold is edited: the small-window notice's action. */
+ onOpenAgentSettings?: () => void;
/** Current context usage (total of the most recent main-session Request). */
contextNow: number;
/** After a successful compaction, before the next regular Request reports usage: usage is **unknown** (not 0); the ring is drawn empty and the value shown as `—`. */
@@ -1240,6 +1270,31 @@ export function ChatInput({
const m = models?.find((x) => sameModelRef(x, modelRef));
return m ? modelLabel(m) : (modelRef?.modelId ?? "…");
})();
+ // The model cannot hold what the Agent is configured to compact at. Raised only in session
+ // state, where a Session id gives the dismissal a key and `/compact` is available to act on
+ // the advice; the draft composer has neither.
+ const windowNoticeKey =
+ sessionId !== undefined && modelRef
+ ? `${sessionId}\u0000${modelRef.provider}\u0000${modelRef.modelId}`
+ : null;
+ const [windowNoticeDismissed, setWindowNoticeDismissed] = useState(false);
+ // Re-read on every key change (a `/model` fork, a new Session) so a dismissal that belongs to
+ // another pairing never suppresses this one, and one that belongs to this pairing survives a
+ // trip away and back.
+ useEffect(() => {
+ setWindowNoticeDismissed(
+ windowNoticeKey !== null && dismissedWindowNotices.has(windowNoticeKey),
+ );
+ }, [windowNoticeKey]);
+ const windowNoticeOpen =
+ windowNoticeKey !== null &&
+ !windowNoticeDismissed &&
+ modelWindowBelowCompactionLimit(contextWindow, compactionLimit);
+ // The Agent the threshold confirmation is about to name. Its display name where it has one,
+ // else the id, which is the same fallback the `/agent` picker draws rows with.
+ const currentAgent = agents.find((a) => a.agentId === currentAgentId);
+ const currentAgentName = currentAgent?.name || (currentAgentId ?? "");
+
// Queued hint: shown after a successful steer until the message shows up in the stream
// (steeringDeliveredCount increases past the baseline captured at queue time) or the run
// stops being observable (task no longer running).
@@ -2179,6 +2234,41 @@ export function ChatInput({
</div>
)}
+ {/* The Agent's compaction threshold is above what this model can hold, so compaction fires
+ at the window's edge instead of at the number the user set. Amber rather than muted
+ body text like the notices below it: the other two describe what the composer is about
+ to do, this one asks for a settings change, and `attention` is the tone for a thing
+ waiting on the user. Dismissible, because keeping the threshold high on purpose is a
+ legitimate answer and a notice with no way down stops being read. */}
+ {windowNoticeOpen && contextWindow !== undefined && compactionLimit !== undefined && (
+ <div
+ className={`anim-fade mb-1 flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs ${toneStrip.attention}`}
+ >
+ <p className="min-w-0">
+ {S.chat.contextWindowUnderThreshold(
+ humanizeTokens(contextWindow),
+ humanizeTokens(compactionLimit),
+ )}
+ </p>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ size="sm"
+ onClick={() => {
+ if (windowNoticeKey !== null) dismissedWindowNotices.add(windowNoticeKey);
+ setWindowNoticeDismissed(true);
+ }}
+ >
+ {S.chat.contextWindowUnderThresholdDismiss}
+ </Button>
+ {onOpenAgentSettings && (
+ <Button size="sm" variant="primary" onClick={onOpenAgentSettings}>
+ {S.chat.contextWindowUnderThresholdAction}
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+
{/* When the model doesn't support viewing images directly: images still upload as usual,
and on send the server writes them to the session's scratchpad and appends the file
path into the message text (the model views them via read_file). A small note is
@@ -2592,7 +2682,10 @@ export function ChatInput({
now={contextNow}
unknown={contextStale}
{...(contextWindow !== undefined ? { window: contextWindow } : {})}
+ {...(compactionLimit !== undefined ? { compactionLimit } : {})}
{...(sessionId !== undefined ? { sessionId } : {})}
+ agentName={currentAgentName}
+ {...(onChangeCompactionLimit ? { onChangeCompactionLimit } : {})}
/>
)}
{/* Draft state: conversation-time thinking level (backed by Agent settings), docked left of the model selector. */}
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 9d3fc321..52082c77 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -33,6 +33,7 @@ import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
+import { configuredCompactionLimit } from "../../lib/context";
import { useDocumentTitle } from "../../lib/use-document-title";
import {
formatDateTime,
@@ -588,26 +589,74 @@ export function ChatPage() {
};
}, [projectId, selectedAgentId]);
- // The session Agent's configured thinking level ("" = unset/loading), via the same
- // agent-config endpoint the draft picker uses: the in-session picker DISPLAYS this while
- // the user hasn't picked a level (auto-follow — sending still omits the level until
- // touched, see turnThinkingLevel). Refetched when the session's Agent changes; a failed
- // fetch leaves it unset (the picker then shows an em dash until picked).
+ // Two readouts come off the session Agent's config, via the same agent-config endpoint the
+ // draft picker uses. The configured thinking level ("" = unset/loading) is what the in-session
+ // picker DISPLAYS while the user hasn't picked a level (auto-follow — sending still omits the
+ // level until touched, see turnThinkingLevel). The configured compaction threshold is the
+ // basis the composer's context ring fills against, and the number its small-window notice is
+ // judged against. A failed fetch leaves both unset (the picker shows an em dash until picked;
+ // the ring falls back to the model window and the notice stays down).
const [agentThinkingLevel, setAgentThinkingLevel] = useState("");
+ const [compactionLimit, setCompactionLimit] = useState<number | undefined>(undefined);
+ // Cleared on an Agent switch only. A plain refresh must not blank values that are about to
+ // come back unchanged: doing that inside the fetch effect would flash the thinking picker's
+ // em dash and drop the ring to the window basis on every refetch.
useEffect(() => {
setAgentThinkingLevel("");
+ setCompactionLimit(undefined);
+ }, [projectId, selectedAgentId]);
+ // Re-read on focus as well as on an Agent switch: the threshold is edited on another page, so
+ // the value this composer holds can go stale under it. Routing to the settings page and back
+ // remounts this page and refetches anyway; the focus listener covers the other tab editing the
+ // same Agent. (`models` has no such refresh — a model entry is not edited mid-conversation the
+ // way a threshold is, and it already listens for its own change event.)
+ const [agentConfigTick, setAgentConfigTick] = useState(0);
+ useEffect(() => {
+ const onFocus = () => setAgentConfigTick((n) => n + 1);
+ window.addEventListener("focus", onFocus);
+ return () => window.removeEventListener("focus", onFocus);
+ }, []);
+ useEffect(() => {
if (!projectId || !selectedAgentId) return;
let cancelled = false;
api
.getAgentConfig(projectId, selectedAgentId)
.then((res) => {
- if (!cancelled) setAgentThinkingLevel(res.config.model?.thinkingLevel ?? "");
+ if (cancelled) return;
+ setAgentThinkingLevel(res.config.model?.thinkingLevel ?? "");
+ setCompactionLimit(configuredCompactionLimit(res.config.compaction?.maxContextLength));
})
.catch(() => undefined);
return () => {
cancelled = true;
};
- }, [projectId, selectedAgentId]);
+ }, [projectId, selectedAgentId, agentConfigTick]);
+ /**
+ * Commits the threshold the context panel's cutter proposed, then re-reads the Agent config
+ * this page holds so the ring, the cutter and the small-window notice all move together.
+ *
+ * Compaction settings are re-read by the engine at every compaction checkpoint, so this
+ * applies to the conversation on screen without waiting for a rotation — which is what the
+ * toast says. Rejecting rather than swallowing the failure is what keeps the dialog open on
+ * the value the user typed.
+ */
+ const onChangeCompactionLimit = useCallback(
+ async (maxContextLength: number): Promise<void> => {
+ if (!projectId || !selectedAgentId) return;
+ try {
+ await api.putAgentConfig(projectId, selectedAgentId, {
+ config: { compaction: { maxContextLength } },
+ });
+ } catch (e) {
+ toastError(apiErrorText(e));
+ throw e;
+ }
+ setCompactionLimit(configuredCompactionLimit(maxContextLength));
+ setAgentConfigTick((n) => n + 1);
+ toastSuccess(S.chat.contextThresholdSaved(humanizeTokens(maxContextLength)));
+ },
+ [projectId, selectedAgentId],
+ );
// The Session list is paged: a deep-linked Session (old bookmark, cross-page jump) may sit
// beyond the loaded pages. Look it up directly and insert it before the auto-select effect
@@ -1653,6 +1702,9 @@ export function ChatPage() {
// Guarded: a mid-chat change stages behind the prefix-cache confirm dialog (issue #310).
onChangeTurnThinkingLevel={onPickTurnThinkingLevel}
{...(contextWindow !== undefined ? { contextWindow } : {})}
+ {...(compactionLimit !== undefined ? { compactionLimit } : {})}
+ onChangeCompactionLimit={onChangeCompactionLimit}
+ onOpenAgentSettings={() => navigate(`/agents/${selected.agentId}?tab=runtime`)}
contextNow={stream.model.stats.contextNow}
contextStale={stream.model.stats.contextStale}
sessionId={selected.sessionId}
diff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsx
index 916f37b0..7089ace5 100644
--- a/packages/web/src/features/chat/context-gauge.tsx
+++ b/packages/web/src/features/chat/context-gauge.tsx
@@ -2,10 +2,18 @@
* Context usage gauge in the composer toolbar, and the composition panel behind it.
*
* The resting state is the ring alone: a **single-colour** indicator of total occupancy (no
- * bucketing), turning amber past 80% and red past 95%. The exact `used/window` figures are not
+ * bucketing), turning amber past 80% and red past 95%. The exact `used/basis` figures are not
* printed beside it — the panel a click away leads with them, and hovering the ring names them
- * too. When the model has no `context_window` configured, resolveContextWindow falls back to
- * 128000 and the ring is drawn as usual, so the ratio always has a reference point.
+ * too.
+ *
+ * What it fills against is the **effective compaction threshold**, not the model window: the
+ * question a reader brings to this ring is how much room is left before the context is
+ * summarized away, and against a window that dwarfs the threshold every answer looks like
+ * "plenty" (64k used at a 128k threshold on a 1M window would draw 6% instead of 50%). The
+ * basis therefore comes from contextFillBasis, which caps the Agent's configured threshold by
+ * what the window leaves room for — exactly the derivation the Agent itself compacts at. Where
+ * no threshold applies it falls back to the window: compaction switched off, and a caller with
+ * no Agent config to give (the subagent composer).
*
* `unknown` (a compaction succeeded and the next regular Request has not reported usage yet)
* draws an empty ring. **Never a full-looking 0**: that would claim the context had been cleared
@@ -16,18 +24,35 @@
* Given a `sessionId` the ring becomes a button that discloses the panel, which answers what the
* ring cannot: what the context is full of. The server splits the Session's newest Trace shard —
* one shard is one complete model context — into six parts and ranks the tools whose traffic
- * occupies the most of it. Those figures come from a character heuristic, not a tokenizer (this
+ * occupies the most of it, and the files the file tools named; a switch above the ranking picks
+ * which of the two it lists. Those figures come from a character heuristic, not a tokenizer (this
* project bundles none), so only their **shares** are used: each part is drawn as its share of
* `now`, the measured occupancy the ring itself shows. The parts therefore always add up to the
* figure in the panel header, and the estimate's absolute error never reaches the display; the
* `~` on every derived value marks what is still an approximation.
*
- * The bar runs the full **context window**, so its filled run is the occupancy the ring shows and
- * a dashed mark says where compaction will fire — how much room is left before the context is
- * summarized away is the thing that decides what to do next. The parts subdivide that filled run;
- * their exact shares are the legend's job, since at low occupancy the run is only a few pixels
- * wide. Hovering a segment or its legend row links the two: the row lights up and the other
- * segments fade.
+ * The bar runs to the **model window**, not to the threshold the ring uses. The two answer
+ * different questions and each keeps its own scale: the ring says how close compaction is, the
+ * bar says how much model there is and where inside it the trigger sits — drawn as a dashed
+ * cutter at the effective threshold. Making both read the threshold cost the bar its only
+ * answer, since a bar that ends on the trigger point can no longer show the room past it. The
+ * header carries the ring's figures (`used / threshold`) and the bar names its own scale
+ * underneath itself, so neither number has to be inferred from the other. While the panel is open
+ * the server's own reading of the threshold wins over the client's: both come from the same
+ * derivation, so they differ only when the Agent's config changed after this page loaded. The
+ * parts subdivide the filled run; their exact shares are the legend's job, since at low
+ * occupancy the run is only a few pixels wide. Hovering a segment or its legend row links the
+ * two: the row lights up and the other segments fade.
+ *
+ * The cutter is also the control that moves the threshold. Dragging it (or focusing it and
+ * using the arrow keys) proposes a value on a 1,000-token lattice, and the release opens a
+ * confirmation carrying an editable number — a gesture this coarse must not write a
+ * configuration value on its own, and the dialog is also where a threshold above the window can
+ * be typed deliberately. Confirming writes the Agent's `compaction.max_context_length` and it
+ * applies to this conversation at once, without waiting for a compaction to rotate the context.
+ * While a proposal is in flight the panel's own dismissal stands down (see `gesture` below):
+ * Esc has to cancel the adjustment and then the dialog, and the dialog's overlay would
+ * otherwise read as a click outside the panel.
*
* The panel is portaled to document.body and positioned against viewport coordinates by
* usePortalPanel, so the composer's own overflow cannot clip it, and it closes on outside click /
@@ -35,15 +60,28 @@
* streaming reply leaves it open. It opens upward on its own: the composer sits at the bottom of
* the page, so there is never room below.
*/
-import { useEffect, useId, useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
+import type { RefObject } from "react";
import { createPortal } from "react-dom";
import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
import { getSessionContext } from "../../api/endpoints";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { Input } from "../../components/ui/input";
import { usePortalPanel } from "../../components/ui/use-portal-panel";
-import { resolveContextWindow } from "../../lib/context";
+import {
+ MIN_COMPACTION_THRESHOLD,
+ THRESHOLD_STEP,
+ contextFillBasis,
+ resolveContextWindow,
+ snapThreshold,
+ thresholdCappedByWindow,
+ thresholdFraction,
+ thresholdFromPointer,
+} from "../../lib/context";
import { formatPercent, humanizeTokens } from "../../lib/format";
import { S } from "../../lib/strings";
import { toneInk } from "../../lib/tone";
+import { usePointerDrag } from "../dock/use-pointer-drag";
import { contextComposition } from "./context-parts";
import type { ContextPartKey } from "./context-parts";
@@ -56,39 +94,124 @@ import type { ContextPartKey } from "./context-parts";
*/
const PANEL_WIDTH = 300;
const PANEL_MAX_WIDTH = "calc(100vw - 32px)";
-const PANEL_HEIGHT = 264;
+const PANEL_HEIGHT = 370;
+/**
+ * The cap usePortalPanel already assumes when it chooses a direction, made real: without it a
+ * panel taller than the space it was flipped into is simply cut off by the viewport, and its
+ * own scroll is exempt from the hook's close-on-scroll.
+ */
+const PANEL_MAX_HEIGHT = "70vh";
/** Smallest painted width (px) of the filled run, so a context with a few hundred tokens in it still shows a mark rather than nothing. */
const MIN_FILL_PX = 2;
-/** How far (px) the compaction mark runs past the bar top and bottom: a 9px dash inside the bar reads as a dot, an 18px one reads as dashed. */
+/** How far (px) the compaction cutter runs past the bar top and bottom: a 9px dash inside the bar reads as a dot, an 18px one reads as dashed. */
const MARK_OVERHANG_PX = 4;
+/** Width (px) of the cutter's pointer target, centred on its 1px line: a line is not something a pointer can be asked to hit. */
+const CUTTER_HIT_PX = 14;
+
+/** What Shift multiplies the arrow-key step by, so a 1M window is crossable without holding a key down. */
+const ARROW_MULTIPLIER = 10;
+
type PanelState =
{ status: "loading" } | { status: "failed" } | { status: "ready"; data: SessionContextResponse };
+/** Which Top 5 the panel's ranking lists. */
+type RankingView = "tools" | "files";
+
+/**
+ * The ranking view picked last, kept for the tab session: the panel unmounts on every close, and
+ * a reader comparing contexts should not have to flip back to Files each time it opens.
+ */
+let lastRankingView: RankingView = "tools";
+
+/** The switch's two buttons. The labels are thunks: `S` is a live binding swapped on locale change. */
+const RANKING_VIEWS: readonly { view: RankingView; label: () => string }[] = [
+ { view: "tools", label: () => S.chat.contextRankTools },
+ { view: "files", label: () => S.chat.contextRankFiles },
+];
+
export function ContextGauge({
now,
window: win,
+ compactionLimit,
unknown = false,
sessionId,
+ agentName,
+ onChangeCompactionLimit,
}: {
now: number;
window?: number;
+ /**
+ * The Agent's configured `compaction.max_context_length` (its seeded default when the config
+ * carries none). Omitting it makes the ring fill against the model window instead — which is
+ * what the subagent composer does: it has no Session-level Agent config at hand, and a ring
+ * measured against a threshold nobody supplied would be a made-up number.
+ */
+ compactionLimit?: number;
unknown?: boolean;
/** Enables the composition panel. Omitted where no Session-level endpoint can serve it (the subagent composer), leaving the ring a plain readout. */
sessionId?: string;
+ /** Names the Agent whose threshold the confirmation is about to change; only needed alongside `onChangeCompactionLimit`. */
+ agentName?: string;
+ /**
+ * Writes a new `compaction.max_context_length` to the Agent and re-reads the config this
+ * gauge was given, rejecting when the write failed (the caller reports it). Its absence
+ * leaves the cutter a readout: a composer with no Agent config to write back to must not
+ * offer to change one.
+ */
+ onChangeCompactionLimit?: (maxContextLength: number) => Promise<void>;
}) {
- const max = resolveContextWindow(win);
- const pct = unknown ? 0 : Math.min(1, now / max);
+ const basis = contextFillBasis(compactionLimit, win);
+ const windowTokens = resolveContextWindow(win);
+ const pct = unknown ? 0 : Math.min(1, now / basis);
const [open, setOpen] = useState(false);
+ // The threshold gesture, held here rather than inside the panel because the panel's own
+ // dismissal has to stand down while one is in flight: `usePortalPanel` takes Esc on the
+ // capture phase, so an Esc meant for the adjustment (or for the dialog above it) would
+ // otherwise close the panel first, and the dialog's overlay is an outside click as far as
+ // the panel is concerned.
+ const [pendingThreshold, setPendingThreshold] = useState<number | null>(null);
+ const [proposal, setProposal] = useState<number | null>(null);
+ const [savingThreshold, setSavingThreshold] = useState(false);
+ // Bumped after a successful write: the panel's data is a snapshot from when it opened, and
+ // its `compactionThreshold` would otherwise keep overriding the fresher value the config
+ // refetch just produced.
+ const [reloadTick, setReloadTick] = useState(0);
+ const gesture = pendingThreshold !== null || proposal !== null;
const panelId = useId();
+ // A gesture must not outlive the panel it was made in: an adjustment left pending would keep
+ // the panel's own dismissal suspended for as long as this composer is mounted. The cutter's
+ // blur cannot do this — closing the panel unmounts it rather than blurring it.
+ const closePanel = (): void => {
+ setOpen(false);
+ setPendingThreshold(null);
+ };
const { triggerRef, panelRef, position } = usePortalPanel({
- open,
- onClose: () => setOpen(false),
+ open: open && !gesture,
+ onClose: closePanel,
estimatedHeight: PANEL_HEIGHT,
panelWidth: PANEL_WIDTH,
});
+ // What the cutter stands on: the effective threshold, and nothing at all when compaction is
+ // off (no trigger point to draw) or no Agent config reached this composer. A threshold the
+ // window cannot reach still draws — pinned to the right edge by `thresholdFraction` — because
+ // the cutter is how such a threshold gets lowered.
+ const cutAt = compactionLimit !== undefined && compactionLimit > 0 ? basis : null;
+ const confirmThreshold = async (tokens: number): Promise<void> => {
+ if (!onChangeCompactionLimit) return;
+ setSavingThreshold(true);
+ try {
+ await onChangeCompactionLimit(tokens);
+ setProposal(null);
+ setReloadTick((n) => n + 1);
+ } catch {
+ // Reported by the caller; the dialog stays open on its edited value.
+ } finally {
+ setSavingThreshold(false);
+ }
+ };
const color =
unknown || pct <= 0.8
@@ -100,7 +223,7 @@ export function ContextGauge({
// was computed from, which is all the subagent composer's panel-less ring can offer.
const usageText = unknown
? S.chat.contextUnknown
- : `${S.chat.contextUsage} ${Math.round(pct * 100)}% · ${humanizeTokens(now)}/${humanizeTokens(max)}`;
+ : `${S.chat.contextUsage} ${Math.round(pct * 100)}% · ${humanizeTokens(now)}/${humanizeTokens(basis)}`;
const R = 5;
const C = 2 * Math.PI * R;
const gauge = (
@@ -149,7 +272,7 @@ export function ContextGauge({
aria-label={usageText}
aria-expanded={open}
aria-controls={panelId}
- onClick={() => setOpen((v) => !v)}
+ onClick={() => (open ? closePanel() : setOpen(true))}
className={`${shell} rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
>
{gauge}
@@ -169,13 +292,37 @@ export function ContextGauge({
left: position.left,
width: PANEL_WIDTH,
maxWidth: PANEL_MAX_WIDTH,
+ maxHeight: PANEL_MAX_HEIGHT,
}}
- className="anim-pop z-[60] rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900"
+ className="anim-pop z-[60] overflow-y-auto rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900"
>
- <ContextPanel sessionId={sessionId} now={now} max={max} pct={pct} unknown={unknown} />
+ <ContextPanel
+ sessionId={sessionId}
+ now={now}
+ fallbackBasis={basis}
+ windowTokens={windowTokens}
+ unknown={unknown}
+ cutAt={cutAt}
+ reloadTick={reloadTick}
+ editable={onChangeCompactionLimit !== undefined}
+ pendingThreshold={pendingThreshold}
+ onPendingThreshold={setPendingThreshold}
+ onProposeThreshold={(tokens) => setProposal(tokens)}
+ />
</div>,
document.body,
)}
+ {proposal !== null && (
+ <ThresholdDialog
+ agentName={agentName ?? ""}
+ current={cutAt ?? basis}
+ proposed={proposal}
+ contextWindow={win}
+ busy={savingThreshold}
+ onClose={() => setProposal(null)}
+ onConfirm={confirmThreshold}
+ />
+ )}
</>
);
}
@@ -183,24 +330,48 @@ export function ContextGauge({
function ContextPanel({
sessionId,
now,
- max,
- pct,
+ fallbackBasis,
+ windowTokens,
unknown,
+ cutAt,
+ reloadTick,
+ editable,
+ pendingThreshold,
+ onPendingThreshold,
+ onProposeThreshold,
}: {
sessionId: string;
now: number;
- max: number;
- pct: number;
+ /** The ring's own basis, shown until the server's reading of the threshold arrives. */
+ fallbackBasis: number;
+ /** The model's resolved context window: the bar's scale, and named beside the ratio when it is larger than the basis. */
+ windowTokens: number;
unknown: boolean;
+ /** The client's reading of the effective compaction threshold, or null when there is no cutter to draw. */
+ cutAt: number | null;
+ /** Changes when a threshold write lands, re-running the fetch so the snapshot below stops being older than the config. */
+ reloadTick: number;
+ /** Whether the cutter accepts a gesture at all. */
+ editable: boolean;
+ /** The value the cutter is being dragged (or arrowed) to, held by the gauge above. */
+ pendingThreshold: number | null;
+ onPendingThreshold: (tokens: number | null) => void;
+ onProposeThreshold: (tokens: number) => void;
}) {
// A snapshot taken when the panel opens (it only mounts while open), not a live counter: the
// endpoint re-reads a whole Trace shard, so polling it through a streaming run is not free.
// The figures in the header above stay live — they come from the ring's own props — so what
// holds still is the composition breakdown, for as long as the panel is left open.
const [state, setState] = useState<PanelState>({ status: "loading" });
- // Row id under the pointer — a part key, or `tool:<name>` for the ranking below. One piece of
- // state for both lists, so a hovered tool row cannot also dim the bar it has no segment in.
+ // Row id under the pointer — a part key, or `tool:<name>` / `file:<path>` for the ranking
+ // below. One piece of state for both lists, so a hovered ranking row cannot also dim the bar
+ // it has no segment in.
const [hovered, setHovered] = useState<string | null>(null);
+ const [ranking, setRanking] = useState<RankingView>(lastRankingView);
+ const pickRanking = (view: RankingView) => {
+ lastRankingView = view;
+ setRanking(view);
+ };
useEffect(() => {
let cancelled = false;
setState({ status: "loading" });
@@ -215,21 +386,30 @@ function ContextPanel({
return () => {
cancelled = true;
};
- }, [sessionId]);
+ }, [sessionId, reloadTick]);
const data = state.status === "ready" ? state.data : null;
+ // The server re-reads the Agent's config from disk when the panel opens, so its threshold is
+ // the fresher of the two; the client's is the same derivation over the config this page
+ // loaded with. Null means no threshold is in force (compaction off), and then the ring's own
+ // fallback — the window — is what both the header and the bar are drawn against.
+ const basis = data?.compactionThreshold ?? fallbackBasis;
+ const pct = Math.min(1, now / basis);
+ // The bar's own scale is the window, so its filled run is a different ratio from the header's.
+ const fill = Math.min(1, now / windowTokens);
+ // The server re-read the config when the panel opened, so its threshold is the fresher of the
+ // two — but it reports null both for "compaction off" and for "at or past the window", and the
+ // second of those still needs a cutter (pinned to the right edge) to lower it with. The
+ // client's value settles that case, and a write bumps `reloadTick` so this can never be the
+ // stale one.
+ const threshold = data?.compactionThreshold ?? cutAt;
+ const barRef = useRef<HTMLDivElement>(null);
// `contextClosed` is the server seeing what `unknown` reports from the stream: a completed
// compaction, and no measurement of the new context yet. Both say the occupancy is unknown
// rather than zero, so both render `—` instead of describing a context that no longer exists.
const unmeasured = unknown || data?.contextClosed === true;
const composition = data === null ? null : contextComposition(data, now);
const hoveredPart = composition?.parts.some((p) => p.key === hovered) ? hovered : null;
- // Only drawn when it falls inside the bar's scale; the server already returns null for a
- // Session whose compaction is off or whose threshold sits past the window.
- const compactAt =
- data !== null && data.compactionThreshold !== null && data.compactionThreshold < max
- ? data.compactionThreshold
- : null;
return (
<>
@@ -241,7 +421,7 @@ function ContextPanel({
</span>
</span>
<span className="font-mono text-gray-500 dark:text-gray-400">
- {unmeasured ? "—" : humanizeTokens(now)} / {humanizeTokens(max)}
+ {unmeasured ? "—" : humanizeTokens(now)} / {humanizeTokens(basis)}
</span>
</div>
@@ -257,51 +437,67 @@ function ContextPanel({
<p className="mt-2 text-gray-400 dark:text-gray-500">{S.chat.contextBreakdownEmpty}</p>
) : (
<>
- {/* The bar's scale is the whole window: the filled run is the occupancy, the rest is
- headroom, and the dashed mark is where compaction fires. Squared off, and with no
- gaps between the fills — once the bar carries an absolute position scale, a surface
- gap would push every fill after it off the coordinate the mark is drawn on. What
- keeps neighbouring hues apart is the palette's own adjacent-pair separation.
- Decorative: the legend below carries every figure, which is why the bar is hidden
- from assistive tech and offers hover rather than focus. */}
+ {/* The bar's scale is the model window: the filled run is the occupancy, the rest is
+ the room the model still has, and the dashed cutter is where compaction fires.
+ Squared off, and with no gaps between the fills — the bar carries an absolute
+ position scale, so a surface gap would push every fill after it off the coordinate
+ the cutter is drawn on. What keeps neighbouring hues apart is the palette's own
+ adjacent-pair separation. The track is decorative (the legend below carries every
+ figure, which is why it is hidden from assistive tech and offers hover rather than
+ focus); the cutter beside it is not, and it is a focusable control, which is why
+ `aria-hidden` sits on the track alone and never on the box that holds both. */}
<div
- aria-hidden
- className="relative mt-2 h-2 bg-gray-200 dark:bg-gray-800"
+ ref={barRef}
+ className="relative mt-2 h-2"
style={{ marginBottom: MARK_OVERHANG_PX }}
>
- <div
- className="absolute inset-y-0 left-0 flex overflow-hidden"
- style={{ width: `${(now / max) * 100}%`, minWidth: now > 0 ? MIN_FILL_PX : 0 }}
- >
- {composition.parts.map((p) =>
- p.tokens > 0 ? (
- <span
- key={p.key}
- title={`${PART_LABELS[p.key]()} ~${humanizeTokens(p.tokens)} · ${p.percent}%`}
- onMouseEnter={() => setHovered(p.key)}
- onMouseLeave={() => setHovered(null)}
- style={{ flexGrow: p.tokens, flexBasis: 0 }}
- className={`h-full transition-opacity duration-150 ${p.color} ${
- hoveredPart !== null && hoveredPart !== p.key ? "opacity-25" : ""
- }`}
- />
- ) : null,
- )}
+ <div aria-hidden className="absolute inset-0 bg-gray-200 dark:bg-gray-800">
+ <div
+ className="absolute inset-y-0 left-0 flex overflow-hidden"
+ style={{ width: `${fill * 100}%`, minWidth: now > 0 ? MIN_FILL_PX : 0 }}
+ >
+ {composition.parts.map((p) =>
+ p.tokens > 0 ? (
+ <span
+ key={p.key}
+ title={`${PART_LABELS[p.key]()} ~${humanizeTokens(p.tokens)} · ${p.percent}%`}
+ onMouseEnter={() => setHovered(p.key)}
+ onMouseLeave={() => setHovered(null)}
+ style={{ flexGrow: p.tokens, flexBasis: 0 }}
+ className={`h-full transition-opacity duration-150 ${p.color} ${
+ hoveredPart !== null && hoveredPart !== p.key ? "opacity-25" : ""
+ }`}
+ />
+ ) : null,
+ )}
+ </div>
</div>
- {compactAt !== null && (
- <span
- title={S.chat.contextCompactAt(humanizeTokens(compactAt))}
- style={{
- left: `${(compactAt / max) * 100}%`,
- top: -MARK_OVERHANG_PX,
- bottom: -MARK_OVERHANG_PX,
- }}
- className="absolute border-l border-dashed border-gray-500 dark:border-gray-400"
+ {threshold !== null && (
+ <ThresholdCutter
+ barRef={barRef}
+ threshold={threshold}
+ windowTokens={windowTokens}
+ editable={editable}
+ pending={pendingThreshold}
+ onPending={onPendingThreshold}
+ onPropose={onProposeThreshold}
/>
)}
</div>
+ {/* The bar's scale, spelled out: the header's ratio is measured against the compaction
+ threshold, so without this the number the bar actually runs to appears nowhere. It
+ sits with the bar rather than with the legend below, and it goes invisible — not
+ away, so nothing shifts — while a threshold gesture is running, because the
+ cutter's pending value hangs into exactly this row. */}
+ <p
+ className={`mt-1 text-right font-mono text-gray-400 dark:text-gray-500 ${
+ pendingThreshold !== null ? "invisible" : ""
+ }`}
+ >
+ {S.chat.contextWindowIs(humanizeTokens(windowTokens))}
+ </p>
- <ul className="mt-2 space-y-0.5">
+ <ul className="mt-1.5 space-y-0.5">
{composition.parts.map((p) => (
<ShareRow
key={p.key}
@@ -317,25 +513,77 @@ function ContextPanel({
{composition.tools.length > 0 && (
<>
- <p
- title={S.chat.contextTopToolsHint}
- className="mt-2 border-t border-gray-100 pt-1.5 text-gray-400 dark:border-gray-800 dark:text-gray-500"
- >
- {S.chat.contextTopTools}
- </p>
- <ul className="mt-1 space-y-0.5">
- {composition.tools.map((t) => (
- <ShareRow
- key={t.name}
- label={t.name}
- mono
- tokens={t.tokens}
- percent={t.percent}
- highlighted={hovered === `tool:${t.name}`}
- onHover={(on) => setHovered(on ? `tool:${t.name}` : null)}
- />
- ))}
- </ul>
+ {/* The heading names the ranking on show and its tooltip says what it is ordered
+ by; the two text buttons beside it swap both, sized to the heading's own line so
+ the switch reads as part of it. A context with tool traffic but no file traffic
+ keeps the switch, so the Files view can say so itself. */}
+ <div className="mt-2 flex items-center justify-between gap-2 border-t border-gray-100 pt-1.5 dark:border-gray-800">
+ <p
+ title={
+ ranking === "tools" ? S.chat.contextTopToolsHint : S.chat.contextTopFilesHint
+ }
+ className="min-w-0 truncate text-gray-400 dark:text-gray-500"
+ >
+ {ranking === "tools" ? S.chat.contextTopTools : S.chat.contextTopFiles}
+ </p>
+ <div
+ role="group"
+ aria-label={S.chat.contextRankLabel}
+ className="flex shrink-0 items-center gap-0.5"
+ >
+ {RANKING_VIEWS.map(({ view, label }) => (
+ <button
+ key={view}
+ type="button"
+ aria-pressed={ranking === view}
+ onClick={() => pickRanking(view)}
+ className={`rounded px-1 text-xs leading-4 transition-colors duration-150 outline-none focus-visible:ring-2 focus-visible:ring-gray-400/60 ${
+ ranking === view
+ ? "font-medium text-gray-700 dark:text-gray-200"
+ : "text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
+ }`}
+ >
+ {label()}
+ </button>
+ ))}
+ </div>
+ </div>
+ {ranking === "tools" ? (
+ <ul className="mt-1 space-y-0.5">
+ {composition.tools.map((t) => (
+ <ShareRow
+ key={t.name}
+ label={t.name}
+ mono
+ tokens={t.tokens}
+ percent={t.percent}
+ highlighted={hovered === `tool:${t.name}`}
+ onHover={(on) => setHovered(on ? `tool:${t.name}` : null)}
+ />
+ ))}
+ </ul>
+ ) : composition.files.length === 0 ? (
+ <p className="mt-1 text-gray-400 dark:text-gray-500">
+ {S.chat.contextNoFileTraffic}
+ </p>
+ ) : (
+ <ul className="mt-1 space-y-0.5">
+ {composition.files.map((f) => (
+ <ShareRow
+ key={f.path}
+ label={f.name}
+ // Two files can share a name; the path settles which is which on hover
+ // rather than trailing after every row.
+ title={f.path}
+ mono
+ tokens={f.tokens}
+ percent={f.percent}
+ highlighted={hovered === `file:${f.path}`}
+ onHover={(on) => setHovered(on ? `file:${f.path}` : null)}
+ />
+ ))}
+ </ul>
+ )}
</>
)}
</>
@@ -344,6 +592,226 @@ function ContextPanel({
);
}
+/**
+ * The dashed mark on the bar at the effective compaction threshold — and the control that moves
+ * it. Two absolutely positioned children of the bar box: the line itself inside a comfortable
+ * pointer target, and the value being proposed while a gesture is running.
+ *
+ * The gesture is deliberately coarse and deliberately does not commit. It snaps to
+ * `THRESHOLD_STEP` because nobody means 127,431 tokens, it stops at the bar's own ends, and its
+ * release hands the value to a confirmation rather than writing it: a stray drag across a panel
+ * must not silently re-configure an Agent, and the dialog is where a threshold above the window
+ * can still be typed on purpose.
+ *
+ * Keyboard reaches the same place: `role="slider"` with the arrow keys on the same lattice
+ * (Shift takes ten steps), Enter for the release and Escape to abandon the adjustment. Escape
+ * gets to stop here rather than closing the panel because the gauge suspends the panel's own
+ * key handling while a proposal is pending. The pending value also lives up there, so the
+ * suspension and the mark can never disagree about whether a gesture is running.
+ */
+function ThresholdCutter({
+ barRef,
+ threshold,
+ windowTokens,
+ editable,
+ pending,
+ onPending,
+ onPropose,
+}: {
+ barRef: RefObject<HTMLDivElement | null>;
+ threshold: number;
+ windowTokens: number;
+ editable: boolean;
+ pending: number | null;
+ onPending: (tokens: number | null) => void;
+ onPropose: (tokens: number) => void;
+}) {
+ const [focused, setFocused] = useState(false);
+ const shown = pending ?? threshold;
+ // `usePointerDrag`'s onEnd fires in the same tick as the last onMove, before React has
+ // re-rendered with the new pending value, so the release reads it from a ref rather than from
+ // a closure that is one value behind.
+ const pendingRef = useRef(pending);
+ pendingRef.current = pending;
+
+ const drag = usePointerDrag<DOMRect>({
+ threshold: 3,
+ begin: (event) => {
+ const rect = barRef.current?.getBoundingClientRect() ?? null;
+ // Take focus on the press, so the arrow keys continue where the pointer left off.
+ if (rect) event.currentTarget.focus();
+ return rect;
+ },
+ onMove: (event, rect) => {
+ onPending(thresholdFromPointer(event.clientX, rect.left, rect.width, windowTokens));
+ },
+ onEnd: (_rect, dragged) => {
+ const proposed = pendingRef.current;
+ if (!dragged || proposed === null) return;
+ onPending(null);
+ onPropose(proposed);
+ },
+ onCancel: () => onPending(null),
+ });
+
+ const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
+ event.preventDefault();
+ const step = THRESHOLD_STEP * (event.shiftKey ? ARROW_MULTIPLIER : 1);
+ const from = pendingRef.current ?? threshold;
+ onPending(snapThreshold(from + (event.key === "ArrowRight" ? step : -step), windowTokens));
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ const proposed = pendingRef.current;
+ if (proposed === null) return;
+ onPending(null);
+ onPropose(proposed);
+ } else if (event.key === "Escape" && pendingRef.current !== null) {
+ event.preventDefault();
+ onPending(null);
+ }
+ };
+
+ const fraction = thresholdFraction(shown, windowTokens);
+ const active = pending !== null;
+ const lineColor =
+ active || focused
+ ? "border-gray-900 dark:border-gray-100"
+ : "border-gray-500 dark:border-gray-400";
+ const box = {
+ left: `${fraction * 100}%`,
+ marginLeft: -CUTTER_HIT_PX / 2,
+ width: CUTTER_HIT_PX,
+ top: -MARK_OVERHANG_PX,
+ bottom: -MARK_OVERHANG_PX,
+ };
+ const line = <span aria-hidden className={`h-full border-l border-dashed ${lineColor}`} />;
+ return (
+ <>
+ {editable ? (
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label={S.chat.contextThresholdCutter}
+ aria-valuemin={MIN_COMPACTION_THRESHOLD}
+ // A bogus `context_window` — small enough that core reads it as unconfigured and
+ // derives the threshold from the assumed default instead — can leave the threshold
+ // above the bar's own scale. The mark pins to the right edge; the announced range has
+ // to hold the announced value all the same.
+ aria-valuemax={Math.max(windowTokens, shown)}
+ aria-valuenow={shown}
+ aria-valuetext={humanizeTokens(shown)}
+ title={S.chat.contextThresholdHover(humanizeTokens(shown))}
+ onFocus={() => setFocused(true)}
+ onBlur={() => {
+ setFocused(false);
+ onPending(null);
+ }}
+ {...drag}
+ onKeyDown={onKeyDown}
+ style={box}
+ className="absolute flex cursor-ew-resize touch-none justify-center outline-none"
+ >
+ {line}
+ </div>
+ ) : (
+ // No config to write back to (the subagent composer): the mark is what it always was —
+ // decorative, naming the threshold on hover, and nothing to focus.
+ <div
+ aria-hidden
+ title={S.chat.contextThresholdHover(humanizeTokens(shown))}
+ style={box}
+ className="absolute flex justify-center"
+ >
+ {line}
+ </div>
+ )}
+ {/* The proposed value, anchored to whichever side keeps it inside the bar's box: a chip
+ centred on the cutter would hang past the panel's edge at either end, and the panel's
+ vertical scroll forces the horizontal axis to `auto`, so hanging past it means a
+ scrollbar under the whole panel rather than a chip that merely overlaps. */}
+ {active && (
+ <span
+ style={
+ fraction > 0.5 ? { right: `${(1 - fraction) * 100}%` } : { left: `${fraction * 100}%` }
+ }
+ className="absolute -bottom-5 rounded bg-gray-900 px-1 py-px font-mono text-[10px] whitespace-nowrap text-white dark:bg-gray-100 dark:text-gray-900"
+ >
+ {humanizeTokens(shown)}
+ </span>
+ )}
+ </>
+ );
+}
+
+/**
+ * The confirmation a released cutter opens: what the threshold is now, what it would become,
+ * and an editable number in case the drag landed near the intended value rather than on it.
+ *
+ * The field validates only what a threshold has to be — a whole number above zero. A value
+ * above the model window is accepted on purpose (the Agent may move to a roomier model later),
+ * and the hint says what the window will do to it in the meantime, naming the number rather
+ * than only warning that one exists.
+ */
+function ThresholdDialog({
+ agentName,
+ current,
+ proposed,
+ contextWindow,
+ busy,
+ onClose,
+ onConfirm,
+}: {
+ agentName: string;
+ /** The threshold being replaced, as it stands right now. */
+ current: number;
+ /** What the gesture proposed; the field opens on it and stays editable. */
+ proposed: number;
+ contextWindow: number | undefined;
+ busy: boolean;
+ onClose: () => void;
+ onConfirm: (tokens: number) => void;
+}) {
+ const [text, setText] = useState(String(proposed));
+ const trimmed = text.trim();
+ const valid = /^\d+$/.test(trimmed) && Number(trimmed) > 0;
+ const tokens = valid ? Number(trimmed) : 0;
+ const capped = valid ? thresholdCappedByWindow(tokens, contextWindow) : null;
+ return (
+ <ConfirmModal
+ open
+ title={S.chat.contextThresholdTitle}
+ tone="primary"
+ confirmLabel={S.common.save}
+ confirmDisabled={!valid}
+ busy={busy}
+ onClose={onClose}
+ onConfirm={() => {
+ if (valid) onConfirm(tokens);
+ }}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.chat.contextThresholdBody(agentName, humanizeTokens(current))}
+ </p>
+ <div className="mt-3">
+ <Input
+ label={S.chat.contextThresholdField}
+ type="text"
+ inputMode="numeric"
+ autoFocus
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ {...(valid
+ ? capped !== null
+ ? { hint: S.chat.contextThresholdCapped(humanizeTokens(capped)) }
+ : {}
+ : { error: S.chat.contextThresholdInvalid })}
+ />
+ </div>
+ </ConfirmModal>
+ );
+}
+
/** Part label lookups, read at render time: `S` is a live binding swapped on locale change. */
const PART_LABELS: Record<ContextPartKey, () => string> = {
systemPrompt: () => S.chat.contextPartSystemPrompt,
@@ -354,9 +822,10 @@ const PART_LABELS: Record<ContextPartKey, () => string> = {
toolResults: () => S.chat.contextPartToolResults,
};
-/** One `swatch · label · ~tokens · percent` line, shared by the six parts and the tool ranking. */
+/** One `swatch · label · ~tokens · percent` line, shared by the six parts and both rankings. */
function ShareRow({
label,
+ title,
swatch,
tokens,
percent,
@@ -365,10 +834,12 @@ function ShareRow({
onHover,
}: {
label: string;
- /** Legend colour of the matching bar segment; absent for the tool ranking, which has no segment. */
+ /** Tooltip of the label, when it should say more than the label does; the label is its own otherwise. */
+ title?: string;
+ /** Legend colour of the matching bar segment; absent for the rankings, which have no segment. */
swatch?: string;
tokens: number;
- /** Already a whole percent (apportioned for the parts, rounded for the tools) — not re-rounded here. */
+ /** Already a whole percent (apportioned for the parts, rounded for the rankings) — not re-rounded here. */
percent: number;
mono?: boolean;
highlighted?: boolean;
@@ -386,7 +857,7 @@ function ShareRow({
<span aria-hidden className={`h-2 w-2 shrink-0 rounded-[2px] ${swatch}`} />
)}
<span
- title={label}
+ title={title ?? label}
className={`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${mono ? "font-mono" : ""}`}
>
{label}
diff --git a/packages/web/src/features/chat/context-parts.ts b/packages/web/src/features/chat/context-parts.ts
index 6dd06780..2b8a9ac6 100644
--- a/packages/web/src/features/chat/context-parts.ts
+++ b/packages/web/src/features/chat/context-parts.ts
@@ -2,13 +2,13 @@
* Context composition rows: the server's estimated parts, re-expressed on the scale the context
* ring actually shows.
*
- * The server splits a Session's current model context into six parts and ranks the tools whose
- * traffic occupies the most of it, sizing everything with a character heuristic rather than a
- * tokenizer (this project bundles none). Taken as counts those figures would contradict the
- * ring, which reports the provider's own measurement; taken as **shares** they are exactly what
- * the ring cannot say. So each part is expressed as its share of the estimate, applied to `now`
- * — the parts add up to the occupancy in the panel header, and the estimate's absolute error
- * never reaches the display.
+ * The server splits a Session's current model context into six parts and ranks the tools, and
+ * the files the file tools named, whose traffic occupies the most of it, sizing everything with
+ * a character heuristic rather than a tokenizer (this project bundles none). Taken as counts
+ * those figures would contradict the ring, which reports the provider's own measurement; taken
+ * as **shares** they are exactly what the ring cannot say. So each part is expressed as its
+ * share of the estimate, applied to `now` — the parts add up to the occupancy in the panel
+ * header, and the estimate's absolute error never reaches the display.
*
* Pure, no React: unit-tested in test/context-parts.test.ts, rendered by context-gauge.tsx.
*/
@@ -55,10 +55,21 @@ export interface ContextToolShare extends ContextShare {
name: string;
}
+export interface ContextFileShare extends ContextShare {
+ /** The path as the server spells it: Workspace-relative inside the Workspace, else absolute with `~` for the home directory. */
+ path: string;
+ /** The last segment of `path`, and the whole of what the row prints — the path itself is the row's tooltip. */
+ name: string;
+ /** How many `read_file` / `edit_file` / `write_file` calls named the file. */
+ ops: { read: number; edit: number; write: number };
+}
+
export interface ContextComposition {
parts: ContextPartShare[];
/** Tools ranked by the context their calls and results occupy; their shares are of the whole context, so they do not sum to 100. */
tools: ContextToolShare[];
+ /** Files ranked the same way, over the three file tools' calls and results. */
+ files: ContextFileShare[];
}
/**
@@ -78,6 +89,10 @@ export function contextComposition(
// so they land on exactly the measured occupancy and exactly 100%.
const tokens = apportion(estimates, now);
const percents = apportion(estimates, 100);
+ const share = (estimate: number): ContextShare => ({
+ tokens: Math.round((estimate / data.total) * now),
+ percent: Math.round((estimate / data.total) * 100),
+ });
return {
parts: CONTEXT_PART_KEYS.map((key, i) => ({
key,
@@ -85,16 +100,30 @@ export function contextComposition(
tokens: tokens[i] ?? 0,
percent: percents[i] ?? 0,
})),
- // A ranking, not a partition: these are shares of the whole context and sum to less than it,
+ // Rankings, not partitions: these are shares of the whole context and sum to less than it,
// so there is nothing to apportion against — each is simply rounded.
- tools: data.topTools.map((t) => ({
- name: t.name,
- tokens: Math.round((t.tokens / data.total) * now),
- percent: Math.round((t.tokens / data.total) * 100),
+ tools: data.topTools.map((t) => ({ name: t.name, ...share(t.tokens) })),
+ files: data.topFiles.map((f) => ({
+ path: f.path,
+ name: splitFilePath(f.path).name,
+ ops: f.ops,
+ ...share(f.tokens),
})),
};
}
+/**
+ * Splits a path into its file name and the directory before it, on either separator — a
+ * Windows Workspace records backslashes, and the server keeps the platform's own spelling. The
+ * directory carries no trailing separator (`src/state` + `config.ts`); a bare file name has an
+ * empty one, and a file at the root keeps the root itself (`/` + `hosts`).
+ */
+export function splitFilePath(p: string): { name: string; dir: string } {
+ const cut = Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"));
+ if (cut < 0) return { name: p, dir: "" };
+ return { name: p.slice(cut + 1), dir: p.slice(0, Math.max(cut, 1)) };
+}
+
/**
* Splits `total` across `values` in proportion, as whole numbers that sum to exactly `total`
* (largest remainder: everyone takes their floor, and the leftover units go to the largest
diff --git a/packages/web/src/features/chat/memory-changes-card.tsx b/packages/web/src/features/chat/memory-changes-card.tsx
index b77a0de4..8e298935 100644
--- a/packages/web/src/features/chat/memory-changes-card.tsx
+++ b/packages/web/src/features/chat/memory-changes-card.tsx
@@ -17,15 +17,14 @@ import { ICON_SIZE } from "../../lib/icon-scale";
import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
import { memoryRowKey } from "../../lib/omni/memory-changes";
import { PathLabel } from "./message-files-card";
+import { FILE_EDIT_ICON, FILE_WRITE_ICON } from "../../components/ui/icons";
import { scopeGlyph } from "./memory-view";
const MAX_VISIBLE = 3;
-/** Open book (the card's mark, same as the Memory panel's), page-with-plus (full write), pencil (in-place edit). */
+/** Open book: the card's mark, same as the Memory panel's. */
const MEMORY_ICON =
"M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";
-const WRITE_ICON = "M6 3h8l4 4v14H6zM12 11v6M9 14h6";
-const EDIT_ICON = "M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";
export function MemoryChangesCard({
rows,
@@ -62,7 +61,10 @@ export function MemoryChangesCard({
title={row.op === "write" ? S.chat.memoryOpWrite : S.chat.memoryOpEdit}
className="shrink-0 text-gray-400"
>
- <GlyphIcon d={row.op === "write" ? WRITE_ICON : EDIT_ICON} size={ICON_SIZE.inlineGlyph} />
+ <GlyphIcon
+ d={row.op === "write" ? FILE_WRITE_ICON : FILE_EDIT_ICON}
+ size={ICON_SIZE.inlineGlyph}
+ />
</span>
</>
);
diff --git a/packages/web/src/features/chat/message-files-card.tsx b/packages/web/src/features/chat/message-files-card.tsx
index 6bc6ff56..f438dca8 100644
--- a/packages/web/src/features/chat/message-files-card.tsx
+++ b/packages/web/src/features/chat/message-files-card.tsx
@@ -16,12 +16,10 @@ import { useEffect, useMemo, useState } from "react";
import { S } from "../../lib/strings";
import { isFilePathLike, toWorkspaceRelative } from "../../lib/file-path";
import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { FILE_ICON } from "../../components/ui/icons";
import { Chevron } from "../../components/ui/chevron";
import { ICON_SIZE } from "../../lib/icon-scale";
-/** File glyph (a page with a folded corner), the card header's mark and each row's lead. */
-const FILE_ICON = "M6 3h8l4 4v14H6zM14 3v4h4";
-
const MAX_VISIBLE = 3;
/** Extracts file paths from inline code in raw Markdown (deduplicated, preserving order of appearance). */
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index 0c1512c8..932d8387 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -194,8 +194,19 @@ const TONE_CLASS: Record<SpeedTone, string> = {
*/
const refMapKey = (provider: string, modelId: string) => `${provider}\u0000${modelId}`;
-/** Default context window (tokens) for custom models when left unset. */
-const CUSTOM_CONTEXT_DEFAULT = 128000;
+/**
+ * Context window (tokens) recorded for a custom or user-group model whose field is left blank.
+ *
+ * A million, not the 128000 the rest of the app assumes for an *unknown* window. The two answer
+ * different questions: the assumption exists so a model with nothing on file still gets a
+ * conservative compaction threshold, while this is a value the dialog is about to WRITE, on an
+ * entry the user is adding by hand — and models being added by hand today are large-window ones.
+ * Guessing low there costs real capacity (the ring reads full, compaction fires early) for a
+ * model that can hold far more; guessing high costs a number the user narrows once, when the
+ * endpoint turns out to serve less. Preset entries left blank still mean "unknown" and stay
+ * blank.
+ */
+const CUSTOM_CONTEXT_DEFAULT = 1000000;
/** Numeric input filter: context window keeps digits only. */
export function digitsOnly(v: string): string {
diff --git a/packages/web/src/lib/context.ts b/packages/web/src/lib/context.ts
index d42ae136..bcf0b4a9 100644
--- a/packages/web/src/lib/context.ts
+++ b/packages/web/src/lib/context.ts
@@ -1,9 +1,29 @@
/**
- * Context window resolution: falls back to the default of 128000 when a
- * model has no `context_window` configured (or it resolves to a non-positive
- * value like `"unknown"`), giving the chat page and Trace page a consistent
- * upper bound for the context-usage ring.
+ * Context window resolution and the basis the composer's context ring fills against.
+ *
+ * Two different upper bounds live here, and confusing them is what this module exists to
+ * prevent. `resolveContextWindow` answers "how much can this model hold at all" and falls back
+ * to 128000 when a model entry has no `context_window`; it is what the Trace page's per-round
+ * donuts and the model readouts want. The composer's ring wants the other one: the point
+ * **compaction fires**, which is what decides whether to keep going or compact now. On a model
+ * whose window dwarfs the Agent's threshold the two are far apart — 64k used against a 128k
+ * threshold on a 1M window is half full, not 6% full — so the ring reads the threshold.
+ *
+ * The threshold arithmetic itself is core's (`effectiveMaxContextLength`), imported rather than
+ * restated: the number drawn here has to be the number the Agent actually compacts at, and two
+ * copies of that rule would eventually disagree.
+ *
+ * The panel's bar keeps the window as its scale, and marks the threshold on it with a draggable
+ * cutter; the second half of this module is that cutter's arithmetic — pointer position to
+ * proposed tokens, tokens to bar position, and what the window does to a value typed past it.
+ * It lives here rather than in the component because it is the part worth pinning down: a
+ * rounding or clamping mistake in a gesture that rewrites an Agent's configuration is not
+ * something a render test would catch.
*/
+import {
+ DEFAULT_MAX_CONTEXT_LENGTH,
+ effectiveMaxContextLength,
+} from "@prismshadow/penguin-core/context-limits";
/** Default upper bound when a model has no configured context window. */
export const DEFAULT_CONTEXT_WINDOW = 128000;
@@ -13,3 +33,131 @@ export function resolveContextWindow(x: number | string | undefined | null): num
const n = typeof x === "string" ? Number(x) : x;
return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : DEFAULT_CONTEXT_WINDOW;
}
+
+/**
+ * The Agent's configured compaction threshold, filling in the seeded default for a config that
+ * carries no `compaction.max_context_length` of its own — the same substitution core makes when
+ * it builds a Session's compaction settings, so the composer never reasons from a threshold the
+ * Agent does not actually run at.
+ *
+ * This is the CONFIGURED value, not the effective one: it is what the Agent settings page edits,
+ * and the only value the small-window notice below can be judged against.
+ */
+export function configuredCompactionLimit(maxContextLength: number | undefined): number {
+ return maxContextLength ?? DEFAULT_MAX_CONTEXT_LENGTH;
+}
+
+/**
+ * Upper bound the context ring, its panel header and its bar are all drawn against: the
+ * effective compaction threshold — the configured threshold capped by what the model's window
+ * leaves room for — so a full ring means "compaction is about to fire".
+ *
+ * Falls back to the resolved window in the two cases where no threshold applies: compaction
+ * switched off (`<= 0`), and a caller with no Agent config at hand (the subagent composer,
+ * and the moment before the config arrives), which passes `undefined`.
+ */
+export function contextFillBasis(
+ compactionLimit: number | undefined,
+ contextWindow: number | string | undefined | null,
+): number {
+ // Resolve first, then derive: core's own resolution only accepts a number, so a Trace-shaped
+ // numeric string would reach it as "unconfigured" and silently derive from 128000 instead.
+ const windowTokens = resolveContextWindow(contextWindow);
+ if (compactionLimit === undefined) return windowTokens;
+ const threshold = effectiveMaxContextLength(compactionLimit, windowTokens);
+ return threshold > 0 ? threshold : windowTokens;
+}
+
+/**
+ * Whether the selected model cannot hold what the Agent is configured to compact at: the model
+ * declares a window smaller than the Agent's configured `compaction.max_context_length`.
+ *
+ * Judged on the CONFIGURED threshold, never the effective one — the effective value is already
+ * capped by the window, so it can never exceed it and the question would never be asked. The
+ * situation is not fatal (compaction still fires at the capped point), but it means the
+ * threshold the user set is not the threshold in force, and lowering it below the window is
+ * what makes their number real again.
+ *
+ * False when the model has no configured window (nothing to compare) and when compaction is
+ * off (`<= 0`), where no threshold is in force to disagree with.
+ */
+export function modelWindowBelowCompactionLimit(
+ modelContextWindow: number | undefined,
+ compactionLimit: number | undefined,
+): boolean {
+ if (modelContextWindow === undefined || compactionLimit === undefined) return false;
+ return compactionLimit > 0 && modelContextWindow < compactionLimit;
+}
+
+/**
+ * Granularity of the panel's threshold cutter, in tokens. A threshold is a coarse quantity —
+ * nobody means 127,431 — so a drag and an arrow key both land on this lattice, which is also
+ * what makes a dragged value readable the moment it appears.
+ */
+export const THRESHOLD_STEP = 1000;
+
+/**
+ * Floor of the cutter's travel. One step, so the extreme left is on the same lattice as every
+ * other stop, and above all NOT zero: zero is the configured value that means "compaction off",
+ * and a gesture aimed at "compact very early" must never be read as "never compact". Switching
+ * compaction off stays an Agent-settings decision, where the field says what the value means.
+ */
+export const MIN_COMPACTION_THRESHOLD = THRESHOLD_STEP;
+
+/**
+ * Rounds a proposed threshold onto the step lattice and clamps it to the cutter's travel —
+ * `[MIN_COMPACTION_THRESHOLD, the model window]`.
+ *
+ * The upper clamp is applied AFTER rounding and is the window itself, not the nearest step
+ * below it: a 32768-token window would otherwise stop the cutter at 32,000 and leave the bar's
+ * right edge unreachable. Beyond the window is refused here because there is nothing to point
+ * at past the bar's end — the confirmation dialog's number field is where a threshold above the
+ * window is typed deliberately, and it says there what the window will do to it.
+ */
+export function snapThreshold(tokens: number, windowTokens: number): number {
+ const max = Math.max(windowTokens, MIN_COMPACTION_THRESHOLD);
+ const stepped = Math.round(tokens / THRESHOLD_STEP) * THRESHOLD_STEP;
+ return Math.min(Math.max(stepped, MIN_COMPACTION_THRESHOLD), max);
+}
+
+/**
+ * Where along the bar (0..1) a threshold is drawn. The bar's scale is the model window, so this
+ * is the plain ratio — clamped, because a threshold above the window has to pin the cutter to
+ * the right edge rather than leave the bar: the cutter is the control that lowers such a
+ * threshold, so it is the last thing that may disappear when the threshold is wrong.
+ */
+export function thresholdFraction(threshold: number, windowTokens: number): number {
+ if (!(windowTokens > 0)) return 0;
+ return Math.min(1, Math.max(0, threshold / windowTokens));
+}
+
+/**
+ * Pointer position to proposed threshold: the x coordinate is read against the bar's own box
+ * (viewport coordinates, as `getBoundingClientRect` gives them), turned into a fraction of the
+ * window, then snapped. A zero-width box — a bar measured while the panel is mid-animation —
+ * yields the floor rather than a NaN that would travel into the dialog.
+ */
+export function thresholdFromPointer(
+ pointerX: number,
+ barLeft: number,
+ barWidth: number,
+ windowTokens: number,
+): number {
+ if (!(barWidth > 0)) return MIN_COMPACTION_THRESHOLD;
+ const fraction = Math.min(1, Math.max(0, (pointerX - barLeft) / barWidth));
+ return snapThreshold(fraction * windowTokens, windowTokens);
+}
+
+/**
+ * The threshold actually in force for a value the user typed, when the model window cuts it
+ * down; null when the typed value is what will run. Feeds the dialog's hint, which has to name
+ * the number rather than only warn that one exists.
+ */
+export function thresholdCappedByWindow(
+ threshold: number,
+ contextWindow: number | string | undefined | null,
+): number | null {
+ const windowTokens = resolveContextWindow(contextWindow);
+ const effective = effectiveMaxContextLength(threshold, windowTokens);
+ return effective < threshold ? effective : null;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 6b3c50e1..e697d80f 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -478,6 +478,7 @@ export const en: Strings = {
agent: {
savedTakesEffect:
"Saved. New conversations pick it up right away; running ones after their next compaction.",
+ savedTakesEffectNow: "Saved. It takes effect immediately, including running conversations.",
takesEffectSuffix:
" — new conversations pick it up right away, running ones after their next compaction",
listTitle: "Agents",
@@ -1768,13 +1769,35 @@ Scenarios:
contextPartToolRequests: "Tool requests",
contextPartToolResults: "Tool results",
contextTopTools: "Top 5 tools",
- contextCompactAt: (n: string): string => `Compaction threshold ${n}`,
+ contextWindowIs: (n: string): string => `Max context ${n}`,
contextTopToolsHint:
"Ranked by the context each tool's calls and results occupy (definitions count under “Tool definitions”)",
+ contextTopFiles: "Top 5 files",
+ contextTopFilesHint:
+ "Ranked by the context each file's read_file / edit_file / write_file calls and results occupy; hover a row for the full path",
+ contextRankLabel: "Ranking",
+ contextRankTools: "Tools",
+ contextRankFiles: "Files",
+ contextNoFileTraffic: "No file traffic in this context",
contextUnknownHint:
"Just compacted — the next request reports the usage, and the composition with it",
contextBreakdownEmpty: "Nothing in the current context to break down yet",
contextBreakdownFailed: "Could not read the context composition",
+ contextThresholdCutter: "Compaction threshold",
+ contextThresholdHover: (n: string): string => `Compaction threshold ${n} (drag to adjust)`,
+ contextThresholdTitle: "Change the compaction threshold",
+ contextThresholdBody: (agentName: string, old: string): string =>
+ `Change ${agentName}'s compaction threshold from ${old} to the value below? It takes effect immediately, including the running conversation.`,
+ contextThresholdField: "Compaction threshold (tokens)",
+ contextThresholdInvalid: "Must be a whole number above 0",
+ contextThresholdCapped: (n: string): string =>
+ `Above the model window — the threshold in force will be ${n}`,
+ contextThresholdSaved: (n: string): string =>
+ `Compaction threshold changed to ${n}; it applies immediately`,
+ contextWindowUnderThreshold: (n: string, m: string): string =>
+ `This model's context window ${n} is smaller than this agent's compaction threshold ${m}, so compaction actually fires at the edge of the window. Drag the dashed mark in the context panel, or set the threshold below the window in the agent settings — it applies immediately.`,
+ contextWindowUnderThresholdAction: "Open agent settings",
+ contextWindowUnderThresholdDismiss: "Dismiss",
slashHint: "Type / for commands",
switchAgent: "Hand off to another agent — opens a new session on send",
switchAgentTitle: "Choose agent",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 3233e642..86017616 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -471,6 +471,8 @@ export const zh = {
* next compaction; a new conversation starts with it.
*/
savedTakesEffect: "已保存。新对话立即生效;进行中的对话在下一次压缩后生效。",
+ /** Save feedback when the change touched compaction settings only: the engine re-reads them at every compaction checkpoint, so a running conversation does not have to reach one first. */
+ savedTakesEffectNow: "已保存,立即生效(包括进行中的对话)。",
/** Appended to an action's own toast (skill install / uninstall) — same timing statement. */
takesEffectSuffix: ";新对话立即生效,进行中的对话在下一次压缩后生效",
listTitle: "Agents",
@@ -1740,12 +1742,36 @@ Benchmark:
contextPartToolRequests: "工具请求",
contextPartToolResults: "工具结果",
contextTopTools: "工具用量 Top 5",
- /** Tooltip of the dashed mark on the context bar; n = the humanized threshold. */
- contextCompactAt: (n: string): string => `压缩阈值 ${n}`,
+ /** Under the bar: the model window the bar is scaled to. */
+ contextWindowIs: (n: string): string => `最大上下文 ${n}`,
contextTopToolsHint: "按每个工具的调用与结果所占上下文排序(工具定义计入「工具定义」一项)",
+ contextTopFiles: "文件用量 Top 5",
+ contextTopFilesHint:
+ "按每个文件经 read_file / edit_file / write_file 的调用与结果所占上下文排序(悬停显示完整路径)",
+ /** The ranking switch: the group's accessible name, its two buttons, and the Files view's empty state. */
+ contextRankLabel: "切换排行",
+ contextRankTools: "工具",
+ contextRankFiles: "文件",
+ contextNoFileTraffic: "本轮上下文没有文件读写",
contextUnknownHint: "刚压缩过,占用待下次请求回报,届时才能给出构成",
contextBreakdownEmpty: "当前上下文还没有可统计的内容",
contextBreakdownFailed: "读取上下文构成失败",
+ /** The dashed cutter on the panel's bar: its accessible name, and its tooltip naming the threshold it stands on. */
+ contextThresholdCutter: "压缩阈值",
+ contextThresholdHover: (n: string): string => `压缩阈值 ${n}(拖动可调整)`,
+ /** Confirmation for a dragged (or arrowed) threshold: dialog name, body (agent name + the threshold being replaced), the editable field and its rejection, the note when the model window will cut the typed value down, and the toast on success. */
+ contextThresholdTitle: "修改压缩阈值",
+ contextThresholdBody: (agentName: string, old: string): string =>
+ `把 ${agentName} 的压缩阈值从 ${old} 改为下面的值?立即生效,包括正在进行的对话。`,
+ contextThresholdField: "压缩阈值(token)",
+ contextThresholdInvalid: "必须是大于 0 的整数",
+ contextThresholdCapped: (n: string): string => `超出模型窗口,实际生效的阈值是 ${n}`,
+ contextThresholdSaved: (n: string): string => `压缩阈值已改为 ${n},立即生效`,
+ /** Composer notice: the model's window is below the Agent's configured compaction threshold; n = window, m = threshold. */
+ contextWindowUnderThreshold: (n: string, m: string): string =>
+ `当前模型的上下文窗口 ${n} 小于本 Agent 的压缩阈值 ${m},压缩实际会在窗口边缘触发。拖动上下文面板里的虚线或在 Agent 设置中把阈值调到窗口以下,立即生效。`,
+ contextWindowUnderThresholdAction: "打开 Agent 设置",
+ contextWindowUnderThresholdDismiss: "忽略",
slashHint: "输入 / 使用命令",
/** `/agent` handoff: command description, picker title, search box, no-match hint, and the staged target's description and remove button. */
switchAgent: "交给其他 Agent,发送时开启新会话",
diff --git a/packages/web/test/context-parts.test.ts b/packages/web/test/context-parts.test.ts
index dfdea229..8734e3a4 100644
--- a/packages/web/test/context-parts.test.ts
+++ b/packages/web/test/context-parts.test.ts
@@ -4,7 +4,11 @@
*/
import { describe, expect, it } from "vitest";
import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
-import { CONTEXT_PART_KEYS, contextComposition } from "../src/features/chat/context-parts";
+import {
+ CONTEXT_PART_KEYS,
+ contextComposition,
+ splitFilePath,
+} from "../src/features/chat/context-parts";
import { CONTEXT_PART_COLORS } from "../src/lib/category-colors";
function response(over: Partial<SessionContextResponse> = {}): SessionContextResponse {
@@ -19,6 +23,7 @@ function response(over: Partial<SessionContextResponse> = {}): SessionContextRes
{ name: "read_file", tokens: 6000 },
{ name: "exec_command", tokens: 4000 },
],
+ topFiles: [],
contextClosed: false,
compactionThreshold: null,
...over,
@@ -84,6 +89,34 @@ describe("contextComposition", () => {
expect(c.tools.reduce((n, t) => n + t.percent, 0)).toBeLessThan(100);
});
+ it("scales the file ranking the same way and keeps each file's name for display", () => {
+ const c = contextComposition(
+ response({
+ topFiles: [
+ { path: "src/state/config.ts", tokens: 5000, ops: { read: 2, edit: 1, write: 0 } },
+ { path: "~/notes.md", tokens: 1000, ops: { read: 1, edit: 0, write: 0 } },
+ ],
+ }),
+ 50_000,
+ )!;
+ expect(c.files).toEqual([
+ {
+ path: "src/state/config.ts",
+ name: "config.ts",
+ ops: { read: 2, edit: 1, write: 0 },
+ tokens: 12_500,
+ percent: 25,
+ },
+ {
+ path: "~/notes.md",
+ name: "notes.md",
+ ops: { read: 1, edit: 0, write: 0 },
+ tokens: 2500,
+ percent: 5,
+ },
+ ]);
+ });
+
it("has nothing to break down for an empty estimate or a closed context", () => {
const empty = response({
systemPrompt: 0,
@@ -100,3 +133,13 @@ describe("contextComposition", () => {
expect(contextComposition(response({ contextClosed: true }), 50_000)).toBeNull();
});
});
+
+describe("splitFilePath", () => {
+ it("splits on either separator, keeping a root's own separator as the directory", () => {
+ expect(splitFilePath("src/state/config.ts")).toEqual({ name: "config.ts", dir: "src/state" });
+ expect(splitFilePath("C:\\ws\\src\\a.ts")).toEqual({ name: "a.ts", dir: "C:\\ws\\src" });
+ expect(splitFilePath("/etc/hosts")).toEqual({ name: "hosts", dir: "/etc" });
+ expect(splitFilePath("/hosts")).toEqual({ name: "hosts", dir: "/" });
+ expect(splitFilePath("README.md")).toEqual({ name: "README.md", dir: "" });
+ });
+});
diff --git a/packages/web/test/context.test.ts b/packages/web/test/context.test.ts
index 33144769..28e4cb96 100644
--- a/packages/web/test/context.test.ts
+++ b/packages/web/test/context.test.ts
@@ -1,10 +1,22 @@
/**
- * context.ts unit tests: context window cap resolution (used for the ring
- * cap display) — positive numbers are used as-is, otherwise fall back to
- * the default 128000.
+ * context.ts unit tests: the two upper bounds the app draws against — the model's context
+ * window (positive numbers as-is, otherwise the 128000 default) and the compaction threshold
+ * the composer's ring fills against — the small-window notice's predicate, and the arithmetic
+ * behind the context panel's threshold cutter (pointer to tokens, tokens to bar position).
*/
import { describe, expect, it } from "vitest";
-import { DEFAULT_CONTEXT_WINDOW, resolveContextWindow } from "../src/lib/context";
+import {
+ DEFAULT_CONTEXT_WINDOW,
+ MIN_COMPACTION_THRESHOLD,
+ configuredCompactionLimit,
+ contextFillBasis,
+ modelWindowBelowCompactionLimit,
+ resolveContextWindow,
+ snapThreshold,
+ thresholdCappedByWindow,
+ thresholdFraction,
+ thresholdFromPointer,
+} from "../src/lib/context";
describe("resolveContextWindow", () => {
it("positive numbers return as-is", () => {
@@ -29,3 +41,109 @@ describe("resolveContextWindow", () => {
expect(resolveContextWindow(Number.NaN)).toBe(128000);
});
});
+
+describe("configuredCompactionLimit", () => {
+ it("passes a configured threshold through and fills in core's seeded default for none", () => {
+ expect(configuredCompactionLimit(120000)).toBe(120000);
+ expect(configuredCompactionLimit(undefined)).toBe(256000);
+ // "Off" is a configured value like any other and must not be replaced by the default.
+ expect(configuredCompactionLimit(0)).toBe(0);
+ });
+});
+
+describe("contextFillBasis", () => {
+ it("is the threshold, not the window, when the window has room for it", () => {
+ // The case the ring exists for: a 1M-window model whose Agent compacts at 128k.
+ expect(contextFillBasis(128000, 1000000)).toBe(128000);
+ });
+
+ it("is the window minus the compaction headroom when the threshold does not fit", () => {
+ expect(contextFillBasis(256000, 32768)).toBe(32768 - 2048);
+ });
+
+ it("derives from the assumed 128000 window when the model has none", () => {
+ expect(contextFillBasis(256000, undefined)).toBe(128000 - 2048);
+ });
+
+ it("falls back to the window when compaction is off", () => {
+ expect(contextFillBasis(0, 200000)).toBe(200000);
+ expect(contextFillBasis(-1, undefined)).toBe(DEFAULT_CONTEXT_WINDOW);
+ });
+
+ it("falls back to the window when no Agent config is at hand (the subagent composer)", () => {
+ expect(contextFillBasis(undefined, 200000)).toBe(200000);
+ expect(contextFillBasis(undefined, undefined)).toBe(DEFAULT_CONTEXT_WINDOW);
+ });
+});
+
+describe("modelWindowBelowCompactionLimit", () => {
+ it("holds when the model cannot reach the Agent's configured threshold", () => {
+ expect(modelWindowBelowCompactionLimit(32768, 256000)).toBe(true);
+ });
+
+ it("does not hold when the window has room, or the two are equal", () => {
+ expect(modelWindowBelowCompactionLimit(1000000, 256000)).toBe(false);
+ expect(modelWindowBelowCompactionLimit(256000, 256000)).toBe(false);
+ });
+
+ it("stays down with nothing to compare: no window, no config, compaction off", () => {
+ expect(modelWindowBelowCompactionLimit(undefined, 256000)).toBe(false);
+ expect(modelWindowBelowCompactionLimit(32768, undefined)).toBe(false);
+ expect(modelWindowBelowCompactionLimit(32768, 0)).toBe(false);
+ });
+});
+
+describe("snapThreshold", () => {
+ it("rounds onto the 1,000-token lattice", () => {
+ expect(snapThreshold(127431, 1000000)).toBe(127000);
+ expect(snapThreshold(127500, 1000000)).toBe(128000);
+ });
+
+ it("never proposes 0 — that is the configured value meaning 'compaction off'", () => {
+ expect(snapThreshold(0, 1000000)).toBe(MIN_COMPACTION_THRESHOLD);
+ expect(snapThreshold(-50000, 1000000)).toBe(MIN_COMPACTION_THRESHOLD);
+ });
+
+ it("stops at the window itself, not at the nearest step below it", () => {
+ // A 32768 window would otherwise leave its own right edge unreachable at 32,000.
+ expect(snapThreshold(32768, 32768)).toBe(32768);
+ expect(snapThreshold(999999, 32768)).toBe(32768);
+ });
+});
+
+describe("thresholdFraction", () => {
+ it("is the plain ratio against the bar's window scale", () => {
+ expect(thresholdFraction(250000, 1000000)).toBe(0.25);
+ });
+
+ it("pins a threshold past the window to the right edge instead of dropping the cutter off the bar", () => {
+ expect(thresholdFraction(256000, 32768)).toBe(1);
+ expect(thresholdFraction(-1, 200000)).toBe(0);
+ });
+});
+
+describe("thresholdFromPointer", () => {
+ it("reads the pointer against the bar's box and snaps the result", () => {
+ // Half way along a 200px bar on a 1M window.
+ expect(thresholdFromPointer(140, 40, 200, 1000000)).toBe(500000);
+ });
+
+ it("clamps a pointer that ran off either end of the bar", () => {
+ expect(thresholdFromPointer(1000, 40, 200, 1000000)).toBe(1000000);
+ expect(thresholdFromPointer(-1000, 40, 200, 1000000)).toBe(MIN_COMPACTION_THRESHOLD);
+ });
+
+ it("an unmeasurable bar yields the floor rather than NaN", () => {
+ expect(thresholdFromPointer(140, 40, 0, 1000000)).toBe(MIN_COMPACTION_THRESHOLD);
+ });
+});
+
+describe("thresholdCappedByWindow", () => {
+ it("names the value actually in force when the window cuts the typed one down", () => {
+ expect(thresholdCappedByWindow(256000, 32768)).toBe(32768 - 2048);
+ });
+
+ it("is null when the typed value is what will run", () => {
+ expect(thresholdCappedByWindow(128000, 1000000)).toBeNull();
+ });
+});