Skip to content

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): Show past conversations when previewing with the /resume command

kdgmpw4800a9a901ae
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 47a3796a3c..f55bc8af61 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -170,10 +170,21 @@ type ResumeSessionListState = {
currentBranch: string;
/** 非空时进入只读预览态(Space 触发,对齐 Claude Code preview):展示选中会话的信息卡 */
preview: SessionMeta | null;
+ /** 预览时的最新对话摘要列表 */
+ previewMessages: PreviewMessage[];
+ /** 预览消息是否仍在请求中(用于区分"加载中"与"已加载但为空") */
+ previewLoading: boolean;
/** 非空时进入重命名态(Ctrl+R 触发,对齐 Claude Code Ctrl+R):编辑选中会话标题 */
rename: { sessionId: string; value: string } | null;
};
+/** 预览消息摘要 */
+type PreviewMessage = {
+ role: string;
+ summary: string;
+ event_type: string;
+};
+
type ModelListState = {
list: SelectList;
models: string[];
@@ -1620,14 +1631,14 @@ export class AppScreen implements Component, Focusable {
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.resumeSessionList = { ...this.resumeSessionList, preview: null, previewMessages: [], previewLoading: false };
this.tui.requestRender();
}
return;
}
// Space 打开选中会话的预览(牺牲在搜索框输入空格的能力,按用户要求)
if (matchesKey(data, "space")) {
- this.openResumeSessionPreview();
+ void this.openResumeSessionPreview();
return;
}
// Ctrl+R 重命名选中会话
@@ -2480,6 +2491,8 @@ export class AppScreen implements Component, Focusable {
branchFilterEnabled: false,
currentBranch,
preview: null,
+ previewMessages: [],
+ previewLoading: false,
rename: null,
};
this.tui.requestRender();
@@ -2517,6 +2530,8 @@ export class AppScreen implements Component, Focusable {
branchFilterEnabled,
currentBranch,
preview: null,
+ previewMessages: [],
+ previewLoading: false,
rename: null,
};
this.tui.requestRender();
@@ -2642,8 +2657,8 @@ export class AppScreen implements Component, Focusable {
this.tui.requestRender();
}
- /** 打开选中会话的只读预览(信息卡)。Space 触发,对齐 Claude Code 的 preview。 */
- private openResumeSessionPreview(): void {
+ /** 打开选中会话的只读预览(信息卡 + 最新对话)。Space 触发,对齐 Claude Code 的 preview。 */
+ private async openResumeSessionPreview(): Promise<void> {
if (!this.resumeSessionList) return;
const selected = this.resumeSessionList.list.getSelectedItem();
if (!selected) return;
@@ -2651,8 +2666,36 @@ export class AppScreen implements Component, Focusable {
(s) => s.session_id === selected.value,
);
if (!session) return;
- this.resumeSessionList = { ...this.resumeSessionList, preview: session };
+ // 先设置 preview 状态并标记加载中,显示基本信息
+ this.resumeSessionList = {
+ ...this.resumeSessionList,
+ preview: session,
+ previewMessages: [],
+ previewLoading: true,
+ };
this.tui.requestRender();
+ // 异步获取预览消息
+ try {
+ const resp = await this.state.request<{ session_id: string; preview_messages: PreviewMessage[] }>(
+ "session.preview",
+ { session_id: session.session_id, count: 2 },
+ );
+ if (this.resumeSessionList && this.resumeSessionList.preview?.session_id === session.session_id) {
+ this.resumeSessionList = {
+ ...this.resumeSessionList,
+ previewMessages: resp.preview_messages ?? [],
+ previewLoading: false,
+ };
+ this.tui.requestRender();
+ }
+ } catch (error) {
+ // 获取失败不影响预览基本信息显示,但需结束加载态
+ console.debug("[openResumeSessionPreview] session.preview failed:", error);
+ if (this.resumeSessionList && this.resumeSessionList.preview?.session_id === session.session_id) {
+ this.resumeSessionList = { ...this.resumeSessionList, previewLoading: false };
+ this.tui.requestRender();
+ }
+ }
}
/** 进入重命名态,初始值取当前标题。Ctrl+R 触发,对齐 Claude Code。 */
@@ -2729,25 +2772,59 @@ export class AppScreen implements Component, Focusable {
].filter((l) => l !== "");
}
- private buildResumeSessionPreviewLines(width: number, session: SessionMeta): string[] {
+ private buildResumeSessionPreviewLines(width: number, session: SessionMeta, previewMessages: PreviewMessage[]): 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);
+
+ // 构建预览消息行:每条对话按宽度换行展示,内容超长时优先保留后半部分(末尾若干行)
+ const MAX_LINES_PER_MSG = 5;
+ const indent = " ";
+ const contentWidth = Math.max(1, width - indent.length);
+ const messageLines: string[] = [];
+ if (previewMessages.length > 0) {
+ previewMessages.forEach((msg, msgIdx) => {
+ const isUser = msg.role === "user";
+ const roleLabel = isUser ? "You:" : "Assistant:";
+ const roleColor = isUser ? palette.text.accent : palette.text.primary;
+ messageLines.push(padToWidth(roleColor(roleLabel), width));
+ // 按宽度换行,内容过长时只保留末尾 MAX_LINES_PER_MSG 行(展示对话后半部分)
+ const wrapped = renderWrappedText(contentWidth, msg.summary.trim());
+ let shown = wrapped;
+ let headTruncated = false;
+ if (wrapped.length > MAX_LINES_PER_MSG) {
+ shown = wrapped.slice(wrapped.length - MAX_LINES_PER_MSG);
+ headTruncated = true;
+ }
+ if (headTruncated) {
+ // 用纯 ASCII 省略号另起一行标记“上文已截断”,避免 U+2026 在部分终端按 2 列
+ // 渲染、而 visibleWidth 按 1 列计算导致该行超宽
+ messageLines.push(padToWidth(palette.text.dim(`${indent}...`), width));
+ }
+ shown.forEach((line) => {
+ messageLines.push(padToWidth(palette.text.dim(`${indent}${line}`), width));
+ });
+ // 消息之间留空行分隔(最后一条不加)
+ if (msgIdx < previewMessages.length - 1) {
+ messageLines.push("");
+ }
+ });
+ } else if (this.resumeSessionList?.previewLoading) {
+ // 请求进行中:显示加载提示
+ messageLines.push(padToWidth(palette.text.dim("Loading recent messages..."), width));
+ } else {
+ // 请求已完成但无可展示对话(如全部为 tool_call/tool_result,被后端过滤)
+ messageLines.push(padToWidth(palette.text.dim("No conversation to preview"), 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("Project: ")}${palette.text.primary(project)}`, width),
+ "",
+ padToWidth(palette.text.dim("Recent conversation"), width),
+ "",
+ ...messageLines,
"",
padToWidth(palette.text.dim("Enter resume · Space/Esc back"), width),
];
@@ -2783,7 +2860,7 @@ export class AppScreen implements Component, Focusable {
return this.buildResumeSessionRenameLines(width, session, r.value);
}
if (this.resumeSessionList.preview !== null) {
- return this.buildResumeSessionPreviewLines(width, this.resumeSessionList.preview);
+ return this.buildResumeSessionPreviewLines(width, this.resumeSessionList.preview, this.resumeSessionList.previewMessages);
}
const showAll = this.resumeSessionList.showAllProjects;
const branchOn = this.resumeSessionList.branchFilterEnabled;
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 7fd80d29e7..bdba3d1ac5 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -1817,6 +1817,97 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
payload={"session_id": target, "accent_color": str(color)}
)
+ async def _session_preview(ws, req_id, params, session_id):
+ """获取 session 预览信息,包括最新几条对话摘要。"""
+ import json
+ from pathlib import Path
+ from jiuwenswarm.common.utils import get_agent_sessions_dir
+
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"
+ )
+ return
+ target = str(params.get("session_id") or session_id).strip()
+ if not target:
+ await channel.send_response(
+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"
+ )
+ return
+
+ # 预览消息数量,默认 3 条
+ preview_count = 3
+ raw_count = params.get("count")
+ if isinstance(raw_count, int):
+ preview_count = max(1, min(raw_count, 10))
+ elif isinstance(raw_count, str) and raw_count.strip().isdigit():
+ preview_count = max(1, min(int(raw_count.strip()), 10))
+
+ # 读取 history.json
+ history_path: Path = get_agent_sessions_dir() / target / "history.json"
+ preview_messages = []
+ if history_path.exists():
+ try:
+ raw = json.loads(history_path.read_text(encoding="utf-8"))
+ if isinstance(raw, list):
+ # history.json 的写入很宽松:interface.py 中所有 event_type 以 "chat." 开头
+ # 的记录(外加 team.message)都会以 role="assistant" 落盘,因此历史里混有大量
+ # 非对话内容。预览只需展示真正代表"对话"的两类,用白名单显式放行:
+ # - chat.final :assistant 的完整最终回复(单人模式与团队成员回复都用它)
+ # - team.message:团队消息
+ # 刻意排除(均非完整对话文本,纳入会造成碎片化/重复/噪声):
+ # - chat.delta(流式增量片段,内容已包含在 chat.final 中)
+ # - chat.reasoning(思考过程)/ chat.tool_call / chat.tool_update / chat.tool_result
+ # - chat.error / chat.processing_status / chat.usage_* / chat.media / chat.file 等
+ # 注:用白名单而非黑名单,是为了让将来新增的 chat.* 状态类型不会意外混入预览。
+ _chat_event_types = frozenset({
+ "chat.final", # assistant 最终回复
+ "team.message", # team 消息
+ })
+
+ def _is_previewable(item):
+ if not isinstance(item, dict):
+ return False
+ role = item.get("role")
+ content = item.get("content")
+ has_content = isinstance(content, str) and bool(content.strip())
+ if role == "user":
+ return has_content
+ # 非 user 记录只放行白名单内的对话类型(不依赖 role,
+ # 以兼容团队成员回复可能带 teammate 等非 assistant role 的情况)
+ event_type = item.get("event_type")
+ if event_type in _chat_event_types:
+ return has_content
+ return False
+
+ previewable = [item for item in raw if _is_previewable(item)]
+ # 取时间顺序下最新的 N 条(保持原顺序:旧的在上、新的在下)
+ recent = previewable[-preview_count:]
+ # 提取摘要(优先展示对话后半部分)
+ for msg in recent:
+ role = msg.get("role", "unknown")
+ content = msg.get("content", "")
+ event_type = msg.get("event_type", "")
+ if isinstance(content, str):
+ # 折叠所有空白(含换行/制表符)为单个空格,避免破坏预览布局;
+ # 再截取末尾 400 字符,优先保留对话的后半部分
+ normalized = " ".join(content.split())
+ summary = normalized[-400:]
+ else:
+ summary = ""
+ preview_messages.append({
+ "role": role,
+ "summary": summary,
+ "event_type": event_type,
+ })
+ except Exception as exc:
+ logger.warning("[session.preview] read history failed: %s", exc)
+
+ await channel.send_response(
+ ws, req_id, ok=True,
+ payload={"session_id": target, "preview_messages": preview_messages}
+ )
+
async def _chat_send(ws, req_id, params, session_id):
await channel.send_response(
ws, req_id, ok=True, payload={"accepted": True, "session_id": session_id}
@@ -2230,6 +2321,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
channel.register_local_handler(path, "session.delete", _session_delete)
channel.register_local_handler(path, "session.rename", _session_rename)
channel.register_local_handler(path, "session.color_set", _session_color_set)
+ channel.register_local_handler(path, "session.preview", _session_preview)
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)