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): 多tui窗口resume同一session防护

kdgmpw677c3a02fbb4
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
index 87692c33ee..4acdf61f04 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
@@ -14,6 +14,8 @@ export interface SessionMeta {
project_dir?: string;
/** 会话首条消息时所在的 git 分支(gateway 回填;非 git/detached 为 "HEAD",存量会话为空串) */
git_branch?: string;
+ /** 该会话已在另一个 TUI 窗口打开(gateway 由 _session_to_client 标记),resume 前端拦截冲突 */
+ active_in_window?: boolean;
}
export interface SessionListPayload {
@@ -63,6 +65,17 @@ async function doResume(
ctx: Parameters<SlashCommand["action"]>[0],
session: SessionMeta,
): Promise<void> {
+ if (session.active_in_window) {
+ const title = session.title?.trim() || session.session_id;
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Session "${title}" is already open in another TUI window. Close that window first or choose a different session.`,
+ "r",
+ ),
+ );
+ return;
+ }
ctx.updateSession(session.session_id);
ctx.clearEntries();
ctx.setAccentColor(session.accent_color || "default");
@@ -137,9 +150,10 @@ export function createResumeCommand(): SlashCommand {
? new Date(s.last_message_at * 1000).toLocaleString()
: "-";
const title = s.title || "-";
+ const activeTag = s.active_in_window ? " [open in another window]" : "";
return {
label: String(i + 1),
- value: `${s.session_id} | ${title} | msgs: ${s.message_count ?? 0} | ${lastActive}`,
+ value: `${s.session_id} | ${title} | msgs: ${s.message_count ?? 0} | ${lastActive}${activeTag}`,
};
});
ctx.addItem(
@@ -182,9 +196,10 @@ export function createResumeCommand(): SlashCommand {
? new Date(s.last_message_at * 1000).toLocaleString()
: "-";
const title = s.title || "(untitled)";
+ const activeTag = s.active_in_window ? " [open in another window]" : "";
return {
label: String(i + 1),
- value: `${s.session_id} | ${title} | msgs: ${s.message_count ?? 0} | ${lastActive}`,
+ value: `${s.session_id} | ${title} | msgs: ${s.message_count ?? 0} | ${lastActive}${activeTag}`,
};
});
ctx.addItem(
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 25a3e9df37..98a93cb1ca 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -1030,6 +1030,7 @@ function sessionToSelectItem(s: SessionMeta, showProject = false): SelectItem {
const msgCount = s.message_count ?? 0;
if (msgCount > 0) parts.push(`${msgCount} msgs`);
if (showProject && s.project_dir?.trim()) parts.push(s.project_dir.trim());
+ if (s.active_in_window) parts.push("in another window");
return {
value: s.session_id,
label: getDisplayLabel(s),
@@ -3220,6 +3221,20 @@ export class AppScreen implements Component, Focusable {
const matchedSession = sessions.find((s) => s.session_id === nextSessionId);
const accentColor = matchedSession?.accent_color ?? "default";
+ // 检测目标 session 是否已在其他 TUI 窗口打开,避免多窗口 session 冲突
+ if (matchedSession?.active_in_window) {
+ const title = matchedSession.title?.trim() || nextSessionId;
+ this.state.addItem(
+ addInfo(
+ this.state.getSnapshot().sessionId,
+ `Session "${title}" is already open in another TUI window. Close that window first or choose a different session.`,
+ "r",
+ ),
+ );
+ this.tui.requestRender();
+ return;
+ }
+
// 跨项目目录已由后端 session.list 完成过滤(_session_matches_project),
// 此处不再重复校验,避免前后端路径规范化差异(resolve vs realpath)
// 导致误拦截本已通过后端过滤的会话。
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 412b3f45b2..c52403c0d7 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -275,6 +275,25 @@ class GatewayServer:
if isinstance(key, tuple) and key[0] == channel_id and not getattr(client_ws, "closed", False)
]
+ def get_active_session_ids(self, channel_id: str, exclude_ws: Any = None) -> set[str]:
+ """返回当前已绑定到活跃连接的 session_id 集合(排除 exclude_ws 自身)。
+
+ 用于 /resume 冲突检测:当目标 session 已在另一个 TUI 窗口打开时,
+ 前端可据此给出提示而非切换 session。
+ """
+ result: set[str] = set()
+ for key, ws in self._session_to_client.items():
+ if not isinstance(key, tuple) or len(key) < 2 or key[0] != channel_id:
+ continue
+ if ws is exclude_ws:
+ continue
+ if bool(getattr(ws, "closed", False)):
+ continue
+ sid = str(key[1] or "").strip()
+ if sid:
+ result.add(sid)
+ return result
+
@staticmethod
def _extract_routing_session_id(msg, *, include_top_level: bool = True) -> str | None:
"""Best-effort session id from message fields for outbound event routing."""
@@ -675,7 +694,8 @@ class GatewayServer:
)
return
- session_id = str(params.get("session_id") or "").strip() or req_id
+ explicit_session_id = bool(str(params.get("session_id") or "").strip())
+ session_id = (str(params.get("session_id") or "").strip()) or req_id
# 1. forward 优先:方法在 forward_methods 中则转发到 MessageHandler
if method in route.forward_methods:
@@ -695,9 +715,32 @@ class GatewayServer:
return
request_key = self._client_route_key(route.channel_id, req_id)
+ # 仅当客户端显式提供 session_id 时才计算 session_key,
+ # 避免 session_id 回退到 req_id 时在 _session_to_client 中积累
+ # 无用的逐请求条目(污染 get_active_session_ids 遍历与冲突检测)。
+ session_key = self._client_route_key(route.channel_id, session_id) if explicit_session_id else None
+ # 检测 session 是否已在其他窗口打开:若已绑定到另一个仍活跃的连接,
+ # 拒绝当前请求,避免多窗口 session 冲突(事件路由串台、binding 被覆盖)。
+ # 前端 session.list 的 active_in_window 标记是"事后快照",此处是实时防线。
+ if session_key is not None:
+ existing_ws = self._session_to_client.get(session_key)
+ if (
+ existing_ws is not None
+ and existing_ws is not ws
+ and not bool(getattr(existing_ws, "closed", False))
+ ):
+ logger.warning(
+ "GatewayServer reject %s: session %s already active in another %s connection",
+ method, session_id, route.channel_id,
+ )
+ await self.send_response(
+ ws, req_id, ok=False,
+ error=f"Session {session_id} is already active in another window. Close that window first.",
+ code="SESSION_IN_USE",
+ )
+ return
if request_key is not None:
self._request_to_client[request_key] = ws
- session_key = self._client_route_key(route.channel_id, session_id)
if session_key is not None:
self._session_to_client[session_key] = ws
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 3b05b46621..bbb1b67cc4 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -1260,6 +1260,19 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
# 会话首条消息时记录的分支;存量会话无该字段时回填空串(前端按"兜底显示"处理)
s["git_branch"] = str(ch_meta.get("git_branch") or "").strip()
+ # 标记已在其他 TUI 窗口中打开的会话,供前端拦截冲突的 /resume
+ try:
+ active_session_ids = channel.get_active_session_ids("tui", exclude_ws=ws)
+ except Exception:
+ logger.warning(
+ "[tui] session.list: get_active_session_ids failed, active_in_window degraded",
+ exc_info=True,
+ )
+ active_session_ids = set()
+ for s in cli_sessions:
+ if s.get("session_id") in active_session_ids:
+ s["active_in_window"] = True
+
# 当前项目的 git 分支,供前端 Ctrl+B 过滤对比(非 git/失败为哨兵 "HEAD")
from jiuwenswarm.common.utils import resolve_git_branch