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: /branch and /rewind command supported for tui-cli
ldstyle841ad3b410a6d
diff --git a/jiuwenclaw/agents/harness/common/session_ops_service.py b/jiuwenclaw/agents/harness/common/session_ops_service.pynew file mode 100644index 0000000000..22b5bb7979--- /dev/null+++ b/jiuwenclaw/agents/harness/common/session_ops_service.py@@ -0,0 +1,395 @@+from __future__ import annotations++import json+import logging+import re+import shutil+from pathlib import Path+from typing import Any, TYPE_CHECKING++from jiuwenclaw.common.utils import get_agent_sessions_dir++if TYPE_CHECKING:+ from openjiuwen.harness import DeepAgent++logger = logging.getLogger(__name__)+++def _derive_first_prompt(history: list[dict[str, Any]]) -> str:+ for record in history:+ if record.get("role") != "user":+ continue+ content = record.get("content", "")+ if not isinstance(content, str) or not content.strip():+ continue+ text = re.sub(r"\s+", " ", content).strip()+ return text[:100] if text else "Branched conversation"+ return "Branched conversation"+++def _get_unique_fork_name(base_name: str, existing_titles: set[str]) -> str:+ """Generate a unique fork title.++ With custom name: "custom-name (Branch)"+ Without name: "(Branch)" or "(Branch N)"+ """+ candidate = f"{base_name} (Branch)" if base_name else "(Branch)"+ if candidate not in existing_titles:+ return candidate+ pattern = re.compile(+ r"^" + re.escape(base_name) + r" \(Branch(?: (\d+))?\)$"+ if base_name+ else r"^\(Branch(?: (\d+))?\)$"+ )+ used_numbers: set[int] = {1}+ for title in existing_titles:+ m = pattern.match(title)+ if m:+ num = int(m.group(1)) if m.group(1) else 1+ used_numbers.add(num)+ next_number = 2+ while next_number in used_numbers:+ next_number += 1+ return f"{base_name} (Branch {next_number})" if base_name else f"(Branch {next_number})"+++def fork_session(+ *,+ source_session_id: str,+ target_session_id: str,+ title: str = "",+ channel_id: str = "tui",+) -> dict[str, Any]:+ sessions_dir = get_agent_sessions_dir()+ source_dir = sessions_dir / source_session_id+ target_dir = sessions_dir / target_session_id++ if not source_dir.exists():+ raise ValueError("source session not found")+ if target_dir.exists():+ raise ValueError("target session already exists")++ target_dir.mkdir(parents=True, exist_ok=True)++ source_history = source_dir / "history.json"+ target_history = target_dir / "history.json"+ history_data: list[dict[str, Any]] = []+ if source_history.exists():+ shutil.copy2(source_history, target_history)+ try:+ data = json.loads(target_history.read_text(encoding="utf-8"))+ if isinstance(data, list):+ history_data = data+ for record in data:+ record["forked_from"] = {+ "session_id": source_session_id,+ "original_id": record.get("id", ""),+ }+ target_history.write_text(+ json.dumps(data, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ except Exception as exc:+ logger.warning("fork: failed to add forked_from to history: %s", exc)++ from jiuwenclaw.server.runtime.session.session_metadata import (+ _current_timestamp,+ _enqueue_write,+ get_all_sessions_metadata,+ get_session_metadata,+ )++ source_meta = get_session_metadata(source_session_id)++ if title:+ base_name = title+ elif source_meta.get("title"):+ base_name = source_meta["title"]+ else:+ # Don't derive from first prompt — "(Branch)" alone is cleaner+ # for the status bar. First prompt like "hi" makes an ugly title.+ base_name = ""++ existing_titles: set[str] = set()+ try:+ all_sessions = get_all_sessions_metadata(limit=500, offset=0)+ if isinstance(all_sessions, list):+ for s in all_sessions:+ t = s.get("title", "")+ if t:+ existing_titles.add(t)+ except Exception as exc:+ logger.debug("fork_session: failed to get existing titles: %s", exc)++ final_title = _get_unique_fork_name(base_name, existing_titles)+ source_mode = source_meta.get("mode", "code.normal")++ metadata = {+ "session_id": target_session_id,+ "channel_id": channel_id,+ "user_id": source_meta.get("user_id", ""),+ "created_at": _current_timestamp(),+ "last_message_at": source_meta.get("last_message_at", 0),+ "title": final_title,+ "message_count": source_meta.get("message_count", 0),+ "mode": source_mode,+ "forked_from": source_session_id,+ }+ _enqueue_write(target_session_id, metadata)++ return {+ "session_id": target_session_id,+ "source_session_id": source_session_id,+ "title": final_title,+ }+++def rewind_session(+ *,+ session_id: str,+ turn_index: int,+) -> dict[str, Any]:+ if turn_index < 1:+ raise ValueError("turn_index must be >= 1")++ sessions_dir = get_agent_sessions_dir()+ history_path = sessions_dir / session_id / "history.json"+ if not history_path.exists():+ raise ValueError("session history not found")++ from jiuwenclaw.server.runtime.session.session_history import truncate_history_records++ history = json.loads(history_path.read_text(encoding="utf-8"))+ if not isinstance(history, list):+ raise ValueError("invalid history format")++ user_positions = []+ for i, record in enumerate(history):+ if record.get("role") == "user":+ user_positions.append(i)++ total_turns = len(user_positions)+ if total_turns == 0:+ raise ValueError("no user messages in session")+ if turn_index > total_turns:+ raise ValueError(+ f"turn_index {turn_index} exceeds total turns ({total_turns})"+ )++ target_user_index = user_positions[turn_index - 1]+ cut_index = target_user_index++ removed_turn_content = ""+ if 0 <= target_user_index < len(history):+ content = history[target_user_index].get("content", "")+ removed_turn_content = content if isinstance(content, str) else str(content)++ result = truncate_history_records(session_id=session_id, cut_index=cut_index)++ from jiuwenclaw.server.runtime.session.session_metadata import update_session_metadata++ update_session_metadata(+ session_id=session_id,+ set_message_count=result["remaining_records"],+ )++ return {+ "session_id": session_id,+ "turn_index": turn_index,+ "content": removed_turn_content,+ "content_preview": removed_turn_content[:80] if removed_turn_content else "",+ "remaining_records": result["remaining_records"],+ "removed_records": result["removed_records"],+ }+++_NON_USER_AUTHORED_TAGS = (+ "<local-command-stdout>",+ "<local-command-stderr>",+ "<bash-stdout>",+ "<bash-stderr>",+ "<task-notification>",+ "<tick>",+ "<teammate-message",+)+++def _is_selectable_user_message(content: str) -> bool:+ for tag in _NON_USER_AUTHORED_TAGS:+ if tag in content:+ return False+ return True+++def list_session_turns(+ *,+ session_id: str,+) -> dict[str, Any]:+ sessions_dir = get_agent_sessions_dir()+ history_path = sessions_dir / session_id / "history.json"++ if not history_path.exists():+ return {"turns": [], "total": 0}++ try:+ history = json.loads(history_path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.warning("list_session_turns: failed to read history: %s", exc)+ return {"turns": [], "total": 0}++ if not isinstance(history, list):+ return {"turns": [], "total": 0}++ diff_stats_map: dict[int, dict[str, int]] = {}+ try:+ from jiuwenclaw.server.utils.diff_service import get_diff_service++ diff_service = get_diff_service()+ turn_diffs = diff_service.get_turn_diffs(session_id)+ if isinstance(turn_diffs, list):+ for td in turn_diffs:+ ti = td.get("turnIndex")+ if isinstance(ti, int) and ti > 0:+ diff_stats_map[ti] = td.get("stats", {})+ except Exception as exc:+ logger.debug("list_session_turns: diff service unavailable: %s", exc)++ turns = []+ user_count = 0+ for record in history:+ if record.get("role") != "user":+ continue+ user_count += 1+ content = record.get("content", "")+ if isinstance(content, str) and not _is_selectable_user_message(content):+ continue+ preview = content[:80] if isinstance(content, str) else ""+ stats = diff_stats_map.get(user_count, {+ "filesChanged": 0,+ "linesAdded": 0,+ "linesRemoved": 0,+ })+ turns.append({+ "turn_index": user_count,+ "content_preview": preview,+ "timestamp": record.get("timestamp", 0),+ "id": record.get("id", ""),+ "request_id": record.get("request_id", ""),+ "stats": stats,+ })++ return {"turns": turns, "total": user_count}+++def restore_session_files(+ *,+ session_id: str,+ turn_index: int,+) -> dict[str, Any]:+ """恢复指定 turn 之后所有被修改的文件到目标 turn 开始前的状态.++ 基于 DiffService.get_files_to_restore() 确定需要恢复的文件,+ 然后将每个文件写回其 old_content(或删除 agent 新建的文件)。++ 局限性(底层暂不支持,后续迭代):+ - bash 命令修改的文件不在 file_ops 日志中,无法恢复+ - 文件删除操作未记录在 file_ops 中,无法恢复被删除的文件+ - 多 session 共享 file_ops 日志,若其他 session 也修改了同一文件,+ 时间戳匹配可能不够精确+ """+ from jiuwenclaw.server.utils.diff_service import get_diff_service++ diff_service = get_diff_service()+ files_to_restore = diff_service.get_files_to_restore(session_id, turn_index)++ if not files_to_restore:+ return {+ "session_id": session_id,+ "turn_index": turn_index,+ "restored_files": [],+ "deleted_files": [],+ "errors": [],+ }++ restored: list[str] = []+ deleted: list[str] = []+ errors: list[dict[str, str]] = []++ for file_path, info in files_to_restore.items():+ path = Path(file_path)+ try:+ if info["action"] == "write":+ # 文件在目标 turn 前已有内容,写回 old_content+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(info["restore_content"], encoding="utf-8")+ restored.append(file_path)+ elif info["action"] == "delete":+ # 文件由 agent 在目标 turn 后创建,删除+ if path.exists():+ path.unlink()+ deleted.append(file_path)+ except Exception as exc:+ errors.append({"file": file_path, "error": str(exc)})+ logger.warning(+ "restore_session_files: failed to restore %s: %s",+ file_path, exc,+ )++ logger.info(+ "restore_session_files: session=%s turn=%s restored=%d deleted=%d errors=%d",+ session_id, turn_index, len(restored), len(deleted), len(errors),+ )++ return {+ "session_id": session_id,+ "turn_index": turn_index,+ "restored_files": restored,+ "deleted_files": deleted,+ "errors": errors,+ }+++async def copy_session_context(+ deep_agent: "DeepAgent",+ source_session_id: str,+ target_session_id: str,+) -> bool:+ """Copy in-memory conversation context from source to target session.++ Uses DeepAgent.get_current_context() to read the source session's+ accumulated LLM conversation history (UserMessage, AssistantMessage,+ ToolMessage objects), then calls create_new_context_engine() to+ seed the target session with identical history.++ Returns True on success, False if context copy was skipped or failed.+ """+ try:+ messages = deep_agent.get_current_context(session_id=source_session_id)+ except Exception as exc:+ logger.warning(+ "copy_session_context: cannot read source context: %s", exc+ )+ return False++ if not messages:+ logger.info(+ "copy_session_context: no in-memory messages for %s, skipping",+ source_session_id,+ )+ return False++ try:+ await deep_agent.create_new_context_engine(+ session_id=target_session_id,+ messages=messages,+ )+ logger.info(+ "copy_session_context: copied %d messages from %s to %s",+ len(messages), source_session_id, target_session_id,+ )+ return True+ except Exception as exc:+ logger.warning(+ "copy_session_context: failed to seed target context: %s", exc+ )+ return Falsediff --git a/jiuwenclaw/agents/harness/team/monitor_handler.py b/jiuwenclaw/agents/harness/team/monitor_handler.pyindex a5fdef467e..06be1326dc 100644--- a/jiuwenclaw/agents/harness/team/monitor_handler.py+++ b/jiuwenclaw/agents/harness/team/monitor_handler.py@@ -53,7 +53,7 @@ class TeamMonitorHandler:returntry:- from openjiuwen.agent_teams.spawn.context import set_session_id, reset_session_id+ from openjiuwen.agent_teams.context import set_session_id, reset_session_idtoken = set_session_id(self._session_id)try:@@ -241,7 +241,7 @@ class TeamMonitorHandler:return ""try:- from openjiuwen.agent_teams.spawn.context import set_session_id, reset_session_id+ from openjiuwen.agent_teams.context import set_session_id, reset_session_idtoken = set_session_id(self._session_id)try:diff --git a/jiuwenclaw/agents/harness/team/remote_member_bootstrap.py b/jiuwenclaw/agents/harness/team/remote_member_bootstrap.pyindex 8a2aa3a863..0e44a831f7 100644--- a/jiuwenclaw/agents/harness/team/remote_member_bootstrap.py+++ b/jiuwenclaw/agents/harness/team/remote_member_bootstrap.py@@ -1214,7 +1214,7 @@ async def _ensure_dynamic_member_execution_loop(return False, Falsetry:from openjiuwen.agent_teams.agent.team_agent import TeamAgent- from openjiuwen.agent_teams.spawn.context import reset_session_id, set_session_id+ from openjiuwen.agent_teams.context import reset_session_id, set_session_idfrom jiuwenclaw.server.agent_ws_server import AgentWebSocketServerfrom jiuwenclaw.agents.harness.team.team_manager import get_team_managerdiff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex ff768657fe..ce46cf430c 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -105,6 +105,10 @@ export interface AppSnapshot {export class CliPiAppState {private listeners = new Set<() => void>();private entries: HistoryItem[] = [];+ /** AppScreen 注入的 setInput 回调,用于自动恢复后填充输入框。 */+ private _setInputRef: ((text: string) => void) | null = null;+ /** AppScreen 注入的 getInputValue 回调,用于自动恢复判断输入框是否为空。 */+ private _getInputValueRef: (() => string) | null = null;private connectionStatus: ConnectionStatus = "idle";private sessionId: string;private sessionTitle: string = "";@@ -244,6 +248,7 @@ export class CliPiAppState {resolver();}},+ tryAutoRestoreAfterCancel: () => this.tryAutoRestoreAfterCancel(),appendUsageSummary: (usage, model) => {const key = model || "unknown";const existing = this.usageByModel.get(key);@@ -448,6 +453,7 @@ export class CliPiAppState {clearTrustedDirs: clearTrustedDirs,getWorkspaceDir: () => getTrustedDirs()[0] || process.cwd(),enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.+ setInput: this._setInputRef ?? undefined,enterStatusView: undefined,getUsageSummary: () => this.getUsageSummary(),};@@ -463,6 +469,16 @@ export class CliPiAppState {};}+ /** AppScreen 在初始化时注入 setInput 回调,使 app-state 可以填充输入框。 */+ setInputRef(ref: (text: string) => void): void {+ this._setInputRef = ref;+ }++ /** AppScreen 在初始化时注入 getInputValue 回调,使 app-state 可以读取输入框内容。 */+ getInputValueRef(ref: () => string): void {+ this._getInputValueRef = ref;+ }+readonly sendEventOnly = (method: string, params: Record<string, unknown>): string => {const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;const trustedDirs = getTrustedDirs();@@ -901,6 +917,99 @@ readonly request = async <T = Record<string, unknown>>(}, 80);};+ /** cancel 成功后自动回退判断(与 Claude Code auto-restore 对齐)。++ 条件:+ 1. 输入框为空(用户取消后没有输入新内容)+ 2. 最后一个 selectable user message 之后的消息只有合成/系统类,+ 无实质 assistant 输出+ 满足时自动调用 rewind_and_restore RPC 截断对话+恢复文件,+ 并将被回退的内容填充输入框。+ */+ readonly tryAutoRestoreAfterCancel = async (): Promise<void> => {+ // 条件 1:输入框为空+ if (this._getInputValueRef && this._getInputValueRef().trim() !== "") return;++ const entries = this.getSnapshot().entries;+ if (!entries || entries.length === 0) return;++ // 找最后一个实质 user message+ const nonSyntheticTags = [+ "<local-command-stdout>",+ "<bash-stdout>",+ "<task-notification>",+ ];+ let lastUserIdx = -1;+ for (let i = entries.length - 1; i >= 0; i--) {+ const e = entries[i];+ if (e.kind !== "user") continue;+ const content = typeof e.content === "string" ? e.content : "";+ if (nonSyntheticTags.some((tag) => content.includes(tag))) continue;+ lastUserIdx = i;+ break;+ }+ if (lastUserIdx < 0) return;++ // 判断 lastUserIdx 之后是否只有合成/系统类消息+ const hasSubstantialAfter = entries.slice(lastUserIdx + 1).some((e) => {+ if (e.kind === "user") {+ const content = typeof e.content === "string" ? e.content : "";+ return !nonSyntheticTags.some((tag) => content.includes(tag));+ }+ // assistant 含实质内容视为有实质输出+ if (e.kind === "assistant") return true;+ // 其他(info/error/system)视为合成消息+ return false;+ });++ if (hasSubstantialAfter) return; // 有实质内容,不自动回退++ // 获取 turn 列表以确定 lastUserIdx 对应的 turn_index+ try {+ const turnsPayload = await this.request<{+ turns?: { turn_index: number; content_preview: string; content?: string }[];+ total?: number;+ }>("history.list_turns", { session_id: this.sessionId });+ const turns = turnsPayload.turns ?? [];+ if (turns.length === 0) return;++ const lastTurn = turns[turns.length - 1];+ if (!lastTurn) return;++ const rewindPayload = await this.request<{+ content?: string;+ content_preview?: string;+ remaining_records?: number;+ removed_records?: number;+ restored_files?: string[];+ deleted_files?: string[];+ restore_errors?: { file: string; error: string }[];+ }>("session.rewind_and_restore", {+ session_id: this.sessionId,+ turn_index: lastTurn.turn_index,+ });++ this.entries = [];+ this.emitChange();+ await this.restoreHistory(this.sessionId);++ const restoreText = rewindPayload.content ?? lastTurn.content_preview ?? "";+ this._setInputRef?.(restoreText);++ this.addItem(+ addInfo(+ this.sessionId,+ "Auto-restored to before the last turn (no substantial output after cancel). " ++ "The removed turn text has been placed in the input for you to edit.\n" ++ "Note: Rewinding does not affect files edited manually or via bash commands.",+ "i",+ ),+ );+ } catch {+ // 自动回退失败不影响 cancel 本身+ }+ };+private applyHistoryEntriesToTranscript(): void {// AgentServer 为了让分页优先返回最新页,在 `_handle_history_get_stream` 中把整条历史做了// `list(reversed(raw))` 后再流式下发;CLI 按到达顺序 push 到 `historyEntries` 会得到倒序。diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/branch.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/branch.tsnew file mode 100644index 0000000000..52e5e22b1f--- /dev/null+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/branch.ts@@ -0,0 +1,66 @@+import { generateSessionId } from "../../session-state.js";+import { addCommandEcho, addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";++export interface SessionForkPayload {+ session_id?: string;+ source_session_id?: string;+ title?: string;+}++export function createBranchCommand(): SlashCommand {+ return {+ name: "branch",+ altNames: ["fork"],+ description: "Create a branch of the current conversation at this point",+ usage: "/branch [name]",+ example: "/branch fix-login-bug",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ if (ctx.isProcessing) {+ ctx.addItem(+ addError(ctx.sessionId, "session is busy; stop the current run before branching"),+ );+ return;+ }++ if (ctx.entries.length === 0) {+ ctx.addItem(addError(ctx.sessionId, "no conversation to branch from"));+ return;+ }++ const customTitle = args.trim();+ const targetId = generateSessionId();++ try {+ const payload = await ctx.request<SessionForkPayload>("session.fork", {+ source_session_id: ctx.sessionId,+ target_session_id: targetId,+ title: customTitle || undefined,+ });++ const forkSessionId = payload.session_id || targetId;++ const originalSessionId = ctx.sessionId;+ ctx.updateSession(forkSessionId);+ ctx.clearEntries();+ ctx.addItem(addCommandEcho(forkSessionId, "/branch"));+ ctx.addItem(+ addInfo(+ forkSessionId,+ "You are now in the new branch " ++ `(session ${forkSessionId}).\n` ++ `Use /resume ${originalSessionId} to return to the original.`,+ "i",+ ),+ );+ ctx.setSessionTitle(payload.title || "");+ await ctx.restoreHistory(forkSessionId);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `branch failed: ${message}`));+ }+ },+ };+}diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.tsnew file mode 100644index 0000000000..209b03fbeb--- /dev/null+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/rewind.ts@@ -0,0 +1,290 @@+import { addCommandEcho, addError, addInfo } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";++export interface TurnInfo {+ turn_index: number;+ content_preview: string;+ timestamp: number;+ id: string;+ request_id: string;+ stats: {+ filesChanged: number;+ linesAdded: number;+ linesRemoved: number;+ };+}++export interface ListTurnsPayload {+ turns?: TurnInfo[];+ total?: number;+}++export interface RewindPayload {+ session_id?: string;+ turn_index?: number;+ content?: string;+ content_preview?: string;+ remaining_records?: number;+ removed_records?: number;+ restored_files?: string[];+ deleted_files?: string[];+ restore_errors?: { file: string; error: string }[];+}++/** 恢复选项类型,与 Claude Code MessageSelector 对齐 */+type RestoreOption = "both" | "conversation" | "code" | "cancel";++export function createRewindCommand(): SlashCommand {+ return {+ name: "rewind",+ altNames: ["checkpoint"],+ description: "Rewind the conversation to before a previous turn",+ usage: "/rewind [turn_number]",+ example: "/rewind 2",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ if (ctx.isProcessing) {+ ctx.addItem(+ addError(ctx.sessionId, "session is busy; stop the current run before rewinding"),+ );+ return;+ }++ const directTurn = args.trim();++ try {+ const payload = await ctx.request<ListTurnsPayload>("history.list_turns", {+ session_id: ctx.sessionId,+ });++ const turns = payload.turns ?? [];+ const total = payload.total ?? turns.length;++ if (turns.length === 0) {+ ctx.addItem(addInfo(ctx.sessionId, "No conversation turns to rewind to", "r"));+ return;+ }++ let selectedTurnIndex: number;++ if (directTurn) {+ const parsed = parseInt(directTurn, 10);+ if (Number.isNaN(parsed) || parsed < 1 || parsed > total) {+ ctx.addItem(+ addError(+ ctx.sessionId,+ `Invalid turn number: ${directTurn}. Valid range: 1-${total}`,+ ),+ );+ return;+ }+ selectedTurnIndex = parsed;+ } else {+ const items = turns.map((t) => {+ const time = t.timestamp+ ? new Date(t.timestamp * 1000).toLocaleString()+ : "-";+ const statsStr =+ t.stats.filesChanged > 0+ ? ` | files: ${t.stats.filesChanged} +${t.stats.linesAdded}/-${t.stats.linesRemoved}`+ : "";+ return {+ label: String(t.turn_index),+ value: `${t.content_preview} | ${time}${statsStr}`,+ };+ });++ ctx.addItem(+ addInfo(ctx.sessionId, `Conversation Turns (${total} total)`, "r", {+ view: "list",+ title: "Rewind - Select a Turn",+ items,+ }),+ );++ const answers = await ctx.askQuestions(+ [+ {+ header: "Turn",+ question: "Which turn do you want to rewind to? (this turn and all after will be removed)",+ options: turns.map((t) => ({+ label: String(t.turn_index),+ description: t.content_preview,+ })),+ },+ ],+ "rewind",+ );++ const userInput = answers[0]?.selected_options?.[0] || answers[0]?.custom_input || "";+ const parsed = parseInt(userInput, 10);+ if (Number.isNaN(parsed) || parsed < 1 || parsed > total) {+ ctx.addItem(addError(ctx.sessionId, `Invalid turn number: ${userInput}`));+ return;+ }+ selectedTurnIndex = parsed;+ }++ const selectedTurn = turns.find((t) => t.turn_index === selectedTurnIndex);+ if (!selectedTurn) {+ ctx.addItem(addError(ctx.sessionId, `Turn ${selectedTurnIndex} not found`));+ return;+ }++ // 判断目标 turn 是否有文件变更(决定是否显示 code 相关选项)+ const hasCodeChanges = selectedTurn.stats.filesChanged > 0;++ // 构建恢复选项,与 Claude Code MessageSelector 对齐+ const restoreOptions: { label: string; description: string; value: RestoreOption }[] = [+ {+ label: "Restore conversation and code",+ description: "Remove this turn and all after; restore modified files to their prior state",+ value: "both",+ },+ {+ label: "Restore conversation only",+ description: "Remove this turn and all after; files remain unchanged",+ value: "conversation",+ },+ ];++ if (hasCodeChanges) {+ restoreOptions.push({+ label: "Restore code only",+ description: "Restore modified files to their prior state; conversation remains unchanged",+ value: "code",+ });+ }++ restoreOptions.push({+ label: "Cancel",+ description: "Keep conversation and files as is",+ value: "cancel",+ });++ // 局限提示(与 Claude Code "Rewinding does not affect files edited manually or via bash" 对齐)+ const limitationNote =+ "\nNote: Rewinding does not affect files edited manually or via bash commands.";++ const confirmAnswers = await ctx.askQuestions(+ [+ {+ header: "Confirm Rewind",+ question:+ `Rewind to before turn ${selectedTurnIndex}: "${selectedTurn.content_preview}"?` ++ limitationNote,+ options: restoreOptions,+ },+ ],+ "rewind_confirm",+ );++ const selectedOption = confirmAnswers[0]?.selected_options?.[0] as RestoreOption | undefined;+ // 从选项 label 反推 value(askQuestions 返回的是 label)+ const optionValue = restoreOptions.find((o) => o.label === selectedOption)?.value ?? "cancel";++ if (optionValue === "cancel") {+ ctx.addItem(addInfo(ctx.sessionId, "Rewind cancelled", "c"));+ return;+ }++ // 根据恢复选项调用不同 RPC+ if (optionValue === "both") {+ // 截断对话 + 恢复文件+ const rewindPayload = await ctx.request<RewindPayload>("session.rewind_and_restore", {+ session_id: ctx.sessionId,+ turn_index: selectedTurnIndex,+ });++ ctx.clearEntries();+ ctx.addItem(addCommandEcho(ctx.sessionId, `/rewind ${selectedTurnIndex}`));++ const restoredFiles = rewindPayload.restored_files ?? [];+ const deletedFiles = rewindPayload.deleted_files ?? [];+ const restoreErrors = rewindPayload.restore_errors ?? [];+ let fileRestoreMsg = "";+ if (restoredFiles.length > 0) {+ fileRestoreMsg += `\nRestored ${restoredFiles.length} file(s) to prior state.`;+ }+ if (deletedFiles.length > 0) {+ fileRestoreMsg += `\nDeleted ${deletedFiles.length} file(s) created after this turn.`;+ }+ if (restoreErrors.length > 0) {+ fileRestoreMsg += `\nWarning: ${restoreErrors.length} file(s) could not be restored.`;+ }++ ctx.addItem(+ addInfo(+ ctx.sessionId,+ `Rewound conversation and code: removed turn ${selectedTurnIndex} and everything after.\n` ++ `Removed ${rewindPayload.removed_records ?? 0} records, ` ++ `${rewindPayload.remaining_records ?? 0} remaining` ++ fileRestoreMsg,+ "i",+ ),+ );+ await ctx.restoreHistory(ctx.sessionId);++ const restoreText = rewindPayload.content ?? selectedTurn.content_preview;+ if (restoreText) {+ ctx.setInput?.(restoreText);+ }+ } else if (optionValue === "conversation") {+ // 仅截断对话(原有行为)+ const rewindPayload = await ctx.request<RewindPayload>("session.rewind", {+ session_id: ctx.sessionId,+ turn_index: selectedTurnIndex,+ });++ ctx.clearEntries();+ ctx.addItem(addCommandEcho(ctx.sessionId, `/rewind ${selectedTurnIndex}`));+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ `Rewound conversation: removed turn ${selectedTurnIndex} and everything after.\n` ++ `Removed ${rewindPayload.removed_records ?? 0} records, ` ++ `${rewindPayload.remaining_records ?? 0} remaining`,+ "i",+ ),+ );+ await ctx.restoreHistory(ctx.sessionId);++ const restoreText = rewindPayload.content ?? selectedTurn.content_preview;+ if (restoreText) {+ ctx.setInput?.(restoreText);+ }+ } else if (optionValue === "code") {+ // 仅恢复文件(不截断对话)+ const restorePayload = await ctx.request<RewindPayload>("session.restore_files", {+ session_id: ctx.sessionId,+ turn_index: selectedTurnIndex,+ });++ const restoredFiles = restorePayload.restored_files ?? [];+ const deletedFiles = restorePayload.deleted_files ?? [];+ const restoreErrors = restorePayload.restore_errors ?? [];++ let msg = `Restored files to state before turn ${selectedTurnIndex}:`;+ if (restoredFiles.length > 0) {+ msg += `\n Written back: ${restoredFiles.length} file(s)`;+ }+ if (deletedFiles.length > 0) {+ msg += `\n Deleted: ${deletedFiles.length} file(s)`;+ }+ if (restoreErrors.length > 0) {+ msg += `\n Failed: ${restoreErrors.length} file(s)`;+ }+ if (restoredFiles.length === 0 && deletedFiles.length === 0) {+ msg += "\n No file changes found to restore.";+ }++ ctx.addItem(addInfo(ctx.sessionId, msg, "i"));+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `rewind failed: ${message}`));+ }+ },+ };+}\ No newline at end of filediff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.tsindex 237f493557..3e5a057b28 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts@@ -1,5 +1,6 @@/** 内置 slash 与 Gateway 受控指令对齐时参见仓库 `jiuwenclaw/gateway/slash_command.py`(SSOT)与 `docs/zh/CLI_COMMANDS.md`。 */import type { SlashCommand } from "./types.js";+import { createBranchCommand } from "./builtins/branch.js";import { createClearCommand } from "./builtins/clear.js";import { createColorCommand } from "./builtins/color.js";import { createCompactCommand } from "./builtins/compact.js";@@ -25,6 +26,7 @@ import { createPermissionsCommand } from "./builtins/permissions.js";import { createPlanCommand } from "./builtins/plan.js";import { createResumeCommand } from "./builtins/resume.js";import { createRenameCommand } from "./builtins/rename.js";+import { createRewindCommand } from "./builtins/rewind.js";import { createSessionCommand } from "./builtins/session.js";import { createStatusCommand } from "./builtins/status.js";import { createSkillsCommand } from "./builtins/skills.js";@@ -35,6 +37,7 @@ import { createWorkspaceCommand } from "./builtins/workspace-dir.js";export function createBuiltinCommands(): SlashCommand[] {const commands: SlashCommand[] = [createHelpCommand(() => commands),+ createBranchCommand(),createClearCommand(),createInitCommand(),createColorCommand(),@@ -55,6 +58,7 @@ export function createBuiltinCommands(): SlashCommand[] {createPlanCommand(),createResumeCommand(),createRenameCommand(),+ createRewindCommand(),createSessionCommand(),createSkillsCommand(),createStatusCommand(),diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.tsindex d1473a5f2f..70ba598011 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts@@ -72,6 +72,7 @@ export interface CommandContext {clearTrustedDirs: () => void;// Workspace directory (current working directory)getWorkspaceDir: () => string | undefined;+ setInput?: (text: string) => void;getUsageSummary: () => SessionUsageSummary;enterConfigEditor?: (focusKey?: string,diff --git a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.tsindex 7d7915ba94..8b17cbfe97 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts@@ -96,6 +96,8 @@ export interface AppEventDelegate {reportHistoryPageMeta(meta: { pageIdx?: number; totalPages?: number }): void;/** 某一页 history.get 流已结束(收到 `status: done` 帧),由 app-state 决定是否继续拉下一页。 */notifyHistoryPageDone(pageIdx: number): void;+ /** cancel 成功后判断是否需要自动回退(与 Claude Code 的 auto-restore 对齐)。 */+ tryAutoRestoreAfterCancel(): Promise<void>;/** 累加 chat.usage_summary 事件的 token/cost 数据(按 model 分桶)。 */appendUsageSummary(usage: Record<string, unknown>, model?: string): void;}@@ -785,6 +787,10 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFramicon: "i",at: new Date().toISOString(),});+ // 仅当目标 turn 之后无实质性 assistant 输出时执行+ delegate.tryAutoRestoreAfterCancel().catch(() => {+ // 自动回退失败不影响 cancel 本身,用户可手动 /rewind+ });} else {appendEntry(delegate, {kind: "error",diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex 2e19f262a2..cfa1502788 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -400,6 +400,12 @@ export class AppScreen implements Component, Focusable {this.unsubscribe = this.state.onChange(() => {this.handleStateChange();});+ // Inject editor refs into app-state so tryAutoRestoreAfterCancel can+ // check input emptiness and populate the input field after auto-restore.+ this.state.setInputRef((text: string) => {+ this.editor.setText(text);+ });+ this.state.getInputValueRef(() => this.editor.getText());// Initialize startup prompt for workspace trustthis.initStartupPrompt();}@@ -856,6 +862,8 @@ export class AppScreen implements Component, Focusable {subMatch?.[1] === "config" ? "config" :undefined;await this.openStatusView(tab);+ return;+ }if (/^\/theme\s*$/.test(text)) {this.editor.addToHistory(text);this.editor.setText("");@@ -871,6 +879,9 @@ export class AppScreen implements Component, Focusable {await this.commands.execute(text, {...this.state.getCommandContext(),exitApp: this.exit,+ setInput: (text: string) => {+ this.editor.setText(text);+ },enterConfigEditor: (focusKey, configPayload) => {this.openConfigEditor(focusKey, configPayload);},diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.tsindex e6db10289a..c32080803a 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts@@ -101,9 +101,10 @@ function buildStatusLines(const connectionLabel = connectionStatusLabel(snapshot.connectionStatus);if (connectionLabel) left.push(connectionLabel);if (snapshot.sessionTitle) {- const displayTitle = snapshot.sessionTitle.length > 30- ? snapshot.sessionTitle.slice(0, 30) + "..."- : snapshot.sessionTitle;+ // Lowercase "(Branch)" / "(Branch N)" for the status bar — less+ // prominent than the uppercase metadata version used in /resume list.+ const raw = snapshot.sessionTitle.replace("(Branch", "(branch");+ const displayTitle = raw.length > 30 ? raw.slice(0, 30) + "..." : raw;left.push(displayTitle);}if (snapshot.mode !== "agent.plan") left.push(`mode:${snapshot.mode}`);diff --git a/jiuwenclaw/common/schema/message.py b/jiuwenclaw/common/schema/message.pyindex af706b7f06..612391cc26 100644--- a/jiuwenclaw/common/schema/message.py+++ b/jiuwenclaw/common/schema/message.py@@ -34,6 +34,11 @@ class ReqMethod(Enum):SESSION_CREATE = "session.create"SESSION_DELETE = "session.delete"SESSION_RENAME = "session.rename"+ SESSION_FORK = "session.fork"+ SESSION_REWIND = "session.rewind"+ SESSION_REWIND_AND_RESTORE = "session.rewind_and_restore"+ SESSION_RESTORE_FILES = "session.restore_files"+ HISTORY_LIST_TURNS = "history.list_turns"PATH_GET = "path.get"PATH_SET = "path.set"diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.pyindex e33f1235ed..0570d56dab 100644--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py@@ -87,6 +87,7 @@ CLI_FORWARD_REQ_METHODS = frozenset("extensions.import","extensions.delete","extensions.toggle",+ "session.fork",})@@ -135,6 +136,7 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("extensions.import","extensions.delete","extensions.toggle",+ "session.fork",})@@ -765,6 +767,140 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:shutil.rmtree(session_dir)await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})+ async def _session_rewind(ws, req_id, params, session_id):+ from jiuwenclaw.agents.harness.common.session_ops_service import rewind_session++ if not isinstance(params, dict):+ await channel.send_response(+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"+ )+ return+ target_sid = str(params.get("session_id") or session_id or "").strip()+ turn_index = params.get("turn_index")+ if not target_sid:+ await channel.send_response(+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"+ )+ return+ if turn_index is None:+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index is required", code="BAD_REQUEST"+ )+ return+ try:+ turn_index = int(turn_index)+ except (ValueError, TypeError):+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index must be an integer", code="BAD_REQUEST"+ )+ return+ try:+ result = rewind_session(session_id=target_sid, turn_index=turn_index)+ await channel.send_response(ws, req_id, ok=True, payload=result)+ except ValueError as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")+ except Exception as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")++ async def _history_list_turns(ws, req_id, params, session_id):+ from jiuwenclaw.agents.harness.common.session_ops_service import list_session_turns++ if not isinstance(params, dict):+ params = {}+ target_sid = str(params.get("session_id") or session_id or "").strip()+ if not target_sid:+ await channel.send_response(+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"+ )+ return+ try:+ result = list_session_turns(session_id=target_sid)+ await channel.send_response(ws, req_id, ok=True, payload=result)+ except Exception as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")++ async def _session_rewind_and_restore(ws, req_id, params, session_id):+ """session.rewind_and_restore: 截断对话 + 恢复文件."""+ from jiuwenclaw.agents.harness.common.session_ops_service import (+ restore_session_files,+ rewind_session,+ )++ if not isinstance(params, dict):+ await channel.send_response(+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"+ )+ return+ target_sid = str(params.get("session_id") or session_id or "").strip()+ turn_index = params.get("turn_index")+ if not target_sid:+ await channel.send_response(+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"+ )+ return+ if turn_index is None:+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index is required", code="BAD_REQUEST"+ )+ return+ try:+ turn_index = int(turn_index)+ except (ValueError, TypeError):+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index must be an integer", code="BAD_REQUEST"+ )+ return+ try:+ rewind_result = rewind_session(session_id=target_sid, turn_index=turn_index)+ restore_result = restore_session_files(session_id=target_sid, turn_index=turn_index)+ combined = {+ **rewind_result,+ "restored_files": restore_result.get("restored_files", []),+ "deleted_files": restore_result.get("deleted_files", []),+ "restore_errors": restore_result.get("errors", []),+ }+ await channel.send_response(ws, req_id, ok=True, payload=combined)+ except ValueError as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")+ except Exception as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")++ async def _session_restore_files(ws, req_id, params, session_id):+ """session.restore_files: 仅恢复文件,不截断对话."""+ from jiuwenclaw.agents.harness.common.session_ops_service import restore_session_files++ if not isinstance(params, dict):+ await channel.send_response(+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"+ )+ return+ target_sid = str(params.get("session_id") or session_id or "").strip()+ turn_index = params.get("turn_index")+ if not target_sid:+ await channel.send_response(+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"+ )+ return+ if turn_index is None:+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index is required", code="BAD_REQUEST"+ )+ return+ try:+ turn_index = int(turn_index)+ except (ValueError, TypeError):+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index must be an integer", code="BAD_REQUEST"+ )+ return+ try:+ result = restore_session_files(session_id=target_sid, turn_index=turn_index)+ await channel.send_response(ws, req_id, ok=True, payload=result)+ except ValueError as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")+ except Exception as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")+async def _session_rename(ws, req_id, params, session_id):"""优先经 E2A 转发至 AgentWebSocketServer._handle_session_rename;无 agent 或转发失败时本地回退。"""from jiuwenclaw.server.runtime.session.session_rename import apply_session_rename@@ -1338,6 +1474,10 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:channel.register_local_handler(path, "session.create", _session_create)channel.register_local_handler(path, "session.delete", _session_delete)channel.register_local_handler(path, "session.rename", _session_rename)+ channel.register_local_handler(path, "session.rewind", _session_rewind)+ channel.register_local_handler(path, "session.rewind_and_restore", _session_rewind_and_restore)+ channel.register_local_handler(path, "session.restore_files", _session_restore_files)+ channel.register_local_handler(path, "history.list_turns", _history_list_turns)channel.register_local_handler(path, "chat.send", _chat_send)channel.register_local_handler(path, "chat.resume", _chat_resume)channel.register_local_handler(path, "chat.interrupt", _chat_interrupt)diff --git a/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py b/jiuwenclaw/gateway/message_handler/command_parser/slash_command.pyindex fabdd4a205..875d6a737e 100644--- a/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py+++ b/jiuwenclaw/gateway/message_handler/command_parser/slash_command.py@@ -25,6 +25,8 @@ class GatewaySlashCommand(str, Enum):SWITCH = "/switch"SKILLS = "/skills"SKILLS_LIST = "/skills list"+ BRANCH = "/branch"+ REWIND = "/rewind"class ModeSubcommand(str, Enum):@@ -62,6 +64,8 @@ CONTROL_MESSAGE_TEXTS: frozenset[str] = frozenset(*_VALID_MODE_LINES,*_VALID_SWITCH_LINES,GatewaySlashCommand.SKILLS_LIST.value,+ GatewaySlashCommand.BRANCH.value,+ GatewaySlashCommand.REWIND.value,})@@ -77,6 +81,11 @@ class ParsedControlAction(str, Enum):SWITCH_OK = "switch_ok"SWITCH_BAD = "switch_bad"SKILLS_OK = "skills_ok"+ BRANCH_OK = "branch_ok"+ REWIND_OK = "rewind_ok"+ REWIND_BAD = "rewind_bad"+ REWIND_CONFIRM = "rewind_confirm"+ REWIND_CANCEL = "rewind_cancel"@dataclass(frozen=True)@@ -88,16 +97,26 @@ class ParsedChannelControl:"""mode_ok 时为 agent|code|team|agent.plan|agent.fast|code.plan|code.normal 之一。"""switch_subcommand: str | None = None"""switch_ok 时为 plan|fast|normal 之一。"""+ branch_name: str | None = None+ """branch_ok 时为用户指定的分支名称(可为空字符串)。"""+ rewind_turn: int | None = None+ """rewind_ok 时为用户指定的回退轮次编号;None 表示未指定。"""+ rewind_pending_turn: int | None = None+ """rewind_ok 时记录原始轮次编号,用于 confirm/cancel 两步确认。"""def parse_channel_control_text(text: str) -> ParsedChannelControl:- """解析单条用户文本是否为 /new_session、/mode、/switch、/skills list 控制指令。+ """解析单条用户文本是否为 /new_session、/mode、/switch、/skills list、/branch、/rewind 控制指令。- 含换行则视为非控制(与原 _handle_channel_control 一致)。- /new_session 仅整行精确匹配为合法;带后缀为非法但仍为控制指令。- /mode 仅白名单整行合法;支持 agent|code|team 及四个直达模式值;其它以 /mode 开头且单行非法。- /switch 仅白名单整行合法;其它以 /switch 开头且单行非法。- /skills list 仅整行精确匹配(/skills 本身不再触发)。+ - /branch [name] 合法;name 为可选自定义分支标题。+ - /rewind [N] 合法;N 为可选回退轮次编号(正整数);无参数或非整数参数为非法。+ - /rewind confirm N 确认执行之前发起的 /rewind N。+ - /rewind cancel 取消之前发起的 /rewind N。"""if not text:return ParsedChannelControl(ParsedControlAction.NONE)@@ -123,13 +142,44 @@ def parse_channel_control_text(text: str) -> ParsedChannelControl:return ParsedChannelControl(ParsedControlAction.MODE_BAD)if t.startswith(GatewaySlashCommand.SWITCH.value):return ParsedChannelControl(ParsedControlAction.SWITCH_BAD)+ if t == GatewaySlashCommand.BRANCH.value:+ return ParsedChannelControl(ParsedControlAction.BRANCH_OK, branch_name="")+ if t.startswith(f"{GatewaySlashCommand.BRANCH.value} "):+ name = t[len(GatewaySlashCommand.BRANCH.value):].strip()+ return ParsedChannelControl(ParsedControlAction.BRANCH_OK, branch_name=name)+ if t == GatewaySlashCommand.REWIND.value:+ return ParsedChannelControl(ParsedControlAction.REWIND_BAD)+ # /rewind cancel — 取消之前的 /rewind(须在 /rewind N 前解析)+ if t == "/rewind cancel":+ return ParsedChannelControl(ParsedControlAction.REWIND_CANCEL)+ # /rewind confirm N — 二步确认执行(须在 /rewind N 前解析)+ if t.startswith("/rewind confirm "):+ arg = t[len("/rewind confirm "):].strip()+ try:+ turn = int(arg)+ if turn < 1:+ return ParsedChannelControl(ParsedControlAction.REWIND_BAD)+ return ParsedChannelControl(+ ParsedControlAction.REWIND_CONFIRM, rewind_turn=turn+ )+ except (ValueError, TypeError):+ return ParsedChannelControl(ParsedControlAction.REWIND_BAD)+ if t.startswith(f"{GatewaySlashCommand.REWIND.value} "):+ arg = t[len(GatewaySlashCommand.REWIND.value):].strip()+ try:+ turn = int(arg)+ if turn < 1:+ return ParsedChannelControl(ParsedControlAction.REWIND_BAD)+ return ParsedChannelControl(ParsedControlAction.REWIND_OK, rewind_turn=turn)+ except (ValueError, TypeError):+ return ParsedChannelControl(ParsedControlAction.REWIND_BAD)return ParsedChannelControl(ParsedControlAction.NONE)def is_control_like_for_im_batching(text: str) -> bool:"""飞书/企微等:控制类消息不走合并窗口(与历史行为一致并补全 mode 变体与 /skills list)。- 单条文本、且为已知控制句、或以 /mode / /switch / /new_session 为前缀(含非法变体)时返回 True。+ 单条文本、且为已知控制句、或以 /mode / /switch / /new_session / /branch / /rewind 为前缀时返回 True。"""if not text:return False@@ -149,6 +199,10 @@ def is_control_like_for_im_batching(text: str) -> bool:return Trueif t.startswith(GatewaySlashCommand.NEW_SESSION.value):return True+ if t.startswith(GatewaySlashCommand.BRANCH.value):+ return True+ if t.startswith(GatewaySlashCommand.REWIND.value):+ return Truereturn False@@ -211,6 +265,20 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (req_method=None,notes="TUI 本地保存工作区路径;随 chat.send params.workspace_dir 发往 Gateway/AgentServer。",),+ SlashCommandEntry(+ id="branch",+ canonical_text=f"{GatewaySlashCommand.BRANCH.value} [name]",+ scope="gateway",+ req_method="session.fork",+ notes="受控通道分叉当前会话;Gateway 调 session.fork 并以通知回复;CLI 同路径见 builtins/branch.ts。",+ ),+ SlashCommandEntry(+ id="rewind",+ canonical_text=f"{GatewaySlashCommand.REWIND.value} <turn_number>",+ scope="gateway",+ req_method="session.rewind",+ notes="受控通道回退对话到指定轮次;IM 须带正整数轮次编号;CLI 同路径见 builtins/rewind.ts。",+ ),)diff --git a/jiuwenclaw/gateway/message_handler/message_handler.py b/jiuwenclaw/gateway/message_handler/message_handler.pyindex 537868b447..954c860a0e 100644--- a/jiuwenclaw/gateway/message_handler/message_handler.py+++ b/jiuwenclaw/gateway/message_handler/message_handler.py@@ -700,6 +700,57 @@ class MessageHandler(ABC):)return True+ if parsed.action is ParsedControlAction.BRANCH_OK:+ asyncio.create_task(+ self._branch_slash_notice(+ user_infos, ch, msg.session_id, msg,+ branch_name=parsed.branch_name or "",+ )+ )+ return True++ if parsed.action is ParsedControlAction.REWIND_OK:+ # 两步确认:先发送确认提示,不立即执行+ turn_index = parsed.rewind_turn or 1+ asyncio.create_task(+ self._rewind_slash_confirm_prompt(+ user_infos, ch, msg.session_id, msg,+ turn_index=turn_index,+ )+ )+ return True++ if parsed.action is ParsedControlAction.REWIND_CONFIRM:+ # 用户确认执行 rewind+ asyncio.create_task(+ self._rewind_slash_notice(+ user_infos, ch, msg.session_id, msg,+ turn_index=parsed.rewind_turn or 1,+ )+ )+ return True++ if parsed.action is ParsedControlAction.REWIND_CANCEL:+ # 用户取消 rewind+ asyncio.create_task(+ self._send_channel_notice(+ user_infos, ch, msg.session_id,+ "[收到 /rewind cancel] 已取消回退操作。",+ )+ )+ return True++ if parsed.action is ParsedControlAction.REWIND_BAD:+ asyncio.create_task(+ self._send_channel_notice(+ user_infos,+ ch,+ msg.session_id,+ "非法指令,/rewind 须带正整数轮次编号,如 /rewind 2",+ )+ )+ return True+return Falseasync def _skills_slash_notice(@@ -756,6 +807,165 @@ class MessageHandler(ABC):{"error": f"获取技能列表失败:{exc}"},)+ async def _branch_slash_notice(+ self,+ user_infos: dict[str, Any],+ channel_id: str,+ reply_session_id: str | None,+ msg: "Message",+ *,+ branch_name: str = "",+ ) -> None:+ """受控通道 /branch:分叉当前会话,切换到新 session 并通知。++ Sends session.fork to AgentServer so both filesystem copy (history.json,+ metadata) and in-memory context copy (DeepAgent checkpointer + context+ engine) are performed atomically.+ """+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenclaw.schema.message import ReqMethod++ state = self._get_or_create_channel_state(msg)+ source_sid = state.session_id+ if not source_sid:+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": "当前无活跃会话,无法分叉"},+ )+ return++ channel_type = self._resolve_control_channel_type(msg)+ new_sid = self._generate_channel_session_id(channel_type)++ try:+ env = e2a_from_agent_fields(+ request_id=f"branch-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",+ channel_id=channel_type,+ session_id=source_sid,+ req_method=ReqMethod.SESSION_FORK,+ params={+ "source_session_id": source_sid,+ "target_session_id": new_sid,+ "title": branch_name,+ },+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await self._agent_client.send_request(env)+ if not resp.ok:+ payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}+ raise ValueError(str(payload.get("error") or "session.fork failed"))++ result = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}+ fork_sid = result.get("session_id", new_sid)+ fork_title = result.get("title", branch_name or "Branched conversation")++ old_sid = state.session_id+ state.session_id = fork_sid++ await self._cancel_agent_work_for_session(msg, old_sid)++ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ f"[收到 /branch 指令] 已分叉会话「{fork_title}」,当前已切换到新会话。",+ )+ logger.info(+ "[MessageHandler] /branch 完成: source=%s fork=%s title=%s",+ source_sid, fork_sid, fork_title,+ )+ except ValueError as e:+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": f"分叉失败:{e}"},+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("[MessageHandler] /branch 失败: %s", exc)+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": f"分叉失败:{exc}"},+ )++ async def _rewind_slash_confirm_prompt(+ self,+ user_infos: dict[str, Any],+ channel_id: str,+ reply_session_id: str | None,+ msg: "Message",+ *,+ turn_index: int = 1,+ ) -> None:+ """受控通道 /rewind N:发送确认提示(两步确认第一步)。++ 与 Claude Code 对齐:IM 渠道 /rewind 是不可逆操作,需要确认后才执行。+ """+ state = self._get_or_create_channel_state(msg)+ target_sid = state.session_id+ if not target_sid:+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": "当前无活跃会话,无法回退"},+ )+ return++ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ f"[收到 /rewind {turn_index} 指令] 确认要回退到第 {turn_index} 轮吗?\n"+ f"此操作不可逆,将删除第 {turn_index} 轮及之后的所有对话。\n"+ f"请回复 /rewind confirm {turn_index} 确认,或 /rewind cancel 取消。\n"+ f"注意:回退不影响手动编辑的文件或通过 bash 执行的命令。",+ )++ async def _rewind_slash_notice(+ self,+ user_infos: dict[str, Any],+ channel_id: str,+ reply_session_id: str | None,+ msg: "Message",+ *,+ turn_index: int = 1,+ ) -> None:+ """受控通道 /rewind N:回退当前会话到指定轮次并通知。"""+ from jiuwenclaw.agents.harness.common.session_ops_service import rewind_session++ state = self._get_or_create_channel_state(msg)+ target_sid = state.session_id+ if not target_sid:+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": "当前无活跃会话,无法回退"},+ )+ return++ try:+ await self._cancel_agent_work_for_session(msg, target_sid)++ result = rewind_session(session_id=target_sid, turn_index=turn_index)+ preview = result.get("content_preview", "")+ remaining = result.get("remaining_records", 0)+ removed = result.get("removed_records", 0)++ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ f"[收到 /rewind 指令] 已回退到第 {turn_index} 轮"+ f'("{preview[:50]}")'+ f",删除 {removed} 条记录,剩余 {remaining} 条。",+ )+ logger.info(+ "[MessageHandler] /rewind 完成: session=%s turn=%s remaining=%s removed=%s",+ target_sid, turn_index, remaining, removed,+ )+ except ValueError as e:+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": f"回退失败:{e}"},+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("[MessageHandler] /rewind 失败: %s", exc)+ await self._send_channel_notice(+ user_infos, channel_id, reply_session_id,+ {"error": f"回退失败:{exc}"},+ )+def _apply_channel_state(self, msg: "Message") -> None:"""将当前 Channel 的控制状态应用到消息上(session_id / mode)."""channel_type = self._resolve_control_channel_type(msg)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.pyindex 8716c45dba..a00e33b407 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/report_helper.py@@ -25,7 +25,7 @@ from typing import Any# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径try:- from jiuwenclaw.utils import get_agent_root_dir+ from jiuwenclaw.common.utils import get_agent_root_dir_has_jiuwenclaw = Trueexcept ImportError:_has_jiuwenclaw = Falsediff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.pyindex 25ee298670..ace506d5b0 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/advanced-daily-report/run_report.py@@ -21,7 +21,7 @@ from zoneinfo import ZoneInfo# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径try:- from jiuwenclaw.utils import get_agent_root_dir, get_env_file+ from jiuwenclaw.common.utils import get_agent_root_dir, get_env_file_has_jiuwenclaw = Trueexcept ImportError:_has_jiuwenclaw = Falsediff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.pyindex a00d0a42a5..5fdd7cf000 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py@@ -15,7 +15,7 @@ from typing import Any# 尝试从 jiuwenclaw.utils 导入,如果失败则使用环境变量或硬编码路径try:- from jiuwenclaw.utils import get_agent_sessions_dir+ from jiuwenclaw.common.utils import get_agent_sessions_dir_has_jiuwenclaw = Trueexcept ImportError:_has_jiuwenclaw = Falsediff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.pyindex d1e38649ee..4c8e22d24f 100644--- a/jiuwenclaw/server/agent_ws_server.py+++ b/jiuwenclaw/server/agent_ws_server.py@@ -519,6 +519,10 @@ class AgentWebSocketServer:await self._handle_session_create(ws, request, send_lock)return+ if request.req_method == ReqMethod.SESSION_FORK:+ await self._handle_session_fork(ws, request, send_lock)+ return+if request.req_method == ReqMethod.ACP_TOOL_RESPONSE:await self._handle_acp_tool_response(ws, request, send_lock)return@@ -1872,6 +1876,106 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_session_fork(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:+ """Handle session.fork: filesystem copy + in-memory context copy.++ Args:+ ws: WebSocket connection.+ request: AgentRequest with source_session_id, target_session_id, title.+ send_lock: Send lock.+ """+ from jiuwenclaw.agents.harness.common.session_ops_service import (+ copy_session_context,+ fork_session,+ )++ logger.info(+ "[AgentServer] session.fork: request_id=%s", request.request_id+ )++ try:+ params = request.params if isinstance(request.params, dict) else {}+ source = str(params.get("source_session_id") or "").strip()+ target = str(params.get("target_session_id") or "").strip()+ fork_title = str(params.get("title") or "").strip()+ channel_id = request.channel_id or "default"++ if not source:+ raise ValueError("source_session_id is required")+ if not target:+ raise ValueError("target_session_id is required")++ # 1. Filesystem fork (copies history.json, writes metadata)+ result = fork_session(+ source_session_id=source,+ target_session_id=target,+ title=fork_title,+ channel_id=channel_id,+ )++ # 2. Copy in-memory context (LLM conversation history)+ agent = self._agent_manager.get_agent_nowait(channel_id)+ if agent is not None:+ deep_agent = agent.get_instance()+ await copy_session_context(deep_agent, source, target)+ else:+ logger.warning(+ "[AgentServer] session.fork: no agent for channel %s, "+ "in-memory context copy skipped",+ channel_id,+ )++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=result,+ )+ wire = encode_agent_response_for_wire(+ resp, response_id=request.request_id+ )+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ logger.info(+ "[AgentServer] session.fork completed: source=%s target=%s title=%s",+ source, target, result.get("title", ""),+ )++ except ValueError as e:+ logger.warning("[AgentServer] session.fork ValueError: %s", e)+ code = (+ "NOT_FOUND" if "not found" in str(e)+ else "ALREADY_EXISTS" if "already exists" in str(e)+ else "BAD_REQUEST"+ )+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e), "code": code},+ )+ wire = encode_agent_response_for_wire(+ resp, response_id=request.request_id+ )+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+ except Exception as e:+ logger.exception("[AgentServer] session.fork failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )+ wire = encode_agent_response_for_wire(+ resp, response_id=request.request_id+ )+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_acp_tool_response(self,ws: Any,diff --git a/jiuwenclaw/server/runtime/session/session_history.py b/jiuwenclaw/server/runtime/session/session_history.pyindex ffd1b31d9c..870c916ce0 100644--- a/jiuwenclaw/server/runtime/session/session_history.py+++ b/jiuwenclaw/server/runtime/session/session_history.py@@ -153,3 +153,35 @@ def append_history_record()except Exception as exc:logger.warning("更新会话元数据失败: %s", exc)+++def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, Any]:+ """截断会话历史到指定位置(线程安全)。++ 先等待异步写入队列刷盘,再持锁截断 history.json。+ 返回截断结果 dict,包含 remaining / removed 计数。+ """+ sid = (session_id or "default").strip() or "default"+ _WRITE_QUEUE.join()++ fpath = _history_file(sid)+ with _FILE_LOCK:+ if not fpath.exists():+ return {"remaining_records": 0, "removed_records": 0}+ history = _read_history(fpath)+ if not isinstance(history, list):+ return {"remaining_records": 0, "removed_records": 0}+ total = len(history)+ if cut_index < 0:+ cut_index = 0+ if cut_index > total:+ cut_index = total+ truncated = history[:cut_index]+ fpath.write_text(+ json.dumps(truncated, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ return {+ "remaining_records": len(truncated),+ "removed_records": total - len(truncated),+ }diff --git a/jiuwenclaw/server/runtime/session/session_metadata.py b/jiuwenclaw/server/runtime/session/session_metadata.pyindex 2a662bedf0..06e2e7b6ef 100644--- a/jiuwenclaw/server/runtime/session/session_metadata.py+++ b/jiuwenclaw/server/runtime/session/session_metadata.py@@ -153,6 +153,7 @@ def update_session_metadata(title: str | None = None,clear_title: bool = False,increment_message_count: bool = False,+ set_message_count: int | None = None,user_content: str | None = None,channel_metadata: dict[str, Any] | None = None,mode: str | None = None,@@ -201,6 +202,8 @@ def update_session_metadata(metadata["title"] = titleif increment_message_count:metadata["message_count"] = metadata.get("message_count", 0) + 1+ if set_message_count is not None:+ metadata["message_count"] = set_message_count# 自动生成标题: 当 title 为空且提供了用户消息内容时if not metadata.get("title") and user_content:diff --git a/jiuwenclaw/server/utils/diff_service.py b/jiuwenclaw/server/utils/diff_service.pyindex cca49180c8..2403c6b8fe 100644--- a/jiuwenclaw/server/utils/diff_service.py+++ b/jiuwenclaw/server/utils/diff_service.py@@ -38,7 +38,7 @@ class DiffService:def _compute_turn_diffs(self, session_id: str) -> list[dict[str, Any]]:"""计算 turn-based diffs."""history = self._read_history(session_id)- agent_history = self._read_agent_history()+ agent_history = self._read_agent_history(session_id)if not history:return []@@ -158,8 +158,12 @@ class DiffService:except Exception:return []- def _read_agent_history(self) -> dict[str, Any]:- """读取 .agent_history(同时读取两个可能的位置并合并)."""+ def _read_agent_history(self, session_id: str | None = None) -> dict[str, Any]:+ """读取 .agent_history(同时读取全局与 session-specific 文件并合并).++ Args:+ session_id: 若提供,额外扫描匹配该 session 的 file_ops 文件。+ """result: dict[str, Any] = {}paths = [@@ -167,6 +171,21 @@ class DiffService:get_user_workspace_dir() / ".agent_history" / f"file_ops_{self._agent_id}.json",]+ # session-specific file_ops(如 file_ops_jiuwenclaw_tui_xxx.json)+ if session_id:+ for base_dir in (get_agent_workspace_dir(), get_user_workspace_dir()):+ hist_dir = base_dir / ".agent_history"+ if not hist_dir.is_dir():+ continue+ for f in hist_dir.iterdir():+ name = f.name+ if (+ name.startswith(f"file_ops_{self._agent_id}_")+ and name.endswith(".json")+ and session_id in name+ ):+ paths.append(f)+for history_file in paths:if history_file.exists():try:@@ -287,6 +306,66 @@ class DiffService:f["linesRemoved"] for f in turn["files"].values())+ def get_files_to_restore(+ self, session_id: str, turn_index: int+ ) -> dict[str, dict[str, Any]]:+ """返回需要恢复的文件及其目标内容.++ 对于在 turn_index 及之后所有 turn 中被修改的文件,+ 找到它们在 turn_index 开始前的状态(old_content of the first+ edit at/after the target turn),以便恢复操作将文件写回。++ Args:+ session_id: 会话 ID+ turn_index: 目标回退轮次(1-based,即 /rewind 使用的编号)++ Returns:+ { file_path: { "restore_content": str | None, "action": "write" | "delete" } }+ restore_content 为 None 表示文件在目标 turn 之前不存在,应删除。+ """+ history = self._read_history(session_id)+ if not history:+ return {}++ # 1. 找到目标 turn 的起始时间(第 N 条 user 消息的 timestamp)+ user_count = 0+ target_timestamp: float | None = None+ for record in history:+ if record.get("role") == "user":+ user_count += 1+ if user_count == turn_index:+ target_timestamp = record.get("timestamp")+ break++ if target_timestamp is None:+ return {}++ # 2. 读取 file_ops 日志+ agent_history = self._read_agent_history(session_id)++ # 3. 对于每个文件,找到第一条 timestamp >= target_timestamp 的 entry+ # 该 entry 的 old_content 即为目标 turn 开始前的文件状态+ files_to_restore: dict[str, dict[str, Any]] = {}+ for file_path, entries in agent_history.items():+ # entries 按 timestamp 排序(写入时序)+ for entry in entries:+ edit_time = self._iso_to_timestamp(entry["timestamp"])+ if edit_time >= target_timestamp:+ if entry.get("old_content") is not None:+ files_to_restore[file_path] = {+ "restore_content": entry["old_content"],+ "action": "write",+ }+ else:+ # 文件由 agent 创建,恢复时应删除+ files_to_restore[file_path] = {+ "restore_content": None,+ "action": "delete",+ }+ break # 只需要第一条匹配的 entry++ return files_to_restore+_diff_service: DiffService | None = Nonediff --git a/tests/unit_tests/gateway/test_slash_command.py b/tests/unit_tests/gateway/test_slash_command.pyindex dcaca6f705..92e6718042 100644--- a/tests/unit_tests/gateway/test_slash_command.py+++ b/tests/unit_tests/gateway/test_slash_command.py@@ -30,43 +30,64 @@ parse_channel_control_text = _MOD.parse_channel_control_text@pytest.mark.parametrize(- ("text", "action", "mode_sub", "switch_sub"),+ ("text", "action", "subcommand", "branch_name", "rewind_turn"),[- ("", ParsedControlAction.NONE, None, None),- ("hello", ParsedControlAction.NONE, None, None),- ("/new_session", ParsedControlAction.NEW_SESSION_OK, None, None),- ("/new_session x", ParsedControlAction.NEW_SESSION_BAD, None, None),- ("/mode agent", ParsedControlAction.MODE_OK, "agent", None),- ("/mode code", ParsedControlAction.MODE_OK, "code", None),- ("/mode team", ParsedControlAction.MODE_OK, "team", None),- ("/mode agent.plan", ParsedControlAction.MODE_OK, "agent.plan", None),- ("/mode agent.fast", ParsedControlAction.MODE_OK, "agent.fast", None),- ("/mode code.plan", ParsedControlAction.MODE_OK, "code.plan", None),- ("/mode code.normal", ParsedControlAction.MODE_OK, "code.normal", None),- ("/mode plan", ParsedControlAction.MODE_BAD, None, None),- ("/mode", ParsedControlAction.MODE_BAD, None, None),- ("/switch plan", ParsedControlAction.SWITCH_OK, None, "plan"),- ("/switch fast", ParsedControlAction.SWITCH_OK, None, "fast"),- ("/switch normal", ParsedControlAction.SWITCH_OK, None, "normal"),- ("/switch code", ParsedControlAction.SWITCH_BAD, None, None),- ("/switch", ParsedControlAction.SWITCH_BAD, None, None),- ("/skills", ParsedControlAction.NONE, None, None),- ("/skills list", ParsedControlAction.SKILLS_OK, None, None),- ("/skills list", ParsedControlAction.SKILLS_OK, None, None),- ("/skills extra", ParsedControlAction.NONE, None, None),- ("line1\nline2", ParsedControlAction.NONE, None, None),+ ("", ParsedControlAction.NONE, None, None, None),+ ("hello", ParsedControlAction.NONE, None, None, None),+ ("/new_session", ParsedControlAction.NEW_SESSION_OK, None, None, None),+ ("/new_session x", ParsedControlAction.NEW_SESSION_BAD, None, None, None),+ ("/mode agent", ParsedControlAction.MODE_OK, ("agent", None), None, None),+ ("/mode code", ParsedControlAction.MODE_OK, ("code", None), None, None),+ ("/mode team", ParsedControlAction.MODE_OK, ("team", None), None, None),+ ("/mode agent.plan", ParsedControlAction.MODE_OK, ("agent.plan", None), None, None),+ ("/mode agent.fast", ParsedControlAction.MODE_OK, ("agent.fast", None), None, None),+ ("/mode code.plan", ParsedControlAction.MODE_OK, ("code.plan", None), None, None),+ ("/mode code.normal", ParsedControlAction.MODE_OK, ("code.normal", None), None, None),+ ("/mode plan", ParsedControlAction.MODE_BAD, (None, None), None, None),+ ("/mode", ParsedControlAction.MODE_BAD, (None, None), None, None),+ ("/switch plan", ParsedControlAction.SWITCH_OK, (None, "plan"), None, None),+ ("/switch fast", ParsedControlAction.SWITCH_OK, (None, "fast"), None, None),+ ("/switch normal", ParsedControlAction.SWITCH_OK, (None, "normal"), None, None),+ ("/switch code", ParsedControlAction.SWITCH_BAD, (None, None), None, None),+ ("/switch", ParsedControlAction.SWITCH_BAD, (None, None), None, None),+ ("/skills", ParsedControlAction.NONE, None, None, None),+ ("/skills list", ParsedControlAction.SKILLS_OK, None, None, None),+ ("/skills list", ParsedControlAction.SKILLS_OK, None, None, None),+ ("/skills extra", ParsedControlAction.NONE, None, None, None),+ ("line1\nline2", ParsedControlAction.NONE, None, None, None),+ ("/branch", ParsedControlAction.BRANCH_OK, None, "", None),+ ("/branch fix-login", ParsedControlAction.BRANCH_OK, None, "fix-login", None),+ ("/branch multi word name", ParsedControlAction.BRANCH_OK, None, "multi word name", None),+ ("/rewind 3", ParsedControlAction.REWIND_OK, None, None, 3),+ ("/rewind 1", ParsedControlAction.REWIND_OK, None, None, 1),+ ("/rewind", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind abc", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind 0", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind -1", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind confirm 3", ParsedControlAction.REWIND_CONFIRM, None, None, 3),+ ("/rewind confirm 1", ParsedControlAction.REWIND_CONFIRM, None, None, 1),+ ("/rewind confirm 0", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind confirm abc", ParsedControlAction.REWIND_BAD, None, None, None),+ ("/rewind cancel", ParsedControlAction.REWIND_CANCEL, None, None, None),],)def test_parse_channel_control_text(text: str,action: ParsedControlAction,- mode_sub: str | None,- switch_sub: str | None,+ subcommand: tuple[str | None, str | None] | None,+ branch_name: str | None,+ rewind_turn: int | None,) -> None:p = parse_channel_control_text(text)assert p.action is action- assert p.mode_subcommand == mode_sub- assert p.switch_subcommand == switch_sub+ if subcommand:+ assert p.mode_subcommand == subcommand[0]+ assert p.switch_subcommand == subcommand[1]+ else:+ assert p.mode_subcommand is None+ assert p.switch_subcommand is None+ assert p.branch_name == branch_name+ assert p.rewind_turn == rewind_turndef test_control_message_texts_contains_mode_variants_and_skills() -> None:@@ -79,6 +100,8 @@ def test_control_message_texts_contains_mode_variants_and_skills() -> None:assert "/mode agent.plan" in CONTROL_MESSAGE_TEXTSassert "/mode code.normal" in CONTROL_MESSAGE_TEXTSassert "/switch normal" in CONTROL_MESSAGE_TEXTS+ assert "/branch" in CONTROL_MESSAGE_TEXTS+ assert "/rewind" in CONTROL_MESSAGE_TEXTSdef test_is_control_like_for_im_batching() -> None:@@ -91,6 +114,10 @@ def test_is_control_like_for_im_batching() -> None:assert is_control_like_for_im_batching("/new_sessionoops")assert is_control_like_for_im_batching("/skills list")assert is_control_like_for_im_batching("/skills list")+ assert is_control_like_for_im_batching("/branch")+ assert is_control_like_for_im_batching("/branch fix-login")+ assert is_control_like_for_im_batching("/rewind 3")+ assert is_control_like_for_im_batching("/rewind")assert not is_control_like_for_im_batching("/skills")assert not is_control_like_for_im_batching("/skills extra")assert not is_control_like_for_im_batching("")@@ -113,4 +140,4 @@ def test_format_skills_list_for_notice() -> None:def test_first_batch_registry_ids() -> None:ids = {e.id for e in FIRST_BATCH_REGISTRY}- assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir"}+ assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir", "branch", "rewind"}