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 --session命令启动后端调用/resume以及对session_id的限制
Lexie-73fae43e95a14
diff --git a/docs/en/Quickstart_tui.md b/docs/en/Quickstart_tui.mdindex 531e13abb2..62bbc01e39 100644--- a/docs/en/Quickstart_tui.md+++ b/docs/en/Quickstart_tui.md@@ -58,6 +58,49 @@ Suitable for users who manage their own Python environment. Follow these steps:You can run the command above in **multiple terminals** against the same Gateway (default `ws://127.0.0.1:19001/tui`) for parallel sessions in separate TUI windows. See the **Multi-window TUI** section in [TUI Usage Guide (zh)](../zh/TUI使用指南.md#多窗口-tui).+### `--session`: resume or create a session by id++`--session <id>` makes the TUI connect with a specific session id and, after the connection is established, take one of two paths depending on whether the id already exists:++| id state | Startup behavior | Backend RPC |+|------|------|------|+| **exists** | Resume the session: triggers `session.switch` lifecycle (KV cache affinity / Team state migration), aligns the frontend mode to the backend-resolved mode, then fetches history and replays it in the UI | `session.switch` + `history.get` + `session.rename` (title) |+| **does not exist** | Create and persist the session: triggers `session.create` (creates the directory + `metadata.json` + lifecycle init); the UI starts as an empty session. Once persisted it can be resumed next time | `session.create` + `history.get` (empty) |++Detection is **try-create-then-switch**: first attempt `session.create(<id>)`; on `ALREADY_EXISTS`, fall back to `session.switch` to resume. Driven by `app-state.ts` `resumeOrCreateBootSession` after `connection.ack`, runs once (idempotent on reconnect).++**Examples**:++```bash+# First launch with an id → does not exist → created and persisted+jiuwenswarm-tui --session tui_myproj_001+# Chat a few turns in the TUI, then quit. The id is persisted to ~/.jiuwenswarm/agent/sessions/tui_myproj_001/++# Launch again with the same id → exists → resume and replay history+jiuwenswarm-tui --session tui_myproj_001+```++**Relationship with runtime `/resume`**: `--session` is the **startup-time** resume/create entry; `/resume` is the **runtime** command to switch to another session after the TUI is already running. Both invoke the same backend RPCs (`session.switch`/`session.create`), but `--session` fires on the handshake first frame and `/resume` fires on user input. No conflict in normal sequencing.++**id naming constraints** (validated by the frontend before startup; invalid ids exit immediately without entering the TUI):++| Constraint | Value | Reason |+|------|------|------|+| Max length | ≤ 128 chars | `session_id` is used directly as a directory name on disk (`~/.jiuwenswarm/agent/sessions/<id>/`); bounded by the filesystem's 255-char single-name limit, leaving headroom for the path prefix |+| Allowed chars | `A-Z a-z 0-9 . _ -` | Same charset as `generateSessionId` output (`tui_<hex>_<hex>`) |+| Forbidden chars | CJK / Unicode letters, spaces, `/ \ : * ? " < > |`, etc. | Prevents directory injection (`/` creates nested dirs → lost session) and cross-platform `mkdir` failures |++Invalid examples:++```bash+jiuwenswarm-tui --session 测试会话 # CJK chars → exits: --session <id> contains invalid characters+jiuwenswarm-tui --session "my session" # space → same+jiuwenswarm-tui --session a/b # slash → same+jiuwenswarm-tui --session "$(printf 'a%.0s' {1..200})" # over 128 → length limit+```++**Without `--session`**: the frontend generates a random id (`generateSessionId` → `tui_<hex>_<hex>`), and the backend directory is lazily created only when the **first message writes history**. So launching without `--session` and quitting before sending any message leaves no backend directory and the id does not appear in `/sessions` (empty sessions do not pollute the list). Launching with `--session` creates the directory immediately, so **even without sending a message the id appears in the list** for next-time resume — a key behavioral difference.+## Method 2: Install from SourceSuitable for users who perform custom development or adaptation based on JiuwenSwarm.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 b79a0cb89f..15d9ba1047 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"@@ -21,7 +21,7 @@| **同窗口新消息** | 在同一窗口(相同 `session_id`)再次发送聊天,仍会取消该 session 上旧的流式任务。 || **与 ACP 差异** | ACP 仍为 single-user channel(新消息会取消同 channel 上所有进行中任务);TUI/CLI 已改为按 session 隔离。 |-**打开多窗口**:在多个终端分别运行 `jiuwenswarm-tui` 或 `jiuwenswarm-cli` 即可。需要恢复特定会话时使用 `--session <id>` 或 `/resume`。+**打开多窗口**:在多个终端分别运行 `jiuwenswarm-tui` 或 `jiuwenswarm-cli` 即可。需要恢复或指定会话时使用 `--session <id>`(启动时,详见下文 [CLI 参考](#cli-参考) 中的 `--session` 小节)或运行时 `/resume`。注意:同一 `--session <id>` 在两个窗口同时启动会被 Gateway 拒绝(`SESSION_IN_USE`),需先关闭另一窗口。> **与「单机多实例」的区别**:[单机多实例运行](单机多实例运行.md) 指不同工作区、不同端口的独立后端;**多窗口 TUI** 指多个终端共享同一 Gateway 后端。二者可同时使用(例如 `dev` 实例上开两个 TUI 窗口),但不要混淆端口与工作区。@@ -36,15 +36,58 @@| `jiuwenswarm-tui` | 通过 `jiuwenswarm-tui` PyPI 包启动时,由包装器拉起对应平台的二进制(见 `packages/jiuwenswarm-tui`)。 || `jiuwenswarm-cli` | 源码/开发路径下,在 `jiuwenswarm/cli` 执行 `npm run dev` 或 `npm run start` 后使用 `jiuwenswarm-cli`(见 `package.json` 的 `bin`)。 |-以下 **命令行标志** 由 `jiuwenswarm/cli/src/index.ts` 中的 `parseArgs` 定义:+以下 **命令行标志** 由 `jiuwenswarm/channels/tui/frontend/src/index.ts` 中的 `parseArgs` 定义:| 标志 | 说明 | 默认值 | 示例 ||------|------|--------|------|| `--url <url>` | Gateway 的 CLI WebSocket 地址 | `ws://127.0.0.1:19001/tui` | `jiuwenswarm-cli --url ws://192.168.1.10:19001/tui` |-| `--session <id>` | 启动时恢复指定会话 ID | 无 | `jiuwenswarm-cli --session abc-123` |+| `--session <id>` | 启动时按 id **恢复或新建**会话(详见下节) | 无 | `jiuwenswarm-tui --session tui_myproj_001` || `--token <token>` | 鉴权令牌(若 Gateway 需要) | 空字符串 | `jiuwenswarm-cli --token YOUR_TOKEN` || `-h`, `--help` | 打印帮助并退出 | - | `jiuwenswarm-cli -h` |+### `--session`:按 id 恢复或新建会话++`--session <id>` 让 TUI 在启动时**以指定 session id 为身份**连接后端,并在连接建立后按 id 是否已存在走两条路径之一:++| id 状态 | 启动行为 | 后端 RPC |+|------|------|------|+| **已存在** | 恢复该会话:触发 `session.switch` 生命周期(KV cache affinity / Team 状态迁移),前端按后端返回的 `mode` 对齐当前模式,随后拉取历史并回显到界面 | `session.switch` + `history.get` + `session.rename`(取标题) |+| **不存在** | 新建并落盘该会话:触发 `session.create`(建目录 + 写 `metadata.json` + 生命周期初始化),界面为空会话。**已落盘即可下次恢复** | `session.create` + `history.get`(空)|++判定方式为 **try-create-then-switch**:先尝试 `session.create(<id>)`,返回 `ALREADY_EXISTS` 则转 `session.switch` 恢复。该逻辑在连接收到 `connection.ack` 后由 `app-state.ts` 的 `resumeOrCreateBootSession` 驱动,仅执行一次(重连/重发幂等)。++**示例**:++```bash+# 首次用某 id 启动 → 不存在 → 新建落盘+jiuwenswarm-tui --session tui_myproj_001+# 在 TUI 内对话若干轮后退出。该 id 已落盘到 ~/.jiuwenswarm/agent/sessions/tui_myproj_001/++# 再次用同 id 启动 → 已存在 → 恢复并回显历史+jiuwenswarm-tui --session tui_myproj_001+```++**与运行时 `/resume` 的关系**:`--session` 是**启动时**的恢复/新建入口;`/resume` 是 TUI 已启动后**运行中**切换到另一会话的命令。两者调同一套后端 RPC(`session.switch`/`session.create`),但 `--session` 在握手首帧触发、`/resume` 在用户手动输入时触发。正常时序无冲突。++**id 命名约束**(前端在启动前校验,不合规直接报错退出,不进入 TUI):++| 约束 | 值 | 原因 |+|------|------|------|+| 长度上限 | ≤ 128 字符 | `session_id` 直接作为目录名落地(`~/.jiuwenswarm/agent/sessions/<id>/`),受文件系统单项 255 字符限制,留路径前缀余量 |+| 允许字符 | `A-Z a-z 0-9 . _ -` | 与 `generateSessionId` 产出的 `tui_<hex>_<hex>` 同字符集 |+| 禁止字符 | 中文、空格、`/ \ : * ? " < > \|` 等 | 防止目录注入(`/` 会建出嵌套目录导致会话丢失)与跨平台 `mkdir` 失败 |++不合规示例:++```bash+jiuwenswarm-tui --session 测试会话 # 含中文 → 启动即退出:--session <id> 含非法字符+jiuwenswarm-tui --session "my session" # 含空格 → 同上+jiuwenswarm-tui --session a/b # 含 / → 同上+jiuwenswarm-tui --session "$(printf 'a%.0s' {1..200})" # 超 128 → 长度超限+```++**不传 `--session`**:前端生成随机 id(`generateSessionId` → `tui_<hex>_<hex>`),后端目录在**首条对话写入历史时**懒创建。即未传参启动、未发消息即退出 → 后端无目录、`/sessions` 列表不显示该 id(空会话不污染列表)。传 `--session` 启动即建目录,**即使不发言也会出现在列表**,方便下次恢复——这是两者关键行为差异。+### 连接到非标准端口(端口冲突回退后)当后端启动时端口被占用,`jiuwenswarm-start` 会自动回退到相邻可用端口组(详见 [快速开始 · 端口冲突自动处理](Quickstart.md#端口冲突自动处理))。回退后新端口会被持久化,TUI / CLI 有两种连接方式:diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 9e043f0af2..73024850e5 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -324,6 +324,15 @@ export class CliPiAppState {private connectionStatus: ConnectionStatus = "idle";private sessionId: string;private sessionTitle: string = "";+ /**+ * `--session <id>` 启动时传入的目标 session id;为 null 表示用户未显式指定+ * (走 generateSessionId 新会话路径,不触发 boot resume/create)。+ * 由 connection.ack 收到后驱动 resumeOrCreateBootSession:已存在→session.switch+ * 恢复,不存在→session.create 新建并落盘。+ */+ private bootSessionId: string | null = null;+ /** 幂等守卫:boot resume/create 只在首次 connection.ack 触发一次(重连/重发不重试)。 */+ private bootSessionHandled = false;private mode: ClientMode = "code.normal";private themeName: ThemeName = getCurrentThemeName();private accentColor: AccentColorName = getCurrentAccentColor();@@ -549,6 +558,10 @@ export class CliPiAppState {safeFetchSessionTitle: (sessionId) => {this.safeFetchSessionTitle(sessionId);},+ hasBootSession: () => this.bootSessionId !== null,+ resumeOrCreateBootSession: () => {+ this.resumeOrCreateBootSession();+ },getSuppressInterruptResult: () => this.suppressInterruptResult,clearSuppressInterruptResult: () => {this.suppressInterruptResult = false;@@ -621,6 +634,7 @@ export class CliPiAppState {},) {this.sessionId = cliSession || generateSessionId();+ this.bootSessionId = cliSession ? cliSession : null;const config = loadTuiConfig();if (config.theme) {setCurrentThemeName(config.theme);@@ -3267,4 +3281,67 @@ export class CliPiAppState {}})();}++ /**+ * `--session <id>` 启动闭环:connection.ack 收到后驱动。+ * 先 try `session.create(target)`:+ * - 成功 → id 不存在,后端已新建并落盘 metadata;下次同 id 启动即可恢复。+ * - 返回 ALREADY_EXISTS → id 已存在,转 `session.switch` 恢复会话生命周期+ * (KV cache affinity + team prepare),并按 res.mode 对齐前端 mode。+ * - 其他错误 → 降级仅拉历史,不阻断 UI(用户可手动 /resume)。+ * 收尾统一 safeRestoreHistory + safeFetchSessionTitle 展示历史/标题。+ * 无 --session(bootSessionId 为 null)时直接 return,由外层走原生成新会话路径。+ */+ private resumeOrCreateBootSession(): void {+ if (this.bootSessionHandled) return;+ if (this.bootSessionId === null) return;+ if (this.connectionStatus !== "connected") return;+ this.bootSessionHandled = true;+ const target = this.bootSessionId;+ const previousMode = this.mode;+ void (async () => {+ try {+ await this.request("session.create", {+ session_id: target,+ previous_session_id: "",+ previous_mode: previousMode,+ mode: previousMode,+ });+ // 新建成功:target 已落盘,无历史/标题可拉(空页无害)。+ } catch (createErr) {+ const message = createErr instanceof Error ? createErr.message : String(createErr);+ // ALREADY_EXISTS → 已存在,转 switch 恢复+ if (/ALREADY_EXISTS|already exists/i.test(message)) {+ try {+ const res = await this.request<{+ session_id?: string;+ mode?: string;+ switched?: boolean;+ }>("session.switch", {+ session_id: target,+ previous_session_id: "",+ previous_mode: previousMode,+ mode: previousMode,+ });+ const resolvedMode = res?.mode;+ if (typeof resolvedMode === "string" && resolvedMode) {+ this.setMode(resolvedMode as ClientMode);+ }+ } catch (switchErr) {+ const switchMessage =+ switchErr instanceof Error ? switchErr.message : String(switchErr);+ this.lastError = `session.switch failed: ${switchMessage}`;+ this.emitChange();+ }+ } else {+ // 非已存在错误:降级仅拉历史,不阻断+ this.lastError = `session.create failed: ${message}`;+ this.emitChange();+ }+ } finally {+ this.safeRestoreHistory(target);+ this.safeFetchSessionTitle(target);+ }+ })();+ }}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.tsindex 302573f43f..314a01aa03 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts@@ -174,6 +174,13 @@ export interface AppEventDelegate {pushHistoryEntry(entry: HistoryItem): void;scheduleHistoryFlush(): void;safeRestoreHistory(sessionId: string): void;+ /** 是否通过 `--session <id>` 启动(决定 boot resume/create 是否介入)。 */+ hasBootSession(): boolean;+ /**+ * `--session <id>` 启动闭环:已存在→session.switch 恢复,不存在→session.create 新建。+ * 无 --session 时 no-op,由调用方回退到纯 safeRestoreHistory。+ */+ resumeOrCreateBootSession(): void;/** 报告 history.get 流返回的分页元数据(本页 page_idx / total_pages)。 */reportHistoryPageMeta(meta: { pageIdx?: number; totalPages?: number }): void;/** 某一页 history.get 流已结束(收到 `status: done` 帧),由 app-state 决定是否继续拉下一页。 */@@ -448,12 +455,16 @@ function handleConnectionAck(delegate: AppEventDelegate, frame: EventFrame): booif (frame.event !== "connection.ack") {return false;}- // session_id is determined at construction time; connection.ack is only- // used as a signal to restore history once connected.+ // `--session <id>` 启动:走 resume/create 闭环(已存在→switch 恢复,不存在→create 新建),+ // 由该方法内部负责 safeRestoreHistory/safeFetchSessionTitle。+ // 无 --session(hasBootSession=false):该方法 no-op,回退到下方纯历史拉取。const sessionId = delegate.getSessionId();if (sessionId && delegate.getConnectionStatus() === "connected") {- delegate.safeRestoreHistory(sessionId);- delegate.safeFetchSessionTitle(sessionId);+ delegate.resumeOrCreateBootSession();+ if (!delegate.hasBootSession()) {+ delegate.safeRestoreHistory(sessionId);+ delegate.safeFetchSessionTitle(sessionId);+ }}return true;}diff --git a/jiuwenswarm/channels/tui/frontend/src/index.ts b/jiuwenswarm/channels/tui/frontend/src/index.tsindex 6fdff91ad8..fcb5c84337 100644--- a/jiuwenswarm/channels/tui/frontend/src/index.ts+++ b/jiuwenswarm/channels/tui/frontend/src/index.ts@@ -30,7 +30,8 @@ if (values.help) {Options:--url <url> Gateway CLI WebSocket URL (default: ws://127.0.0.1:19001/tui)- --session <id> Resume a specific session+ --session <id> Resume or create a specific session by id. id 需匹配+ [A-Za-z0-9._-]、长度 ≤ 128(作为目录名落盘,受文件系统限制)--token <token> Authentication token--user-id <id> User identifier for the session-h, --help Show this help@@ -38,6 +39,35 @@ Options:process.exit(0);}+// session_id 直接作为文件系统目录名落地(~/.jiuwenswarm/agent/sessions/<id>/),+// 后端无任何校验,故在此前置校验,避免 OS 层 mkdir 报错导致的静默失败。+// 约束:长度 ≤ 128(NTFS/ext 文件名单项上限 255,留余量 + 路径前缀),+// 字符白名单 [A-Za-z0-9._-](与 generateSessionId 产出 tui_<hex>_<hex> 同集),+// 禁止中文 / 空格 / 路径分隔符等,防止目录注入与跨平台 mkdir OSError。+const SESSION_ID_MAX_LEN = 128;+const SESSION_ID_PATTERN = /^[A-Za-z0-9._-]+$/;+const rawSession = values.session;+if (rawSession !== undefined && rawSession !== "") {+ const trimmed = rawSession.trim();+ if (!trimmed) {+ console.error("--session <id> 不能为空");+ process.exit(1);+ }+ if (trimmed.length > SESSION_ID_MAX_LEN) {+ console.error(+ `--session <id> 长度 ${trimmed.length} 超出上限 ${SESSION_ID_MAX_LEN}(session_id 作为目录名落地,受文件系统限制)`,+ );+ process.exit(1);+ }+ if (!SESSION_ID_PATTERN.test(trimmed)) {+ console.error(+ "--session <id> 含非法字符:仅允许英文字母、数字、点(.)、下划线(_)、连字符(-)。禁止中文、空格及 / \\ : * ? \" < > | 等。",+ );+ process.exit(1);+ }+ values.session = trimmed;+}+// 允许通过环境变量跳过 TTY 检查(用于自动化测试)if (!process.env.JIUWENSWARM_TUI_HEADLESS && (!process.stdin.isTTY || !process.stdout.isTTY)) {console.error("jiuwenswarm-tui requires an interactive TTY");