A local-first multi-agent app development platform, built on PenguinHarness
feat(web): confirm mid-chat thinking-level switches to protect the prefix cache (#320)
Yaowei Zheng44addedb5fe8
diff --git a/changelog/unreleased/2026-08-18-thinking-switch-guard.md b/changelog/unreleased/2026-08-18-thinking-switch-guard.mdnew file mode 100644index 00000000..735a604c--- /dev/null+++ b/changelog/unreleased/2026-08-18-thinking-switch-guard.md@@ -0,0 +1,42 @@+# Web App: confirm a mid-chat thinking-level switch, and keep the picked level++- **Date:** 2026-08-18+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#320](https://github.com/Prism-Shadow/penguin-harness/pull/320)+- **Issue:** [#310](https://github.com/Prism-Shadow/penguin-harness/issues/310)++[中文版](2026-08-18-thinking-switch-guard.zh.md)++The active-session composer's thinking-level picker applied a pick silently, even in the middle of a long conversation where switching lowers the provider's prompt-cache hit rate and raises the cost of the next request. A pick that would change the level now opens the standard confirmation card, which says exactly that in one sentence and offers three choices. The picked level is also stored on the Session, so it no longer evaporates on reload.++## The dialog's three choices++- **Compact, then switch** — the recommended action, on the card's primary button. It starts a context compaction through the same path as the composer's `/compact` command and applies the new level once that compaction ends. A compaction that fails or is aborted still applies the level (the switch is what the user asked for) and says that the compaction did not finish, so nobody is left assuming the context was rewritten. Compaction can neither start nor queue while the session is busy, so this choice is disabled with a stated reason unless the conversation is idle, and the other two stay live.+- **Switch anyway** — a neutral button beside it that applies the pick immediately.+- **Cancel** — keeps the current level.++`POST /compact` answers `202` and the outcome arrives later over the stream, so the pick is held while the compaction runs — holding it is about order, not about a veto: a level applied mid-compaction would ride on anything sent in between and invalidate the very cache the compaction is there to shrink. `compactionTally` snapshots the settled and completed compactions at request time, `compactionSettledSince` reports how the next one ended, and `heldThinkingSwitch` turns that into the release decision (apply now, and with which notice). Counting rather than matching item ids keeps that correct across a stream reconnect.++## The picked level survives a reload++The level used to live in React state only: a refresh re-initialized the picker from the Agent config and the user's choice silently reverted. It is now a Session field.++- `sessions.thinking_level` (nullable, added through the existing `ensureColumn` upgrade path — no migration) backs a new `SessionInfo.thinkingLevel`, written with `PATCH /api/sessions/:sessionId { thinkingLevel }` (`none | low | medium | high | xhigh`, anything else is a 400).+- The server applies it to every run that carries no level of its own — tasks, queued follow-ups and goal runs alike, resolved at launch time in `SessionManager` — so the fallback chain becomes: the request's own level, then the Session's pinned level, then the Agent config's.+- Unset (the default for a new Session) keeps the previous behavior exactly: the picker displays the Agent config's level and auto-follows it, and runs fall back to it. Once pinned, an Agent-config edit no longer moves the session, which is the point of pinning it.++## When the dialog is skipped++- The conversation has no messages yet, so a brand-new session's initial selection stays free.+- The pick equals the level the picker already displays, which merely pins the level for the session.+- The transcript ends in a successful compaction, so whoever took the "compact, then switch" path is not warned a second time.++The draft picker (no session yet, writes through to the Agent settings) is unchanged.++## Details++- Guard, sequencing and display rules went into `thinking-level.ts` as pure functions — `prefixCacheAtRisk`, `needsThinkingSwitchConfirm`, `compactionTally`, `compactionSettledSince`, `heldThinkingSwitch`, `sessionThinkingLevel` — covered by unit tests, including that a failed compaction still switches and that a pinned level beats a changed Agent config.+- The shared `ConfirmModal` gained an optional third action (`secondaryLabel` plus `onSecondary`, rendered as a neutral button between Cancel and Confirm) and a `confirmDisabled` flag that greys out the primary button alone. Both default off, leaving the previous two-button card and its other call sites unchanged. The button row wraps, because three long labels do not fit one row in a phone-width bottom sheet.+- The server's `compacting` error code gained a localized message.+- The bilingual Web App and Server API docs describe the flow and the new field.diff --git a/changelog/unreleased/2026-08-18-thinking-switch-guard.zh.md b/changelog/unreleased/2026-08-18-thinking-switch-guard.zh.mdnew file mode 100644index 00000000..6c561fa0--- /dev/null+++ b/changelog/unreleased/2026-08-18-thinking-switch-guard.zh.md@@ -0,0 +1,42 @@+# Web App:会话中途切换思考等级需确认,且所选档位不再丢失++- **Date:** 2026-08-18+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#320](https://github.com/Prism-Shadow/penguin-harness/pull/320)+- **Issue:** [#310](https://github.com/Prism-Shadow/penguin-harness/issues/310)++[English](2026-08-18-thinking-switch-guard.md)++进行中会话输入区的思考等级拾取器原本直接应用所选档位,哪怕对话已经很长——而中途切换会降低服务商的提示词缓存命中率,抬高下一次请求的成本。现在,凡是会改变档位的选择都会弹出标准确认卡片,用一句话把这件事说清楚,并给出三个选择。所选档位同时落到 Session 上,刷新页面不再丢失。++## 对话框的三个选择++- **压缩后切换**——推荐操作,位于卡片的主按钮。它会沿输入区 `/compact` 命令相同的路径发起一次上下文压缩,并在压缩结束后应用新档位。压缩失败或被中断时档位照样切换(切换本来就是用户要的),同时提示压缩未成功完成,不会让人误以为上下文已被重写。会话繁忙时压缩既无法启动也不会排队,因此除非会话空闲,该选项会置灰并说明原因,另外两项照常可用。+- **仍要切换**——旁边的普通按钮,立即应用所选档位。+- **取消**——保持当前档位。++`POST /compact` 返回 `202`,结果稍后经流式通道送达,因此压缩期间所选档位被暂存——暂存是为了顺序,而不是为了否决:压缩进行到一半就应用新档位,会让这期间发出的任何消息带上新档位,正好毁掉这次压缩想要收缩的那份缓存。`compactionTally` 在发起请求时记下已结束与已成功的压缩计数,`compactionSettledSince` 判断新一次压缩如何收场,`heldThinkingSwitch` 据此给出释放决定(是否应用、附带哪种提示)。这里采用计数而非比对条目 id,是为了在流式重连后依然正确。++## 所选档位可跨刷新保留++档位此前只存在 React 状态里:刷新一次,拾取器就按 Agent 配置重新初始化,用户的选择被悄悄退回。现在它是 Session 的一个字段。++- 新增可空列 `sessions.thinking_level`(走既有的 `ensureColumn` 升级路径,无需迁移)支撑新的 `SessionInfo.thinkingLevel`,由 `PATCH /api/sessions/:sessionId { thinkingLevel }` 写入(`none | low | medium | high | xhigh`,其余取值 400)。+- 服务端会把它应用到所有自身未携带等级的运行——普通 Task、排队的跟进消息、目标模式运行一视同仁,均在启动时解析——于是回退链变为:请求自带的档位 → 该 Session 固定的档位 → Agent 配置的档位。+- 未固定(新会话的默认状态)与此前行为完全一致:拾取器显示并自动跟随 Agent 配置的档位,运行也回退到它。一旦固定,Agent 配置再改也不会带走这个会话——这正是固定的意义。++## 不弹框的情况++- 会话尚无消息,全新会话的初次选择照常自由选取。+- 所选档位与拾取器当前显示的一致,这只是把档位固定到本会话。+- 时间线以一次成功的压缩收尾,即走过「压缩后切换」路径的用户不会被二次提醒。++草稿态拾取器(尚未创建会话,直接写回 Agent 设置)保持原样。++## 细节++- 守卫、时序与显示规则以纯函数形式落在 `thinking-level.ts`——`prefixCacheAtRisk`、`needsThinkingSwitchConfirm`、`compactionTally`、`compactionSettledSince`、`heldThinkingSwitch`、`sessionThinkingLevel`——并配有单元测试,其中包括「压缩失败也照样切换」与「已固定的档位压过被改动的 Agent 配置」。+- 共享的 `ConfirmModal` 新增一个可选的第三操作(`secondaryLabel` 与 `onSecondary`,渲染为取消与确认之间的普通按钮),以及一个只置灰主按钮的 `confirmDisabled` 标志。两者默认关闭,原有的双按钮卡片与其余调用点均不受影响。按钮行改为可换行,因为三个长标签在手机宽度的底部弹层里排不进一行。+- 服务端的 `compacting` 错误码补上了本地化文案。+- Web App 与 Server API 双语文档记录了这套流程与新字段。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex b6b06e46..f5f2ea2a 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -179,7 +179,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| Method | Path | Description || --- | --- | --- || GET | / | Session info (the single-session GET additionally carries `tracePath`, the absolute path of the latest Trace file; list rows omit it) |-| PATCH | / | Update: `{approvalMode?, archived?, title?}` |+| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable): every later run that carries no level of its own uses it instead of the Agent config's, and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned) || DELETE | / | Delete the Session (along with its Traces and scratch files) || GET | /messages | Full OmniMessage history; while a Task runs the response also carries `live` (the in-progress stream tail, see below) || GET | /stream | SSE event stream (next section) |@@ -263,7 +263,7 @@ Key request bodies (explicit keys):interface TaskCreateRequest {input: TaskInputPart[];// Thinking level for this Task (a per-turn parameter, one of the five names; 400 otherwise);- // omitted = falls back to the Agent config+ // omitted = falls back to the Session's pinned level, then to the Agent configthinkingLevel?: "none" | "low" | "medium" | "high" | "xhigh";}type TaskInputPart =diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex cb9515d3..19456ab1 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -179,7 +179,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| 方法 | 路径 | 说明 || --- | --- | --- || GET | / | Session 信息(单会话 GET 额外携带 `tracePath`:最新 Trace 文件的绝对路径;列表行不含) |-| PATCH | / | 更新:`{approvalMode?, archived?, title?}` |+| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级固定在该 Session 上并持久化:此后凡是自身未携带等级的运行都改用它,而不再回落到 Agent 配置;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未固定) || DELETE | / | 删除 Session(连同 Trace 与暂存文件) || GET | /messages | 完整 OmniMessage 历史;Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) || GET | /stream | SSE 事件流(见下节) |@@ -261,7 +261,7 @@ GET /preview/<token>/<相对路径> (不鉴权,令牌即凭证// POST /api/sessions/:sessionId/tasks —— 发起一个 Taskinterface TaskCreateRequest {input: TaskInputPart[];- // 本次 Task 的思考等级(逐轮参数,五档之一;非法值 400);缺省 = 回退到 Agent 配置的档位+ // 本次 Task 的思考等级(逐轮参数,五档之一;非法值 400);缺省 = 先回退到该 Session 固定的档位,再回退到 Agent 配置thinkingLevel?: "none" | "low" | "medium" | "high" | "xhigh";}type TaskInputPart =diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex dcc8b208..8648eff3 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -33,7 +33,7 @@ The interface language (中文 / English / system) and theme (light / dark / sys### Creating a Conversation-A new conversation starts as a draft: pick the Agent, the Workspace (via a server-side directory browser), the approval mode, the model, and the thinking level before sending the first message. The Session is created on first send, and from then on its model and Workspace are locked. Switching the thinking level or the model in the draft makes the switched-to value the new default: the level is written back to the selected Agent's `model.thinking_level` immediately, and the picked model carries over as the next conversation's default. Inside an active session the thinking level is a per-turn parameter: the composer's picker starts out showing the Agent config's level and auto-follows it until touched (sends omit the level, so config edits keep taking effect); a pick sticks for the session and rides on every subsequent send (never written back to the Agent config); the model stays locked per session — the `/model` command switches models the way the `/agent` handoff does: picking a model stages it as a chip in the composer, and **sending** opens a new session for the same Agent on the picked model, keeping the current Workspace, whose first message carries a `[model_switch_from]` source block (source session id, Trace file path, previous model) followed by whatever the composer held (an interface-language auto-line when empty). In the new session that block collapses into a "switched model" banner linking back to the source conversation, and the model reads the source Trace file itself when it needs the earlier history.+A new conversation starts as a draft: pick the Agent, the Workspace (via a server-side directory browser), the approval mode, the model, and the thinking level before sending the first message. The Session is created on first send, and from then on its model and Workspace are locked. Switching the thinking level or the model in the draft makes the switched-to value the new default: the level is written back to the selected Agent's `model.thinking_level` immediately, and the picked model carries over as the next conversation's default. Inside an active session the thinking level belongs to the session: the composer's picker starts out showing the Agent config's level and auto-follows it until touched (sends omit the level, so config edits keep taking effect); a pick is **stored on the Session itself**, so it survives a page reload and shows up in another tab, applies to every later run of that conversation — a later Agent-config edit no longer moves it — and is still never written back to the Agent config. Changing the level mid-chat asks first, because switching mid-conversation lowers the prompt-cache hit rate and raises cost — the dialog offers three choices: **Compact, then switch** (recommended — it compacts the context exactly like `/compact` and applies the level once that compaction ends; a compaction that fails or is aborted still applies the level, with a notice that it did not finish), **Switch anyway** (applies immediately), and Cancel (keeps the current level). A compaction can only start on an idle conversation, so while a task is running the first choice is disabled with a note explaining why, and the other two stay available. A conversation with no messages yet, a re-pick of the displayed level, or a switch right after a successful compaction applies directly without asking; the model stays locked per session — the `/model` command switches models the way the `/agent` handoff does: picking a model stages it as a chip in the composer, and **sending** opens a new session for the same Agent on the picked model, keeping the current Workspace, whose first message carries a `[model_switch_from]` source block (source session id, Trace file path, previous model) followed by whatever the composer held (an interface-language auto-line when empty). In the new session that block collapses into a "switched model" banner linking back to the source conversation, and the model reads the source Trace file itself when it needs the earlier history.There are four approval modes: `allow-all`, `deny-all`, `read-only` (only read-only tools pass), and `always-ask`. See [Tools and Approvals](/tools).diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 946b5aa5..27b13b8b 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -33,7 +33,7 @@ penguin web### 新建会话-新会话从草稿开始:先选择 Agent、Workspace(服务器端目录浏览器选取)、审批模式、模型与思考等级,再发送第一条消息。Session 在首次发送时才真正创建,此后该会话的模型与 Workspace 即被锁定。草稿里切换思考等级或模型时,切换后的值即成为新的默认:思考等级立即写回所选 Agent 的 `model.thinking_level`,所选模型则作为下一个新会话的默认延续。进行中的会话里,思考等级是逐轮参数:输入区拾取器初始显示 Agent 配置的档位并自动跟随(未选择时发送不携带档位,配置修改持续生效),选定后即固定为该会话档位、随每次发送下发(不写回 Agent 配置);模型仍在会话内锁定,改用 `/model` 命令切换模型——与 `/agent` 交接同一方式:选中模型只是在输入框暂存为一枚 chip,**发送时**才在同一 Agent 下新建一个使用所选模型、沿用当前 Workspace 的会话并跳转,其首条消息携带 `[model_switch_from]` 源块(源会话 id、Trace 文件路径、原模型),输入框中的文字随之发出(为空时发一句界面语言的自动消息);新会话中该源块折叠为一条“已切换模型”横幅,可点击回到原会话,模型需要早前历史时按路径自行读取源 Trace 文件。+新会话从草稿开始:先选择 Agent、Workspace(服务器端目录浏览器选取)、审批模式、模型与思考等级,再发送第一条消息。Session 在首次发送时才真正创建,此后该会话的模型与 Workspace 即被锁定。草稿里切换思考等级或模型时,切换后的值即成为新的默认:思考等级立即写回所选 Agent 的 `model.thinking_level`,所选模型则作为下一个新会话的默认延续。进行中的会话里,思考等级属于该会话:输入区拾取器初始显示 Agent 配置的档位并自动跟随(未选择时发送不携带档位,配置修改持续生效);一旦选定,该档位**存在 Session 上**——刷新页面、换一个标签页打开都保持不变,此后该会话的每次运行都用它,Agent 配置再改也不会把它带走,同时依旧不写回 Agent 配置。会话中途切换思考等级会先弹确认框,因为中途切换会降低提示词缓存命中率、增加成本——确认框提供三种选择:**压缩后切换**(推荐,等同于先执行 `/compact` 压缩上下文,压缩结束后应用新档位;压缩失败或被中断时档位照样切换,并提示压缩未成功完成)、**仍要切换**(立即生效)与取消(保持当前档位)。压缩只能在会话空闲时启动,因此任务运行期间第一项会置灰并说明原因,另外两项照常可用。会话尚无消息、重选当前显示档位、或刚完成一次成功压缩后的切换则直接生效、不弹框;模型仍在会话内锁定,改用 `/model` 命令切换模型——与 `/agent` 交接同一方式:选中模型只是在输入框暂存为一枚 chip,**发送时**才在同一 Agent 下新建一个使用所选模型、沿用当前 Workspace 的会话并跳转,其首条消息携带 `[model_switch_from]` 源块(源会话 id、Trace 文件路径、原模型),输入框中的文字随之发出(为空时发一句界面语言的自动消息);新会话中该源块折叠为一条“已切换模型”横幅,可点击回到原会话,模型需要早前历史时按路径自行读取源 Trace 文件。审批模式共四种:`allow-all`(全部放行)、`deny-all`(全部拒绝)、`read-only`(仅放行只读工具)、`always-ask`(每次询问),详见[工具与审批](/tools)。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 8fc78585..03fda9f1 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -742,6 +742,14 @@ export interface SessionInfo {modelId: string;workspace: string;approvalMode: ApprovalMode;+ /**+ * Thinking level pinned for this Session (set via PATCH; the Web App's in-chat picker).+ * Unset = never pinned: runs that carry no level of their own fall back to the Agent+ * config's `model.thinking_level`, so config edits keep taking effect. Once pinned it+ * survives reloads and applies to every later run of this Session, and an Agent-config+ * change no longer moves it.+ */+ thinkingLevel?: ThinkingLevelName;/** Short title auto-generated by the model after the first turn; unset until generated (frontend shows "New Chat"). */title?: string;/** Session source (for list badges/folders), derived from core session_meta — the single source of truth (not stored in the DB); unset for user-created sessions. */@@ -845,6 +853,13 @@ export interface SessionResponse {export interface SessionPatchRequest {approvalMode?: ApprovalMode;+ /**+ * Pin this Session's thinking level (`none | low | medium | high | xhigh`, anything else+ * is a 400). It applies to every later run of the Session that doesn't carry its own+ * level, and replaces the Agent-config fallback for this Session. There is no unpin:+ * the picker only offers concrete levels.+ */+ thinkingLevel?: ThinkingLevelName;/** Archive / unarchive (default list hides archived). */archived?: boolean;/** Manual rename; non-empty string, overrides the auto-generated title. */@@ -958,8 +973,9 @@ export interface TaskCreateRequest {/*** Thinking level for this Task's LLM requests (a per-turn parameter; one of* `none | low | medium | high | xhigh`, anything else is a 400). Omitted = falls back to- * the session's default (the Agent config's `model.thinking_level`). A queued follow-up- * (`queueIfBusy`) keeps its level and applies it when it auto-starts.+ * the Session's pinned level (`SessionInfo.thinkingLevel`) and, when that is unset too,+ * to the Agent config's `model.thinking_level`. A queued follow-up (`queueIfBusy`) keeps+ * its level and applies it when it auto-starts.*/thinkingLevel?: ThinkingLevelName;/**diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.tsindex 9c75d673..b182940f 100644--- a/packages/server/src/db/database.ts+++ b/packages/server/src/db/database.ts@@ -29,6 +29,7 @@ export function openDatabase(dbPath: string): DatabaseSync {// schema.ts; drop entries only in a release allowed to break existing web.db files.ensureColumn(db, "sessions", "client", "TEXT");ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");+ ensureColumn(db, "sessions", "thinking_level", "TEXT");ensureColumn(db, "auth_sessions", "via", "TEXT");ensureColumn(db, "trace_files", "page_stats", "TEXT");// Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created ondiff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.tsindex da933264..db5525a9 100644--- a/packages/server/src/db/repos/sessions.ts+++ b/packages/server/src/db/repos/sessions.ts@@ -3,6 +3,7 @@* Session index, approval mode, and auto-generated title; Session-level routes use this to look up project ownership.*/import type { DatabaseSync } from "node:sqlite";+import type { ThinkingLevelName } from "@prismshadow/penguin-core/interfaces";import type { ApprovalMode } from "../../api/types.js";export interface SessionRow {@@ -15,6 +16,12 @@ export interface SessionRow {modelId: string;workspace: string;approvalMode: ApprovalMode;+ /**+ * Thinking level pinned for THIS session (PATCH /api/sessions/:id); NULL = not pinned,+ * so runs that carry no level of their own follow the Agent config as before. Sessions+ * are never inserted with one — pinning is an explicit act inside a live conversation.+ */+ thinkingLevel?: ThinkingLevelName | null;/** Auto-generated session title; NULL = not yet generated (frontend shows "New Conversation"). */title: string | null;/** Archive timestamp, ISO; NULL = not archived (omitting on insert defaults to NULL). */@@ -50,6 +57,7 @@ function mapRow(r: Record<string, unknown>): SessionRow {modelId: r.model_id as string,workspace: r.workspace as string,approvalMode: r.approval_mode as ApprovalMode,+ thinkingLevel: (r.thinking_level as ThinkingLevelName | null) ?? null,title: (r.title as string | null) ?? null,archivedAt: (r.archived_at as string | null) ?? null,client: (r.client as "web" | "cli" | null) ?? null,@@ -166,6 +174,13 @@ export class SessionsRepo {.run(mode, sessionId);}+ /** Pin the session's thinking level (runs without one of their own then use it). */+ updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void {+ this.db+ .prepare("UPDATE sessions SET thinking_level = ? WHERE session_id = ?")+ .run(level, sessionId);+ }+updateTitle(sessionId: string, title: string): void {this.db.prepare("UPDATE sessions SET title = ? WHERE session_id = ?").run(title, sessionId);}diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex 7e1105cf..b170fbfb 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -52,6 +52,7 @@ CREATE TABLE IF NOT EXISTS sessions (model_id TEXT NOT NULL, -- upstream model id (sent to AgentHub as-is; never concatenate <provider>/<id>)workspace TEXT NOT NULL,approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask+ thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh); NULL=not pinned, runs follow the Agent configtitle TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows "New chat")archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under "Archived")client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as webdiff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex caa622c2..19305fe6 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -419,6 +419,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const row = resolveSession(c);const body = await readJson(c);const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);+ const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVELS);const archivedRaw = (body as Record<string, unknown>).archived;const archived = typeof archivedRaw === "boolean" ? archivedRaw : undefined;const titleRaw = (body as Record<string, unknown>).title;@@ -436,11 +437,16 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {);}}- if (approvalMode === undefined && archived === undefined && title === undefined) {+ if (+ approvalMode === undefined &&+ thinkingLevel === undefined &&+ archived === undefined &&+ title === undefined+ ) {throw new HttpError(400,"no_update",- "No updatable field provided (approvalMode / archived / title).",+ "No updatable field provided (approvalMode / thinkingLevel / archived / title).",);}let updated: SessionRow = { ...row };@@ -454,6 +460,12 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {deps.sessionsRepo.updateApprovalMode(row.sessionId, approvalMode);updated = { ...updated, approvalMode };}+ if (thinkingLevel !== undefined) {+ // Takes effect from the next run on: launchTask/startGoal read the pinned level for+ // any run that carries none of its own (a run already in flight keeps its level).+ deps.sessionsRepo.updateThinkingLevel(row.sessionId, thinkingLevel);+ updated = { ...updated, thinkingLevel };+ }if (archived !== undefined) {const at = archived ? new Date().toISOString() : null;deps.sessionsRepo.setArchived(row.sessionId, at);diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex a4ec4e90..ecd082b6 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -652,10 +652,12 @@ export class SessionManager {objective,budget: args.budget,});+ // Same fallback chain as a task: the goal's own level, else the Session's pinned one.+ const thinkingLevel = this.runThinkingLevel(entry.sessionId, args.thinkingLevel);const gen = this.goalStream(entry, {input: args.input,budget: args.budget,- ...(args.thinkingLevel !== undefined ? { thinkingLevel: args.thinkingLevel } : {}),+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),approve,signal: ac.signal,...(goalId !== undefined ? { goalId } : {}),@@ -762,11 +764,26 @@ export class SessionManager {}/** Shared task launch (fresh tasks and auto-started follow-ups): flips to running, publishes the input, and drives the run with the per-turn thinking level (if any). Caller holds the session lock and has verified idle. */+ /**+ * Thinking level for one run: the level the request carried wins, else the level pinned+ * on the Session row (PATCH /api/sessions/:id — the Web App's in-chat picker), else+ * undefined so core keeps falling back to the Agent config. Resolved at LAUNCH time, so+ * a queued follow-up that carried no level of its own picks up the pin as it stands when+ * it finally starts, and a pin set mid-run applies from the next run.+ */+ private runThinkingLevel(+ sessionId: string,+ requested?: ThinkingLevelName,+ ): ThinkingLevelName | undefined {+ return requested ?? this.deps.sessions.findById(sessionId)?.thinkingLevel ?? undefined;+ }+private launchTask(entry: RuntimeEntry,input: OmniMessage[],- thinkingLevel?: ThinkingLevelName,+ requestedThinkingLevel?: ThinkingLevelName,): void {+ const thinkingLevel = this.runThinkingLevel(entry.sessionId, requestedThinkingLevel);const channel = this.deps.channels.get(entry.sessionId);const ac = new AbortController();entry.status = "running";diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex e6db5bc6..5813f8f7 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -79,6 +79,7 @@ export class SessionService {modelId: row.modelId,workspace: row.workspace,approvalMode: row.approvalMode,+ ...(row.thinkingLevel ? { thinkingLevel: row.thinkingLevel } : {}),...(row.title !== null ? { title: row.title } : {}),...(source !== undefined ? { source } : {}),createdAt: row.createdAt,diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.tsindex c3fe8bfe..f25b21be 100644--- a/packages/server/test/session-index.test.ts+++ b/packages/server/test/session-index.test.ts@@ -1,7 +1,7 @@/*** Integration tests for the Session index: creation (default model / workspace- * guard), listing (DB union Trace directory discovery), PATCH approval mode,- * and createdAt parsing.+ * guard), listing (DB union Trace directory discovery), PATCH approval mode and+ * thinking level, and createdAt parsing.*/import fs from "node:fs/promises";import path from "node:path";@@ -574,6 +574,28 @@ describe("session-index", () => {).toBe(400);});+ it("PATCH thinking level pins it on the Session and reads back (survives a reload)", async () => {+ await configureModels();+ const { session } = (await (await api.post(base(), {})).json()) as SessionCreateResponse;+ // A fresh Session pins nothing: runs follow the Agent config (the field stays absent).+ expect(session.thinkingLevel).toBeUndefined();+ const patched = await api.patch(`/api/sessions/${session.sessionId}`, {+ thinkingLevel: "high",+ });+ expect(patched.status).toBe(200);+ expect(((await patched.json()) as SessionResponse).session.thinkingLevel).toBe("high");+ // Read back through a fresh GET — this is what a page reload sees.+ const got = (await (+ await api.get(`/api/sessions/${session.sessionId}`)+ ).json()) as SessionResponse;+ expect(got.session.thinkingLevel).toBe("high");+ // An invalid level returns 400, and an empty body still reports nothing to update.+ expect(+ (await api.patch(`/api/sessions/${session.sessionId}`, { thinkingLevel: "ultra" })).status,+ ).toBe(400);+ expect((await api.patch(`/api/sessions/${session.sessionId}`, {})).status).toBe(400);+ });+it("insertOrIgnore is idempotent: concurrent first discovery of one Session doesn't throw on the UNIQUE constraint", async () => {const createdAt = new Date().toISOString();const row = {diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.tsindex 31b2ec0a..1a65fe7e 100644--- a/packages/server/test/session-manager.test.ts+++ b/packages/server/test/session-manager.test.ts@@ -280,12 +280,43 @@ describe("session-manager", () => {const manager = makeManager(loaderOf(fake));await manager.startTask("session-1", [userText("a")], { thinkingLevel: "high" });await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 1);- // Omitted on the next Task: the session falls back to its default (nothing forwarded).+ // Omitted on the next Task, with nothing pinned on the Session row either: nothing is+ // forwarded and core falls back to the Agent config.await manager.startTask("session-1", [userText("b")]);await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 2);expect(seen).toEqual(["high", undefined]);});+ it("a level pinned on the Session applies to later Tasks that carry none (a request's own level still wins)", async () => {+ sessions.updateApprovalMode("session-1", "allow-all");+ const seen: (string | undefined)[] = [];+ const fake: RuntimeSession = {+ sessionId: "session-1",+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run(_input: OmniMessage[], opts: { thinkingLevel?: string }) {+ seen.push(opts.thinkingLevel);+ yield assistantText("ok");+ },+ async *compact(): AsyncGenerator<OmniMessage> {},+ };+ const manager = makeManager(loaderOf(fake));+ // What the Web App's in-chat picker writes (PATCH /api/sessions/:id).+ sessions.updateThinkingLevel("session-1", "xhigh");+ await manager.startTask("session-1", [userText("a")]);+ await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 1);+ await manager.startTask("session-1", [userText("b")], { thinkingLevel: "low" });+ await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 2);+ // Re-pinning applies from the next Task on.+ sessions.updateThinkingLevel("session-1", "medium");+ await manager.startTask("session-1", [userText("c")]);+ await waitFor(() => manager.statusOf("session-1") === "idle" && seen.length === 3);+ expect(seen).toEqual(["xhigh", "low", "medium"]);+ });+it("LLM / tool failures in the message stream are persisted via drive (source=llm / environment, with the current Session context)", async () => {sessions.updateApprovalMode("session-1", "allow-all");const captured: ErrorRecordArgs[] = [];diff --git a/packages/web/src/components/ui/confirm-modal.tsx b/packages/web/src/components/ui/confirm-modal.tsxindex 74737c8f..78f2a791 100644--- a/packages/web/src/components/ui/confirm-modal.tsx+++ b/packages/web/src/components/ui/confirm-modal.tsx@@ -6,6 +6,14 @@* danger (red) for deletions, primary for saves and other overwrites. The message* and any details (e.g. a version list) go in children; `title` only names the* dialog for assistive tech (never rendered).+ *+ * A dialog may add ONE extra choice (`secondaryLabel` + `onSecondary`) between Cancel+ * and Confirm — for prompts whose recommended path is the confirm button while a plain+ * "do it anyway" escape hatch has to stay one click away (the mid-chat thinking-level+ * switch: compact-then-switch / switch anyway / cancel). It stays the same card: a+ * neutral button in the same row, never a second primary. `confirmDisabled` covers the+ * case where that recommended action is temporarily unavailable — the body then says+ * why, and the other choices stay live.*/import { useState } from "react";import type { ReactNode } from "react";@@ -52,6 +60,9 @@ export function ConfirmModal({onClose,onConfirm,confirmLabel,+ confirmDisabled = false,+ secondaryLabel,+ onSecondary,tone = "danger",busy = false,children,@@ -63,6 +74,12 @@ export function ConfirmModal({onConfirm: () => void;/** Confirm button text (defaults to the shared "Confirm"). */confirmLabel?: string;+ /** Disables ONLY the confirm button (its action is temporarily unavailable — the body copy is expected to say why); Cancel and the secondary action stay clickable. */+ confirmDisabled?: boolean;+ /** Optional third choice, rendered as a neutral button between Cancel and Confirm; needs `onSecondary` to appear. */+ secondaryLabel?: string;+ /** Handler for the third choice (the dialog does not close itself — the caller decides, exactly like onConfirm). */+ onSecondary?: () => void;/** Confirm button variant: danger for deletions, primary for saves and other overwrites. */tone?: "danger" | "primary";busy?: boolean;@@ -74,11 +91,18 @@ export function ConfirmModal({<ToneBadge tone={tone} /><div className="min-w-0 flex-1 pt-1.5">{children}</div></div>- <div className="mt-4 flex justify-end gap-2">+ {/* Wraps rather than overflows: three choices with long labels don't fit one row inside+ the bottom-sheet width on a phone (a two-button card never reaches the wrap point). */}+ <div className="mt-4 flex flex-wrap justify-end gap-2"><Button size="sm" onClick={onClose} disabled={busy}>{S.common.cancel}</Button>- <Button size="sm" variant={tone} disabled={busy} onClick={onConfirm}>+ {secondaryLabel !== undefined && onSecondary !== undefined && (+ <Button size="sm" onClick={onSecondary} disabled={busy}>+ {secondaryLabel}+ </Button>+ )}+ <Button size="sm" variant={tone} disabled={busy || confirmDisabled} onClick={onConfirm}>{confirmLabel ?? S.common.confirm}</Button></div>diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 02c0cf36..d365c6c4 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -22,6 +22,7 @@ import type {ApprovalMode,ModelRefDto,ModelsResponse,+ SessionPatchRequest,SessionProcessInfo,SessionStatus,SkillMetadataItem,@@ -50,17 +51,26 @@ import { useTheme } from "../../state/theme";import { useProject } from "../../state/project";import { useSessions } from "../../state/sessions";import { Modal } from "../../components/ui/modal";+import { ConfirmModal } from "../../components/ui/confirm-modal";import { Button } from "../../components/ui/button";import { Skeleton } from "../../components/ui/skeleton";import { Truncated } from "../../components/ui/truncated";import { Dropdown } from "../../components/ui/dropdown";import { CopyButton, ROW_COPY_CLASS } from "../../components/ui/copy-button";import { EmptyState } from "../../components/ui/empty-state";-import { toastError } from "../../components/ui/toast";+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { MessageStream } from "./message-stream";import type { StreamRenderContext } from "./message-stream";import { latestTaskHasSubagent, taskStartCount } from "./agent-topology";import { ChatInput } from "./chat-input";+import {+ compactionTally,+ heldThinkingSwitch,+ needsThinkingSwitchConfirm,+ sessionThinkingLevel,+ thinkingLevelLabel,+} from "./thinking-level";+import type { StagedThinkingSwitch } from "./thinking-level";import { ChatDropRegion } from "./drop-zone";import { ConversationOutline, OutlineMenuButton, useOutlineRailFit } from "./conversation-outline";import { DraftView } from "./draft-view";@@ -291,12 +301,14 @@ export function ChatPage() {// Latest trace file path (single-session GET only — list rows don't carry it), fetched// when the details popover opens; null = none yet (brand-new session) or still loading.const [tracePath, setTracePath] = useState<string | null>(null);- // Per-turn thinking level, local per-session UI state: "" = untouched — the picker then- // displays the Agent config's level and postTask omits thinkingLevel (auto-follow: the- // server/core fallback applies, so mid-session Agent-config edits keep taking effect).- // Once the user picks a level it sticks for the session and rides on every subsequent- // postTask. Never written through to the Agent config (that behavior stays draft-only).- const [turnThinkingLevel, setTurnThinkingLevel] = useState("");+ // A mid-chat thinking-level pick staged behind the confirm dialog (issue #310): some+ // providers key their prompt PREFIX on the thinking level, so switching with history in+ // place invalidates the provider's prefix cache and the next request re-bills the whole+ // history as uncached input. The pick is only applied on an explicit choice; null = no+ // dialog, "ask" = dialog open, "compacting" = the user chose "compact, then switch" and+ // the pick is held until the compaction completes. Logic in thinking-level.ts+ // (needsThinkingSwitchConfirm / thinkingSwitchAfterCompaction).+ const [thinkingSwitch, setThinkingSwitch] = useState<StagedThinkingSwitch | null>(null);const routeSessionId = params.sessionId ?? null;const filesPanelRaw = useFilesPanel(routeSessionId);@@ -446,6 +458,14 @@ export function ChatPage() {// causing the new chat to end up created on the old Agent.const selectedSessionId = selected?.sessionId ?? null;const selectedAgentId = selected?.agentId ?? null;+ // The thinking level pinned on THIS Session, read straight off the Session row+ // (SessionInfo.thinkingLevel, written by the picker through PATCH — see+ // applyTurnThinkingLevel): "" = never pinned, and the picker then displays the Agent+ // config's level while sends omit thinkingLevel (auto-follow — the server/core fallback+ // applies, so Agent-config edits keep taking effect). A pin is DURABLE: it survives a+ // reload, shows up in a second tab, and the server applies it to every later run of this+ // Session. It is still never written through to the Agent config (that stays draft-only).+ const turnThinkingLevel = selected?.thinkingLevel ?? "";useEffect(() => {if (selectedSessionId && selectedAgentId) setCurrentAgentId(selectedAgentId);// eslint-disable-next-line react-hooks/exhaustive-deps@@ -615,14 +635,17 @@ export function ChatPage() {// create the same path, so its summary must re-check instead of inheriting stale false state.const statCacheRef = useRef(new Map<string, true | Promise<boolean>>());- // Session switch: resets the usage-fetch marker, the file-card existence cache, the- // per-turn thinking level (it's per-session UI state), and the popover's per-session- // data (process list / token buckets / trace path), avoiding stale data from the- // previous Session (Files panel state resets itself keyed on sessionId inside- // use-files-panel, and the cost hold re-keys itself on sessionId inside advanceCostStat).+ // Session switch: resets the usage-fetch marker, the file-card existence cache, any+ // thinking-level switch staged behind its dialog (per-session UI state — a compaction+ // that self-heals to a new session id routes through here too and drops the held pick),+ // and the popover's per-session data (process list / token buckets / trace path),+ // avoiding stale data from the previous Session (Files panel state resets itself keyed+ // on sessionId inside use-files-panel, and the cost hold re-keys itself inside+ // advanceCostStat). The thinking level itself needs no reset — it is read off the+ // selected Session row, so it changes with the session by construction.useEffect(() => {usageAppliedRef.current = null;- setTurnThinkingLevel("");+ setThinkingSwitch(null);statCacheRef.current = new Map();setProcesses([]);setUsageBuckets(null);@@ -1103,17 +1126,126 @@ export function ChatPage() {[selected, modeSaving, replace],);- const onCompact = useCallback(async () => {- if (!selected) return;+ // Starts a context compaction — the single path to the server for it (the composer's+ // /compact command and the thinking-switch dialog's "compact, then switch" both come+ // through here). Returns whether the request was ACCEPTED: the endpoint answers 202 and+ // the compaction itself runs asynchronously, so a true here means "started", not+ // "finished" — the outcome only shows up on the stream (see the staged-switch watcher).+ // false means the server refused it (409 while a task runs / nothing to compact / …) and+ // the reason has already been surfaced as a toast.+ const runCompaction = useCallback(async (): Promise<boolean> => {+ if (!selected) return false;try {// compact shares get-or-resume-or-heal with tasks: it can likewise self-heal to a new session_id.const res = await api.postCompact(selected.sessionId);await syncHealedSessionId(selected.sessionId, res.sessionId);+ return true;} catch (e) {toastError(apiErrorText(e, { modelId: selected.modelId }));+ return false;}}, [selected, syncHealedSessionId]);+ // The composer's /compact command: unchanged behavior (fire it, errors land as a toast).+ const onCompact = useCallback(async () => {+ await runCompaction();+ }, [runCompaction]);++ // Pins a picked level on the Session so it outlives this tab: PATCH, then swap the+ // returned row into the session store (the picker reads it back from there). Modeled on+ // onChangeApprovalMode — a failed write surfaces as a toast and leaves the level as it+ // was, rather than showing a level the server does not have.+ const applyTurnThinkingLevel = useCallback(+ (level: string) => {+ if (!selected) return;+ void api+ .patchSession(selected.sessionId, {+ thinkingLevel: level as SessionPatchRequest["thinkingLevel"],+ })+ .then((res) => replace(res.session))+ .catch((e: unknown) => {+ toastError(apiErrorText(e));+ });+ },+ [selected, replace],+ );++ // Session picker pick: pinned directly while it cannot hurt (empty transcript, a re-pick+ // of the displayed level, or right after a successful compaction), staged behind the+ // confirm dialog otherwise — switching the level mid-chat costs prompt-cache hits over+ // the whole history (issue #310), so the dialog offers compact-then-switch (recommended),+ // switch anyway, or cancel. The transcript is always loaded when the picker is clickable+ // (the composer only mounts once history load settles), so the live tail items are+ // authoritative here.+ const onPickTurnThinkingLevel = useCallback(+ (level: string) => {+ if (+ needsThinkingSwitchConfirm(+ stream.model.items,+ sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel),+ level,+ )+ ) {+ setThinkingSwitch({ phase: "ask", level });+ } else {+ applyTurnThinkingLevel(level);+ }+ },+ [stream.model, turnThinkingLevel, agentThinkingLevel, applyTurnThinkingLevel],+ );++ // Dialog choice 1 (recommended): compact first, then switch. The compaction is only+ // STARTED here — POST /compact answers 202 — so the pick is held with a tally of the+ // compactions already on record, and the watcher below releases it once a new one ends+ // (either way it ends). Compaction cannot be started (nor queued) while the session is+ // busy, so the dialog disables this choice unless idle; the guard here is the same rule.+ const compactThenThinkingSwitch = useCallback(() => {+ if (thinkingSwitch === null || stream.taskState !== "idle") return;+ const staged: StagedThinkingSwitch = {+ phase: "compacting",+ level: thinkingSwitch.level,+ baseline: compactionTally(stream.model.items),+ };+ setThinkingSwitch(staged);+ toastInfo(S.chat.thinkingSwitchCompacting);+ void runCompaction().then((ok) => {+ // Refused (the toast already said why, e.g. nothing to compact): no compaction will+ // ever settle, so hand the pick to the watcher below to release — the user asked to+ // switch, and only the compaction half of that failed. A pick staged meanwhile owns+ // the state instead.+ if (!ok) {+ setThinkingSwitch((cur) =>+ cur === staged ? { phase: "settle", level: staged.level } : cur,+ );+ }+ });+ }, [thinkingSwitch, stream.taskState, stream.model, runCompaction]);++ // Releases the pick held behind a running compaction: applied as soon as the compaction is+ // over, whichever way it ended. A failed/aborted compaction is reported (the context was+ // not rewritten, so this switch does cost cache hits) but never swallows the switch the+ // user asked for. Runs on every stream version bump because the model's items are mutated+ // in place.+ useEffect(() => {+ if (thinkingSwitch === null) return;+ const next = heldThinkingSwitch(thinkingSwitch, stream.model.items);+ if (next.act === "wait") return;+ setThinkingSwitch(null);+ applyTurnThinkingLevel(next.level);+ if (next.notice === "compacted") {+ toastSuccess(+ S.chat.thinkingSwitchApplied(+ thinkingLevelLabel(S.chat.thinkingLevelNames, next.level) ?? next.level,+ ),+ );+ } else if (next.notice === "compaction-failed") {+ toastError(S.chat.thinkingSwitchCompactFailed);+ }+ // notice "none": the compaction never started and runCompaction already said why.+ // The items are read from the model per run; `version` is the change signal.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [stream.version, stream.model, thinkingSwitch, applyTurnThinkingLevel]);+// "New Chat" = enter draft state: no Session is created until the first message is sent.// Typed-but-unsent text in the ACTIVE new-chat draft first becomes a parked draft// conversation (a sidebar row, sendable anytime) instead of lingering invisibly in the@@ -1257,10 +1389,11 @@ export function ChatPage() {{...(models !== null ? { models: models.models } : {})}{...(models?.defaultModel !== undefined ? { defaultModel: models.defaultModel } : {})}onSwitchModel={onSwitchModel}- // Display value: the user's pick for this session, else the Agent config's level- // (auto-follow while untouched; the send path uses the raw pick — see onSend).- turnThinkingLevel={turnThinkingLevel || agentThinkingLevel}- onChangeTurnThinkingLevel={setTurnThinkingLevel}+ // Display value: the level pinned on this Session, else the Agent config's level+ // (auto-follow while unpinned; the send path uses the raw pin — see onSend).+ turnThinkingLevel={sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel)}+ // Guarded: a mid-chat change stages behind the prefix-cache confirm dialog (issue #310).+ onChangeTurnThinkingLevel={onPickTurnThinkingLevel}{...(contextWindow !== undefined ? { contextWindow } : {})}contextNow={stream.model.stats.contextNow}contextStale={stream.model.stats.contextStale}@@ -1796,6 +1929,40 @@ export function ChatPage() {><p className="text-sm text-gray-600 dark:text-gray-300">{S.project.noCredentialBody}</p></Modal>++ {/* Mid-chat thinking-level switch confirmation (issue #310), three choices: compact+ first and switch when it finishes (primary — the recommended, cheap path), switch+ anyway (immediate, today's force path), or cancel (keeps the current level). The+ compact choice is unavailable while the session is busy — the server only starts a+ compaction on an idle session and does not queue it — and the body then says so.+ After a successful compaction the guard lets a re-pick through without asking. */}+ <ConfirmModal+ open={thinkingSwitch?.phase === "ask"}+ title={S.chat.thinkingSwitchTitle}+ tone="primary"+ confirmLabel={S.chat.thinkingSwitchCompactFirst}+ confirmDisabled={stream.taskState !== "idle"}+ onConfirm={compactThenThinkingSwitch}+ secondaryLabel={S.chat.thinkingSwitchConfirm}+ onSecondary={() => {+ if (thinkingSwitch !== null) applyTurnThinkingLevel(thinkingSwitch.level);+ setThinkingSwitch(null);+ }}+ onClose={() => setThinkingSwitch(null)}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.chat.thinkingSwitchBody(+ thinkingLevelLabel(S.chat.thinkingLevelNames, thinkingSwitch?.level) ??+ thinkingSwitch?.level ??+ "",+ )}+ </p>+ {stream.taskState !== "idle" && (+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">+ {S.chat.thinkingSwitchBusyHint}+ </p>+ )}+ </ConfirmModal></div>);}diff --git a/packages/web/src/features/chat/thinking-level.ts b/packages/web/src/features/chat/thinking-level.tsindex d60798be..6a9414c8 100644--- a/packages/web/src/features/chat/thinking-level.ts+++ b/packages/web/src/features/chat/thinking-level.ts@@ -63,6 +63,19 @@ export function thinkingLevelLabel(: null;}+/**+ * The level the ACTIVE-SESSION picker displays, and the one its sends carry.+ *+ * `pinned` is the Session's own stored level (`SessionInfo.thinkingLevel`, written by the+ * picker through PATCH — durable, so it survives a reload and a second tab); "" = never+ * pinned, and the picker then auto-follows `agentLevel`, the Agent config's level, exactly+ * as a brand-new session does. A pin wins from then on: later Agent-config edits no longer+ * move a session whose level the user chose explicitly.+ */+export function sessionThinkingLevel(pinned: string, agentLevel: string): string {+ return pinned || agentLevel;+}+/** One dropdown row of the agent-settings thinking-level menu (shape of OptionMenuChoice<string>). */export interface ThinkingLevelOptionRow {value: string;@@ -110,3 +123,160 @@ export function thinkingLevelOptionsFor(}return rows;}++/**+ * Structural subset of a stream ChatItem that the mid-chat switch guard inspects: the+ * item kind plus the compaction items' outcome fields (`running`/`status` — string unions+ * on the real items, so `ChatItem[]` is assignable as-is).+ */+export interface ThinkingSwitchItem {+ kind: string;+ running?: boolean;+ status?: string;+}++/**+ * Whether the loaded transcript indicates provider-side history whose prefix cache a+ * thinking-level change would invalidate (issue #310): some providers implement the+ * thinking level as a prompt prefix injected at the very FRONT of the chat template, so+ * changing it mid-conversation re-bills the entire history as uncached input on the next+ * request.+ *+ * - An empty transcript (brand-new session, nothing sent yet) is free to switch.+ * - Items only need to be the LIVE TAIL window (stream model): a non-empty session always+ * has a non-empty tail, and the trailing-compaction check below only looks at the tail.+ * - A transcript that ENDS in a settled successful compaction is also free to switch: the+ * provider context was just rewritten to a short summary, so the user who followed the+ * "compact first, then switch" advice is not warned a second time. Failed or still+ * running trailing compactions don't count (the old context is still in effect), but a+ * successful one anywhere in the trailing compaction run does (a failed retry after a+ * success changed nothing).+ */+export function prefixCacheAtRisk(items: ReadonlyArray<ThinkingSwitchItem>): boolean {+ let last = items.length - 1;+ let compacted = false;+ while (last >= 0 && items[last]!.kind === "compaction") {+ const c = items[last]!;+ if (!c.running && c.status === "completed") compacted = true;+ last--;+ }+ // Nothing but (at most) compaction rows: no billable history to protect.+ if (last < 0) return false;+ return !compacted;+}++/**+ * Gate for the ACTIVE-SESSION picker's pick (the draft picker never confirms — there is no+ * session, so no provider cache yet): true = stage the pick behind the confirm dialog+ * instead of applying it.+ *+ * `currentLevel` is the level the picker currently DISPLAYS (the user's session pick, else+ * the Agent config's level; "" = unknown — config unset or still loading). Re-picking the+ * displayed level changes nothing provider-visible (it merely pins the level for the+ * session), so it never confirms; an unknown current level confirms whenever history is at+ * risk — a needless dialog costs one click, a silently invalidated prefix cache costs real+ * money.+ */+export function needsThinkingSwitchConfirm(+ items: ReadonlyArray<ThinkingSwitchItem>,+ currentLevel: string,+ nextLevel: string,+): boolean {+ if (currentLevel !== "" && nextLevel === currentLevel) return false;+ return prefixCacheAtRisk(items);+}++/**+ * Settled compaction attempts visible in the transcript, and how many of them completed.+ * Snapshotted when the user picks "compact, then switch" so the wait below can tell OUR+ * compaction's outcome from the ones that were already on record.+ */+export interface CompactionTally {+ settled: number;+ completed: number;+}++/** Counts settled (not still running) compaction items and the completed subset. */+export function compactionTally(items: ReadonlyArray<ThinkingSwitchItem>): CompactionTally {+ let settled = 0;+ let completed = 0;+ for (const item of items) {+ if (item.kind !== "compaction" || item.running === true) continue;+ settled++;+ if (item.status === "completed") completed++;+ }+ return { settled, completed };+}++/**+ * The dialog's "compact, then switch" choice, held while the compaction runs.+ *+ * `POST /compact` answers **202** — it only starts the compaction, whose outcome arrives+ * later over the stream — so the pick cannot be applied on the request promise. It is held+ * here until compactionSettledSince below reports the compaction over.+ *+ * The pick is applied either way once that happens (a failed compaction is reported, not+ * silently swallowed): holding it is about ORDER, not about a veto — a level applied while+ * the compaction is still running would ride on anything sent in between (a queued+ * follow-up auto-starts the moment the session goes idle) and invalidate the very cache+ * the compaction is there to shrink.+ */+export type StagedThinkingSwitch =+ /** The dialog is open on this pick. */+ | { phase: "ask"; level: string }+ /** A compaction was started; the pick lands when it settles (see compactionSettledSince). */+ | { phase: "compacting"; level: string; baseline: CompactionTally }+ /** The compaction never started (the server refused it): release the pick on the next pass. */+ | { phase: "settle"; level: string };++/**+ * Whether a compaction has finished since the tally was taken, and how it ended:+ * - `"completed"` — one completed: the provider context is now the short summary. Reported+ * even if items were appended after it (a queued follow-up may have started), because the+ * compaction the user asked for did happen.+ * - `"failed"` — one settled without completing (failed / aborted): the old context is still+ * in effect, and the caller says so while still applying the pick.+ * - `"pending"` — nothing has settled yet, keep waiting.+ *+ * Counting rather than matching item ids keeps this correct across a stream reconnect+ * (history is rebuilt and ids restart); the worst case is a stalled `"pending"`.+ */+export function compactionSettledSince(+ items: ReadonlyArray<ThinkingSwitchItem>,+ baseline: CompactionTally,+): "pending" | "completed" | "failed" {+ const now = compactionTally(items);+ if (now.completed > baseline.completed) return "completed";+ if (now.settled > baseline.settled) return "failed";+ return "pending";+}++/**+ * What the page owes a staged switch right now — the whole decision, so the rule stays+ * testable instead of living in an effect:+ * - `"wait"` — the dialog is still open, or the compaction is still running.+ * - `"apply"` with a notice — release the pick. **The pick is applied whichever way the+ * compaction ended**: a failed one only means the context was not rewritten (so the+ * switch does cost cache hits), never that the user's choice is dropped.+ * - `"compacted"`: the compaction completed, the cheap path worked out;+ * - `"compaction-failed"`: it ended without completing — say so alongside the switch;+ * - `"none"`: it never started (the server refused it and already said why).+ */+export type HeldThinkingSwitch =+ | { act: "wait" }+ | { act: "apply"; level: string; notice: "compacted" | "compaction-failed" | "none" };++export function heldThinkingSwitch(+ staged: StagedThinkingSwitch,+ items: ReadonlyArray<ThinkingSwitchItem>,+): HeldThinkingSwitch {+ if (staged.phase === "ask") return { act: "wait" };+ if (staged.phase === "settle") return { act: "apply", level: staged.level, notice: "none" };+ const outcome = compactionSettledSince(items, staged.baseline);+ if (outcome === "pending") return { act: "wait" };+ return {+ act: "apply",+ level: staged.level,+ notice: outcome === "completed" ? "compacted" : "compaction-failed",+ };+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex adb13f00..025fdd9d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -856,6 +856,17 @@ export const en: Strings = {high: "High",xhigh: "Extreme High",},+ thinkingSwitchTitle: "Switch thinking level",+ thinkingSwitchBody: (to: string): string =>+ `Switch the thinking level to "${to}"? Switching mid-conversation lowers the prompt-cache hit rate and raises cost; compacting the context first is cheaper.`,+ thinkingSwitchBusyHint: "This conversation is still working — compaction has to wait for it.",+ thinkingSwitchCompactFirst: "Compact, then switch",+ thinkingSwitchConfirm: "Switch anyway",+ thinkingSwitchCompacting: "Compacting the context — the thinking level switches when it ends.",+ thinkingSwitchApplied: (to: string): string =>+ `Context compacted; thinking level switched to "${to}".`,+ thinkingSwitchCompactFailed:+ "The compaction did not finish; the thinking level was switched anyway.",workspaceUseThis: "Use this dir",workspaceUp: "Parent dir",workspaceNoSubdirs: "No subdirectories",@@ -1482,6 +1493,7 @@ Scenarios:path_not_found: "That path does not exist.",workspace_missing: "This Session's Workspace no longer exists.",task_in_progress: "This Session already has a task running.",+ compacting: "This Session is compacting its context and is not accepting new input.",version_conflict: "The snapshot's version is not newer than the current one.",invalid_title: "The title is invalid.",invalid_proxy_url:diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0f9444dd..70ce3f74 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -811,6 +811,20 @@ export const zh = {high: "高",xhigh: "极高",} as Readonly<Record<string, string>>,+ /** Mid-chat switch guard (issue #310): confirm before a level change that costs prompt-cache hits over the existing history. Title is the dialog's accessible name only. */+ thinkingSwitchTitle: "切换思考等级",+ thinkingSwitchBody: (to: string): string =>+ `将思考等级切换为「${to}」?会话中途切换会降低提示词缓存命中率、增加成本,先压缩上下文再切换更省。`,+ /** Shown under the body when the session isn't idle — compaction can only start on an idle session. */+ thinkingSwitchBusyHint: "会话正在运行,压缩要等空闲后才能开始。",+ /** Primary (recommended) choice: compact first, then apply the switch. */+ thinkingSwitchCompactFirst: "压缩后切换",+ thinkingSwitchConfirm: "仍要切换",+ /** Toast when the compaction starts: the switch is applied once it ends. */+ thinkingSwitchCompacting: "正在压缩上下文,压缩结束后切换思考等级。",+ thinkingSwitchApplied: (to: string): string => `上下文已压缩,思考等级已切换为「${to}」。`,+ /** Compaction ended without completing — the switch still applies, so say both. */+ thinkingSwitchCompactFailed: "压缩未成功完成,思考等级已照常切换。",workspaceUseThis: "使用此目录",workspaceUp: "上级目录",workspaceNoSubdirs: "无子目录",@@ -1433,6 +1447,8 @@ Benchmark:path_not_found: "该路径不存在。",workspace_missing: "该 Session 的 Workspace 已不存在。",task_in_progress: "该 Session 已有任务在运行。",+ /** `nothing_to_compact` is deliberately NOT mapped: the server sends three different specific reasons under that one code (not configured / no completed turn yet / just compacted), and a single localized sentence would flatten them into a wrong one. */+ compacting: "该 Session 正在压缩上下文,暂不接受新的输入。",version_conflict: "快照版本不高于当前版本。",invalid_title: "标题无效。",invalid_proxy_url: "代理地址无效:应为 http(s):// 或 socks5:// 代理 URL,或 主机[:端口]。",diff --git a/packages/web/test/thinking-level.test.ts b/packages/web/test/thinking-level.test.tsindex 957dd575..ef24e79e 100644--- a/packages/web/test/thinking-level.test.ts+++ b/packages/web/test/thinking-level.test.ts@@ -5,15 +5,27 @@* config by initializing its display to it), while "none" stays a displayable stored value;* "" (internally "untouched"/no override) and a legacy meta's "default" resolve to null so* callers substitute the config level or a placeholder.+ *+ * Plus the mid-chat switch guard (#310): when a pick has to be confirmed, and how the+ * dialog's "compact, then switch" choice decides — from the transcript alone — whether the+ * compaction it started completed (apply the pick), settled without completing (keep the+ * level and say so), or is still in flight.*/import { describe, expect, it } from "vitest";import {SELECTABLE_THINKING_LEVELS,THINKING_LEVELS,+ compactionSettledSince,+ compactionTally,effectiveThinkingLevel,+ heldThinkingSwitch,+ needsThinkingSwitchConfirm,+ prefixCacheAtRisk,+ sessionThinkingLevel,thinkingLevelLabel,thinkingLevelOptionsFor,} from "../src/features/chat/thinking-level";+import type { ThinkingSwitchItem } from "../src/features/chat/thinking-level";/** Mirrors the shape of S.chat.thinkingLevelNames. */const NAMES: Readonly<Record<string, string>> = {@@ -102,3 +114,200 @@ describe("thinkingLevelOptionsFor (agent-settings dropdown assembly)", () => {});});});++/** Stream-item stubs for the mid-chat switch guard (structural ThinkingSwitchItem subset). */+const user: ThinkingSwitchItem = { kind: "user_text" };+const reply: ThinkingSwitchItem = { kind: "assistant_text" };+const stats: ThinkingSwitchItem = { kind: "task_stats" };+const compactionDone: ThinkingSwitchItem = {+ kind: "compaction",+ running: false,+ status: "completed",+};+const compactionFailed: ThinkingSwitchItem = {+ kind: "compaction",+ running: false,+ status: "failed",+};+const compactionRunning: ThinkingSwitchItem = { kind: "compaction", running: true };++describe("prefixCacheAtRisk (issue #310 — provider prefix cache over the existing history)", () => {+ it("empty transcript: nothing cached provider-side yet", () => {+ expect(prefixCacheAtRisk([])).toBe(false);+ });++ it("any conversation history puts the prefix cache at risk", () => {+ expect(prefixCacheAtRisk([user])).toBe(true);+ expect(prefixCacheAtRisk([user, reply, stats])).toBe(true);+ });++ it("a transcript ending in a successful compaction is safe (compact-then-switch is not re-warned)", () => {+ expect(prefixCacheAtRisk([user, reply, stats, compactionDone])).toBe(false);+ });++ it("a failed or still-running trailing compaction leaves the old context — still at risk", () => {+ expect(prefixCacheAtRisk([user, reply, compactionFailed])).toBe(true);+ expect(prefixCacheAtRisk([user, reply, compactionRunning])).toBe(true);+ });++ it("a failed retry after a successful trailing compaction changed nothing — still safe", () => {+ expect(prefixCacheAtRisk([user, reply, compactionDone, compactionFailed])).toBe(false);+ });++ it("new turns after a compaction re-arm the guard (only a TRAILING compaction is safe)", () => {+ expect(prefixCacheAtRisk([user, reply, compactionDone, user, reply])).toBe(true);+ });+});++describe("needsThinkingSwitchConfirm (mid-chat switch guard for the session picker)", () => {+ const history = [user, reply, stats];++ it("no dialog on a brand-new/empty session — the initial selection is free", () => {+ expect(needsThinkingSwitchConfirm([], "medium", "high")).toBe(false);+ expect(needsThinkingSwitchConfirm([], "", "high")).toBe(false);+ });++ it("dialog when history exists and the pick differs from the displayed level", () => {+ expect(needsThinkingSwitchConfirm(history, "medium", "high")).toBe(true);+ });++ it("re-picking the displayed level only pins it — never a dialog, history or not", () => {+ expect(needsThinkingSwitchConfirm(history, "high", "high")).toBe(false);+ });++ it("unknown displayed level ('' — config unset/still loading) with history: warn rather than silently invalidate", () => {+ expect(needsThinkingSwitchConfirm(history, "", "medium")).toBe(true);+ });++ it("no dialog right after a successful compaction (the advised flow: /compact, then switch)", () => {+ expect(needsThinkingSwitchConfirm([...history, compactionDone], "medium", "high")).toBe(false);+ });+});++describe("compactionSettledSince (has the compaction we started finished?)", () => {+ const history = [user, reply, stats];+ /** The tally taken when the user picks "compact, then switch". */+ const at = (items: ThinkingSwitchItem[]) => compactionTally(items);++ it("counts settled compactions and their completed subset (a running one is not settled yet)", () => {+ expect(compactionTally([])).toEqual({ settled: 0, completed: 0 });+ expect(compactionTally([user, reply])).toEqual({ settled: 0, completed: 0 });+ expect(compactionTally([user, compactionRunning])).toEqual({ settled: 0, completed: 0 });+ expect(compactionTally([user, compactionFailed, reply, compactionDone])).toEqual({+ settled: 2,+ completed: 1,+ });+ });++ it("pending while the compaction is still running", () => {+ const baseline = at(history);+ expect(compactionSettledSince(history, baseline)).toBe("pending");+ expect(compactionSettledSince([...history, compactionRunning], baseline)).toBe("pending");+ });++ it("completed once one finishes", () => {+ const baseline = at(history);+ expect(compactionSettledSince([...history, compactionDone], baseline)).toBe("completed");+ });++ it("failed when one ends without completing (failed / aborted)", () => {+ const baseline = at(history);+ expect(compactionSettledSince([...history, compactionFailed], baseline)).toBe("failed");+ expect(+ compactionSettledSince(+ [...history, { kind: "compaction", running: false, status: "aborted" }],+ baseline,+ ),+ ).toBe("failed");+ });++ it("compactions already on record when the choice was made don't settle the wait", () => {+ // A failed compaction sitting in the transcript is exactly why the dialog opened+ // (prefixCacheAtRisk stays true) — it must not be read as "our compaction failed".+ const before = [...history, compactionFailed];+ const baseline = at(before);+ expect(compactionSettledSince(before, baseline)).toBe("pending");+ expect(compactionSettledSince([...before, compactionDone], baseline)).toBe("completed");+ });++ it("a failed retry after our compaction completed still reads as completed", () => {+ const baseline = at(history);+ expect(compactionSettledSince([...history, compactionDone, compactionFailed], baseline)).toBe(+ "completed",+ );+ });++ it("items appended after the completed compaction (e.g. a queued follow-up) don't hide it", () => {+ const baseline = at(history);+ expect(compactionSettledSince([...history, compactionDone, user, reply], baseline)).toBe(+ "completed",+ );+ });+});++describe("heldThinkingSwitch (releasing the pick behind 'compact, then switch')", () => {+ const history = [user, reply, stats];+ const compacting = {+ phase: "compacting",+ level: "high",+ baseline: compactionTally(history),+ } as const;++ it("waits while the dialog is open", () => {+ expect(heldThinkingSwitch({ phase: "ask", level: "high" }, history)).toEqual({ act: "wait" });+ });++ it("waits while the compaction is still running", () => {+ expect(heldThinkingSwitch(compacting, [...history, compactionRunning])).toEqual({+ act: "wait",+ });+ });++ it("applies the pick after a completed compaction, announcing the cheap path", () => {+ expect(heldThinkingSwitch(compacting, [...history, compactionDone])).toEqual({+ act: "apply",+ level: "high",+ notice: "compacted",+ });+ });++ it("STILL applies the pick when the compaction failed — the user asked to switch", () => {+ expect(heldThinkingSwitch(compacting, [...history, compactionFailed])).toEqual({+ act: "apply",+ level: "high",+ notice: "compaction-failed",+ });+ expect(+ heldThinkingSwitch(compacting, [+ ...history,+ { kind: "compaction", running: false, status: "aborted" },+ ]),+ ).toEqual({ act: "apply", level: "high", notice: "compaction-failed" });+ });++ it("applies the pick when the compaction never started (the server refused it)", () => {+ // The refusal toast already said why, so there is no notice of our own.+ expect(heldThinkingSwitch({ phase: "settle", level: "low" }, history)).toEqual({+ act: "apply",+ level: "low",+ notice: "none",+ });+ });+});++describe("sessionThinkingLevel (what the in-session picker shows and sends)", () => {+ it("a brand-new session follows the Agent config", () => {+ expect(sessionThinkingLevel("", "medium")).toBe("medium");+ });++ it("a level pinned on the Session wins, so a later Agent-config edit cannot move it", () => {+ expect(sessionThinkingLevel("high", "medium")).toBe("high");+ // The pin is read back off the Session row, so a reload computes this same value —+ // that is what makes the picked level survive a refresh.+ expect(sessionThinkingLevel("high", "low")).toBe("high");+ });++ it("nothing pinned and no config yet (still loading): no level to display", () => {+ expect(sessionThinkingLevel("", "")).toBe("");+ });+});