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): 修复多窗口 /resume 冲突导致窗口异常退出

kdgmpw4309fa2e2eb5
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 4acdf61f04..60cfcd46e0 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/resume.ts
@@ -76,20 +76,47 @@ async function doResume(
);
return;
}
+ // 保存旧会话状态:restoreHistory 在 SESSION_IN_USE / TOCTOU 等场景下会失败,此时本地
+ // sessionId 已切换、entries 已清空,需在 catch 中回滚,避免停留在一个未成功恢复但
+ // sessionId 已切过去的半成品状态(后续消息会继续命中占用冲突)。
+ const previousSessionId = ctx.sessionId;
+ const previousAccent = ctx.accentColor;
+ const previousTitle = ctx.sessionTitle;
ctx.updateSession(session.session_id);
ctx.clearEntries();
ctx.setAccentColor(session.accent_color || "default");
ctx.addItem(addInfo(session.session_id, `Resumed session ${session.session_id}`, "r"));
- void ctx.restoreHistory(session.session_id);
void (async () => {
try {
- const meta = await ctx.request<{ session_id: string; title: string }>(
- "session.rename",
- { session_id: session.session_id },
+ await ctx.restoreHistory(session.session_id);
+ // 成功后才拉取并设置目标会话标题,避免失败回滚后被并行的 title 请求覆盖
+ void (async () => {
+ try {
+ const meta = await ctx.request<{ session_id: string; title: string }>("session.rename", {
+ session_id: session.session_id,
+ });
+ ctx.setSessionTitle(meta.title || "");
+ } catch {
+ ctx.setSessionTitle("");
+ }
+ })();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ // 回滚到恢复前的会话状态:sessionId/accentColor/sessionTitle
+ ctx.updateSession(previousSessionId);
+ ctx.setAccentColor(previousAccent);
+ ctx.setSessionTitle(previousTitle);
+ // 重新拉取旧会话历史以还原 entries(best-effort,失败则保留空 transcript + 错误条)
+ void (async () => {
+ try {
+ await ctx.restoreHistory(previousSessionId);
+ } catch {
+ /* best-effort:旧会话历史拉取失败时保留已有 entries */
+ }
+ })();
+ ctx.addItem(
+ addError(previousSessionId, `Failed to resume ${session.session_id}: ${message}`),
);
- ctx.setSessionTitle(meta.title || "");
- } catch {
- ctx.setSessionTitle("");
}
})();
}
@@ -168,9 +195,7 @@ export function createResumeCommand(): SlashCommand {
// 1. Session ID exact/prefix match
const sessionIdMatch = allSessions.find(
- (s) =>
- s.session_id === value ||
- (s.session_id.startsWith(value) && value.length >= 8),
+ (s) => s.session_id === value || (s.session_id.startsWith(value) && value.length >= 8),
);
if (sessionIdMatch) {
await doResume(ctx, sessionIdMatch);
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 03250ae5de..3b79390a39 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -526,6 +526,32 @@ class GatewayServer:
return False
return self._session_to_client.get(session_key) is ws
+ def get_active_session_ids(
+ self,
+ channel_id: str,
+ exclude_ws: Any = None,
+ ) -> set[str]:
+ """返回在指定 channel 下、仍处于活跃连接绑定的 session_id 集合。
+
+ 用于 session.list 标记 active_in_window,供前端在 /resume 前拦截冲突会话。
+ 排除 exclude_ws(通常是发起 session.list 请求的连接本身),并跳过已关闭的 ws,
+ 与实时防线(forward 阶段 SESSION_IN_USE 检查)口径保持一致。
+ """
+ active: set[str] = set()
+ for key, client_ws in self._session_to_client.items():
+ if not isinstance(key, tuple) or len(key) < 2:
+ continue
+ if key[0] != channel_id:
+ continue
+ if client_ws is exclude_ws:
+ continue
+ if bool(getattr(client_ws, "closed", False)):
+ continue
+ session_id = key[1]
+ if isinstance(session_id, str) and session_id:
+ active.add(session_id)
+ return active
+
@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."""