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
fix(tui): /resume adds shortcuts and functions like Ctrl+A, Ctrl+B, Space, Ctrl+R, etc.
kdgmpw59d3ab294e21
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex d476e94503..d8c87f7da6 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -124,6 +124,28 @@ Manages directories AI can access for file read, edit, and execute operations.- `/resume list`: List historical sessions.- `/resume <conversation_id>`: Resume specified session.+#### Interactive picker (TUI)++Entering **`/resume`** or **`/continue`** with **no arguments** opens an interactive session picker (instead of a plain `session.list` dump).++| Key | Action |+| --- | --- |+| `↑` / `↓` | Move focus between sessions |+| `Enter` | Resume the focused session |+| type chars | Live search (filter by session ID / title / project dir) |+| `Backspace` | Delete a search character |+| `Space` | Preview the focused session info card (title, ID, project dir, branch, message count, last active / created). In preview: `Enter` resumes, `Space`/`Esc` goes back |+| `Ctrl+R` | Rename the focused session. In edit mode: `Enter` saves, `Esc` cancels, empty value clears the title |+| `Ctrl+A` | Toggle scope between "all projects" and "current project only" |+| `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 |++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`.+- **Branch recording & filtering (`Ctrl+B`)**: a session's git branch is recorded (per its `project_dir`) on the first message (`HEAD` for non-git/detached). When the filter is on, sessions are matched by branch **name** strictly; legacy sessions without a recorded branch and `HEAD` sessions are filtered out. Note the match is by name only and not repo-aware — with "all projects + branch filter" enabled, same-named branches in different directories are shown together.+- **Restore scope**: resume only restores the **conversation context** (history, session ID, accent color, workflow snapshot, window title); it does **not** switch the workspace / current working directory.+### `/model` (View / Add / Switch Model)- Usage: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 c7cf7b2c63..f5500e73df 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"@@ -124,6 +124,30 @@- `/resume list`:列出历史会话。- `/resume <conversation_id>`:恢复指定会话。+#### 交互式选择器(TUI)++输入 **`/resume`** 或 **`/continue`** 且无参数时,打开交互式会话选择器:++| 按键 | 功能 |+| --- | --- |+| `↑` / `↓` | 移动焦点 |+| `Enter` | 恢复焦点会话 |+| 输入字符 | 实时搜索(会话 ID / 标题 / 项目目录) |+| `Backspace` | 删除搜索字符 |+| `Space` | 预览焦点会话信息卡;预览态 `Enter` 恢复、`Space`/`Esc` 返回 |+| `Ctrl+R` | 重命名焦点会话;编辑态 `Enter` 保存、`Esc` 取消、留空清除标题 |+| `Ctrl+A` | 「全部项目」与「仅当前项目」范围切换 |+| `Ctrl+B` | 开关 git 分支过滤(严格匹配当前项目分支名) |+| `Esc` | 有搜索词时清空;否则关闭选择器 |++说明:++- **默认列出全部项目** 的会话(`Ctrl+A` 切回仅当前项目);当前项目无会话时仍打开(空)选择器以便按 `Ctrl+A`。+- **分支过滤** 仅按分支名严格匹配,存量无分支记录与 `HEAD` 会话会被过滤;按名比对不区分仓库,「全部项目 + 分支过滤」时同名分支会一并显示。+- **恢复范围**:仅恢复会话上下文(历史、会话 ID、accent 颜色、workflow 快照、窗口标题),**不切换 workspace / 当前工作目录**。++> 完整快捷键与行为详见 [TUI 使用指南](TUI使用指南.md#resume-与-continue-在-tui-中的特殊行为)。+### `/model`(查看 / 新增 / 切换模型)- 用法: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 9c478ac46e..3a36d03de7 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"@@ -92,9 +92,29 @@#### `/resume` 与 `/continue` 在 TUI 中的特殊行为-- 输入 **`/resume`** 或 **`/continue`** 且 **无其它参数** 时,TUI 会打开 **会话列表** 供选择恢复,而不走纯文本 `session.list` 展示(`app-screen.ts`)。+- 输入 **`/resume`** 或 **`/continue`** 且 **无其它参数** 时,TUI 会打开 **交互式会话选择器** 供选择恢复,而不走纯文本 `session.list` 展示(`app-screen.ts`)。- 带参数时仍走命令实现:`/resume list`、`/resume <conversation_id>` 等。+交互式选择器的快捷键:++| 按键 | 功能 |+| --- | --- |+| `↑` / `↓` | 在会话间移动焦点 |+| `Enter` | 恢复当前焦点的会话 |+| 输入字符 | 实时搜索(按会话 ID / 标题 / 项目目录过滤) |+| `Backspace` | 删除搜索字符 |+| `Space` | 预览当前焦点会话的信息卡(标题、ID、项目目录、分支、消息数、最近活跃/创建时间);预览态 `Enter` 恢复、`Space`/`Esc` 返回 |+| `Ctrl+R` | 重命名当前焦点会话;编辑态 `Enter` 保存、`Esc` 取消、留空则清除标题 |+| `Ctrl+A` | 在「全部项目」与「仅当前项目」范围间切换 |+| `Ctrl+B` | 开关 git 分支过滤(仅显示 `git_branch` 严格等于当前项目分支的会话) |+| `Esc` | 有搜索词时清空搜索;否则关闭选择器 |++行为说明:++- **默认列出全部项目** 的会话(进入后可按 `Ctrl+A` 切回仅当前项目)。当前项目无会话时仍会打开(空)选择器,便于按 `Ctrl+A` 查看其它项目。+- **分支记录与过滤(`Ctrl+B`)**:会话首条消息时会按其 `project_dir` 记录 git 分支(非 git/detached 记为 `HEAD`)。开启过滤后按「分支名」**严格匹配**当前项目分支,存量无分支记录的会话与 `HEAD` 会话都会被过滤掉;关掉过滤即可看到全部。注意分支过滤仅按名字比对,不区分仓库——「全部项目 + 分支过滤」同时开启时,不同目录下的同名分支会一并显示。+- **恢复范围**:resume 仅恢复 **会话上下文**(对话历史、会话 ID、accent 颜色、workflow 快照、窗口标题),**不切换 workspace / 当前工作目录**。+---### 重点命令说明diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.tsindex 301ae1c1ea..a813ff9f56 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts@@ -12,6 +12,8 @@ export interface SessionMeta {message_count?: number;/** 会话所属项目目录(由 gateway 从 channel_metadata 中提取) */project_dir?: string;+ /** 会话首条消息时所在的 git 分支(gateway 回填;非 git/detached 为 "HEAD",存量会话为空串) */+ git_branch?: string;}export interface SessionListPayload {@@ -19,6 +21,8 @@ export interface SessionListPayload {total?: number;limit?: number;offset?: number;+ /** 当前项目的 git 分支(gateway 计算;非 git/失败为 "HEAD"),供 Ctrl+B 分支过滤对比 */+ current_branch?: string;}export interface ResumeResumePayload {diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 8bfa62045e..6e7cbd57a3 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -165,6 +165,13 @@ type ResumeSessionListState = {sessions: SessionMeta[];total: number;searchQuery: string;+ showAllProjects: boolean;+ branchFilterEnabled: boolean;+ currentBranch: string;+ /** 非空时进入只读预览态(Space 触发,对齐 Claude Code preview):展示选中会话的信息卡 */+ preview: SessionMeta | null;+ /** 非空时进入重命名态(Ctrl+R 触发,对齐 Claude Code Ctrl+R):编辑选中会话标题 */+ rename: { sessionId: string; value: string } | null;};type ModelListState = {@@ -741,10 +748,11 @@ function getDisplayLabel(s: SessionMeta): string {return s.session_id;}-function sessionToSelectItem(s: SessionMeta): SelectItem {+function sessionToSelectItem(s: SessionMeta, showProject = false): SelectItem {const parts: string[] = [formatRelativeTime(s.last_message_at)];const msgCount = s.message_count ?? 0;if (msgCount > 0) parts.push(`${msgCount} msgs`);+ if (showProject && s.project_dir?.trim()) parts.push(s.project_dir.trim());return {value: s.session_id,label: getDisplayLabel(s),@@ -752,19 +760,34 @@ function sessionToSelectItem(s: SessionMeta): SelectItem {};}-function buildResumeSessionItems(sessions: SessionMeta[]): SelectItem[] {- return sessions.map(sessionToSelectItem);-}+type ResumeItemOptions = {+ query: string;+ showProject: boolean;+ branchFilter: boolean;+ currentBranch: string;+};-function filterResumeSessions(sessions: SessionMeta[], query: string): SelectItem[] {- const normalizedQuery = query.toLowerCase();- return sessions- .filter((s) => {+function computeResumeItems(sessions: SessionMeta[], opts: ResumeItemOptions): SelectItem[] {+ let list = sessions;+ // 按 git 分支过滤(对齐 Claude Code Ctrl+B):严格匹配当前分支。+ // 无分支记录的存量会话、以及非 git/HEAD 会话都会被过滤掉;关掉 Ctrl+B 即可看到全部。+ if (opts.branchFilter && opts.currentBranch) {+ list = list.filter((s) => (s.git_branch ?? "").trim() === opts.currentBranch);+ }+ const normalizedQuery = opts.query.toLowerCase();+ if (normalizedQuery) {+ list = list.filter((s) => {const label = getDisplayLabel(s).toLowerCase();const sid = s.session_id.toLowerCase();- return label.includes(normalizedQuery) || sid.includes(normalizedQuery);- })- .map(sessionToSelectItem);+ const proj = (s.project_dir ?? "").toLowerCase();+ return (+ label.includes(normalizedQuery) ||+ sid.includes(normalizedQuery) ||+ (opts.showProject && proj.includes(normalizedQuery))+ );+ });+ }+ return list.map((s) => sessionToSelectItem(s, opts.showProject));}function formatConfigValue(schema: ConfigItemSchema, val: string): string {@@ -1368,6 +1391,53 @@ export class AppScreen implements Component, Focusable {}if (!snapshot.pendingQuestion && this.resumeSessionList !== null) {+ // 重命名态:Enter 保存,Esc 取消,其余按键编辑标题(允许空格)+ if (this.resumeSessionList.rename !== null) {+ if (matchesKey(data, "return")) {+ void this.submitResumeRename();+ } else if (matchesKey(data, "escape")) {+ this.resumeSessionList = { ...this.resumeSessionList, rename: null };+ this.tui.requestRender();+ } else if (matchesKey(data, "backspace")) {+ const r = this.resumeSessionList.rename;+ this.resumeSessionList = {+ ...this.resumeSessionList,+ rename: { ...r, value: r.value.slice(0, -1) },+ };+ this.tui.requestRender();+ } else {+ const ch = this.getPrintableChar(data);+ if (ch !== undefined) {+ const r = this.resumeSessionList.rename;+ this.resumeSessionList = {+ ...this.resumeSessionList,+ rename: { ...r, value: r.value + ch },+ };+ this.tui.requestRender();+ }+ }+ return;+ }+ // 只读预览态:Enter 恢复该会话,Space/Esc 返回列表,其余按键忽略+ if (this.resumeSessionList.preview !== null) {+ if (matchesKey(data, "return")) {+ void this.handleResumeSessionSelection(this.resumeSessionList.preview.session_id);+ } else if (matchesKey(data, "space") || matchesKey(data, "escape")) {+ this.resumeSessionList = { ...this.resumeSessionList, preview: null };+ this.tui.requestRender();+ }+ return;+ }+ // Space 打开选中会话的预览(牺牲在搜索框输入空格的能力,按用户要求)+ if (matchesKey(data, "space")) {+ this.openResumeSessionPreview();+ return;+ }+ // Ctrl+R 重命名选中会话+ if (matchesKey(data, "ctrl+r")) {+ this.openResumeRename();+ return;+ }const printableChar = this.getPrintableChar(data);if (printableChar !== undefined) {const newQuery = this.resumeSessionList.searchQuery + printableChar;@@ -1375,6 +1445,10 @@ 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")) {+ void this.toggleResumeAllProjects();+ } else if (matchesKey(data, "ctrl+b")) {+ this.toggleResumeBranchFilter();} else if (matchesKey(data, "escape")) {if (this.resumeSessionList.searchQuery) {this.updateResumeSearchQuery("");@@ -1603,9 +1677,15 @@ export class AppScreen implements Component, Focusable {// IME composing text from appearing in the bottom input box instead of the config panel.// input_value phase: editor is rendered inside buildConfigEditorLines.// search_list/select_value phase: no text input needed in the main editor.+ // The resume picker has its own search input, so hide the main editor while it is+ // open to avoid a misleading second input bar (restored on Esc). Mirrors Claude Code.const isConfigEditorActive = this.configEditorState !== null;const hideEditorForInlinePlanReject = this.isEditingInlinePlanReject(snapshot);- const editorLines = isConfigEditorActive || hideEditorForInlinePlanReject+ const hideMainEditor =+ isConfigEditorActive ||+ hideEditorForInlinePlanReject ||+ this.resumeSessionList !== null;+ const editorLines = hideMainEditor? []: this.applySlashCommandHint(this.editor.render(width), width);const composerPreviewLines: string[] = [];@@ -1891,7 +1971,8 @@ export class AppScreen implements Component, Focusable {this.editor.addToHistory(text);this.editor.setText("");this.state.addItem(addCommandEcho(snapshot.sessionId, text));- await this.openResumeSessionList();+ // 默认列出全部项目的会话;进入后可按 Ctrl+A 切回仅当前项目+ await this.openResumeSessionList(true);return;}if (/^\/model\s*$/.test(text)) {@@ -2147,33 +2228,57 @@ export class AppScreen implements Component, Focusable {}}- private async openResumeSessionList(): Promise<void> {+ private makeResumeSelectList(items: SelectItem[]): SelectList {+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {+ minPrimaryColumnWidth: 24,+ maxPrimaryColumnWidth: 42,+ });+ list.onSelect = (item) => {+ if (item && item.value) {+ void this.handleResumeSessionSelection(item.value);+ }+ };+ list.onCancel = () => {+ this.resumeSessionList = null;+ this.tui.requestRender();+ };+ return list;+ }++ private async openResumeSessionList(allProjects = false): Promise<void> {const snapshot = this.state.getSnapshot();try {- const payload = await this.state.request<SessionListPayload>("session.list", {});+ const payload = await this.state.request<SessionListPayload>("session.list", {+ all_projects: allProjects,+ });const sessions = payload.sessions ?? [];const total = payload.total ?? sessions.length;- if (sessions.length === 0) {+ const currentBranch = payload.current_branch ?? "HEAD";+ // 全部项目仍为空:确无可恢复会话,直接提示,不打开选择器+ if (sessions.length === 0 && allProjects) {this.resumeSessionList = null;this.state.addItem(addInfo(snapshot.sessionId, "No sessions found", "r"));return;}+ // 当前项目为空:仍打开(空)选择器,便于用户按 Ctrl+A 切到全部项目- const items = buildResumeSessionItems(sessions);- const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {- minPrimaryColumnWidth: 24,- maxPrimaryColumnWidth: 42,+ const items = computeResumeItems(sessions, {+ query: "",+ showProject: allProjects,+ branchFilter: false,+ currentBranch,});- list.onSelect = (item) => {- if (item && item.value) {- void this.handleResumeSessionSelection(item.value);- }- };- list.onCancel = () => {- this.resumeSessionList = null;- this.tui.requestRender();+ this.resumeSessionList = {+ list: this.makeResumeSelectList(items),+ sessions,+ total,+ searchQuery: "",+ showAllProjects: allProjects,+ branchFilterEnabled: false,+ currentBranch,+ preview: null,+ rename: null,};- this.resumeSessionList = { list, sessions, total, searchQuery: "" };this.tui.requestRender();} catch (error) {const message = error instanceof Error ? error.message : String(error);@@ -2182,6 +2287,60 @@ export class AppScreen implements Component, Focusable {}}+ private async toggleResumeAllProjects(): Promise<void> {+ if (!this.resumeSessionList) return;+ const next = !this.resumeSessionList.showAllProjects;+ const { searchQuery, branchFilterEnabled } = this.resumeSessionList;+ const snapshot = this.state.getSnapshot();+ try {+ const payload = await this.state.request<SessionListPayload>("session.list", {+ all_projects: next,+ });+ const sessions = payload.sessions ?? [];+ const total = payload.total ?? sessions.length;+ const currentBranch = payload.current_branch ?? this.resumeSessionList.currentBranch;+ const items = computeResumeItems(sessions, {+ query: searchQuery,+ showProject: next,+ branchFilter: branchFilterEnabled,+ currentBranch,+ });+ this.resumeSessionList = {+ list: this.makeResumeSelectList(items),+ sessions,+ total,+ searchQuery,+ showAllProjects: next,+ branchFilterEnabled,+ currentBranch,+ preview: null,+ rename: null,+ };+ this.tui.requestRender();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.state.addItem(addError(snapshot.sessionId, `resume failed: ${message}`));+ }+ }++ private toggleResumeBranchFilter(): void {+ if (!this.resumeSessionList) return;+ const st = this.resumeSessionList;+ const next = !st.branchFilterEnabled;+ const items = computeResumeItems(st.sessions, {+ query: st.searchQuery,+ showProject: st.showAllProjects,+ branchFilter: next,+ currentBranch: st.currentBranch,+ });+ this.resumeSessionList = {+ ...st,+ list: this.makeResumeSelectList(items),+ branchFilterEnabled: next,+ };+ this.tui.requestRender();+ }+private async handleResumeSessionSelection(sessionId: string): Promise<void> {if (!sessionId || typeof sessionId !== "string") {return;@@ -2265,24 +2424,132 @@ export class AppScreen implements Component, Focusable {private updateResumeSearchQuery(query: string): void {if (!this.resumeSessionList) return;- const filteredItems = filterResumeSessions(this.resumeSessionList.sessions, query);- const list = new SelectList(filteredItems, Math.min(Math.max(filteredItems.length, 1), 8), selectListTheme, {- minPrimaryColumnWidth: 24,- maxPrimaryColumnWidth: 42,+ const st = this.resumeSessionList;+ const filteredItems = computeResumeItems(st.sessions, {+ query,+ showProject: st.showAllProjects,+ branchFilter: st.branchFilterEnabled,+ currentBranch: st.currentBranch,});- list.onSelect = (item) => {- if (item && item.value) {- void this.handleResumeSessionSelection(item.value);- }+ this.resumeSessionList = {+ ...st,+ list: this.makeResumeSelectList(filteredItems),+ searchQuery: query,};- list.onCancel = () => {- this.resumeSessionList = null;- this.tui.requestRender();+ this.tui.requestRender();+ }++ /** 打开选中会话的只读预览(信息卡)。Space 触发,对齐 Claude Code 的 preview。 */+ private openResumeSessionPreview(): void {+ if (!this.resumeSessionList) return;+ const selected = this.resumeSessionList.list.getSelectedItem();+ if (!selected) return;+ const session = this.resumeSessionList.sessions.find(+ (s) => s.session_id === selected.value,+ );+ if (!session) return;+ this.resumeSessionList = { ...this.resumeSessionList, preview: session };+ this.tui.requestRender();+ }++ /** 进入重命名态,初始值取当前标题。Ctrl+R 触发,对齐 Claude Code。 */+ private openResumeRename(): void {+ if (!this.resumeSessionList) return;+ const selected = this.resumeSessionList.list.getSelectedItem();+ if (!selected) return;+ const session = this.resumeSessionList.sessions.find(+ (s) => s.session_id === selected.value,+ );+ if (!session) return;+ this.resumeSessionList = {+ ...this.resumeSessionList,+ rename: { sessionId: session.session_id, value: session.title?.trim() ?? "" },};- this.resumeSessionList = { ...this.resumeSessionList, list, searchQuery: query };this.tui.requestRender();}+ /** 提交重命名:调用 session.rename 写入标题,成功后就地更新列表并退出重命名态。 */+ private async submitResumeRename(): Promise<void> {+ if (!this.resumeSessionList || !this.resumeSessionList.rename) return;+ const st = this.resumeSessionList;+ const { sessionId, value } = st.rename!;+ const title = value.trim();+ try {+ const resp = await this.state.request<{ session_id: string; title: string }>(+ "session.rename",+ { session_id: sessionId, title },+ );+ const newTitle = resp.title ?? title;+ // 就地更新本地会话标题并重建列表项+ const sessions = st.sessions.map((s) =>+ s.session_id === sessionId ? { ...s, title: newTitle } : s,+ );+ const items = computeResumeItems(sessions, {+ query: st.searchQuery,+ showProject: st.showAllProjects,+ branchFilter: st.branchFilterEnabled,+ currentBranch: st.currentBranch,+ });+ this.resumeSessionList = {+ ...st,+ sessions,+ list: this.makeResumeSelectList(items),+ rename: null,+ };+ // 若重命名的是当前活动会话,同步终端窗口标题+ if (sessionId === this.state.getSnapshot().sessionId) {+ this.state.setSessionTitle(newTitle);+ }+ this.tui.requestRender();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.resumeSessionList = { ...st, rename: null };+ this.state.addItem(+ addError(this.state.getSnapshot().sessionId, `rename failed: ${message}`),+ );+ this.tui.requestRender();+ }+ }++ private buildResumeSessionRenameLines(width: number, session: SessionMeta | undefined, value: string): string[] {+ const placeholder = session?.title?.trim() || session?.session_id || "";+ return [+ padToWidth(palette.status.warning("Rename session"), width),+ padToWidth(palette.text.dim(session?.session_id ?? ""), width),+ "",+ padToWidth(`${palette.text.dim("Title: ")}${palette.text.primary(value)}${END_CURSOR}`, width),+ value.length === 0+ ? padToWidth(palette.text.dim(`(current: ${placeholder})`), width)+ : "",+ "",+ padToWidth(palette.text.dim("Enter save · Esc cancel · empty clears title"), width),+ ].filter((l) => l !== "");+ }++ private buildResumeSessionPreviewLines(width: number, session: SessionMeta): string[] {+ const title = session.title?.trim() || "(untitled)";+ const project = session.project_dir?.trim() || "-";+ const branch = session.git_branch?.trim() || "(unknown)";+ const msgs = session.message_count ?? 0;+ const lastActive = formatRelativeTime(session.last_message_at);+ const created = formatRelativeTime(session.created_at);+ const row = (k: string, v: string) =>+ padToWidth(`${palette.text.dim(k.padEnd(11))}${palette.text.primary(v)}`, width);+ return [+ padToWidth(palette.status.warning("Session preview"), width),+ padToWidth(palette.text.primary(title), width),+ "",+ row("ID", session.session_id),+ row("Project", project),+ row("Branch", branch),+ row("Messages", String(msgs)),+ row("Last active", lastActive),+ row("Created", created),+ "",+ padToWidth(palette.text.dim("Enter resume · Space/Esc back"), width),+ ];+ }+private buildStartupPromptLines(width: number): string[] {if (!this.startupPromptList) {return [];@@ -2307,21 +2574,59 @@ export class AppScreen implements Component, Focusable {if (!this.resumeSessionList) {return [];}+ if (this.resumeSessionList.rename !== null) {+ const r = this.resumeSessionList.rename;+ const session = this.resumeSessionList.sessions.find((s) => s.session_id === r.sessionId);+ return this.buildResumeSessionRenameLines(width, session, r.value);+ }+ if (this.resumeSessionList.preview !== null) {+ return this.buildResumeSessionPreviewLines(width, this.resumeSessionList.preview);+ }+ const showAll = this.resumeSessionList.showAllProjects;+ const branchOn = this.resumeSessionList.branchFilterEnabled;+ const scopeLabel = showAll ? "all projects" : "current dir";+ const projectHint = showAll ? "Ctrl+A current dir" : "Ctrl+A all projects";+ const branchHint = branchOn+ ? `Ctrl+B all branches`+ : `Ctrl+B branch:${this.resumeSessionList.currentBranch}`;+ const toggleHint = `${projectHint} · ${branchHint}`;+ const scopeSuffix = branchOn ? ` · branch:${this.resumeSessionList.currentBranch}` : "";const searchBox = this.resumeSessionList.searchQuery? padToWidth(palette.text.primary(`Search: ${this.resumeSessionList.searchQuery}${END_CURSOR}`), width)- : padToWidth(palette.text.dim("Type to search · ↑/↓ choose · Enter resume · Esc cancel"), width);+ : padToWidth(+ palette.text.dim(`Type to search · ↑/↓ choose · Enter resume · Space preview · Ctrl+R rename · ${toggleHint} · Esc cancel`),+ width,+ );+ const st = this.resumeSessionList;+ const visibleCount = computeResumeItems(st.sessions, {+ query: st.searchQuery,+ showProject: st.showAllProjects,+ branchFilter: st.branchFilterEnabled,+ currentBranch: st.currentBranch,+ }).length;+ const emptyMessage = st.searchQuery+ ? "No matches"+ : showAll+ ? "No sessions found"+ : "No sessions in current project · press Ctrl+A to search all projects";+ const listLines =+ visibleCount === 0+ ? [padToWidth(palette.text.dim(emptyMessage), width)]+ : this.resumeSessionList.list.render(width);return [padToWidth(- palette.status.warning(`Resume session (${this.resumeSessionList.total} total)`),+ palette.status.warning(+ `Resume session (${this.resumeSessionList.total} total · ${scopeLabel}${scopeSuffix})`,+ ),width,),searchBox,- ...this.resumeSessionList.list.render(width),+ ...listLines,padToWidth(palette.text.dim(this.resumeSessionList.searchQuery- ? "Backspace delete · Enter resume · Esc clear"- : "↑/↓ choose · Enter resume · Esc cancel"+ ? `Backspace delete · Enter resume · Space preview · Ctrl+R rename · ${toggleHint} · Esc clear`+ : `↑/↓ choose · Enter resume · Space preview · Ctrl+R rename · ${toggleHint} · Esc cancel`),width,),diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex b1e5a246cc..7e6e2a60c6 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1432,6 +1432,45 @@ def get_agent_sessions_dir() -> Path:return get_agent_root_dir() / "sessions"+# 当前 git 分支解析(带短 TTL 缓存),用于 /resume 按分支过滤会话。+# 对齐 Claude Code:非 git 目录 / detached HEAD / 任何失败一律返回 "HEAD" 哨兵值。+_GIT_BRANCH_CACHE: dict[str, tuple[float, str]] = {}+_GIT_BRANCH_TTL_SECONDS = 5.0+++def resolve_git_branch(project_dir: str | None) -> str:+ """返回 ``project_dir`` 当前 git 分支,取不到时返回哨兵 ``"HEAD"``。++ 结果按 ``project_dir`` 缓存数秒,避免在 session.list / 每次聊天请求时+ 频繁 spawn git 进程。+ """+ if not project_dir or not os.path.isdir(project_dir):+ return "HEAD"+ now = time.time()+ cached = _GIT_BRANCH_CACHE.get(project_dir)+ if cached and now - cached[0] < _GIT_BRANCH_TTL_SECONDS:+ return cached[1]+ branch = "HEAD"+ git_bin = shutil.which("git")+ if git_bin:+ try:+ import subprocess++ result = subprocess.run(+ [git_bin, "rev-parse", "--abbrev-ref", "HEAD"],+ capture_output=True,+ text=True,+ timeout=5,+ cwd=project_dir,+ )+ if result.returncode == 0:+ branch = result.stdout.strip() or "HEAD"+ except Exception:+ branch = "HEAD"+ _GIT_BRANCH_CACHE[project_dir] = (now, branch)+ return branch++_legacy_migration_done: bool = Falsediff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex b716f07202..4755b5f44c 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -674,6 +674,11 @@ class GatewayServer:project_dir = params.get("project_dir")if project_dir and isinstance(project_dir, str) and project_dir.strip():metadata["project_dir"] = project_dir.strip()+ # 记录会话首条消息时所在的 git 分支,供 /resume 按分支过滤(Ctrl+B)。+ # 非 git/detached/失败时为哨兵 "HEAD",对齐 Claude Code。+ from jiuwenswarm.common.utils import resolve_git_branch++ metadata["git_branch"] = resolve_git_branch(project_dir.strip())is_stream = bool(data.get("is_stream", False))diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex e4561a51d2..ca08b8fb42 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -1174,6 +1174,11 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:else [])# 按项目目录过滤 + 排除当前会话(对齐 Claude Code /resume 行为)+ # all_projects=True 时跳过项目过滤,列出所有项目的会话(对齐 CC 的 Ctrl+A)+ show_all_projects = (+ bool(params.get("all_projects"))+ if isinstance(params, dict) else False+ )project_dir = (str(params.get("project_dir", "")).strip()if isinstance(params, dict) else ""@@ -1187,6 +1192,8 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:current_sid = str(session_id or "").strip()def _session_matches_project(s):+ if show_all_projects:+ return Trueif not project_dir:return Truech_meta = s.get("channel_metadata") or {}@@ -1219,7 +1226,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:)cli_sessions = cli_sessions[:limit]- # 附带每个会话的 project_dir 供前端判断跨项目恢复+ # 附带每个会话的 project_dir / git_branch 供前端判断跨项目恢复 + 按分支过滤for s in cli_sessions:ch_meta = s.get("channel_metadata") or {}sp = (ch_meta.get("project_dir") or ch_meta.get("cwd") or "").strip()@@ -1229,8 +1236,20 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:except OSError:passs["project_dir"] = sp+ # 会话首条消息时记录的分支;存量会话无该字段时回填空串(前端按"兜底显示"处理)+ s["git_branch"] = str(ch_meta.get("git_branch") or "").strip()++ # 当前项目的 git 分支,供前端 Ctrl+B 过滤对比(非 git/失败为哨兵 "HEAD")+ from jiuwenswarm.common.utils import resolve_git_branch- await channel.send_response(ws, req_id, ok=True, payload={"sessions": cli_sessions})+ current_branch = resolve_git_branch(project_dir or None)++ await channel.send_response(+ ws,+ req_id,+ ok=True,+ payload={"sessions": cli_sessions, "current_branch": current_branch},+ )async def _session_create(ws, req_id, params, session_id):from jiuwenswarm.common.utils import get_agent_sessions_dir