From 08ab1bc264191f10d14a71fc0777db95339baaaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Mon, 7 Sep 2026 16:37:48 +0800 Subject: [PATCH 1/3] fix: enforce the language-preference ask with a per-turn re-injection and a tool hard gate 1. Reset the per-session ask latch on every new user message so the directive re-surfaces each turn until .switchman/settings.json exists 2. Deny write/edit/bash/task with an ask-first error while unconfigured (reads stay open; shell/internal sessions exempt); a declined questionnaire waives gate+ask for that session 3. Push the ask directive as the first injected system part for main sessions instead of the tail of the protocol block 4. Extend tests (gate decision, marker detection, sandbox fixtures) and sync READMEs/CHANGELOG --- CHANGELOG.md | 1 + README.md | 4 +-- README.zh.md | 4 +-- src/index.ts | 70 +++++++++++++++++++++++++++++++------- src/lang-config.ts | 42 ++++++++++++++++++++--- src/shells.json | 2 +- src/version.ts | 2 +- test/auto-redirect.test.ts | 12 +++++-- test/lang-config.test.ts | 33 +++++++++++++++++- test/pane-resume.test.ts | 5 +++ test/subagent-cap.test.ts | 8 +++-- 11 files changed, 155 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9d34ed..16d7f58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes d ### Fixed +- **Language-preference ask no longer lost after a skipped first turn** — the ask directive was injected only on a session's first turn (one-shot in-memory latch), and main models routinely skipped the question and dove into the task, so unconfigured projects were never prompted again. Two layers fix it: the latch resets on every new user message (the ask re-surfaces at the start of each user turn until the config is persisted to `.switchman/settings.json`), and a hard gate denies write/edit/bash/task calls with an ask-first error while the project is unconfigured — the question no longer depends on the model's goodwill. A completed question call the user declines waives the gate and the ask for that session; `lang.ask: false` silences both. The directive is also pushed as the first injected system part and is never injected into shell/internal sessions. - **Split-screen pane no longer missing when the main session re-invokes a previously used subagent** — a task call carrying `task_id` makes opencode reuse the previous child session instead of creating a new one, so no `session.created` event fires and the pane trigger (which relied entirely on that event) never ran — resume dispatches opened no pane. The plugin now detects the reuse at the allowed dispatch sites, verifies the reused session still exists (a stale `task_id` falls back to a fresh session, which the existing event path covers), and opens/maintains the pane directly; a viewer pane the user closed moments earlier no longer swallows the re-display either. - **Vision/review lanes no longer collapse to "all unavailable" when a whole provider dies** — lane base chains allocated their few candidate seats by capability tier only, so when every top-seated combo was genuinely down (e.g. Copilot answering `402 monthly quota exceeded` across the board and DeepSeek in arrears), healthy lower-tier shells (GLM) had been sliced out of the chain in advance and the lanes showed "all unavailable→terminal failure protocol" until quotas recovered, restarts included. Two layers fix it: matrix-down shells are now filtered out **before** seat allocation (health-aware seats, same combo-down verdict the registry uses to mark a shell disabled; unknown/missing verdicts still fail-open), and `computeLane` backfills an otherwise-empty chain once from candidates dropped only by health reasons (matrix-down / disabled / breaker) via a relaxed-gate ranking pass — structural and pool-level gates (modality, capability, pool-config, exhaustion, retirement) still reject, so illegitimate candidates are never resurrected; if nothing structurally valid remains, the lane keeps its `exhausted` status and the terminal failure protocol. diff --git a/README.md b/README.md index a843cb7..d3dccaf 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ Both commands can also be driven directly via the bundled CLI: `node /dist/ - **Shell subagent context hard cap**: every shell subagent session now has a hard context cap (`context.subagentForceTokens`, default 100k tokens) — past the cap every tool call is denied with a wrap-up order, the subagent hands back a detailed progress summary as its task result, and the session can never be resumed via `task_id` (persistent registry); configured via `context.subagentCap` (see [Subagent context hard cap](#subagent-context-hard-cap)). - **Always-on per-call read budget (core routing algorithm update)**: the old per-tool one-time nudge (a coupon models rationally burned via retry/probing) is replaced by a deterministic budget gate. Every read is costed against `context.readBudgetTokens` (default 1500, clamped 200..20000) from turn 1 — over-budget reads are auto-bounded (a `limit` is appended in place) or denied with exact bounded-retry params; a per-turn 2× self-read cap (resetting on user turns) stops read chains; un-estimable tool outputs are charged post-hoc. Watermarks keep lifecycle duties only (soft = advice, hard = wrap-up deny, force = auto-handover). Delivery/verification bash (git, test/lint, build) passes at every tier; unbounded archaeology (`git log -p` without `-n`) is denied at every tier with a scoping hint. -- **Per-project language preference**: a per-turn `[LANG]` iron-rule line pins the conversation / comments & commits / docs languages, captured by a first-use ask (once per session), persisted per project, adjustable via `/switchman-lang`. +- **Per-project language preference**: a per-turn `[LANG]` iron-rule line pins the conversation / comments & commits / docs languages, captured by a first-use ask (re-surfaced at the start of every user turn until configured, and enforced by a hard gate — write/edit/bash/task calls are denied with an ask-first error while the project is unconfigured; the user's decline waives the gate for that session), persisted per project, adjustable via `/switchman-lang`. - **Todo discipline**: protocol §0.7 plus a per-turn `[TODO]` status line keeps the main session's todo list real-time current (delegated-shell results included). - **/expert expert consultation** and **bundled agent skills**: dispatch requirements to the strongest cross-family expert; opinionated skills sync into the opencode global skills dir at startup (add/overwrite-only, marker-gated cleanup, fail-open). - **Review-lane last resort**: with no cross-family read-only shell alive, the chain keeps the best ro shells and same-family review is allowed with a `DOWNGRADED` note instead of an empty chain. @@ -231,7 +231,7 @@ See the complete, user-facing release notes and migration guide in [CHANGELOG.md | `injection.mode` | `chain` | Shell injection face: `chain` = six lane chains ∪ favorites/visible models (saves ~6-10k tokens of task-tool description per session; naming an off-chain model gets a `denyUninjected` hint to enable it in model management), `all` = every usable model (old behavior). Startup-level: restart to apply | | `dispatch.autoRedirect` | `true` | On a dispatch deny, rewrite `subagent_type` in-flight to the chain-head candidate the deny message already names (single hop, same-snapshot guard re-check) — the first dispatch lands on the best available shell instead of burning deny-and-retry rounds; `false` restores deny-and-retry | | `relay.image` | `true` | Vision-less main models: user-attached images are decoded to disk and replaced with path text + reading guidance (delegate a vision-lane shell or an MCP vision tool); local paths / http URLs pass through; fully fail-open | -| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask once per session, persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks | +| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask re-surfaced every user turn until configured and enforced by a hard gate (write/edit/bash/task denied while unconfigured; decline waives per session), persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks | | `lanes` | built-in chains | Custom per-lane shell chains (override built-in preference order); keys = economy/mechanical/main/hard/vision/review | | `workspace.enabled / dirname` | `true / ".switchman"` | Artifact workspace: per main session, a `/.switchman//-/` folder whose path is injected into the dispatcher protocol every turn; holds `SESSION.md` / `dispatches.jsonl` / `media/`. Disabled = no folders created and the protocol section is neutralized | | `tmux.enabled / rightPct / maxPanes / mini` | `true / 60 / 3 / false` | tmux pane mirroring (effective only when the opencode server itself runs inside tmux): every dispatched subagent opens as a live `opencode attach` pane in a right-hand column of the home tmux window; `rightPct` = right column width percent (10..90, main pane keeps the rest), `maxPanes` = max visible subagent panes (1..4; extra dispatches wait in a FIFO queue), `mini` = minimal attach interface instead of the full TUI | diff --git a/README.zh.md b/README.zh.md index 2db9be6..9ed194d 100644 --- a/README.zh.md +++ b/README.zh.md @@ -188,7 +188,7 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** - **壳子代理上下文硬顶**:每条壳子代理会话现在都有硬性上下文上限(`context.subagentForceTokens`,默认 100k token)——越过上限后每次工具调用都会被拒绝并附收尾指令,子代理以一份详细的进度总结作为任务结果交回主会话,且该会话永远无法再经 `task_id` 续接(持久化注册表);经 `context.subagentCap` 配置(详见 [子代理上下文硬顶](#子代理上下文硬顶))。 - **常开逐次调用读预算(核心算法更新)**:用确定性预算闸取代旧的「每工具一次性提醒」(那种优惠券式提醒会被模型用重试/试探理性烧掉)。自第 1 轮起,每次读取都按 `context.readBudgetTokens`(默认 1500,钳制 200..20000)计费——预估超限的读取就地追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮 2× 自读上限(用户发言即重置)阻断连续读取链;无法预估的工具输出事后记账。水位只保留生命周期职责(软=建议、硬=收尾拒绝、压=自动交接)。交付/验证类 bash(git、测试/lint、构建)任何水位放行;无界翻史(不带 `-n` 的 `git log -p`)任何水位拦截并附收窄提示。 -- **项目级语言偏好**:每轮注入 `[LANG]` 铁律行(会话 / 注释与提交 / 文档三种语言),首次使用每会话询问一次并按项目落盘,`/switchman-lang` 可随时修改。 +- **项目级语言偏好**:每轮注入 `[LANG]` 铁律行(会话 / 注释与提交 / 文档三种语言),首次使用时询问并按项目落盘(未配置则每轮用户输入都会重新询问,且写入/编辑/bash/派发调用会被硬闸门拒绝并指回问卷;用户明确拒绝则本会话豁免),`/switchman-lang` 可随时修改。 - **待办纪律**:规程 §0.7 + 每轮 `[TODO]` 状态行,主会话待办实时更新(含委派壳的结果)。 - **/expert 专家咨询与随包 agent skills**:需求一键派给当前最强跨家族专家;开箱技能启动时同步进 opencode 全局技能目录(只增改不删、标记门控清理、fail-open)。 - **review 档兜底**:跨家族只读壳全灭时保留最优 ro 壳、允许同族评审并标注 `DOWNGRADED`,不再出现空链。 @@ -229,7 +229,7 @@ v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感 | `context.subagentForceTokens / subagentCap` | `100000 / true` | **子代理上下文硬顶**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),钳制 20k..1M 并额外以壳模型上下文窗口的 90% 封顶。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止;此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 只阻止新的终止——已终止的会话不复活 | | `dispatch.autoRedirect` | `true` | 派发被拒时在途改写 `subagent_type` 到拒绝消息已点名的链首候选(单跳、同快照守卫复检)——首次派发直接落在最优可用壳上,不再烧「拒绝-重试」轮次;`false` 恢复拒绝-重试 | | `relay.image` | `true` | 无视觉主模型:用户附带图片自动落盘并替换为路径文本+阅读指引(委托 vision 壳或交给 MCP 视觉工具);本地路径 / http URL 原样透传;全程 fail-open | -| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次使用每会话询问一次,落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | +| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次询问未完成配置则每轮用户输入重新询问,未配置期间写入/编辑/bash/派发被硬闸门拒绝(拒绝问卷则本会话豁免),落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | | `builtinAgents.mode` | `deny` | 内置 explore/general 与壳路由抢任务且此前放行;`deny`=拦截附 economy/main 改派建议,`allow`=恢复放行 | | `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为)。启动级,重启生效 | | `lanes` | 内置六档链 | 自定义各档壳链(覆盖内置偏好序);键=economy/mechanical/main/hard/vision/review | diff --git a/src/index.ts b/src/index.ts index 6850369..bac4e64 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,7 +60,7 @@ import { LANE_ORDER, DEFAULT_LANG_CANDIDATES } from "./types" import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey } from "./types" import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace" import { TmuxPaneManager, serverOriginOf } from "./tmux" -import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion } from "./lang-config" +import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions } from "./lang-config" import { detectMode, readConfigured, normalizeProviderListResponse } from "./activation" import type { MatrixModeOption } from "./activation" // [2026-08-29]-[event/parameter shape-extraction pure functions moved to helpers.ts: the entry must not export non-plugin functions, otherwise @@ -193,6 +193,9 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-05]-[project language preference: per-session first-ask latch (released on capture/session delete); // the config itself is re-read from disk EVERY turn, so "configured = never ask again" holds across restarts] const langAsked = new Set<string>() + // [2026-09-07]-[lang hard gate: per-session waiver set — a completed marker question call that did NOT persist a + // config (user declined / unparsable output) opens the gate for this session so a decline never deadlocks writes] + const langGateWaived = new Set<string>() // [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in the home // tmux window — main pane left / subagent column right (max 3 visible, FIFO replacement on completion); inert // outside tmux, fail-open everywhere. pendingTask = dispatch intents recorded per main session, consumed by the @@ -1378,6 +1381,23 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (/-mx-/.test(agent) || agent === "title" || agent === "compaction" || agent === "summary") return } } + // [2026-09-05]-[project language preference: per-turn [LANG] iron-rule line (settings.json → AGENTS.md marker, + // disk re-read every turn = mechanism-enforced stickiness); unconfigured → ask directive re-injected at the + // start of every user turn (latch resets per user message, see the message.updated handler; the question-tool + // answers are captured and persisted plugin-side, never by the model)] + // [2026-09-07]-[pushed FIRST among the injected parts + backed by the tool gate: the directive sat at the tail + // of a multi-k-token block and models skipped it in favor of starting the task — attention follows position]- + // [2026-09-07]-[moved BELOW the shell/internal early-return: main-session-only injection (shell subagents and + // title/compaction sessions must not receive the [LANG] line or the ask directive); for main sessions it is + // still the first injected part of the turn]- + if (options.lang!.enabled) { + const loaded = loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) + if (loaded) output.system.push(renderLangLine(loaded.cfg, loaded.source)) + else if (options.lang!.ask !== false && input.sessionID && !langAsked.has(input.sessionID) && !langGateWaived.has(input.sessionID)) { + langAsked.add(input.sessionID) + output.system.push(renderAskDirective(options.lang!.candidates ?? DEFAULT_LANG_CANDIDATES)) + } + } // [2026-08-29]-[fail-open visibility: explicit warning when injection crashes — don't dispatch; do it yourself or tell the user]- if (configFailed) { output.system.push("[opencode-switchman] ⚠ plugin injection failed (shells/dispatch gates unavailable) — task delegation forbidden this turn; do it yourself or explain to the user, then proceed yourself") @@ -1422,17 +1442,6 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const todoLine = sessionTodoLine(input.sessionID) if (todoLine) output.system.push(todoLine) } - // [2026-09-05]-[project language preference: per-turn [LANG] iron-rule line (settings.json → AGENTS.md marker, - // disk re-read every turn = mechanism-enforced stickiness); unconfigured → first-turn-only ask directive - // (latched per session; the question-tool answers are captured and persisted plugin-side, never by the model)] - if (options.lang!.enabled) { - const loaded = loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) - if (loaded) output.system.push(renderLangLine(loaded.cfg, loaded.source)) - else if (options.lang!.ask !== false && input.sessionID && !langAsked.has(input.sessionID)) { - langAsked.add(input.sessionID) - output.system.push(renderAskDirective(options.lang!.candidates ?? DEFAULT_LANG_CANDIDATES)) - } - } } catch (exc) { appendStatusLog(`rules/banner fail-open: ${exc}`) } @@ -1521,6 +1530,32 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (denySkip.has(input.callID)) throw e // internal error on our side (never one of our own denies) → fail-open, do not break the tool path } + // [2026-09-07]-[lang hard gate: while the project language preference is unconfigured (and ask is on, not waived), + // deny write/edit/bash/task with an ask-first error — structural enforcement of the questionnaire; reads stay + // open so the model can explore; capture/persist happens plugin-side in tool.execute.after. Disk check per gated + // call only (cheap existsSync/read), so a config that appears by any means opens the gate immediately; fail-open + // on internal errors. Excludes shell/internal sessions — dispatched executors and title/compaction are unaffected] + try { + const lgSid = (input as any).sessionID as string | undefined + const langAskOn = options.lang!.ask !== false + if (lgSid && LANG_GATE_TOOLS.has(input.tool) && !isShellOrInternalSession(lgSid) + && langAskOn && !langGateWaived.has(lgSid)) { + const reason = langGateDecision({ + tool: input.tool, + configured: !!loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME), + askEnabled: langAskOn, + waived: false, + }) + if (reason) { + denySkip.add(input.callID) + appendStatusLog(`lang gate: tool '${input.tool}' denied in unconfigured project session ${lgSid}`) + throw new Error(reason) + } + } + } catch (e) { + if (denySkip.has(input.callID)) throw e + // internal error on our side (never one of our own denies) → fail-open, do not break the tool path + } // [2026-09-04]-[read watermark gate: read-class/bash tools other than task are intercepted by tier per the measured session watermark] if (input.tool !== "task") { // [2026-09-05]-[no-vision image read guard runs first: image files are skipped by the read budget gate (BINARY_EXT), @@ -1689,12 +1724,17 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { "tool.execute.after": async (hookInput, hookOutput) => { // [2026-09-05]-[project language preference capture: our marker question answered → the plugin persists the config // itself (the model never writes the settings file); unrelated tools fall through, fail-open everywhere] + // [2026-09-07]-[completed marker question call that did NOT persist (user declined / unparsable output) waives + // the hard gate + the ask directive for this session — a decline must never deadlock writes on a new project] if (hookInput.tool === "question") { try { const saved = saveLangFromQuestion(hookInput.args, (hookOutput as any)?.output, pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) if (saved) { langAsked.delete(hookInput.sessionID) appendStatusLog(`project language preference saved (${saved.rel}): conversation=${saved.cfg.conversation} comments=${saved.cfg.comments} docs=${saved.cfg.docs}`) + } else if (hasLangMarkerQuestions(hookInput.args)) { + langGateWaived.add(hookInput.sessionID) + appendStatusLog(`lang gate: marker question completed without a saved config — gate waived for session ${hookInput.sessionID}`) } } catch { /* fail-open */ } } @@ -1812,6 +1852,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (info?.role === "user") { lastUserMsg.set(sid, info.id) turnReadUsage.delete(sid) + // [2026-09-07]-[lang ask was one-shot per session and the model routinely skipped the turn-1 directive + // (buried under the injected protocol) — reset the latch on every new user message so the ask directive + // re-surfaces each user turn until the config is persisted; impact: unconfigured projects get asked + // every turn instead of silently never (decline still re-asks; escape hatch = lang.ask:false)] + langAsked.delete(sid) } else if (info?.role === "assistant") { // [2026-09-05]-[window cap: track the current model (AssistantMessage modelID+providerID, sdk types.gen.ts:108-109) // as the registry key for the context-window threshold cap] @@ -1871,6 +1916,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { sessionTodos.delete(sid) workspace.forget(sid) langAsked.delete(sid) + langGateWaived.delete(sid) // [2026-09-06]-[tmux pane mirroring: deleted child frees its pane; deleted main drops its dispatch intents] if (tmuxPanes.tracking(sid)) void tmuxPanes.noteChildEnd(sid) pendingTask.delete(sid) diff --git a/src/lang-config.ts b/src/lang-config.ts index 89e3fe0..0be7e4a 100644 --- a/src/lang-config.ts +++ b/src/lang-config.ts @@ -102,9 +102,11 @@ export function renderAskDirective(candidates: readonly string[]): string { `2. question "${askTag(2)}: Language for code comments and commit messages?", single-choice, options: ${opts}`, `3. question "${askTag(3)}: Language for generated documents (plans, PRD, design docs, reports)?", single-choice, options: ${opts}`, `The user may also type any other language (custom answer) — relay it verbatim as the option text.`, - `After the tool returns: confirm the saved preferences in one line, then continue the user's task in the chosen`, - `conversation language. If the question tool is unavailable or the user declines, skip silently and proceed with`, - `English defaults; do not ask again in this session.`, + `HARD GATE: the plugin denies every write / edit / bash / task call in this project until the answers are captured`, + `and the config is saved — asking first is not optional. After the tool returns: confirm the saved preferences in`, + `one line, then continue the user's task in the chosen conversation language. If the user declines or the question`, + `tool is unavailable, skip silently and proceed with English defaults (the plugin waives the gate and this ask for`, + `the session); otherwise the ask re-surfaces on the next user turn until the config is saved.`, ].join("\n") } @@ -128,11 +130,41 @@ export function parseQuestionAnswers(output: string): [string, string, string] | return [pairs[0]![1], pairs[1]![1], pairs[2]![1]] } +// [2026-09-07]-[lang hard gate: prompt-only enforcement proved unreliable — models routinely skipped the turn-1 (and +// per-turn) ask directive and dove into the task. These pure helpers power a tool.execute.before gate in index.ts: +// write/edit/bash/task calls are denied with an ask-first error while the config is missing; reads stay open so the +// model can still explore; a completed-but-unsaved marker question call (user declined / unparsable) waives the gate +// for that session — impact: unconfigured projects get asked structurally, not on the model's goodwill] + +/** Tools blocked by the lang gate while the project is unconfigured (mutation + delegation; reads stay allowed) */ +export const LANG_GATE_TOOLS: ReadonlySet<string> = new Set(["bash", "edit", "write", "task"]) + +export interface LangGateInput { tool: string; configured: boolean; askEnabled: boolean; waived: boolean } + +/** Pure gate decision: null = allow, string = the denial message shown to the model */ +export function langGateDecision(input: LangGateInput): string | null { + if (!input.askEnabled || input.configured || input.waived) return null + if (!LANG_GATE_TOOLS.has(input.tool)) return null + return [ + `[opencode-switchman] BLOCKED: this project's language preference is not configured yet. Ask the user ONCE via the`, + `question tool with exactly the three "switchman-lang n/3" questions (see the ask directive in your system prompt)`, + `and wait for the answers — the plugin persists them and unblocks this call automatically, then retry. Reads stay`, + `allowed. If the user declines, the gate is waived for this session.`, + ].join(" ") +} + +/** True when the question-tool args carry our marker questions (the lang ask relayed by the model) */ +export function hasLangMarkerQuestions(args: unknown): boolean { + try { + const questions = (args as any)?.questions + return Array.isArray(questions) && questions.some((q) => typeof q?.question === "string" && q.question.includes(LANG_ASK_MARKER)) + } catch { return false } +} + /** tool.execute.after capture: marker-carrying question args + textual result → persisted config (fail-open null) */ export function saveLangFromQuestion(args: unknown, toolOutput: unknown, projectDir: string, workspaceDirname: string): { rel: string; cfg: LangConfig } | null { try { - const questions = (args as any)?.questions - if (!Array.isArray(questions) || !questions.some((q) => typeof q?.question === "string" && q.question.includes(LANG_ASK_MARKER))) return null + if (!hasLangMarkerQuestions(args)) return null if (typeof toolOutput !== "string") return null const answers = parseQuestionAnswers(toolOutput) if (!answers) return null diff --git a/src/shells.json b/src/shells.json index 8fd5df2..8f16bc9 100644 --- a/src/shells.json +++ b/src/shells.json @@ -1,6 +1,6 @@ { "_note": "opencode-switchman full matrix: authoritative enabled surface (models enabled in model management, scripts/visible-models.txt) × all declared thinking efforts (models.dev reasoning_options, toggle→off). Generated by scripts/gen-shells.ts — do not edit by hand; after model on/off changes, sync the pin file and re-run bun run gen:shells. The six lane chains are computed from capability score × lane affinity × structural gate × billing factor (api billing 0.85, unknown group 0.75, sunk by coefficient; no vendor-reserved seats).", - "generated_at": "2026-09-06T14:55:56.419Z", + "generated_at": "2026-09-07T08:09:07.964Z", "counts": { "shells": 104, "visible_models": 13 diff --git a/src/version.ts b/src/version.ts index 45febd8..c050c86 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ // Generated at build time: run bun scripts/gen-version.ts -export const PLUGIN_VERSION = "1.0.0" +export const PLUGIN_VERSION = "1.0.1" diff --git a/test/auto-redirect.test.ts b/test/auto-redirect.test.ts index 776c802..e9f4233 100644 --- a/test/auto-redirect.test.ts +++ b/test/auto-redirect.test.ts @@ -11,6 +11,10 @@ const prevConfigDir = process.env.OPENCODE_CONFIG_DIR process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-autoredir-state-")) process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-autoredir-cfg-")) mkdirSync(process.env.SWITCHMAN_STATE, { recursive: true }) +// [2026-09-07]-[lang hard gate fixture: sandbox project counts as lang-configured] +const projectDir = mkdtempSync(join(tmpdir(), "switchman-lang-fix-")) +mkdirSync(join(projectDir, ".switchman"), { recursive: true }) +writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, configuredAt: "x", lang: { conversation: "en", comments: "en", docs: "en" } })) // capability data decoupled (same trick as routing.test.ts): empty capability.json pins the curated table; empty catalog takes the static-manifest floor writeFileSync( join(process.env.SWITCHMAN_STATE, "capability.json"), @@ -48,7 +52,7 @@ import { loadManifest, stateDir } from "../src/state" type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> -const pluginInput = { client: { provider: { list: async () => [] } } } as any +const pluginInput = { client: { provider: { list: async () => [] } }, directory: projectDir } as any async function makeHooks(rawOptions: unknown): Promise<Hooks> { const hooks = await SwitchmanPlugin(pluginInput, rawOptions as any) @@ -176,7 +180,11 @@ describe("autoRedirect: dynamic hooks (denyUninjected redirect)", () => { describe("image relay: messages.transform hook (legacy)", () => { let hooks: Hooks test("plugin construction", async () => { - hooks = await makeHooks({ matrix: { mode: "legacy" } }) + // [2026-09-07]-[workspace disabled for this group: the relay assertions target the global state-dir fallback media + // path (stateDir()/media/<sid>); with the real pluginInput.directory (lang fixture above) the workspace-first + // writeDir (index.ts: ws ? <ws>/media : stateDir()/media/<sid>) would create <projectDir>/.switchman/<day>/<sid>/ + // and persist media there instead — production behavior, wrong path under test here]- + hooks = await makeHooks({ matrix: { mode: "legacy" }, workspace: { enabled: false } }) }, 20_000) test("no-vision main model + data URL image → persisted and replaced by a reading-guidance text part", async () => { diff --git a/test/lang-config.test.ts b/test/lang-config.test.ts index a41e3b3..7bead4a 100644 --- a/test/lang-config.test.ts +++ b/test/lang-config.test.ts @@ -7,7 +7,8 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { normalizeLangValue, parseLangSettings, parseAgentsMdLangMarker, loadLangConfig, saveLangConfig, - renderAskDirective, renderLangLine, parseQuestionAnswers, saveLangFromQuestion, LANG_SETTINGS_FILE, + renderAskDirective, renderLangLine, parseQuestionAnswers, saveLangFromQuestion, langGateDecision, + hasLangMarkerQuestions, LANG_SETTINGS_FILE, } from "../src/lang-config" import { validateUserConfig, resolveEffectiveOptions } from "../src/config" import { DEFAULT_LANG_CANDIDATES } from "../src/types" @@ -59,6 +60,8 @@ describe("lang-config: render functions", () => { expect(d).toContain("switchman-lang 3/3") for (const c of DEFAULT_LANG_CANDIDATES) expect(d).toContain(c) expect(d).toContain("never write the settings file yourself") + expect(d).toContain("the ask re-surfaces on the next user turn") + expect(d).toContain("HARD GATE") }) test("[LANG] line carries three keys, iron rule and single-turn exception semantics", () => { const line = renderLangLine({ conversation: "zh-CN", comments: "zh-CN", docs: "en" }, "settings") @@ -71,6 +74,34 @@ describe("lang-config: render functions", () => { }) }) +// [2026-09-07]-[lang hard gate fixtures: deny write/edit/bash/task while unconfigured with an ask-first message, +// reads stay allowed, configured/ask-off/waived allow, marker-question arg detection for the waiver path] +describe("lang-config: langGateDecision / hasLangMarkerQuestions", () => { + test("gate denies write/edit/bash/task while unconfigured, with an ask-first message", () => { + for (const tool of ["bash", "edit", "write", "task"]) { + const d = langGateDecision({ tool, configured: false, askEnabled: true, waived: false }) + expect(d).toContain("BLOCKED") + expect(d).toContain("switchman-lang") + } + }) + test("reads and misc tools stay allowed", () => { + for (const tool of ["read", "grep", "glob", "list", "question", "todowrite", "webfetch"]) { + expect(langGateDecision({ tool, configured: false, askEnabled: true, waived: false })).toBeNull() + } + }) + test("configured / ask disabled / waived → allow", () => { + expect(langGateDecision({ tool: "bash", configured: true, askEnabled: true, waived: false })).toBeNull() + expect(langGateDecision({ tool: "edit", configured: false, askEnabled: false, waived: false })).toBeNull() + expect(langGateDecision({ tool: "task", configured: false, askEnabled: true, waived: true })).toBeNull() + }) + test("hasLangMarkerQuestions: marker-carrying args true, everything else false", () => { + expect(hasLangMarkerQuestions({ questions: [{ question: "switchman-lang 1/3: lang?" }] })).toBe(true) + expect(hasLangMarkerQuestions({ questions: [{ question: "plain question?" }] })).toBe(false) + expect(hasLangMarkerQuestions({})).toBe(false) + expect(hasLangMarkerQuestions(null)).toBe(false) + }) +}) + describe("lang-config: parseQuestionAnswers", () => { test("marker-question match over the question tool's textual result", () => { const out = 'User has answered your questions: "switchman-lang 1/3: Conversation language?"="简体中文", "switchman-lang 2/3: Comments language?"="简体中文", "switchman-lang 3/3: Docs language?"="English"' diff --git a/test/pane-resume.test.ts b/test/pane-resume.test.ts index b105ced..1656619 100644 --- a/test/pane-resume.test.ts +++ b/test/pane-resume.test.ts @@ -13,6 +13,10 @@ const prevConfigDir = process.env.OPENCODE_CONFIG_DIR process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-pane-resume-state-")) process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-pane-resume-cfg-")) mkdirSync(process.env.SWITCHMAN_STATE, { recursive: true }) +// [2026-09-07]-[lang hard gate fixture: sandbox project counts as lang-configured] +const projectDir = mkdtempSync(join(tmpdir(), "switchman-lang-fix-")) +mkdirSync(join(projectDir, ".switchman"), { recursive: true }) +writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, configuredAt: "x", lang: { conversation: "en", comments: "en", docs: "en" } })) // hermetic state (same trick as routing.test.ts / auto-redirect.test.ts): pre-seed every TTL cache so the six gates // never hit the network; the empty catalog pins the curated table writeFileSync( @@ -62,6 +66,7 @@ function pluginInput(behavior: GetBehavior, seen: string[]): any { }, }, }, + directory: projectDir, } } diff --git a/test/subagent-cap.test.ts b/test/subagent-cap.test.ts index 1118571..59a8086 100644 --- a/test/subagent-cap.test.ts +++ b/test/subagent-cap.test.ts @@ -3,7 +3,7 @@ // (persistent registry, survives plugin re-instantiation), internal sessions and sub-cap sessions are untouched, and // fresh dispatches without task_id are unaffected] import { describe, expect, test } from "bun:test" -import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" @@ -13,6 +13,10 @@ process.env.OPENCODE_CONFIG_DIR = configDir process.env.SWITCHMAN_STATE = stateDir // [2026-09-06]-[model catalog stub: message.updated model-key recording consults the runtime index for the window cap] writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// [2026-09-07]-[lang hard gate fixture: sandbox project counts as lang-configured] +const projectDir = mkdtempSync(join(tmpdir(), "switchman-lang-fix-")) +mkdirSync(join(projectDir, ".switchman"), { recursive: true }) +writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, configuredAt: "x", lang: { conversation: "en", comments: "en", docs: "en" } })) import { SwitchmanPlugin } from "../src/index" import { @@ -41,7 +45,7 @@ async function bootPlugin(): Promise<Hooks> { } // [2026-09-06]-[legacy mode forced (same pattern as todo-nudge/pane-resume tests): the classification under test is // sessionAgent-based; dynamic mode would need a probed superset for isShellSession] - return SwitchmanPlugin({ client: fakeClient, directory: "/w" } as any, { matrix: { mode: "legacy" } } as any) + return SwitchmanPlugin({ client: fakeClient, directory: projectDir } as any, { matrix: { mode: "legacy" } } as any) } async function mark(hooks: Hooks, sessionId: string, input: number): Promise<void> { From f620ded523ebab901d0277c0c074086bfb046352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Mon, 7 Sep 2026 16:59:41 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat:=20TUI=20sidebar=20version=20line=20?= =?UTF-8?q?=E2=80=94=20running/latest=20version=20and=20upgrade-pending=20?= =?UTF-8?q?restart=20tag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - marquee row now renders the running version (local builds append the checked commit short SHA) and a green '→ v<latest>' / '→ origin/main' tag when the 24h-cached update check reports a newer release (/switchman-ignore suppresses it like the banner) - blinking [RESTART NEEDED] now also covers installed-but-not-loaded upgrades: upgraded.flag this session or prod disk-version mismatch, merged with the shell-registration restartRequired tag - new pure helpers in selfupdate.ts: versionBrief(), installedPluginVersion() - docs: sidebar paragraph + What's New bullet in both READMEs, changelog --- CHANGELOG.md | 6 ++++++ README.md | 3 ++- README.zh.md | 3 ++- src/selfupdate.ts | 43 +++++++++++++++++++++++++++++++++++++++- src/tui.tsx | 34 +++++++++++++++++++++++++++++-- test/selfupdate.test.ts | 44 ++++++++++++++++++++++++++++++++++++++++- 6 files changed, 127 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16d7f58..e59f6c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. +## [Unreleased] + +### Added + +- **Version line in the TUI sidebar marquee row** — the rainbow `switchman` title now shows the running version (local builds append the checked commit short SHA) and, when the 24h-cached update check reports a newer release, a green `→ v<latest>` tag (`→ origin/main` for local builds; suppressed by `/switchman-ignore` exactly like the update banner). The blinking bold-red `[RESTART NEEDED]` tag — previously keyed only on pending shell registration (`active-matrix.json.restartRequired`) — now also covers installed-but-not-loaded upgrades: it lights up when `/switchman-update` touched `upgraded.flag` this session or the on-disk package version differs from the running one (out-of-band upgrades), merging with the shell-registration case into one indicator; both clear naturally after a restart. All sources are fail-open: missing state renders just the bare running version. + ## [1.0.1] - 2026-09-07 ### Added diff --git a/README.md b/README.md index d3dccaf..c30a7e8 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ The log also shows `[opencode-switchman] injected N model shells (agents)` — N ### Sidebar status panel (TUI plugin, optional) -v0.2.0 adds a live `switchman` panel at the bottom of the OpenCode TUI sidebar; v1.0.0 polishes it into a fully aligned, English-localized operational view. Observed provider water levels render as gradient bars on a globally aligned 8-column grid (labels, bars, and reset times line up across provider blocks; any non-zero quota paints at least one filled cell), with peak-period warnings, per-provider observe-only tags (collapsed when every provider observes), the current head candidate for each of the six lanes, restart-required badges for newly detected models/providers, and the most recent status notice. The panel polls local state every 2 seconds; non-banner notices never flood `stderr` or cover the input box. It is a separate TUI Slot plugin (`src/tui.tsx`, exported at `opencode-switchman/tui`) and is independent of the server-side hook plugin above. +v0.2.0 adds a live `switchman` panel at the bottom of the OpenCode TUI sidebar; v1.0.0 polishes it into a fully aligned, English-localized operational view. Observed provider water levels render as gradient bars on a globally aligned 8-column grid (labels, bars, and reset times line up across provider blocks; any non-zero quota paints at least one filled cell), with peak-period warnings, per-provider observe-only tags (collapsed when every provider observes), the current head candidate for each of the six lanes, restart-required badges for newly detected models/providers, a version line on the marquee row (the running version — local builds append the checked commit short SHA — plus a green `→ v<latest>` when the update check reports a newer release, `→ origin/main` for local builds; the blinking `[RESTART NEEDED]` tag also lights up while an installed upgrade awaits a restart), and the most recent status notice. The panel polls local state every 2 seconds; non-banner notices never flood `stderr` or cover the input box. It is a separate TUI Slot plugin (`src/tui.tsx`, exported at `opencode-switchman/tui`) and is independent of the server-side hook plugin above. > **Recommended workflow**: set the plugin up in the TUI first — pick model favorites, tune `/poolConfig` and `/modelRank`, and watch the sidebar while it routes. The desktop app is an optional alternative afterwards (it shares the same config and state); the TUI is simply where the operational surface — dialogs, sidebar, banners — is richest. @@ -193,6 +193,7 @@ Both commands can also be driven directly via the bundled CLI: `node <pkg>/dist/ - **/expert expert consultation** and **bundled agent skills**: dispatch requirements to the strongest cross-family expert; opinionated skills sync into the opencode global skills dir at startup (add/overwrite-only, marker-gated cleanup, fail-open). - **Review-lane last resort**: with no cross-family read-only shell alive, the chain keeps the best ro shells and same-family review is allowed with a `DOWNGRADED` note instead of an empty chain. - **Auto-handover robustness**: numbered `[backup]` sessions (survives restarts, never recycles numbers), compaction routed through the same channel as the manual `/compact`, and a detached compaction leg that can no longer deadlock the session. +- **Sidebar version line**: the marquee row shows the running version and, when the update check reports a newer release, the latest version; the blinking `[RESTART NEEDED]` tag now also covers installed-but-not-loaded upgrades (see [Sidebar status panel](#sidebar-status-panel-tui-plugin-optional)). - **tmux pane mirroring**: when the opencode server itself runs inside tmux, every dispatched subagent opens as a live `opencode attach` pane stacked in a right-hand column of the home tmux window — capped visible panes with a FIFO queue, in-place respawn, auto re-evening on completion, and full fail-open safety (see [tmux pane mirroring](#tmux-pane-mirroring-optional)). ### v1.0.0 — English-first stable release diff --git a/README.zh.md b/README.zh.md index 9ed194d..7eb80c5 100644 --- a/README.zh.md +++ b/README.zh.md @@ -134,7 +134,7 @@ bun run build # 生成 dist/opencode-switchman.js ### 侧边栏状态面板(TUI 插件,可选) -v0.2.0 在 OpenCode TUI 侧边栏底部新增实时 `switchman` 面板,v1.0.0 又做了全面的排版与配色打磨(并完成英文本地化):各家 provider 的水位以渐变条呈现、对齐到全局 8 列网格(标签、进度条与刷新时间跨块对齐,非零小额配额也保证至少一格填充),带高峰标记、observe-only 折叠标签、六个任务档位当前链首、新增模型/provider 的「需要重启」标记,以及最新一条运行通知。面板每 2 秒轮询本地状态;非横幅 `stderr` 通知不会刷屏或遮挡输入框。这是一套独立的 TUI Slot 插件(`src/tui.tsx`,导出路径 `opencode-switchman/tui`),与上面的 server 端 hook 插件互相独立。 +v0.2.0 在 OpenCode TUI 侧边栏底部新增实时 `switchman` 面板,v1.0.0 又做了全面的排版与配色打磨(并完成英文本地化):各家 provider 的水位以渐变条呈现、对齐到全局 8 列网格(标签、进度条与刷新时间跨块对齐,非零小额配额也保证至少一格填充),带高峰标记、observe-only 折叠标签、六个任务档位当前链首、新增模型/provider 的「需要重启」标记、走马灯行上的版本信息(当前运行版本——本地构建会附上所在提交短 SHA——更新检查发现新版本时以绿色显示 `→ v<最新版>`,本地构建显示 `→ origin/main`;已安装升级待重启时闪烁 `[RESTART NEEDED]` 标记),以及最新一条运行通知。面板每 2 秒轮询本地状态;非横幅 `stderr` 通知不会刷屏或遮挡输入框。这是一套独立的 TUI Slot 插件(`src/tui.tsx`,导出路径 `opencode-switchman/tui`),与上面的 server 端 hook 插件互相独立。 > **推荐工作流**:先用 TUI 完成全部配置——选好模型收藏、调好 `/poolConfig` 与 `/modelRank`、盯着侧栏看它路由;之后可自行选择是否换用桌面端(强烈推荐 TUI:两端共享同一份配置与状态,而弹窗、侧栏、横幅等操作面在 TUI 里最完整)。 @@ -193,6 +193,7 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** - **/expert 专家咨询与随包 agent skills**:需求一键派给当前最强跨家族专家;开箱技能启动时同步进 opencode 全局技能目录(只增改不删、标记门控清理、fail-open)。 - **review 档兜底**:跨家族只读壳全灭时保留最优 ro 壳、允许同族评审并标注 `DOWNGRADED`,不再出现空链。 - **自动交接健壮性**:`[backup]` 备份自行编号(重启不乱、编号不回收)、压缩走与手动 `/compact` 相同通道、压缩腿异步化不再死锁会话。 +- **侧栏版本行**:走马灯行显示当前运行版本,更新检查发现新版本时同时显示最新版本;闪烁的 `[RESTART NEEDED]` 标记现在也覆盖「已安装升级但未生效」的场景(详见 [侧边栏状态面板](#侧边栏状态面板tui-插件可选))。 - **tmux 窗格镜像**:opencode 服务器自身跑在 tmux 里时,每条被委派的子代理都会在主 tmux 窗口右侧列以实时 `opencode attach` 窗格打开——可见窗格封顶+FIFO 队列、原地接管、完成即重新均分布局,全程 fail-open(详见 [tmux 窗格镜像](#tmux-窗格镜像可选))。 ### v1.0.0——英文优先的稳定版 diff --git a/src/selfupdate.ts b/src/selfupdate.ts index efe6526..23bb463 100644 --- a/src/selfupdate.ts +++ b/src/selfupdate.ts @@ -1,7 +1,7 @@ // [2026-09-04]-[English localization: translate CLI messages and comments; no logic change] // Plugin self-update check: state cache and all external calls are fail-open, never affecting OpenCode startup. import { execFileSync } from "node:child_process" -import { mkdirSync, rmSync, statSync, writeFileSync } from "node:fs" +import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" import { dirname, join } from "node:path" import { fileURLToPath } from "node:url" import { homedir } from "node:os" @@ -36,6 +36,17 @@ function moduleDir(): string { return dirname(decodeURIComponent(url).replace(/^file:\/\//, "")) } +// [2026-09-07]-[TUI sidebar version line: read the on-disk package.json version next to the loaded dist; null when +// unreadable (fail-open). Disk version differing from the running one means an out-of-band upgrade awaits a restart]- +export function installedPluginVersion(): string | null { + try { + const raw = JSON.parse(readFileSync(join(dirname(moduleDir()), "package.json"), "utf8")) as { version?: unknown } + return typeof raw.version === "string" && raw.version.trim() ? raw.version : null + } catch { + return null + } +} + export function modeOfDistPath(dir: string): LoadMode { return dir.split(/[\\/]+/).includes("node_modules") ? "prod" : "local" } @@ -145,6 +156,36 @@ export function flagSemantics(baseDir = join(homedir(), ".config", "opencode", " return { upgraded: active("upgraded.flag"), ignored: active("update-ignore.flag") } } +// ---- [2026-09-07]-[TUI sidebar version line (next to the marquee title): current/latest/restart-pending derivation]---- + +export interface VersionBrief { + /** Running version label, e.g. "v1.0.1"; local mode appends the checked commit short SHA when available */ + running: string + /** Update-available tag, e.g. "v1.2.0" (prod) or "origin/main" (local); null when up to date / ignored / unknown */ + update: string | null + /** True when a restart is required for the running code to match the installed plugin */ + restartPending: boolean +} + +/** Pure derivation shared by the TUI sidebar; all inputs come from fail-open readers and may be null/unknown. */ +export function versionBrief(opts: { + state: SelfUpdateState | null + flags: { upgraded: boolean; ignored: boolean } + running: string + installed: string | null +}): VersionBrief { + const state = opts.state + const sha = state?.mode === "local" && /^[0-9a-f]{40}$/.test(state.current) ? `@${state.current.slice(0, 7)}` : "" + const update = state?.outdated && !opts.flags.ignored + ? (state.mode === "prod" ? `v${state.latest}` : "origin/main") + : null + // upgraded.flag (in-session /switchman-update) or a prod disk-version mismatch (out-of-band upgrade) both mean + // the running process predates the installed code; local-mode mismatch is ignored (a stale dist is rebuilt, not restarted) + const restartPending = opts.flags.upgraded + || (state?.mode === "prod" && opts.installed !== null && opts.installed !== opts.running) + return { running: `v${opts.running}${sha}`, update, restartPending } +} + /** Bundled updater path (same directory as the main build output; copied to dist/update-cli.js by scripts/update-cli.mjs at build time) */ export function updateCliPath(): string { return pluginCliPath("update-cli.js") diff --git a/src/tui.tsx b/src/tui.tsx index 3b9124f..1b0e076 100644 --- a/src/tui.tsx +++ b/src/tui.tsx @@ -17,11 +17,15 @@ import type { TuiPlugin, TuiPluginModule, TuiPluginApi } from "@opencode-ai/plug import { createSignal, createMemo, onCleanup, For } from "solid-js" import { readFileSync, statSync } from "node:fs" import { homedir } from "node:os" -import { join, relative, isAbsolute, sep } from "node:path" +import { join, relative, isAbsolute, sep, dirname } from "node:path" // [2026-09-03]-[/poolConfig //modelRank interactive dialogs: task-pool pick lists and capability ranking read/write the // user override layer (pool-config.json / capability-rank.json) directly, taking effect in sync with the plugin main // process mtime hot reload] import { loadPoolConfig, writePoolConfig, resetPoolConfig, loadCapabilityRank, writeCapabilityRank, applyRankMove } from "./user-overrides" +// [2026-09-07]-[version line next to the marquee: reuse the selfupdate state/flag readers so the sidebar shares the +// exact same sources and TTL semantics as the update banner] +import { readSelfUpdateState, flagSemantics, installedPluginVersion, versionBrief } from "./selfupdate" +import { PLUGIN_VERSION } from "./version" import { allModelRows, rankViewRows } from "./config-cli" import { LANE_ORDER, type Lane } from "./types" import { runHandover, type HandoverPort } from "./handover-core" @@ -85,6 +89,9 @@ const SHOW_LAST = 1 const RESTART_HINT_RE = /restart opencode[^;]*/gi const MARQUEE_MS = 150 const TITLE = "switchman" +// [2026-09-07]-[version/restart flags are session-scoped: mtime later than this process's start = active, matching +// the main process PLUGIN_START semantics in selfupdate.ts; naturally clears after a restart] +const PROCESS_START = Date.now() // [2026-09-02]-[Fixed palette for lanes/recommended models: orange = lane type, green = recommended model name; echoes // the watermark greens but keeps independent semantics] // [2026-09-04]-[Brightened to the 400-level palette to match the new waterColor stops; the notice header drops its @@ -220,6 +227,11 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { const [routes, setRoutes] = createSignal<RouteSnapshotEntry[]>(readRouteSnapshot()) const [quotaBrief, setQuotaBrief] = createSignal<QuotaBriefEntry[]>(readQuotaBrief()) const [restartRequired, setRestartRequired] = createSignal<string[]>(readRestartRequired()) + // [2026-09-07]-[version line: selfupdate.json (24h TTL-validated), upgrade/ignore flag mtimes vs process start, + // and the on-disk package.json version (prod restart-needed detection); all fail-open like the other readers] + const [selfUpdate, setSelfUpdate] = createSignal(readSelfUpdateState()) + const [updateFlags, setUpdateFlags] = createSignal(flagSemantics(statusLogPath(), PROCESS_START)) + const [installedVersion, setInstalledVersion] = createSignal<string | null>(installedPluginVersion()) const [tick, setTick] = createSignal(0) // [2026-09-02]-[Branch signal: re-read .git/HEAD every poll cycle (session directory first, TUI directory as // fallback); also subscribes to vcs.branch.updated for instant refresh when the event chain works, with polling as @@ -235,6 +247,9 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { setRoutes(readRouteSnapshot()) setQuotaBrief(readQuotaBrief()) setRestartRequired(readRestartRequired()) + setSelfUpdate(readSelfUpdateState()) + setUpdateFlags(flagSemantics(statusLogPath(), PROCESS_START)) + setInstalledVersion(installedPluginVersion()) refreshBranch() }, POLL_MS) // [2026-09-02]-[The title rainbow marquee needs its own heartbeat far faster than data polling; separate duties and @@ -260,6 +275,15 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { const list = out.split("/") return { parent: list.slice(0, -1).join("/"), name: list.at(-1) ?? "", branch } }) + // [2026-09-07]-[version line derivation: running label (local adds the checked commit short SHA), update tag + // (suppressed by /switchman-ignore like the banner), and upgrade-pending restart detection] + const version = createMemo(() => versionBrief({ + state: selfUpdate(), + flags: updateFlags(), + running: PLUGIN_VERSION, + installed: installedVersion(), + })) + const restartPending = () => restartRequired().length > 0 || version().restartPending return ( <box flexDirection="column" gap={0}> @@ -314,10 +338,16 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { {(ch, i) => <span style={{ fg: hsvToHex(i() * 28 + tick() * 3, 0.65, 1) }}>{ch}</span>} </For> </b> + {/* [2026-09-07]-[version line next to the marquee: muted running version (local mode appends the checked + commit short SHA), green "→ latest" when outdated, and the blinking restart tag now merges the + shell-registration restartRequired with upgrade-pending (upgraded.flag / prod disk-version mismatch); + fail-open unchanged: missing state renders just the bare running version]-[impacts the sidebar title row only] */} + <span style={{ fg: theme().textMuted }}> {version().running}</span> + {version().update !== null && <span style={{ fg: MODEL_COLOR }}> → {version().update}</span>} {/* [2026-09-06]-[blinking restart tag: ~600ms on/off via the 150ms marquee heartbeat (tick/4 parity), bold red — a pending shell-registration restart used to render as a static tag that was easy to stop seeing; fail-open unchanged: empty restartRequired list renders nothing]-[impacts the sidebar title row only] */} - {restartRequired().length > 0 && Math.floor(tick() / 4) % 2 === 0 && ( + {restartPending() && Math.floor(tick() / 4) % 2 === 0 && ( <span style={{ fg: theme().error }}><b> [RESTART NEEDED]</b></span> )} </text> diff --git a/test/selfupdate.test.ts b/test/selfupdate.test.ts index 1c1e1a3..967c012 100644 --- a/test/selfupdate.test.ts +++ b/test/selfupdate.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test" import { mkdtempSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { bannerTextOf, compareSemver, ensureUpdateCommands, flagSemantics, modeOfDistPath } from "../src/selfupdate" +import { bannerTextOf, compareSemver, ensureUpdateCommands, flagSemantics, modeOfDistPath, installedPluginVersion, versionBrief } from "../src/selfupdate" import { readFileSync, existsSync, writeFileSync, rmSync, utimesSync } from "node:fs" import type { SelfUpdateState } from "../src/selfupdate" @@ -88,3 +88,45 @@ describe("One-click upgrade command assets", () => { expect(bannerTextOf({ checked_at: "", mode: "prod", current: "0.0.1", latest: "9.9.9", outdated: true })).toContain("/switchman-update") }) }) + +describe("Sidebar version line derivation (versionBrief)", () => { + const flagsNone = { upgraded: false, ignored: false } + const prodCurrent = { checked_at: "", mode: "prod" as const, current: "1.0.1", latest: "1.0.1", outdated: false } + + test("up-to-date prod: running version only, no update tag, no restart", () => { + expect(versionBrief({ state: prodCurrent, flags: flagsNone, running: "1.0.1", installed: "1.0.1" })) + .toEqual({ running: "v1.0.1", update: null, restartPending: false }) + }) + + test("prod outdated: update tag carries the latest version; /switchman-ignore suppresses it", () => { + const st = { ...prodCurrent, latest: "1.2.0", outdated: true } + expect(versionBrief({ state: st, flags: flagsNone, running: "1.0.1", installed: "1.0.1" }).update).toBe("v1.2.0") + expect(versionBrief({ state: st, flags: { upgraded: false, ignored: true }, running: "1.0.1", installed: "1.0.1" }).update).toBeNull() + }) + + test("local mode: update tag reads origin/main, running label carries the checked commit short SHA", () => { + const st = { checked_at: "", mode: "local" as const, current: "a".repeat(40), latest: "origin/main has new commits", outdated: true } + const b = versionBrief({ state: st, flags: flagsNone, running: "1.0.1", installed: null }) + expect(b.running).toBe("v1.0.1@aaaaaaa") + expect(b.update).toBe("origin/main") + expect(b.restartPending).toBe(false) + }) + + test("restart pending: upgraded.flag wins; prod disk-version mismatch counts; local mismatch does not", () => { + expect(versionBrief({ state: prodCurrent, flags: { upgraded: true, ignored: false }, running: "1.0.1", installed: "1.0.1" }).restartPending).toBe(true) + expect(versionBrief({ state: prodCurrent, flags: flagsNone, running: "1.0.1", installed: "1.2.0" }).restartPending).toBe(true) + const localSt = { checked_at: "", mode: "local" as const, current: "deadbeef".repeat(5), latest: "", outdated: false } + expect(versionBrief({ state: localSt, flags: flagsNone, running: "1.0.1", installed: "1.2.0" }).restartPending).toBe(false) + }) + + test("missing state: labels degrade to the bare running version, flags still drive the restart tag", () => { + expect(versionBrief({ state: null, flags: { upgraded: false, ignored: true }, running: "1.0.1", installed: null })) + .toEqual({ running: "v1.0.1", update: null, restartPending: false }) + expect(versionBrief({ state: null, flags: { upgraded: true, ignored: true }, running: "1.0.1", installed: null }).restartPending).toBe(true) + }) + + test("installedPluginVersion reads package.json next to the loaded module (repo root under test)", () => { + const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string } + expect(installedPluginVersion()).toBe(pkg.version) + }) +}) From a7ca82e6d85eb09fff880e451caaf92e85bc9e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Mon, 7 Sep 2026 17:13:27 +0800 Subject: [PATCH 3/3] =?UTF-8?q?release:=20v1.0.2=20=E2=80=94=20TUI=20sideb?= =?UTF-8?q?ar=20version=20line,=20language-ask=20enforcement,=20OIDC=20tru?= =?UTF-8?q?sted=20publishing=20(version=20bump=20and=20changelog)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/publish.yml | 10 +++++++--- CHANGELOG.md | 7 +++++-- package.json | 2 +- src/version.ts | 2 +- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ff51f40..aab5d5b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,11 +6,15 @@ on: permissions: contents: read + # [2026-09-07]-[npm OIDC trusted publishing: no long-lived NPM_TOKEN; requires the package's Trusted Publisher on npmjs.com to match repo/workflow/environment]-[publish authenticates via short-lived OIDC tokens; provenance is generated automatically] + id-token: write jobs: publish: # [2026-09-06]-[only main-branch releases may publish to npm; dev-branch releases are ignored]-[prevents accidental npm publish from dev] if: github.event.release.target_commitish == 'main' + # [2026-09-07]-[route the publish through the release-publish environment: required-reviewer approval gate + branch/tag policy (environment needs a v* tag rule since release runs carry refs/tags/*)]-[each release waits for manual approval before npm publish] + environment: release-publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 @@ -19,7 +23,8 @@ jobs: - uses: actions/setup-node@v5 with: - node-version: 22 + # [2026-09-07]-[trusted publishing needs npm >= 11.5.1; node 22's bundled npm is too old]-[node 24 ships a compatible npm] + node-version: 24 registry-url: https://registry.npmjs.org/ - name: Verify tag matches package version @@ -43,7 +48,6 @@ jobs: - name: Build run: bun run build + # [2026-09-07]-[OIDC trusted publishing: npm exchanges the workflow's OIDC token for a short-lived publish token; no NODE_AUTH_TOKEN]-[long-lived NPM_TOKEN secret is no longer used by this workflow] - name: Publish run: npm publish - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index e59f6c4..d41ca98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,16 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. -## [Unreleased] +## [1.0.2] - 2026-09-07 ### Added - **Version line in the TUI sidebar marquee row** — the rainbow `switchman` title now shows the running version (local builds append the checked commit short SHA) and, when the 24h-cached update check reports a newer release, a green `→ v<latest>` tag (`→ origin/main` for local builds; suppressed by `/switchman-ignore` exactly like the update banner). The blinking bold-red `[RESTART NEEDED]` tag — previously keyed only on pending shell registration (`active-matrix.json.restartRequired`) — now also covers installed-but-not-loaded upgrades: it lights up when `/switchman-update` touched `upgraded.flag` this session or the on-disk package version differs from the running one (out-of-band upgrades), merging with the shell-registration case into one indicator; both clear naturally after a restart. All sources are fail-open: missing state renders just the bare running version. +### Fixed + +- **Language-preference ask no longer lost after a skipped first turn** — the ask directive was injected only on a session's first turn (one-shot in-memory latch), and main models routinely skipped the question and dove into the task, so unconfigured projects were never prompted again. Two layers fix it: the latch resets on every new user message (the ask re-surfaces at the start of each user turn until the config is persisted to `.switchman/settings.json`), and a hard gate denies write/edit/bash/task calls with an ask-first error while the project is unconfigured — the question no longer depends on the model's goodwill. A completed question call the user declines waives the gate and the ask for that session; `lang.ask: false` silences both. The directive is also pushed as the first injected system part and is never injected into shell/internal sessions. + ## [1.0.1] - 2026-09-07 ### Added @@ -22,7 +26,6 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes d ### Fixed -- **Language-preference ask no longer lost after a skipped first turn** — the ask directive was injected only on a session's first turn (one-shot in-memory latch), and main models routinely skipped the question and dove into the task, so unconfigured projects were never prompted again. Two layers fix it: the latch resets on every new user message (the ask re-surfaces at the start of each user turn until the config is persisted to `.switchman/settings.json`), and a hard gate denies write/edit/bash/task calls with an ask-first error while the project is unconfigured — the question no longer depends on the model's goodwill. A completed question call the user declines waives the gate and the ask for that session; `lang.ask: false` silences both. The directive is also pushed as the first injected system part and is never injected into shell/internal sessions. - **Split-screen pane no longer missing when the main session re-invokes a previously used subagent** — a task call carrying `task_id` makes opencode reuse the previous child session instead of creating a new one, so no `session.created` event fires and the pane trigger (which relied entirely on that event) never ran — resume dispatches opened no pane. The plugin now detects the reuse at the allowed dispatch sites, verifies the reused session still exists (a stale `task_id` falls back to a fresh session, which the existing event path covers), and opens/maintains the pane directly; a viewer pane the user closed moments earlier no longer swallows the re-display either. - **Vision/review lanes no longer collapse to "all unavailable" when a whole provider dies** — lane base chains allocated their few candidate seats by capability tier only, so when every top-seated combo was genuinely down (e.g. Copilot answering `402 monthly quota exceeded` across the board and DeepSeek in arrears), healthy lower-tier shells (GLM) had been sliced out of the chain in advance and the lanes showed "all unavailable→terminal failure protocol" until quotas recovered, restarts included. Two layers fix it: matrix-down shells are now filtered out **before** seat allocation (health-aware seats, same combo-down verdict the registry uses to mark a shell disabled; unknown/missing verdicts still fail-open), and `computeLane` backfills an otherwise-empty chain once from candidates dropped only by health reasons (matrix-down / disabled / breaker) via a relaxed-gate ranking pass — structural and pool-level gates (modality, capability, pool-config, exhaustion, retirement) still reject, so illegitimate candidates are never resurrected; if nothing structurally valid remains, the lane keeps its `exhausted` status and the terminal failure protocol. diff --git a/package.json b/package.json index e925b1a..654b1df 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-switchman", - "version": "1.0.1", + "version": "1.0.2", "description": "OpenCode orchestration plugin: six-lane shell matrix dispatch (hard ROUTE_META validation / breaker self-healing / probes / three-pool quota awareness / cost-aware tiebreaker)", "license": "MIT", "repository": { diff --git a/src/version.ts b/src/version.ts index c050c86..6b191a4 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ // Generated at build time: run bun scripts/gen-version.ts -export const PLUGIN_VERSION = "1.0.1" +export const PLUGIN_VERSION = "1.0.2"