JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(coding): 添加/keybindings指令,支持快捷键编辑
kdgmpw7eea4a2575c3
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex 93c6698305..e2d361532f 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -18,6 +18,7 @@ Executed locally in the terminal UI, not through Gateway control pipeline.| `/copy` | Copy last message || `/exit` | Exit || `/help` | Show available commands |+| `/keybindings` | View, edit, or reset TUI keyboard shortcuts (alias `/keybind`) || `/theme` | Switch theme || `/config` | Modify configuration (currently local, planned to unify with Gateway) || `/context` | Show context window usage and token breakdown (see below) |@@ -140,6 +141,8 @@ Entering **`/resume`** or **`/continue`** with **no arguments** opens an interac| `Ctrl+B` | Toggle git branch filter (only show sessions whose `git_branch` strictly equals the current project's branch) || `Esc` | Clear search if any; otherwise close the picker |+> `Space` / `Ctrl+R` / `Ctrl+A` / `Ctrl+B` / `Esc` in the list can be rebound under the `ResumeList` context via `/keybindings` (preview/rename sub-states and search text entry stay hardcoded).+Behavior:- **Defaults to listing all projects** (press `Ctrl+A` to narrow to the current project). When the current project has no sessions, an (empty) picker still opens so you can press `Ctrl+A`.@@ -568,6 +571,30 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command- `/sandbox files deny ./tmp/secret/` — deny write under an allowed parent (ro)- `/sandbox exclude add "git *"` — let `git` run on the host instead of inside the sandbox+### `/keybindings` (Keyboard Shortcuts)++View, edit, or reset TUI keyboard shortcuts. Config file: `~/.jiuwenswarm-tui/keybindings.json`.++#### Usage++| Command | Action |+|---------|--------|+| `/keybindings` | Same as `/keybindings edit` |+| `/keybindings edit` | Create or open the config file; reload after the external editor closes |+| `/keybindings list` | List effective shortcuts grouped by context |+| `/keybindings reset` | Delete user config and restore built-in defaults |++Alias: `/keybind`.++#### Notes++- Built-in defaults are merged with user JSON per **context**; set a key to `null` to unbind a default.+- Key ids must match pi-tui `matchesKey` format (`ctrl`/`shift`/`alt` + main key); chords are not supported.+- **Non-rebindable**: `ctrl+c`, `ctrl+d`, `ctrl+m` (reserved keys).+- Select-list navigation, config editor text input, Resume preview/rename sub-states, etc. remain hardcoded.++See the Chinese [TUI User Guide · Keyboard shortcuts](../zh/TUI使用指南.md#快捷键) for the full context/action reference.+### `/hooks` (Browse Hooks Configuration)View a summary of all hooks configured in `config.yaml` (read-only).diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 2d6d66d4cd..ba4b21bf71 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -18,6 +18,7 @@| `/copy` | 复制上一条消息 || `/exit` | 退出 || `/help` | 查看可用命令 |+| `/keybindings` | 查看/编辑/重置 TUI 快捷键(别名 `/keybind`) || `/theme` | 切换主题 || `/config` | 修改配置(当前为本地实现,后续计划统一到 Gateway) || `/context` | 查看上下文窗口占用与 Token 用量明细(见下文) |@@ -140,13 +141,15 @@| `Ctrl+B` | 开关 git 分支过滤(严格匹配当前项目分支名) || `Esc` | 有搜索词时清空;否则关闭选择器 |+> 上表 `Space` / `Ctrl+R` / `Ctrl+A` / `Ctrl+B` / `Esc` 可在 `ResumeList` context 下通过 `/keybindings` 重绑;预览态、重命名编辑态与搜索文本输入除外。+说明:- **默认列出全部项目** 的会话(`Ctrl+A` 切回仅当前项目);当前项目无会话时仍打开(空)选择器以便按 `Ctrl+A`。- **分支过滤** 仅按分支名严格匹配,存量无分支记录与 `HEAD` 会话会被过滤;按名比对不区分仓库,「全部项目 + 分支过滤」时同名分支会一并显示。- **恢复范围**:仅恢复会话上下文(历史、会话 ID、accent 颜色、workflow 快照、窗口标题),**不切换 workspace / 当前工作目录**。-> 完整快捷键与行为详见 [TUI 使用指南](TUI使用指南.md#resume-与-continue-在-tui-中的特殊行为)。+> 完整快捷键与行为详见 [TUI 使用指南](TUI使用指南.md#resume-与-continue-在-tui-中的特殊行为);自定义快捷键见 [快捷键](TUI使用指南.md#快捷键)。### `/model`(查看 / 新增 / 切换模型)@@ -587,6 +590,30 @@- `/sandbox files deny ./tmp/secret/` — 在已 allow 的父目录下禁止写入子目录(ro)- `/sandbox exclude add "git *"` — 让 `git` 命令穿透到本地执行,不进沙箱+### `/keybindings`(快捷键配置)++查看、编辑或重置 TUI 键盘快捷键。配置文件:`~/.jiuwenswarm-tui/keybindings.json`。++#### 用法++| 命令 | 作用 |+|------|------|+| `/keybindings` | 同 `/keybindings edit` |+| `/keybindings edit` | 创建或打开配置文件;关闭外部编辑器后重新加载 |+| `/keybindings list` | 列出当前生效的快捷键(按 context 分组) |+| `/keybindings reset` | 删除用户配置,恢复内置默认 |++别名:`/keybind`。++#### 配置说明++- 以内置默认绑定为底,用户 JSON 按 **context** 覆盖;键设为 `null` 可取消默认绑定。+- 键名需符合 pi-tui `matchesKey` 格式(`ctrl`/`shift`/`alt` + 主键);不支持 chord。+- **不可重绑**:`ctrl+c`、`ctrl+d`、`ctrl+m`(保留键)。+- Select 列表内部导航、Config 编辑器文本输入、Resume 预览/重命名子态等仍为硬编码。++详见 [TUI 使用指南 · 快捷键](TUI使用指南.md#快捷键)。+### `/hooks`(浏览 Hooks 配置)查看当前 `config.yaml` 中配置的所有 hooks 的摘要信息(只读)。diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"index fec8b0cdb7..15fb408c4b 100644--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"@@ -71,7 +71,7 @@| 命令 | 别名 | 用途 | 示例 | 适用模式 ||------|------|------|------|----------|| `/help` | - | 列出已注册 Slash 命令 | `/help` | 全部 |-| `/hotkey` | - | 显示快捷键与 `/help` 提示 | `/hotkey` | 全部 |+| `/keybindings` | `/keybind` | 查看/编辑/重置 TUI 快捷键配置 | `/keybindings`、`/keybindings list` | 全部 || `/hooks` | - | 浏览已配置的 hooks(只读) | `/hooks` | 全部 || `/exit` | `/quit` | 退出 TUI | `/exit` | 全部 || `/clear` | `/reset`, `/new` | 新建会话 ID、清空当前 transcript(忙时拒绝) | `/clear` | 全部 |@@ -124,6 +124,8 @@| `Ctrl+B` | 开关 git 分支过滤(仅显示 `git_branch` 严格等于当前项目分支的会话) || `Esc` | 有搜索词时清空搜索;否则关闭选择器 |+> 上表 `Space` / `Ctrl+R` / `Ctrl+A` / `Ctrl+B` / `Esc` 属于 **`ResumeList` context**,可通过 `/keybindings` 重绑;预览态、重命名编辑态内的 `Enter` / `Esc` / `Backspace` 及搜索框文本输入仍为硬编码。+行为说明:- **默认列出全部项目** 的会话(进入后可按 `Ctrl+A` 切回仅当前项目)。当前项目无会话时仍会打开(空)选择器,便于按 `Ctrl+A` 查看其它项目。@@ -444,16 +446,77 @@### 快捷键+#### 默认全局快捷键+| 按键 | 行为 ||------|------|-| `Ctrl+C` | **第一次**:中断当前任务(`chat.interrupt`);**1 秒内第二次**:退出 TUI |+| `Ctrl+C` | **第一次**:中断当前任务(`chat.interrupt`);**3 秒内第二次**:退出 TUI(**不可重绑**) |+| `Ctrl+D` | 中断任务;连按两次退出(**不可重绑**) || `Ctrl+L` | 重绘整屏 || `Ctrl+T` | 显示/隐藏 Todos 面板 || `Ctrl+G` | 显示/隐藏 Team 面板 || `Ctrl+O` | 在 transcript **紧凑 / 详细** 视图间切换 |-| `Esc` | 无待处理问题时,若存在可取消的工作,则发送取消 |+| `Esc` | 无 overlay 且存在可取消工作时,发送取消 |++权限类问答中,`y` / `n` 可快速选择允许/拒绝类选项(`Confirmation` context)。++底部 shortcut 提示栏仍显示**默认键名**;若已自定义,请以 `/keybindings list` 或实际按键行为为准。++#### 自定义快捷键(`/keybindings`)++配置文件路径:`~/.jiuwenswarm-tui/keybindings.json`(首次 `/keybindings` 会按当前默认值生成模板)。++| 子命令 | 作用 |+|--------|------|+| `/keybindings` 或 `/keybindings edit` | 创建或打开配置文件;关闭外部编辑器后自动重新加载 |+| `/keybindings list` | 列出当前**生效**的快捷键(按 context 分组) |+| `/keybindings reset` | 删除用户配置文件,恢复内置默认 |++**合并规则**:以内置 `DEFAULT_BINDINGS` 为底,用户 JSON 按 context 覆盖;某键设为 `null` 表示取消该默认绑定。非法键名、未知 action、保留键等会给出 warning,TUI 仍用合法部分继续运行。++**示例**(将重绘改为 `F5`,并取消 Esc 取消任务):++```json+{+ "bindings": [+ {+ "context": "Global",+ "bindings": {+ "f5": "app:redraw",+ "escape": null+ }+ }+ ]+}+```++键名格式需符合 pi-tui 的 `matchesKey` 约定:小写修饰键 `ctrl` / `shift` / `alt`,特殊键如 `pageUp`、`escape`、`return` 等;不支持 chord(空格分隔的多段按键)。++#### 可配置的 Context 与 Action++| Context | 生效场景 | 主要默认键 |+|---------|----------|------------|+| `Global` | 主界面(无 overlay 时部分 Esc 行为) | `ctrl+l/t/g/o`,`escape` → 取消任务 |+| `Scroll` | Transcript 滚动 | `pageUp` / `pageDown`,`ctrl+home/end` |+| `FileViewer` | 全屏文件/日志查看 | `esc`/`q` 退出,`↑↓`/`jk` 行移,`g`/`shift+g` 顶/底 |+| `Confirmation` | 权限/确认问答 | `y` / `n` |+| `TeamPanel` | Team 面板打开 | `←` 返回列表,`↑↓` 选成员,`Enter` 查看 |+| `SwarmWorkflows` | Swarm 工作流视图 | `esc` 返回,`tab`/`→` 切焦点,`l/p/o/e/r` 等 |+| `StatusView` | 状态/配置视图 | `esc` 关闭,`←`/`→` 切标签(搜索框输入仍硬编码) |+| `ResumeList` | 会话选择器列表 | `space` 预览,`ctrl+r` 重命名,`ctrl+a/b`,`esc` 关闭 |+| `Overlay` | MCP 详情/工具子视图 | `esc` 关闭 |++完整 action 名称与说明见 `/keybindings list` 或生成的 `keybindings.json` 模板。++#### 刻意不可重绑或仍硬编码的部分++- **保留键**:`ctrl+c`、`ctrl+d`、`ctrl+m`(终端语义 / 连按退出,见 `reserved.ts`)。+- **Select 列表内部**:`/model`、`/theme`、`/mcp` 等 pi-tui `SelectList` 的上下移动、回车选中、typeahead 过滤。+- **Config 编辑器**:搜索框与值输入阶段的文本键、`/status` 配置 Tab 的 `/` 进入搜索等。+- **Resume 子态**:只读预览态、重命名输入态内的按键逻辑。+- **Diff 查看器**、**Startup 提示**等尚未接入 resolver 的视图。-权限类问答中,`y` / `n` 可快速选择允许/拒绝类选项(`app-screen.ts`)。+如需扩展可配置范围,需在 `actions.ts` / `defaultBindings.ts` 声明 action,并在 `app-screen.ts` 对应输入路径改为 `resolveAction`。### 输入、附件与 `@` 引用diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/hotkey.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/hotkey.tsdeleted file mode 100644index f545ef5cd0..0000000000--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/hotkey.ts+++ /dev/null@@ -1,28 +0,0 @@-import { APP_SCREEN_KEY_BINDINGS } from "../../../ui/keymap.js";-import { addInfo } from "../helpers.js";-import { CommandKind, type SlashCommand } from "../types.js";--export function createHotkeyCommand(): SlashCommand {- return {- name: "hotkey",- description: "Show available keyboard shortcuts",- usage: "/hotkey",- example: "/hotkey",- kind: CommandKind.BUILT_IN,- action: (ctx) => {- ctx.addItem(- addInfo(ctx.sessionId, "Keyboard shortcuts", "k", {- view: "list",- title: "Hotkeys",- items: [- ...APP_SCREEN_KEY_BINDINGS.map((binding) => ({- label: binding.label,- description: binding.description,- })),- { label: "/help", description: "show slash commands" },- ],- }),- );- },- };-}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/keybindings.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/keybindings.tsnew file mode 100644index 0000000000..5b5c584dea--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/keybindings.ts@@ -0,0 +1,146 @@+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";++import { addError, addInfo } from "../helpers.js";+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";+import {+ KEYBINDING_ACTION_DESCRIPTIONS,+ KEYBINDING_CONTEXTS,+ type KeybindingContextName,+} from "../../keybindings/actions.js";+import { getContextBindings, reloadResolver } from "../../keybindings/resolver.js";+import { getKeybindingsPath } from "../../keybindings/store.js";+import { generateKeybindingsTemplate } from "../../keybindings/template.js";+import type { KeybindingWarning } from "../../keybindings/types.js";++function formatWarning(w: KeybindingWarning): string {+ const where = [w.context, w.key].filter(Boolean).join(" / ");+ return where ? `${where}: ${w.message}` : w.message;+}++function applyAndReport(ctx: CommandContext): void {+ const warnings = reloadResolver();+ if (warnings.length > 0) {+ ctx.addItem(+ addError(+ ctx.sessionId,+ `Keybindings 已重新加载,但发现 ${warnings.length} 个问题:\n` ++ warnings.map((w) => ` • ${formatWarning(w)}`).join("\n"),+ ),+ );+ }+}++function openEditor(ctx: CommandContext): void {+ const path = getKeybindingsPath();+ let created = false;+ if (!existsSync(path)) {+ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, generateKeybindingsTemplate(), { encoding: "utf8", flag: "wx" });+ created = true;+ } catch (err) {+ ctx.addItem(addError(ctx.sessionId, `创建 keybindings.json 失败:${(err as Error).message}`));+ return;+ }+ }++ if (!ctx.openInEditor) {+ ctx.addItem(addInfo(ctx.sessionId, `请手动编辑: $EDITOR ${path}`, "k"));+ return;+ }++ ctx.openInEditor(path);+ applyAndReport(ctx);+ ctx.addItem(+ addInfo(ctx.sessionId, `${created ? "已创建并打开" : "已打开"} ${path}(保存后已重新加载)`, "k"),+ );+}++function listBindings(ctx: CommandContext): void {+ const items: Array<{ label: string; description?: string }> = [];+ for (const context of KEYBINDING_CONTEXTS) {+ const bindings = getContextBindings(context as KeybindingContextName);+ if (bindings.length === 0) continue;+ items.push({ label: `[${context}]` });+ for (const { key, action } of bindings) {+ items.push({ label: ` ${key}`, description: KEYBINDING_ACTION_DESCRIPTIONS[action] ?? action });+ }+ }+ ctx.addItem(+ addInfo(ctx.sessionId, "当前生效的快捷键", "k", {+ view: "list",+ title: "Keybindings",+ items,+ }),+ );+}++function resetBindings(ctx: CommandContext): void {+ const path = getKeybindingsPath();+ if (existsSync(path)) {+ try {+ rmSync(path);+ } catch (err) {+ ctx.addItem(addError(ctx.sessionId, `删除 keybindings.json 失败:${(err as Error).message}`));+ return;+ }+ }+ applyAndReport(ctx);+ ctx.addItem(addInfo(ctx.sessionId, "已重置为默认快捷键", "k"));+}++export function createKeybindingsCommand(): SlashCommand {+ return {+ name: "keybindings",+ altNames: ["keybind"],+ description: "Open or create your keybindings configuration file",+ usage: "/keybindings [edit|list|reset]",+ example: "/keybindings",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: async () => ["edit", "list", "reset"],+ subCommands: [+ {+ name: "edit",+ description: "创建/打开 keybindings.json 并在保存后重新加载",+ usage: "/keybindings edit",+ kind: CommandKind.BUILT_IN,+ action: (ctx) => openEditor(ctx),+ },+ {+ name: "list",+ description: "列出当前生效的快捷键",+ usage: "/keybindings list",+ kind: CommandKind.BUILT_IN,+ isSafeConcurrent: true,+ action: (ctx) => listBindings(ctx),+ },+ {+ name: "reset",+ description: "删除用户配置,恢复默认快捷键",+ usage: "/keybindings reset",+ kind: CommandKind.BUILT_IN,+ action: (ctx) => resetBindings(ctx),+ },+ ],+ action: (ctx, args) => {+ const sub = args.trim().split(/\s+/)[0];+ if (!sub || sub === "edit") {+ openEditor(ctx);+ return;+ }+ if (sub === "list") {+ listBindings(ctx);+ return;+ }+ if (sub === "reset") {+ resetBindings(ctx);+ return;+ }+ ctx.addItem(+ addError(ctx.sessionId, `未知子命令:${sub}\n用法:/keybindings [edit|list|reset]`),+ );+ },+ };+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.tsindex aa07455809..124c0616ab 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts@@ -20,6 +20,7 @@ import {import { createExitCommand } from "./builtins/exit.js";import { createHelpCommand } from "./builtins/help.js";import { createHooksCommand } from "./builtins/hooks.js";+import { createKeybindingsCommand } from "./builtins/keybindings.js";import { createInitCommand } from "./builtins/init.js";import { createModelCommand } from "./builtins/model.js";import { createMcpCommand } from "./builtins/mcp.js";@@ -50,6 +51,7 @@ export function createBuiltinCommands(): SlashCommand[] {createAgentsCommand(),createHelpCommand(() => commands),createHooksCommand(),+ createKeybindingsCommand(),createBranchCommand(),createClearCommand(),createInitCommand(),diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.tsnew file mode 100644index 0000000000..6e91df90ad--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts@@ -0,0 +1,146 @@+/**+ * Keybinding contexts and actions for the TUI.+ *+ * Phase 1 scope: only the centrally-managed Global shortcuts (keymap.ts) and+ * transcript Scroll keys are configurable. New contexts/actions are added here+ * as more of app-screen.ts's hardcoded `matchesKey` calls are migrated.+ */++export const KEYBINDING_CONTEXTS = [+ "Global",+ "Scroll",+ "FileViewer",+ "Confirmation",+ "TeamPanel",+ "SwarmWorkflows",+ "StatusView",+ "ResumeList",+ "Overlay",+] as const;++export type KeybindingContextName = (typeof KEYBINDING_CONTEXTS)[number];++export const KEYBINDING_CONTEXT_DESCRIPTIONS: Record<KeybindingContextName, string> = {+ Global: "Active on the main screen, regardless of focus",+ Scroll: "When scrolling the transcript",+ FileViewer: "When viewing a file/log in the full-screen viewer",+ Confirmation: "When a permission/confirmation prompt is shown",+ TeamPanel: "When the team panel is open",+ SwarmWorkflows: "When the swarm workflows view is open",+ StatusView: "When the status/config view is open (tab navigation only)",+ ResumeList: "When the resume session picker is open",+ Overlay:+ "Generic close binding for MCP detail/tool sub-views (list navigation itself is owned by pi-tui)",+};++export const KEYBINDING_ACTIONS = [+ // Global — rebindable.+ // Note: interrupt/exit (ctrl+c / ctrl+d) are intentionally NOT actions here.+ // They are reserved keys with double-press semantics, handled directly in+ // keymap.ts and bypass the resolver, so exposing them as bindable actions+ // would only allow dead (never-fired) user bindings.+ "app:redraw",+ "app:toggleTodos",+ "app:toggleTeamPanel",+ "app:toggleTranscript",+ "app:cancelWork",+ // Scroll+ "scroll:pageUp",+ "scroll:pageDown",+ "scroll:top",+ "scroll:bottom",+ // FileViewer+ "fileViewer:exit",+ "fileViewer:lineUp",+ "fileViewer:lineDown",+ "fileViewer:pageUp",+ "fileViewer:pageDown",+ "fileViewer:top",+ "fileViewer:bottom",+ // Confirmation (permission / confirm prompts — quick allow/reject)+ "confirm:yes",+ "confirm:no",+ // TeamPanel+ "team:prev",+ "team:next",+ "team:back",+ "team:viewMember",+ // SwarmWorkflows+ "swarm:back",+ "swarm:left",+ "swarm:nextFocus",+ "swarm:logs",+ "swarm:viewPrompt",+ "swarm:viewOutcome",+ "swarm:viewError",+ "swarm:refresh",+ // StatusView (tab navigation; search/text entry stays hardcoded)+ "status:close",+ "status:prevTab",+ "status:nextTab",+ // ResumeList (session picker shortcuts; list nav + search text entry, plus the+ // rename-input and preview sub-states, stay hardcoded).+ "resume:close",+ "resume:toggleAllProjects",+ "resume:toggleBranchFilter",+ "resume:preview",+ "resume:rename",+ // Overlay (generic close for MCP sub-views)+ "overlay:close",+] as const;++export type KeybindingAction = (typeof KEYBINDING_ACTIONS)[number];++/** Human-readable descriptions, also used by /keybindings list. */+export const KEYBINDING_ACTION_DESCRIPTIONS: Record<KeybindingAction, string> = {+ "app:redraw": "重绘屏幕",+ "app:toggleTodos": "显示/隐藏 Todos 面板",+ "app:toggleTeamPanel": "显示/隐藏 Team 面板",+ "app:toggleTranscript": "切换 transcript 紧凑/详细视图",+ "app:cancelWork": "取消/暂停当前任务(Esc)",+ "scroll:pageUp": "向上翻页",+ "scroll:pageDown": "向下翻页",+ "scroll:top": "滚动到顶部",+ "scroll:bottom": "滚动到底部",+ "fileViewer:exit": "退出查看器",+ "fileViewer:lineUp": "上移一行",+ "fileViewer:lineDown": "下移一行",+ "fileViewer:pageUp": "向上翻页",+ "fileViewer:pageDown": "向下翻页",+ "fileViewer:top": "跳到顶部",+ "fileViewer:bottom": "跳到底部",+ "confirm:yes": "选择允许类选项(y)",+ "confirm:no": "选择拒绝类选项(n)",+ "team:prev": "上一个成员",+ "team:next": "下一个成员",+ "team:back": "返回成员列表",+ "team:viewMember": "查看选中成员",+ "swarm:back": "返回上一级/关闭",+ "swarm:left": "返回上一级面板",+ "swarm:nextFocus": "切换焦点(phases/agents)",+ "swarm:logs": "查看工作流日志",+ "swarm:viewPrompt": "查看 agent prompt",+ "swarm:viewOutcome": "查看 agent outcome",+ "swarm:viewError": "查看 agent error",+ "swarm:refresh": "刷新工作流视图",+ "status:close": "关闭状态/配置视图",+ "status:prevTab": "上一个标签页",+ "status:nextTab": "下一个标签页",+ "resume:close": "关闭会话选择器(先清空搜索)",+ "resume:toggleAllProjects": "切换“所有项目”过滤",+ "resume:toggleBranchFilter": "切换分支过滤",+ "resume:preview": "预览选中会话(默认 Space,会占用搜索框空格)",+ "resume:rename": "重命名选中会话",+ "overlay:close": "关闭当前浮层",+};++const ACTION_SET = new Set<string>(KEYBINDING_ACTIONS);+const CONTEXT_SET = new Set<string>(KEYBINDING_CONTEXTS);++export function isKeybindingAction(value: string): value is KeybindingAction {+ return ACTION_SET.has(value);+}++export function isKeybindingContext(value: string): value is KeybindingContextName {+ return CONTEXT_SET.has(value);+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.tsnew file mode 100644index 0000000000..5160d9a06b--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts@@ -0,0 +1,107 @@+import type { KeybindingBlock } from "./types.js";++/**+ * Default keybindings that match the current hardcoded TUI behavior.+ * Loaded first; the user's keybindings.json is merged on top.+ *+ * Key ids must be understood by pi-tui's matchesKey (lowercase modifiers+ * ctrl/shift/alt; special keys like pageUp/home/end are case-insensitive).+ *+ * Note: ctrl+c (app:interrupt) and ctrl+d (app:exit) are intentionally NOT+ * listed here — they keep their double-press logic in keymap.ts and are+ * non-rebindable (see reserved.ts).+ */+export const DEFAULT_BINDINGS: KeybindingBlock[] = [+ {+ context: "Global",+ bindings: {+ "ctrl+l": "app:redraw",+ "ctrl+t": "app:toggleTodos",+ "ctrl+g": "app:toggleTeamPanel",+ "ctrl+o": "app:toggleTranscript",+ escape: "app:cancelWork",+ },+ },+ {+ context: "Scroll",+ bindings: {+ pageUp: "scroll:pageUp",+ "shift+pageUp": "scroll:pageUp",+ pageDown: "scroll:pageDown",+ "shift+pageDown": "scroll:pageDown",+ "ctrl+home": "scroll:top",+ "ctrl+end": "scroll:bottom",+ },+ },+ {+ context: "FileViewer",+ bindings: {+ escape: "fileViewer:exit",+ q: "fileViewer:exit",+ up: "fileViewer:lineUp",+ k: "fileViewer:lineUp",+ down: "fileViewer:lineDown",+ j: "fileViewer:lineDown",+ pageUp: "fileViewer:pageUp",+ pageDown: "fileViewer:pageDown",+ home: "fileViewer:top",+ g: "fileViewer:top",+ end: "fileViewer:bottom",+ "shift+g": "fileViewer:bottom",+ },+ },+ {+ context: "Confirmation",+ bindings: {+ y: "confirm:yes",+ n: "confirm:no",+ },+ },+ {+ context: "TeamPanel",+ bindings: {+ left: "team:back",+ up: "team:prev",+ down: "team:next",+ return: "team:viewMember",+ },+ },+ {+ context: "SwarmWorkflows",+ bindings: {+ escape: "swarm:back",+ left: "swarm:left",+ right: "swarm:nextFocus",+ tab: "swarm:nextFocus",+ l: "swarm:logs",+ p: "swarm:viewPrompt",+ o: "swarm:viewOutcome",+ e: "swarm:viewError",+ r: "swarm:refresh",+ },+ },+ {+ context: "StatusView",+ bindings: {+ escape: "status:close",+ left: "status:prevTab",+ right: "status:nextTab",+ },+ },+ {+ context: "ResumeList",+ bindings: {+ escape: "resume:close",+ "ctrl+a": "resume:toggleAllProjects",+ "ctrl+b": "resume:toggleBranchFilter",+ space: "resume:preview",+ "ctrl+r": "resume:rename",+ },+ },+ {+ context: "Overlay",+ bindings: {+ escape: "overlay:close",+ },+ },+];diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/reserved.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/reserved.tsnew file mode 100644index 0000000000..8536d624f4--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/reserved.ts@@ -0,0 +1,82 @@+/**+ * Shortcuts that cannot be rebound — they are hardcoded in keymap.ts with+ * special double-press semantics, mirroring Claude Code's reserved keys.+ */+export interface ReservedShortcut {+ key: string;+ reason: string;+}++export const NON_REBINDABLE: ReservedShortcut[] = [+ { key: "ctrl+c", reason: "中断/退出语义,硬编码(连按两次退出)" },+ { key: "ctrl+d", reason: "退出语义,硬编码(连按两次退出)" },+ { key: "ctrl+m", reason: "终端中等同于 Enter" },+];++/**+ * Normalize a key id for comparison the same way pi-tui's matchesKey does:+ * lowercase, sort modifiers, keep the last segment as the main key.+ * Only `ctrl` / `shift` / `alt` are valid modifiers.+ */+const VALID_MODIFIERS = new Set(["ctrl", "shift", "alt"]);++/**+ * Base key names understood by pi-tui's matchesKey (lowercased — matchesKey+ * lowercases the key id before matching). Mirrors the SpecialKey/Letter/Digit/+ * SymbolKey unions in @mariozechner/pi-tui's KeyId type.+ */+const SPECIAL_KEYS = new Set([+ "escape", "esc", "enter", "return", "tab", "space", "backspace", "delete",+ "insert", "clear", "home", "end", "pageup", "pagedown", "up", "down", "left",+ "right", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",+]);++const SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(""));++/** Whether `main` (already lowercased) is a key name matchesKey can match. */+function isKnownBaseKey(main: string): boolean {+ if (main.length === 1) {+ return (main >= "a" && main <= "z") || (main >= "0" && main <= "9") || SYMBOL_KEYS.has(main);+ }+ return SPECIAL_KEYS.has(main);+}++export function normalizeKey(key: string): string {+ const parts = key.trim().toLowerCase().split("+");+ const main = parts[parts.length - 1] ?? "";+ const mods = parts+ .slice(0, -1)+ .filter((m) => VALID_MODIFIERS.has(m))+ .sort();+ return [...mods, main].join("+");+}++const RESERVED_SET = new Set(NON_REBINDABLE.map((r) => normalizeKey(r.key)));++export function isReservedKey(key: string): boolean {+ return RESERVED_SET.has(normalizeKey(key));+}++/**+ * Validate that a key id is something matchesKey can understand:+ * a single (non-chord) key with only ctrl/shift/alt modifiers and a non-empty+ * main key. Chords (space-separated) are rejected because pi-tui's matchesKey+ * does not support them.+ */+export function validateKeyId(key: string): string | null {+ const trimmed = key.trim();+ if (!trimmed) return "按键不能为空";+ if (/\s/.test(trimmed)) return `不支持组合键(chord):"${key}"`;+ const parts = trimmed.toLowerCase().split("+");+ const main = parts[parts.length - 1];+ if (!main) return `按键格式无效:"${key}"`;+ for (const mod of parts.slice(0, -1)) {+ if (!VALID_MODIFIERS.has(mod)) {+ return `不支持的修饰键 "${mod}"(仅支持 ctrl/shift/alt):"${key}"`;+ }+ }+ if (!isKnownBaseKey(main)) {+ return `未知按键 "${main}"(无法被识别,请检查拼写):"${key}"`;+ }+ return null;+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/resolver.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/resolver.tsnew file mode 100644index 0000000000..111dc3d80d--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/resolver.ts@@ -0,0 +1,47 @@+import { type KeyId, matchesKey } from "@mariozechner/pi-tui";++import type { KeybindingAction, KeybindingContextName } from "./actions.js";+import { loadKeybindings } from "./store.js";+import type { KeybindingWarning, ResolvedBindings } from "./types.js";++// Initialized at module load from defaults + user file. /keybindings triggers+// reloadResolver() after the user edits the file.+let current: ResolvedBindings = loadKeybindings().resolved;++/** Reload bindings from disk. Returns any validation warnings. */+export function reloadResolver(): KeybindingWarning[] {+ const result = loadKeybindings();+ current = result.resolved;+ return result.warnings;+}++/**+ * Resolve a terminal input string to an action within a context.+ * Returns null if no binding in this context matches.+ */+export function resolveAction(+ context: KeybindingContextName,+ data: string,+): KeybindingAction | null {+ const ctxMap = current.get(context);+ if (!ctxMap) return null;+ for (const [key, action] of ctxMap) {+ // Keys in the map are either authored defaults or user keys that passed+ // validateKeyId() (structure + known base key), so they are valid KeyIds.+ // matchesKey is also total over arbitrary strings (unknown ids return+ // false), so this cast can never cause a runtime error.+ if (matchesKey(data, key as KeyId)) {+ return action;+ }+ }+ return null;+}++/** Effective bindings for a context as [key, action] pairs (for /keybindings list). */+export function getContextBindings(+ context: KeybindingContextName,+): Array<{ key: string; action: KeybindingAction }> {+ const ctxMap = current.get(context);+ if (!ctxMap) return [];+ return [...ctxMap.entries()].map(([key, action]) => ({ key, action }));+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/store.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/store.tsnew file mode 100644index 0000000000..ae0d6a5959--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/store.ts@@ -0,0 +1,142 @@+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++import {+ isKeybindingAction,+ isKeybindingContext,+ type KeybindingAction,+} from "./actions.js";+import { DEFAULT_BINDINGS } from "./defaultBindings.js";+import { isReservedKey, validateKeyId } from "./reserved.js";+import type {+ KeybindingBlock,+ KeybindingWarning,+ KeybindingsFile,+ LoadResult,+ ResolvedBindings,+} from "./types.js";++const CONFIG_DIR = join(homedir(), ".jiuwenswarm-tui");+const KEYBINDINGS_FILE = join(CONFIG_DIR, "keybindings.json");++export function getKeybindingsPath(): string {+ return KEYBINDINGS_FILE;+}++export function keybindingsFileExists(): boolean {+ return existsSync(KEYBINDINGS_FILE);+}++/** Build a resolved map from a list of blocks (no validation). */+function buildResolved(blocks: KeybindingBlock[]): ResolvedBindings {+ const resolved: ResolvedBindings = new Map();+ for (const block of blocks) {+ if (!isKeybindingContext(block.context)) continue;+ let ctxMap = resolved.get(block.context);+ if (!ctxMap) {+ ctxMap = new Map<string, KeybindingAction>();+ resolved.set(block.context, ctxMap);+ }+ for (const [key, action] of Object.entries(block.bindings)) {+ if (action === null) {+ ctxMap.delete(key);+ continue;+ }+ if (isKeybindingAction(action)) {+ ctxMap.set(key, action);+ }+ }+ }+ return resolved;+}++/** Apply a user block on top of an already-resolved map, collecting warnings. */+function applyUserBlock(+ resolved: ResolvedBindings,+ block: KeybindingBlock,+ warnings: KeybindingWarning[],+): void {+ if (!isKeybindingContext(block.context)) {+ warnings.push({ context: String(block.context), message: `未知 context:"${block.context}"` });+ return;+ }+ if (typeof block.bindings !== "object" || block.bindings === null) {+ warnings.push({ context: block.context, message: "bindings 必须是对象" });+ return;+ }+ let ctxMap = resolved.get(block.context);+ if (!ctxMap) {+ ctxMap = new Map<string, KeybindingAction>();+ resolved.set(block.context, ctxMap);+ }+ for (const [key, action] of Object.entries(block.bindings)) {+ const keyError = validateKeyId(key);+ if (keyError) {+ warnings.push({ context: block.context, key, message: keyError });+ continue;+ }+ if (isReservedKey(key)) {+ warnings.push({+ context: block.context,+ key,+ message: `"${key}" 是保留键,不可重绑`,+ });+ continue;+ }+ if (action === null) {+ ctxMap.delete(key);+ continue;+ }+ if (typeof action !== "string" || !isKeybindingAction(action)) {+ warnings.push({+ context: block.context,+ key,+ message: `未知 action:"${String(action)}"`,+ });+ continue;+ }+ ctxMap.set(key, action);+ }+}++/**+ * Load keybindings: start from defaults, merge the user's keybindings.json on+ * top. Always succeeds — on any error it falls back to defaults and reports a+ * warning, so the TUI can never fail to start because of a bad config.+ */+export function loadKeybindings(): LoadResult {+ const resolved = buildResolved(DEFAULT_BINDINGS);+ const warnings: KeybindingWarning[] = [];++ if (!existsSync(KEYBINDINGS_FILE)) {+ return { resolved, warnings, userFileLoaded: false };+ }++ let parsed: KeybindingsFile;+ try {+ const raw = readFileSync(KEYBINDINGS_FILE, "utf8").trim();+ if (!raw) {+ return { resolved, warnings, userFileLoaded: false };+ }+ parsed = JSON.parse(raw) as KeybindingsFile;+ } catch (err) {+ warnings.push({ message: `解析 keybindings.json 失败:${(err as Error).message}` });+ return { resolved, warnings, userFileLoaded: false };+ }++ if (!parsed || !Array.isArray(parsed.bindings)) {+ warnings.push({ message: 'keybindings.json 必须包含 "bindings" 数组' });+ return { resolved, warnings, userFileLoaded: true };+ }++ for (const block of parsed.bindings) {+ if (!block || typeof block !== "object") {+ warnings.push({ message: "bindings 数组中存在无效的 block" });+ continue;+ }+ applyUserBlock(resolved, block as KeybindingBlock, warnings);+ }++ return { resolved, warnings, userFileLoaded: true };+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/template.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/template.tsnew file mode 100644index 0000000000..eb18c37bed--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/template.ts@@ -0,0 +1,19 @@+import { DEFAULT_BINDINGS } from "./defaultBindings.js";+import type { KeybindingsFile } from "./types.js";++/**+ * Generate the initial keybindings.json content: a valid file pre-filled with+ * all default bindings, so users can edit in place. Mirrors Claude Code's+ * template approach.+ */+export function generateKeybindingsTemplate(): string {+ const file: KeybindingsFile = {+ $schema: "https://jiuwenswarm/keybindings.schema.json",+ $docs: "docs/zh/TUI使用指南.md#快捷键",+ bindings: DEFAULT_BINDINGS.map((block) => ({+ context: block.context,+ bindings: { ...block.bindings },+ })),+ };+ return JSON.stringify(file, null, 2) + "\n";+}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/types.tsnew file mode 100644index 0000000000..ef291a218f--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/types.ts@@ -0,0 +1,32 @@+import type { KeybindingAction, KeybindingContextName } from "./actions.js";++/**+ * A block of bindings for a single context, as stored in keybindings.json.+ * `null` unbinds a default shortcut.+ */+export interface KeybindingBlock {+ context: KeybindingContextName;+ bindings: Record<string, KeybindingAction | string | null>;+}++export interface KeybindingsFile {+ $schema?: string;+ $docs?: string;+ bindings: KeybindingBlock[];+}++/** Merged, ready-to-query bindings: context -> (keyId -> action). */+export type ResolvedBindings = Map<KeybindingContextName, Map<string, KeybindingAction>>;++export interface KeybindingWarning {+ context?: string;+ key?: string;+ message: string;+}++export interface LoadResult {+ resolved: ResolvedBindings;+ warnings: KeybindingWarning[];+ /** True when a user keybindings.json was found and parsed (even if partially invalid). */+ userFileLoaded: boolean;+}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex d8d5fdacaa..f27fe53e53 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -80,6 +80,7 @@ import {stripBracketedPasteMarkers,} from "../core/pasted-text.js";import { handleAppScreenKeyInput } from "./keymap.js";+import { resolveAction } from "../core/keybindings/resolver.js";import { buildAppScreenLines } from "./screen-layout.js";import { buildTranscriptLines } from "./transcript-renderer.js";import {@@ -1365,56 +1366,38 @@ export class AppScreen implements Component, Focusable {const contentLines = this.fileViewerState.content.split("\n");const height = this.tui.terminal.rows;const availableHeight = Math.max(1, height - 2); // Reserve for title + hint+ const maxScroll = Math.max(0, contentLines.length - availableHeight);- // Esc or q to exit- if (matchesKey(data, "escape") || data.toLowerCase() === "q") {- this.exitFileViewer();- return;- }-- // Scroll up (up arrow or k)- if (matchesKey(data, "up") || data.toLowerCase() === "k") {- this.fileViewerState.scrollOffset = Math.max(0, this.fileViewerState.scrollOffset - 1);- this.tui.requestRender();- return;- }-- // Scroll down (down arrow or j)- if (matchesKey(data, "down") || data.toLowerCase() === "j") {- const maxScroll = Math.max(0, contentLines.length - availableHeight);- this.fileViewerState.scrollOffset = Math.min(maxScroll, this.fileViewerState.scrollOffset + 1);- this.tui.requestRender();- return;- }-- // Page up- if (matchesKey(data, "pageUp")) {- this.fileViewerState.scrollOffset = Math.max(0, this.fileViewerState.scrollOffset - availableHeight);- this.tui.requestRender();- return;- }-- // Page down- if (matchesKey(data, "pageDown")) {- const maxScroll = Math.max(0, contentLines.length - availableHeight);- this.fileViewerState.scrollOffset = Math.min(maxScroll, this.fileViewerState.scrollOffset + availableHeight);- this.tui.requestRender();- return;- }-- // Go to top (Home)- if (matchesKey(data, "home") || data.toLowerCase() === "g") {- this.fileViewerState.scrollOffset = 0;- this.tui.requestRender();- return;- }-- // Go to bottom (End)- if (matchesKey(data, "end") || data.toLowerCase() === "shift+g") {- const maxScroll = Math.max(0, contentLines.length - availableHeight);- this.fileViewerState.scrollOffset = maxScroll;- this.tui.requestRender();- return;+ switch (resolveAction("FileViewer", data)) {+ case "fileViewer:exit":+ this.exitFileViewer();+ return;+ case "fileViewer:lineUp":+ this.fileViewerState.scrollOffset = Math.max(0, this.fileViewerState.scrollOffset - 1);+ this.tui.requestRender();+ return;+ case "fileViewer:lineDown":+ this.fileViewerState.scrollOffset = Math.min(maxScroll, this.fileViewerState.scrollOffset + 1);+ this.tui.requestRender();+ return;+ case "fileViewer:pageUp":+ this.fileViewerState.scrollOffset = Math.max(0, this.fileViewerState.scrollOffset - availableHeight);+ this.tui.requestRender();+ return;+ case "fileViewer:pageDown":+ this.fileViewerState.scrollOffset = Math.min(maxScroll, this.fileViewerState.scrollOffset + availableHeight);+ this.tui.requestRender();+ return;+ case "fileViewer:top":+ this.fileViewerState.scrollOffset = 0;+ this.tui.requestRender();+ return;+ case "fileViewer:bottom":+ this.fileViewerState.scrollOffset = maxScroll;+ this.tui.requestRender();+ return;+ default:+ return;}}@@ -1781,7 +1764,9 @@ export class AppScreen implements Component, Focusable {return;}- if (!pendingQuestion && snapshot.cancellableWork && matchesKey(data, "escape") && !hasOverlay) {+ const isCancelWorkKey = !hasOverlay && resolveAction("Global", data) === "app:cancelWork";++ if (!pendingQuestion && snapshot.cancellableWork && isCancelWorkKey) {if (isTeamMode(snapshot.mode)) {this.state.pause();} else {@@ -1791,7 +1776,7 @@ export class AppScreen implements Component, Focusable {}// 检查不可中断命令列表(ESC 显示提示)- if (!pendingQuestion && snapshot.runningCommand && UNINTERRUPTIBLE_COMMANDS.includes(snapshot.runningCommand) && matchesKey(data, "escape") && !hasOverlay) {+ if (!pendingQuestion && snapshot.runningCommand && UNINTERRUPTIBLE_COMMANDS.includes(snapshot.runningCommand) && isCancelWorkKey) {this.transientNotice = `${snapshot.runningCommand} 命令执行中,无法中断`;if (this.transientNoticeTimer) {clearTimeout(this.transientNoticeTimer);@@ -1899,15 +1884,15 @@ export class AppScreen implements Component, Focusable {}if (permissionRequest && activeQuestion) {- const lower = data.toLowerCase();- if (lower === "y") {+ const confirmAction = resolveAction("Confirmation", data);+ if (confirmAction === "confirm:yes") {const allow = activeQuestion.options.find((option) => isAllowOption(option.label));if (allow) {this.handleQuestionSelection(allow.label);return;}}- if (lower === "n") {+ if (confirmAction === "confirm:no") {const reject = activeQuestion.options.find((option) => isRejectOption(option.label));if (reject) {this.handleQuestionSelection(reject.label);@@ -1961,13 +1946,15 @@ export class AppScreen implements Component, Focusable {}return;}- // Space 打开选中会话的预览(牺牲在搜索框输入空格的能力,按用户要求)- if (matchesKey(data, "space")) {+ const resumeAction = resolveAction("ResumeList", data);+ // These shortcuts must win over search-text input: the default for+ // resume:preview is Space, which would otherwise be typed into the query+ // (intentionally sacrificing the ability to type a space in search).+ if (resumeAction === "resume:preview") {void this.openResumeSessionPreview();return;}- // Ctrl+R 重命名选中会话- if (matchesKey(data, "ctrl+r")) {+ if (resumeAction === "resume:rename") {this.openResumeRename();return;}@@ -1978,11 +1965,11 @@ export class AppScreen implements Component, Focusable {} else if (matchesKey(data, "backspace")) {const newQuery = this.resumeSessionList.searchQuery.slice(0, -1);this.updateResumeSearchQuery(newQuery);- } else if (matchesKey(data, "ctrl+a")) {+ } else if (resumeAction === "resume:toggleAllProjects") {void this.toggleResumeAllProjects();- } else if (matchesKey(data, "ctrl+b")) {+ } else if (resumeAction === "resume:toggleBranchFilter") {this.toggleResumeBranchFilter();- } else if (matchesKey(data, "escape")) {+ } else if (resumeAction === "resume:close") {if (this.resumeSessionList.searchQuery) {this.updateResumeSearchQuery("");} else {@@ -2019,11 +2006,11 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();return;}- if (matchesKey(data, "left")) {+ if (resolveAction("StatusView", data) === "status:prevTab") {this.switchStatusViewTab(-1);return;}- if (matchesKey(data, "right")) {+ if (resolveAction("StatusView", data) === "status:nextTab") {this.switchStatusViewTab(1);return;}@@ -2050,17 +2037,18 @@ export class AppScreen implements Component, Focusable {return;}// Normal mode: Esc to close, / or printable char on config tab enters search- if (matchesKey(data, "escape")) {- this.closeStatusView();- return;- }- if (matchesKey(data, "left")) {- this.switchStatusViewTab(-1);- return;- }- if (matchesKey(data, "right")) {- this.switchStatusViewTab(1);- return;+ switch (resolveAction("StatusView", data)) {+ case "status:close":+ this.closeStatusView();+ return;+ case "status:prevTab":+ this.switchStatusViewTab(-1);+ return;+ case "status:nextTab":+ this.switchStatusViewTab(1);+ return;+ default:+ break;}// On config tab, / enters search mode; printable chars also enter search mode// Use getPrintableChar() for Kitty CSI-u (VSCode) + UTF-8 multi-byte (IME) support@@ -2110,7 +2098,7 @@ export class AppScreen implements Component, Focusable {}if (this.mcpDetail !== null) {- if (matchesKey(data, "escape")) {+ if (resolveAction("Overlay", data) === "overlay:close") {this.mcpDetail = null;this.openMcpList();return;@@ -2123,7 +2111,7 @@ export class AppScreen implements Component, Focusable {}if (this.mcpToolDetail !== null) {- if (matchesKey(data, "escape")) {+ if (resolveAction("Overlay", data) === "overlay:close") {const serverName = this.mcpToolDetail.serverName;this.mcpToolDetail = null;void this.openMcpToolsList(serverName);@@ -2133,7 +2121,7 @@ export class AppScreen implements Component, Focusable {}if (this.mcpTools !== null) {- if (matchesKey(data, "escape")) {+ if (resolveAction("Overlay", data) === "overlay:close") {const serverName = this.mcpTools.serverName;this.mcpTools = null;void this.handleMcpSelection(serverName);@@ -2156,25 +2144,25 @@ export class AppScreen implements Component, Focusable {}if (!snapshot.pendingQuestion && this.showTeamPanel) {- if (matchesKey(data, "left")) {- this.viewedTeamMemberId = null;- this.tui.requestRender();- return;- }- if (matchesKey(data, "return")) {- this.viewedTeamMemberId = this.selectedTeamMemberId;- this.tui.requestRender();- return;- }- if (matchesKey(data, "up")) {- this.moveTeamPanelSelection(snapshot, -1);- this.tui.requestRender();- return;- }- if (matchesKey(data, "down")) {- this.moveTeamPanelSelection(snapshot, 1);- this.tui.requestRender();- return;+ switch (resolveAction("TeamPanel", data)) {+ case "team:back":+ this.viewedTeamMemberId = null;+ this.tui.requestRender();+ return;+ case "team:viewMember":+ this.viewedTeamMemberId = this.selectedTeamMemberId;+ this.tui.requestRender();+ return;+ case "team:prev":+ this.moveTeamPanelSelection(snapshot, -1);+ this.tui.requestRender();+ return;+ case "team:next":+ this.moveTeamPanelSelection(snapshot, 1);+ this.tui.requestRender();+ return;+ default:+ break;}}@@ -2720,27 +2708,27 @@ export class AppScreen implements Component, Focusable {}const pageSize = Math.max(1, Math.floor(this.tui.terminal.rows * 0.8));- if (matchesKey(data, "pageUp") || matchesKey(data, "shift+pageUp")) {- this.transcriptScrollOffset += pageSize;- this.tui.requestRender();- return true;- }- if (matchesKey(data, "pageDown") || matchesKey(data, "shift+pageDown")) {- this.transcriptScrollOffset = Math.max(0, this.transcriptScrollOffset - pageSize);- this.tui.requestRender();- return true;- }- if (matchesKey(data, "ctrl+home")) {- this.transcriptScrollOffset = Number.MAX_SAFE_INTEGER;- this.tui.requestRender();- return true;- }- if (matchesKey(data, "ctrl+end")) {- this.transcriptScrollOffset = 0;- this.tui.requestRender();- return true;+ const scrollAction = resolveAction("Scroll", data);+ switch (scrollAction) {+ case "scroll:pageUp":+ this.transcriptScrollOffset += pageSize;+ this.tui.requestRender();+ return true;+ case "scroll:pageDown":+ this.transcriptScrollOffset = Math.max(0, this.transcriptScrollOffset - pageSize);+ this.tui.requestRender();+ return true;+ case "scroll:top":+ this.transcriptScrollOffset = Number.MAX_SAFE_INTEGER;+ this.tui.requestRender();+ return true;+ case "scroll:bottom":+ this.transcriptScrollOffset = 0;+ this.tui.requestRender();+ return true;+ default:+ return false;}- return false;}private clearPendingSubmittedInput(requestRender = true): void {@@ -4109,7 +4097,8 @@ export class AppScreen implements Component, Focusable {private handleSwarmWorkflowsInput(data: string): void {const state = this.swarmWorkflowsViewState;if (!state) return;- if (matchesKey(data, "escape")) {+ const action = resolveAction("SwarmWorkflows", data);+ if (action === "swarm:back") {if (state.phase === "list") {this.closeSwarmWorkflowsView();} else if (state.phase === "workflow") {@@ -4130,7 +4119,7 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();return;}- if (matchesKey(data, "left")) {+ if (action === "swarm:left") {if (state.phase === "agent") {const lookup = findWorkflowAgent(this.state.getSnapshot().workflowRuns,@@ -4157,7 +4146,7 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();return;}- if (state.phase === "workflow" && (matchesKey(data, "right") || data === "\t")) {+ if (state.phase === "workflow" && action === "swarm:nextFocus") {const nextFocus = state.focus === "phases" ? "agents" : "phases";this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(state.workflowId,@@ -4167,25 +4156,25 @@ export class AppScreen implements Component, Focusable {this.tui.requestRender();return;}- if (state.phase === "workflow" && matchesKey(data, "l")) {+ if (state.phase === "workflow" && action === "swarm:logs") {this.openSwarmWorkflowLogs(state.workflowId);return;}if (state.phase === "agent") {- if (matchesKey(data, "p")) {+ if (action === "swarm:viewPrompt") {this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "prompt");return;}- if (matchesKey(data, "o")) {+ if (action === "swarm:viewOutcome") {this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "outcome");return;}- if (matchesKey(data, "e")) {+ if (action === "swarm:viewError") {this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "error");return;}}- if (matchesKey(data, "r")) {+ if (action === "swarm:refresh") {void this.openSwarmWorkflowsView();this.tui.requestRender();return;diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts b/jiuwenswarm/channels/tui/frontend/src/ui/keymap.tsindex f67c2a3883..a8df420ecf 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts@@ -1,5 +1,8 @@import { matchesKey } from "@mariozechner/pi-tui";+import type { KeybindingAction } from "../core/keybindings/actions.js";+import { resolveAction } from "../core/keybindings/resolver.js";+/*** 快捷键约定(Ctrl+C):* 第一次按下:设置本地中断标志(用于中断长运行命令如日志流);@@ -33,109 +36,109 @@ export interface AppScreenKeymapDelegate {hasServerTask(): boolean;}-interface KeyBinding {+interface KeyBindingDisplay {+ /** Default key id (display only — effective key may differ via keybindings.json). */key: Parameters<typeof matchesKey>[1];label: string;description: string;- run: (delegate: AppScreenKeymapDelegate) => void;+ /** Resolver action; reserved keys (ctrl+c/d) have no rebindable action. */+ action?: KeybindingAction;+}++function runCtrlC(delegate: AppScreenKeymapDelegate): void {+ const now = Date.now();+ if (now - lastInterruptTime < 3000) {+ delegate.exitApp();+ return;+ }++ // Always set local interrupt flag (for long-running local commands).+ // Returns true if an active command request was cancelled — this means+ // Ctrl+C was consumed by command cancellation, not a generic interrupt.+ const commandCancelled = delegate.requestLocalInterrupt();++ // Only send chat.interrupt if there's a server task running+ if (delegate.hasServerTask()) {+ delegate.interruptTask();+ }++ // When a command (e.g. /recap) was cancelled, reset the double-press timer+ // so the user needs TWO fresh Ctrl+C presses to exit, not just one more.+ if (commandCancelled && !delegate.hasServerTask()) {+ lastInterruptTime = 0;+ return;+ }++ // If idle (no server task and no local command running), clear input+ if (delegate.isIdle()) {+ delegate.clearInput();+ }++ delegate.showCtrlCExitHint();+ lastInterruptTime = now;}-export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [- {- key: "ctrl+c",- label: "ctrl+c",- description: "中断任务;连按两次退出",- run: (delegate) => {- const now = Date.now();- if (now - lastInterruptTime < 3000) {- delegate.exitApp();- return;- }-- // Always set local interrupt flag (for long-running local commands)- // Returns true if an active command request was cancelled — this means- // Ctrl+C was consumed by command cancellation, not a generic interrupt.- const commandCancelled = delegate.requestLocalInterrupt();-- // Only send chat.interrupt if there's a server task running- if (delegate.hasServerTask()) {- delegate.interruptTask();- }-- // When a command (e.g. /recap) was cancelled, reset the double-press timer- // so the user needs TWO fresh Ctrl+C presses to exit, not just one more.- if (commandCancelled && !delegate.hasServerTask()) {- lastInterruptTime = 0;- // Don't show the "Press Ctrl+C again to exit" hint — the user just- // cancelled a command, they don't intend to exit the TUI.- return;- }-- // If idle (no server task and no local command running), clear input- if (delegate.isIdle()) {- delegate.clearInput();- }-- // Show hint that pressing Ctrl+C again will exit- delegate.showCtrlCExitHint();-- lastInterruptTime = now;- },- },- {- key: "ctrl+d",- label: "ctrl+d",- description: "中断任务;连按两次退出",- run: (delegate) => {- const now = Date.now();- if (now - lastInterruptTime < 3000) {- delegate.exitApp();- return;- }- lastInterruptTime = now;- delegate.interruptTask();- delegate.showCtrlCExitHint();- },- },- {- key: "ctrl+l",- label: "ctrl+l",- description: "redraw screen",- run: (delegate) => {- delegate.redraw();- },- },- {- key: "ctrl+t",- label: "ctrl+t",- description: "toggle todos",- run: (delegate) => {- delegate.toggleTodos();- },- },- {- key: "ctrl+g",- label: "ctrl+g",- description: "toggle team panel",- run: (delegate) => {- delegate.toggleTeamPanel();- },- },- {- key: "ctrl+o",- label: "ctrl+o",- description: "toggle transcript detail",- run: (delegate) => {- delegate.toggleTranscript();- },- },+function runCtrlD(delegate: AppScreenKeymapDelegate): void {+ const now = Date.now();+ if (now - lastInterruptTime < 3000) {+ delegate.exitApp();+ return;+ }+ lastInterruptTime = now;+ delegate.interruptTask();+ delegate.showCtrlCExitHint();+}++/**+ * Reserved (non-rebindable) keys with special double-press semantics.+ * These bypass the keybindings resolver entirely (see core/keybindings/reserved.ts).+ */+const RESERVED_BINDINGS: ReadonlyArray<{+ key: Parameters<typeof matchesKey>[1];+ run: (delegate: AppScreenKeymapDelegate) => void;+}> = [+ { key: "ctrl+c", run: runCtrlC },+ { key: "ctrl+d", run: runCtrlD },+];++/** Rebindable Global actions → handlers. */+const GLOBAL_ACTION_HANDLERS: Partial<Record<KeybindingAction, (d: AppScreenKeymapDelegate) => void>> = {+ "app:redraw": (d) => d.redraw(),+ "app:toggleTodos": (d) => d.toggleTodos(),+ "app:toggleTeamPanel": (d) => d.toggleTeamPanel(),+ "app:toggleTranscript": (d) => d.toggleTranscript(),+};++/**+ * Display metadata for the main-screen shortcuts (used by the shortcut hint+ * footer). Effective keys come from the resolver; these are the defaults.+ */+export const APP_SCREEN_KEY_BINDINGS: readonly KeyBindingDisplay[] = [+ { key: "ctrl+c", label: "ctrl+c", description: "中断任务;连按两次退出" },+ { key: "ctrl+d", label: "ctrl+d", description: "中断任务;连按两次退出" },+ { key: "ctrl+l", label: "ctrl+l", description: "重绘屏幕", action: "app:redraw" },+ { key: "ctrl+t", label: "ctrl+t", description: "显示/隐藏 Todos 面板", action: "app:toggleTodos" },+ { key: "ctrl+g", label: "ctrl+g", description: "显示/隐藏 Team 面板", action: "app:toggleTeamPanel" },+ { key: "ctrl+o", label: "ctrl+o", description: "切换 transcript 紧凑/详细视图", action: "app:toggleTranscript" },] as const;export function handleAppScreenKeyInput(data: string, delegate: AppScreenKeymapDelegate): boolean {- for (const binding of APP_SCREEN_KEY_BINDINGS) {- if (!matchesKey(data, binding.key)) continue;- binding.run(delegate);- return true;+ // Reserved keys first — never rebindable.+ for (const binding of RESERVED_BINDINGS) {+ if (matchesKey(data, binding.key)) {+ binding.run(delegate);+ return true;+ }+ }++ // Rebindable Global actions via the keybindings resolver.+ const action = resolveAction("Global", data);+ if (action) {+ const handler = GLOBAL_ACTION_HANDLERS[action];+ if (handler) {+ handler(delegate);+ return true;+ }}return false;