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(btw): overlay UI isolation and session-scoped context lookup

ldstyle899b9672381e2
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
index eb192762a2..f02e66aa6c 100644
--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
@@ -143,6 +143,10 @@ export interface AppSnapshot {
streamStalled: boolean;
streamIdleMs: number | null;
currentQueryUsage: CurrentQueryUsage;
+ /** /btw 侧问题覆盖层:独立于 transcript 渲染,不受滚动影响 */
+ btwOverlay: { question: string; answer: string } | null;
+ /** BTW 是否处于活动状态(加载中或 overlay 可见),Esc 优先消费 */
+ btwActive: boolean;
}
function formatElapsed(ms: number): string {
@@ -320,6 +324,10 @@ export class CliPiAppState {
private streamStalled = false;
/** 当 closeUi 中 cancelBeforeExit 调 cancel({showNotice:false}) 时置 true,抑制 chat.interrupt_result 的 UI 通知。 */
private suppressInterruptResult = false;
+ /** /btw 侧问题覆盖层:独立于 transcript 渲染 */
+ private btwOverlay: { question: string; answer: string } | null = null;
+ /** BTW 是否处于活动状态(加载中或 overlay 可见),用于 Esc 优先级判断 */
+ private _btwActive = false;
/** 本地中断请求标志,cancel() 调用时立即置 true,用于 long-running 命令的中断检测。 */
private interruptRequested = false;
/** 当前正在执行的斜杠命令 WS 请求 ID,用于 Ctrl+C 时立即取消。 */
@@ -865,12 +873,15 @@ export class CliPiAppState {
(s) => s.status !== "completed" && s.status !== "error",
);
// 与「Ctrl+C 强制结束当前任务」对齐:有任一进行中工作则为 true。
+ // 包含 activeCommandRequestId 以确保 /btw 等命令请求在等待响应期间
+ // 也能被 Esc 取消(WS 请求会被立即中止,避免等待超时)。
const cancellableWork =
isProcessing ||
this.streamingState === StreamingState.Paused ||
hasRunningTools ||
hasActiveSubtasks ||
this.evolutionStatus === "running" ||
+ this.activeCommandRequestId !== null ||
(isTeamMode(this.mode) && isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));
return {
connectionStatus: this.connectionStatus,
@@ -930,6 +941,9 @@ export class CliPiAppState {
streamIdleMs:
this.lastStreamActivityAt === null ? null : Date.now() - this.lastStreamActivityAt,
currentQueryUsage: { ...this.currentQueryUsage },
+ streamIdleMs: this.lastStreamActivityAt === null ? null : Date.now() - this.lastStreamActivityAt,
+ btwOverlay: this.btwOverlay,
+ btwActive: this._btwActive,
};
}
@@ -990,6 +1004,9 @@ export class CliPiAppState {
accentColor: snapshot.accentColor,
updateSession: this.updateSession,
addItem: this.addItem,
+ setBtwOverlay: this.setBtwOverlay,
+ clearBtwOverlay: this.clearBtwOverlay,
+ setBtwActive: this.setBtwActive,
clearEntries: this.clearEntries,
restoreHistory: this.restoreHistory,
exitApp: () => {
@@ -1219,6 +1236,8 @@ export class CliPiAppState {
this.usageByModel.clear();
this.resetCurrentUsageTokens();
this.workflowRuns = [];
+ this.btwOverlay = null;
+ this._btwActive = false;
if (this.accentColor !== "default") {
this.accentColor = "default";
setCurrentAccentColor("default");
@@ -1254,10 +1273,38 @@ export class CliPiAppState {
// 用户发言后重置自动回顾状态,允许下一次空闲时触发新的回顾
if (item.kind === "user") {
this.autoRecapState = "idle";
+ // 用户发送新消息时自动清除 /btw overlay
+ if (this.btwOverlay !== null) {
+ this.btwOverlay = null;
+ this._btwActive = false;
+ }
}
this.emitChange();
};
+ /** 设置 /btw 侧问题覆盖层(独立于 transcript 渲染,不受滚动影响) */
+ readonly setBtwOverlay = (question: string, answer: string): void => {
+ this.btwOverlay = { question, answer };
+ this.emitChange();
+ };
+
+ /** 设置 BTW 活动状态(加载中或 overlay 可见),用于 Esc 优先级判断 */
+ readonly setBtwActive = (active: boolean): void => {
+ if (this._btwActive !== active) {
+ this._btwActive = active;
+ this.emitChange();
+ }
+ };
+
+ /** 清除 /btw 侧问题覆盖层 */
+ readonly clearBtwOverlay = (): void => {
+ if (this.btwOverlay !== null) {
+ this.btwOverlay = null;
+ this._btwActive = false;
+ this.emitChange();
+ }
+ };
+
readonly isHelpVisible = (): boolean => {
if (this.entries.length === 0) return false;
const lastEntry = this.entries[this.entries.length - 1];
@@ -1299,6 +1346,8 @@ export class CliPiAppState {
this.entries = [];
this.pendingQuestion = null;
this.lastError = null;
+ this.btwOverlay = null;
+ this._btwActive = false;
this.setStreamingStateInternal(StreamingState.Idle);
this.collapsedToolGroupIds.clear();
this.activeSubtasks.clear();
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts
index 3af9c417d4..e223ebcd1c 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/btw.ts
@@ -3,6 +3,10 @@
* the main conversation. The backend spawns an isolated, tool-free,
* single-turn LLM query against the current conversation context
* and returns just the answer.
+ *
+ * UI 隔离:btw 回答渲染在固定的 overlay 区域(transcript 之外),
+ * 不会混入主对话的流式输出,也不受 transcript 滚动影响。
+ * 等待响应期间可按 Esc 取消请求。
*/
import { addError, addInfo } from "../helpers.js";
import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";
@@ -16,6 +20,7 @@ interface BtwResponse {
const NO_CONTEXT_MSG = "No conversation context available yet — send a message first.";
const FAILED_MSG = "Couldn't answer the side question. Please try again or ask in the main conversation.";
const EMPTY_QUESTION_MSG = "Usage: /btw <your question>";
+const CANCELLED_MSG = "Side question cancelled.";
export function createBtwCommand(): SlashCommand {
return {
@@ -32,18 +37,23 @@ export function createBtwCommand(): SlashCommand {
return;
}
- // Dim indicator while the side query is running
+ // 标记 BTW 活动状态,确保 Esc 优先消费(不干扰主会话)
+ ctx.setBtwActive?.(true);
+
+ // Dim indicator while the side query is running — placed in transcript
const thinkingId = `btw-thinking-${Date.now()}`;
ctx.addItem({
kind: "info",
id: thinkingId,
sessionId: ctx.sessionId,
- content: `Answering: ${question}`,
+ content: `Answering: ${question} (Esc to cancel)`,
icon: "💭",
at: new Date().toISOString(),
meta: { view: "dim" as const },
});
+ let overlayShown = false;
+
try {
const payload = await ctx.request<BtwResponse>(
"command.btw",
@@ -51,12 +61,20 @@ export function createBtwCommand(): SlashCommand {
120000,
);
+ // Check if cancelled mid-request (Esc pressed during wait)
+ if (ctx.isInterruptRequested?.()) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, CANCELLED_MSG, "i", { view: "dim" as const }),
+ );
+ return;
+ }
+
switch (payload.status) {
case "ok":
if (payload.answer) {
- ctx.addItem(
- addInfo(ctx.sessionId, `💡 /btw ${question}\n\n${payload.answer}`),
- );
+ // 使用 overlay 渲染 btw 回答(固定在屏幕底部,独立于 transcript)
+ ctx.setBtwOverlay?.(question, payload.answer);
+ overlayShown = true;
} else {
ctx.addItem(addInfo(ctx.sessionId, "(empty answer)", "💡"));
}
@@ -71,8 +89,21 @@ export function createBtwCommand(): SlashCommand {
ctx.addItem(addError(ctx.sessionId, FAILED_MSG));
}
} catch (error) {
+ // Cancelled by Esc → the WS request was aborted; show dim notice
+ if (ctx.isInterruptRequested?.()) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, CANCELLED_MSG, "i", { view: "dim" as const }),
+ );
+ return;
+ }
const message = error instanceof Error ? error.message : String(error);
ctx.addItem(addError(ctx.sessionId, `btw failed: ${message}`));
+ } finally {
+ // 只有在 overlay 未显示时才清除活动状态
+ // overlay 显示时保持 btwActive = true,由 Esc 处理清除
+ if (!overlayShown) {
+ ctx.setBtwActive?.(false);
+ }
}
},
};
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
index 8214dc5008..54ac8bbbe1 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts
@@ -52,6 +52,12 @@ export interface CommandContext {
accentColor: AccentColorName;
updateSession: (id: string) => void;
addItem: (item: HistoryItem) => void;
+ /** 设置 /btw 侧问题覆盖层(独立于 transcript 渲染,不受滚动影响) */
+ setBtwOverlay?: (question: string, answer: string) => void;
+ /** 清除 /btw 侧问题覆盖层 */
+ clearBtwOverlay?: () => void;
+ /** 设置 BTW 活动状态(加载中或 overlay 可见),用于 Esc 优先级判断 */
+ setBtwActive?: (active: boolean) => void;
clearEntries: () => void;
restoreHistory: (sessionId: string) => Promise<void>;
exitApp: () => void;
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index b2450570f8..6a9e5db032 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -1800,6 +1800,20 @@ export class AppScreen implements Component, Focusable {
const isCancelWorkKey = !hasOverlay && resolveAction("Global", data) === "app:cancelWork";
+ // BTW 浮层优先消费 Esc(不干扰主会话)
+ // 只要 btw 浮层弹窗存在(可见、加载中、正在输出),按一次 Esc 只关闭/终止 btw 旁路
+ if (!pendingQuestion && isCancelWorkKey && snapshot.btwActive) {
+ // 关闭 BTW overlay(如果可见)
+ if (snapshot.btwOverlay) {
+ this.state.clearBtwOverlay();
+ }
+ // 取消正在进行的 BTW WS 请求(加载中状态),不影响主会话
+ this.state.requestLocalInterrupt();
+ this.state.setBtwActive(false);
+ this.tui.requestRender();
+ return;
+ }
+
if (!pendingQuestion && snapshot.cancellableWork && isCancelWorkKey) {
if (isTeamMode(snapshot.mode)) {
this.state.pause();
@@ -1824,6 +1838,15 @@ export class AppScreen implements Component, Focusable {
return;
}
+ // ESC 关闭 /btw overlay(独立于 transcript 的覆盖层)
+ if (!pendingQuestion && !hasOverlay && !snapshot.cancellableWork && isCancelWorkKey) {
+ if (snapshot.btwOverlay) {
+ this.state.clearBtwOverlay();
+ this.tui.requestRender();
+ return;
+ }
+ }
+
// ESC 关闭 help 视图(只读,无输入栏)
if (!pendingQuestion && !hasOverlay && !snapshot.cancellableWork && isCancelWorkKey) {
if (this.state.dismissHelp()) {
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
index 4f0881e0c9..183fbaff26 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
@@ -203,6 +203,35 @@ function buildStatusLineBar(snapshot: AppSnapshot, width: number): string[] {
});
}
+function renderBtwOverlay(
+ overlay: { question: string; answer: string },
+ width: number,
+): string[] {
+ const lines: string[] = [];
+ const safeWidth = Math.max(1, width);
+ // 确保与其他固定区块有视觉分隔
+ lines.push(" ".repeat(safeWidth));
+
+ // 标题行: 💡 /btw <question>
+ const headerText = `💡 /btw ${overlay.question}`;
+ lines.push(padToWidth(palette.text.accent(headerText), safeWidth));
+
+ // 分隔线
+ lines.push(padToWidth(palette.text.dim("─".repeat(Math.min(safeWidth, 80))), safeWidth));
+
+ // 回答内容:完整展示,不折叠(btw 本身是单轮简短回答,不会过长)
+ const answerLines = overlay.answer.split("\n");
+ for (const line of answerLines) {
+ lines.push(padToWidth(palette.text.secondary(line), safeWidth));
+ }
+
+ // 提示行: Esc to dismiss
+ lines.push(padToWidth(palette.text.dim("Esc to dismiss"), safeWidth));
+ lines.push(" ".repeat(safeWidth));
+
+ return lines;
+}
+
function buildShortcutLines(width: number): string[] {
const lines = [
padToWidth(palette.text.secondary("Shortcuts"), width),
@@ -281,6 +310,9 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout
options.width,
)
: [];
+ const btwOverlayLines =
+ snapshot.btwOverlay ? renderBtwOverlay(snapshot.btwOverlay, options.width) : [];
+
const fixedLines = [
...todoLines,
...(todoLines.length > 0 &&
@@ -291,6 +323,7 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout
...miniTeamTreeLines,
...teamPanelLines,
...options.questionLines,
+ ...btwOverlayLines,
...options.editorLines,
...options.composerPreviewLines,
...statusLineBarLines,
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 4199235aaf..4ab456631e 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -6732,10 +6732,14 @@ class JiuWenSwarmDeepAdapter:
def _get_recent_messages(self, session_id: str, window: int = 30) -> list[Any]:
"""从当前 agent 对话上下文中提取最近N条消息。
- 当 context_engine 中没有该 session 的上下文时(例如 /resume 之后),
- 回退到从磁盘读取兼容格式的 history 文件。
+ 查找顺序:
+ 1. 当前 adapter 的 context_engine(session-scoped adapter 自身或已加载的 parent)
+ 2. 父 adapter 查找 session-scoped child adapter 的 context_engine
+ (解决 /btw 等侧查询在 parent adapter 上执行时,会话上下文在 child adapter
+ 中而 parent 的 context_engine 未加载该 session 的问题)
+ 3. 回退到从磁盘读取兼容格式的 history 文件
"""
- # --- 快速路径:context_engine 已加载 ---
+ # --- 快速路径:当前 adapter 的 context_engine 已加载 ---
if self._instance is not None and self._instance.react_agent is not None:
context_engine = self._instance.react_agent.context_engine
context = context_engine.get_context(session_id=session_id)
@@ -6747,6 +6751,36 @@ class JiuWenSwarmDeepAdapter:
except Exception as exc:
logger.debug("[JiuWenSwarmDeepAdapter] _get_recent_messages from context_engine failed: %s", exc)
+ # --- 中间路径:从 session-scoped child adapter 的 context_engine 查找 ---
+ # 当 /btw 等侧查询在 parent adapter 上执行时,会话上下文实际在
+ # session-scoped child adapter 的内存中(context_engine),而非磁盘。
+ # 直接从内存读取可避免与异步写队列的"写后读"竞态。
+ if not getattr(self, "_is_session_scoped_adapter", False):
+ session_adapter = self._get_cached_session_adapter(session_id)
+ if session_adapter is not None:
+ inst = getattr(session_adapter, "_instance", None)
+ if inst is not None and getattr(inst, "react_agent", None) is not None:
+ ctx_eng = inst.react_agent.context_engine
+ ctx = ctx_eng.get_context(session_id=session_id)
+ if ctx is not None:
+ try:
+ all_msgs = list(ctx.get_messages() or [])
+ if all_msgs:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] _get_recent_messages: "
+ "read %d messages from session-scoped adapter context_engine "
+ "for session %s",
+ len(all_msgs),
+ session_id,
+ )
+ return all_msgs[-window:]
+ except Exception as exc:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] _get_recent_messages "
+ "from session-scoped adapter context_engine failed: %s",
+ exc,
+ )
+
# --- 回退路径:从磁盘读取兼容格式 history ---
# 典型场景:/resume 之后,context_engine 还未加载新 session 的上下文,
# 但磁盘上已有该 session 的历史消息。