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: 分支合一--回合四模块企业版能力到 dev-stable
jiangchenglin50d59b36ff46
diff --git a/deploy/enterprise/runtime_handler.sh b/deploy/enterprise/runtime_handler.shindex 89b3d7a9a5..5a9cd7e1d1 100755--- a/deploy/enterprise/runtime_handler.sh+++ b/deploy/enterprise/runtime_handler.sh@@ -5,6 +5,23 @@ gen_runtime_file() {local template_file="${CONFIG["RUNTIME_TEMPLATE_FILE"]}"local file="${CONFIG["RUNTIME_FILE"]}"+ # 按 REDIS_MODE 计算 AgentServer checkpointer 的 Redis URL+ # cluster:redis+cluster://host:port(cluster 只有 db 0,不能带库号)+ # standalone:redis://host:port/db+ local redis_mode="${DEPLOY_VARS["REDIS_MODE"]:-standalone}"+ local redis_host="${DEPLOY_VARS["REDIS_HOST"]:-}"+ local redis_port="${DEPLOY_VARS["REDIS_PORT"]:-}"+ local redis_db="${DEPLOY_VARS["AGENT_RUNTIME_REDIS_DB"]:-0}"+ # 校验非空:host/port 缺失时不能拼出残缺的 Redis URL(如 redis://:6379/0),+ # 否则 AgentServer checkpointer 会因连接串非法而启动失败。此时跳过赋值并告警。+ if [[ -z "${redis_host}" || -z "${redis_port}" ]]; then+ warning "REDIS_HOST 或 REDIS_PORT 为空,跳过 OPENJIUWEN_SERVICE_REDIS_URL 赋值(AgentServer checkpointer Redis 连接串未设置)"+ elif [[ "${redis_mode}" == "cluster" ]]; then+ DEPLOY_VARS["OPENJIUWEN_SERVICE_REDIS_URL"]="redis+cluster://${redis_host}:${redis_port}"+ else+ DEPLOY_VARS["OPENJIUWEN_SERVICE_REDIS_URL"]="redis://${redis_host}:${redis_port}/${redis_db}"+ fi+render_config_template "${template_file}" "${file}" "DEPLOY_VARS"enable_dev_mode_if_needed ${file} runtimediff --git a/deploy/enterprise/templates/runtime.template.yaml b/deploy/enterprise/templates/runtime.template.yamlindex fb873bde45..31a121c46a 100644--- a/deploy/enterprise/templates/runtime.template.yaml+++ b/deploy/enterprise/templates/runtime.template.yaml@@ -108,7 +108,9 @@ spec:- name: OPENJIUWEN_SERVICE_PORTvalue: "<<AGENT_RUNTIME_PORT>>"- name: OPENJIUWEN_SERVICE_REDIS_URL- value: "redis://<<REDIS_HOST>>:<<REDIS_PORT>>/<<AGENT_RUNTIME_REDIS_DB>>"+ # AgentServer checkpointer 用此 URL 连接 Redis(与 gateway 的 redis client 独立)+ # 由 runtime_handler.sh 按 REDIS_MODE 计算:cluster -> redis+cluster://host:port / standalone -> redis://host:port/db+ value: "<<OPENJIUWEN_SERVICE_REDIS_URL>>"- name: OPENJIUWEN_SERVICE_REQUEST_TIMEOUT_SECONDSvalue: "<<AGENT_RUNTIME_REQUEST_TIMEOUT>>"- name: OPENJIUWEN_SERVICE_DB_TYPEdiff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.pyindex 274d9dcc75..b720d15cb5 100644--- a/jiuwenswarm/channels/web/app_web.py+++ b/jiuwenswarm/channels/web/app_web.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport argparseimport errnoimport http.client+import ioimport jsonimport loggingimport mimetypes@@ -631,6 +632,9 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):).encode("utf-8")self.send_response(200)self.send_header("Content-Type", "text/html; charset=utf-8")+ # 运行时配置已逐请求注入 index.html,必须禁止缓存,+ # 否则浏览器会复用含过期/跨用户配置的旧响应。+ self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")self.send_header("Content-Length", str(len(body)))self.end_headers()self.wfile.write(body)@@ -684,7 +688,9 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):def _is_document_request(self) -> bool:path = urlparse(self.path).path- return path in ("/", "/index.html") and "text/html" in self.headers.get("Accept", "")+ # Accept header may be absent (e.g. IAB initial navigation); serve+ # the runtime-config-injected index.html for root and index.html paths.+ return path in ("/", "/index.html")def send_head(self):parsed = urlparse(self.path)@@ -698,6 +704,44 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):if in_base and target.exists():return super().send_head()+ # Vite base:'./' produces relative asset URLs (./assets/...). When the+ # SPA route is a sub-path (e.g. /chat/new), the browser resolves these+ # to /chat/assets/... which don't exist under dist/. Strip leading path+ # segments and retry from the dist root before falling back to index.html.+ static_exts = (".js", ".css", ".svg", ".png", ".jpg", ".jpeg", ".ico",+ ".webp", ".gif", ".woff", ".woff2", ".ttf", ".eot",+ ".map", ".json", ".webmanifest")+ if req_path.endswith(static_exts) and "/" in rel_path:+ basename = rel_path.rsplit("/", 1)[-1]+ # Try progressively shorter prefixes (e.g. chat/assets/x.js ->+ # assets/x.js -> x.js).+ parts = rel_path.split("/")+ for i in range(1, len(parts)):+ candidate_rel = "/".join(parts[i:])+ candidate = (base_dir / candidate_rel).resolve()+ cand_in_base = os.path.commonpath(+ [str(base_dir), str(candidate)]+ ) == str(base_dir)+ if cand_in_base and candidate.exists():+ self.path = "/" + candidate_rel+ return super().send_head()++ # SPA fallback: serve index.html with runtime config injected.+ index_path = base_dir / "index.html"+ if index_path.exists():+ body = _inject_user_web_runtime_config(+ index_path.read_text(encoding="utf-8"), self.user_web_mode+ ).encode("utf-8")+ f = io.BytesIO(body)+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ # 运行时配置已逐请求注入 index.html,必须禁止缓存,+ # 否则浏览器会复用含过期/跨用户配置的旧响应。+ self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ return f+self.path = "/index.html"return super().send_head()diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 609ad9badd..322c192329 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -11,6 +11,7 @@ import { SkillPanel } from './components/SkillPanel';import { AgentPanel } from './components/AgentPanel/index';import { TeamPanel } from './components/TeamPanel';import { SessionsPanel } from './components/SessionsPanel';+import { HistoryPanel } from './components/HistoryPanel';import CronPanel from './components/CronPanel';import { ToolPanel } from './components/ToolPanel';import { ConfigPanel } from './components/ConfigPanel';@@ -102,7 +103,7 @@ function shouldPreviewModelSetupGuide(): boolean {return PREVIEW_MODEL_SETUP_GUIDE;}-type MainNavKey = 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';+type MainNavKey = 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'history' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';type LoadedHistoryPage = {pageIdx: number;@@ -2207,7 +2208,7 @@ function AppContent() {isConnected={isConnected}onNewSession={handleNewSession}showNewSession={false}- hiddenNavItems={enterpriseMode ? ['sessions', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions']}+ hiddenNavItems={enterpriseMode ? ['sessions', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions', 'history']}onMorePanelOpenChange={setSidebarMorePanelOpen}/>@@ -2344,9 +2345,18 @@ function AppContent() {isConnected={isConnected}isProcessing={isProcessing}onRestoreSession={handleRestoreSession}+ isRemoteSessionStorage={+ typeof serverConfig?.gateway_web_session_storage === 'string' &&+ serverConfig.gateway_web_session_storage.trim().toLowerCase() === 'remote'+ }/></div>)}+ {activeNav === 'history' && (+ <div className="app-section">+ <HistoryPanel />+ </div>+ )}{activeNav === 'cron' && (<div className="chat-layout flex-1 flex min-h-0 overflow-hidden"><ConversationSidebardiff --git a/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsxnew file mode 100644index 0000000000..ea6b6af233--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsx@@ -0,0 +1,159 @@+/**+ * HistoryPanel —— Web Pod 本地会话历史浏览(只读)。+ *+ * 列表态:GET /api/sessions,展示标题 / 预览 / 时间 / 消息数。+ * 详情态:GET /api/sessions/{id},复用 MessageItem 渲染完整对话。+ * 数据源为 Web Pod 落库的会话历史(企业版 ChatHistoryStore),独立于 WS(AgentServer)链路。+ */++import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ fetchSessionDetail,+ fetchSessions,+ type HistoryDetail,+ type HistoryMessage,+ type HistorySession,+} from '../../services/api';+import { getRuntimeScope } from '../../services/runtimeScope';+import type { Message } from '../../types';+import { formatRelativeTime } from '../../utils';+import { MessageItem } from '../ChatPanel/MessageItem';++function toMessage(msg: HistoryMessage, sessionId: string, index: number): Message {+ return {+ id: msg.request_id || `${sessionId}-${index}`,+ role: msg.role,+ content: msg.content,+ timestamp: new Date(msg.timestamp * 1000).toISOString(),+ };+}++const BTN =+ 'px-3 py-1.5 rounded-md border border-border text-sm text-text hover:bg-secondary transition-colors';++export function HistoryPanel() {+ const { t } = useTranslation();+ const [sessions, setSessions] = useState<HistorySession[]>([]);+ const [loadingList, setLoadingList] = useState(true);+ const [errorList, setErrorList] = useState<string | null>(null);++ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [detail, setDetail] = useState<HistoryDetail | null>(null);+ const [loadingDetail, setLoadingDetail] = useState(false);+ const [errorDetail, setErrorDetail] = useState<string | null>(null);++ const loadList = useCallback(async () => {+ setLoadingList(true);+ setErrorList(null);+ try {+ // 多用户隔离:显式传入当前 user_id,确保只返回当前用户的会话+ // (defense-in-depth;即使后端已按认证过滤也显式传递)。+ const userId = getRuntimeScope().userId;+ setSessions(await fetchSessions(50, 0, userId));+ } catch (e) {+ setErrorList(e instanceof Error ? e.message : String(e));+ } finally {+ setLoadingList(false);+ }+ }, []);++ useEffect(() => {+ void loadList();+ }, [loadList]);++ const openDetail = useCallback(+ async (id: string) => {+ setSelectedId(id);+ setDetail(null);+ setErrorDetail(null);+ setLoadingDetail(true);+ try {+ const d = await fetchSessionDetail(id, getRuntimeScope().userId);+ if (d === null) {+ setErrorDetail(t('history.notFound'));+ } else {+ setDetail(d);+ }+ } catch (e) {+ setErrorDetail(e instanceof Error ? e.message : String(e));+ } finally {+ setLoadingDetail(false);+ }+ },+ [t],+ );++ const closeDetail = useCallback(() => {+ setSelectedId(null);+ setDetail(null);+ setErrorDetail(null);+ }, []);++ // ---- 详情态 ----+ if (selectedId) {+ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center gap-3 p-3 border-b border-border">+ <button onClick={closeDetail} className={BTN}>+ {t('history.back')}+ </button>+ <div className="font-medium text-text truncate">{detail?.title || selectedId}</div>+ </div>+ <div className="flex-1 overflow-y-auto p-4">+ {loadingDetail && <div className="text-text-muted">{t('history.loading')}</div>}+ {errorDetail && <div className="text-danger">{errorDetail}</div>}+ {detail && detail.messages.length === 0 && (+ <div className="text-text-muted">{t('history.emptyMessages')}</div>+ )}+ {detail &&+ detail.messages.map((m, i) => (+ <MessageItem key={`${selectedId}-${i}`} message={toMessage(m, selectedId, i)} />+ ))}+ </div>+ </div>+ );+ }++ // ---- 列表态 ----+ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between p-3 border-b border-border">+ <div>+ <div className="text-lg font-semibold text-text">{t('history.title')}</div>+ <div className="text-xs text-text-muted">{t('history.subtitle')}</div>+ </div>+ <button onClick={loadList} className={BTN}>+ {t('history.refresh')}+ </button>+ </div>+ <div className="flex-1 overflow-y-auto p-3 space-y-2">+ {loadingList && <div className="text-text-muted">{t('history.loading')}</div>}+ {errorList && <div className="text-danger">{errorList}</div>}+ {!loadingList && !errorList && sessions.length === 0 && (+ <div className="text-text-muted">{t('history.empty')}</div>+ )}+ {sessions.map((s) => (+ <button+ key={s.session_id}+ onClick={() => openDetail(s.session_id)}+ className="w-full text-left rounded-lg border border-border bg-card/70 p-3 hover:border-[var(--color-border-accent)] hover:shadow-sm transition-colors"+ >+ <div className="flex items-center justify-between gap-2">+ <div className="font-medium text-text truncate">{s.title || s.session_id}</div>+ <div className="text-xs text-text-muted shrink-0">+ {formatRelativeTime(new Date(s.updated_at * 1000).toISOString())}+ </div>+ </div>+ {s.last_preview && (+ <div className="text-sm text-text-muted truncate mt-1">{s.last_preview}</div>+ )}+ <div className="text-xs text-text-muted mt-1">+ {t('history.messageCount', { count: s.message_count })}+ </div>+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsxindex 8fa381c889..0c9c8d30d9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx@@ -24,7 +24,7 @@ import { webRequest } from '../../services/webClient';import { useEnterpriseContext } from '../../services/enterpriseContext';type MainNavKey =- 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';+ 'chat' | 'skills' | 'agents' | 'teams' | 'sessions' | 'history' | 'cron' | 'channels' | 'extensions' | 'configpanel' | 'browserpanel' | 'updatepanel' | 'a2aingress';interface SessionSidebarProps {activeNav: MainNavKey;@@ -53,12 +53,23 @@ const teamNavIcon = (</svg>);+const historyNavIcon = (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M3 3v5h5M3.05 13A9 9 0 1 0 6 5.3L3 8"+ />+ </svg>+);+const mainNavItems: NavItem[] = [{ key: 'chat', labelKey: 'nav.work', icon: <WorkIcon aria-hidden /> },{ key: 'skills', labelKey: 'nav.skills', icon: <SkillDesignIcon aria-hidden /> },{ key: 'channels', labelKey: 'nav.channels', icon: <ChannelIcon aria-hidden /> },{ key: 'agents', labelKey: 'nav.agent', icon: <AgentDesignIcon aria-hidden /> },{ key: 'teams', labelKey: 'nav.teams', icon: teamNavIcon },+ { key: 'history', labelKey: 'nav.history', icon: historyNavIcon },];const moreNavItems: NavItem[] = [diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsxindex 5ae5753336..e4bb08cb7b 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx@@ -23,6 +23,8 @@ interface SessionsPanelProps {isConnected: boolean;isProcessing: boolean;onRestoreSession: (sessionId: string, mode?: string) => void | Promise<void>;+ /** remote 模式:会话文件在远程/Web Pod,不浏览网关本地文件 */+ isRemoteSessionStorage?: boolean;}interface SessionListResponse {@@ -262,6 +264,7 @@ export function SessionsPanel({isConnected,isProcessing,onRestoreSession,+ isRemoteSessionStorage = false,}: SessionsPanelProps) {const { t } = useTranslation();const [sessions, setSessions] = useState<SessionItem[]>([]);@@ -297,6 +300,12 @@ export function SessionsPanel({setSelectedFile(null);return;}+ if (isRemoteSessionStorage) {+ setFiles([]);+ setFilesError(null);+ setSelectedFile(null);+ return;+ }setLoadingFiles(true);setFilesError(null);if (!preserve) {@@ -381,7 +390,7 @@ export function SessionsPanel({setLoadingFiles(false);}},- [t]+ [isRemoteSessionStorage, t]);const loadSessions = useCallback(async () => {@@ -588,6 +597,10 @@ export function SessionsPanel({<div className="flex-1 overflow-auto p-2">{!selectedSessionId ? (<div className="h-full flex items-center justify-center text-sm text-text-muted">{t('sessions.selectFirst')}</div>+ ) : isRemoteSessionStorage ? (+ <div className="h-full flex items-center justify-center text-sm text-text-muted px-4 text-center">+ {t('sessions.remoteFilesUnavailable')}+ </div>) : loadingFiles ? (<div className="h-full flex items-center justify-center text-sm text-text-muted">{t('sessions.loadingFiles')}</div>) : filesError ? (diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 9ef8580d8f..4dcbcad539 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -78,6 +78,7 @@ type HistoryTimelineEntry =interface BeginHistoryRestoreOptions {sessionId: string;+ requestId?: string;onReady: (messages: Message[], totalPages: number | null) => void;/** 与消息同一时间线顺序,用于恢复 ToolGroupDisplay */onToolReplay?: (items: HistoryToolReplayItem[]) => void;@@ -947,17 +948,25 @@ function isHistoryBatchEnd(payload: Record<string, unknown>): boolean {/*** 仅处理属于当前 `history.get` 会话的帧,避免多标签/乱序下的串台。* 无 `session_id` 时:丢弃数据行;仍接受明确的结束帧(兼容未注入 id 的旧链路)。+ * 若提供了 `expectedRequestId`,则同时验证 `request_id` 是否匹配。*/function shouldProcessHistoryPayload(payload: Record<string, unknown>,expectedSessionId: string,expectedPageIdx?: number,- allowLegacyNoSession = false+ allowLegacyNoSession = false,+ expectedRequestId?: string): boolean {const sid = typeof payload.session_id === 'string' ? payload.session_id.trim() : '';if (sid && sid !== expectedSessionId) {return false;}+ if (expectedRequestId) {+ const rid = typeof payload.request_id === 'string' ? payload.request_id.trim() : '';+ if (rid && rid !== expectedRequestId) {+ return false;+ }+ }if (expectedPageIdx !== undefined && payload.page_idx !== expectedPageIdx) {return false;}@@ -983,8 +992,11 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historreturn;}- const payload = event.payload;- if (!shouldProcessHistoryPayload(payload, options.sessionId, undefined, activeHistoryRequests.size === 1)) {+ const payload = { ...event.payload };+ if (event.request_id) {+ payload.request_id = event.request_id;+ }+ if (!shouldProcessHistoryPayload(payload, options.sessionId, undefined, activeHistoryRequests.size === 1, options.requestId)) {return;}@@ -1067,6 +1079,7 @@ export interface FetchHistoryPageResult {export interface FetchHistoryPageOptions {sessionId: string;+ requestId?: string;pageIdx: number;onReady: (result: FetchHistoryPageResult) => void;onEmpty?: (totalPages: number | null) => void;@@ -1093,8 +1106,11 @@ export function fetchHistoryPage(options: FetchHistoryPageOptions): HistoryRestoreturn;}- const payload = event.payload;- if (!shouldProcessHistoryPayload(payload, options.sessionId, options.pageIdx, activeHistoryRequests.size === 1)) {+ const payload = { ...event.payload };+ if (event.request_id) {+ payload.request_id = event.request_id;+ }+ if (!shouldProcessHistoryPayload(payload, options.sessionId, options.pageIdx, activeHistoryRequests.size === 1, options.requestId)) {return;}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/requestEventFilter.ts b/jiuwenswarm/channels/web/frontend/src/hooks/requestEventFilter.tsnew file mode 100644index 0000000000..457a2f780d--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/hooks/requestEventFilter.ts@@ -0,0 +1,41 @@+import type { WsEvent } from '../types';++export interface ShouldHandleRequestEventOptions {+ activeRequestId?: string | null;+ expectedRequestId?: string;+ /** 当前连接发出的 `chat.interrupt` 请求的 ws id(与 chat.send 链路的 id 不属于同一枚举) */+ pendingInterruptRequestIds?: ReadonlySet<string>;+}++/**+ * 决定一条流式事件是否属于当前 tab 的活跃请求。+ *+ * - 无 request_id 的事件一律放行(后端不给 chat.delta/final 注入 request_id)。+ * - interrupt_result 只认本 tab 发出的 interrupt 请求 id,其余一律拒绝。+ * - 其余带 request_id 的事件,必须匹配 activeRequestId(或 expectedRequestId)才放行。+ */+export function shouldHandleRequestEvent(+ event: WsEvent,+ options: ShouldHandleRequestEventOptions = {}+): boolean {+ const eventIdRaw = event.request_id;+ const rid = typeof eventIdRaw === 'string' ? eventIdRaw.trim() : '';+ if (!rid) {+ return true;+ }+ const pending = options.pendingInterruptRequestIds;+ if (pending?.has(rid)) {+ return true;+ }+ if (event.event === 'chat.interrupt_result') {+ return false;+ }+ const expected =+ options.expectedRequestId ??+ options.activeRequestId ??+ null;+ if (!expected) {+ return true;+ }+ return rid === expected;+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 7fdbb5cd55..5579ac8e9b 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -47,6 +47,7 @@ import { normalizeTaskEvent } from '../stores/teamTaskNormalize';import { webClient, requestGoalAction, sendGoalStreamCommand } from '../services/webClient';import { getWebTransport } from '../utils/env';import { createStreamDeltaBatcher } from '../services/streamDeltaBatcher';+import { shouldHandleRequestEvent } from './requestEventFilter';import {fetchTtsAudio,playAudioBase64,@@ -99,6 +100,14 @@ function isCompletedResumeResult(interruptResult: unknown): boolean {return result.intent === 'resume' && result.success === true && result.has_active_task === false;}+function makeClientRequestId(prefix: string): string {+ return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;+}++function isActiveStreamRequestId(requestId: string): boolean {+ return requestId.startsWith('req_') || requestId.startsWith('chat-');+}+const GOAL_COMPLETED_AUTO_HIDE_MS = 4000;const GOAL_COMPLETED_SETTLE_FALLBACK_MS = 8000;/** get 失败后的重试间隔(毫秒):首次失败后再试 2 次,都失败才判定为 unknown(真实环境联调方案)。 */@@ -796,6 +805,17 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// 必须在渲染阶段同步更新,否则 effect 执行之前收到的事件会被错误过滤const userInputVersionRef = useRef(0);const activeRequestIdRef = useRef<string | undefined>(undefined);+ /** 本会话实例发出的 interrupt 请求的 ws req id(用于识别属于本 tab 的 interrupt_result) */+ const pendingInterruptRequestIdsRef = useRef<Set<string>>(new Set());+ /** 已 cancel 的 chat.send request_id,用于丢弃取消后仍滞留在网关队列中的流式事件 */+ const suppressedChatRequestIdsRef = useRef<Set<string>>(new Set());+ /** 用户点击暂停后立即生效,暂停期间收到的流式事件写入暂存区 */+ const pauseHoldActiveRef = useRef(false);+ /** 被暂停的那条 chat.send 的 request_id,仅暂存与之匹配的事件 */+ const pausedStreamRequestIdRef = useRef<string | null>(null);+ const pausedEventsRef = useRef<WsEvent[]>([]);+ /** supplement 后待认领的新流 request_id(后端形如 req_{hex}_{interruptId}) */+ const pendingSupplementInterruptIdRef = useRef<string | null>(null);// 立即同步更新,不等待 effectconst [isConnected, setIsConnected] = useState(false);@@ -871,6 +891,83 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {streamDeltaBatcherRef.current?.flush(streamDeltaBatchKey(sessionId, streamId));}, []);+ // ── pause buffer 生命周期(回合自 enterprise_kub)──────────────────────────+ const clearPauseBuffer = useCallback(() => {+ pauseHoldActiveRef.current = false;+ pausedStreamRequestIdRef.current = null;+ pausedEventsRef.current = [];+ }, []);++ const tryAdoptSupplementStreamRequestId = useCallback((eventRequestId: string): boolean => {+ const pendingInterruptId = pendingSupplementInterruptIdRef.current;+ if (!pendingInterruptId || !eventRequestId) return false;+ if (!eventRequestId.includes(pendingInterruptId)) return false;+ // 仅认领 supplement 流式 chat.send(req_ 前缀);忽略 interrupt_result 附带的 interrupt id+ if (!eventRequestId.startsWith('req_')) return false;+ activeRequestIdRef.current = eventRequestId;+ pendingSupplementInterruptIdRef.current = null;+ if (pauseHoldActiveRef.current) {+ pausedStreamRequestIdRef.current = eventRequestId;+ }+ return true;+ }, []);++ const bindStreamRequestIdFromEvent = useCallback((eventRequestId: string) => {+ if (!isActiveStreamRequestId(eventRequestId)) return;+ const current = activeRequestIdRef.current?.trim() ?? '';+ if (!current || current.startsWith('interrupt-')) {+ activeRequestIdRef.current = eventRequestId;+ }+ }, []);++ const shouldHandleCurrentRequestEvent = useCallback((event: WsEvent): boolean => {+ return shouldHandleRequestEvent(event, {+ activeRequestId: activeRequestIdRef.current,+ pendingInterruptRequestIds: pendingInterruptRequestIdsRef.current,+ });+ }, []);++ const enterPauseHold = useCallback((sessionId: string) => {+ pauseHoldActiveRef.current = true;+ const activeRid = activeRequestIdRef.current?.trim() ?? '';+ pausedStreamRequestIdRef.current =+ activeRid && isActiveStreamRequestId(activeRid) ? activeRid : null;+ useChatStore.getState().setPaused(sessionId, true);+ useChatStore.getState().setProcessing(sessionId, false);+ useChatStore.getState().setThinking(sessionId, false);+ stopAllTts();+ const currentStreamId = useChatStore.getState().getRuntime(sessionId)?.currentStreamId;+ if (currentStreamId) {+ useChatStore.getState().updateMessage(sessionId, currentStreamId, { isStreaming: false });+ }+ }, []);++ const exitPauseHoldForNewTurn = useCallback(+ (sessionId: string, options?: { interruptRequestId?: string; suppressPausedStream?: boolean }) => {+ const pausedRid = pausedStreamRequestIdRef.current ?? activeRequestIdRef.current;+ if (options?.suppressPausedStream !== false && pausedRid) {+ suppressedChatRequestIdsRef.current.add(pausedRid);+ }+ clearPauseBuffer();+ useChatStore.getState().setPaused(sessionId, false);+ useChatStore.getState().stopStreaming(sessionId);+ activeRequestIdRef.current = undefined;+ if (options?.interruptRequestId) {+ pendingSupplementInterruptIdRef.current = options.interruptRequestId;+ }+ },+ [clearPauseBuffer]+ );++ const flushPausedEvents = useCallback(() => {+ pauseHoldActiveRef.current = false;+ const events = pausedEventsRef.current.splice(0);+ for (const event of events) {+ webClient.replayBufferedEvent(event);+ }+ }, []);+ // ──────────────────────────────────────────────────────────────────────────+const handleTtsPlayback = useCallback((sessionId: string, messageId: string, content: string) => {const sanitized = sanitizeTtsText(content);@@ -1457,6 +1554,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// Goal 处于 active 时,普通输入按文档 §5.1 作为补充约束插入当前 Goal,而不是覆盖它const activeGoal = useGoalStore.getState().getRuntime(sessionId)?.goal;const inputMode = activeGoal?.status === 'active' ? 'steer' : undefined;+ const chatRequestId = makeClientRequestId('chat');+ activeRequestIdRef.current = chatRequestId;await request('chat.send', {session_id: sessionId,content: outgoingContent,@@ -1467,7 +1566,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {...workContext,skills: selectedSkills,...(inputMode ? { input_mode: inputMode } : {}),- });+ }, { requestId: chatRequestId });return true;} catch (error) {const webError = error as WebError;@@ -1523,13 +1622,15 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().setPaused(sessionId, false);}try {+ const chatRequestId = makeClientRequestId('chat');+ activeRequestIdRef.current = chatRequestId;await request('chat.send', {session_id: sessionId,content,mode: currentMode,...(selectedModel ? { model_name: selectedModel } : {}),...workContext,- });+ }, { requestId: chatRequestId });} catch (error) {const webError = error as WebError;setConnectionStats({ lastError: webError.message });@@ -1596,6 +1697,30 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {timestamp: new Date().toISOString(),});}++ // 乐观本地状态变更(回合自 enterprise_kub)——先改 UI,不等后端确认+ const interruptRequestId = makeClientRequestId('interrupt');+ pendingInterruptRequestIdsRef.current.add(interruptRequestId);+ if (intent === 'pause') {+ enterPauseHold(sessionId);+ } else if (intent === 'cancel') {+ const activeRid = activeRequestIdRef.current;+ if (activeRid) {+ suppressedChatRequestIdsRef.current.add(activeRid);+ }+ clearPauseBuffer();+ pendingSupplementInterruptIdRef.current = null;+ useChatStore.getState().setProcessing(sessionId, false);+ useChatStore.getState().setThinking(sessionId, false);+ useChatStore.getState().stopStreaming(sessionId);+ activeRequestIdRef.current = undefined;+ useChatStore.getState().setPaused(sessionId, false);+ } else if (intent === 'supplement') {+ exitPauseHoldForNewTurn(sessionId, { interruptRequestId });+ useChatStore.getState().setProcessing(sessionId, true);+ useChatStore.getState().setThinking(sessionId, true);+ }+try {const params: Record<string, unknown> = {session_id: sessionId,@@ -1614,15 +1739,36 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const selectedModel = useSessionStore.getState().getEffectiveModelName(sessionId);if (selectedModel) params.model_name = selectedModel;}- await request('chat.interrupt', params);+ await request('chat.interrupt', params, { requestId: interruptRequestId });} catch (error) {const webError = error as WebError;+ // 回滚乐观变更+ pendingInterruptRequestIdsRef.current.delete(interruptRequestId);+ if (intent === 'pause') {+ clearPauseBuffer();+ useChatStore.getState().setPaused(sessionId, false);+ // enterPauseHold 设了 processing/thinking=false 并停止 streaming,+ // pause 失败说明后端仍在处理,恢复执行态让 UI 与后端一致+ useChatStore.getState().setProcessing(sessionId, true);+ useChatStore.getState().setThinking(sessionId, true);+ const currentStreamId = useChatStore.getState().getRuntime(sessionId)?.currentStreamId;+ if (currentStreamId) {+ useChatStore.getState().updateMessage(sessionId, currentStreamId, { isStreaming: true });+ }+ } else if (intent === 'supplement') {+ pendingSupplementInterruptIdRef.current = null;+ useChatStore.getState().setProcessing(sessionId, false);+ useChatStore.getState().setThinking(sessionId, false);+ }setConnectionStats({ lastError: webError.message });onErrorRef.current?.(webError.message || t('network.interruptFailed'));}},[+ clearPauseBuffer,closeActiveTeamLeaderMessages,+ enterPauseHold,+ exitPauseHoldForNewTurn,request,resetContextCompressionTurn,setConnectionStats,@@ -1868,6 +2014,27 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {onConfigChangedRef.current = onConfigChanged;}, [onConfigChanged, onConnect, onDisconnect, onError]);+ // pause buffer + stream event filter 接入传输层(回合自 enterprise_kub)+ useEffect(() => {+ webClient.setStreamEventFilter((event) => {+ const rid = typeof event.request_id === 'string' ? event.request_id.trim() : '';+ if (!rid) return true;+ const name = event.event;+ if (!name.startsWith('chat.') && !name.startsWith('context.')) return true;+ return !suppressedChatRequestIdsRef.current.has(rid);+ });+ webClient.setPauseBufferHook({+ isActive: () => pauseHoldActiveRef.current,+ onBuffer: (event) => {+ pausedEventsRef.current.push(event);+ },+ });+ return () => {+ webClient.setStreamEventFilter(null);+ webClient.setPauseBufferHook(null);+ };+ }, []);+const shouldDropDuplicatedEvent = useCallback((eventName: string, payload: Record<string, unknown>): boolean => {const now = Date.now();@@ -2057,10 +2224,19 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('hello', ({ payload }) => {handleConnectionAck(payload);}),- webClient.on('chat.delta', ({ payload }) => {+ webClient.on('chat.delta', (event) => {+ if (pauseHoldActiveRef.current) return;+ const payload = event.payload;const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ // supplement 流认领:后端 supplement 后新 chat.send 的 request_id 含 interrupt id+ const eventRid = typeof event.request_id === 'string' ? event.request_id.trim() : '';+ if (eventRid) {+ tryAdoptSupplementStreamRequestId(eventRid);+ bindStreamRequestIdFromEvent(eventRid);+ }+// 页面刷新后,如果收到活跃事件但 isProcessing=false,自动恢复执行状态if (!useChatStore.getState().getRuntime(sessionId)?.isProcessing && !useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory) {useChatStore.getState().setProcessing(sessionId, true);@@ -2761,6 +2937,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('chat.tool_call', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ if (pauseHoldActiveRef.current) return;if (shouldDropDuplicatedEvent('chat.tool_call', payload)) return;// 页面刷新后,如果收到活跃事件但 isProcessing=false,自动恢复执行状态if (!useChatStore.getState().getRuntime(sessionId)?.isProcessing && !useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory) {@@ -2832,6 +3009,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('chat.tool_result', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ if (pauseHoldActiveRef.current) return;if (shouldDropDuplicatedEvent('chat.tool_result', payload)) return;const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;const toolResult = normalizeToolResultPayload(payload);@@ -2980,9 +3158,15 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useSessionStore.getState().setMode(sessionId, normalizeAgentMode(payload.mode));}}),- webClient.on('chat.processing_status', ({ payload }) => {+ webClient.on('chat.processing_status', (event) => {+ const payload = event.payload;const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ // supplement 流认领:后端 supplement 后新 chat.send 的 request_id 含 interrupt id+ const eventRid = typeof event.request_id === 'string' ? event.request_id.trim() : '';+ if (eventRid) {+ tryAdoptSupplementStreamRequestId(eventRid);+ }if (shouldDropDuplicatedEvent('chat.processing_status', payload)) return;// 切换模式时忽略处理状态更新if (useChatStore.getState().getRuntime(sessionId)?.switchingMode) return;@@ -3236,9 +3420,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const retractRequestId = typeof event.payload.request_id === 'string' ? event.payload.request_id : undefined;useChatStore.getState().clearCurrentTurnData(sessionId, retractRequestId);}),- webClient.on('chat.interrupt_result', ({ payload }) => {+ webClient.on('chat.interrupt_result', (event) => {+ const payload = event.payload;const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ if (!shouldHandleCurrentRequestEvent(event)) return;if (shouldDropDuplicatedEvent('chat.interrupt_result', payload)) return;// 切换模式时忽略中断结果if (useChatStore.getState().getRuntime(sessionId)?.switchingMode) return;@@ -3250,22 +3436,45 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (resultPayload.intent === 'pause') {if (resultPayload.success) {+ pauseHoldActiveRef.current = true;+ const activeRid = activeRequestIdRef.current?.trim() ?? '';+ if (!pausedStreamRequestIdRef.current) {+ pausedStreamRequestIdRef.current =+ activeRid && isActiveStreamRequestId(activeRid) ? activeRid : null;+ }useChatStore.getState().setPaused(sessionId, true, resultPayload.paused_task);+ useChatStore.getState().markInterruptedExecutions(sessionId);+ useChatStore.getState().setProcessing(sessionId, false);+ useChatStore.getState().setThinking(sessionId, false);+ // 集群模式下输入框的"停止"按钮走的是 pause(不是 cancel,见 App.tsx+ // handleCancel:mode==='team' 时调用 pause)。team-leader 消息的+ // isStreaming 不经过 currentStreamId 收尾,这里同 cancel 分支一样显式+ // 关闭还在 streaming 的 team-leader 消息,避免光标永久闪烁(bug001)。+ closeActiveTeamLeaderMessages(sessionId);+ } else {+ clearPauseBuffer();+ useChatStore.getState().setPaused(sessionId, false);+ // pause 失败说明后端仍在处理,恢复执行态让 UI 与后端一致+ // (与 handleInterrupt catch 块的网络错误回滚逻辑一致)+ useChatStore.getState().setProcessing(sessionId, true);+ useChatStore.getState().setThinking(sessionId, true);+ const currentStreamId = useChatStore.getState().getRuntime(sessionId)?.currentStreamId;+ if (currentStreamId) {+ useChatStore.getState().updateMessage(sessionId, currentStreamId, { isStreaming: true });+ }}- useChatStore.getState().setProcessing(sessionId, false);- useChatStore.getState().setThinking(sessionId, false);- // 集群模式下输入框的"停止"按钮走的是 pause(不是 cancel,见 App.tsx- // handleCancel:mode==='team' 时调用 pause)。team-leader 消息的- // isStreaming 不经过 currentStreamId 收尾,这里同 cancel 分支一样显式- // 关闭还在 streaming 的 team-leader 消息,避免光标永久闪烁(bug001)。- closeActiveTeamLeaderMessages(sessionId);+ // 保留 activeRequestIdRef,恢复后 stream 事件仍能对齐原 chat.send} else if (resultPayload.intent === 'resume') {if (resultPayload.success) {- // 直接设置所有状态值if (hasActiveTask) {useChatStore.getState().setPaused(sessionId, false);useChatStore.getState().setProcessing(sessionId, true);useChatStore.getState().setThinking(sessionId, true);+ flushPausedEvents();+ const currentStreamId = useChatStore.getState().getRuntime(sessionId)?.currentStreamId;+ if (currentStreamId) {+ useChatStore.getState().updateMessage(sessionId, currentStreamId, { isStreaming: true });+ }} else {useChatStore.getState().setPaused(sessionId, false);useChatStore.getState().setProcessing(sessionId, false);@@ -3285,9 +3494,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {}}} else if (resultPayload.intent === 'cancel') {+ clearPauseBuffer();useChatStore.getState().setPaused(sessionId, false);useChatStore.getState().setProcessing(sessionId, false);useChatStore.getState().setThinking(sessionId, false);+ useChatStore.getState().markInterruptedExecutions(sessionId);// chat.interrupt_result 是一元响应,跟流式分片的 goal_intermediate 判断走的是完全// 独立的通道——不依赖后端把"目标已清除/暂停后这一轮该不该被当成中间态"判断对,// 用户主动点了停止/删除就该让当前气泡收尾,不再等一个可能被误判、永远不会来的@@ -3297,10 +3508,35 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// stopStreaming 对它无效;取消后本该到来的 chat.final 也不会再来兜底,// 这里显式收尾,避免 team-leader 气泡的光标永久闪烁(bug001)。closeActiveTeamLeaderMessages(sessionId);+ activeRequestIdRef.current = undefined;} else if (resultPayload.intent === 'supplement') {- useChatStore.getState().setPaused(sessionId, false);+ if (resultPayload.success) {+ clearPauseBuffer();+ useChatStore.getState().setPaused(sessionId, false);+ useChatStore.getState().setProcessing(sessionId, true);+ useChatStore.getState().setThinking(sessionId, true);+ } else {+ pendingSupplementInterruptIdRef.current = null;+ // supplement 失败:exitPauseHoldForNewTurn 已把 processing/thinking 置 true,+ // 后端未接受补充输入,恢复为未处理态(与 handleInterrupt catch 块一致)+ useChatStore.getState().setProcessing(sessionId, false);+ useChatStore.getState().setThinking(sessionId, false);+ }+ }+ // 清理本 tab 发出的 interrupt 请求 id+ const irid = typeof event.request_id === 'string' ? event.request_id.trim() : '';+ if (irid) {+ window.setTimeout(() => {+ pendingInterruptRequestIdsRef.current.delete(irid);+ }, 0);}}),+ webClient.on('chat.invocation_paused', ({ payload }) => {+ const sessionId = resolveEventSessionId(payload);+ if (!sessionId) return;+ useChatStore.getState().setProcessing(sessionId, true);+ useChatStore.getState().setThinking(sessionId, false);+ }),webClient.on('chat.subtask_update', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex cc8eccf2cf..17efcb62bb 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -28,6 +28,7 @@"agent": "Agent","teams": "Teams","sessions": "Sessions",+ "history": "History","cron": "Scheduled Tasks","skills": "Skills","channels": "Channels",@@ -502,6 +503,7 @@"folder": "Folder","notPreviewable": "Not previewable","selectFile": "Select a file to view",+ "remoteFilesUnavailable": "In distributed mode, only session history restore is supported for now; browsing gateway-local session files is unavailable.","noneSelected": "No session selected","unknownSession": "Unknown session-unknown time","unknownTime": "unknown time",@@ -536,6 +538,17 @@"language": "Language","moreSettings": "More Settings"},+ "history": {+ "title": "Session History",+ "subtitle": "Browse session history stored on the Web Pod",+ "refresh": "Refresh",+ "loading": "Loading...",+ "empty": "No session history",+ "emptyMessages": "This session has no messages",+ "notFound": "Session not found",+ "back": "Back to list",+ "messageCount": "{{count}} messages"+ },"a2aIngress": {"title": "A2A Control Center","subtitle": "Manage the A2A ingress service exposed by JiuwenSwarm.",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 3e0475a67c..c40287d280 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -28,6 +28,7 @@"agent": "智能体","teams": "团队","sessions": "会话",+ "history": "会话历史","cron": "定时任务","skills": "技能","channels": "频道",@@ -503,6 +504,7 @@"folder": "文件夹","notPreviewable": "不可预览","selectFile": "请选择一个文件查看",+ "remoteFilesUnavailable": "分布式模式下当前仅支持恢复会话历史,暂不支持浏览网关本地会话文件","noneSelected": "未选择会话","unknownSession": "未知会话-未知时间","unknownTime": "未知时间",@@ -537,6 +539,17 @@"language": "语言","moreSettings": "更多设置"},+ "history": {+ "title": "会话历史",+ "subtitle": "浏览 Web Pod 落库的会话历史",+ "refresh": "刷新",+ "loading": "加载中...",+ "empty": "暂无会话历史",+ "emptyMessages": "该会话没有消息记录",+ "notFound": "未找到该会话",+ "back": "返回列表",+ "messageCount": "{{count}} 条消息"+ },"a2aIngress": {"title": "A2A 调度中心","subtitle": "管理 JiuwenSwarm 对外提供的 A2A 入站服务。",diff --git a/jiuwenswarm/channels/web/frontend/src/services/api.ts b/jiuwenswarm/channels/web/frontend/src/services/api.tsnew file mode 100644index 0000000000..4ebd07a5c6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/services/api.ts@@ -0,0 +1,53 @@+/**+ * HTTP API 客户端:会话历史(企业 MySQL 库 web)。+ *+ * 与 webClient(WS 通道)并列;仅用于读取 Web Pod 落库的会话历史:+ * GET /api/sessions(列表)、GET /api/sessions/{id}(详情)。+ *+ * 个人版后端已在 web_http_sessions_compat.py 注册了 GET /api/sessions* 路由,+ * 但只有在企业版(is_enterprise()=true)时 ChatHistoryStore 才会写入数据,+ * 因此个人版下接口可调但通常返回空列表——前端按企业模式才展示 HistoryPanel。+ */++const API_BASE = '/api';++export interface HistorySession {+ session_id: string;+ user: string | null;+ title: string | null;+ message_count: number;+ last_preview: string | null;+ created_at: number;+ updated_at: number;+}++export interface HistoryMessage {+ role: 'user' | 'assistant';+ content: string;+ event_type: string | null;+ timestamp: number;+ request_id: string;+}++export interface HistoryDetail extends HistorySession {+ messages: HistoryMessage[];+}++export async function fetchSessions(limit = 50, offset = 0, user?: string): Promise<HistorySession[]> {+ const params = new URLSearchParams({ limit: String(limit), offset: String(offset) });+ if (user) params.set('user', user);+ const res = await fetch(`${API_BASE}/sessions?${params.toString()}`);+ if (!res.ok) throw new Error(`fetchSessions failed: HTTP ${res.status}`);+ const data = (await res.json()) as { sessions?: HistorySession[] };+ return data.sessions ?? [];+}++export async function fetchSessionDetail(sessionId: string, user?: string): Promise<HistoryDetail | null> {+ const target =+ `${API_BASE}/sessions/${encodeURIComponent(sessionId)}` ++ (user ? `?user=${encodeURIComponent(user)}` : '');+ const res = await fetch(target);+ if (res.status === 404) return null;+ if (!res.ok) throw new Error(`fetchSessionDetail failed: HTTP ${res.status}`);+ return (await res.json()) as HistoryDetail;+}diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex d9e8b746ba..3d5f4dee7c 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -27,6 +27,20 @@ interface PendingRequest {const MAX_RECONNECT_ATTEMPTS = 5;const DEFAULT_TIMEOUT_MS = 15000;+/** 暂停期间暂存、恢复后回放的流式事件 */+export const PAUSABLE_STREAM_EVENTS = new Set([+ 'chat.delta', 'chat.final', 'chat.media', 'chat.file',+ 'chat.tool_call', 'chat.tool_result', 'chat.tool_update',+ 'team.member.tool_call', 'team.member.tool_result',+ 'todo.updated', 'context.compressed', 'context.usage',+ 'chat.subtask_update', 'chat.usage_summary',+]);++export interface PauseBufferHook {+ isActive: () => boolean;+ onBuffer: (event: WsEvent) => void;+}+const LEGACY_EVENT_MAP: Record<string, string> = {connection_ack: 'connection.ack',content_chunk: 'chat.delta',@@ -88,6 +102,8 @@ class WebClient {private connectPromise: Promise<void> | null = null;private lastConnectOptions: WebConnectOptions = {};private requestSeq = 0;+ private streamEventFilter: ((event: WsEvent) => boolean) | null = null;+ private pauseBufferHook: PauseBufferHook | null = null;getState(): WebConnectionState {return this.state;@@ -125,6 +141,21 @@ class WebClient {};}+ /** 丢弃已 cancel 的 chat/context 流式事件(在 dispatch 前统一过滤) */+ setStreamEventFilter(filter: ((event: WsEvent) => boolean) | null): void {+ this.streamEventFilter = filter;+ }++ /** 暂停期间将流式输出写入暂存区,恢复后通过 replayBufferedEvent 回放 */+ setPauseBufferHook(hook: PauseBufferHook | null): void {+ this.pauseBufferHook = hook;+ }++ /** 回放暂存的事件——直接派发给 handler,绕过 filter 和 buffer */+ replayBufferedEvent(event: WsEvent): void {+ this.dispatchEventToHandlers(event);+ }+async connect(options: WebConnectOptions = {}): Promise<void> {if (this.ws?.readyState === WebSocket.OPEN) {return;@@ -255,7 +286,7 @@ class WebClient {throw this.createWebError(i18n.t('network.connectionUnavailable'), 'WS_NOT_READY', undefined, true);}- const id = this.generateRequestId();+ const id = options.requestId ?? this.generateRequestId();const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;const message: WsRequest = {type: 'req',@@ -372,6 +403,14 @@ class WebClient {data: message,});+ if (+ message.type === 'event' &&+ this.streamEventFilter &&+ !this.streamEventFilter(message)+ ) {+ return;+ }+if (message.type === 'res') {this.resolvePending(message);return;@@ -405,12 +444,14 @@ class WebClient {if (!eventName) {return null;}+ const payload = this.normalizePayload(msg.payload);return {type: 'event',event: eventName,- payload: this.normalizePayload(msg.payload),+ payload,seq: typeof msg.seq === 'number' ? msg.seq : undefined,stream_id: typeof msg.stream_id === 'string' ? msg.stream_id : undefined,+ request_id: this.extractRequestId(msg, payload),};}@@ -419,10 +460,12 @@ class WebClient {if (!mappedEvent) {return null;}+ const payload = this.normalizePayload(msg.payload);return {type: 'event',event: mappedEvent,- payload: this.normalizePayload(msg.payload),+ payload,+ request_id: this.extractRequestId(msg, payload),};}@@ -436,6 +479,19 @@ class WebClient {return payload as Record<string, unknown>;}+ /** 后端 WS 路径把 request_id 放在 payload 内部;HTTP/SSE 路径放在顶层。两者都兼容。 */+ private extractRequestId(+ msg: Record<string, unknown>,+ payload: Record<string, unknown>+ ): string | undefined {+ const top = typeof msg.request_id === 'string' ? msg.request_id : undefined;+ if (top) return top;+ const inner = typeof payload.request_id === 'string' ? payload.request_id : undefined;+ if (inner) return inner;+ const rid = typeof payload.rid === 'string' ? payload.rid : undefined;+ return rid;+ }+private resolvePending(message: WsResponse): void {const pending = this.pending.get(message.id);if (!pending) {@@ -460,6 +516,20 @@ class WebClient {}private dispatchEvent(event: WsEvent): void {+ const hook = this.pauseBufferHook;+ if (hook?.isActive()) {+ if (event.event === 'chat.processing_status') {+ return;+ }+ if (PAUSABLE_STREAM_EVENTS.has(event.event)) {+ hook.onBuffer(event);+ return;+ }+ }+ this.dispatchEventToHandlers(event);+ }++ private dispatchEventToHandlers(event: WsEvent): void {const handlers = this.handlers.get(event.event);if (!handlers || handlers.size === 0) {return;diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.tsindex 61d4639463..b7ffd0580d 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts@@ -12,6 +12,7 @@ import {import { getGatewayHttpBase } from '../utils/env';import i18n from '../i18n';import { buildRuntimeIdentityHeaders } from './runtimeScope';+import { PauseBufferHook, PAUSABLE_STREAM_EVENTS } from './webClient';type EventHandler = (event: WsEvent) => void;type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;@@ -313,37 +314,55 @@ export function consumeSseBuffer(buffer: string): { frames: SseFrame[]; rest: streturn { frames, rest };}-function payloadFromData(data: string | undefined): Record<string, unknown> {+function payloadFromData(+ data: string | undefined+): { payload: Record<string, unknown>; raw: Record<string, unknown> | null } {if (!data) {- return {};+ return { payload: {}, raw: null };}try {const parsed: unknown = JSON.parse(data);if (isRecord(parsed)) {if (isRecord(parsed.payload)) {- return parsed.payload;+ return { payload: parsed.payload, raw: parsed };}- return parsed;+ return { payload: parsed, raw: parsed };}- return { value: parsed };+ return { payload: { value: parsed }, raw: null };} catch {- return { raw: data };+ return { payload: { raw: data }, raw: null };}}+function extractSseRequestId(+ raw: Record<string, unknown> | null,+ payload: Record<string, unknown>+): string | undefined {+ if (raw) {+ const top = typeof raw.request_id === 'string' ? raw.request_id : undefined;+ if (top) return top;+ }+ const inner = typeof payload.request_id === 'string' ? payload.request_id : undefined;+ if (inner) return inner;+ const rid = typeof payload.rid === 'string' ? payload.rid : undefined;+ return rid;+}+export function sseFrameToWsEvent(frame: SseFrame): WsEvent | null {let eventName = frame.event?.trim() ?? '';- const payload = payloadFromData(frame.data);+ const { payload, raw } = payloadFromData(frame.data);if (!eventName && typeof payload.event === 'string') {eventName = payload.event;}if (!eventName) {return null;}+ const requestId = extractSseRequestId(raw, payload);return {type: 'event',event: eventName,payload,+ ...(requestId ? { request_id: requestId } : {}),};}@@ -429,6 +448,8 @@ export class WebHttpClient {private connectPromise: Promise<void> | null = null;private lastConnectOptions: WebConnectOptions = {};private requestSeq = 0;+ private streamEventFilter: ((event: WsEvent) => boolean) | null = null;+ private pauseBufferHook: PauseBufferHook | null = null;getState(): WebConnectionState {return this.state;@@ -445,6 +466,21 @@ export class WebHttpClient {};}+ /** 丢弃已 cancel 的 chat/context 流式事件(在 dispatch 前统一过滤) */+ setStreamEventFilter(filter: ((event: WsEvent) => boolean) | null): void {+ this.streamEventFilter = filter;+ }++ /** 暂停期间将流式输出写入暂存区,恢复后通过 replayBufferedEvent 回放 */+ setPauseBufferHook(hook: PauseBufferHook | null): void {+ this.pauseBufferHook = hook;+ }++ /** 回放暂存的事件——直接派发给 handler,绕过 filter 和 buffer */+ replayBufferedEvent(event: WsEvent): void {+ this.dispatchEventToHandlers(event);+ }+on<TPayload = Record<string, unknown>>(eventName: string,handler: TypedEventHandler<TPayload>@@ -507,7 +543,7 @@ export class WebHttpClient {);}- const requestId = this.generateRequestId();+ const requestId = options.requestId ?? this.generateRequestId();let assembled;try {assembled = assembleWebRest(method, params, getGatewayHttpBase());@@ -854,6 +890,23 @@ export class WebHttpClient {}private dispatchEvent(event: WsEvent): void {+ if (this.streamEventFilter && !this.streamEventFilter(event)) {+ return;+ }+ const hook = this.pauseBufferHook;+ if (hook?.isActive()) {+ if (event.event === 'chat.processing_status') {+ return;+ }+ if (PAUSABLE_STREAM_EVENTS.has(event.event)) {+ hook.onBuffer(event);+ return;+ }+ }+ this.dispatchEventToHandlers(event);+ }++ private dispatchEventToHandlers(event: WsEvent): void {const handlers = this.handlers.get(event.event);if (!handlers || handlers.size === 0) {return;diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.tsindex da40183a49..86845d16d8 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts@@ -243,6 +243,8 @@ interface ChatState {updateToolProgress: (sessionId: string, toolCallId: string, progress: Partial<ToolResult>) => void;addToolResult: (sessionId: string, toolResult: ToolResult, options?: { updatedAt?: string }) => void;markTimedOutExecutions: (sessionId: string) => void;+ /** 打断(pause/cancel)时把仍 pending 的工具行标记为 timeout,并注入 "Interrupted by user" 合成结果。 */+ markInterruptedExecutions: (sessionId: string) => void;/** 历史回放常只有 tool_call、无 tool_result:把仍 pending 的工具按 startedAt 结算,避免超时巡检用 now 污染耗时 */settleHistoricalToolExecutions: (sessionId: string) => void;updateSubtask: (sessionId: string, payload: SubtaskUpdatePayload) => void;@@ -1196,6 +1198,46 @@ export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get)});},+ markInterruptedExecutions: (sessionId) => {+ const nowIso = new Date().toISOString();+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ let changed = false;+ const nextExecutions = new Map(runtime.toolExecutions);+ for (const [toolCallId, execution] of nextExecutions) {+ if (execution.status !== 'pending') {+ continue;+ }+ changed = true;+ nextExecutions.set(toolCallId, {+ ...execution,+ status: 'timeout',+ timedOutAt: nowIso,+ updatedAt: nowIso,+ result: execution.result ?? {+ toolCallId,+ toolName: execution.toolCall.name,+ result: 'Interrupted by user',+ success: false,+ summary: 'Interrupted',+ },+ });+ }+ if (!changed) return state;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ toolExecutions: nextExecutions,+ activeSubtasks: new Map(),+ },+ },+ };+ });+ },+settleHistoricalToolExecutions: (sessionId) => {set((state) => {const runtime = state.runtimes[sessionId];diff --git a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts b/jiuwenswarm/channels/web/frontend/src/types/websocket.tsindex cc8d11d527..13bcece91d 100644--- a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts@@ -32,6 +32,8 @@ export interface WsEvent {payload: Record<string, unknown>;seq?: number;stream_id?: string;+ /** 后端在 chat.* 事件 payload 内注入的请求关联 id(chat.delta/final 不携带)。 */+ request_id?: string;}export type WebMessage = WsRequest | WsResponse | WsEvent;@@ -41,6 +43,8 @@ export interface WebRequestOptions {signal?: AbortSignal;/** 对应协议里请求消息的顶层 is_stream 字段(如 command.goal 的 set/resume) */isStream?: boolean;+ /** 调用方指定请求 id,用于 chat.send/chat.interrupt 的流式事件关联与取消过滤。 */+ requestId?: string;}export interface WebConnectOptions {diff --git a/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts b/jiuwenswarm/channels/web/frontend/src/utils/finalContent.tsindex 94a074a8a5..2687955c34 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/finalContent.ts@@ -8,6 +8,8 @@ function decodeQuotedPythonLikeString(raw: string): string {.replace(/\\\\/g, '\\');}+import { stripResidualInlineToolProtocol } from './toolProtocol';+/** 字面量 `\\n` 明显多于真换行时还原,避免 GFM 表格解析失败。 */export function unescapeLiteralNewlines(text: string): string {const realNl = (text.match(/\n/g) || []).length;@@ -114,7 +116,9 @@ export function normalizeFinalContent(payload: Record<string, unknown>): stringreturn '';}- const trimmed = rawContent.trim();+ const cleaned = stripResidualInlineToolProtocol(rawContent);++ const trimmed = cleaned.trim();if (trimmed.startsWith('{') && trimmed.endsWith('}')) {try {@@ -139,18 +143,18 @@ export function normalizeFinalContent(payload: Record<string, unknown>): string} catch {// ignore}- return normalizeFinalDisplayText(rawContent);+ return normalizeFinalDisplayText(cleaned);}- const singleQuoted = rawContent.match(/['"]output['"]\s*:\s*'((?:\\'|[^'])*)'/s);+ const singleQuoted = cleaned.match(/['"]output['"]\s*:\s*'((?:\\'|[^'])*)'/s);if (singleQuoted?.[1] != null) {return normalizeFinalDisplayText(decodeQuotedPythonLikeString(singleQuoted[1]));}- const doubleQuoted = rawContent.match(/['"]output['"]\s*:\s*"((?:\\"|[^"])*)"/s);+ const doubleQuoted = cleaned.match(/['"]output['"]\s*:\s*"((?:\\"|[^"])*)"/s);if (doubleQuoted?.[1] != null) {return normalizeFinalDisplayText(decodeQuotedPythonLikeString(doubleQuoted[1]));}- return normalizeFinalDisplayText(rawContent);+ return normalizeFinalDisplayText(cleaned);}diff --git a/jiuwenswarm/channels/web/frontend/src/utils/index.ts b/jiuwenswarm/channels/web/frontend/src/utils/index.tsindex de88a3ef75..5c9af1e53d 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/index.ts@@ -10,3 +10,4 @@ export * from './chatFinalProtocol';export * from './timestamp';export * from './harnessErrors';export * from './fileDownloadDedup';+export { stripInlineToolProtocol, stripResidualInlineToolProtocol } from './toolProtocol';diff --git a/jiuwenswarm/channels/web/frontend/src/utils/toolProtocol.ts b/jiuwenswarm/channels/web/frontend/src/utils/toolProtocol.tsnew file mode 100644index 0000000000..52b7ff318e--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/utils/toolProtocol.ts@@ -0,0 +1,193 @@+/**+ * 前端内联工具协议清洗工具(与后端 stream_content_sanitize.py 同语义)。+ *+ * 剥离模型/网关写入 delta.content 后泄漏到 chat.final/chat.delta 中的协议串:+ * <tool_calls_begin><tool_call_begin>function<tool_sep>tool_name{...}</tool_calls_end>+ *+ * 仅影响展示与 TTS,不修改 chatStore 持久化内容。+ */++const OPEN_TAGS = ['<tool_calls_begin>', '<tool_call_begin>'] as const;+const CLOSE_TAGS = ['</tool_calls_end>', '</tool_call_end>'] as const;+const FUNC_SEP = 'function<tool_sep>';+const TOOL_NAME_RE = /^[A-Za-z0-9_]+/;++const TOOL_WHITELIST: ReadonlySet<string> = new Set([+ 'todo_create',+ 'todo_complete',+ 'todo_insert',+ 'todo_remove',+ 'todo_list',+]);++function findBalancedJsonEnd(text: string, start: number): number {+ let depth = 0;+ let inString = false;+ let escapeNext = false;+ const n = text.length;++ for (let i = start; i < n; i++) {+ const ch = text[i];+ if (escapeNext) {+ escapeNext = false;+ continue;+ }+ if (inString) {+ if (ch === '\\') { escapeNext = true; }+ else if (ch === '"') { inString = false; }+ continue;+ }+ if (ch === '"') {+ inString = true;+ } else if (ch === '{' || ch === '[') {+ depth++;+ } else if (ch === '}' || ch === ']') {+ depth--;+ if (depth === 0) return i + 1;+ }+ }+ return -1;+}++function findEarliestOpenTag(text: string, from = 0): { pos: number; tag: string } {+ let bestPos = -1;+ let bestTag = '';+ for (const tag of OPEN_TAGS) {+ const pos = text.indexOf(tag, from);+ if (pos !== -1 && (bestPos === -1 || pos < bestPos)) {+ bestPos = pos;+ bestTag = tag;+ }+ }+ return { pos: bestPos, tag: bestTag };+}++function findFuncSep(text: string, from = 0): number {+ return text.indexOf(FUNC_SEP, from);+}++function findCloseTags(text: string, from: number): number {+ let pos = from;+ let foundAny = false;+ while (true) {+ let bestIdx = -1;+ let bestTag = '';+ for (const tag of CLOSE_TAGS) {+ const idx = text.indexOf(tag, pos);+ if (idx !== -1 && (bestIdx === -1 || idx < bestIdx)) {+ bestIdx = idx;+ bestTag = tag;+ }+ }+ if (bestIdx === -1) break;+ const gap = text.slice(pos, bestIdx);+ if (foundAny && gap.trim()) break;+ pos = bestIdx + bestTag.length;+ foundAny = true;+ }+ return foundAny ? pos : -1;+}++function toolNameAllowed(name: string): boolean {+ return TOOL_WHITELIST.has(name);+}++function toolNameMayBeIncompletePrefix(name: string): boolean {+ return Array.from(TOOL_WHITELIST).some((tool) => tool.startsWith(name) && tool !== name);+}++function hasExplicitInlineToolTags(text: string): boolean {+ return OPEN_TAGS.some((tag) => text.includes(tag)) || CLOSE_TAGS.some((tag) => text.includes(tag));+}++function stripOnePass(text: string): string {+ let pos = 0;+ const n = text.length;++ while (pos < n) {+ const { pos: tagPos, tag: openTag } = findEarliestOpenTag(text, pos);+ const funcPos = findFuncSep(text, pos);++ if (tagPos === -1 && funcPos === -1) break;++ const useOuter = tagPos !== -1 && (funcPos === -1 || tagPos <= funcPos);++ if (useOuter) {+ const anchor = tagPos;+ const innerFunc = findFuncSep(text, anchor);++ if (innerFunc === -1) {+ const closeEnd = findCloseTags(text, anchor + openTag.length);+ if (closeEnd !== -1) {+ return text.slice(0, anchor) + text.slice(closeEnd);+ }+ return text.slice(0, anchor);+ }++ const nameStart = innerFunc + FUNC_SEP.length;+ const nameMatch = TOOL_NAME_RE.exec(text.slice(nameStart));+ if (!nameMatch) { pos = innerFunc + 1; continue; }+ const toolName = nameMatch[0];+ if (!toolNameAllowed(toolName)) {+ if (toolNameMayBeIncompletePrefix(toolName)) {+ return text.slice(0, anchor);+ }+ pos = innerFunc + 1;+ continue;+ }++ const jsonStart = nameStart + toolName.length;+ if (jsonStart >= n || text[jsonStart] !== '{') { pos = jsonStart; continue; }++ const jsonEnd = findBalancedJsonEnd(text, jsonStart);+ if (jsonEnd === -1) {+ return text.slice(0, anchor);+ }+ const closeEnd = findCloseTags(text, jsonEnd);+ const segEnd = closeEnd !== -1 ? closeEnd : jsonEnd;+ return text.slice(0, anchor) + text.slice(segEnd);+ } else {+ const anchor = funcPos;+ const nameStart = anchor + FUNC_SEP.length;+ const nameMatch = TOOL_NAME_RE.exec(text.slice(nameStart));+ if (!nameMatch) { pos = anchor + 1; continue; }+ const toolName = nameMatch[0];+ if (!toolNameAllowed(toolName)) {+ if (toolNameMayBeIncompletePrefix(toolName)) {+ return text.slice(0, anchor);+ }+ pos = anchor + 1;+ continue;+ }++ const jsonStart = nameStart + toolName.length;+ if (jsonStart >= n || text[jsonStart] !== '{') { pos = jsonStart; continue; }++ const jsonEnd = findBalancedJsonEnd(text, jsonStart);+ if (jsonEnd === -1) {+ return text.slice(0, anchor);+ }+ return text.slice(0, anchor) + text.slice(jsonEnd);+ }+ }+ return text;+}++export function stripInlineToolProtocol(text: string): string {+ if (!text) return text;+ let result = text;+ let changed = true;+ while (changed) {+ const next = stripOnePass(result);+ changed = next !== result;+ result = next;+ }+ return result;+}++export function stripResidualInlineToolProtocol(text: string): string {+ if (!text || !hasExplicitInlineToolTags(text)) {+ return text;+ }+ return stripInlineToolProtocol(text);+}diff --git a/jiuwenswarm/channels/web/frontend/src/utils/tts.ts b/jiuwenswarm/channels/web/frontend/src/utils/tts.tsindex f2e2bf8a8a..4af458378b 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/tts.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/tts.ts@@ -3,6 +3,7 @@*/import { webRequest } from '../services/webClient';+import { stripResidualInlineToolProtocol } from './toolProtocol';interface TtsResponse {success: boolean;@@ -34,7 +35,7 @@ export function sanitizeTtsText(return '';}- const sanitized = input+ const sanitized = stripResidualInlineToolProtocol(input).replace(CODE_BLOCK_RE, '代码块已省略').replace(INLINE_CODE_RE, '').replace(MEDIA_BRACE_RE, '')diff --git a/jiuwenswarm/extensions/redis/redis_client.py b/jiuwenswarm/extensions/redis/redis_client.pyindex 2334fb3e23..9b91620839 100644--- a/jiuwenswarm/extensions/redis/redis_client.py+++ b/jiuwenswarm/extensions/redis/redis_client.py@@ -3,9 +3,10 @@from __future__ import annotations+import asyncioimport loggingfrom collections.abc import AsyncIterator-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Anyif TYPE_CHECKING:@@ -44,6 +45,8 @@ def _coerce_float(val: Any, default: float) -> float:class RedisConfig:"""与 config 中 ``redis:`` 段及 §3.2.1 对齐。"""+ mode: str = "standalone" # standalone | cluster+ startup_nodes: list[dict] = field(default_factory=list) # [{host, port}, ...]; cluster 启动节点host: str = "localhost"port: int = 6379password: str | None = None@@ -63,6 +66,18 @@ class RedisConfig:return Nonereturn str(value)+ @staticmethod+ def _parse_startup_nodes(value: Any, default_port: int = 6379) -> list[dict]:+ """解析 'host[:port]' 或逗号分隔列表;未带端口用 default_port。"""+ nodes: list[dict] = []+ for item in str(value or "").split(","):+ host, _, port = item.partition(":")+ host = host.strip()+ if not host:+ continue+ nodes.append({"host": host, "port": _coerce_int(port.strip() or str(default_port), default_port)})+ return nodes+@classmethoddef from_mapping(cls, data: dict[str, Any] | None) -> RedisConfig:m = data or {}@@ -70,9 +85,25 @@ class RedisConfig:if kp and not kp.endswith(":"):kp = f"{kp}:"pw = cls._normalize_password(m.get("password"))+ mode = str(m.get("mode") or "standalone").strip().lower()+ if mode not in ("standalone", "cluster"):+ mode = "standalone"+ # host 字段承载地址:单机 host/host:port 或集群逗号列表;未带端口用 port(REDIS_PORT)+ fallback_port = _coerce_int(m.get("port"), 6379)+ node_list = cls._parse_startup_nodes(m.get("host"), default_port=fallback_port)+ if node_list:+ host = node_list[0]["host"]+ port = node_list[0]["port"]+ startup_nodes = node_list if mode == "cluster" else []+ else:+ host = "localhost"+ port = fallback_port+ startup_nodes = []return cls(- host=str(m.get("host") if m.get("host") is not None else "localhost"),- port=_coerce_int(m.get("port"), 6379),+ mode=mode,+ startup_nodes=startup_nodes,+ host=host,+ port=port,password=pw,db=_coerce_int(m.get("db"), 0),key_prefix=kp,@@ -94,7 +125,11 @@ class RedisConfig:class RedisClient:- """§3.3.3 接口:连接池 + KV/Hash + Pub/Sub + ping + close。"""+ """§3.3.3 接口:连接池 + KV/Hash + Pub/Sub + ping + close。++ ``mode="cluster"`` 时 ``open()`` 用 ``redis.asyncio.RedisCluster`` 替代单机连接池,+ 其余接口不变;``mget()`` 在 CROSSSLOT 异常时自动回退逐 key get。+ """def __init__(self, cfg: RedisConfig) -> None:self._cfg = cfg@@ -109,6 +144,27 @@ class RedisClient:if self._redis is not None:returnredis = _require_redis_async()+ if self._cfg.mode == "cluster":+ from redis.asyncio.cluster import RedisCluster+ from redis.cluster import ClusterNode+ if not self._cfg.startup_nodes:+ logger.warning(+ "[RedisClient] cluster 模式未配置 startup_nodes,回退单节点 %s:%s"+ "(若该节点非集群成员将连接失败)",+ self._cfg.host, self._cfg.port,+ )+ nodes = [ClusterNode(n["host"], int(n["port"])) for n in self._cfg.startup_nodes] \+ or [ClusterNode(self._cfg.host, self._cfg.port)]+ self._redis = RedisCluster(+ startup_nodes=nodes,+ password=self._cfg.password,+ decode_responses=True,+ socket_connect_timeout=self._cfg.connect_timeout,+ socket_timeout=self._cfg.operation_timeout,+ health_check_interval=self._cfg.health_check_interval,+ max_connections=self._cfg.pool_size,+ )+ returnself._pool = redis.ConnectionPool(host=self._cfg.host,port=self._cfg.port,@@ -184,7 +240,14 @@ class RedisClient:if not keys:return []full = [self._cfg.effective_key(k) for k in keys]- vals = await r.mget(*full)+ try:+ vals = await r.mget(*full)+ except Exception as exc:+ # Cluster 跨 slot 抛 CROSSSLOT -> 回退逐个 get;其余异常(连接断开等)直接抛出+ if "CROSSSLOT" not in str(exc).upper():+ raise+ logger.warning("[RedisClient] mget CROSSSLOT fallback to per-key get: %s", exc)+ return await asyncio.gather(*(r.get(k) for k in full))out: list[str | None] = []for v in vals or []:if v is None:@@ -213,14 +276,14 @@ class RedisClient:"""``scan_iter`` 的别名(SessionMap / LeaderElection 故障切换用)。"""return await self.scan_iter(pattern)- async def hget(self, key: str, field: str) -> str | None:+ async def hget(self, key: str, hash_field: str) -> str | None:r = self._connection()- return await r.hget(self._cfg.effective_key(key), field)+ return await r.hget(self._cfg.effective_key(key), hash_field)- async def hset(self, key: str, field: str, value: Any) -> bool:+ async def hset(self, key: str, hash_field: str, value: Any) -> bool:r = self._connection()v = value if isinstance(value, str) else str(value)- await r.hset(self._cfg.effective_key(key), field, v)+ await r.hset(self._cfg.effective_key(key), hash_field, v)return Trueasync def hgetall(self, key: str) -> dict[str, Any]:@@ -228,9 +291,9 @@ class RedisClient:raw = await r.hgetall(self._cfg.effective_key(key))return dict(raw) if raw else {}- async def hdel(self, key: str, field: str) -> bool:+ async def hdel(self, key: str, hash_field: str) -> bool:r = self._connection()- n = int(await r.hdel(self._cfg.effective_key(key), field))+ n = int(await r.hdel(self._cfg.effective_key(key), hash_field))return n > 0async def publish(self, channel: str, message: str) -> int:diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 7f356131a4..ad97d8f9b5 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1830,6 +1830,10 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:proactive_cfg.get("max_recommend_per_day", 10))payload["proactive_recommendation_max_rounds_per_tick"] = str(proactive_cfg.get("max_rounds_per_tick", 20))+ gateway_cfg = raw.get("gateway") or {}+ payload["gateway_web_session_storage"] = str(+ gateway_cfg.get("web_session_storage") or "local"+ ).strip().lower()except Exception: # noqa: BLE001payload.setdefault("context_engine_enabled", "false")payload.setdefault("kv_cache_release_enabled", "false")@@ -1859,6 +1863,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload.setdefault("proactive_recommendation_enabled", "false")payload.setdefault("proactive_recommendation_max_recommend_per_day", "10")payload.setdefault("proactive_recommendation_max_rounds_per_tick", "20")+ payload.setdefault("gateway_web_session_storage", "local")await channel.send_response(ws, req_id, ok=True, payload=payload)def _persist_env_updates(updates: dict[str, str]) -> None:@@ -2980,7 +2985,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:service = updater_service or UpdaterService()await channel.send_response(ws, req_id, ok=True, payload=service.get_runtime_config())- async def _session_list(ws, req_id, params, session_id):+ async def _session_list(ws, req_id, params, session_id, user_id=None):"""返回会话列表,包含完整的会话管理信息。"""limit = 20offset = 0@@ -3005,6 +3010,35 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:limit = max(1, min(limit, 200))offset = max(0, offset)+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage++ if is_remote_storage():+ logger.warning(+ "[session.list] remote 模式执行了 WebChannel 本地 handler(缺少入站转发时);"+ "将就地读网关索引。",+ )+ from jiuwenswarm.gateway.routing.session_index import list_sessions_page_async++ _params = params if isinstance(params, dict) else {}+ # 多用户隔离:remote 模式必须按用户过滤,否则会返回所有用户的会话。+ # user_id 缺失(未认证/匿名连接)时回退 "guest"(与 history_store 一致),+ # 避免空串导致 list_sessions_page 不过滤而泄露跨用户数据;同时告警便于排查。+ _raw_uid = str(user_id or "").strip()+ if not _raw_uid:+ logger.warning(+ "[session.list] remote 模式缺少 user_id,按 guest 过滤(可能是匿名连接)",+ )+ _raw_uid = "guest"+ _params = {**_params, "user": _raw_uid}+ sessions, total, limit_ret, offset_ret = await list_sessions_page_async(_params)+ await channel.send_response(ws, req_id, ok=True, payload={+ "sessions": [_to_session_info(s) for s in sessions],+ "total": total,+ "limit": limit_ret,+ "offset": offset_ret,+ })+ return+from jiuwenswarm.server.runtime.session.session_metadata import get_all_sessions_metadatasessions, total = get_all_sessions_metadata(limit=limit, offset=offset)@@ -3068,6 +3102,19 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",)return+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage++ if is_remote_storage():+ logger.error(+ "[session.create] remote 模式但执行了本地 handler(转发未生效?)session_id=%s",+ session_id,+ )+ await channel.send_response(+ ws, req_id, ok=False,+ error="remote session storage is enabled but request was not forwarded to agent",+ code="REMOTE_STORAGE_FORWARD_FAILED",+ )+ returnresolved_agent_client = _resolve(agent_client)if resolved_agent_client is None:await channel.send_response(@@ -3187,6 +3234,20 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:returnsession_id_to_delete = session_id_to_delete.strip()+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage++ if is_remote_storage():+ logger.error(+ "[session.delete] remote 模式但执行了本地 handler(转发未生效?)session_id=%s",+ session_id_to_delete,+ )+ await channel.send_response(+ ws, req_id, ok=False,+ error="remote session storage is enabled but request was not forwarded to agent",+ code="REMOTE_STORAGE_FORWARD_FAILED",+ )+ return+from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadatafrom jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.message import ReqMethod@@ -5137,7 +5198,28 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload={"rss_mb": rss_mb, "total_mb": total_mb,"available_mb": available_mb})- async def _chat_send(ws, req_id, params, session_id):+ async def _chat_send(ws, req_id, params, session_id, user_id=None):+ # remote 模式下维护会话索引:chat.send 时写入最近一条用户消息预览+ if session_id:+ try:+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage, upsert_async+ if is_remote_storage():+ content = ""+ if isinstance(params, dict):+ content = str(params.get("content") or params.get("query") or "")+ # user_id 缺失时回退 "guest"(与 history_store 一致),避免写空串+ # 到索引 user 字段、后续按用户过滤匹配不到而破坏多用户隔离。+ _raw_uid = str(user_id or "").strip()+ if not _raw_uid:+ logger.warning(+ "[chat.send] remote 模式缺少 user_id,索引 user 回退为 guest",+ )+ _raw_uid = "guest"+ await upsert_async(+ session_id, "user", content, time.time(), user=_raw_uid,+ )+ except Exception:+ logger.debug("[chat.send] session_index upsert skipped", exc_info=True)await channel.send_response(ws,req_id,diff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.pyindex 7126b8e21c..a41d00887d 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py@@ -873,6 +873,31 @@ class WebWsTransport(BaseWsChannel):}await self._broadcast_to(frame_data, all_clients)+ # remote 模式下维护会话索引:chat.final 时写入最近一条助手消息预览+ if event_name == "chat.final" and msg.session_id:+ try:+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage, upsert_async+ if is_remote_storage():+ _md = msg.metadata if isinstance(msg.metadata, dict) else {}+ # 缺少 user_id 时回退 "guest"(与 history_store 一致),避免写空串+ # 到索引 user 字段破坏多用户隔离;告警提示连接未携带 user_id。+ _raw_uid = str(_md.get("user_id") or "").strip()+ if not _raw_uid:+ logger.warning(+ "[WebChannel] chat.final 缺少 user_id,索引 user 回退为 guest"+ "(WebSocket 连接未携带 user_id,多用户隔离可能受影响)",+ )+ _raw_uid = "guest"+ await upsert_async(+ msg.session_id,+ "assistant",+ str(payload.get("content") or ""),+ time.time(),+ user=_raw_uid,+ )+ except Exception:+ logger.debug("[WebChannel] session_index upsert skipped", exc_info=True)+# 维护 session busy 状态(供 /ws/git 写操作查询)if event_name == "chat.processing_status" and isinstance(payload, dict):sid = payload.get("session_id") or msg.session_iddiff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex f73db1a9d6..513d040dde 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -3746,6 +3746,18 @@ class MessageHandler(ABC):resp.request_id,resp.channel_id,)+ # remote 模式下 session.delete 成功后从索引移除+ if env.method == "session.delete" and getattr(resp, "ok", False):+ try:+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage, remove_async+ if is_remote_storage():+ del_session_id = msg.session_id+ if isinstance(msg.params, dict):+ del_session_id = msg.params.get("session_id") or msg.session_id+ if del_session_id:+ await remove_async(del_session_id)+ except Exception:+ logger.debug("[MessageHandler] session_index remove skipped", exc_info=True)if (self._is_interrupt_evolution_approval_chat_send(msg, method=env.method)and self._approval_response_resolved(resp)diff --git a/jiuwenswarm/gateway/routing/session_index.py b/jiuwenswarm/gateway/routing/session_index.pynew file mode 100644index 0000000000..3db5cdb8a7--- /dev/null+++ b/jiuwenswarm/gateway/routing/session_index.py@@ -0,0 +1,178 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Gateway 侧轻量会话索引(仅在 web_session_storage=remote 时启用)。++预览与排序依赖 ``chat.final`` 以及 ``chat.send`` / ``chat.resume`` 路径上的索引更新;+若某条链路未产生 ``chat.final`` 或内容在其它字段,列表预览可能为空或不更新。+同步文件 I/O 封装在 ``asyncio.to_thread`` 中,避免阻塞事件循环。++每条记录格式:+ {+ "session_id": str,+ "role": str, # 最近一条消息的角色,如 "user" / "assistant"+ "timestamp": float, # Unix 时间戳(最近活动时间)+ "content": str, # 最近一条消息的内容预览(截断)+ "user": str, # 用户标识(用于多用户隔离)+ }++最多保留 MAX_SESSIONS 条,按 timestamp 降序排列;写入时自动淘汰最旧条目。+``list_sessions_page`` 按 user 过滤,确保多用户环境下不会跨用户泄漏预览。+"""+from __future__ import annotations++import asyncio+import json+import logging+import os+import threading+from pathlib import Path+from typing import Any, Mapping++logger = logging.getLogger(__name__)++MAX_SESSIONS = 100+CONTENT_PREVIEW_LEN = 200++_lock = threading.Lock()+++def _index_path() -> Path:+ from jiuwenswarm.common.utils import get_user_workspace_dir++ p = get_user_workspace_dir() / "gateway" / "session_index.json"+ p.parent.mkdir(parents=True, exist_ok=True)+ return p+++def _read_index() -> list[dict[str, Any]]:+ path = _index_path()+ if not path.exists():+ return []+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ if isinstance(data, list):+ return data+ except Exception as exc: # noqa: BLE001+ logger.warning("[session_index] 读取索引失败: %s", exc)+ return []+++def _write_index(entries: list[dict[str, Any]]) -> None:+ try:+ path = _index_path()+ path.write_text(json.dumps(entries, ensure_ascii=False, indent=2), encoding="utf-8")+ except Exception as exc: # noqa: BLE001+ logger.warning("[session_index] 写入索引失败: %s", exc)+++def upsert(session_id: str, role: str, content: str, timestamp: float, user: str = "") -> None:+ """插入或更新一条会话记录,并维持最多 MAX_SESSIONS 条限制。++ ``user`` 用于多用户隔离:索引条目携带 user 字段,``list_sessions_page`` 据此过滤。+ """+ preview = content[:CONTENT_PREVIEW_LEN] if content else ""+ with _lock:+ entries = _read_index()+ entries = [e for e in entries if e.get("session_id") != session_id]+ entries.insert(0, {+ "session_id": session_id,+ "role": role,+ "timestamp": timestamp,+ "content": preview,+ "user": user or "",+ })+ entries.sort(key=lambda e: e.get("timestamp", 0), reverse=True)+ entries = entries[:MAX_SESSIONS]+ _write_index(entries)+++async def upsert_async(+ session_id: str, role: str, content: str, timestamp: float, user: str = "",+) -> None:+ """``upsert`` 的异步包装,将同步文件 I/O offload 到线程池,避免阻塞事件循环。"""+ await asyncio.to_thread(upsert, session_id, role, content, timestamp, user)+++def remove(session_id: str) -> None:+ """从索引中删除指定会话。"""+ with _lock:+ entries = _read_index()+ new_entries = [e for e in entries if e.get("session_id") != session_id]+ if len(new_entries) != len(entries):+ _write_index(new_entries)+++async def remove_async(session_id: str) -> None:+ """``remove`` 的异步包装,将同步文件 I/O offload 到线程池,避免阻塞事件循环。"""+ await asyncio.to_thread(remove, session_id)+++def list_sessions() -> list[dict[str, Any]]:+ """读取当前索引(最多 MAX_SESSIONS 条,按时间降序)。"""+ with _lock:+ return list(_read_index())+++def list_sessions_page(+ params: Mapping[str, Any] | None = None,+) -> tuple[list[dict[str, Any]], int, int, int]:+ """读取索引并应用与本地 ``session.list`` 一致的 limit/offset 分页。++ 从 ``params`` 中提取 ``user`` / ``user_id`` 并按用户过滤,确保多用户环境下+ 用户只能看到自己的会话预览。+ """+ params = dict(params or {})+ limit = 20+ offset = 0+ raw_limit = params.get("limit")+ if isinstance(raw_limit, int):+ limit = raw_limit+ elif isinstance(raw_limit, str) and raw_limit.strip().isdigit():+ limit = int(raw_limit.strip())+ raw_offset = params.get("offset")+ if isinstance(raw_offset, int):+ offset = raw_offset+ elif isinstance(raw_offset, str) and raw_offset.strip().isdigit():+ offset = int(raw_offset.strip())+ limit = max(1, min(limit, 200))+ offset = max(0, offset)++ # 用户隔离:从 params 提取 user / user_id,仅返回该用户的会话+ raw_user = params.get("user") or params.get("user_id")+ if isinstance(raw_user, str):+ user = raw_user.strip()+ elif isinstance(raw_user, int):+ user = str(raw_user)+ else:+ user = ""++ with _lock:+ all_entries = list(_read_index())+ if user:+ all_entries = [e for e in all_entries if str(e.get("user", "")) == user]+ total = len(all_entries)+ page = all_entries[offset:offset + limit]+ return page, total, limit, offset+++async def list_sessions_page_async(+ params: Mapping[str, Any] | None = None,+) -> tuple[list[dict[str, Any]], int, int, int]:+ """``list_sessions_page`` 的异步包装,将同步文件 I/O offload 到线程池。"""+ return await asyncio.to_thread(list_sessions_page, params)+++def is_remote_storage() -> bool:+ """根据配置判断是否启用网关索引(remote)模式。"""+ val = os.getenv("GATEWAY_WEB_SESSION_STORAGE", "").strip().lower()+ if val in ("remote", "local"):+ return val == "remote"+ try:+ from jiuwenswarm.common.config import get_config++ raw = str(+ (get_config().get("gateway") or {}).get("web_session_storage", "local") or "local"+ ).strip().lower()+ return raw == "remote"+ except Exception as exc: # noqa: BLE001+ logger.warning("[session_index] 读取 web_session_storage 配置失败,使用 local: %s", exc)+ return Falsediff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex cae2965daf..b32a8b2db3 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -682,8 +682,8 @@ react:tool_args_bailout_threshold: 2 # 工具入参规则压缩次数达此值后终止# Skills 在线自演进配置evolution:- enabled: true # true = 启用在线 Skills 自演进(挂载后被动扫描始终开启)- signal_trigger: true # true = 对话结束后被动 signal 扫描(run_evolution);默认 true+ enabled: false # true = 启用在线 Skills 自演进(挂载后被动扫描始终开启)+ signal_trigger: false # true = 对话结束后被动 signal 扫描(run_evolution);默认 truereview_trigger: false # true / false = Leader review follow-up;单 agent/teammate 由代码强制 falseauto_save: true # true = 自演进审批无需用户点击自动通过(内部开关)skill_create: false # true = 注册 SkillCreateRail(单 agent)及 TeamSkillCreateRail(leader)@@ -742,6 +742,9 @@ task_memory:# ========== Redis(主备 Gateway:状态存储 / Pub/Sub / Leader;standalone 下不连接)==========# 通过 gateway.deployment_mode 控制:standalone(不连接)/ active-standby(连接 Redis)redis:+ # standalone | cluster;cluster 时下方 host 解析为逗号分隔的多节点列表+ mode: ${REDIS_MODE:-standalone}+ # 单机:host / host:port;cluster:逗号列表(如 10.0.0.11:6379,10.0.0.12:6379);不带端口时用 porthost: ${REDIS_HOST:-localhost}port: ${REDIS_PORT:-6379}password: ${REDIS_PASSWORD:-}@@ -770,6 +773,10 @@ gateway:# 分布式下用于实例标识;空则启动时自动生成instance_id: ${GATEWAY_INSTANCE_ID:-}+ # Web 会话存储位置:local(默认,会话文件在网关本地磁盘)| remote(会话在 Web Pod / 远程存储)+ # remote 时前端 SessionsPanel 不再浏览网关本地会话文件,仅支持恢复会话历史。+ web_session_storage: ${GATEWAY_WEB_SESSION_STORAGE:-local}+# 企业版 Gateway 多副本:从共享库轮询 Gateway 自身配置(channel/logging/log_masking)config_poll:enabled: ${GATEWAY_CONFIG_POLL_ENABLED:-false}diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex df3b6008c6..ee4ee7e867 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -314,6 +314,7 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import ()from jiuwenswarm.server.runtime.agent_adapter import evolution_version as evolution_version_ctlfrom jiuwenswarm.server.utils.stream_utils import parse_ask_user_question_payload+from jiuwenswarm.server.utils.stream_content_sanitize import StreamProtocolBuffer, strip_inline_tool_protocolfrom jiuwenswarm.common.local_env_config import (is_enterprise,bind_agent_env_ns,@@ -14861,6 +14862,7 @@ class JiuWenSwarmDeepAdapter:accumulated_reasoning = ""had_assistant_output = Falseemitted_terminal_chat_final = False+ _protocol_buffer = StreamProtocolBuffer()usage_accumulator = {"input_tokens": 0,"output_tokens": 0,@@ -15450,7 +15452,7 @@ class JiuWenSwarmDeepAdapter:if run_failure is None:run_failure = self._run_failure(chunk)if not (hasattr(chunk, "type") and hasattr(chunk, "payload")):- parsed = self._parse_stream_chunk(chunk)+ parsed = self._parse_stream_chunk(chunk, _protocol_buffer=_protocol_buffer)# Only stamp provenance / inject split on new visible deltas.# A late user-round chat.final must keep the prior content kind.if isinstance(parsed, dict) and parsed.get("event_type") == "chat.delta":@@ -15570,6 +15572,9 @@ class JiuWenSwarmDeepAdapter:if isinstance(chunk.payload, dict)else str(chunk.payload))+ # Feed through the protocol buffer to suppress cross-chunk+ # inline-tool-protocol fragments before emitting the delta.+ content = _protocol_buffer.feed(content)delta_payload = self._stream_text_payload("chat.delta", content)if delta_payload is None:continue@@ -15624,7 +15629,9 @@ class JiuWenSwarmDeepAdapter:)accumulated_reasoning = ""if has_streamed_content:- parsed = self._parse_stream_chunk(chunk, _has_streamed_content=True)+ parsed = self._parse_stream_chunk(+ chunk, _has_streamed_content=True, _protocol_buffer=_protocol_buffer,+ )parsed = self._adapt_goal_intermediate_final(parsed)if parsed is not None:if should_skip_duplicate_ask_user(parsed):@@ -15645,7 +15652,7 @@ class JiuWenSwarmDeepAdapter:suppress_stream_after_hitl = Truecontinuecontinue- parsed = self._parse_stream_chunk(chunk)+ parsed = self._parse_stream_chunk(chunk, _protocol_buffer=_protocol_buffer)parsed = self._adapt_goal_intermediate_final(parsed)if parsed is not None:if should_skip_duplicate_ask_user(parsed):@@ -15718,6 +15725,17 @@ class JiuWenSwarmDeepAdapter:)emitted_chat_error = True+ # Flush any content still buffered in the protocol buffer (stream+ # ended without an answer chunk, or answer branch already flushed).+ _buffered = _protocol_buffer.flush()+ if _buffered and not hitl_pending_stream:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload({"event_type": "chat.delta", "content": _buffered}),+ is_complete=False,+ )+if accumulated_text and not hitl_pending_stream:# Same rule as _adapt_goal_intermediate_final: demote host# flush only when the flushed text belonged to a goal round.@@ -16012,9 +16030,18 @@ class JiuWenSwarmDeepAdapter:event_type: str,content: Any,) -> dict[str, Any] | None:- """Build a text event without discarding formatting-only chunks."""+ """Build a text event without discarding formatting-only chunks.++ Applies per-chunk ``strip_inline_tool_protocol`` so inline tool-protocol+ fragments (e.g. ``<tool_calls_begin>...``) that fall fully within one+ delta are stripped before reaching the client. Cross-chunk fragments+ are handled by the ``StreamProtocolBuffer`` at the call site.+ """if content is None or content == "":return None+ content = strip_inline_tool_protocol(content)+ if not content:+ return Nonereturn {"event_type": event_type, "content": content}@staticmethod@@ -16172,6 +16199,8 @@ class JiuWenSwarmDeepAdapter:content = str(payload)is_chunked = False+ content = strip_inline_tool_protocol(content)+if not content or not content.strip():return Nonediff --git a/jiuwenswarm/server/utils/stream_content_sanitize.py b/jiuwenswarm/server/utils/stream_content_sanitize.pynew file mode 100644index 0000000000..42b4d651aa--- /dev/null+++ b/jiuwenswarm/server/utils/stream_content_sanitize.py@@ -0,0 +1,330 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""+流式内容剥离工具:去除模型/网关写入 delta.content 的内联工具协议串。++已知泄漏格式(以实际样本为准):+ <tool_calls_begin><tool_call_begin>function<tool_sep>tool_name{"key": "val"}</tool_call_end></tool_calls_end>++若闭合标签不出现(流式截断),则按「平衡括号+EOF」策略处理。+供 stream_utils.py / interface_deep.py 复用。+"""+from __future__ import annotations++import os+import re+from typing import Optional++# ---------------------------------------------------------------------------+# 可配置常量+# ---------------------------------------------------------------------------++_OPEN_TAGS: tuple[str, ...] = (+ "<tool_calls_begin>",+ "<tool_call_begin>",+)+_CLOSE_TAGS: tuple[str, ...] = (+ "</tool_calls_end>",+ "</tool_call_end>",+)++_FUNC_SEP = "function<tool_sep>"++_TOOL_NAME_RE = re.compile(r"[A-Za-z0-9_]+")++_DEFAULT_TOOL_WHITELIST: Optional[frozenset[str]] = frozenset(+ [+ "todo_create",+ "todo_complete",+ "todo_insert",+ "todo_remove",+ "todo_list",+ ]+)+++def _build_whitelist() -> Optional[frozenset[str]]:+ mode = os.environ.get("STREAM_STRIP_INLINE_TOOLS", "whitelist").strip().lower()+ if mode == "all":+ return None+ return _DEFAULT_TOOL_WHITELIST+++_TOOL_WHITELIST: Optional[frozenset[str]] = _build_whitelist()++_PROTOCOL_INCOMPLETE = -1+_NOT_INLINE_TOOL_PROTOCOL = -2+++def _find_balanced_json_end(text: str, start: int) -> int:+ depth = 0+ in_string = False+ escape_next = False+ i = start+ n = len(text)+ while i < n:+ ch = text[i]+ if escape_next:+ escape_next = False+ elif in_string:+ if ch == "\\":+ escape_next = True+ elif ch == '"':+ in_string = False+ else:+ if ch == '"':+ in_string = True+ elif ch in "{[":+ depth += 1+ elif ch in "}]":+ depth -= 1+ if depth == 0:+ return i + 1+ i += 1+ return -1+++def _tool_name_allowed(name: str) -> bool:+ if _TOOL_WHITELIST is None:+ return True+ return name in _TOOL_WHITELIST+++def _tool_name_may_be_incomplete_prefix(name: str) -> bool:+ if _TOOL_WHITELIST is None:+ return False+ return any(tool.startswith(name) and tool != name for tool in _TOOL_WHITELIST)+++def _find_earliest_open_tag(text: str, from_pos: int = 0) -> tuple[int, str]:+ best_pos = -1+ best_tag = ""+ for tag in _OPEN_TAGS:+ pos = text.find(tag, from_pos)+ if pos != -1 and (best_pos == -1 or pos < best_pos):+ best_pos = pos+ best_tag = tag+ return best_pos, best_tag+++def _find_func_sep(text: str, from_pos: int = 0) -> int:+ return text.find(_FUNC_SEP, from_pos)+++def strip_inline_tool_protocol(text: str) -> str:+ """对完整文本,循环剥离所有已闭合或截断的内联工具协议段。"""+ if not text:+ return text++ result = text+ changed = True+ while changed:+ changed = False+ new_result = _strip_one_pass(result)+ if new_result != result:+ result = new_result+ changed = True+ return result+++def _strip_one_pass(text: str) -> str:+ pos = 0+ n = len(text)++ while pos < n:+ tag_pos, tag = _find_earliest_open_tag(text, pos)+ func_pos = _find_func_sep(text, pos)++ if tag_pos == -1 and func_pos == -1:+ break++ if tag_pos != -1 and (func_pos == -1 or tag_pos <= func_pos):+ anchor = tag_pos+ inner_func = _find_func_sep(text, anchor)+ if inner_func == -1:+ close_end = _find_close_tags(text, anchor + len(tag))+ if close_end != -1:+ text = text[:anchor] + text[close_end:]+ else:+ text = text[:anchor]+ return text++ name_start = inner_func + len(_FUNC_SEP)+ m = _TOOL_NAME_RE.match(text, name_start)+ if not m:+ pos = inner_func + 1+ continue+ tool_name = m.group(0)+ if not _tool_name_allowed(tool_name):+ if _tool_name_may_be_incomplete_prefix(tool_name):+ text = text[:anchor]+ return text+ pos = inner_func + 1+ continue++ json_start = m.end()+ if json_start >= n or text[json_start] != "{":+ pos = json_start+ continue++ json_end = _find_balanced_json_end(text, json_start)+ if json_end == -1:+ text = text[:anchor]+ return text++ close_end = _find_close_tags(text, json_end)+ seg_end = close_end if close_end != -1 else json_end+ text = text[:anchor] + text[seg_end:]+ return text++ else:+ anchor = func_pos+ name_start = anchor + len(_FUNC_SEP)+ m = _TOOL_NAME_RE.match(text, name_start)+ if not m:+ pos = anchor + 1+ continue+ tool_name = m.group(0)+ if not _tool_name_allowed(tool_name):+ if _tool_name_may_be_incomplete_prefix(tool_name):+ text = text[:anchor]+ return text+ pos = anchor + 1+ continue++ json_start = m.end()+ if json_start >= n or text[json_start] != "{":+ pos = json_start+ continue++ json_end = _find_balanced_json_end(text, json_start)+ if json_end == -1:+ text = text[:anchor]+ return text++ text = text[:anchor] + text[json_end:]+ return text++ return text+++def _find_close_tags(text: str, from_pos: int) -> int:+ pos = from_pos+ found_any = False+ while True:+ best_idx = -1+ best_tag = ""+ for tag in _CLOSE_TAGS:+ idx = text.find(tag, pos)+ if idx != -1 and (best_idx == -1 or idx < best_idx):+ best_idx = idx+ best_tag = tag+ if best_idx == -1:+ break+ gap = text[pos:best_idx]+ if found_any and gap.strip():+ break+ pos = best_idx + len(best_tag)+ found_any = True+ return pos if found_any else -1+++class StreamProtocolBuffer:+ """在流式累积文本时缓冲可能是协议开头的尾部,只暴露确认安全的前缀。"""++ def __init__(self) -> None:+ self._pending: str = ""++ def feed(self, new_text: str) -> str:+ combined = self._pending + new_text+ safe, self._pending = _split_safe_and_pending(combined)+ return safe++ def flush(self) -> str:+ if not self._pending:+ return ""+ result = strip_inline_tool_protocol(self._pending)+ self._pending = ""+ return result+++def _find_complete_protocol_end(text: str, anchor: int) -> int:+ n = len(text)++ matched_open = next((t for t in _OPEN_TAGS if text.startswith(t, anchor)), "")+ if matched_open:+ inner_func = _find_func_sep(text, anchor)+ if inner_func == -1:+ close_end = _find_close_tags(text, anchor + len(matched_open))+ return close_end if close_end != -1 else _PROTOCOL_INCOMPLETE+ name_start = inner_func + len(_FUNC_SEP)+ m = _TOOL_NAME_RE.match(text, name_start)+ if not m:+ return _PROTOCOL_INCOMPLETE if name_start >= n else _NOT_INLINE_TOOL_PROTOCOL+ tool_name = m.group(0)+ if not _tool_name_allowed(tool_name):+ return (+ _PROTOCOL_INCOMPLETE+ if _tool_name_may_be_incomplete_prefix(tool_name)+ else _NOT_INLINE_TOOL_PROTOCOL+ )+ json_start = m.end()+ if json_start >= n:+ return _PROTOCOL_INCOMPLETE+ if text[json_start] != "{":+ return _NOT_INLINE_TOOL_PROTOCOL+ json_end = _find_balanced_json_end(text, json_start)+ if json_end == -1:+ return _PROTOCOL_INCOMPLETE+ close_end = _find_close_tags(text, json_end)+ return close_end if close_end != -1 else json_end++ if text.startswith(_FUNC_SEP, anchor):+ name_start = anchor + len(_FUNC_SEP)+ m = _TOOL_NAME_RE.match(text, name_start)+ if not m:+ return _PROTOCOL_INCOMPLETE if name_start >= n else _NOT_INLINE_TOOL_PROTOCOL+ tool_name = m.group(0)+ if not _tool_name_allowed(tool_name):+ return (+ _PROTOCOL_INCOMPLETE+ if _tool_name_may_be_incomplete_prefix(tool_name)+ else _NOT_INLINE_TOOL_PROTOCOL+ )+ json_start = m.end()+ if json_start >= n:+ return _PROTOCOL_INCOMPLETE+ if text[json_start] != "{":+ return _NOT_INLINE_TOOL_PROTOCOL+ json_end = _find_balanced_json_end(text, json_start)+ return json_end if json_end != -1 else _PROTOCOL_INCOMPLETE++ return _NOT_INLINE_TOOL_PROTOCOL+++def _split_safe_and_pending(text: str) -> tuple[str, str]:+ safe_parts: list[str] = []+ pos = 0+ n = len(text)++ while pos < n:+ tag_pos, _ = _find_earliest_open_tag(text, pos)+ func_pos = _find_func_sep(text, pos)++ anchors = [p for p in (tag_pos, func_pos) if p != -1]+ if not anchors:+ safe_parts.append(text[pos:])+ return "".join(safe_parts), ""++ anchor = min(anchors)+ safe_parts.append(text[pos:anchor])++ end = _find_complete_protocol_end(text, anchor)+ if end == _PROTOCOL_INCOMPLETE:+ return "".join(safe_parts), text[anchor:]+ if end == _NOT_INLINE_TOOL_PROTOCOL:+ safe_parts.append(text[anchor:anchor + 1])+ pos = anchor + 1+ continue+ pos = end++ return "".join(safe_parts), ""diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.pyindex 9063d4248f..c8840384e1 100644--- a/jiuwenswarm/server/utils/stream_utils.py+++ b/jiuwenswarm/server/utils/stream_utils.py@@ -7,6 +7,11 @@ from __future__ import annotationsimport loggingfrom typing import Any+from jiuwenswarm.server.utils.stream_content_sanitize import (+ StreamProtocolBuffer,+ strip_inline_tool_protocol,+)+logger = logging.getLogger(__name__)@@ -25,7 +30,12 @@ def _propagate_stream_source_id(src_payload: Any) -> dict[str, Any]:return {}-def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> dict[str, Any] | None:+def parse_stream_chunk(+ chunk: Any,+ *,+ _has_streamed_content: bool = False,+ _protocol_buffer: StreamProtocolBuffer | None = None,+) -> dict[str, Any] | None:"""Parse agent output chunk to frontend-consumable payload dict.统一处理所有 SDK 输出格式,包括:@@ -45,24 +55,28 @@ def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> direturn Noneif isinstance(chunk, dict):- return _parse_dict_chunk(chunk, _has_streamed_content)+ return _parse_dict_chunk(chunk, _has_streamed_content, _protocol_buffer)if hasattr(chunk, "type") and hasattr(chunk, "payload"):- return _parse_typed_chunk(chunk, _has_streamed_content)+ return _parse_typed_chunk(chunk, _has_streamed_content, _protocol_buffer)if hasattr(chunk, "event_type"):return _parse_event_typed_chunk(chunk)if hasattr(chunk, "payload") and hasattr(chunk, "request_id"):- return _parse_response_chunk(chunk, _has_streamed_content)+ return _parse_response_chunk(chunk, _has_streamed_content, _protocol_buffer)return {"event_type": "chat.delta",- "content": str(chunk),+ "content": strip_inline_tool_protocol(str(chunk)),}-def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dict[str, Any] | None:+def _parse_dict_chunk(+ chunk: dict[str, Any],+ _has_streamed_content: bool,+ _protocol_buffer: StreamProtocolBuffer | None = None,+) -> dict[str, Any] | None:"""Parse dict chunk."""if "event_type" in chunk:if chunk.get("event_type") == "chat.tracer_agent":@@ -88,6 +102,12 @@ def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dicif "content" in chunk:content = chunk.get("content", "")+ if not content or not content.strip():+ return None+ if _protocol_buffer is not None:+ content = _protocol_buffer.feed(content)+ else:+ content = strip_inline_tool_protocol(content)if not content or not content.strip():return Nonereturn {@@ -113,6 +133,13 @@ def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dic"error": output.get("output", ""),}output = chunk.get("output", "")+ if not output or not output.strip():+ return None+ if _protocol_buffer is not None:+ _flushed = _protocol_buffer.flush()+ if _flushed:+ output = _flushed + output+ output = strip_inline_tool_protocol(output)if not output or not output.strip():return Nonereturn {@@ -132,7 +159,11 @@ def _serialize_chunk_recursive(obj: Any) -> Any:return _serialize_value(obj)-def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any] | None:+def _parse_typed_chunk(+ chunk: Any,+ _has_streamed_content: bool,+ _protocol_buffer: StreamProtocolBuffer | None = None,+) -> dict[str, Any] | None:"""Parse OutputSchema-like chunk with type and payload attributes."""chunk_type = getattr(chunk, "type", "")payload = getattr(chunk, "payload", {})@@ -287,6 +318,12 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Anyif isinstance(payload, dict)else str(payload))+ if not content or not content.strip():+ return None+ if _protocol_buffer is not None:+ content = _protocol_buffer.feed(content)+ else:+ content = strip_inline_tool_protocol(content)if not content or not content.strip():return Nonereturn {@@ -326,6 +363,14 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Anycontent = str(payload)is_chunked = False+ # Flush any pending buffered content from cross-chunk protocol fragments+ if _protocol_buffer is not None:+ _flushed = _protocol_buffer.flush()+ if _flushed:+ content = _flushed + content++ content = strip_inline_tool_protocol(content)+if not content or not content.strip():return None@@ -638,7 +683,11 @@ def _serialize_value(value: Any) -> Any:return value-def _parse_response_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any] | None:+def _parse_response_chunk(+ chunk: Any,+ _has_streamed_content: bool,+ _protocol_buffer: StreamProtocolBuffer | None = None,+) -> dict[str, Any] | None:"""Parse AgentResponseChunk-like object."""payload = getattr(chunk, "payload", None)@@ -663,15 +712,30 @@ def _parse_response_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str,"event_type": "chat.error","error": output.get("output", ""),}+ _out = payload.get("output", "")+ if _protocol_buffer is not None:+ _flushed = _protocol_buffer.flush()+ if _flushed:+ _out = _flushed + _out+ _out = strip_inline_tool_protocol(_out)+ if not _out or not _out.strip():+ return Nonereturn {"event_type": "chat.delta" if not _has_streamed_content else "chat.final",- "content": payload.get("output", ""),+ "content": _out,}if "content" in payload:+ _c = payload.get("content", "")+ if _protocol_buffer is not None:+ _c = _protocol_buffer.feed(_c)+ else:+ _c = strip_inline_tool_protocol(_c)+ if not _c or not _c.strip():+ return Nonereturn {"event_type": "chat.delta" if not _has_streamed_content else "chat.final",- "content": payload.get("content", ""),+ "content": _c,}return payload