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(runtime): keep the subagent frontend and backend changes in one branch
n9935770287ad45d41573e
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 275cfd23bc..03ba490df8 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -37,6 +37,9 @@"test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs","test:history-pagination": "tsc src/features/historyPagination.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/history-pagination --skipLibCheck --noEmitOnError && node --test tests/historyPagination.test.mjs","test:history-restore-source-skill": "esbuild src/features/historyRestore.ts --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/history-restore/historyRestore.mjs --define:import.meta.env.DEV=false --define:import.meta.env.VITE_API_BASE='\"\"' --define:import.meta.env.VITE_WS_BASE='\"\"' --define:import.meta.env.VITE_JIUWENSWARM_EDITION='\"personal\"' --define:window.__JIUWEN_WEB_TRANSPORT__='\"websocket\"' --define:window.__JIUWENSWARM_EDITION__='\"personal\"' && node --test tests/historyRestoreSourceSkill.test.mjs",+ "test:subagent-store": "esbuild src/stores/subagentStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/subagent-store/subagentStore.mjs && esbuild src/features/subagent/subagentNormalizer.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/subagent-store/subagentNormalizer.mjs && node --test tests/subagentStore.test.mjs",+ "test:subagent-status-presentation": "esbuild src/features/subagent/subagentStatusPresentation.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/subagent-status/subagentStatusPresentation.mjs && node --test tests/subagentStatusPresentation.test.mjs",+ "test:subagent-activity-presentation": "esbuild src/features/subagent/subagentActivityPresentation.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/subagent-activity/subagentActivityPresentation.mjs && node --test tests/subagentActivityPresentation.test.mjs","test:artifact-collection": "esbuild src/components/ArtifactsPanel/artifactCollection.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/artifact-collection/artifactCollection.mjs && node --test tests/artifactCollection.test.mjs","test:desktop-save": "esbuild src/utils/desktopSave.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/desktop-save/desktopSave.mjs && node --test tests/desktopSave.test.mjs","test:ask-user-submission": "tsc src/components/InteractionSlot/interactionSubmission.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/ask-user-submission --skipLibCheck --noEmitOnError && node --test tests/askUserSubmission.test.mjs",@@ -126,5 +129,8 @@"typescript": "^5.3.0","vite": "^5.0.0","vite-plugin-svgr": "^4.5.0"+ },+ "allowScripts": {+ "[email protected]": true}}diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 807c6e2dfd..fe58393872 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -63,6 +63,7 @@ import {useHarnessStore,useWorkspaceStore,useCronStore,+ useSubagentStore,} from './stores';import { chatRoutePath } from './multi-session/routing/route';import { useChatRoute } from './multi-session/routing/useChatRoute';@@ -495,6 +496,11 @@ function AppContent() {setHistoryPrepending(historyLoadingSessionsRef.current.has(sessionId));}, [sessionId]);+ useEffect(() => {+ if (!sessionId || sessionId === NEW_CONVERSATION_ID) return;+ useSubagentStore.getState().hydrateRuntime(sessionId);+ }, [sessionId]);+const {teamAreaExpanded,teamAreaActiveTab,@@ -716,18 +722,20 @@ function AppContent() {const proactiveNotificationMessage = useHarnessStore((s) => s.proactiveNotificationMessage);const setProactiveNotification = useHarnessStore((s) => s.setProactiveNotification);+ const subagentCount = useSubagentStore((s) => Object.keys(s.runtimes[sessionId]?.subagentsById ?? {}).length);const toolPanelHasContent = useMemo(() => {const hasMessages = messages.length > 0;const hasCodeEnvironment = sessionProject?.work_mode === 'code' && sessionId !== NEW_CONVERSATION_ID;+ const hasSubagents = subagentCount > 0;switch (mode) {case 'auto_harness':return Boolean(extensionReady?.runtimePath) || hasMessages;case 'team':- return isRestoringTeamHistory || teamTaskEvents.length > 0 || teamTasks.length > 0 || teamMembers.length > 0 || hasMessages || hasCodeEnvironment;+ return isRestoringTeamHistory || teamTaskEvents.length > 0 || teamTasks.length > 0 || teamMembers.length > 0 || hasMessages || hasCodeEnvironment || hasSubagents;default:- return todos.length > 0 || hasMessages || hasCodeEnvironment;+ return todos.length > 0 || hasMessages || hasCodeEnvironment || hasSubagents;}- }, [mode, todos.length, teamTaskEvents.length, teamTasks.length, teamMembers.length, extensionReady?.runtimePath, messages.length, isRestoringTeamHistory, sessionId, sessionProject?.work_mode]);+ }, [mode, todos.length, teamTaskEvents.length, teamTasks.length, teamMembers.length, extensionReady?.runtimePath, messages.length, isRestoringTeamHistory, sessionId, sessionProject?.work_mode, subagentCount]);// 单 agent 模式同样复用集群模式的展开布局(百分比宽度 + 可拖拽分割线),// 避免右侧面板与聊天面板平分空间导致宽度与集群模式不一致;auto_harness 走收起态分支。const isTeamAreaExpanded = mode !== 'auto_harness' && teamAreaExpanded && toolPanelHasContent;diff --git a/jiuwenswarm/channels/web/frontend/src/assets/back.svg b/jiuwenswarm/channels/web/frontend/src/assets/back.svgnew file mode 100644index 0000000000..54a3d2152c--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/back.svg@@ -0,0 +1,4 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none">+ <rect id="返回" width="16" height="16" x="0" y="0" fill="none"/>+ <path id="形状结合" d="M8.77467 1.46407C9.04375 1.7275 9.07238 2.14388 8.85765 2.43979L4.159 7.25L13.75 7.25C14.1642 7.25 14.5 7.58579 14.5 8C14.5 8.41421 14.1642 8.75 13.75 8.75L3.947 8.75L8.72638 13.4662C8.9944 13.7307 9.02137 14.1472 8.80546 14.4422C8.54097 14.7102 8.05241 14.8218 7.75736 14.6059L1.7232 8.66258C1.45593 8.39883 1.42826 7.98376 1.64253 7.68872L7.71407 1.47533C8.00384 1.17934 8.47869 1.1743 8.77467 1.46407Z" fill="currentColor" fill-rule="evenodd"/>+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/collapse.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/collapse.svgnew file mode 100644index 0000000000..eb69c0fa7b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/collapse.svg@@ -0,0 +1,5 @@+<svg viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="12.000000" height="12.000000" fill="none">+ <rect id="框类/收起" width="12.000000" height="12.000000" x="0.000000" y="0.000000" />+ <path id="路径" d="M4.725 0C5.01495 0 5.25 0.23505 5.25 0.525L5.25 4.875C5.25 5.08211 5.08211 5.25 4.875 5.25C4.66789 5.25 4.5 5.08211 4.5 4.875L4.5 0.75L0.375 0.75C0.190905 0.75 0.0377936 0.617344 0.00604177 0.442407L0 0.375C0 0.167893 0.167893 0 0.375 0L4.725 0Z" fill="currentColor" fill-rule="nonzero" transform="matrix(-0.707107,0.707107,-0.707107,-0.707107,9.71289,4.5)" />+ <path id="路径" d="M5.25 0.525L5.25 4.875C5.25 5.08211 5.08211 5.25 4.875 5.25C4.66789 5.25 4.5 5.08211 4.5 4.875L4.5 0.75L0.375 0.75C0.190905 0.75 0.0377936 0.617344 0.00604177 0.442407L0 0.375C0 0.167893 0.167893 0 0.375 0L4.725 0C5.01495 0 5.25 0.23505 5.25 0.525Z" fill="currentColor" fill-rule="nonzero" stroke="none" stroke-width="0.300000" transform="matrix(-0.707107,0.707107,-0.707107,-0.707107,9.71289,4.5)" />+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/loading.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/loading.svgnew file mode 100644index 0000000000..3e04b0a316--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/loading.svg@@ -0,0 +1,26 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16.000000" height="16.000000" fill="none">+ <mask id="mask_15" width="14.000000" height="14.000000" x="1.000000" y="1.000000" maskUnits="userSpaceOnUse">+ <g filter="url(#pixso_custom_mask_type_alpha)">+ <path id="Stroke-2" d="M8 1C8.44043 1 8.79747 1.35704 8.79747 1.79747C8.79747 2.2379 8.44043 2.59494 8 2.59494C5.01486 2.59494 2.59494 5.01486 2.59494 8C2.59494 10.9851 5.01486 13.4051 8 13.4051C10.9851 13.4051 13.4051 10.9851 13.4051 8C13.4051 7.55957 13.7621 7.20253 14.2025 7.20253C14.643 7.20253 15 7.55957 15 8C15 11.866 11.866 15 8 15C4.134 15 1 11.866 1 8C1 4.134 4.134 1 8 1Z" fill="url(#paint_linear_9)" fill-rule="nonzero" />+ </g>+ </mask>+ <defs>+ <clipPath id="clipPath_11">+ <rect width="16.000000" height="16.000000" x="0.000000" y="0.000000" fill="rgb(255,255,255)" />+ </clipPath>+ <linearGradient id="paint_linear_9" x1="18.9547691" x2="4.75360775" y1="8.00000095" y2="0.999997139" gradientUnits="userSpaceOnUse">+ <stop stop-color="rgb(255,255,255)" offset="0.00095607515" stop-opacity="0" />+ <stop stop-color="rgb(255,254.745,254.745)" offset="0.975277901" stop-opacity="1" />+ </linearGradient>+ <filter id="pixso_custom_mask_type_alpha">+ <feColorMatrix type="matrix" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 " />+ </filter>+ </defs>+ <rect id="加载" width="16.000000" height="16.000000" x="0.000000" y="0.000000" />+ <g id="loading黑" clip-path="url(#clipPath_11)">+ <rect id="loading黑" width="16.000000" height="16.000000" x="0.000000" y="0.000000" />+ <g id="蒙版" mask="url(#mask_15)">+ <path id="Fill-1" d="M0 16L16 16L16 0L0 0L0 16Z" fill="currentColor" fill-rule="evenodd" />+ </g>+ </g>+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/processing.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/processing.svgnew file mode 100644index 0000000000..15588c66b1--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/processing.svg@@ -0,0 +1,12 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16.000000" height="16.000000" fill="none">+ <rect id="正在进行" width="16.000000" height="16.000000" x="0.000000" y="0.000000" />+ <g id="ic_gts_loading-加载/base/ic_gts_loading">+ <path id="path1" d="M0.501823 7.99389C0.501823 6.8222 0.497722 5.6505 0.501823 4.47881C0.499465 3.91183 0.569153 3.34684 0.709212 2.79743C1.0162 1.63452 1.7737 0.944393 2.93543 0.676661C3.51794 0.550805 4.11291 0.491839 4.70879 0.500907C6.95571 0.500907 9.20282 0.500907 11.4501 0.500907C12.0177 0.497384 12.5836 0.562295 13.1356 0.694236C14.3325 0.98716 15.0507 1.74525 15.3243 2.93803C15.4473 3.50176 15.5061 4.07761 15.4995 4.65456C15.4995 6.9257 15.4995 9.19703 15.4995 11.4686C15.5026 12.0306 15.4379 12.591 15.3068 13.1376C15.0138 14.3351 14.2522 15.0498 13.0594 15.3234C12.4769 15.4488 11.882 15.5078 11.2861 15.4992C9.04855 15.4992 6.8112 15.4992 4.57404 15.4992C4.00215 15.5038 3.43176 15.4399 2.87509 15.3088C1.67293 15.0159 0.951167 14.2543 0.678163 13.0556C0.538731 12.4463 0.501823 11.8353 0.501823 11.219C0.501823 10.1441 0.501823 9.06912 0.501823 7.99389Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path1" d="M0.501823 4.47881C0.499465 3.91183 0.569153 3.34684 0.709212 2.79743C1.0162 1.63452 1.7737 0.944393 2.93543 0.676661C3.51794 0.550805 4.11291 0.491839 4.70879 0.500907C6.95571 0.500907 9.20282 0.500907 11.4501 0.500907C12.0177 0.497384 12.5836 0.562295 13.1356 0.694236C14.3325 0.98716 15.0507 1.74525 15.3243 2.93803C15.4473 3.50176 15.5061 4.07761 15.4995 4.65456C15.4995 6.9257 15.4995 9.19703 15.4995 11.4686C15.5026 12.0306 15.4379 12.591 15.3068 13.1376C15.0138 14.3351 14.2522 15.0498 13.0594 15.3234C12.4769 15.4488 11.882 15.5078 11.2861 15.4992C9.04855 15.4992 6.8112 15.4992 4.57404 15.4992C4.00215 15.5038 3.43176 15.4399 2.87509 15.3088C1.67293 15.0159 0.951167 14.2543 0.678163 13.0556C0.538731 12.4463 0.501823 11.8353 0.501823 11.219C0.501823 10.1441 0.501823 9.06912 0.501823 7.99389C0.501823 6.8222 0.497722 5.6505 0.501823 4.47881Z" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.888889" />+ <path id="path2" d="M0.501823 4.47881C0.499465 3.91183 0.569153 3.34684 0.709212 2.79743C1.0162 1.63452 1.7737 0.944393 2.93543 0.676661C3.51794 0.550805 4.11291 0.491839 4.70879 0.500907C6.95571 0.500907 9.20282 0.500907 11.4501 0.500907C12.0177 0.497384 12.5836 0.562295 13.1356 0.694236C14.3325 0.98716 15.0507 1.74525 15.3243 2.93803C15.4473 3.50176 15.5061 4.07761 15.4995 4.65456C15.4995 6.9257 15.4995 9.19703 15.4995 11.4686C15.5026 12.0306 15.4379 12.591 15.3068 13.1376C15.0138 14.3351 14.2522 15.0498 13.0594 15.3234C12.4769 15.4488 11.882 15.5078 11.2861 15.4992C9.04855 15.4992 6.8112 15.4992 4.57404 15.4992C4.00215 15.5038 3.43176 15.4399 2.87509 15.3088C1.67293 15.0159 0.951167 14.2543 0.678163 13.0556C0.538731 12.4463 0.501823 11.8353 0.501823 11.219C0.501823 10.1441 0.501823 9.06912 0.501823 7.99389C0.501823 6.8222 0.497722 5.6505 0.501823 4.47881Z" opacity="0.200000003" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.888889" />+ <circle id="path3" cx="8" cy="8" r="8" fill="rgb(255,255,255)" fill-opacity="0" />+ <path id="path4" d="M12 8L15 8M1 8L4 8M8 12L8 15M8 1L8 4M5.17157 10.8284L3.05025 12.9497M12.9497 3.05025L10.8284 5.17157M5.17157 5.17157L3.05025 3.05025M12.9497 12.9497L10.8284 10.8284" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="0.888889" />+ <path id="path5" d="M8.00033 11.666C8.18442 11.666 8.33366 11.8153 8.33366 11.9993L8.33366 14.9993C8.33366 15.1834 8.18442 15.3327 8.00033 15.3327C7.81623 15.3327 7.66699 15.1834 7.66699 14.9993L7.66699 11.9993C7.66699 11.8153 7.81623 11.666 8.00033 11.666ZM4.9362 10.5921C5.06637 10.4619 5.27743 10.4619 5.4076 10.5921C5.53778 10.7222 5.53778 10.9333 5.4076 11.0635L3.28628 13.1848C3.15611 13.315 2.94505 13.315 2.81488 13.1848C2.6847 13.0546 2.6847 12.8436 2.81488 12.7134L4.9362 10.5921ZM10.5931 10.5921C10.7232 10.4619 10.9343 10.4619 11.0645 10.5921L13.1858 12.7134C13.3159 12.8436 13.3159 13.0546 13.1858 13.1848C13.0556 13.315 12.8445 13.315 12.7144 13.1848L10.5931 11.0635C10.4629 10.9333 10.4629 10.7222 10.5931 10.5921ZM15.0003 7.66602C15.1844 7.66602 15.3337 7.81525 15.3337 7.99935C15.3337 8.18344 15.1844 8.33268 15.0003 8.33268L12.0003 8.33268C11.8162 8.33268 11.667 8.18344 11.667 7.99935C11.667 7.81525 11.8162 7.66602 12.0003 7.66602L15.0003 7.66602ZM4.00033 7.66602C4.18442 7.66602 4.33366 7.81525 4.33366 7.99935C4.33366 8.18344 4.18442 8.33268 4.00033 8.33268L1.00033 8.33268C0.816231 8.33268 0.666992 8.18344 0.666992 7.99935C0.666992 7.81525 0.816231 7.66602 1.00033 7.66602L4.00033 7.66602ZM12.7144 2.8139C12.8445 2.68372 13.0556 2.68372 13.1858 2.8139C13.3159 2.94407 13.3159 3.15513 13.1858 3.2853L11.0645 5.40662C10.9343 5.5368 10.7232 5.5368 10.5931 5.40662C10.4629 5.27645 10.4629 5.06539 10.5931 4.93522L12.7144 2.8139ZM2.81488 2.8139C2.94505 2.68372 3.15611 2.68372 3.28628 2.8139L5.4076 4.93522C5.53778 5.06539 5.53778 5.27645 5.4076 5.40662C5.27743 5.5368 5.06637 5.5368 4.9362 5.40662L2.81488 3.2853C2.6847 3.15513 2.6847 2.94407 2.81488 2.8139ZM8.00033 0.666016C8.18442 0.666016 8.33366 0.815254 8.33366 0.999349L8.33366 3.99935C8.33366 4.18344 8.18442 4.33268 8.00033 4.33268C7.81623 4.33268 7.66699 4.18344 7.66699 3.99935L7.66699 0.999349C7.66699 0.815254 7.81623 0.666016 8.00033 0.666016Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path5" d="M8.33366 11.9993L8.33366 14.9993C8.33366 15.1834 8.18442 15.3327 8.00033 15.3327C7.81623 15.3327 7.66699 15.1834 7.66699 14.9993L7.66699 11.9993C7.66699 11.8153 7.81623 11.666 8.00033 11.666C8.18442 11.666 8.33366 11.8153 8.33366 11.9993ZM5.4076 10.5921C5.53778 10.7222 5.53778 10.9333 5.4076 11.0635L3.28628 13.1848C3.15611 13.315 2.94505 13.315 2.81488 13.1848C2.6847 13.0546 2.6847 12.8436 2.81488 12.7134L4.9362 10.5921C5.06637 10.4619 5.27743 10.4619 5.4076 10.5921ZM11.0645 10.5921L13.1858 12.7134C13.3159 12.8436 13.3159 13.0546 13.1858 13.1848C13.0556 13.315 12.8445 13.315 12.7144 13.1848L10.5931 11.0635C10.4629 10.9333 10.4629 10.7222 10.5931 10.5921C10.7232 10.4619 10.9343 10.4619 11.0645 10.5921ZM15.3337 7.99935C15.3337 8.18344 15.1844 8.33268 15.0003 8.33268L12.0003 8.33268C11.8162 8.33268 11.667 8.18344 11.667 7.99935C11.667 7.81525 11.8162 7.66602 12.0003 7.66602L15.0003 7.66602C15.1844 7.66602 15.3337 7.81525 15.3337 7.99935ZM4.33366 7.99935C4.33366 8.18344 4.18442 8.33268 4.00033 8.33268L1.00033 8.33268C0.816231 8.33268 0.666992 8.18344 0.666992 7.99935C0.666992 7.81525 0.816231 7.66602 1.00033 7.66602L4.00033 7.66602C4.18442 7.66602 4.33366 7.81525 4.33366 7.99935ZM13.1858 2.8139C13.3159 2.94407 13.3159 3.15513 13.1858 3.2853L11.0645 5.40662C10.9343 5.5368 10.7232 5.5368 10.5931 5.40662C10.4629 5.27645 10.4629 5.06539 10.5931 4.93522L12.7144 2.8139C12.8445 2.68372 13.0556 2.68372 13.1858 2.8139ZM3.28628 2.8139L5.4076 4.93522C5.53778 5.06539 5.53778 5.27645 5.4076 5.40662C5.27743 5.5368 5.06637 5.5368 4.9362 5.40662L2.81488 3.2853C2.6847 3.15513 2.6847 2.94407 2.81488 2.8139C2.94505 2.68372 3.15611 2.68372 3.28628 2.8139ZM8.33366 0.999349L8.33366 3.99935C8.33366 4.18344 8.18442 4.33268 8.00033 4.33268C7.81623 4.33268 7.66699 4.18344 7.66699 3.99935L7.66699 0.999349C7.66699 0.815254 7.81623 0.666016 8.00033 0.666016C8.18442 0.666016 8.33366 0.815254 8.33366 0.999349Z" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-linejoin="round" stroke-width="0.888889" />+ </g>+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/success.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/success.svgnew file mode 100644index 0000000000..a15a55e539--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/success.svg@@ -0,0 +1,8 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16.000000" height="16.000000" fill="none">+ <rect id="成功" width="16.000000" height="16.000000" x="0.000000" y="0.000000" />+ <rect id="ic_public_success-成功/base/ic_public_success" width="16.000000" height="16.000000" x="0.000000" y="0.000000" fill="none" />+ <g id="组合 143939">+ <ellipse id="path3" rx="6.000189" ry="6.000000" cx="8.00018883" cy="8" stroke="currentColor" stroke-width="0.981849" />+ <path id="path6" d="M4.86328 7.72751L7.20336 10.1821L11.3517 5.81836" fill-rule="nonzero" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="0.981849" />+ </g>+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/team-members.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/team-members.svgnew file mode 100644index 0000000000..d3ac8b2b82--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/team-members.svg@@ -0,0 +1,4 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16.000000" height="16.000000" fill="none">+ <rect id="Team 成员" width="15.999999" height="16.000000" x="0.000000" y="0.000000" fill="none" />+ <path id="形状结合" d="M7.99605 1.59961C9.33224 1.59961 10.4701 2.31396 10.9611 3.51525C11.152 3.97176 11.2485 4.48984 11.2485 5.06304C11.2485 6.55559 10.9932 7.51025 10.3333 8.57391L10.2196 8.75231L10.0723 8.97161L10.0978 8.9846L10.5788 9.1959C11.7851 9.71984 12.842 10.5791 13.5827 11.5946C13.7782 11.8469 13.9329 12.2707 13.9329 12.6375C13.9329 13.5259 13.2576 14.2735 12.3787 14.3853L12.2678 14.3959L12.1531 14.3996L3.84613 14.3996C2.86574 14.3996 2.06628 13.6063 2.06628 12.6375C2.06628 12.2316 2.23349 11.8411 2.5229 11.4716C3.22384 10.5689 4.14477 9.81727 5.19309 9.31774L5.83128 9.03517L5.94228 8.98361L5.81407 8.7942L5.69875 8.61796C5.63909 8.52425 5.58545 8.4355 5.53369 8.34466C5.4129 8.13271 5.30903 7.91999 5.21892 7.69865C4.90612 6.93991 4.75013 6.07292 4.75013 5.04328C4.75013 2.95863 6.09152 1.59961 7.99605 1.59961ZM7.99605 2.77881C6.75194 2.77881 5.95013 3.61534 5.95013 5.04328C5.95013 5.9224 6.07727 6.64015 6.33209 7.25824C6.40352 7.4337 6.48501 7.60058 6.5807 7.76851C6.62244 7.84176 6.6662 7.91419 6.71602 7.99244L6.86494 8.21782L7.00695 8.42841L7.06264 8.51751C7.38655 9.07177 7.26146 9.57898 6.71555 9.91194L6.65181 9.9493L6.58239 9.98698L6.50783 10.0248L6.21974 10.1565L6.10017 10.2086L5.70872 10.3826C4.83525 10.8005 4.06153 11.434 3.47541 12.1888C3.36615 12.3283 3.26628 12.5367 3.26628 12.6375C3.26628 12.9066 3.45523 13.1401 3.70575 13.2032L3.7755 13.2161L3.84613 13.2204L12.1531 13.2204C12.4691 13.2204 12.7329 12.9559 12.7329 12.6375C12.7329 12.5431 12.6627 12.3539 12.6178 12.2954C11.9917 11.4374 11.1009 10.712 10.0936 10.2744L9.49611 10.0097C9.44087 9.98304 9.40402 9.96298 9.36491 9.93986L9.28399 9.89051L9.20525 9.83844C8.85693 9.59224 8.70509 9.25946 8.78476 8.88389L8.80952 8.78913L8.84388 8.69377L8.85544 8.66653L8.8736 8.6294L8.89679 8.58868L9.20123 8.12822C9.82731 7.17546 10.0485 6.41052 10.0485 5.06303C10.0485 4.64187 9.98151 4.27514 9.84935 3.95917C9.54379 3.21152 8.84872 2.77881 7.99605 2.77881ZM3.52293 3.91409C3.80122 3.75226 4.15819 3.84634 4.32028 4.12427C4.45521 4.35564 4.41327 4.64458 4.22733 4.83011L4.16727 4.88251L4.1098 4.92072C3.87147 5.05932 3.69626 5.26372 3.58555 5.53916C3.50019 5.7482 3.456 5.99641 3.456 6.27393C3.456 6.91984 3.55537 7.4228 3.75936 7.85921L3.83124 8.00231L3.89343 8.11285L3.96197 8.22376L4.14403 8.49962C4.3228 8.77768 4.23437 9.14841 3.9493 9.31612L3.90306 9.34217L3.79064 9.39871L3.47578 9.53991C2.81511 9.83226 2.26227 10.2939 1.86256 10.851C1.80988 10.9285 1.76593 11.0481 1.76593 11.13C1.76593 11.1649 1.76976 11.1991 1.77693 11.2312L1.79012 11.2776L1.81095 11.3278C1.95141 11.6173 1.83024 11.9657 1.54037 12.1059C1.25056 12.2461 0.90179 12.1252 0.761358 11.8357C0.654897 11.6163 0.599609 11.3759 0.599609 11.13C0.599609 10.7872 0.709605 10.4731 0.906061 10.1846C1.35268 9.56175 1.92982 9.04061 2.62095 8.66348L2.81028 8.56428L2.80444 8.55473C2.54588 8.0741 2.38609 7.5448 2.32198 6.92713L2.30242 6.69128L2.29245 6.47154L2.28968 6.27393C2.28968 5.84719 2.36204 5.45081 2.50439 5.10227C2.71108 4.58795 3.06102 4.1827 3.52293 3.91409ZM11.6789 4.12427C11.841 3.84634 12.198 3.75226 12.4763 3.91409C12.9382 4.1827 13.2881 4.58795 13.4947 5.10192C13.5965 5.35117 13.6625 5.62478 13.692 5.91755L13.7052 6.09546L13.7095 6.27486L13.7067 6.4725C13.6878 7.13636 13.5731 7.70224 13.3595 8.21005L13.2748 8.39783L13.1883 8.56494L13.3961 8.6732C13.9424 8.97404 14.4173 9.36558 14.8126 9.82705L14.9571 10.0033L15.0941 10.1859C15.2896 10.4731 15.3996 10.7872 15.3996 11.13C15.3996 11.3759 15.3443 11.6163 15.2379 11.8357C15.0974 12.1252 14.7487 12.2461 14.4588 12.1059C14.2174 11.9892 14.0905 11.7256 14.1417 11.4672L14.1601 11.3969L14.2078 11.2811C14.2247 11.2331 14.2333 11.1824 14.2333 11.13C14.2333 11.0481 14.1893 10.9285 14.1376 10.8524C13.8166 10.4049 13.3965 10.0182 12.9022 9.73242L12.7134 9.63005L12.5231 9.53977L12.2072 9.39809C12.1434 9.36776 12.094 9.34204 12.0499 9.31612C11.8126 9.17651 11.709 8.89335 11.7911 8.63607L11.8182 8.56667L11.8556 8.49894L12.0365 8.22493L12.1051 8.11406L12.1674 8.00342C12.4205 7.53281 12.5432 6.99161 12.5432 6.27393C12.5432 5.99641 12.499 5.7482 12.4135 5.53882C12.3327 5.33764 12.2173 5.17433 12.0693 5.04778L11.9766 4.97626L11.8859 4.91854L11.8286 4.88009C11.5961 4.70295 11.5305 4.37877 11.6789 4.12427Z" fill="currentColor" fill-rule="evenodd" />+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/assets/subagent/waiting.svg b/jiuwenswarm/channels/web/frontend/src/assets/subagent/waiting.svgnew file mode 100644index 0000000000..0608ffcfa7--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/assets/subagent/waiting.svg@@ -0,0 +1,17 @@+<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16.000000" height="16.000000" fill="none">+ <rect id="等待" width="16.000000" height="16.000000" x="0.000000" y="0.000000" />+ <g id="ic_digital_office_waite-等候/base/ic_digital_office_waite">+ <path id="path1" d="M1.90773 7.99503C1.90773 7.04303 1.9044 6.09103 1.90773 5.13903C1.90582 4.67836 1.96244 4.21931 2.07624 3.77291C2.32566 2.82805 2.94113 2.26732 3.88504 2.04979C4.35833 1.94753 4.84174 1.89962 5.32589 1.90699C7.15151 1.90699 8.97729 1.90699 10.8032 1.90699C11.2644 1.90412 11.7242 1.95686 12.1727 2.06407C13.1452 2.30207 13.7287 2.91801 13.951 3.88715C14.051 4.34518 14.0987 4.81305 14.0933 5.28183C14.0933 7.12713 14.0933 8.97258 14.0933 10.8182C14.0958 11.2749 14.0433 11.7302 13.9367 12.1743C13.6987 13.1473 13.0799 13.728 12.1108 13.9503C11.6375 14.0521 11.1541 14.1001 10.6699 14.0931C8.85194 14.0931 7.0341 14.0931 5.21641 14.0931C4.75175 14.0969 4.28831 14.0449 3.83601 13.9384C2.85926 13.7004 2.27282 13.0816 2.05101 12.1077C1.93772 11.6126 1.90773 11.1162 1.90773 10.6154C1.90773 9.74211 1.90773 8.86865 1.90773 7.99503Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path1" d="M1.90773 5.13903C1.90582 4.67836 1.96244 4.21931 2.07624 3.77291C2.32566 2.82805 2.94113 2.26732 3.88504 2.04979C4.35833 1.94753 4.84174 1.89962 5.32589 1.90699C7.15151 1.90699 8.97729 1.90699 10.8032 1.90699C11.2644 1.90412 11.7242 1.95686 12.1727 2.06407C13.1452 2.30207 13.7287 2.91801 13.951 3.88715C14.051 4.34518 14.0987 4.81305 14.0933 5.28183C14.0933 7.12713 14.0933 8.97258 14.0933 10.8182C14.0958 11.2749 14.0433 11.7302 13.9367 12.1743C13.6987 13.1473 13.0799 13.728 12.1108 13.9503C11.6375 14.0521 11.1541 14.1001 10.6699 14.0931C8.85194 14.0931 7.0341 14.0931 5.21641 14.0931C4.75175 14.0969 4.28831 14.0449 3.83601 13.9384C2.85926 13.7004 2.27282 13.0816 2.05101 12.1077C1.93772 11.6126 1.90773 11.1162 1.90773 10.6154C1.90773 9.74211 1.90773 8.86865 1.90773 7.99503C1.90773 7.04303 1.9044 6.09103 1.90773 5.13903Z" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.720417" />+ <path id="path2" d="M1.90773 5.13903C1.90582 4.67836 1.96244 4.21931 2.07624 3.77291C2.32566 2.82805 2.94113 2.26732 3.88504 2.04979C4.35833 1.94753 4.84174 1.89962 5.32589 1.90699C7.15151 1.90699 8.97729 1.90699 10.8032 1.90699C11.2644 1.90412 11.7242 1.95686 12.1727 2.06407C13.1452 2.30207 13.7287 2.91801 13.951 3.88715C14.051 4.34518 14.0987 4.81305 14.0933 5.28183C14.0933 7.12713 14.0933 8.97258 14.0933 10.8182C14.0958 11.2749 14.0433 11.7302 13.9367 12.1743C13.6987 13.1473 13.0799 13.728 12.1108 13.9503C11.6375 14.0521 11.1541 14.1001 10.6699 14.0931C8.85194 14.0931 7.0341 14.0931 5.21641 14.0931C4.75175 14.0969 4.28831 14.0449 3.83601 13.9384C2.85926 13.7004 2.27282 13.0816 2.05101 12.1077C1.93772 11.6126 1.90773 11.1162 1.90773 10.6154C1.90773 9.74211 1.90773 8.86865 1.90773 7.99503C1.90773 7.04303 1.9044 6.09103 1.90773 5.13903Z" opacity="0.200000003" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.720417" />+ <circle id="path3" cx="8" cy="8" r="6.5" fill="rgb(255,255,255)" fill-opacity="0" />+ <path id="path4" d="M11.0139 6.42773C11.4462 6.74293 11.7015 7.25389 11.7015 8.07533C11.7015 8.20876 11.6969 8.34354 11.6876 8.47917C11.8648 8.39966 12.0617 8.35572 12.269 8.35572C13.0525 8.35572 13.6876 8.9834 13.6876 9.75769C13.6876 10.532 13.0525 11.1596 12.269 11.1596C11.8251 11.1596 11.354 11.0864 11.0554 10.8434C10.2854 12.4225 8.83306 13.6832 6.73624 13.6832C3.47334 13.6832 2.05469 10.9109 2.05469 8.35572C2.05469 7.34982 2.36554 6.76606 2.90025 6.42795L11.0139 6.42773Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path4" d="M11.7015 8.07533C11.7015 8.20876 11.6969 8.34354 11.6876 8.47917C11.8648 8.39966 12.0617 8.35572 12.269 8.35572C13.0525 8.35572 13.6876 8.9834 13.6876 9.75769C13.6876 10.532 13.0525 11.1596 12.269 11.1596C11.8251 11.1596 11.354 11.0864 11.0554 10.8434C10.2854 12.4225 8.83306 13.6832 6.73624 13.6832C3.47334 13.6832 2.05469 10.9109 2.05469 8.35572C2.05469 7.34982 2.36554 6.76606 2.90025 6.42795L11.0139 6.42773C11.4462 6.74293 11.7015 7.25389 11.7015 8.07533Z" fill-rule="nonzero" stroke="currentColor" stroke-linejoin="round" stroke-width="0.720417" />+ <line id="path5" x1="1.90625" x2="13.8229179" y1="13.6835938" y2="13.6835938" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="0.720417" />+ <path id="path6" d="M4.70462 2.44727C4.1434 2.80838 3.95632 3.16949 4.1434 3.5306C4.42401 4.07227 4.87778 4.1991 4.98523 4.61393C5.05687 4.89049 4.86979 5.16132 4.42401 5.42643M7.23013 2.44727C6.66891 2.80838 6.48183 3.16949 6.66891 3.5306C6.94952 4.07227 7.40329 4.1991 7.51075 4.61393C7.58238 4.89049 7.39531 5.16132 6.94952 5.42643M9.46525 2.44727C8.90403 2.80838 8.71695 3.16949 8.90403 3.5306C9.18464 4.07227 9.63841 4.1991 9.74587 4.61393C9.8175 4.89049 9.63043 5.16132 9.18464 5.42643" fill-rule="evenodd" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="0.720417" />+ <path id="path7" d="M13.8226 13.5469C13.8974 13.5469 13.958 13.6075 13.958 13.6823C13.958 13.7488 13.9101 13.8041 13.8469 13.8155L13.8226 13.8177L1.90592 13.8177C1.83114 13.8177 1.77051 13.7571 1.77051 13.6823C1.77051 13.6158 1.81841 13.5605 1.88158 13.5491L1.90592 13.5469L13.8226 13.5469Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path7" d="M13.958 13.6823C13.958 13.7488 13.9101 13.8041 13.8469 13.8155L13.8226 13.8177L1.90592 13.8177C1.83114 13.8177 1.77051 13.7571 1.77051 13.6823C1.77051 13.6158 1.81841 13.5605 1.88158 13.5491L1.90592 13.5469L13.8226 13.5469C13.8974 13.5469 13.958 13.6075 13.958 13.6823Z" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.720417" />+ <path id="path8" d="M4.63143 2.33405C4.69433 2.29359 4.77812 2.31176 4.81859 2.37466C4.85905 2.43755 4.84087 2.52134 4.77798 2.56181C4.26831 2.88975 4.11598 3.18379 4.26372 3.46898C4.34016 3.61653 4.43316 3.73796 4.55901 3.86562L4.66992 3.97275L4.80911 4.10446C4.97697 4.26833 5.07011 4.40188 5.11641 4.58064C5.20684 4.92978 4.98484 5.25117 4.49331 5.54349C4.42903 5.58172 4.34593 5.5606 4.3077 5.49632C4.26948 5.43204 4.2906 5.34894 4.35488 5.31071C4.75492 5.07281 4.90706 4.85254 4.85423 4.64856C4.82623 4.54047 4.77011 4.45244 4.66266 4.34116L4.60423 4.28334L4.38291 4.07249C4.37657 4.06624 4.37092 4.06061 4.36614 4.05575C4.22253 3.91008 4.1134 3.76759 4.02324 3.59356C3.79683 3.15652 4.01865 2.72834 4.63143 2.33405ZM7.15694 2.33405C7.21984 2.29359 7.30363 2.31176 7.3441 2.37466C7.38457 2.43755 7.36639 2.52134 7.30349 2.56181C6.79382 2.88975 6.64149 3.18379 6.78923 3.46898C6.86568 3.61653 6.95868 3.73796 7.08452 3.86562L7.19543 3.97275L7.33462 4.10446C7.50249 4.26833 7.59562 4.40188 7.64192 4.58064C7.73236 4.92978 7.51036 5.25117 7.01882 5.54349C6.95454 5.58172 6.87144 5.5606 6.83322 5.49632C6.79499 5.43204 6.81611 5.34894 6.88039 5.31071C7.28043 5.07281 7.43258 4.85254 7.37974 4.64856C7.35174 4.54047 7.29562 4.45244 7.18817 4.34116L7.12974 4.28334L6.90842 4.07249C6.90208 4.06624 6.89644 4.06061 6.89165 4.05575C6.74804 3.91008 6.63891 3.76759 6.54875 3.59356C6.32234 3.15652 6.54417 2.72834 7.15694 2.33405ZM9.39207 2.33405C9.45496 2.29359 9.53875 2.31176 9.57922 2.37466C9.61969 2.43755 9.60151 2.52134 9.53861 2.56181C9.02894 2.88975 8.87661 3.18379 9.02435 3.46898C9.08988 3.59545 9.16756 3.70273 9.26767 3.8112L9.33529 3.88121L9.56974 4.10446C9.73761 4.26833 9.83074 4.40188 9.87704 4.58064C9.96748 4.92978 9.74548 5.25117 9.25394 5.54349C9.18966 5.58172 9.10656 5.5606 9.06834 5.49632C9.03011 5.43204 9.05123 5.34894 9.11551 5.31071C9.51555 5.07281 9.6677 4.85254 9.61486 4.64856C9.58687 4.54047 9.53074 4.45244 9.42329 4.34116L9.37355 4.29157L9.14355 4.07249C9.1372 4.06624 9.13156 4.06061 9.12677 4.05575C8.98316 3.91008 8.87403 3.76759 8.78387 3.59356C8.55747 3.15652 8.77929 2.72834 9.39207 2.33405Z" fill="rgb(255,255,255)" fill-opacity="0" fill-rule="nonzero" />+ <path id="path8" d="M4.81859 2.37466C4.85905 2.43755 4.84087 2.52134 4.77798 2.56181C4.26831 2.88975 4.11598 3.18379 4.26372 3.46898C4.34016 3.61653 4.43316 3.73796 4.55901 3.86562L4.66992 3.97275L4.80911 4.10446C4.97697 4.26833 5.07011 4.40188 5.11641 4.58064C5.20684 4.92978 4.98484 5.25117 4.49331 5.54349C4.42903 5.58172 4.34593 5.5606 4.3077 5.49632C4.26948 5.43204 4.2906 5.34894 4.35488 5.31071C4.75492 5.07281 4.90706 4.85254 4.85423 4.64856C4.82623 4.54047 4.77011 4.45244 4.66266 4.34116L4.60423 4.28334L4.38291 4.07249C4.37657 4.06624 4.37092 4.06061 4.36614 4.05575C4.22253 3.91008 4.1134 3.76759 4.02324 3.59356C3.79683 3.15652 4.01865 2.72834 4.63143 2.33405C4.69433 2.29359 4.77812 2.31176 4.81859 2.37466ZM7.3441 2.37466C7.38457 2.43755 7.36639 2.52134 7.30349 2.56181C6.79382 2.88975 6.64149 3.18379 6.78923 3.46898C6.86568 3.61653 6.95868 3.73796 7.08452 3.86562L7.19543 3.97275L7.33462 4.10446C7.50249 4.26833 7.59562 4.40188 7.64192 4.58064C7.73236 4.92978 7.51036 5.25117 7.01882 5.54349C6.95454 5.58172 6.87144 5.5606 6.83322 5.49632C6.79499 5.43204 6.81611 5.34894 6.88039 5.31071C7.28043 5.07281 7.43258 4.85254 7.37974 4.64856C7.35174 4.54047 7.29562 4.45244 7.18817 4.34116L7.12974 4.28334L6.90842 4.07249C6.90208 4.06624 6.89644 4.06061 6.89165 4.05575C6.74804 3.91008 6.63891 3.76759 6.54875 3.59356C6.32234 3.15652 6.54417 2.72834 7.15694 2.33405C7.21984 2.29359 7.30363 2.31176 7.3441 2.37466ZM9.57922 2.37466C9.61969 2.43755 9.60151 2.52134 9.53861 2.56181C9.02894 2.88975 8.87661 3.18379 9.02435 3.46898C9.08988 3.59545 9.16756 3.70273 9.26767 3.8112L9.33529 3.88121L9.56974 4.10446C9.73761 4.26833 9.83074 4.40188 9.87704 4.58064C9.96748 4.92978 9.74548 5.25117 9.25394 5.54349C9.18966 5.58172 9.10656 5.5606 9.06834 5.49632C9.03011 5.43204 9.05123 5.34894 9.11551 5.31071C9.51555 5.07281 9.6677 4.85254 9.61486 4.64856C9.58687 4.54047 9.53074 4.45244 9.42329 4.34116L9.37355 4.29157L9.14355 4.07249C9.1372 4.06624 9.13156 4.06061 9.12677 4.05575C8.98316 3.91008 8.87403 3.76759 8.78387 3.59356C8.55747 3.15652 8.77929 2.72834 9.39207 2.33405C9.45496 2.29359 9.53875 2.31176 9.57922 2.37466Z" fill-rule="nonzero" stroke="rgb(255,255,255)" stroke-opacity="0" stroke-width="0.720417" />+ </g>+</svg>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex eda9e14a0d..c079b7c493 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -23,6 +23,7 @@ import deleteIcon from '../../assets/delete.svg';import moveIcon from '../../assets/move.svg';import restartIcon from '../../assets/restart.svg';import { SubtaskProgress } from './SubtaskProgress';+import { SubagentCompactPanel } from '../subagent/SubagentCompactPanel';import { InlineQuestionCard } from './InlineQuestionCard';import { InteractionSlot } from '../InteractionSlot';import { GoalBar } from '../GoalBar';@@ -1190,6 +1191,12 @@ export function ChatPanel({onShare={() => setHumanShareOpen(true)}/>)}+ {activeSessionId ? (+ <SubagentCompactPanel+ sessionId={activeSessionId}+ onExpand={() => onToggleTeamArea?.(true)}+ />+ ) : null}<SubtaskProgress />{/* 内联审批卡片(演进审批 & 权限审批共用) */}<InlineQuestionCard onSubmit={onUserAnswer} />diff --git a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsxindex a49fa36bae..a942ffcd47 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx@@ -6,6 +6,8 @@import { useTranslation } from 'react-i18next';import { useChatStore, useSessionStore, useTodoStore } from '../../stores';+import { useSubagentStore } from '../../stores';+import { SubagentExpandedPanel } from '../subagent/SubagentExpandedPanel';import { useEffect, useMemo, useRef, type ReactNode } from 'react';import { FileCheck2, FileText, Minimize2 } from 'lucide-react';import { webRequest } from '../../services/webClient';@@ -211,6 +213,10 @@ export function ToolPanel({const enterpriseMode = isEnterprise();const { isConnected, memoryUsage, setMemoryUsage } = useSessionStore();const activeSessionId = useChatStore((s) => s.activeSessionId);+ const resolvedSessionId = sessionId || activeSessionId || '';+ const subagentCount = useSubagentStore((state) => Object.keys(state.runtimes[resolvedSessionId]?.subagentsById ?? {}).length);+ const selectedSubagentId = useSubagentStore((state) => state.runtimes[resolvedSessionId]?.selectedSubagentId ?? null);+ const setSelectedSubagent = useSubagentStore((state) => state.setSelectedSubagent);const contextCompressionRate = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.contextCompressionRate ?? 0);const contextCompressionBefore = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.contextCompressionBefore ?? null);const contextCompressionAfter = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.contextCompressionAfter ?? null);@@ -441,6 +447,15 @@ export function ToolPanel({className="bg-panel h-full overflow-hidden flex-1 flex flex-col"><div className="h-full bg-panel flex flex-col overflow-hidden">+ {resolvedSessionId && subagentCount > 0 ? (+ <div className="min-h-0 flex-1 overflow-hidden border-b border-border">+ <SubagentExpandedPanel+ sessionId={resolvedSessionId}+ selectedSubagentId={selectedSubagentId}+ onSelectSubagent={(subagentId) => setSelectedSubagent(resolvedSessionId, subagentId)}+ />+ </div>+ ) : null}<ExpandedSingleAgentAreaactiveTab={teamAreaActiveTab}tasks={todoTeamTasks}diff --git a/jiuwenswarm/channels/web/frontend/src/components/subagent/Subagent.css b/jiuwenswarm/channels/web/frontend/src/components/subagent/Subagent.cssnew file mode 100644index 0000000000..6093c91213--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/subagent/Subagent.css@@ -0,0 +1,330 @@+.subagent-compact-panel {+ display: flex;+ min-height: 0;+ flex: 0 0 auto;+ flex-direction: column;+ overflow: hidden;+ border-bottom: 1px solid var(--color-border-default);+ background: var(--color-surface-card);+ padding: 16px 32px 18px;+}++.panel-tab-icon-btn:hover {+ background: var(--color-tool-tab-active-bg);+ border-radius: 10.67px;+}++.panel-tab-icon-btn--collapse {+ background: var(--color-tool-tab-active-bg);+ border-radius: 10.67px;+}++.single-agent-tool-tabs {+ display: flex;+ min-height: 68px;+ flex-shrink: 0;+ align-items: stretch;+ justify-content: space-between;+ border-bottom: 1px solid var(--color-border-default);+ background: var(--color-surface-card);+ padding-left: 24px;+ padding-right: 24px;+}++.single-agent-tool-tabs__list {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 16px;+}++.single-agent-tool-tab {+ position: relative;+ display: inline-flex;+ align-items: center;+ gap: 8px;+ height: 36px;+ padding: 8px 16px;+ border-bottom: 2px solid transparent;+ color: var(--color-text-primary);+ font-size: var(--font-size-sm);+ white-space: nowrap;+}++.single-agent-tool-tab:hover,+.single-agent-tool-tab:focus-visible {+ color: var(--color-text-primary);+}++.single-agent-tool-tab:not(.single-agent-tool-tab--active):hover,+.single-agent-tool-tab:not(.single-agent-tool-tab--active):focus-visible {+ background: var(--color-tool-tab-active-bg);+ border-radius: 8px;+}++.single-agent-tool-tab--active {+ color: var(--color-text-primary);+ font-weight: 600;+ background: var(--color-tool-tab-active-bg);+ border-radius: 8px;+}++.single-agent-tool-tabs__collapse {+ align-self: center;+}++.subagent-compact-panel__header,+.subagent-expanded-panel__list-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+}++.subagent-compact-panel__header {+ min-height: 24px;+ flex-shrink: 0;+}++.subagent-compact-panel__list {+ display: flex;+ min-height: 0;+ max-height: 240px;+ flex-direction: column;+ overflow-y: auto;+ padding-top: 16px;+ scrollbar-gutter: stable;+}++.subagent-compact-row,+.subagent-expanded-row {+ display: flex;+ width: 100%;+ align-items: center;+ gap: 10px;+ border-radius: var(--radius-md);+ text-align: left;+ transition: background-color 120ms ease;+}++.subagent-compact-row {+ min-height: 40px;+ flex-shrink: 0;+ padding: 0 8px;+}++.subagent-compact-row:hover,+.subagent-compact-row:focus-visible,+.subagent-expanded-row:hover,+.subagent-expanded-row:focus-visible {+ background: var(--color-surface-hover);+}++.subagent-compact-row__copy {+ display: flex;+ min-width: 0;+ flex: 1;+ align-items: baseline;+ gap: 0;+ overflow: hidden;+ line-height: 20px;+ white-space: nowrap;+}++.subagent-compact-row__name,+.subagent-compact-row__role {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.subagent-compact-row__name {+ flex-shrink: 0;+}++.subagent-compact-row__role {+ flex: 1;+}++.subagent-compact-row__closed,+.subagent-closed-badge {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ min-height: 20px;+ border-radius: var(--radius-sm);+ background: var(--color-action-secondary);+ padding: 0 8px;+ color: var(--color-text-secondary);+ font-size: var(--font-size-xs);+ line-height: 20px;+ white-space: nowrap;+}++.subagent-icon-button {+ display: inline-flex;+ height: 28px;+ width: 28px;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ border-radius: var(--radius-md);+ color: var(--color-text-secondary);+}++.subagent-icon-button:hover,+.subagent-icon-button:focus-visible {+ background: var(--color-surface-hover);+ color: var(--color-text-primary);+}++.subagent-detail__state {+ display: flex;+ min-height: 80px;+ align-items: center;+ justify-content: center;+ gap: 8px;+ color: var(--color-text-secondary);+ font-size: var(--font-size-sm);+}++.subagent-error-note {+ color: var(--color-feedback-danger);+}++.subagent-expanded-panel {+ display: flex;+ flex: 1;+ height: 100%;+ min-width: 0;+ overflow: hidden;+ background: var(--color-surface-card);+}++.subagent-expanded-panel__list {+ display: flex;+ width: 240px;+ flex-shrink: 0;+ flex-direction: column;+ overflow-y: auto;+ border-right: 1px solid var(--color-border-default);+ background: var(--color-surface-card);+ scrollbar-gutter: stable;+}++.subagent-expanded-row {+ min-height: 60px;+ flex-shrink: 0;+ border: 1px solid transparent;+ padding: 7px;+}++.subagent-expanded-row--selected {+ border-color: transparent;+ background: var(--color-action-secondary);+}++.subagent-detail {+ --subagent-turn-gap: 40px;+ --subagent-turn-padding: 32px;+ --subagent-inline-gap: 8px;+ --subagent-block-gap: 16px;+ --subagent-content-gap: 28px;+ display: flex;+ height: 100%;+ min-width: 0;+ flex-direction: column;+ background: var(--color-surface-card);+}++.subagent-turn + .subagent-turn {+ margin-top: var(--subagent-turn-gap);+ border-top: 2px solid var(--color-border-default);+ padding-top: var(--subagent-turn-padding);+}++.subagent-closed-badge--error {+ background: var(--color-feedback-danger-subtle);+ color: var(--color-feedback-danger);+}++.subagent-assignment {+ width: fit-content;+ margin: 16px 0 var(--subagent-content-gap) auto;+ border-radius: var(--radius-xl);+ background: var(--color-surface-muted);+ padding: 16px 20px;+}++.subagent-markdown {+ min-width: 0;+ color: var(--color-text-primary);+ font-size: var(--font-size-sm);+ line-height: 1.6;+}++.subagent-markdown > :first-child {+ margin-top: 0;+}++.subagent-markdown > :last-child {+ margin-bottom: 0;+}++.subagent-error-note {+ margin: 0 0 24px;+ border-radius: var(--radius-md);+ background: var(--color-feedback-danger-subtle);+ padding: 10px 12px;+ font-size: var(--font-size-sm);+}++.subagent-identity {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: var(--subagent-inline-gap);+ margin: 0 0 var(--subagent-block-gap);+}++.subagent-message {+ display: flex;+ min-width: 0;+ align-items: flex-start;+ gap: var(--subagent-inline-gap);+}++.subagent-message__body {+ min-width: 0;+ flex: 1;+}++.subagent-message__name {+ color: var(--color-text-primary);+ font-size: var(--font-size-xs);+ line-height: 18px;+}++.subagent-message__content {+ font-size: var(--font-size-sm);+ line-height: 1.75;+}++.subagent-activity-section {+ min-width: 0;+}++.subagent-history-loading {+ margin: var(--subagent-block-gap) 0 0;+ color: var(--color-text-placeholder);+ font-size: var(--font-size-xs);+ line-height: 20px;+}++.subagent-detail__footer {+ min-height: 54px;+ flex-shrink: 0;+ border-top: 1px solid var(--color-border-default);+ background: var(--color-surface-card);+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentCompactPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentCompactPanel.tsxnew file mode 100644index 0000000000..7e4421c68e--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentCompactPanel.tsx@@ -0,0 +1,60 @@+import { useTranslation } from 'react-i18next';+import { useSubagentStore, selectSubagents } from '../../stores/subagentStore';+import { getSubagentStatusLabelKey } from '../../features/subagent/subagentStatusPresentation';+import CollapseIcon from '../../assets/subagent/collapse.svg?react';+import TeamMembersIcon from '../../assets/subagent/team-members.svg?react';+import { TeamMemberAvatar } from '../TeamMemberAvatar';+import { SubagentStatusIcon } from './SubagentStatusIcon';+import './Subagent.css';++export function SubagentCompactPanel({ sessionId, onExpand }: { sessionId: string; onExpand: () => void }) {+ const { t } = useTranslation();+ const runtime = useSubagentStore(state => state.runtimes[sessionId]);+ const setSelectedSubagent = useSubagentStore(state => state.setSelectedSubagent);+ const subagents = selectSubagents(runtime);++ if (!runtime || subagents.length === 0) return null;++ return (+ <section className="subagent-compact-panel" aria-label={t('subagent.title')} data-testid="subagent-compact-panel">+ <div className="subagent-compact-panel__header">+ <div className="flex min-w-0 items-center gap-2">+ <TeamMembersIcon className="h-4 w-4 shrink-0 text-text-muted" aria-hidden="true" />+ <h2 className="truncate text-sm font-semibold text-text" data-testid="subagent-compact-title">{t('subagent.compactTitle', { count: subagents.length })}</h2>+ </div>+ <button type="button" className="subagent-icon-button" onClick={onExpand} aria-label={t('subagent.expand')} title={t('subagent.expand')} data-testid="subagent-compact-expand-button">+ <CollapseIcon className="h-4 w-4" aria-hidden="true" />+ </button>+ </div>++ <div className="subagent-compact-panel__list" data-testid="subagent-compact-list">+ {subagents.map(subagent => {+ const statusLabel = t(getSubagentStatusLabelKey(subagent.status, subagent.closed_reason, subagent.turn_outcome));+ return (+ <button+ key={subagent.subagent_id}+ type="button"+ className="subagent-compact-row"+ onClick={() => {+ setSelectedSubagent(sessionId, subagent.subagent_id);+ onExpand();+ }}+ aria-label={t('subagent.selectWithStatus', { name: subagent.display_name, status: statusLabel })}+ data-testid="subagent-compact-row"+ data-variant={subagent.subagent_id}+ >+ <TeamMemberAvatar member={subagent.subagent_id} alt={subagent.display_name} className="h-6 w-6 rounded-lg" imageClassName="rounded-lg" />+ <span className="subagent-compact-row__copy">+ <span className="subagent-compact-row__name truncate text-sm font-semibold text-text" data-testid="subagent-compact-row-name">{subagent.display_name}</span>+ {(subagent.role || subagent.task_description) ? (+ <span className="subagent-compact-row__role truncate text-sm text-text-muted" data-testid="subagent-compact-row-role"> | {subagent.role || subagent.task_description}</span>+ ) : null}+ </span>+ <SubagentStatusIcon status={subagent.status} closedReason={subagent.closed_reason} turnOutcome={subagent.turn_outcome} />+ </button>+ );+ })}+ </div>+ </section>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentExpandedPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentExpandedPanel.tsxnew file mode 100644index 0000000000..46ec1d320c--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentExpandedPanel.tsx@@ -0,0 +1,692 @@+import { AlertCircle, CircleEllipsis, Lightbulb, ListTodo, Search, SquareTerminal, Wrench } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import ProcessingIcon from '../../assets/subagent/processing.svg?react';+import BackIcon from '../../assets/back.svg?react';+import { getSubagentStatusLabelKey } from '../../features/subagent/subagentStatusPresentation';+import {+ extractSubagentTasks,+ finalizeSubagentTasks,+ getSubagentActivityPreview,+ groupSubagentActivities,+ type SubagentActivityGroup,+} from '../../features/subagent/subagentActivityPresentation';+import {+ selectSubagentActivities,+ selectSubagentHistoryRestoring,+ selectSubagentResult,+ selectSubagentTurns,+ selectSubagents,+ useSubagentStore,+} from '../../stores/subagentStore';+import type { Subagent, SubagentActivity, SubagentActivityKind, SubagentTurn } from '../../types/subagent';+import type { TeamMemberExecutionEvent } from '../../stores/sessionStore';+import { MemberOverviewCard } from '../teamArea/MemberOverviewCard';+import { MemberTaskListBar, MemberTaskListPanel, type MemberTaskListItem } from '../teamArea/MemberTaskList';+import { Chevron, formatTime, type ProcessItem } from '../teamArea/shared';+import { MarkdownRenderer } from '../MarkdownRenderer';+import { TeamMemberAvatar } from '../TeamMemberAvatar';+import { SubagentStatusIcon } from './SubagentStatusIcon';+import './Subagent.css';++function ActivityIcon({+ activity,+ className = 'h-[13px] w-[13px] shrink-0',+}: {+ activity: SubagentActivity;+ className?: string;+}) {+ const toolName = activity.tool_name?.toLowerCase() ?? '';++ if (activity.kind === 'thinking') {+ return <Lightbulb className={className} aria-hidden="true" />;+ }+ if (activity.kind === 'error' || activity.ok === false) {+ return <AlertCircle className={`${className} text-danger`} aria-hidden="true" />;+ }+ if (activity.kind === 'truncated') {+ return <CircleEllipsis className={className} aria-hidden="true" />;+ }+ if (toolName.includes('search') || toolName.includes('fetch') || toolName.includes('web')) {+ return <Search className={className} aria-hidden="true" />;+ }+ if (toolName.includes('bash') || toolName.includes('terminal') || toolName.includes('shell')) {+ return <SquareTerminal className={className} aria-hidden="true" />;+ }+ if (toolName.includes('todo')) {+ return <ListTodo className={className} aria-hidden="true" />;+ }+ return <Wrench className={className} aria-hidden="true" />;+}++function activityLabel(kind: SubagentActivityKind, t: (key: string) => string): string {+ const labels: Record<SubagentActivityKind, string> = {+ thinking: t('subagent.activity.thinking'),+ tool_call: t('subagent.activity.toolCall'),+ tool_result: t('subagent.activity.toolResult'),+ error: t('subagent.activity.error'),+ truncated: t('subagent.activity.truncated'),+ };+ return labels[kind];+}++function activityToolLabel(toolName: string | null | undefined, t: (key: string) => string): string | null {+ const normalized = toolName?.trim().toLowerCase();+ if (!normalized) return null;+ if (normalized.includes('search') || normalized.includes('fetch') || normalized.includes('web')) {+ return t('subagent.activity.tools.search');+ }+ if (normalized.includes('bash') || normalized.includes('terminal') || normalized.includes('shell')) {+ return t('subagent.activity.tools.terminal');+ }+ if (normalized.includes('todo')) {+ return t('subagent.activity.tools.todo');+ }+ return toolName?.trim() || normalized;+}++type ActivityDetailRow = [label: string, value: string];++function buildActivityDetailRows(group: SubagentActivityGroup, t: (key: string) => string): ActivityDetailRow[] {+ const activity = group.activity;+ const latestActivity = group.activities[group.activities.length - 1] ?? activity;+ const rows: ActivityDetailRow[] = [+ [t('subagent.activity.fields.type'), activityLabel(activity.kind, t)],+ [t('subagent.activity.fields.time'), formatTime(latestActivity.at_ms) || '-'],+ ];++ if (activity.tool_name) {+ rows.push([t('subagent.activity.fields.tool'), activity.tool_name]);+ }++ if (activity.kind === 'tool_call') {+ rows.push([t('subagent.activity.fields.call'), activity.summary || '-']);+ } else if (activity.kind === 'tool_result') {+ rows.push([t('subagent.activity.fields.result'), activity.summary || '-']);+ } else {+ rows.push([t('subagent.activity.fields.content'), group.summary || '-']);+ }++ if (activity.ok !== undefined) {+ rows.push([+ t('subagent.activity.fields.status'),+ activity.ok ? t('subagent.activity.ok') : t('subagent.activity.error'),+ ]);+ }+ if (activity.dropped !== undefined) {+ rows.push([t('subagent.activity.fields.dropped'), String(activity.dropped)]);+ }++ return rows;+}++function ActivityRow({+ group,+ isLast,+ isSubagentRunning,+}: {+ group: SubagentActivityGroup;+ isLast: boolean;+ isSubagentRunning: boolean;+}) {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);+ const activity = group.activity;+ const latestActivity = group.activities[group.activities.length - 1] ?? activity;+ const isThinking = activity.kind === 'thinking';+ const isRunning =+ isLast && isSubagentRunning && (latestActivity.kind === 'thinking' || latestActivity.kind === 'tool_call');+ const label = isThinking+ ? t('subagent.activity.thinking')+ : (activityToolLabel(activity.tool_name, t) ?? activityLabel(activity.kind, t));+ const summary = getSubagentActivityPreview(group);+ const timestamp = formatTime(latestActivity.at_ms);+ const detailRows = buildActivityDetailRows(group, t);+ const detailsId = `subagent-activity-details-${activity.activity_id}`;++ return (+ <li data-testid="subagent-activity-row" data-variant={activity.activity_id}>+ <button+ type="button"+ onClick={() => setExpanded((value) => !value)}+ className="flex h-[22px] w-full items-center gap-3 px-3 pr-1 text-left hover:bg-secondary"+ aria-expanded={expanded}+ aria-controls={detailsId}+ aria-label={t(expanded ? 'subagent.activity.collapse' : 'subagent.activity.expand')}+ data-testid="subagent-activity-row-toggle"+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted" aria-hidden="true">+ <ActivityIcon activity={activity} />+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2 text-sm text-text-muted">+ <span className="shrink-0 text-muted-strong" data-testid="subagent-activity-row-label">+ {label}+ </span>+ {summary && summary !== label ? (+ <>+ <span className="flex" aria-hidden="true">+ <span className="w-[1px] h-[10px] bg-border" />+ </span>+ <span className="truncate text-muted" data-testid="subagent-activity-row-summary">+ {summary}+ </span>+ </>+ ) : null}+ {activity.dropped ? (+ <span className="shrink-0 text-muted" data-testid="subagent-activity-row-dropped">+ +{activity.dropped}+ </span>+ ) : null}+ </div>+ </div>+ {timestamp ? (+ <span className="shrink-0 text-xs text-text-muted" data-testid="subagent-activity-row-timestamp">+ {timestamp}+ </span>+ ) : null}+ <span className="shrink-0 text-muted">+ {isRunning ? (+ <ProcessingIcon className="h-4 w-4 shrink-0 animate-spin" aria-label={t('subagent.running')} role="img" />+ ) : (+ <Chevron expanded={expanded} />+ )}+ </span>+ </button>+ {expanded ? (+ <div+ id={detailsId}+ className="border-t border-border bg-secondary px-12 py-3 text-xs text-text"+ data-testid="subagent-activity-row-detail"+ >+ <div className="space-y-2">+ {detailRows.map(([detailLabel, detailValue]) => (+ <div+ key={detailLabel}+ className="grid grid-cols-[72px_minmax(0,1fr)] gap-3"+ data-testid="subagent-activity-row-detail-row"+ data-variant={detailLabel}+ >+ <span className="text-muted" data-testid="subagent-activity-row-detail-label">+ {detailLabel}+ </span>+ <span className="whitespace-pre-wrap break-words" data-testid="subagent-activity-row-detail-value">+ {detailValue}+ </span>+ </div>+ ))}+ </div>+ </div>+ ) : null}+ {!isLast ? (+ <div className="flex h-4 py-px pl-[20px]" aria-hidden="true">+ <span className="w-[1px] h-[10px] -translate-x-1/2 rounded-full bg-border" />+ </div>+ ) : null}+ </li>+ );+}++function SubagentDetail({+ sessionId,+ subagentId,+ onBack,+}: {+ sessionId: string;+ subagentId: string;+ onBack?: () => void;+}) {+ const { t } = useTranslation();+ const [tasksExpanded, setTasksExpanded] = useState(false);+ const runtime = useSubagentStore((state) => state.runtimes[sessionId]);+ const activities = selectSubagentActivities(runtime, subagentId);+ const historyRestoring = selectSubagentHistoryRestoring(runtime, subagentId);+ const result = selectSubagentResult(runtime, subagentId);+ const turns = selectSubagentTurns(runtime, subagentId);+ const subagent = runtime?.subagentsById[subagentId];++ if (!subagent) {+ return (+ <div className="subagent-detail__state" role="status" data-testid="subagent-detail-empty">+ {t('subagent.empty')}+ </div>+ );+ }++ const taskDescription = subagent.task_description?.trim() || subagent.display_name;+ const hasFailed = subagent.closed_reason === 'failed' || subagent.turn_outcome === 'failed';+ const visibleTurns: SubagentTurn[] =+ turns.length > 0+ ? turns+ : [+ {+ task_id: '__legacy__',+ task_description: taskDescription,+ started_at: subagent.created_at,+ ...(result ? { result } : {}),+ },+ ];+ const hasTurnResult = visibleTurns.some((turn) => Boolean(turn.result?.content?.trim()));+ const legacyFallbackResult = !historyRestoring && !hasTurnResult ? result : undefined;+ const latestTurnId = visibleTurns[visibleTurns.length - 1]?.task_id;+ const tasks = finalizeSubagentTasks(+ extractSubagentTasks(activities),+ subagent.turn_outcome === 'completed' && visibleTurns.some((turn) => Boolean(turn.result?.content?.trim())),+ subagent.updated_at,+ );+ const taskListItems: MemberTaskListItem[] = tasks.map((task) => ({+ id: task.id,+ title: task.content,+ detail: task.detail,+ status: task.status,+ raw: task.raw,+ statusHistory: task.statusHistory,+ }));++ return (+ <div className="subagent-detail" data-testid="subagent-detail">+ <div+ className="flex shrink-0 items-center gap-2 bg-card pl-4 pr-6 pt-6"+ data-testid="subagent-member-detail-section"+ >+ {onBack ? (+ <button+ type="button"+ onClick={onBack}+ className="flex shrink-0 items-center text-sm text-text-muted hover:text-text"+ data-testid="subagent-member-detail-back"+ >+ <BackIcon className="text-text" />+ </button>+ ) : null}+ <div className="flex min-w-0 items-center gap-2">+ <h2 className="truncate text-sm font-semibold text-text" data-testid="subagent-detail-name">+ {subagent.display_name}+ </h2>+ {subagent.role ? (+ <span className="truncate text-sm text-text-muted" data-testid="subagent-detail-role">+ {' '}+ | {subagent.role}+ </span>+ ) : null}+ {subagent.status === 'closed' ? (+ <span className="subagent-closed-badge" data-testid="subagent-detail-closed-badge">+ {t('subagent.closed')}+ </span>+ ) : null}+ </div>+ {subagent.status !== 'closed' || hasFailed || subagent.closed_reason === 'evicted' ? (+ <div className="ml-auto shrink-0">+ <SubagentStatusIcon+ status={subagent.status}+ closedReason={subagent.closed_reason}+ turnOutcome={subagent.turn_outcome}+ />+ </div>+ ) : null}+ </div>++ <div+ className="member-detail-body min-h-0 flex-1 overflow-y-auto px-12 pt-[26px] pb-7"+ data-testid="subagent-member-detail-body"+ >+ {hasFailed && subagent.error ? (+ <div className="subagent-error-note" role="alert" data-testid="subagent-detail-error">+ {subagent.error.message}+ </div>+ ) : null}++ <div className="subagent-conversation" aria-live="polite" data-testid="subagent-detail-conversation">+ {visibleTurns.map((turn) => {+ const turnActivities =+ turn.task_id === '__legacy__'+ ? activities+ : activities.filter((activity) => activity.task_id === turn.task_id);+ const activityGroups = groupSubagentActivities(turnActivities);+ const turnResult =+ (historyRestoring && turn.result?.source === 'wait' ? undefined : turn.result) ??+ (!historyRestoring && visibleTurns.length === 1 ? result : undefined) ??+ (turn.task_id === latestTurnId ? legacyFallbackResult : undefined);+ const waitingForHistory = historyRestoring && turnResult == null;+ return (+ <section+ className="subagent-turn"+ key={turn.task_id}+ data-testid="subagent-turn"+ data-variant={turn.task_id}+ >+ {turn.task_description.trim() ? (+ <div className="subagent-assignment" data-testid="subagent-turn-assignment">+ <MarkdownRenderer+ content={turn.task_description}+ className="chat-text chat-markdown subagent-markdown"+ />+ </div>+ ) : null}++ <div className="subagent-identity" data-testid="subagent-turn-identity">+ <TeamMemberAvatar+ member={subagent.subagent_id}+ alt={subagent.display_name}+ className="h-8 w-8 rounded-xl"+ imageClassName="rounded-xl"+ />+ <div className="subagent-message__name">{subagent.display_name}</div>+ </div>++ <div className="subagent-activity-section" data-testid="subagent-turn-activity-section">+ {turnActivities.length > 0 ? (+ <ol+ className="m-0 w-full list-none overflow-hidden rounded-md border border-border bg-card pt-2 pb-1"+ aria-label={t('subagent.activityTitle')}+ data-testid="subagent-activity-list"+ >+ {activityGroups.map((group, index) => (+ <ActivityRow+ key={group.activity.activity_id}+ group={group}+ isLast={index === activityGroups.length - 1}+ isSubagentRunning={subagent.status === 'running' && turn.task_id === latestTurnId}+ />+ ))}+ </ol>+ ) : null}+ </div>++ {waitingForHistory ? (+ <div+ className="subagent-history-loading"+ role="status"+ aria-live="polite"+ data-testid="subagent-history-loading"+ >+ {t('subagent.historyLoading')}+ </div>+ ) : null}++ {turnResult?.content?.trim() ? (+ <div className="subagent-message" data-testid="subagent-turn-message">+ <div className="subagent-message__body">+ <MarkdownRenderer+ content={turnResult.content}+ className="chat-text chat-markdown subagent-markdown subagent-message__content"+ />+ </div>+ </div>+ ) : null}+ </section>+ );+ })}+ {activities.length === 0 && !visibleTurns.some((turn) => turn.result?.content?.trim()) ? (+ <div className="subagent-detail__state" data-testid="subagent-detail-activity-empty">+ {t('subagent.activityEmpty')}+ </div>+ ) : null}+ </div>+ </div>++ {taskListItems.length > 0 ? (+ <div className="subagent-detail__footer relative" data-testid="subagent-detail-footer">+ <MemberTaskListBar+ tasks={taskListItems}+ expanded={tasksExpanded}+ onToggle={() => setTasksExpanded((value) => !value)}+ />+ {tasksExpanded ? <MemberTaskListPanel tasks={taskListItems} /> : null}+ </div>+ ) : null}+ </div>+ );+}++function SubagentOverviewPanel({+ sessionId,+ subagents,+ onSubagentClick,+}: {+ sessionId: string;+ subagents: Subagent[];+ onSubagentClick: (subagentId: string) => void;+}) {+ const { t } = useTranslation();++ return (+ <section+ className="flex min-w-0 flex-1 flex-col bg-card"+ data-testid="team-area-member-overview"+ data-panel="subagents"+ >+ <div+ className="min-h-0 flex-1 overflow-y-auto px-6 pt-6 pb-[48px] [scrollbar-gutter:stable]"+ data-testid="team-area-member-overview-body"+ >+ {subagents.length === 0 ? (+ <div className="py-12 text-center text-sm text-text-muted" data-testid="team-area-member-overview-empty">+ {t('subagent.empty')}+ </div>+ ) : (+ <div className="flex flex-col gap-4" data-testid="team-area-member-overview-grid">+ {subagents.map((subagent, index) => (+ <SubagentOverviewCard+ key={subagent.subagent_id}+ sessionId={sessionId}+ subagent={subagent}+ sequence={index + 1}+ onClick={() => onSubagentClick(subagent.subagent_id)}+ />+ ))}+ </div>+ )}+ </div>+ </section>+ );+}++function toSubagentExecutionEvent(memberId: string, activity: SubagentActivity): TeamMemberExecutionEvent {+ // SubagentActivityKind 的 'thinking' | 'error' | 'truncated' 在 TeamMemberExecutionEventKind 中+ // 无对应值;execution.kind 在渲染路径上不被读取(详情类型标签走 detailRows,内容走+ // tool_name / content),非工具活动回落 'final' 仅用于满足类型,不影响展示。+ const kind: TeamMemberExecutionEvent['kind'] =+ activity.kind === 'tool_call' || activity.kind === 'tool_result' ? activity.kind : 'final';+ return {+ id: activity.activity_id,+ member_id: memberId,+ kind,+ timestamp: activity.at_ms,+ title: '',+ ...(activity.summary ? { content: activity.summary } : {}),+ ...(activity.tool_name ? { tool_name: activity.tool_name } : {}),+ ...(activity.tool_call_id ? { tool_call_id: activity.tool_call_id } : {}),+ };+}++function buildSubagentProcessItems(+ memberId: string,+ activities: SubagentActivity[],+ t: (key: string) => string,+): ProcessItem[] {+ const groups = groupSubagentActivities(activities);+ const resultsByCallId = new Map<string, SubagentActivity>();+ activities.forEach((activity) => {+ if (activity.kind === 'tool_result' && activity.tool_call_id) {+ resultsByCallId.set(activity.tool_call_id, activity);+ }+ });+ const pairedResultIds = new Set<string>();+ activities.forEach((activity) => {+ if (activity.kind !== 'tool_call' || !activity.tool_call_id) return;+ const result = resultsByCallId.get(activity.tool_call_id);+ if (result) pairedResultIds.add(result.activity_id);+ });++ const items: ProcessItem[] = [];+ groups.forEach((group) => {+ const activity = group.activity;+ if (activity.kind === 'tool_result' && pairedResultIds.has(activity.activity_id)) return;+ const latest = group.activities[group.activities.length - 1] ?? activity;+ const linkedResult =+ activity.kind === 'tool_call' && activity.tool_call_id ? resultsByCallId.get(activity.tool_call_id) : undefined;+ const label =+ activity.kind === 'thinking'+ ? t('subagent.activity.thinking')+ : (activityToolLabel(activity.tool_name, t) ?? activityLabel(activity.kind, t));+ const previewGroup: SubagentActivityGroup = linkedResult+ ? { ...group, activities: [activity, linkedResult] }+ : group;+ items.push({+ id: `subagent-${activity.activity_id}`,+ type: 'execution',+ timestamp: latest.at_ms,+ title: label,+ subtitle: getSubagentActivityPreview(previewGroup) || undefined,+ status: 'execution',+ ...(activity.kind === 'tool_call' || activity.kind === 'tool_result' ? { kind: activity.kind } : {}),+ execution: toSubagentExecutionEvent(memberId, activity),+ ...(linkedResult ? { linkedResult: toSubagentExecutionEvent(memberId, linkedResult) } : {}),+ });+ });+ return items;+}++const SubagentOverviewCard = memo(function SubagentOverviewCard({+ sessionId,+ subagent,+ sequence,+ onClick,+}: {+ sessionId: string;+ subagent: Subagent;+ sequence: number;+ onClick?: () => void;+}) {+ const { t } = useTranslation();+ const runtime = useSubagentStore((state) => state.runtimes[sessionId]);+ const activities = selectSubagentActivities(runtime, subagent.subagent_id);+ const processItems = useMemo(+ () => buildSubagentProcessItems(subagent.subagent_id, activities, t),+ [subagent.subagent_id, activities, t],+ );++ return (+ <MemberOverviewCard+ memberId={subagent.subagent_id}+ displayName={subagent.display_name}+ sequence={sequence}+ statusIcon={+ <SubagentStatusIcon+ status={subagent.status}+ closedReason={subagent.closed_reason}+ turnOutcome={subagent.turn_outcome}+ />+ }+ onClick={onClick}+ items={processItems}+ emptyText={t('subagent.activityEmpty')}+ />+ );+});++export function SubagentExpandedPanel({+ sessionId,+ selectedSubagentId,+ onSelectSubagent,+}: {+ sessionId: string;+ selectedSubagentId: string | null;+ onSelectSubagent: (subagentId: string | null) => void;+}) {+ const { t } = useTranslation();+ const runtime = useSubagentStore((state) => state.runtimes[sessionId]);+ const subagents = selectSubagents(runtime);+ const activeCount = subagents.filter((subagent) => subagent.status === 'running').length;+ const detailSubagent = selectedSubagentId+ ? (subagents.find((subagent) => subagent.subagent_id === selectedSubagentId) ?? null)+ : null;++ const openDetail = (subagentId: string) => {+ onSelectSubagent(subagentId);+ };+ const backToOverview = () => {+ onSelectSubagent(null);+ };++ if (!runtime) {+ return (+ <div className="subagent-detail__state" role="status" data-testid="subagent-expanded-empty">+ {t('subagent.empty')}+ </div>+ );+ }++ return (+ <div className="subagent-expanded-panel" data-testid="subagent-expanded-panel">+ <aside+ className="subagent-expanded-panel__list"+ aria-label={t('subagent.title')}+ data-testid="subagent-expanded-list"+ >+ <div className="subagent-expanded-panel__list-heading px-[24px] pt-[24px]">+ <span className="text-sm text-text" data-testid="subagent-expanded-list-heading">+ {t('subagent.activeListTitle', { count: activeCount })}+ </span>+ </div>+ <div className="space-y-3 px-[24px] py-4">+ {subagents.map((subagent) => {+ const statusLabel = t(+ getSubagentStatusLabelKey(subagent.status, subagent.closed_reason, subagent.turn_outcome),+ );+ return (+ <button+ type="button"+ key={subagent.subagent_id}+ className={`subagent-expanded-row ${subagent.subagent_id === selectedSubagentId ? 'subagent-expanded-row--selected' : ''}`}+ onClick={() => openDetail(subagent.subagent_id)}+ aria-pressed={subagent.subagent_id === selectedSubagentId}+ aria-label={t('subagent.selectWithStatus', { name: subagent.display_name, status: statusLabel })}+ data-testid="subagent-expanded-row"+ data-variant={subagent.subagent_id}+ >+ <TeamMemberAvatar+ member={subagent.subagent_id}+ alt={subagent.display_name}+ className="h-8 w-8 rounded-xl"+ imageClassName="rounded-xl"+ />+ <span className="min-w-0 flex-1 text-left">+ <span+ className="block truncate text-sm font-semibold text-text"+ data-testid="subagent-expanded-row-name"+ >+ {subagent.display_name}+ </span>+ {subagent.role || subagent.task_description ? (+ <span className="block truncate text-xs text-text-muted" data-testid="subagent-expanded-row-role">+ {subagent.role || subagent.task_description}+ </span>+ ) : null}+ </span>+ <SubagentStatusIcon+ status={subagent.status}+ closedReason={subagent.closed_reason}+ turnOutcome={subagent.turn_outcome}+ />+ </button>+ );+ })}+ </div>+ </aside>+ {detailSubagent ? (+ <section className="min-w-0 flex-1 overflow-hidden" data-testid="subagent-expanded-detail">+ <SubagentDetail+ key={detailSubagent.subagent_id}+ sessionId={sessionId}+ subagentId={detailSubagent.subagent_id}+ onBack={backToOverview}+ />+ </section>+ ) : (+ <SubagentOverviewPanel sessionId={sessionId} subagents={subagents} onSubagentClick={openDetail} />+ )}+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentStatusIcon.tsx b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentStatusIcon.tsxnew file mode 100644index 0000000000..c6afd733be--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/subagent/SubagentStatusIcon.tsx@@ -0,0 +1,37 @@+import { useTranslation } from 'react-i18next';+import { CircleAlert } from 'lucide-react';+import LoadingIcon from '../../assets/subagent/loading.svg?react';+import SuccessIcon from '../../assets/subagent/success.svg?react';+import WaitingIcon from '../../assets/subagent/waiting.svg?react';+import { getSubagentStatusLabelKey, getSubagentStatusTone } from '../../features/subagent/subagentStatusPresentation';+import type { SubagentClosedReason, SubagentStatus, SubagentTurnOutcome } from '../../types/subagent';++export function SubagentStatusIcon({+ status,+ closedReason,+ turnOutcome,+ className = 'h-4 w-4',+}: {+ status: SubagentStatus;+ closedReason?: SubagentClosedReason | null;+ turnOutcome?: SubagentTurnOutcome | null;+ className?: string;+}) {+ const { t } = useTranslation();+ const tone = getSubagentStatusTone(status, closedReason, turnOutcome);+ const label = t(getSubagentStatusLabelKey(status, closedReason, turnOutcome));++ if (tone === 'running') {+ return <LoadingIcon className={`${className} shrink-0 text-muted animate-spin`} aria-label={label} role="img" />;+ }+ if (tone === 'waiting') {+ return <WaitingIcon className={`${className} shrink-0 text-text-muted`} aria-label={label} role="img" />;+ }+ if (tone === 'danger') {+ return <CircleAlert className={`${className} shrink-0 text-danger`} aria-label={label} role="img" />;+ }+ if (tone === 'success') {+ return <SuccessIcon className={`${className} shrink-0 text-ok`} aria-label={label} role="img" />;+ }+ return <WaitingIcon className={`${className} shrink-0 text-text-muted`} aria-label={label} role="img" />;+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberOverviewCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberOverviewCard.tsxnew file mode 100644index 0000000000..11fe2205c6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberOverviewCard.tsx@@ -0,0 +1,57 @@+import type { ReactNode } from 'react';+import { Chevron, formatTime, type ProcessItem } from './shared';++export function MemberOverviewCard({+ memberId,+ displayName,+ sequence,+ statusIcon,+ onClick,+ items,+ emptyText,+}: {+ memberId: string;+ displayName: string;+ sequence: number;+ statusIcon?: ReactNode;+ onClick?: () => void;+ items: ProcessItem[];+ emptyText?: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="w-full rounded-lg border border-border bg-card p-4 text-left hover:border-accent"+ data-testid="member-overview-card"+ data-member-id={memberId}+ >+ <div className="mb-3 flex items-center gap-2">+ {statusIcon}+ <span className="truncate text-sm font-medium text-text">+ {sequence}. {displayName}+ </span>+ <span className="ml-auto text-text-muted">+ <Chevron />+ </span>+ </div>+ {items.length === 0 ? (+ <div className="text-xs text-text-muted">{emptyText}</div>+ ) : (+ <ul className="flex flex-col gap-2">+ {items.slice(0, 6).map((item) => (+ <li key={item.id} className="min-w-0">+ <div className="truncate text-xs text-text">{item.title}</div>+ {item.subtitle ? (+ <div className="truncate text-[11px] text-text-muted">{item.subtitle}</div>+ ) : null}+ {item.timestamp ? (+ <div className="text-[10px] text-text-muted">{formatTime(item.timestamp)}</div>+ ) : null}+ </li>+ ))}+ </ul>+ )}+ </button>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberTaskList.tsx b/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberTaskList.tsxnew file mode 100644index 0000000000..b928b73381--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/teamArea/MemberTaskList.tsx@@ -0,0 +1,68 @@+import { Chevron, StatusIcon, type TaskStatus } from './shared';++export interface MemberTaskListItem {+ id: string;+ title: string;+ detail?: string;+ status: TaskStatus | string;+ raw?: Record<string, unknown>;+ statusHistory?: Array<{ status: string; atMs?: number; source?: string }>;+}++function asTaskStatus(status: string): TaskStatus {+ if (+ status === 'pending' ||+ status === 'in_progress' ||+ status === 'completed' ||+ status === 'cancelled' ||+ status === 'error'+ ) {+ return status;+ }+ return 'pending';+}++export function MemberTaskListBar({+ tasks,+ expanded,+ onToggle,+}: {+ tasks: MemberTaskListItem[];+ expanded: boolean;+ onToggle: () => void;+}) {+ const completed = tasks.filter((task) => task.status === 'completed').length;+ return (+ <button+ type="button"+ onClick={onToggle}+ className="flex w-full items-center gap-2 border-t border-border px-4 py-2 text-left text-xs text-text"+ data-testid="member-task-list-bar"+ >+ <Chevron expanded={expanded} />+ <span>Tasks {completed}/{tasks.length}</span>+ </button>+ );+}++export function MemberTaskListPanel({+ tasks,+}: {+ tasks: MemberTaskListItem[];+}) {+ return (+ <ul className="flex flex-col gap-2 border-t border-border px-4 py-3" data-testid="member-task-list-panel">+ {tasks.map((task) => (+ <li key={task.id} className="flex items-start gap-2">+ <StatusIcon status={asTaskStatus(String(task.status))} />+ <div className="min-w-0">+ <div className="truncate text-xs text-text">{task.title}</div>+ {task.detail ? (+ <div className="truncate text-[11px] text-text-muted">{task.detail}</div>+ ) : null}+ </div>+ </li>+ ))}+ </ul>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentActivityPresentation.ts b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentActivityPresentation.tsnew file mode 100644index 0000000000..fe43c31b30--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentActivityPresentation.ts@@ -0,0 +1,306 @@+import type { SubagentActivity } from '../../types/subagent';++export interface SubagentActivityGroup {+ activity: SubagentActivity;+ activities: SubagentActivity[];+ summary: string;+ count: number;+}++export type SubagentTaskStatus = 'pending' | 'in_progress' | 'completed';++export interface SubagentTaskStatusChange {+ status: SubagentTaskStatus;+ atMs?: number;+ source: 'create' | 'update' | 'result' | 'final';+}++export interface SubagentTask {+ id: string;+ content: string;+ detail: string;+ status: SubagentTaskStatus;+ raw: Record<string, unknown>;+ statusHistory: SubagentTaskStatusChange[];+}++function firstNonEmptyLine(value: string): string {+ return value+ .split(/\r?\n/)+ .map(line => line.trim())+ .find(Boolean) || '';+}++function boundedPreview(value: string, maxLength = 120): string {+ const line = firstNonEmptyLine(value);+ return line.length > maxLength ? `${line.slice(0, maxLength - 1)}…` : line;+}++function unescapeQuotedValue(value: string): string {+ try {+ return JSON.parse(`"${value}"`) as string;+ } catch {+ return value.replace(/\\([\\"'])/g, '$1');+ }+}++function extractStringField(value: string, field: string): string {+ const doubleQuoted = value.match(new RegExp(`"${field}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`));+ const singleQuoted = value.match(new RegExp(`'${field}'\\s*:\\s*'((?:\\\\.|[^'\\\\])*)'`));+ const match = doubleQuoted || singleQuoted;+ return match ? unescapeQuotedValue(match[1]) : '';+}++function resultPreview(value: string): string {+ const content = value.match(/(?:^|\s)Content:\s*([\s\S]*)$/i)?.[1];+ if (content) return firstNonEmptyLine(content);+ return extractStringField(value, 'message') || extractStringField(value, 'result') || firstNonEmptyLine(value);+}++function parseJsonPayload(value: string): Record<string, unknown> | null {+ const start = value.indexOf('{');+ const end = value.lastIndexOf('}');+ if (start < 0 || end <= start) return null;+ try {+ const parsed = JSON.parse(value.slice(start, end + 1));+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)+ ? parsed as Record<string, unknown>+ : null;+ } catch {+ return null;+ }+}++function normalizeTaskStatus(value: unknown): SubagentTaskStatus {+ if (value === 'completed' || value === 'complete' || value === 'done') return 'completed';+ if (value === 'in_progress' || value === 'in-progress' || value === 'running') return 'in_progress';+ return 'pending';+}++function taskEntries(value: unknown): Array<Record<string, unknown>> {+ return Array.isArray(value)+ ? value.filter((item): item is Record<string, unknown> => Boolean(item) && typeof item === 'object')+ : [];+}++function applyTaskEntry(+ tasks: Map<string, SubagentTask>,+ entry: Record<string, unknown>,+ atMs: number | undefined,+ source: SubagentTaskStatusChange['source'],+): void {+ const id = typeof entry.id === 'string'+ ? entry.id+ : typeof entry.task_id === 'string'+ ? entry.task_id+ : '';+ const content = typeof entry.content === 'string'+ ? entry.content+ : typeof entry.activeForm === 'string'+ ? entry.activeForm+ : '';+ const detail = typeof entry.description === 'string'+ ? entry.description+ : typeof entry.activeForm === 'string'+ ? entry.activeForm+ : '';+ const previous = tasks.get(id);+ if (!id || (!content && !previous)) return;+ const status = entry.status === undefined && previous ? previous.status : normalizeTaskStatus(entry.status);+ const statusHistory = [...(previous?.statusHistory || [])];+ if (!previous || previous.status !== status) {+ statusHistory.push({ status, atMs, source });+ }+ tasks.set(id, {+ id,+ content: content || previous?.content || id,+ detail: detail || previous?.detail || '',+ status,+ raw: {+ ...(previous?.raw || {}),+ ...entry,+ status: entry.status === undefined ? status : entry.status,+ },+ statusHistory,+ });+}++function applyTaskResultLines(tasks: Map<string, SubagentTask>, summary: string, atMs?: number): void {+ const linePattern = /^\s*\[([^\]]*)\]\s*task_id:\s*([^,\s]+)\s*,\s*content:\s*(.*?)(?:\s+\(model:.*)?$/gm;+ for (const match of summary.matchAll(linePattern)) {+ const marker = match[1].trim();+ const status = marker.includes('✓') || marker.includes('✔')+ ? 'completed'+ : marker.includes('→') || marker.includes('>')+ ? 'in_progress'+ : 'pending';+ applyTaskEntry(tasks, { id: match[2], content: match[3].trim(), status }, atMs, 'result');+ }+}++type PendingTodoOperation = {+ toolName: string;+ payload: Record<string, unknown>;+};++function isSuccessfulTodoResult(summary: string): boolean {+ const normalized = summary.trim().toLowerCase();+ if (!normalized || normalized.includes('success=false') || normalized.includes('[error]')) return false;+ return !normalized.includes('error=') || normalized.includes('error=none');+}++function applyTodoPayload(tasks: Map<string, SubagentTask>, toolName: string, payload: Record<string, unknown>, atMs?: number): void {+ const source: SubagentTaskStatusChange['source'] = toolName.includes('create')+ ? 'create'+ : toolName.includes('complete')+ ? 'result'+ : 'update';+ for (const entry of taskEntries(payload.tasks ?? payload.todos)) applyTaskEntry(tasks, entry, atMs, source);+ if (typeof payload.task_id !== 'string') return;+ if (toolName.includes('remove')) {+ tasks.delete(payload.task_id);+ return;+ }+ applyTaskEntry(tasks, {+ ...payload,+ ...(toolName.includes('complete') ? { status: 'completed' } : {}),+ }, atMs, source);+}++export function isSubagentTodoActivity(activity: SubagentActivity): boolean {+ return activity.tool_name?.toLowerCase().includes('todo') ?? false;+}++/** Extract real todo tool data for the separate "Ta的任务" section. */+export function extractSubagentTasks(activities: SubagentActivity[]): SubagentTask[] {+ const tasks = new Map<string, SubagentTask>();+ const pendingOperations = new Map<string, PendingTodoOperation>();+ for (const activity of activities) {+ if (!isSubagentTodoActivity(activity)) continue;+ const toolName = activity.tool_name?.toLowerCase() || '';+ const payload = parseJsonPayload(activity.summary);+ if (activity.kind === 'tool_call') {+ if (payload && activity.tool_call_id) {+ pendingOperations.set(activity.tool_call_id, { toolName, payload });+ }+ continue;+ }+ if (activity.kind === 'tool_result') {+ const operation = activity.tool_call_id ? pendingOperations.get(activity.tool_call_id) : undefined;+ if (isSuccessfulTodoResult(activity.summary)) {+ if (operation) applyTodoPayload(tasks, operation.toolName, operation.payload, activity.at_ms);+ applyTaskResultLines(tasks, activity.summary, activity.at_ms);+ }+ if (activity.tool_call_id) pendingOperations.delete(activity.tool_call_id);+ }+ }+ return Array.from(tasks.values());+}++/** A successful final turn closes any todo items that lack individual completion events. */+export function finalizeSubagentTasks(tasks: SubagentTask[], turnCompleted: boolean, atMs?: number): SubagentTask[] {+ if (!turnCompleted) return tasks;+ return tasks.map(task => {+ const statusHistory = [...task.statusHistory];+ if (task.status !== 'completed') statusHistory.push({ status: 'completed', atMs, source: 'final' });+ return {+ ...task,+ status: 'completed',+ raw: { ...task.raw, status: 'completed' },+ statusHistory,+ };+ });+}++/**+ * Return the concise, user-facing label for a logical activity. The complete+ * call/result stream remains available through the row disclosure.+ */+export function getSubagentActivityPreview(group: SubagentActivityGroup): string {+ if (group.activity.kind === 'thinking') return boundedPreview(group.summary);++ const toolCall = group.activities.find(activity => activity.kind === 'tool_call');+ const toolResult = group.activities.find(activity => activity.kind === 'tool_result');+ const toolName = (toolCall?.tool_name || toolResult?.tool_name || group.activity.tool_name || '').toLowerCase();+ const callSummary = toolCall?.summary || '';+ const resultSummary = toolResult?.summary || '';++ if (toolName.includes('todo')) {+ return extractStringField(callSummary, 'content')+ || extractStringField(callSummary, 'activeForm')+ || resultPreview(resultSummary);+ }+ if (toolName.includes('search') || toolName.includes('fetch') || toolName.includes('web')) {+ return resultPreview(resultSummary) || extractStringField(callSummary, 'url');+ }+ if (toolName.includes('bash') || toolName.includes('terminal') || toolName.includes('shell')) {+ return extractStringField(callSummary, 'command') || resultPreview(resultSummary);+ }+ return resultPreview(resultSummary) || firstNonEmptyLine(callSummary || group.summary);+}++function createGroup(activity: SubagentActivity): SubagentActivityGroup {+ return {+ activity,+ activities: [activity],+ summary: activity.summary,+ count: 1,+ };+}++function canMergeThinking(left: SubagentActivity, right: SubagentActivity): boolean {+ return left.kind === 'thinking'+ && right.kind === 'thinking'+ && left.task_id === right.task_id+ && (+ (left.phase_id === undefined && right.phase_id === undefined)+ || (left.phase_id !== undefined && right.phase_id !== undefined && left.phase_id === right.phase_id)+ );+}++function phaseKey(activity: SubagentActivity): string | null {+ if (activity.kind !== 'thinking' || activity.phase_id === undefined) return null;+ return `${activity.task_id}:${activity.phase_id}`;+}++function appendSummary(group: SubagentActivityGroup, activity: SubagentActivity): void {+ const previous = group.activities[group.activities.length - 1];+ const summary = activity.summary || '';+ if (!summary) return;+ group.summary += previous.kind === activity.kind ? summary : `\n\n${summary}`;+}++/**+ * Keep tool events as independent rows, while coalescing contiguous thinking+ * chunks from the same task into one phase activity. A tool call/result is a+ * real phase boundary; task_id alone is not enough to merge later thinking.+ */+export function groupSubagentActivities(activities: SubagentActivity[]): SubagentActivityGroup[] {+ const groups: SubagentActivityGroup[] = [];+ const thinkingGroupsByPhase = new Map<string, SubagentActivityGroup>();+ for (const activity of activities) {+ if (activity.kind === 'thinking') {+ const key = phaseKey(activity);+ const existingPhase = key ? thinkingGroupsByPhase.get(key) : undefined;+ if (existingPhase) {+ appendSummary(existingPhase, activity);+ existingPhase.activities.push(activity);+ existingPhase.count += 1;+ continue;+ }+ }+ const previous = groups[groups.length - 1];+ const previousActivity = previous?.activities[previous.activities.length - 1];+ if (previous && previousActivity && canMergeThinking(previousActivity, activity)) {+ appendSummary(previous, activity);+ previous.activities.push(activity);+ previous.count += 1;+ continue;+ }+ const group = createGroup(activity);+ groups.push(group);+ const key = phaseKey(activity);+ if (key) thinkingGroupsByPhase.set(key, group);+ }+ return groups;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentNormalizer.tsnew file mode 100644index 0000000000..c9f5f6329b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentNormalizer.ts@@ -0,0 +1,326 @@+import type {+ Subagent,+ SubagentActivity,+ SubagentActivityEvent,+ SubagentActivityKind,+ SubagentClosedReason,+ SubagentError,+ SubagentLifecycle,+ SubagentResult,+ SubagentStatus,+ SubagentTurnOutcome,+ SubagentUpdatedEvent,+} from '../../types/subagent';++type RecordValue = Record<string, unknown>;++const ACTIVITY_KINDS = new Set<SubagentActivityKind>([+ 'tool_call',+ 'tool_result',+ 'thinking',+ 'error',+ 'truncated',+]);++function asRecord(value: unknown): RecordValue | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : null;+}++function asString(value: unknown): string | null {+ return typeof value === 'string' && value.trim() ? value.trim() : null;+}++function asNumber(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}++function asNonNegativeInteger(value: unknown): number | null {+ const number = asNumber(value);+ return number !== null && Number.isSafeInteger(number) && number >= 0 ? number : null;+}++function normalizeLifecycle(value: unknown): SubagentLifecycle | null {+ return value === 'live' || value === 'closed' ? value : null;+}++function normalizeTurnOutcome(value: unknown): SubagentTurnOutcome | null {+ if (value === 'completed' || value === 'failed' || value === 'parent_ended') return value;+ if (value === 'cancelled' || value === 'canceled') return 'cancelled';+ return null;+}++function normalizeStatus(+ value: string,+ lifecycle: SubagentLifecycle | null,+ canSendInput: boolean | null,+ needsResume: boolean | null,+): SubagentStatus | null {+ if (lifecycle === 'closed' || needsResume === true) return 'closed';+ if (value === 'running' || value === 'starting' || value === 'pending') return 'running';+ if (value === 'idle') return 'idle';+ if (value === 'closed') return 'closed';+ if (+ lifecycle === 'live'+ && canSendInput === true+ && ['completed', 'failed', 'error', 'cancelled', 'canceled'].includes(value)+ ) return 'idle';+ if (value === 'completed' || value === 'failed' || value === 'error' || value === 'cancelled' || value === 'canceled') return 'closed';+ return null;+}++function normalizeClosedReason(value: unknown, status: SubagentStatus, rawStatus: string, turnOutcome: SubagentTurnOutcome | null): SubagentClosedReason | null {+ if (status !== 'closed') return null;+ if (value === 'canceled') return 'cancelled';+ if (value === 'completed' || value === 'failed' || value === 'cancelled' || value === 'parent_ended' || value === 'manual' || value === 'evicted') {+ return value;+ }+ if (rawStatus === 'error' || rawStatus === 'failed') return 'failed';+ if (rawStatus === 'canceled' || rawStatus === 'cancelled') return 'cancelled';+ if (turnOutcome === 'failed') return 'failed';+ if (turnOutcome === 'cancelled') return 'cancelled';+ if (turnOutcome === 'parent_ended') return 'parent_ended';+ return 'completed';+}++function normalizeError(value: unknown, rawStatus: string, rawMessage: unknown, turnOutcome: SubagentTurnOutcome | null): SubagentError | null {+ const raw = asRecord(value);+ const message = asString(raw?.message) ?? (rawStatus === 'error' || rawStatus === 'failed' || turnOutcome === 'failed' ? asString(rawMessage) : null);+ if (!message) return null;+ return {+ code: asString(raw?.code) ?? 'SUBAGENT_ERROR',+ message,+ };+}++export function normalizeSubagent(value: unknown, sessionId?: string): Subagent | null {+ const raw = asRecord(value);+ if (!raw) return null;++ const subagentId = asString(raw.subagent_id ?? raw.subagentId);+ const parentSessionId = asString(raw.parent_session_id ?? raw.parentSessionId) ?? sessionId ?? null;+ if (sessionId && parentSessionId && parentSessionId !== sessionId) return null;+ const description = asString(raw.description);+ const displayName = asString(raw.display_name ?? raw.displayName) ?? description ?? subagentId;+ const rawStatus = (asString(raw.status) ?? '').toLowerCase();+ const turnOutcome = normalizeTurnOutcome(raw.turn_outcome ?? raw.turnOutcome);+ const lifecycle = normalizeLifecycle(raw.lifecycle);+ const canSendInput = typeof raw.can_send_input === 'boolean' ? raw.can_send_input : null;+ const needsResume = typeof raw.needs_resume === 'boolean' ? raw.needs_resume : null;+ const status = normalizeStatus(rawStatus, lifecycle, canSendInput, needsResume);+ const createdAt = asNumber(raw.created_at ?? raw.createdAt) ?? asNumber(raw.updated_at ?? raw.updatedAt) ?? 0;+ const updatedAt = asNumber(raw.updated_at ?? raw.updatedAt) ?? createdAt;+ const revision = asNonNegativeInteger(raw.revision) ?? 0;+ if (!subagentId || !parentSessionId || !displayName || !status) return null;++ return {+ subagent_id: subagentId,+ parent_session_id: parentSessionId,+ subagent_type: asString(raw.subagent_type ?? raw.subagentType) ?? '',+ display_name: displayName,+ role: asString(raw.role) ?? '',+ task_description: asString(raw.task_description ?? raw.taskDescription) ?? '',+ status,+ turn_outcome: turnOutcome,+ lifecycle,+ can_send_input: canSendInput,+ needs_resume: needsResume,+ closed_at: status === 'closed' ? asNumber(raw.closed_at ?? raw.closedAt) : null,+ closed_reason: normalizeClosedReason(raw.closed_reason ?? raw.closedReason, status, rawStatus, turnOutcome),+ error: normalizeError(raw.error, rawStatus, raw.message, turnOutcome),+ created_at: createdAt,+ updated_at: updatedAt,+ revision,+ };+}++export function normalizeSubagentActivity(value: unknown, sessionId?: string): SubagentActivity | null {+ const raw = asRecord(value);+ if (!raw) return null;++ const subagentId = asString(raw.subagent_id ?? raw.subagentId);+ const parentSessionId = asString(raw.parent_session_id ?? raw.parentSessionId) ?? sessionId ?? null;+ if (sessionId && parentSessionId && parentSessionId !== sessionId) return null;+ const taskId = asString(raw.task_id ?? raw.taskId) ?? subagentId;+ const sequence = asNonNegativeInteger(raw.seq ?? raw.sequence);+ const kind = ACTIVITY_KINDS.has(raw.kind as SubagentActivityKind) ? raw.kind as SubagentActivityKind : null;+ const atMs = asNumber(raw.at_ms ?? raw.atMs);+ if (!subagentId || !taskId || sequence === null || !kind || atMs === null) return null;++ const activityId = asString(raw.activity_id ?? raw.activityId) ?? `${subagentId}:${taskId}:${sequence}`;+ const normalized: SubagentActivity = {+ activity_id: activityId,+ subagent_id: subagentId,+ ...(parentSessionId ? { parent_session_id: parentSessionId } : {}),+ task_id: taskId,+ sequence,+ kind,+ summary: typeof raw.summary === 'string' ? raw.summary : '',+ at_ms: atMs,+ };+ const toolName = asString(raw.tool_name ?? raw.toolName);+ const toolCallId = asString(raw.tool_call_id ?? raw.toolCallId);+ const phaseId = asNonNegativeInteger(raw.phase_id ?? raw.phaseId);+ if (phaseId !== null && phaseId > 0) normalized.phase_id = phaseId;+ if (toolName) normalized.tool_name = toolName;+ if (toolCallId) normalized.tool_call_id = toolCallId;+ if (typeof raw.ok === 'boolean') normalized.ok = raw.ok;+ const dropped = asNonNegativeInteger(raw.dropped);+ if (dropped !== null) normalized.dropped = dropped;+ return normalized;+}++export function isNativeSubagentRosterPayload(value: unknown): boolean {+ const raw = asRecord(value);+ if (!raw) return false;+ if (!asString(raw.subagent_id ?? raw.subagentId)) return false;+ if (raw.legacy_status != null) return true;+ const status = (asString(raw.status) ?? '').toLowerCase();+ return status === 'running' || status === 'idle' || status === 'closed' || status === 'starting' || status === 'pending';+}++export function normalizeSubagentStatusEvent(value: unknown): SubagentUpdatedEvent | null {+ const raw = asRecord(value);+ if (!raw || (raw.event_type !== undefined && raw.event_type !== 'chat.subtask_update')) return null;+ const sessionId = asString(raw.session_id ?? raw.sessionId ?? raw.parent_session_id ?? raw.parentSessionId);+ if (!sessionId) return null;+ const subagent = normalizeSubagent(raw, sessionId);+ if (!subagent) return null;+ return {+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent,+ };+}++export function normalizeSubagentActivityEvent(value: unknown): SubagentActivityEvent | null {+ const raw = asRecord(value);+ if (!raw || (raw.event_type !== undefined && raw.event_type !== 'chat.subagent_activity')) return null;+ const sessionId = asString(raw.session_id ?? raw.sessionId ?? raw.parent_session_id ?? raw.parentSessionId);+ const activity = normalizeSubagentActivity(raw, sessionId ?? undefined);+ if (!sessionId || !activity) return null;+ return {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity,+ };+}++export interface SubagentToolStatusUpdate {+ subagent_id: string;+ status: SubagentStatus;+ task_id?: string;+}++const STATUS_TOOL_NAMES = new Set(['subagent_close', 'subagent_list', 'subagent_resume', 'subagent_send_input', 'subagent_spawn']);++function normalizeToolStatus(value: unknown): SubagentStatus | null {+ const status = asString(value)?.toLowerCase();+ if (!status) return null;+ if (status === 'running' || status === 'starting' || status === 'pending' || status === 'pending_init') return 'running';+ if (status === 'idle' || status === 'completed' || status === 'failed' || status === 'error' || status === 'cancelled' || status === 'canceled' || status === 'interrupted') return 'idle';+ if (status === 'closed') return 'closed';+ return null;+}++// Parses the compatibility `result` string (str() of the structured tool+// result) for subagent ids and statuses; removed once the UI reads structured+// data instead.+function extractToolResultText(value: RecordValue): string {+ const nested = asRecord(value.tool_result) ?? value;+ const rawOutput = asRecord(nested.raw_output ?? nested.rawOutput);+ const candidates = [+ nested.result,+ rawOutput?.result,+ nested.data,+ rawOutput?.data,+ ];+ return candidates.find((candidate): candidate is string => typeof candidate === 'string') ?? '';+}++function toolResultSucceeded(value: RecordValue, resultText: string): boolean {+ const nested = asRecord(value.tool_result) ?? value;+ if (typeof value.success === 'boolean') return value.success;+ if (typeof nested.success === 'boolean') return nested.success;+ const rawSuccess = /\bsuccess\s*=\s*(True|False)\b/i.exec(resultText)?.[1];+ if (rawSuccess) return rawSuccess.toLowerCase() === 'true';+ const jsonSuccess = /["']success["']\s*:\s*(true|false)\b/i.exec(resultText)?.[1];+ return jsonSuccess?.toLowerCase() === 'true';+}++function collectStructuredToolStatuses(value: unknown, updates: Map<string, SubagentToolStatusUpdate>): void {+ if (Array.isArray(value)) {+ value.forEach(item => collectStructuredToolStatuses(item, updates));+ return;+ }+ const record = asRecord(value);+ if (!record) return;++ const subagentId = asString(record.subagent_id ?? record.subagentId);+ const status = normalizeToolStatus(record.status);+ if (subagentId && status) {+ const taskId = asString(record.task_id ?? record.taskId);+ updates.set(subagentId, { subagent_id: subagentId, status, ...(taskId ? { task_id: taskId } : {}) });+ }+ Object.values(record).forEach(item => collectStructuredToolStatuses(item, updates));+}++function collectTextToolStatuses(resultText: string, updates: Map<string, SubagentToolStatusUpdate>): void {+ const idPattern = /["'](?:subagent_id|subagentId)["']\s*:\s*(["'])([^"']+)\1/g;+ const matches = [...resultText.matchAll(idPattern)];+ matches.forEach((match, index) => {+ const start = match.index ?? 0;+ const end = matches[index + 1]?.index ?? resultText.length;+ const statusMatch = /["']status["']\s*:\s*(["'])([^"']+)\1/.exec(resultText.slice(start, end));+ const taskIdMatch = /["']task_id["']\s*:\s*(["'])([^"']+)\1/.exec(resultText.slice(start, end));+ const subagentId = match[2]?.trim();+ const status = normalizeToolStatus(statusMatch?.[2]);+ if (subagentId && status) {+ const taskId = taskIdMatch?.[2]?.trim();+ updates.set(subagentId, { subagent_id: subagentId, status, ...(taskId ? { task_id: taskId } : {}) });+ }+ });+}++/** Read explicit successful subagent control/list tool results for live roster convergence. */+export function normalizeSubagentToolStatusUpdates(value: unknown): SubagentToolStatusUpdate[] {+ const raw = asRecord(value);+ if (!raw) return [];+ const nested = asRecord(raw.tool_result) ?? raw;+ const toolName = asString(nested.tool_name ?? nested.toolName ?? nested.name ?? raw.tool_name ?? raw.toolName ?? raw.name)?.toLowerCase();+ if (!toolName || !STATUS_TOOL_NAMES.has(toolName)) return [];++ const resultText = extractToolResultText(raw);+ if (!toolResultSucceeded(raw, resultText)) return [];++ if (toolName === 'subagent_close') {+ const subagentId = asString(nested.subagent_id ?? nested.subagentId ?? raw.subagent_id ?? raw.subagentId)+ ?? /["']?subagent_id["']?\s*:\s*["']([^"']+)["']/.exec(resultText)?.[1]?.trim();+ return subagentId ? [{ subagent_id: subagentId, status: 'closed' }] : [];+ }++ const updates = new Map<string, SubagentToolStatusUpdate>();+ collectStructuredToolStatuses(nested, updates);+ collectTextToolStatuses(resultText, updates);+ return [...updates.values()];+}++export function normalizeSubagentWaitResults(value: unknown): SubagentResult[] {+ const raw = asRecord(value);+ const toolResult = asRecord(raw?.tool_result) ?? raw;+ const waitResult = asRecord(toolResult?.subagent_wait ?? toolResult?.subagentWait);+ const results = asRecord(waitResult?.results);+ if (!results) return [];+ const outputFiles = asRecord(waitResult?.output_files ?? waitResult?.outputFiles);++ return Object.entries(results).flatMap(([subagentId, content]) => {+ if (!subagentId || typeof content !== 'string' || !content.trim()) return [];+ const outputFile = typeof outputFiles?.[subagentId] === 'string' && outputFiles[subagentId].trim()+ ? outputFiles[subagentId].trim()+ : undefined;+ return [{+ subagent_id: subagentId,+ content,+ ...(outputFile ? { output_file: outputFile } : {}),+ }];+ });+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentStatusPresentation.ts b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentStatusPresentation.tsnew file mode 100644index 0000000000..6716cc6651--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/subagent/subagentStatusPresentation.ts@@ -0,0 +1,32 @@+import type { SubagentClosedReason, SubagentStatus, SubagentTurnOutcome } from '../../types/subagent';++export type SubagentStatusTone = 'running' | 'waiting' | 'success' | 'danger' | 'neutral';++export function getSubagentStatusTone(+ status: SubagentStatus,+ closedReason?: SubagentClosedReason | null,+ turnOutcome?: SubagentTurnOutcome | null,+): SubagentStatusTone {+ if (status === 'running') return 'running';+ if (status === 'idle') {+ if (turnOutcome === 'failed') return 'danger';+ return turnOutcome === 'cancelled' ? 'neutral' : 'waiting';+ }+ if (closedReason === 'failed' || closedReason === 'evicted' || turnOutcome === 'failed') return 'danger';+ return 'success';+}++export function getSubagentStatusLabelKey(+ status: SubagentStatus,+ closedReason?: SubagentClosedReason | null,+ turnOutcome?: SubagentTurnOutcome | null,+): string {+ if (status === 'running') return 'subagent.running';+ if (status === 'idle') {+ if (turnOutcome === 'failed') return 'subagent.failed';+ if (turnOutcome === 'cancelled') return 'subagent.cancelled';+ return 'subagent.idle';+ }+ if (closedReason === 'failed' || closedReason === 'evicted' || turnOutcome === 'failed') return 'subagent.failed';+ return 'subagent.closed';+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 01bded9408..8eff37fc33 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -42,7 +42,13 @@ import {useHarnessStore,useWorkspaceStore,useCronStore,+ useSubagentStore,} from '../stores';+import {+ isNativeSubagentRosterPayload,+ normalizeSubagentActivityEvent,+ normalizeSubagentStatusEvent,+} from '../features/subagent/subagentNormalizer';import { normalizeTaskEvent } from '../stores/teamTaskNormalize';import { webClient, requestGoalAction, sendGoalStreamCommand } from '../services/webClient';import {@@ -443,7 +449,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {}function getPayloadSessionId(payload: Record<string, unknown>): string | undefined {- const direct = pickString(payload.session_id);+ const direct = pickString(payload.session_id, payload.parent_session_id);if (direct) {return direct;}@@ -1975,6 +1981,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {async (sessionId: string) => {try {await interrupt(sessionId, 'cancel');+ useSubagentStore.getState().markRunningSubagentsCancelled(sessionId);} catch (error) {const webError = error as WebError;setConnectionStats({ lastError: webError.message });@@ -3784,8 +3791,31 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('chat.subtask_update', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;+ if (isNativeSubagentRosterPayload(payload)) {+ const event = normalizeSubagentStatusEvent({+ ...payload,+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ });+ if (event) {+ useSubagentStore.getState().applyEvent(sessionId, event);+ }+ return;+ }useChatStore.getState().updateSubtask(sessionId, payload as unknown as SubtaskUpdatePayload);}),+ webClient.on('chat.subagent_activity', ({ payload }) => {+ const sessionId = resolveEventSessionId(payload);+ if (!sessionId) return;+ const event = normalizeSubagentActivityEvent({+ ...payload,+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ });+ if (event) {+ useSubagentStore.getState().applyEvent(sessionId, event);+ }+ }),webClient.on('chat.ask_user_question', ({ 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 e6010139be..05db63f8c9 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -2990,5 +2990,46 @@"errors": {"actionFailed": "Action failed"}+ },+ "subagent": {+ "title": "Subagents",+ "compactTitle": "Subagents ({{count}})",+ "activeListTitle": "Active now {{count}}",+ "expand": "Expand Subagents",+ "selectWithStatus": "Select {{name}}, status: {{status}}",+ "running": "Running",+ "idle": "Waiting",+ "closed": "Closed",+ "failed": "Error",+ "cancelled": "Cancelled",+ "activityTitle": "Activity",+ "activityEmpty": "No activity yet",+ "historyLoading": "Restoring history…",+ "empty": "No subagents",+ "activity": {+ "thinking": "Thinking",+ "toolCall": "Tool call",+ "toolResult": "Tool result",+ "expand": "Expand activity details",+ "collapse": "Collapse activity details",+ "ok": "OK",+ "error": "Error",+ "truncated": "Activity condensed",+ "fields": {+ "type": "Type",+ "time": "Time",+ "tool": "Tool",+ "call": "Call",+ "result": "Result",+ "content": "Content",+ "status": "Status",+ "dropped": "Dropped"+ },+ "tools": {+ "search": "Web search",+ "terminal": "Terminal",+ "todo": "Task list"+ }+ }}}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 1095a0912f..99f54dac5e 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -2979,5 +2979,46 @@"errors": {"actionFailed": "操作失败"}+ },+ "subagent": {+ "title": "子智能体",+ "compactTitle": "子智能体({{count}})",+ "activeListTitle": "当前活跃 {{count}}",+ "expand": "展开子智能体",+ "selectWithStatus": "选择 {{name}},状态:{{status}}",+ "running": "运行中",+ "idle": "待机中",+ "closed": "已关闭",+ "failed": "异常",+ "cancelled": "已取消",+ "activityTitle": "活动",+ "activityEmpty": "暂无活动",+ "historyLoading": "正在恢复历史…",+ "empty": "暂无子智能体",+ "activity": {+ "thinking": "思考",+ "toolCall": "工具调用",+ "toolResult": "工具结果",+ "expand": "展开活动详情",+ "collapse": "收起活动详情",+ "ok": "完成",+ "error": "异常",+ "truncated": "活动已折叠",+ "fields": {+ "type": "类型",+ "time": "时间",+ "tool": "工具",+ "call": "调用",+ "result": "结果",+ "content": "内容",+ "status": "状态",+ "dropped": "丢弃数量"+ },+ "tools": {+ "search": "搜索网页",+ "terminal": "运行终端",+ "todo": "待办清单"+ }+ }}}diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex 0ce3da195e..67b2b14fc9 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -35,7 +35,7 @@ export const PAUSABLE_STREAM_EVENTS = new Set([// 会把 processing 翻回 true,暂停中的 thinking 面板"复活"。'chat.reasoning','todo.updated', 'context.compressed', 'context.usage',- 'chat.subtask_update', 'chat.usage_summary',+ 'chat.subtask_update', 'chat.subagent_activity', 'chat.usage_summary',]);export interface PauseBufferHook {diff --git a/jiuwenswarm/channels/web/frontend/src/stores/index.ts b/jiuwenswarm/channels/web/frontend/src/stores/index.tsindex ef927278e9..23aec5fbad 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/index.ts@@ -8,6 +8,8 @@ export { useGoalStore } from './goalStore';export { useSessionStore, resolveEffectiveModel } from './sessionStore';export { PROJECT_SESSION_PAGE_SIZE, useWorkspaceStore } from './workspaceStore';export { useHarnessStore } from './harnessStore';+export { useSubagentStore } from './subagentStore';+export type { SubagentRuntime } from './subagentStore';export { ensureSessionRuntimes } from './ensureSessionRuntimes';export { useCronStore, filterJobsForProject, isDefaultProjectId, isWebChannelJob } from './cronStore';export { usePersonalContextStore } from './personalContextStore';diff --git a/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.tsnew file mode 100644index 0000000000..77a8d3b647--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts@@ -0,0 +1,898 @@+import { create } from 'zustand';+import type { Subagent, SubagentActivity, SubagentEvent, SubagentResult, SubagentTurn, SubagentUpdatedEvent } from '../types/subagent';++export interface SubagentRuntime {+ sessionId: string;+ revision: number;+ subagentsById: Record<string, Subagent>;+ activitiesBySubagentId: Record<string, Record<string, SubagentActivity>>;+ turnsBySubagentId: Record<string, Record<string, SubagentTurn>>;+ transcriptMessagesBySubagentId: Record<string, SubagentResult[]>;+ historyRestoringBySubagentId: Record<string, true>;+ resultsBySubagentId: Record<string, SubagentResult>;+ cacheOnlySubagentIds: Record<string, true>;+ selectedSubagentId: string | null;+}++const PERSISTED_RUNTIME_PREFIX = 'jiuwen.subagent.runtime.v1:';+const MAX_PERSISTED_ACTIVITIES = 500;+const PERSIST_DEBOUNCE_MS = 300;+const persistTimers = new Map<string, ReturnType<typeof setTimeout>>();+const pendingPersist = new Map<string, SubagentRuntime>();++interface PersistedSubagentRuntime {+ subagents: Subagent[];+ activities: SubagentActivity[];+ results: SubagentResult[];+ selectedSubagentId: string | null;+}++interface SubagentState {+ runtimes: Record<string, SubagentRuntime>;+ ensureRuntime: (sessionId: string) => SubagentRuntime;+ getRuntime: (sessionId: string | null | undefined) => SubagentRuntime | undefined;+ removeRuntime: (sessionId: string) => void;+ hydrateRuntime: (sessionId: string) => void;+ dropCachedSubagent: (sessionId: string, subagentId: string, revision: number, updatedAt: number) => void;+ applyEvent: (sessionId: string, event: SubagentEvent) => void;+ applyHistoryEvent: (sessionId: string, event: SubagentEvent) => void;+ applyToolStatus: (sessionId: string, subagentId: string, status: Subagent['status'], updatedAt: number, taskDescription?: string, taskId?: string) => void;+ beginHistoryRestore: (sessionId: string, subagentId: string) => void;+ finishHistoryRestore: (sessionId: string, subagentId: string) => void;+ applyTurn: (sessionId: string, subagentId: string, taskId: string, taskDescription: string, startedAt: number) => void;+ markRunningSubagentsCancelled: (sessionId: string) => void;+ applyResult: (sessionId: string, result: SubagentResult) => void;+ applyTranscript: (sessionId: string, result: SubagentResult) => void;+ setSelectedSubagent: (sessionId: string, subagentId: string | null) => void;+}++export function createEmptySubagentRuntime(sessionId: string): SubagentRuntime {+ const runtime = {+ sessionId,+ revision: 0,+ subagentsById: {},+ activitiesBySubagentId: {},+ turnsBySubagentId: {},+ transcriptMessagesBySubagentId: {},+ historyRestoringBySubagentId: {},+ resultsBySubagentId: {},+ cacheOnlySubagentIds: {},+ selectedSubagentId: null,+ };+ return mergePersistedRuntime(runtime, readPersistedRuntime(sessionId));+}++function getStorage(): Storage | null {+ if (typeof window === 'undefined') return null;+ try {+ return window.sessionStorage;+ } catch {+ return null;+ }+}++function storageKey(sessionId: string): string {+ return `${PERSISTED_RUNTIME_PREFIX}${encodeURIComponent(sessionId)}`;+}++function readPersistedRuntime(sessionId: string): PersistedSubagentRuntime | null {+ flushPersistRuntime(sessionId);+ const storage = getStorage();+ if (!storage) return null;+ try {+ const raw = JSON.parse(storage.getItem(storageKey(sessionId)) ?? 'null') as Partial<PersistedSubagentRuntime> | null;+ if (!raw || !Array.isArray(raw.subagents) || !Array.isArray(raw.activities) || !Array.isArray(raw.results)) {+ return null;+ }+ return {+ subagents: raw.subagents.filter((item): item is Subagent => Boolean(item && typeof item === 'object' && typeof item.subagent_id === 'string')),+ activities: raw.activities.filter((item): item is SubagentActivity => Boolean(item && typeof item === 'object' && typeof item.activity_id === 'string')),+ results: raw.results.filter((item): item is SubagentResult => Boolean(item && typeof item === 'object' && typeof item.subagent_id === 'string' && typeof item.content === 'string')),+ selectedSubagentId: typeof raw.selectedSubagentId === 'string' ? raw.selectedSubagentId : null,+ };+ } catch {+ return null;+ }+}++function persistRuntime(runtime: SubagentRuntime): void {+ const storage = getStorage();+ if (!storage) return;+ const activities = Object.values(runtime.activitiesBySubagentId)+ .flatMap((items) => Object.values(items))+ .sort(compareBySequence)+ .slice(-MAX_PERSISTED_ACTIVITIES);+ const payload: PersistedSubagentRuntime = {+ subagents: Object.values(runtime.subagentsById),+ activities,+ results: Object.values(runtime.resultsBySubagentId),+ selectedSubagentId: runtime.selectedSubagentId,+ };+ try {+ storage.setItem(storageKey(runtime.sessionId), JSON.stringify(payload));+ } catch {+ // Browser storage is best-effort; live state remains authoritative.+ }+}++function cancelPersistRuntime(sessionId: string): void {+ const timer = persistTimers.get(sessionId);+ if (timer !== undefined) {+ clearTimeout(timer);+ persistTimers.delete(sessionId);+ }+ pendingPersist.delete(sessionId);+}++function flushPersistRuntime(sessionId: string): void {+ const timer = persistTimers.get(sessionId);+ if (timer !== undefined) {+ clearTimeout(timer);+ persistTimers.delete(sessionId);+ }+ const runtime = pendingPersist.get(sessionId);+ if (!runtime) return;+ pendingPersist.delete(sessionId);+ persistRuntime(runtime);+}++function schedulePersistRuntime(runtime: SubagentRuntime, mode: 'debounce' | 'immediate'): void {+ pendingPersist.set(runtime.sessionId, runtime);+ if (mode === 'immediate') {+ flushPersistRuntime(runtime.sessionId);+ return;+ }+ const existing = persistTimers.get(runtime.sessionId);+ if (existing !== undefined) clearTimeout(existing);+ persistTimers.set(+ runtime.sessionId,+ setTimeout(() => {+ flushPersistRuntime(runtime.sessionId);+ }, PERSIST_DEBOUNCE_MS),+ );+}++function mergePersistedRuntime(runtime: SubagentRuntime, persisted: PersistedSubagentRuntime | null): SubagentRuntime {+ if (!persisted) return runtime;+ const subagentsById = { ...runtime.subagentsById };+ const cacheOnlySubagentIds = { ...runtime.cacheOnlySubagentIds };+ for (const subagent of persisted.subagents) {+ if (subagent.parent_session_id !== runtime.sessionId) continue;+ const current = subagentsById[subagent.subagent_id];+ if (current?.status === 'closed' && subagent.status !== 'closed') continue;+ if (!current || subagent.revision > current.revision) {+ subagentsById[subagent.subagent_id] = subagent;+ if (!current) cacheOnlySubagentIds[subagent.subagent_id] = true;+ }+ }+ const activitiesBySubagentId = { ...runtime.activitiesBySubagentId };+ const turnsBySubagentId = { ...runtime.turnsBySubagentId };+ for (const activity of persisted.activities) {+ if (activity.parent_session_id && activity.parent_session_id !== runtime.sessionId) continue;+ const scopedActivity = activity.parent_session_id+ ? activity+ : { ...activity, parent_session_id: runtime.sessionId };+ const existing = activitiesBySubagentId[scopedActivity.subagent_id] ?? {};+ activitiesBySubagentId[scopedActivity.subagent_id] = {+ ...existing,+ [scopedActivity.activity_id]: scopedActivity,+ };+ const turns = turnsBySubagentId[scopedActivity.subagent_id] ?? {};+ const currentTurn = turns[scopedActivity.task_id];+ turnsBySubagentId[scopedActivity.subagent_id] = {+ ...turns,+ [scopedActivity.task_id]: {+ task_id: scopedActivity.task_id,+ task_description: currentTurn?.task_description ?? '',+ started_at: Math.min(currentTurn?.started_at ?? scopedActivity.at_ms, scopedActivity.at_ms),+ ...(currentTurn?.result ? { result: currentTurn.result } : {}),+ },+ };+ }+ const resultsBySubagentId = { ...runtime.resultsBySubagentId };+ for (const result of persisted.results) {+ if (result.parent_session_id && result.parent_session_id !== runtime.sessionId) continue;+ if (!resultsBySubagentId[result.subagent_id]) {+ resultsBySubagentId[result.subagent_id] = result.parent_session_id+ ? result+ : { ...result, parent_session_id: runtime.sessionId };+ }+ }+ return {+ ...runtime,+ revision: Math.max(runtime.revision, ...Object.values(subagentsById).map((item) => item.revision)),+ subagentsById,+ activitiesBySubagentId,+ turnsBySubagentId,+ resultsBySubagentId,+ cacheOnlySubagentIds,+ selectedSubagentId: runtime.selectedSubagentId ?? persisted.selectedSubagentId ?? chooseDefaultSubagentId(subagentsById, null),+ };+}++function compareBySequence(left: SubagentActivity, right: SubagentActivity): number {+ return left.sequence - right.sequence || left.at_ms - right.at_ms || left.activity_id.localeCompare(right.activity_id);+}++function upsertSubagentTurn(+ runtime: SubagentRuntime,+ subagentId: string,+ taskId: string,+ taskDescription = '',+ startedAt = Date.now(),+ descriptionSource: 'fallback' | 'explicit' = 'explicit',+): SubagentRuntime {+ const normalizedTaskId = taskId.trim();+ if (!normalizedTaskId) return runtime;+ const turns = runtime.turnsBySubagentId[subagentId] ?? {};+ const current = turns[normalizedTaskId];+ const normalizedTaskDescription = taskDescription.trim();+ const useIncomingDescription = Boolean(normalizedTaskDescription)+ && (!current?.task_description || current.description_source === 'fallback' || descriptionSource === 'explicit');+ const nextTaskDescription = useIncomingDescription+ ? normalizedTaskDescription+ : current?.task_description || '';+ const nextDescriptionSource = useIncomingDescription+ ? (descriptionSource === 'fallback' ? 'fallback' as const : undefined)+ : current?.description_source;+ const next: SubagentTurn = {+ task_id: normalizedTaskId,+ task_description: nextTaskDescription,+ ...(nextDescriptionSource ? { description_source: nextDescriptionSource } : {}),+ started_at: Math.min(current?.started_at ?? startedAt, startedAt),+ ...(current?.result ? { result: current.result } : {}),+ };+ if (current+ && current.task_description === next.task_description+ && current.description_source === next.description_source+ && current.started_at === next.started_at+ && current.result === next.result) return runtime;+ return {+ ...runtime,+ turnsBySubagentId: {+ ...runtime.turnsBySubagentId,+ [subagentId]: { ...turns, [normalizedTaskId]: next },+ },+ };+}++function updateLatestSubagentTurnDescription(+ runtime: SubagentRuntime,+ subagentId: string,+ taskDescription: string,+): SubagentRuntime {+ if (!taskDescription.trim()) return runtime;+ const turns = runtime.turnsBySubagentId[subagentId] ?? {};+ const ordered = Object.values(turns).sort((left, right) => left.started_at - right.started_at);+ const latest = ordered[ordered.length - 1];+ if (!latest || latest.task_description.trim()) return runtime;+ const nextLatest = { ...latest, task_description: taskDescription.trim() };+ delete nextLatest.description_source;+ return {+ ...runtime,+ turnsBySubagentId: {+ ...runtime.turnsBySubagentId,+ [subagentId]: {+ ...turns,+ [latest.task_id]: nextLatest,+ },+ },+ };+}++function selectTurnForResult(runtime: SubagentRuntime, subagentId: string, result: SubagentResult): string | null {+ if (result.task_id?.trim()) return result.task_id.trim();+ const turns = Object.values(runtime.turnsBySubagentId[subagentId] ?? {}).sort((left, right) => left.started_at - right.started_at);+ if (turns.length === 0) return null;+ if (typeof result.at_ms === 'number' && Number.isFinite(result.at_ms)) {+ const eligible = turns.filter(turn => turn.started_at <= result.at_ms!);+ return (eligible[eligible.length - 1] ?? turns[turns.length - 1]).task_id;+ }+ return turns[turns.length - 1].task_id;+}++function attachTurnResult(runtime: SubagentRuntime, result: SubagentResult): SubagentRuntime {+ const taskId = selectTurnForResult(runtime, result.subagent_id, result);+ if (!taskId) return runtime;+ const turns = runtime.turnsBySubagentId[result.subagent_id] ?? {};+ const current = turns[taskId];+ if (current?.result?.source === 'wait') return runtime;+ const nextResult = {+ ...result,+ task_id: taskId,+ };+ return {+ ...runtime,+ turnsBySubagentId: {+ ...runtime.turnsBySubagentId,+ [result.subagent_id]: {+ ...turns,+ [taskId]: {+ task_id: taskId,+ task_description: current?.task_description ?? '',+ started_at: current?.started_at ?? result.at_ms ?? Date.now(),+ ...(current?.description_source ? { description_source: current.description_source } : {}),+ result: nextResult,+ },+ },+ },+ };+}++function attachPendingTranscripts(runtime: SubagentRuntime, subagentId: string): SubagentRuntime {+ const pending = runtime.transcriptMessagesBySubagentId[subagentId] ?? [];+ if (pending.length === 0) return runtime;+ let next = runtime;+ const remaining: SubagentResult[] = [];+ for (const result of pending) {+ if (selectTurnForResult(next, subagentId, result)) {+ const attached = attachTurnResult(next, result);+ if (attached === next) remaining.push(result);+ else next = attached;+ } else {+ remaining.push(result);+ }+ }+ return {+ ...next,+ transcriptMessagesBySubagentId: {+ ...next.transcriptMessagesBySubagentId,+ [subagentId]: remaining,+ },+ };+}++function compareByUpdatedAt(left: Subagent, right: Subagent): number {+ return right.updated_at - left.updated_at || left.display_name.localeCompare(right.display_name) || left.subagent_id.localeCompare(right.subagent_id);+}++function statusRank(status: Subagent['status']): number {+ if (status === 'running') return 0;+ if (status === 'idle') return 1;+ return 2;+}++function chooseDefaultSubagentId(subagentsById: Record<string, Subagent>, preferredId: string | null): string | null {+ if (preferredId && subagentsById[preferredId]) return preferredId;+ const subagents = Object.values(subagentsById);+ return subagents+ .filter(subagent => subagent.status === 'running')+ .sort(compareByUpdatedAt)[0]?.subagent_id+ ?? subagents.sort(compareByUpdatedAt)[0]?.subagent_id+ ?? null;+}++function replaceSubagent(runtime: SubagentRuntime, incoming: Subagent, allowSameRevisionNewerSource = false): SubagentRuntime {+ const current = runtime.subagentsById[incoming.subagent_id];+ if (current) {+ const isNewerFollowUpTurn = incoming.task_description.trim() !== ''+ && incoming.task_description !== current.task_description+ && incoming.updated_at > current.updated_at;+ if (current.status === 'closed' && incoming.status !== 'closed' && !allowSameRevisionNewerSource && !isNewerFollowUpTurn) return runtime;+ const incomingIsOlder = incoming.revision < current.revision+ || (+ incoming.revision === current.revision+ && ((!allowSameRevisionNewerSource && !isNewerFollowUpTurn) || incoming.updated_at <= current.updated_at)+ );+ if (incomingIsOlder) {+ const hasUsefulDisplayName = current.display_name.trim() === 'general-purpose'+ && incoming.display_name.trim() !== ''+ && incoming.display_name.trim() !== 'general-purpose';+ if (!hasUsefulDisplayName) return runtime;+ return {+ ...runtime,+ subagentsById: {+ ...runtime.subagentsById,+ [incoming.subagent_id]: {+ ...current,+ display_name: incoming.display_name,+ role: incoming.role.trim() ? incoming.role : current.role,+ },+ },+ };+ }+ }++ // Some recovery sources only carry the status transition. Keep the canonical+ // assignment metadata when a newer sparse snapshot omits it.+ const mergedIncoming = current+ ? {+ ...incoming,+ role: incoming.role.trim() ? incoming.role : current.role,+ task_description: incoming.task_description.trim() ? incoming.task_description : current.task_description,+ }+ : incoming;++ const subagentsById = {+ ...runtime.subagentsById,+ [incoming.subagent_id]: mergedIncoming,+ };+ return {+ ...runtime,+ revision: Math.max(runtime.revision, incoming.revision),+ subagentsById,+ cacheOnlySubagentIds: Object.fromEntries(+ Object.entries(runtime.cacheOnlySubagentIds).filter(([subagentId]) => subagentId !== incoming.subagent_id),+ ),+ selectedSubagentId: chooseDefaultSubagentId(subagentsById, runtime.selectedSubagentId),+ };+}++function replaceActivity(runtime: SubagentRuntime, incoming: SubagentActivity): SubagentRuntime {+ if (incoming.parent_session_id !== runtime.sessionId) return runtime;+ const existingById = runtime.activitiesBySubagentId[incoming.subagent_id] ?? {};+ if (existingById[incoming.activity_id]) return runtime;++ return {+ ...runtime,+ activitiesBySubagentId: {+ ...runtime.activitiesBySubagentId,+ [incoming.subagent_id]: {+ ...existingById,+ [incoming.activity_id]: incoming,+ },+ },+ cacheOnlySubagentIds: Object.fromEntries(+ Object.entries(runtime.cacheOnlySubagentIds).filter(([subagentId]) => subagentId !== incoming.subagent_id),+ ),+ };+}++function replaceResult(runtime: SubagentRuntime, incoming: SubagentResult): SubagentRuntime {+ const current = runtime.resultsBySubagentId[incoming.subagent_id];+ if (current && current.content === incoming.content && current.output_file === incoming.output_file && current.source === incoming.source) return runtime;+ return {+ ...runtime,+ resultsBySubagentId: {+ ...runtime.resultsBySubagentId,+ [incoming.subagent_id]: incoming,+ },+ cacheOnlySubagentIds: Object.fromEntries(+ Object.entries(runtime.cacheOnlySubagentIds).filter(([subagentId]) => subagentId !== incoming.subagent_id),+ ),+ };+}++export function applySubagentUpdated(runtime: SubagentRuntime, event: SubagentUpdatedEvent): SubagentRuntime {+ if (event.session_id !== runtime.sessionId || event.subagent.parent_session_id !== runtime.sessionId) return runtime;+ return replaceSubagent(runtime, event.subagent);+}++export function applySubagentHistoryUpdated(runtime: SubagentRuntime, event: SubagentUpdatedEvent): SubagentRuntime {+ if (event.session_id !== runtime.sessionId || event.subagent.parent_session_id !== runtime.sessionId) return runtime;+ return replaceSubagent(runtime, event.subagent, true);+}++export function applySubagentToolStatus(+ runtime: SubagentRuntime,+ subagentId: string,+ status: Subagent['status'],+ turnStartedAt: number,+ taskDescription?: string,+ taskId?: string,+): SubagentRuntime {+ const current = runtime.subagentsById[subagentId];+ if (!current) return runtime;+ const hasExplicitTaskDescription = Boolean(taskDescription?.trim());+ const nextTaskDescription = taskDescription?.trim() || current.task_description;+ if (current.status === status && nextTaskDescription === current.task_description) return runtime;++ const next: Subagent = {+ ...current,+ status,+ task_description: nextTaskDescription,+ // The tool result only bridges the missing status event. Keep the last+ // authoritative timestamp so the subsequent canonical roster event can+ // still carry the follow-up assignment at the same revision.+ updated_at: current.updated_at,+ revision: current.revision,+ ...(status === 'running'+ ? {+ turn_outcome: null,+ lifecycle: 'live' as const,+ can_send_input: false,+ needs_resume: false,+ closed_at: null,+ closed_reason: null,+ error: null,+ }+ : status === 'idle'+ ? {+ lifecycle: 'live' as const,+ can_send_input: true,+ needs_resume: false,+ closed_at: null,+ closed_reason: null,+ error: null,+ }+ : {+ lifecycle: 'closed' as const,+ can_send_input: false,+ needs_resume: true,+ closed_at: current.closed_at,+ closed_reason: current.closed_reason,+ }),+ };+ const nextRuntime = {+ ...runtime,+ subagentsById: {+ ...runtime.subagentsById,+ [subagentId]: next,+ },+ selectedSubagentId: chooseDefaultSubagentId(runtime.subagentsById, runtime.selectedSubagentId),+ };+ const withTurnDescription = taskId+ ? upsertSubagentTurn(+ nextRuntime,+ subagentId,+ taskId,+ nextTaskDescription,+ turnStartedAt,+ hasExplicitTaskDescription ? 'explicit' : 'fallback',+ )+ : updateLatestSubagentTurnDescription(nextRuntime, subagentId, nextTaskDescription);+ return attachPendingTranscripts(withTurnDescription, subagentId);+}++export function applySubagentTurn(+ runtime: SubagentRuntime,+ subagentId: string,+ taskId: string,+ taskDescription: string,+ startedAt: number,+): SubagentRuntime {+ return attachPendingTranscripts(+ upsertSubagentTurn(runtime, subagentId, taskId, taskDescription, startedAt, 'explicit'),+ subagentId,+ );+}++export function applySubagentActivity(+ runtime: SubagentRuntime,+ event: Extract<SubagentEvent, { event_type: 'chat.subagent_activity' }>,+): SubagentRuntime {+ if (event.session_id !== runtime.sessionId) return runtime;+ const activity = event.activity.parent_session_id+ ? event.activity+ : { ...event.activity, parent_session_id: runtime.sessionId };+ const next = replaceActivity(runtime, activity);+ return next === runtime+ ? runtime+ : attachPendingTranscripts(+ upsertSubagentTurn(+ next,+ activity.subagent_id,+ activity.task_id,+ next.subagentsById[activity.subagent_id]?.task_description ?? '',+ activity.at_ms,+ 'fallback',+ ),+ activity.subagent_id,+ );+}++export function applySubagentResult(runtime: SubagentRuntime, result: SubagentResult): SubagentRuntime {+ if (!result.subagent_id) return runtime;+ if (result.parent_session_id && result.parent_session_id !== runtime.sessionId) return runtime;+ const normalized = {+ ...result,+ parent_session_id: result.parent_session_id ?? runtime.sessionId,+ source: 'wait',+ } satisfies SubagentResult;+ const next = replaceResult(runtime, normalized);+ if (next === runtime) return runtime;+ const pending = next.transcriptMessagesBySubagentId[result.subagent_id] ?? [];+ const withPending = selectTurnForResult(next, result.subagent_id, normalized)+ ? attachTurnResult(next, normalized)+ : {+ ...next,+ transcriptMessagesBySubagentId: {+ ...next.transcriptMessagesBySubagentId,+ [result.subagent_id]: [...pending, normalized],+ },+ };+ return attachPendingTranscripts(withPending, result.subagent_id);+}++export function dropCachedSubagent(+ runtime: SubagentRuntime,+ subagentId: string,+ expectedRevision: number,+ expectedUpdatedAt: number,+): SubagentRuntime {+ const current = runtime.subagentsById[subagentId];+ if (!runtime.cacheOnlySubagentIds[subagentId] || !current) return runtime;+ if (current.revision !== expectedRevision || current.updated_at !== expectedUpdatedAt) return runtime;++ const subagentsById = { ...runtime.subagentsById };+ const activitiesBySubagentId = { ...runtime.activitiesBySubagentId };+ const resultsBySubagentId = { ...runtime.resultsBySubagentId };+ const cacheOnlySubagentIds = { ...runtime.cacheOnlySubagentIds };+ delete subagentsById[subagentId];+ delete activitiesBySubagentId[subagentId];+ const turnsBySubagentId = { ...runtime.turnsBySubagentId };+ const transcriptMessagesBySubagentId = { ...runtime.transcriptMessagesBySubagentId };+ const historyRestoringBySubagentId = { ...runtime.historyRestoringBySubagentId };+ delete resultsBySubagentId[subagentId];+ delete turnsBySubagentId[subagentId];+ delete transcriptMessagesBySubagentId[subagentId];+ delete historyRestoringBySubagentId[subagentId];+ delete cacheOnlySubagentIds[subagentId];++ return {+ ...runtime,+ subagentsById,+ activitiesBySubagentId,+ turnsBySubagentId,+ transcriptMessagesBySubagentId,+ historyRestoringBySubagentId,+ resultsBySubagentId,+ cacheOnlySubagentIds,+ selectedSubagentId: chooseDefaultSubagentId(subagentsById, runtime.selectedSubagentId),+ };+}++export function markRunningSubagentsCancelled(runtime: SubagentRuntime, updatedAt = Date.now()): SubagentRuntime {+ const running = Object.values(runtime.subagentsById).filter(subagent => subagent.status === 'running');+ if (running.length === 0) return runtime;++ const revision = runtime.revision + 1;+ const subagentsById = { ...runtime.subagentsById };+ for (const subagent of running) {+ subagentsById[subagent.subagent_id] = {+ ...subagent,+ status: 'idle',+ turn_outcome: 'cancelled',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ closed_at: null,+ closed_reason: null,+ error: null,+ updated_at: Math.max(updatedAt, subagent.updated_at + 1),+ revision: Math.max(revision, subagent.revision + 1),+ };+ }+ return {+ ...runtime,+ revision: Math.max(revision, ...running.map(subagent => subagent.revision + 1)),+ subagentsById,+ selectedSubagentId: chooseDefaultSubagentId(subagentsById, runtime.selectedSubagentId),+ };+}++export function applySubagentTranscript(runtime: SubagentRuntime, result: SubagentResult): SubagentRuntime {+ if (!result.subagent_id || !result.content.trim()) return runtime;+ if (result.parent_session_id && result.parent_session_id !== runtime.sessionId) return runtime;+ const turnResult = {+ ...result,+ parent_session_id: result.parent_session_id ?? runtime.sessionId,+ source: 'transcript' as const,+ } satisfies SubagentResult;+ const pending = runtime.transcriptMessagesBySubagentId[result.subagent_id] ?? [];+ const pendingMessages = pending.some(item => item.content === turnResult.content && item.task_id === turnResult.task_id && item.at_ms === turnResult.at_ms)+ ? pending+ : [...pending, turnResult];+ const withPending = {+ ...runtime,+ transcriptMessagesBySubagentId: {+ ...runtime.transcriptMessagesBySubagentId,+ [result.subagent_id]: pendingMessages,+ },+ };+ const current = runtime.resultsBySubagentId[result.subagent_id];+ if (current?.source === 'wait') {+ return attachPendingTranscripts(withPending, result.subagent_id);+ }+ if (current?.source === 'transcript' && current.content.split('\n\n').includes(result.content)) {+ return attachPendingTranscripts(withPending, result.subagent_id);+ }+ const content = current?.source === 'transcript' && current.content.trim()+ ? `${current.content}\n\n${result.content}`+ : result.content;+ const normalized = {+ ...result,+ parent_session_id: result.parent_session_id ?? runtime.sessionId,+ content,+ source: 'transcript',+ } satisfies SubagentResult;+ return attachPendingTranscripts(replaceResult(withPending, normalized), result.subagent_id);+}++export function selectSubagents(runtime: SubagentRuntime | undefined): Subagent[] {+ if (!runtime) return [];+ return Object.values(runtime.subagentsById).sort((left, right) => {+ if (left.status !== right.status) return statusRank(left.status) - statusRank(right.status);+ return compareByUpdatedAt(left, right);+ });+}++export function selectSubagentActivities(runtime: SubagentRuntime | undefined, subagentId: string | null | undefined): SubagentActivity[] {+ if (!runtime || !subagentId) return [];+ return Object.values(runtime.activitiesBySubagentId[subagentId] ?? {}).sort(compareBySequence);+}++export function selectSubagentTurns(runtime: SubagentRuntime | undefined, subagentId: string | null | undefined): SubagentTurn[] {+ if (!runtime || !subagentId) return [];+ return Object.values(runtime.turnsBySubagentId[subagentId] ?? {}).sort((left, right) => left.started_at - right.started_at);+}++export function selectSubagentHistoryRestoring(runtime: SubagentRuntime | undefined, subagentId: string | null | undefined): boolean {+ return Boolean(runtime && subagentId && runtime.historyRestoringBySubagentId[subagentId]);+}++export function selectSubagentResult(runtime: SubagentRuntime | undefined, subagentId: string | null | undefined): SubagentResult | undefined {+ if (!runtime || !subagentId) return undefined;+ return runtime.resultsBySubagentId[subagentId];+}++export const useSubagentStore = create<SubagentState>((set, get) => ({+ runtimes: {},++ ensureRuntime: sessionId => {+ const existing = get().runtimes[sessionId];+ if (existing) return existing;+ const runtime = createEmptySubagentRuntime(sessionId);+ set(state => ({ runtimes: { ...state.runtimes, [sessionId]: runtime } }));+ return runtime;+ },++ getRuntime: sessionId => (sessionId ? get().runtimes[sessionId] : undefined),++ removeRuntime: sessionId => {+ set(state => {+ const runtimes = { ...state.runtimes };+ delete runtimes[sessionId];+ cancelPersistRuntime(sessionId);+ getStorage()?.removeItem(storageKey(sessionId));+ return { runtimes };+ });+ },++ hydrateRuntime: sessionId => {+ set(state => {+ const current = state.runtimes[sessionId] ?? createEmptySubagentRuntime(sessionId);+ const next = mergePersistedRuntime(current, readPersistedRuntime(sessionId));+ if (next === current) return state;+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ dropCachedSubagent: (sessionId, subagentId, revision, updatedAt) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const next = dropCachedSubagent(runtime, subagentId, revision, updatedAt);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ applyEvent: (sessionId, event) => {+ set(state => {+ const runtime = state.runtimes[sessionId] ?? createEmptySubagentRuntime(sessionId);+ const next = event.event_type === 'chat.subtask_update'+ ? applySubagentUpdated(runtime, event)+ : applySubagentActivity(runtime, event);+ if (next === runtime) return state;+ schedulePersistRuntime(+ next,+ event.event_type === 'chat.subagent_activity' ? 'debounce' : 'immediate',+ );+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ applyHistoryEvent: (sessionId, event) => {+ set(state => {+ const runtime = state.runtimes[sessionId] ?? createEmptySubagentRuntime(sessionId);+ const next = event.event_type === 'chat.subtask_update'+ ? applySubagentHistoryUpdated(runtime, event)+ : applySubagentActivity(runtime, event);+ if (next === runtime) return state;+ schedulePersistRuntime(+ next,+ event.event_type === 'chat.subagent_activity' ? 'debounce' : 'immediate',+ );+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ applyToolStatus: (sessionId, subagentId, status, updatedAt, taskDescription, taskId) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const next = applySubagentToolStatus(runtime, subagentId, status, updatedAt, taskDescription, taskId);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ beginHistoryRestore: (sessionId, subagentId) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime || runtime.historyRestoringBySubagentId[subagentId]) return state;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ historyRestoringBySubagentId: {+ ...runtime.historyRestoringBySubagentId,+ [subagentId]: true,+ },+ },+ },+ };+ });+ },++ finishHistoryRestore: (sessionId, subagentId) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime || !runtime.historyRestoringBySubagentId[subagentId]) return state;+ const historyRestoringBySubagentId = { ...runtime.historyRestoringBySubagentId };+ delete historyRestoringBySubagentId[subagentId];+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, historyRestoringBySubagentId },+ },+ };+ });+ },++ applyTurn: (sessionId, subagentId, taskId, taskDescription, startedAt) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const next = applySubagentTurn(runtime, subagentId, taskId, taskDescription, startedAt);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ markRunningSubagentsCancelled: sessionId => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const next = markRunningSubagentsCancelled(runtime);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ applyResult: (sessionId, result) => {+ set(state => {+ const runtime = state.runtimes[sessionId] ?? createEmptySubagentRuntime(sessionId);+ const next = applySubagentResult(runtime, result);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ applyTranscript: (sessionId, result) => {+ set(state => {+ const runtime = state.runtimes[sessionId] ?? createEmptySubagentRuntime(sessionId);+ const next = applySubagentTranscript(runtime, result);+ if (next === runtime) return state;+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },++ setSelectedSubagent: (sessionId, subagentId) => {+ set(state => {+ const runtime = state.runtimes[sessionId];+ if (!runtime || (subagentId !== null && !runtime.subagentsById[subagentId])) return state;+ const next = { ...runtime, selectedSubagentId: subagentId };+ schedulePersistRuntime(next, 'immediate');+ return { runtimes: { ...state.runtimes, [sessionId]: next } };+ });+ },+}));diff --git a/jiuwenswarm/channels/web/frontend/src/types/subagent.ts b/jiuwenswarm/channels/web/frontend/src/types/subagent.tsnew file mode 100644index 0000000000..b43b3fa91a--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/types/subagent.ts@@ -0,0 +1,83 @@+export type SubagentStatus = 'running' | 'idle' | 'closed';++export type SubagentTurnOutcome = 'completed' | 'failed' | 'cancelled' | 'parent_ended';++export type SubagentLifecycle = 'live' | 'closed';++export type SubagentClosedReason = 'completed' | 'failed' | 'cancelled' | 'parent_ended' | 'manual' | 'evicted';++export type SubagentActivityKind = 'tool_call' | 'tool_result' | 'thinking' | 'error' | 'truncated';++export interface SubagentError {+ code: string;+ message: string;+}++export interface Subagent {+ subagent_id: string;+ parent_session_id: string;+ subagent_type: string;+ display_name: string;+ role: string;+ task_description: string;+ status: SubagentStatus;+ turn_outcome: SubagentTurnOutcome | null;+ lifecycle: SubagentLifecycle | null;+ can_send_input: boolean | null;+ needs_resume: boolean | null;+ closed_at: number | null;+ closed_reason: SubagentClosedReason | null;+ error: SubagentError | null;+ created_at: number;+ updated_at: number;+ revision: number;+}++export interface SubagentActivity {+ activity_id: string;+ subagent_id: string;+ parent_session_id?: string;+ task_id: string;+ sequence: number;+ kind: SubagentActivityKind;+ summary: string;+ at_ms: number;+ phase_id?: number;+ tool_name?: string;+ tool_call_id?: string;+ ok?: boolean;+ dropped?: number;+}++export interface SubagentUpdatedEvent {+ event_type: 'chat.subtask_update';+ session_id: string;+ subagent: Subagent;+}++export interface SubagentActivityEvent {+ event_type: 'chat.subagent_activity';+ session_id: string;+ activity: SubagentActivity;+}++export interface SubagentResult {+ subagent_id: string;+ parent_session_id?: string;+ task_id?: string;+ at_ms?: number;+ content: string;+ output_file?: string;+ source?: 'wait' | 'transcript';+}++export interface SubagentTurn {+ task_id: string;+ task_description: string;+ /** Only set when the description came from a roster-level fallback. */+ description_source?: 'fallback';+ started_at: number;+ result?: SubagentResult;+}++export type SubagentEvent = SubagentUpdatedEvent | SubagentActivityEvent;diff --git a/jiuwenswarm/channels/web/frontend/tests/live_ws/.gitignore b/jiuwenswarm/channels/web/frontend/tests/live_ws/.gitignorenew file mode 100644index 0000000000..bab69911b6--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/live_ws/.gitignore@@ -0,0 +1,2 @@+*.browser.mjs+snapshot.jsondiff --git a/jiuwenswarm/channels/web/frontend/tests/live_ws/index.html b/jiuwenswarm/channels/web/frontend/tests/live_ws/index.htmlnew file mode 100644index 0000000000..131bb0ab02--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/live_ws/index.html@@ -0,0 +1,88 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <title>Subagent live WS harness</title>+</head>+<body>+ <p id="status">waiting</p>+ <pre id="out">{}</pre>+ <script type="module">+ import {+ useSubagentStore,+ selectSubagents,+ selectSubagentActivities,+ } from "./subagentStore.browser.mjs";+ import {+ normalizeSubagentStatusEvent,+ normalizeSubagentActivityEvent,+ } from "./subagentNormalizer.browser.mjs";++ const params = new URLSearchParams(location.search);+ const sessionId = params.get("session") || "session-h";+ const wsUrl = params.get("ws") || "ws://127.0.0.1:8766";++ function snapshot() {+ const live = useSubagentStore.getState().getRuntime(sessionId);+ return {+ ids: selectSubagents(live).map((item) => item.subagent_id).sort(),+ a: live?.subagentsById?.["sa-a"]?.status ?? null,+ b: live?.subagentsById?.["sa-b"]?.status ?? null,+ c: live?.subagentsById?.["sa-c"]?.status ?? null,+ activitiesA: selectSubagentActivities(live, "sa-a").length,+ ready: Boolean(live?.subagentsById?.["sa-a"] && live?.subagentsById?.["sa-c"]),+ };+ }++ function render(label, snap) {+ document.getElementById("status").textContent = label;+ document.getElementById("out").textContent = JSON.stringify(snap);+ if (snap.ready) {+ document.getElementById("out").dataset.ready = "1";+ }+ }++ const ws = new WebSocket(wsUrl);+ ws.onopen = () => {+ document.getElementById("status").textContent = "connected";+ ws.send(JSON.stringify({ type: "ready", session_id: sessionId }));+ };+ ws.onmessage = (event) => {+ const payload = JSON.parse(event.data);+ if (payload.event_type === "chat.subtask_update") {+ const normalized = normalizeSubagentStatusEvent({+ ...payload,+ event_type: "chat.subtask_update",+ session_id: payload.session_id || sessionId,+ });+ if (normalized) {+ useSubagentStore.getState().applyEvent(sessionId, normalized);+ }+ } else if (payload.event_type === "chat.subagent_activity") {+ const normalized = normalizeSubagentActivityEvent({+ ...payload,+ event_type: "chat.subagent_activity",+ session_id: payload.session_id || sessionId,+ });+ if (normalized) {+ useSubagentStore.getState().applyEvent(sessionId, normalized);+ }+ } else if (payload.type === "done") {+ const snap = snapshot();+ render("done", snap);+ ws.send(JSON.stringify({ type: "snapshot", snapshot: snap }));+ fetch("/snapshot", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(snap),+ });+ return;+ }+ render("updated", snapshot());+ };+ ws.onerror = () => {+ document.getElementById("status").textContent = "error";+ };+ </script>+</body>+</html>diff --git a/jiuwenswarm/channels/web/frontend/tests/subagentActivityPresentation.test.mjs b/jiuwenswarm/channels/web/frontend/tests/subagentActivityPresentation.test.mjsnew file mode 100644index 0000000000..099891df34--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/subagentActivityPresentation.test.mjs@@ -0,0 +1,240 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ extractSubagentTasks,+ finalizeSubagentTasks,+ getSubagentActivityPreview,+ groupSubagentActivities,+} from '../node_modules/.cache/subagent-activity/subagentActivityPresentation.mjs';++function activity(activityId, sequence, overrides = {}) {+ return {+ activity_id: activityId,+ subagent_id: 'agent-a',+ task_id: 'task-a',+ sequence,+ kind: 'thinking',+ summary: '',+ at_ms: 1000 + sequence,+ ...overrides,+ };+}++test('groups adjacent thinking stream chunks and keeps one bounded preview', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { summary: 'The' }),+ activity('thinking-2', 2, { summary: ' user wants' }),+ activity('thinking-3', 3, { summary: ' a report.' }),+ ]);++ assert.equal(groups.length, 1);+ assert.equal(groups[0].summary, 'The user wants a report.');+ assert.equal(groups[0].count, 3);+ assert.deepEqual(groups[0].activities.map(item => item.activity_id), [+ 'thinking-1',+ 'thinking-2',+ 'thinking-3',+ ]);+ assert.equal(getSubagentActivityPreview(groups[0]), 'The user wants a report.');+});++test('does not merge thinking across task boundaries or non-thinking activities', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { summary: 'first' }),+ activity('tool-1', 2, { kind: 'tool_call', tool_name: 'search', summary: 'search()' }),+ activity('thinking-2', 3, { summary: 'second' }),+ activity('thinking-3', 4, { task_id: 'task-b', summary: 'new task' }),+ ]);++ assert.deepEqual(groups.map(group => [group.activity.kind, group.activity.task_id, group.summary]), [+ ['thinking', 'task-a', 'first'],+ ['tool_call', 'task-a', 'search()'],+ ['thinking', 'task-a', 'second'],+ ['thinking', 'task-b', 'new task'],+ ]);+});++test('keeps thinking phases separate when tool activities are interleaved', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { summary: 'first thought' }),+ activity('tool-1', 2, { kind: 'tool_call', tool_name: 'search', summary: 'search()' }),+ activity('thinking-2', 3, { summary: 'second thought' }),+ ]);++ assert.deepEqual(groups.map(group => [group.activity.kind, group.summary, group.count]), [+ ['thinking', 'first thought', 1],+ ['tool_call', 'search()', 1],+ ['thinking', 'second thought', 1],+ ]);+});++test('merges thinking by phase while keeping other activities as sibling rows', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { phase_id: 1, summary: 'phase one start' }),+ activity('tool-1', 2, { phase_id: 1, kind: 'tool_call', tool_name: 'search', summary: 'search()' }),+ activity('thinking-2', 3, { phase_id: 1, summary: 'phase one continuation' }),+ activity('thinking-3', 4, { phase_id: 2, summary: 'phase two' }),+ ]);++ assert.deepEqual(groups.map(group => [group.activity.kind, group.summary, group.count]), [+ ['thinking', 'phase one startphase one continuation', 2],+ ['tool_call', 'search()', 1],+ ['thinking', 'phase two', 1],+ ]);+});++test('keeps todo creation and result visible in the activity timeline', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { summary: '先规划' }),+ activity('call-1', 1, {+ kind: 'tool_call',+ tool_name: 'todo_create',+ tool_call_id: 'tool-1',+ summary: 'todo_create({"tasks":[{"id":"research","content":"搜索市场"},{"id":"write","content":"撰写报告"}]})',+ }),+ activity('result-1', 2, {+ kind: 'tool_result',+ tool_name: 'todo_create',+ tool_call_id: 'tool-1',+ summary: "[→] task_id: research , content: 搜索市场\n[ ] task_id: write , content: 撰写报告",+ }),+ activity('thinking-2', 3, { summary: '继续执行' }),+ ]);++ assert.deepEqual(groups.map(group => group.activity.kind), [+ 'thinking',+ 'tool_call',+ 'tool_result',+ 'thinking',+ ]);+ assert.match(groups[1].summary, /todo_create/);+ assert.match(groups[2].summary, /search|task_id/);+ assert.deepEqual(extractSubagentTasks([+ activity('call-1', 1, {+ kind: 'tool_call',+ tool_name: 'todo_create',+ summary: 'todo_create({"tasks":[{"id":"research","content":"搜索市场"},{"id":"write","content":"撰写报告"}]})',+ }),+ activity('result-1', 2, {+ kind: 'tool_result',+ tool_name: 'todo_create',+ summary: "[→] task_id: research , content: 搜索市场\n[ ] task_id: write , content: 撰写报告",+ }),+ ]).map(({ id, content, status }) => ({ id, content, status })), [+ { id: 'research', content: '搜索市场', status: 'in_progress' },+ { id: 'write', content: '撰写报告', status: 'pending' },+ ]);+});++test('applies todo_modify status updates in the task section', () => {+ const tasks = extractSubagentTasks([+ activity('call-todo', 1, {+ kind: 'tool_call',+ tool_name: 'todo_create',+ tool_call_id: 'create-1',+ summary: 'todo_create({"tasks":[{"id":"research_report","content":"撰写市场报告"}]})',+ }),+ activity('create-result', 2, {+ kind: 'tool_result',+ tool_name: 'todo_create',+ tool_call_id: 'create-1',+ summary: '[→] task_id: research_report , content: 撰写市场报告',+ }),+ activity('modify-todo-call', 3, {+ kind: 'tool_call',+ tool_name: 'todo_modify',+ tool_call_id: 'modify-1',+ summary: 'todo_modify({"todos":[{"id":"research_report","status":"completed"}]})',+ }),+ activity('modify-todo', 4, {+ kind: 'tool_result',+ tool_name: 'todo_modify',+ tool_call_id: 'modify-1',+ summary: "{'message': 'Successfully updated 1 task(s)'}",+ }),+ ]);+ assert.deepEqual(tasks.map(({ id, content, status }) => ({ id, content, status })), [+ { id: 'research_report', content: '撰写市场报告', status: 'completed' },+ ]);+ assert.deepEqual(tasks[0].statusHistory.map(change => change.status), [+ 'pending',+ 'in_progress',+ 'completed',+ ]);+});++test('ignores failed todo updates and closes outstanding tasks only on a completed turn', () => {+ const tasks = extractSubagentTasks([+ activity('create-call', 1, {+ kind: 'tool_call',+ tool_name: 'todo_create',+ tool_call_id: 'create-2',+ summary: 'todo_create({"tasks":[{"id":"one","content":"第一项"},{"id":"two","content":"第二项"}]})',+ }),+ activity('create-result', 2, {+ kind: 'tool_result',+ tool_name: 'todo_create',+ tool_call_id: 'create-2',+ summary: '[→] task_id: one , content: 第一项\n[ ] task_id: two , content: 第二项',+ }),+ activity('failed-call', 3, {+ kind: 'tool_call',+ tool_name: 'todo_modify',+ tool_call_id: 'failed-1',+ summary: 'todo_modify({"todos":[{"id":"one","status":"completed"},{"id":"two","status":"in_progress"}]})',+ }),+ activity('failed-result', 4, {+ kind: 'tool_result',+ tool_name: 'todo_modify',+ tool_call_id: 'failed-1',+ summary: 'success=False data=None error="validation failed"',+ }),+ ]);++ assert.deepEqual(tasks.map(({ id, status }) => ({ id, status })), [+ { id: 'one', status: 'in_progress' },+ { id: 'two', status: 'pending' },+ ]);+ assert.deepEqual(finalizeSubagentTasks(tasks, true).map(({ id, status }) => ({ id, status })), [+ { id: 'one', status: 'completed' },+ { id: 'two', status: 'completed' },+ ]);+ assert.deepEqual(finalizeSubagentTasks(tasks, false).map(({ id, status }) => ({ id, status })), [+ { id: 'one', status: 'in_progress' },+ { id: 'two', status: 'pending' },+ ]);+});++test('uses the meaningful result content as the collapsed web-tool preview', () => {+ const groups = groupSubagentActivities([+ activity('call-search', 1, {+ kind: 'tool_call',+ tool_name: 'fetch_webpage',+ tool_call_id: 'web-1',+ summary: 'fetch_webpage({"url":"https://example.com/report","max_chars":15000})',+ }),+ activity('result-search', 2, {+ kind: 'tool_result',+ tool_name: 'fetch_webpage',+ tool_call_id: 'web-1',+ summary: 'URL: https://example.com/report\nStatus: 200\nContent: 智能眼镜市场报告摘要,包含50个结果',+ }),+ ]);++ assert.equal(getSubagentActivityPreview(groups[1]), '智能眼镜市场报告摘要,包含50个结果');+});++test('keeps thinking collapsed preview bounded and empty for empty summaries', () => {+ const groups = groupSubagentActivities([+ activity('thinking-1', 1, { summary: '先拆解任务\n再检查输入' }),+ ]);++ assert.equal(getSubagentActivityPreview(groups[0]), '先拆解任务');+ assert.equal(getSubagentActivityPreview(groupSubagentActivities([+ activity('thinking-long', 3, { summary: 'x'.repeat(200) }),+ ])[0]).length, 120);+ assert.equal(getSubagentActivityPreview(groupSubagentActivities([+ activity('thinking-empty', 2, { summary: '' }),+ ])[0]), '');+});diff --git a/jiuwenswarm/channels/web/frontend/tests/subagentStatusPresentation.test.mjs b/jiuwenswarm/channels/web/frontend/tests/subagentStatusPresentation.test.mjsnew file mode 100644index 0000000000..4816257376--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/subagentStatusPresentation.test.mjs@@ -0,0 +1,36 @@+import test from 'node:test';+import assert from 'node:assert/strict';++import {+ getSubagentStatusLabelKey,+ getSubagentStatusTone,+} from '../node_modules/.cache/subagent-status/subagentStatusPresentation.mjs';++test('status presentation keeps normal completion distinct from neutral closure', () => {+ assert.equal(getSubagentStatusTone('running', null), 'running');+ assert.equal(getSubagentStatusTone('idle', null), 'waiting');+ assert.equal(getSubagentStatusTone('idle', null, 'failed'), 'danger');+ assert.equal(getSubagentStatusTone('idle', null, 'cancelled'), 'neutral');+ assert.equal(getSubagentStatusTone('closed', 'completed'), 'success');+ assert.equal(getSubagentStatusTone('closed', 'failed'), 'danger');+ assert.equal(getSubagentStatusTone('closed', 'evicted'), 'danger');+ assert.equal(getSubagentStatusTone('closed', 'cancelled'), 'success');+ assert.equal(getSubagentStatusTone('closed', 'parent_ended'), 'success');+ assert.equal(getSubagentStatusTone('closed', 'manual'), 'success');+ assert.equal(getSubagentStatusTone('closed', null), 'success');+});++test('status presentation uses localized labels for every terminal reason', () => {+ assert.equal(getSubagentStatusLabelKey('running', null), 'subagent.running');+ assert.equal(getSubagentStatusLabelKey('idle', null), 'subagent.idle');+ assert.equal(getSubagentStatusLabelKey('idle', null, 'failed'), 'subagent.failed');+ assert.equal(getSubagentStatusLabelKey('idle', null, 'cancelled'), 'subagent.cancelled');+ assert.equal(getSubagentStatusLabelKey('closed', null, 'failed'), 'subagent.failed');+ assert.equal(getSubagentStatusLabelKey('closed', 'completed'), 'subagent.closed');+ assert.equal(getSubagentStatusLabelKey('closed', 'failed'), 'subagent.failed');+ assert.equal(getSubagentStatusLabelKey('closed', 'evicted'), 'subagent.failed');+ assert.equal(getSubagentStatusLabelKey('closed', 'cancelled'), 'subagent.closed');+ assert.equal(getSubagentStatusLabelKey('closed', 'parent_ended'), 'subagent.closed');+ assert.equal(getSubagentStatusLabelKey('closed', 'manual'), 'subagent.closed');+ assert.equal(getSubagentStatusLabelKey('closed', null), 'subagent.closed');+});diff --git a/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs b/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjsnew file mode 100644index 0000000000..ff6281ac77--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs@@ -0,0 +1,1227 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ applySubagentActivity,+ applySubagentHistoryUpdated,+ applySubagentResult,+ applySubagentTranscript,+ applySubagentTurn,+ applySubagentToolStatus,+ applySubagentUpdated,+ createEmptySubagentRuntime,+ dropCachedSubagent,+ markRunningSubagentsCancelled,+ selectSubagentActivities,+ selectSubagentHistoryRestoring,+ selectSubagentResult,+ selectSubagents,+ selectSubagentTurns,+ useSubagentStore,+} from '../node_modules/.cache/subagent-store/subagentStore.mjs';+import {+ normalizeSubagentActivityEvent,+ normalizeSubagentStatusEvent,+ normalizeSubagentToolStatusUpdates,+ normalizeSubagentWaitResults,+} from '../node_modules/.cache/subagent-store/subagentNormalizer.mjs';++const sessionId = 'session-a';++function subagent(overrides = {}) {+ return {+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ subagent_type: 'general',+ display_name: 'Agent A',+ role: 'Researcher',+ task_description: 'Research the topic',+ status: 'running',+ closed_at: null,+ closed_reason: null,+ error: null,+ created_at: 1000,+ updated_at: 1000,+ revision: 1,+ ...overrides,+ };+}++function event(revision, value = subagent({ revision })) {+ return {+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent: value,+ };+}++function activity(activityId, sequence, overrides = {}) {+ return {+ activity_id: activityId,+ subagent_id: 'agent-a',+ task_id: 'task-a',+ sequence,+ kind: 'tool_call',+ summary: activityId,+ at_ms: 1000 + sequence,+ ...overrides,+ };+}++test('subagent status updates are revision-idempotent and keep terminal history', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1));+ runtime = applySubagentUpdated(+ runtime,+ event(3, subagent({+ status: 'closed',+ closed_at: 3000,+ closed_reason: 'completed',+ updated_at: 3000,+ revision: 3,+ })),+ );++ const lateRunning = event(2, subagent({ revision: 2, updated_at: 2000 }));+ assert.equal(applySubagentUpdated(runtime, lateRunning), runtime);+ assert.equal(runtime.subagentsById['agent-a'].status, 'closed');++ const reopened = applySubagentUpdated(runtime, event(4, subagent({ revision: 4, updated_at: 4000 })));+ assert.equal(reopened, runtime);+ assert.equal(runtime.subagentsById['agent-a'].status, 'closed');+});++test('closed lifecycle requires a newer revision even when a backend resets close revision', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({ revision: 1, updated_at: 1000 })));+ runtime = applySubagentUpdated(runtime, event(2, subagent({ status: 'idle', revision: 2, updated_at: 2000 })));+ const staleClosed = applySubagentUpdated(runtime, event(0, subagent({+ status: 'closed',+ closed_reason: 'manual',+ lifecycle: 'closed',+ can_send_input: false,+ needs_resume: true,+ revision: 0,+ updated_at: 3000,+ })));+ assert.equal(staleClosed, runtime);+ assert.equal(runtime.subagentsById['agent-a'].status, 'idle');++ runtime = applySubagentUpdated(runtime, event(3, subagent({+ status: 'closed',+ closed_reason: 'manual',+ lifecycle: 'closed',+ can_send_input: false,+ needs_resume: true,+ revision: 3,+ updated_at: 3000,+ })));+ assert.equal(runtime.subagentsById['agent-a'].status, 'closed');+ assert.equal(runtime.subagentsById['agent-a'].closed_reason, 'manual');+ assert.equal(+ applySubagentUpdated(runtime, event(3, subagent({ status: 'idle', revision: 3, updated_at: 4000 }))),+ runtime,+ );+});++test('store rejects a status event whose nested parent session differs', () => {+ const runtime = createEmptySubagentRuntime(sessionId);+ const mismatched = event(1, subagent({ parent_session_id: 'session-b' }));+ assert.equal(applySubagentUpdated(runtime, mismatched), runtime);+});++test('a lower-revision closed event cannot overwrite a terminal failure', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(5, subagent({+ status: 'closed',+ closed_reason: 'failed',+ turn_outcome: 'failed',+ updated_at: 5000,+ revision: 5,+ })));++ const lateClosed = applySubagentUpdated(runtime, event(4, subagent({+ status: 'closed',+ closed_reason: 'evicted',+ updated_at: 6000,+ revision: 4,+ })));+ assert.equal(lateClosed, runtime);+ assert.equal(runtime.subagentsById['agent-a'].closed_reason, 'failed');+});++test('same revision cannot overwrite a state even with a later timestamp', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(5, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ updated_at: 5000,+ revision: 5,+ })));++ const sameRevision = applySubagentUpdated(runtime, event(5, subagent({+ status: 'closed',+ lifecycle: 'closed',+ needs_resume: true,+ closed_reason: 'evicted',+ updated_at: 6000,+ revision: 5,+ })));+ assert.equal(sameRevision, runtime);+ assert.equal(runtime.subagentsById['agent-a'].status, 'idle');+});++test('a newer same-revision follow-up turn updates the assignment and status', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(2, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ task_description: 'Query today',+ updated_at: 2000,+ revision: 2,+ })));++ const followUp = applySubagentUpdated(runtime, event(2, subagent({+ status: 'running',+ turn_outcome: null,+ lifecycle: 'live',+ can_send_input: false,+ needs_resume: false,+ task_description: 'Query tomorrow',+ updated_at: 3000,+ revision: 2,+ })));+ assert.equal(followUp.subagentsById['agent-a'].status, 'running');+ assert.equal(followUp.subagentsById['agent-a'].task_description, 'Query tomorrow');+ assert.equal(followUp.subagentsById['agent-a'].revision, 2);+});++test('history status with the same revision but newer timestamp supersedes stale cache', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(5, subagent({+ status: 'running',+ updated_at: 5000,+ revision: 5,+ })));++ const historyIdle = event(5, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ updated_at: 6000,+ revision: 5,+ }));+ const restored = applySubagentHistoryUpdated(runtime, historyIdle);+ assert.equal(restored.subagentsById['agent-a'].status, 'idle');+ assert.equal(restored.subagentsById['agent-a'].turn_outcome, 'completed');+});++test('history status snapshots do not erase the recovered assignment', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentHistoryUpdated(runtime, event(1, subagent({+ updated_at: 1000,+ revision: 1,+ })));++ const sparseIdle = event(2, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ role: '',+ task_description: '',+ updated_at: 2000,+ revision: 2,+ }));+ const restored = applySubagentHistoryUpdated(runtime, sparseIdle);+ assert.equal(restored.subagentsById['agent-a'].status, 'idle');+ assert.equal(restored.subagentsById['agent-a'].task_description, 'Research the topic');+ assert.equal(restored.subagentsById['agent-a'].role, 'Researcher');+});++test('history status snapshots enrich a generic cached display name', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(4, subagent({+ display_name: 'general-purpose',+ role: '',+ revision: 4,+ updated_at: 4000,+ })));+ const enriched = applySubagentHistoryUpdated(runtime, event(1, subagent({+ display_name: '汕头天气查询员',+ role: '查询汕头今日天气',+ revision: 1,+ updated_at: 1000,+ })));+ assert.equal(enriched.subagentsById['agent-a'].display_name, '汕头天气查询员');+ assert.equal(enriched.subagentsById['agent-a'].role, '查询汕头今日天气');+ assert.equal(enriched.subagentsById['agent-a'].revision, 4);+});++test('history restore exposes an explicit pending state until replay finishes', () => {+ const restoreSessionId = 'history-restore-session';+ useSubagentStore.getState().removeRuntime(restoreSessionId);+ useSubagentStore.getState().ensureRuntime(restoreSessionId);+ useSubagentStore.getState().beginHistoryRestore(restoreSessionId, 'agent-a');+ assert.equal(+ selectSubagentHistoryRestoring(useSubagentStore.getState().getRuntime(restoreSessionId), 'agent-a'),+ true,+ );+ useSubagentStore.getState().finishHistoryRestore(restoreSessionId, 'agent-a');+ assert.equal(+ selectSubagentHistoryRestoring(useSubagentStore.getState().getRuntime(restoreSessionId), 'agent-a'),+ false,+ );+ useSubagentStore.getState().removeRuntime(restoreSessionId);+});+++test('history can replace a stale cached closure with a newer idle revision', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(0, subagent({+ status: 'closed',+ lifecycle: 'closed',+ needs_resume: true,+ closed_reason: 'manual',+ task_description: '',+ updated_at: 7000,+ revision: 0,+ })));++ const historyIdle = event(5, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ updated_at: 6000,+ revision: 5,+ }));+ const restored = applySubagentHistoryUpdated(runtime, historyIdle);+ assert.equal(restored.subagentsById['agent-a'].status, 'idle');+ assert.equal(restored.subagentsById['agent-a'].revision, 5);+ assert.equal(restored.subagentsById['agent-a'].task_description, 'Research the topic');+});++test('successful subagent tool results recover a running roster state without changing its revision', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(4, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ updated_at: 5000,+ revision: 4,+ })));++ const updates = normalizeSubagentToolStatusUpdates({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_result: {+ tool_name: 'subagent_resume',+ result: "success=True data={'subagent_id': 'agent-a', 'status': 'running'} error=None",+ },+ });+ assert.deepEqual(updates, [{ subagent_id: 'agent-a', status: 'running' }]);++ const recovered = applySubagentToolStatus(runtime, updates[0].subagent_id, updates[0].status, 6000);+ assert.equal(recovered.subagentsById['agent-a'].status, 'running');+ assert.equal(recovered.subagentsById['agent-a'].revision, 4);+ assert.equal(recovered.subagentsById['agent-a'].task_description, 'Research the topic');++ const withFollowUp = applySubagentToolStatus(runtime, 'agent-a', 'running', 6000, 'Query tomorrow');+ assert.equal(withFollowUp.subagentsById['agent-a'].task_description, 'Query tomorrow');++ const completed = applySubagentUpdated(recovered, event(5, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ updated_at: 7000,+ revision: 5,+ })));+ assert.equal(completed.subagentsById['agent-a'].status, 'idle');+});++test('successful close results recover a closed roster state without changing its revision', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(3, subagent({+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ updated_at: 3000,+ revision: 3,+ })));++ const updates = normalizeSubagentToolStatusUpdates({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_result: {+ tool_name: 'subagent_close',+ result: "success=True data={'subagent_id': 'agent-a', 'previous_status': 'completed'} error=None",+ },+ });+ assert.deepEqual(updates, [{ subagent_id: 'agent-a', status: 'closed' }]);++ const closed = applySubagentToolStatus(runtime, updates[0].subagent_id, updates[0].status, 4000);+ assert.equal(closed.subagentsById['agent-a'].status, 'closed');+ assert.equal(closed.subagentsById['agent-a'].revision, 3);+ assert.equal(closed.subagentsById['agent-a'].lifecycle, 'closed');+ assert.equal(closed.subagentsById['agent-a'].needs_resume, true);+});++test('successful subagent spawn results restore the live assignment and turn', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ task_description: '',+ updated_at: 1000,+ revision: 1,+ })));++ const updates = normalizeSubagentToolStatusUpdates({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_result: {+ tool_name: 'subagent_spawn',+ result: "success=True data={'subagent_id': 'agent-a', 'task_id': 'turn-a', 'status': 'running'} error=None",+ },+ });+ assert.deepEqual(updates, [{ subagent_id: 'agent-a', status: 'running', task_id: 'turn-a' }]);++ const recovered = applySubagentToolStatus(runtime, updates[0].subagent_id, updates[0].status, 1100, 'Query from spawn', updates[0].task_id);+ assert.equal(recovered.subagentsById['agent-a'].task_description, 'Query from spawn');+ assert.deepEqual(selectSubagentTurns(recovered, 'agent-a'), [{+ task_id: 'turn-a',+ task_description: 'Query from spawn',+ started_at: 1100,+ }]);+});++test('live spawn assignment fills an activity turn when the tool result has no task id', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ task_description: '',+ updated_at: 1000,+ revision: 1,+ })));+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('spawn-activity', 1, { task_id: 'turn-a', at_ms: 1100 }),+ });++ const recovered = applySubagentToolStatus(runtime, 'agent-a', 'running', 1200, 'Query from spawn');+ assert.equal(recovered.subagentsById['agent-a'].task_description, 'Query from spawn');+ assert.equal(selectSubagentTurns(recovered, 'agent-a')[0].task_description, 'Query from spawn');+});++test('failed subagent tool results do not change roster state', () => {+ assert.deepEqual(normalizeSubagentToolStatusUpdates({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_result: {+ tool_name: 'subagent_resume',+ result: "success=False data=None error={'message': 'not found'}",+ },+ }), []);+});++test('subagent_list success results recover each explicit running status', () => {+ const updates = normalizeSubagentToolStatusUpdates({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_result: {+ tool_name: 'subagent_list',+ result: "success=True data={'subagents': [{'subagent_id': 'agent-a', 'status': 'running'}, {'subagent_id': 'agent-b', 'status': 'idle'}]} error=None",+ },+ });+ assert.deepEqual(updates, [+ { subagent_id: 'agent-a', status: 'running' },+ { subagent_id: 'agent-b', status: 'idle' },+ ]);+});++test('a successful parent cancel settles only still-running subagents locally', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({ updated_at: 1000 })));+ runtime = applySubagentUpdated(runtime, event(2, subagent({+ subagent_id: 'idle-agent',+ status: 'idle',+ turn_outcome: 'completed',+ updated_at: 2000,+ revision: 2,+ })));++ const cancelled = markRunningSubagentsCancelled(runtime, 3000);+ assert.equal(cancelled.subagentsById['agent-a'].status, 'idle');+ assert.equal(cancelled.subagentsById['agent-a'].turn_outcome, 'cancelled');+ assert.equal(cancelled.subagentsById['agent-a'].can_send_input, true);+ assert.equal(cancelled.subagentsById['idle-agent'].turn_outcome, 'completed');+});++test('live activities deduplicate by derived id and remain sequence ordered', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1));+ const first = {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('second', 2),+ };+ const second = {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('first', 1),+ };+ runtime = applySubagentActivity(runtime, first);+ runtime = applySubagentActivity(runtime, second);+ runtime = applySubagentActivity(runtime, second);+ assert.deepEqual(+ selectSubagentActivities(runtime, 'agent-a').map(item => item.activity_id),+ ['first', 'second'],+ );+});++test('store rejects an activity whose nested parent session differs', () => {+ const runtime = createEmptySubagentRuntime(sessionId);+ assert.equal(+ applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('cross-session', 1, { parent_session_id: 'session-b' }),+ }),+ runtime,+ );+});++test('selection prefers running subagents and orders idle before closed history', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({ updated_at: 1000 })));+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ subagent_id: 'idle-agent',+ display_name: 'Idle agent',+ status: 'idle',+ updated_at: 2000,+ revision: 1,+ })));+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ subagent_id: 'closed-agent',+ display_name: 'Closed agent',+ status: 'closed',+ closed_reason: 'completed',+ updated_at: 3000,+ revision: 1,+ })));+ assert.equal(runtime.selectedSubagentId, 'agent-a');+ assert.deepEqual(selectSubagents(runtime).map(item => item.subagent_id), ['agent-a', 'idle-agent', 'closed-agent']);+});++test('normalizers accept the live Web payloads and real activity kinds', () => {+ const status = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ subagent_type: 'general',+ display_name: 'Agent A',+ role: 'Researcher',+ task_description: 'Research the topic',+ status: 'starting',+ created_at: 1000,+ updated_at: 1100,+ revision: 1,+ });+ assert.equal(status?.subagent.status, 'running');+ assert.equal(status?.subagent.created_at, 1000);++ assert.equal(normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: 'session-a',+ subagent_id: 'agent-a',+ parent_session_id: 'session-b',+ display_name: 'Agent A',+ status: 'running',+ revision: 1,+ }), null);++ const activityEvent = normalizeSubagentActivityEvent({+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ subagent_id: 'agent-a',+ task_id: 'task-a',+ seq: 7,+ kind: 'thinking',+ summary: 'checking the source',+ at_ms: 1200,+ phase_id: 3,+ });+ assert.equal(activityEvent?.activity.sequence, 7);+ assert.equal(activityEvent?.activity.kind, 'thinking');+ assert.equal(activityEvent?.activity.phase_id, 3);+ assert.equal(activityEvent?.activity.activity_id, 'agent-a:task-a:7');+ assert.equal(activityEvent?.activity.parent_session_id, sessionId);++ assert.equal(normalizeSubagentActivityEvent({+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ parent_session_id: 'session-b',+ subagent_id: 'agent-a',+ task_id: 'task-a',+ seq: 8,+ kind: 'thinking',+ at_ms: 1200,+ }), null);+});++test('live subagent runtimes stay isolated and retain activity that arrives before status', () => {+ let runtimeA = createEmptySubagentRuntime('session-a');+ const runtimeB = createEmptySubagentRuntime('session-b');++ runtimeA = applySubagentActivity(runtimeA, {+ event_type: 'chat.subagent_activity',+ session_id: 'session-a',+ activity: activity('early', 1),+ });+ assert.deepEqual(selectSubagentActivities(runtimeA, 'agent-a').map(item => item.activity_id), ['early']);+ runtimeA = applySubagentUpdated(runtimeA, event(1));+ assert.equal(+ applySubagentUpdated(runtimeB, event(1)),+ runtimeB,+ );+ assert.deepEqual(selectSubagents(runtimeB), []);+});++test('normalizers preserve live terminal reasons and reject malformed activities', () => {+ for (const [status, closedReason] of [+ ['error', 'failed'],+ ['cancelled', 'cancelled'],+ ['closed', 'evicted'],+ ]) {+ const normalized = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status,+ closed_reason: closedReason,+ revision: 2,+ });+ assert.equal(normalized?.subagent.status, 'closed');+ assert.equal(normalized?.subagent.closed_reason, closedReason);+ }++ assert.equal(normalizeSubagentActivityEvent({+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ subagent_id: 'agent-a',+ task_id: 'task-a',+ seq: -1,+ kind: 'thinking',+ at_ms: 1200,+ }), null);+ assert.equal(normalizeSubagentActivityEvent({+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ subagent_id: 'agent-a',+ task_id: 'task-a',+ seq: 1,+ kind: 'message',+ at_ms: 1200,+ }), null);+});++test('lifecycle closed and needs_resume take precedence over legacy status', () => {+ for (const value of [+ { status: 'idle', lifecycle: 'closed', needs_resume: false },+ { status: 'running', lifecycle: 'closed', needs_resume: false },+ { status: 'idle', lifecycle: 'live', needs_resume: true },+ ]) {+ const normalized = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ parent_session_id: sessionId,+ subagent_id: 'agent-a',+ display_name: 'Agent A',+ revision: 2,+ ...value,+ });+ assert.equal(normalized?.subagent.status, 'closed');+ }+});++test('normalizers preserve idle lifecycle and map adapter projections using lifecycle fields', () => {+ const completed = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status: 'idle',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ closed_at: 25,+ revision: 2,+ });+ assert.equal(completed?.subagent.status, 'idle');+ assert.equal(completed?.subagent.closed_reason, null);+ assert.equal(completed?.subagent.turn_outcome, 'completed');+ assert.equal(completed?.subagent.can_send_input, true);+ assert.equal(completed?.subagent.closed_at, null);++ const adapterIdle = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status: 'completed',+ turn_outcome: 'completed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ revision: 3,+ });+ assert.equal(adapterIdle?.subagent.status, 'idle');+ assert.equal(adapterIdle?.subagent.closed_reason, null);++ const failed = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status: 'idle',+ turn_outcome: 'failed',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ message: 'turn timeout',+ revision: 3,+ });+ assert.equal(failed?.subagent.status, 'idle');+ assert.equal(failed?.subagent.closed_reason, null);+ assert.equal(failed?.subagent.error?.message, 'turn timeout');++ const cancelled = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status: 'completed',+ turn_outcome: 'cancelled',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ revision: 4,+ });+ assert.equal(cancelled?.subagent.status, 'idle');+ assert.equal(cancelled?.subagent.closed_reason, null);++ const closed = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-a',+ parent_session_id: sessionId,+ display_name: 'Agent A',+ status: 'closed',+ closed_reason: 'completed',+ lifecycle: 'closed',+ can_send_input: false,+ needs_resume: true,+ revision: 5,+ });+ assert.equal(closed?.subagent.status, 'closed');+ assert.equal(closed?.subagent.closed_reason, 'completed');++ const closedFailedTurn = normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-closed-failed',+ parent_session_id: sessionId,+ display_name: 'Closed failed turn',+ status: 'closed',+ lifecycle: 'closed',+ turn_outcome: 'failed',+ closed_at: 50,+ revision: 6,+ });+ assert.equal(closedFailedTurn?.subagent.closed_reason, 'failed');+ assert.equal(closedFailedTurn?.subagent.closed_at, 50);++ assert.equal(normalizeSubagentStatusEvent({+ event_type: 'chat.subtask_update',+ session_id: sessionId,+ subagent_id: 'agent-unknown-status',+ parent_session_id: sessionId,+ display_name: 'Unknown status',+ status: 'future-status',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ revision: 7,+ }), null);+});++test('subagent_wait results preserve the full body and attach to the session runtime', () => {+ const results = normalizeSubagentWaitResults({+ event_type: 'chat.tool_result',+ session_id: sessionId,+ tool_name: 'subagent_wait',+ subagent_wait: {+ statuses: { 'agent-a': 'completed' },+ results: {+ 'agent-a': 'Full result\nwith formatting',+ 'agent-empty': '',+ 'agent-whitespace': ' \n ',+ },+ output_files: {+ 'agent-a': '/tmp/agent-a.md',+ 'agent-empty': '/tmp/agent-empty.md',+ },+ timed_out: false,+ },+ });+ assert.deepEqual(results, [{+ subagent_id: 'agent-a',+ content: 'Full result\nwith formatting',+ output_file: '/tmp/agent-a.md',+ }]);++ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentResult(runtime, results[0]);+ assert.equal(selectSubagentResult(runtime, 'agent-a')?.content, 'Full result\nwith formatting');+ assert.equal(selectSubagentResult(runtime, 'agent-a')?.output_file, '/tmp/agent-a.md');+ assert.equal(applySubagentResult(runtime, results[0]), runtime);+});++test('history transcripts are deduplicated and structured wait results remain authoritative', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'first part' });+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'second part' });+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'first part' });+ assert.equal(selectSubagentResult(runtime, 'agent-a')?.content, 'first part\n\nsecond part');++ runtime = applySubagentResult(runtime, { subagent_id: 'agent-a', content: 'final wait result' });+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'late transcript' });+ assert.equal(selectSubagentResult(runtime, 'agent-a')?.content, 'final wait result');+});++test('follow-up turns keep queries, activities, and final results separate', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-1', 'Query today', 1000);+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-2', 'Query tomorrow', 2000);+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-1-activity', 1, { task_id: 'turn-1', at_ms: 1100 }),+ });+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-2-activity', 2, { task_id: 'turn-2', at_ms: 2100 }),+ });+ runtime = applySubagentTranscript(runtime, {+ subagent_id: 'agent-a',+ task_id: 'turn-1',+ at_ms: 1200,+ content: 'Today result',+ });+ runtime = applySubagentTranscript(runtime, {+ subagent_id: 'agent-a',+ task_id: 'turn-2',+ at_ms: 2200,+ content: 'Tomorrow result',+ });++ const turns = selectSubagentTurns(runtime, 'agent-a');+ assert.deepEqual(turns.map(turn => ({+ task_id: turn.task_id,+ task_description: turn.task_description,+ activities: selectSubagentActivities(runtime, 'agent-a').filter(item => item.task_id === turn.task_id).length,+ result: turn.result?.content,+ })), [+ { task_id: 'turn-1', task_description: 'Query today', activities: 1, result: 'Today result' },+ { task_id: 'turn-2', task_description: 'Query tomorrow', activities: 1, result: 'Tomorrow result' },+ ]);+});++test('historical activity does not overwrite an existing turn assignment', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(3, subagent({+ task_description: 'Query tomorrow',+ updated_at: 3000,+ revision: 3,+ })));+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-1', 'Query today', 1000);+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-2', 'Query tomorrow', 2000);+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-1-activity', 1, { task_id: 'turn-1', at_ms: 1100 }),+ });++ assert.deepEqual(selectSubagentTurns(runtime, 'agent-a').map(turn => ({+ task_id: turn.task_id,+ task_description: turn.task_description,+ })), [+ { task_id: 'turn-1', task_description: 'Query today' },+ { task_id: 'turn-2', task_description: 'Query tomorrow' },+ ]);+});++test('explicit turn assignment repairs a fallback created by early activity', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ task_description: 'Query first',+ updated_at: 1000,+ revision: 1,+ })));+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-2-activity', 2, { task_id: 'turn-2', at_ms: 2100 }),+ });+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-2', 'Query second', 2000);++ assert.deepEqual(selectSubagentTurns(runtime, 'agent-a').map(turn => ({+ task_id: turn.task_id,+ task_description: turn.task_description,+ })), [+ { task_id: 'turn-2', task_description: 'Query second' },+ ]);+});++test('later fallback activity does not overwrite an explicit turn description', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentUpdated(runtime, event(1, subagent({+ task_description: 'Roster fallback',+ updated_at: 1000,+ revision: 1,+ })));+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-1-activity', 1, { task_id: 'turn-1', at_ms: 1100 }),+ });+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-1', 'Explicit title', 1000);+ runtime = applySubagentActivity(runtime, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('turn-1-activity-2', 2, { task_id: 'turn-1', at_ms: 1200 }),+ });+ const turns = selectSubagentTurns(runtime, 'agent-a');+ assert.equal(turns.length, 1);+ assert.equal(turns[0].task_description, 'Explicit title');+ assert.equal(turns[0].description_source, undefined);+});++test('a wait result received before turn metadata is attached after turns are restored', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentResult(runtime, {+ subagent_id: 'agent-a',+ content: 'Restored final',+ source: 'wait',+ });+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-1', 'Query today', 1000);+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-2', 'Query tomorrow', 2000);+ assert.equal(selectSubagentTurns(runtime, 'agent-a')[0].result?.content, 'Restored final');+});++test('transcript finals survive a wait result and attach to later restored turns', () => {+ let runtime = createEmptySubagentRuntime(sessionId);+ runtime = applySubagentResult(runtime, {+ subagent_id: 'agent-a',+ content: 'Latest wait result',+ source: 'wait',+ });+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'First final', at_ms: 1100 });+ runtime = applySubagentTranscript(runtime, { subagent_id: 'agent-a', content: 'Second final', at_ms: 2100 });+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-1', 'Query one', 1000);+ runtime = applySubagentTurn(runtime, 'agent-a', 'turn-2', 'Query two', 2000);+ const turns = selectSubagentTurns(runtime, 'agent-a');+ assert.equal(turns[0].result?.content, 'Latest wait result');+ assert.equal(turns[1].result?.content, 'Second final');+});++test('actual live runtime snapshots rehydrate after a page refresh', () => {+ const previousWindow = globalThis.window;+ const values = new Map();+ globalThis.window = {+ sessionStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ },+ };+ try {+ useSubagentStore.getState().removeRuntime(sessionId);+ useSubagentStore.getState().applyEvent(sessionId, event(1));+ useSubagentStore.getState().applyEvent(sessionId, {+ event_type: 'chat.subagent_activity',+ session_id: sessionId,+ activity: activity('persisted', 1),+ });+ const restored = createEmptySubagentRuntime(sessionId);+ assert.equal(restored.subagentsById['agent-a'].status, 'running');+ assert.deepEqual(selectSubagentActivities(restored, 'agent-a').map(item => item.activity_id), ['persisted']);+ } finally {+ useSubagentStore.getState().removeRuntime(sessionId);+ globalThis.window = previousWindow;+ }+});++test('session cache rejects a subagent and activity from another parent session', () => {+ const previousWindow = globalThis.window;+ const values = new Map([+ [`jiuwen.subagent.runtime.v1:${encodeURIComponent(sessionId)}`, JSON.stringify({+ subagents: [subagent({ parent_session_id: 'session-b' })],+ activities: [activity('cross-session', 1, { parent_session_id: 'session-b' })],+ results: [],+ selectedSubagentId: 'agent-a',+ })],+ ]);+ globalThis.window = {+ sessionStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ },+ };+ try {+ const restored = createEmptySubagentRuntime(sessionId);+ assert.deepEqual(selectSubagents(restored), []);+ assert.deepEqual(selectSubagentActivities(restored, 'agent-a'), []);+ } finally {+ globalThis.window = previousWindow;+ }+});++test('session cache does not replace a state with the same revision', () => {+ const previousWindow = globalThis.window;+ const storageKey = `jiuwen.subagent.runtime.v1:${encodeURIComponent(sessionId)}`;+ const values = new Map();+ globalThis.window = {+ sessionStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ },+ };+ try {+ useSubagentStore.getState().removeRuntime(sessionId);+ useSubagentStore.getState().applyEvent(sessionId, event(5, subagent({+ status: 'idle',+ lifecycle: 'live',+ can_send_input: true,+ needs_resume: false,+ turn_outcome: 'completed',+ revision: 5,+ updated_at: 5000,+ })));+ values.set(storageKey, JSON.stringify({+ subagents: [subagent({+ status: 'closed',+ lifecycle: 'closed',+ needs_resume: true,+ closed_reason: 'evicted',+ revision: 5,+ updated_at: 6000,+ })],+ activities: [],+ results: [],+ selectedSubagentId: 'agent-a',+ }));+ useSubagentStore.getState().hydrateRuntime(sessionId);+ const restored = useSubagentStore.getState().getRuntime(sessionId);+ assert.equal(restored?.subagentsById['agent-a'].status, 'idle');+ assert.equal(restored?.subagentsById['agent-a'].turn_outcome, 'completed');+ } finally {+ globalThis.window = previousWindow;+ }+});++test('session cache does not reopen a closed state with a newer revision', () => {+ const previousWindow = globalThis.window;+ const storageKey = `jiuwen.subagent.runtime.v1:${encodeURIComponent(sessionId)}`;+ const values = new Map();+ globalThis.window = {+ sessionStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ },+ };+ try {+ useSubagentStore.getState().removeRuntime(sessionId);+ useSubagentStore.getState().applyEvent(sessionId, event(5, subagent({+ status: 'closed',+ lifecycle: 'closed',+ needs_resume: true,+ can_send_input: false,+ closed_reason: 'completed',+ revision: 5,+ updated_at: 5000,+ })));+ values.set(storageKey, JSON.stringify({+ subagents: [subagent({+ status: 'running',+ lifecycle: 'live',+ needs_resume: false,+ can_send_input: true,+ closed_reason: null,+ revision: 6,+ updated_at: 6000,+ })],+ activities: [],+ results: [],+ selectedSubagentId: 'agent-a',+ }));+ useSubagentStore.getState().hydrateRuntime(sessionId);+ const restored = useSubagentStore.getState().getRuntime(sessionId);+ assert.equal(restored?.subagentsById['agent-a'].status, 'closed');+ assert.equal(restored?.subagentsById['agent-a'].revision, 5);+ } finally {+ useSubagentStore.getState().removeRuntime(sessionId);+ globalThis.window = previousWindow;+ }+});++test('empty history removes storage-only state but keeps a live update', () => {+ const previousWindow = globalThis.window;+ const values = new Map();+ globalThis.window = {+ sessionStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ },+ };+ try {+ useSubagentStore.getState().removeRuntime(sessionId);+ useSubagentStore.getState().applyEvent(sessionId, event(1));+ const cached = createEmptySubagentRuntime(sessionId);+ const cleared = dropCachedSubagent(cached, 'agent-a', 1, 1000);+ assert.equal(cleared.subagentsById['agent-a'], undefined);++ const live = applySubagentUpdated(cached, event(2, subagent({ revision: 2, updated_at: 2000 })));+ assert.equal(dropCachedSubagent(live, 'agent-a', 1, 1000), live);+ } finally {+ useSubagentStore.getState().removeRuntime(sessionId);+ globalThis.window = previousWindow;+ }+});++test('three-child WS sequence replays from history and stays isolated across sessions', () => {+ const parent = 'session-h';+ const other = 'session-h-other';+ const store = useSubagentStore.getState();+ store.removeRuntime(parent);+ store.removeRuntime(other);++ const eventFor = (targetSession, revision, overrides = {}) => ({+ event_type: 'chat.subtask_update',+ session_id: targetSession,+ subagent: subagent({+ parent_session_id: targetSession,+ revision,+ ...overrides,+ }),+ });+ const activityFor = (targetSession, childId, activityId) => ({+ event_type: 'chat.subagent_activity',+ session_id: targetSession,+ activity: activity(activityId, 1, {+ subagent_id: childId,+ parent_session_id: targetSession,+ task_id: `task-${childId}`,+ }),+ });++ try {+ const children = ['sa-a', 'sa-b', 'sa-c'];+ for (const [index, childId] of children.entries()) {+ store.applyEvent(parent, eventFor(parent, 1, {+ subagent_id: childId,+ display_name: `Child ${childId}`,+ status: 'running',+ updated_at: 1000 + index,+ }));+ store.applyEvent(parent, activityFor(parent, childId, `${childId}-think`));+ }+ store.applyEvent(parent, eventFor(parent, 2, {+ subagent_id: 'sa-a',+ display_name: 'Child sa-a',+ status: 'idle',+ turn_outcome: 'completed',+ updated_at: 2000,+ }));+ store.applyEvent(parent, eventFor(parent, 2, {+ subagent_id: 'sa-c',+ display_name: 'Child sa-c',+ status: 'closed',+ closed_reason: 'failed',+ updated_at: 2100,+ }));++ const live = store.getRuntime(parent);+ assert.deepEqual(selectSubagents(live).map(item => item.subagent_id).sort(), children);+ assert.equal(live.subagentsById['sa-a'].status, 'idle');+ assert.equal(live.subagentsById['sa-b'].status, 'running');+ assert.equal(live.subagentsById['sa-c'].status, 'closed');+ assert.equal(selectSubagentActivities(live, 'sa-a').length, 1);++ store.removeRuntime(parent);+ store.ensureRuntime(parent);+ for (const childId of children) {+ store.beginHistoryRestore(parent, childId);+ store.applyHistoryEvent(parent, eventFor(parent, 1, {+ subagent_id: childId,+ display_name: `Child ${childId}`,+ status: 'running',+ updated_at: 1000,+ }));+ store.applyHistoryEvent(parent, activityFor(parent, childId, `${childId}-think`));+ store.finishHistoryRestore(parent, childId);+ }+ store.applyHistoryEvent(parent, eventFor(parent, 2, {+ subagent_id: 'sa-a',+ display_name: 'Child sa-a',+ status: 'idle',+ updated_at: 2000,+ }));++ const restored = store.getRuntime(parent);+ assert.equal(selectSubagentHistoryRestoring(restored, 'sa-a'), false);+ assert.equal(restored.subagentsById['sa-a'].status, 'idle');+ assert.equal(selectSubagentActivities(restored, 'sa-b').length, 1);++ store.applyEvent(other, eventFor(other, 1, {+ subagent_id: 'sa-a',+ display_name: 'Other child',+ status: 'running',+ updated_at: 3000,+ }));+ const parentAfterSwitch = store.getRuntime(parent);+ const otherRuntime = store.getRuntime(other);+ assert.equal(parentAfterSwitch.subagentsById['sa-a'].status, 'idle');+ assert.equal(otherRuntime.subagentsById['sa-a'].status, 'running');+ assert.equal(selectSubagents(otherRuntime).length, 1);+ assert.equal(selectSubagentActivities(otherRuntime, 'sa-a').length, 0);+ } finally {+ useSubagentStore.getState().removeRuntime(parent);+ useSubagentStore.getState().removeRuntime(other);+ }+});diff --git a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.pynew file mode 100644index 0000000000..4d9f98764e--- /dev/null+++ b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py@@ -0,0 +1,200 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Loop-detection tests for develop's CircuitBreakerRail.++These cover repeat / ping-pong / unknown-tool / no-progress interrupts.+They are not the issue 3975 OPEN/HALF_OPEN recovery breaker.+"""++from __future__ import annotations++import time+from types import SimpleNamespace++from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ToolCallInputs,+)++from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (+ CircuitBreakerConfig,+ CircuitBreakerRail,+ ToolCallRecord,+)+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+ _agent_ras_kwargs_from_config,+)+++def _record(+ tool_name: str,+ args_hash: str,+ result_hash: str | None = "r1",+ *,+ has_error: bool = False,+) -> ToolCallRecord:+ return ToolCallRecord(+ tool_name=tool_name,+ args_hash=args_hash,+ result_hash=result_hash,+ timestamp=time.time(),+ has_error=has_error,+ )+++def _rail(**overrides: int) -> CircuitBreakerRail:+ return CircuitBreakerRail(+ CircuitBreakerConfig(+ warning_threshold=overrides.get("warning_threshold", 3),+ critical_threshold=overrides.get("critical_threshold", 4),+ global_breaker_threshold=overrides.get("global_breaker_threshold", 5),+ unknown_tool_threshold=overrides.get("unknown_tool_threshold", 3),+ )+ )+++def test_generic_repeat_warns_without_force_finish() -> None:+ rail = _rail(warning_threshold=3, global_breaker_threshold=10)+ history = [+ _record("read_file", "a", f"out-{index}")+ for index in range(3)+ ]+ result = rail._detect(history, "read_file", "a")+ assert result.stuck is True+ assert result.level == "warning"+ assert result.detector == "generic_repeat"+++def test_global_breaker_interrupts_no_progress() -> None:+ rail = _rail(global_breaker_threshold=5)+ history = [_record("bash", "cmd", "same") for _ in range(5)]+ result = rail._detect(history, "bash", "cmd")+ assert result.stuck is True+ assert result.level == "critical"+ assert result.detector == "global_circuit_breaker"+++def test_unknown_tool_repeat_interrupts_error_streak() -> None:+ rail = _rail(unknown_tool_threshold=3, global_breaker_threshold=10)+ history = [+ _record("missing_tool", "x", f"err-{index}", has_error=True)+ for index in range(3)+ ]+ result = rail._detect(history, "missing_tool", "x")+ assert result.stuck is True+ assert result.level == "critical"+ assert result.detector == "unknown_tool_repeat"+++def test_ping_pong_critical_when_both_sides_stall() -> None:+ rail = _rail(critical_threshold=3, warning_threshold=2, global_breaker_threshold=20)+ history: list[ToolCallRecord] = []+ for _ in range(3):+ history.append(_record("read_file", "hash-a", "same-a"))+ history.append(_record("write_file", "hash-b", "same-b"))+ result = rail._detect(history, "write_file", "hash-b")+ assert result.stuck is True+ assert result.level == "critical"+ assert result.detector == "ping_pong"+++def test_cleanup_session_drops_history() -> None:+ rail = _rail()+ rail._histories["s1"] = [_record("bash", "a")]+ rail._histories["s2"] = [_record("bash", "b")]+ rail.cleanup_session("s1")+ assert "s1" not in rail._histories+ assert "s2" in rail._histories+++def test_detect_is_isolated_per_session_history() -> None:+ rail = _rail(warning_threshold=3, global_breaker_threshold=10)+ session_a = [_record("read_file", "a", f"a-{index}") for index in range(3)]+ session_b = [_record("read_file", "a", "once")]+ hot = rail._detect(session_a, "read_file", "a")+ cold = rail._detect(session_b, "read_file", "a")+ assert hot.detector == "generic_repeat"+ assert cold.stuck is False+++async def test_after_tool_call_force_finishes_unknown_tool() -> None:+ rail = _rail(unknown_tool_threshold=2, global_breaker_threshold=10)+ rail._histories["s1"] = [_record("ghost", "g", "e1", has_error=True)]+ ctx = AgentCallbackContext(+ agent=object(),+ inputs=ToolCallInputs(+ tool_call=SimpleNamespace(name="ghost", arguments={"k": 1}),+ tool_result={"success": False, "error": "not found"},+ ),+ extra={"__jiuwenswarm_cb_session_id__": "s1"},+ )+ await rail.after_tool_call(ctx)+ assert ctx.has_force_finish_request is True+++def test_circuit_breaker_builder_stays_disabled_by_default(monkeypatch) -> None:+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod++ monkeypatch.setattr(deep_mod, "get_config", lambda: {"execution_guard": {}})+ adapter = JiuWenSwarmDeepAdapter()+ assert adapter._build_circuit_breaker_rail() is None+++def test_circuit_breaker_builder_rejects_invalid_thresholds(monkeypatch) -> None:+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod++ monkeypatch.setattr(+ deep_mod,+ "get_config",+ lambda: {+ "execution_guard": {+ "circuit_breaker": {+ "enabled": True,+ "warning_threshold": "10",+ "critical_threshold": 5,+ }+ }+ },+ )+ adapter = JiuWenSwarmDeepAdapter()+ assert adapter._build_circuit_breaker_rail() is None+++def test_circuit_breaker_builder_coerces_string_thresholds(monkeypatch) -> None:+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod++ monkeypatch.setattr(+ deep_mod,+ "get_config",+ lambda: {+ "execution_guard": {+ "circuit_breaker": {+ "enabled": True,+ "warning_threshold": "10",+ "critical_threshold": "20",+ "global_breaker_threshold": "30",+ "unknown_tool_threshold": "10",+ }+ }+ },+ )+ adapter = JiuWenSwarmDeepAdapter()+ rail = adapter._build_circuit_breaker_rail()+ assert rail is not None+ assert rail._config.warning_threshold == 10+ assert rail._config.critical_threshold == 20+++def test_dest_agent_ras_passthrough_is_not_disabled() -> None:+ """dest-stable RAS remains the default loop detector; do not overwrite it."""+ kwargs = _agent_ras_kwargs_from_config(+ {+ "agent_ras": {+ "enabled": True,+ "detectors": {"repeat_tool": {"enabled": True}},+ }+ }+ )+ assert kwargs["agent_ras"]["enabled"] is True+ assert kwargs["agent_ras"]["detectors"]["repeat_tool"]["enabled"] is Truediff --git a/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py b/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.pynew file mode 100644index 0000000000..e663d29eac--- /dev/null+++ b/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py@@ -0,0 +1,255 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Contract tests for ToolResultErrorDetector.++The detector's own docstring invites any module to import and reuse it, so+its behaviour is a shared contract rather than a private helper of+CircuitBreakerRail. Different consumers can want opposite things from it: a+circuit breaker counting consecutive failures of one tool must not fire on a+healthy result, while a rail that holds a task open until a required tool has+succeeded must not read a failure as success.++An unrecognised shape resolves to "no error", which is conservative for a+consumer that only wants to avoid false positives and dangerous for one that+must not miss a failure. That asymmetry is why every tool contract the+detector is expected to understand is pinned here rather than left to+whichever rail happens to exercise it.++Adding a tool that signals failure in a bare string means registering its+marker via ``ToolResultErrorDetector.register_plain_error_prefix`` from the+feature's own module -- not editing ``_PLAIN_ERROR_PREFIXES``. That tuple+stays generic; only ``[ERROR]:``, the project-wide tool-failure convention,+belongs in it.+"""++from __future__ import annotations++import json++import pytest++from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (+ ToolResultErrorDetector as Detector,+)+++class _Result:+ """A tool result object exposing success/data/error attributes."""++ def __init__(self, success: bool, data=None, error=None) -> None:+ self.success = success+ self.data = data+ self.error = error+++# ---------------------------------------------------------------------------+# Failures the detector must recognise+# ---------------------------------------------------------------------------++FAILURES = [+ pytest.param({"success": False, "error": "boom"}, id="dict-success-false"),+ pytest.param({"is_error": True}, id="dict-is-error"),+ pytest.param({"isError": "true"}, id="dict-isError-string"),+ pytest.param({"status": "failed"}, id="dict-status-failed"),+ pytest.param({"result_type": "error"}, id="dict-result-type"),+ pytest.param({"error": "something went wrong"}, id="dict-error-field"),+ pytest.param({"data": {"success": False}}, id="dict-nested-data"),+ # mcp_exec_command: a completed command that exited non-zero.+ pytest.param(+ json.dumps({"command": "git log", "exit_code": 128, "stdout": "",+ "stderr": "fatal: Out of memory, realloc failed"}),+ id="json-exit-code",+ ),+ pytest.param({"returncode": 1}, id="dict-returncode"),+ # Repr of a result object, as it reaches the session history.+ pytest.param("success=False data={'content': 'x'} error='boom'", id="repr-false"),+ # mcp_exec_command: the paths that never produce an exit code.+ pytest.param("[ERROR]: command timed out after 300s.", id="shell-timeout"),+ pytest.param("[ERROR]: command failed to start: No such file", id="shell-spawn"),+ pytest.param("[ERROR]: command execution failed: boom", id="shell-exec"),+ pytest.param("[ERROR]: background command failed: nope", id="shell-background"),+ # The same convention from other tool modules.+ pytest.param("[ERROR]: query cannot be empty.", id="search-empty-query"),+ pytest.param("[ERROR]: failed to fetch webpage: timeout", id="web-fetch-failed"),+ pytest.param("[ERROR]: read_pdf failed: boom", id="pdf-failed"),+ pytest.param(_Result(False, error="boom"), id="object-success-false"),+]++[email protected]("value", FAILURES)+def test_failures_are_recognised(value) -> None:+ assert Detector.has_error(value) is True+++# ---------------------------------------------------------------------------+# Successes the detector must not misread+# ---------------------------------------------------------------------------++SUCCESSES = [+ pytest.param({"success": True, "data": {"content": "ok"}}, id="dict-success-true"),+ pytest.param({"status": "ok"}, id="dict-status-ok"),+ pytest.param({"error": None}, id="dict-error-none"),+ pytest.param({"error": "none"}, id="dict-error-literal-none"),+ pytest.param(+ json.dumps({"command": "git log", "exit_code": 0, "stdout": "d4c3e32a",+ "stderr": ""}),+ id="json-exit-zero",+ ),+ pytest.param("success=True data={'content': 'ok'} error=None", id="repr-true"),+ # mcp_free_search on success: bare prose, no envelope, no marker.+ pytest.param(+ "Free search results (DuckDuckGo) for: circuit breaker\n"+ "1. Circuit breaker pattern\n https://example.invalid/cb",+ id="search-plain-success",+ ),+ # wiki_query on success: the model's answer, returned bare. Nothing in+ # its shape separates it from arbitrary prose, which is exactly why a+ # plain-string convention has to be a marker no success can start with.+ pytest.param(+ "The retry budget is consumed per tool, not per session.",+ id="wiki-plain-success",+ ),+ pytest.param(_Result(True, data={"content": "ok"}), id="object-success-true"),+]++[email protected]("value", SUCCESSES)+def test_successes_are_not_flagged(value) -> None:+ assert Detector.has_error(value) is False+++# ---------------------------------------------------------------------------+# Shapes the detector cannot classify+# ---------------------------------------------------------------------------++UNCLASSIFIABLE = [+ pytest.param(None, id="none"),+ pytest.param("", id="empty-string"),+ pytest.param("plain prose with no contract", id="free-text"),+ pytest.param("{not json", id="broken-json"),+]++[email protected]("value", UNCLASSIFIABLE)+def test_unclassifiable_shapes_claim_neither(value) -> None:+ """Neither an error nor an explicit success, and the consequences differ.++ A consumer that only wants to avoid false positives reads "not an error"+ and declines to count the call -- conservative, and it will not interrupt+ a run spuriously.++ A consumer that must not miss a failure reads the same value as+ satisfied, because its rule is `if not errored`. That is not an oversight+ to be tightened later: several tools return a bare string on success --+ `wiki_query` returns the model's answer, `mcp_free_search` returns a+ formatted result list -- so a gate that demanded explicit success would+ reject every one of them.++ The cost is real and worth stating plainly. A tool that signals failure+ in free text opens the gate for such a consumer. That is exactly the+ failure mode `_PLAIN_ERROR_PREFIXES` and `register_plain_error_prefix`+ exist to close: for any tool whose failure is a bare string, a registered+ marker is the only thing standing between a rejection and a task marked+ complete.+ """+ assert Detector.has_error(value) is False+ assert Detector.has_explicit_success(value) is False+++# ---------------------------------------------------------------------------+# has_explicit_success is narrower than "not an error"+# ---------------------------------------------------------------------------+++def test_explicit_success_requires_the_success_field() -> None:+ assert Detector.has_explicit_success({"success": True}) is True+ assert Detector.has_explicit_success({"status": "ok"}) is False+ assert Detector.has_explicit_success("Free search results for: anything") is False+++def test_a_success_field_beats_a_nonzero_exit_code() -> None:+ """An explicit success wins over the exit-code heuristic."""+ assert Detector.has_error({"success": True, "exit_code": 1}) is False+++def test_plain_error_prefix_is_matched_case_insensitively() -> None:+ assert Detector.has_error("[error]: command timed out after 300s.") is True+++def test_a_prefix_must_start_the_string() -> None:+ """A mention inside prose is not a failure signal."""+ assert Detector.has_error(+ "The tool replied [ERROR]: earlier, but this run succeeded."+ ) is False+++# ---------------------------------------------------------------------------+# A deliberate non-match+# ---------------------------------------------------------------------------++WIKI_FAILURES = [+ pytest.param("Error: Query cannot be empty.", id="wiki-error-colon"),+ pytest.param("Error querying wiki: connection refused", id="wiki-error-querying"),+ pytest.param("Wiki Query Error: boom", id="wiki-error-suffix"),+]++[email protected]("value", WIKI_FAILURES)+def test_bare_error_prose_is_not_matched(value) -> None:+ """`wiki_tools` signals failure in prose, and that stays unrecognised.++ Three different shapes appear in one file, and the common part is the word+ "Error" in ordinary prose. Adding it as a prefix would flag any tool whose+ successful output begins with that word, so the detector deliberately does+ not match it.++ This is a decision, not an oversight. The fix belongs in the tools:+ converge those returns on the project's `[ERROR]:` convention, and they+ are covered by the existing entry with no change here. Teaching this+ detector every dialect is what produced the gap it was written to close.+ """+ assert Detector.has_error(value) is False+++# ---------------------------------------------------------------------------+# register_plain_error_prefix: feature-owned markers, without editing the rail+# ---------------------------------------------------------------------------+++def _clean_registered_prefixes():+ """Isolate a test's registrations from every other test in the suite."""+ saved = set(Detector._extra_plain_error_prefixes)+ try:+ yield+ finally:+ Detector._extra_plain_error_prefixes.clear()+ Detector._extra_plain_error_prefixes.update(saved)+++def test_registered_prefix_is_recognised(_clean_registered_prefixes) -> None:+ """A feature can teach the detector its own bare-string convention.++ A tool whose failure contract is a bare string of its own -- rather than+ the project-wide `[ERROR]:` -- registers that marker from its own module.+ Nothing feature-specific has to be added to the rail for it to be counted.+ """+ assert Detector.has_error("EXAMPLE_TOOL_ERROR: unknown snapshot id.") is False++ Detector.register_plain_error_prefix("EXAMPLE_TOOL_ERROR:")++ assert Detector.has_error(+ "EXAMPLE_TOOL_ERROR: unknown snapshot id. Correct the payload and "+ "call the tool again."+ ) is True+++def test_registered_prefix_is_matched_case_insensitively(_clean_registered_prefixes) -> None:+ Detector.register_plain_error_prefix("my_tool_error:")+ assert Detector.has_error("My_Tool_Error: boom") is True+++def test_registering_a_blank_prefix_is_a_no_op(_clean_registered_prefixes) -> None:+ before = set(Detector._extra_plain_error_prefixes)+ Detector.register_plain_error_prefix(" ")+ assert Detector._extra_plain_error_prefixes == beforediff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex fbb58b4c6a..5e40ba2004 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -1931,7 +1931,7 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatcmonkeypatch.setattr(adapter, "_build_security_rail", lambda: None)monkeypatch.setattr(adapter, "_build_heartbeat_rail", lambda: None)monkeypatch.setattr(adapter, "_build_avatar_rail", lambda: None)- monkeypatch.setattr(adapter, "_build_subagent_rail", lambda: None)+ monkeypatch.setattr(adapter, "_build_subagent_rail", lambda **_kwargs: None)monkeypatch.setattr(adapter, "_build_skill_rail", lambda **_kwargs: None)monkeypatch.setattr(adapter, "_build_skill_retrieval_prompt_rail", lambda: None)monkeypatch.setattr(adapter, "_build_symphony_orchestration_rail", lambda: orchestration_rail)diff --git a/tests/unit_tests/agentserver/test_multi_session_notify.py b/tests/unit_tests/agentserver/test_multi_session_notify.pynew file mode 100644index 0000000000..adeb539c11--- /dev/null+++ b/tests/unit_tests/agentserver/test_multi_session_notify.py@@ -0,0 +1,142 @@+from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from jiuwenswarm.agents.harness.common.tools.multi_session_toolkits import (+ MultiSessionToolkit,+ SessionTask,+ Status,+)+from jiuwenswarm.server.runtime.agent_manager import AgentManager+++def _completed_toolkit() -> MultiSessionToolkit:+ toolkit = object.__new__(MultiSessionToolkit)+ toolkit.session_id = "parent-session"+ toolkit.channel_id = "web"+ toolkit.request_id = "request-1"+ toolkit._agent_manager = None+ toolkit.sessions = [+ SessionTask(+ session_id="child-session",+ description="Summarize the result",+ status=Status.COMPLETED,+ result="done",+ )+ ]+ toolkit._send_task_notification = AsyncMock()+ return toolkit+++async def test_completed_batch_uses_current_agent_manager_contract() -> None:+ toolkit = _completed_toolkit()+ manager = MagicMock(spec=AgentManager)+ manager.get_agent_nowait.return_value = None+ server = MagicMock()+ server.get_agent_manager.return_value = manager+ server.get_agent.return_value = None++ with (+ patch(+ "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",+ return_value=server,+ ),+ patch(+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",+ new=AsyncMock(return_value=True),+ ) as push,+ ):+ await toolkit.notify("child-session", Status.COMPLETED, result="done")++ manager.get_agent_nowait.assert_called_once_with("web")+ server.get_agent.assert_called_once()+ push.assert_awaited_once()+++async def test_completed_batch_uses_injected_agent_manager() -> None:+ toolkit = _completed_toolkit()+ manager = MagicMock(spec=AgentManager)+ manager.get_agent_nowait.return_value = None+ toolkit._agent_manager = manager++ with (+ patch(+ "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",+ ) as current_instance,+ patch(+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",+ new=AsyncMock(return_value=True),+ ) as push,+ ):+ await toolkit.notify("child-session", Status.COMPLETED, result="done")++ current_instance.assert_not_called()+ manager.get_agent_nowait.assert_called_once_with("web")+ push.assert_awaited_once()+++async def test_notify_without_runtime_host_keeps_local_summary() -> None:+ toolkit = _completed_toolkit()++ with (+ patch(+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",+ new=AsyncMock(return_value=False),+ ) as push,+ patch(+ "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.logger"+ ) as toolkit_logger,+ ):+ await toolkit.notify("child-session", Status.COMPLETED, result="done")++ push.assert_awaited_once()+ info_messages = [+ " ".join(str(part) for part in call.args)+ for call in toolkit_logger.info.call_args_list+ ]+ assert any("Runtime push host unavailable" in message for message in info_messages)+ assert any("parent-session" in message for message in info_messages)+++async def test_agent_server_push_host_lifecycle_out_of_order(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.runtime import host_services+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer++ monkeypatch.setattr(host_services, "_runtime_push_handler", None)+ monkeypatch.setattr(host_services, "_runtime_push_handlers", [])++ first = AgentWebSocketServer.__new__(AgentWebSocketServer)+ first._runtime_push_handler = None+ first._previous_runtime_push_handler = None++ async def first_push(_msg: dict) -> int:+ return 1++ first.send_push = first_push # type: ignore[method-assign]++ second = AgentWebSocketServer.__new__(AgentWebSocketServer)+ second._runtime_push_handler = None+ second._previous_runtime_push_handler = None+ calls: list[str] = []++ async def second_push(_msg: dict) -> int:+ calls.append("second")+ return 1++ second.send_push = second_push # type: ignore[method-assign]++ first._install_runtime_push_host()+ second._install_runtime_push_host()+ first._restore_runtime_push_host()+ assert await host_services.send_runtime_push({"value": 1}) is True+ assert calls == ["second"]+ second._restore_runtime_push_host()+ assert await host_services.send_runtime_push({"value": 2}) is Falsediff --git a/tests/unit_tests/agentserver/test_statusline_setup_subagent.py b/tests/unit_tests/agentserver/test_statusline_setup_subagent.pynew file mode 100644index 0000000000..26561371c7--- /dev/null+++ b/tests/unit_tests/agentserver/test_statusline_setup_subagent.py@@ -0,0 +1,209 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Registration tests for the built-in statusline-setup subagent."""++from __future__ import annotations++from unittest.mock import MagicMock++from openjiuwen.harness.rails import SysOperationRail++from jiuwenswarm.agents.swarm.config_specs import build_member_subagent_specs+from jiuwenswarm.agents.swarm import registry+from jiuwenswarm.server.runtime.agent_adapter.interface_code import (+ JiuwenSwarmCodeAdapter,+)+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)+from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (+ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,+ STATUSLINE_SETUP_AGENT_TYPE,+)+from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService+++def test_statusline_setup_is_a_builtin_agent_definition(tmp_path):+ definition = AgentConfigService(tmp_path).get_agent(STATUSLINE_SETUP_AGENT_TYPE)++ assert definition is not None+ assert definition.source == "builtin"+ assert definition.tools == ["Read", "Write", "Edit", "Bash"]+ assert "statusline-setup subagent" in definition.prompt+++def test_single_agent_runtime_registers_statusline_setup(monkeypatch, tmp_path):+ adapter = JiuWenSwarmDeepAdapter()+ adapter._workspace_dir = str(tmp_path)+ adapter._sys_operation = None+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)++ subagents, _ = adapter._build_configured_subagents(+ MagicMock(),+ {+ "max_iterations": 20,+ "subagents": {+ STATUSLINE_SETUP_AGENT_TYPE: {+ "enabled": True,+ "max_iterations": 9,+ }+ },+ },+ {},+ )++ assert subagents is not None+ assert [spec.agent_card.name for spec in subagents] == [STATUSLINE_SETUP_AGENT_TYPE]+ assert subagents[0].max_iterations == 9+ assert subagents[0].enable_task_loop is False+ assert any(isinstance(rail, SysOperationRail) for rail in subagents[0].rails)+++def test_single_agent_runtime_does_not_register_when_disabled(monkeypatch, tmp_path):+ adapter = JiuWenSwarmDeepAdapter()+ adapter._workspace_dir = str(tmp_path)+ adapter._sys_operation = None+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)++ subagents, _ = adapter._build_configured_subagents(+ MagicMock(),+ {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},+ {},+ )++ assert subagents is None+++def test_code_runtime_registers_statusline_setup_by_default(monkeypatch, tmp_path):+ adapter = JiuwenSwarmCodeAdapter()+ adapter._workspace_dir = str(tmp_path)+ adapter._project_dir = str(tmp_path)+ adapter._coding_memory_rail = None+ sys_operation = MagicMock()+ adapter._sys_operation = sys_operation+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)++ subagents, _ = adapter._build_configured_subagents(+ MagicMock(),+ {"max_iterations": 20},+ {},+ )++ assert subagents is not None+ assert [spec.agent_card.name for spec in subagents] == [+ STATUSLINE_SETUP_AGENT_TYPE,+ "explore_agent",+ "plan_agent",+ ]+ statusline_spec = subagents[0]+ assert statusline_spec.max_iterations == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS+ assert statusline_spec.enable_task_loop is False+ assert statusline_spec.sys_operation is sys_operation+ assert statusline_spec.workspace == str(tmp_path)+++def test_code_runtime_honors_explicit_statusline_disable(monkeypatch, tmp_path):+ adapter = JiuwenSwarmCodeAdapter()+ adapter._workspace_dir = str(tmp_path)+ adapter._project_dir = str(tmp_path)+ adapter._coding_memory_rail = None+ adapter._sys_operation = MagicMock()+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)++ subagents, _ = adapter._build_configured_subagents(+ MagicMock(),+ {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},+ {},+ )++ assert subagents is not None+ assert [spec.agent_card.name for spec in subagents] == [+ "explore_agent",+ "plan_agent",+ ]+++def test_code_runtime_honors_explicit_statusline_iteration_budget(+ monkeypatch,+ tmp_path,+):+ adapter = JiuwenSwarmCodeAdapter()+ adapter._workspace_dir = str(tmp_path)+ adapter._project_dir = str(tmp_path)+ adapter._coding_memory_rail = None+ adapter._sys_operation = MagicMock()+ monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)++ subagents, _ = adapter._build_configured_subagents(+ MagicMock(),+ {+ "max_iterations": 100,+ "subagents": {+ STATUSLINE_SETUP_AGENT_TYPE: {+ "enabled": True,+ "max_iterations": 7,+ }+ },+ },+ {},+ )++ assert subagents is not None+ assert subagents[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE+ assert subagents[0].max_iterations == 7+++def test_team_member_runtime_registers_same_builtin_subagent():+ specs = build_member_subagent_specs(+ {+ "react": {+ "subagents": {+ STATUSLINE_SETUP_AGENT_TYPE: {"enabled": True},+ }+ }+ },+ "team",+ "leader",+ )++ assert len(specs) == 1+ assert specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE+ assert specs[0].factory_name == registry.STATUSLINE_SETUP_AGENT+ assert (+ specs[0].factory_kwargs["max_iterations"]+ == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS+ )+++def test_team_member_runtime_honors_statusline_disable_and_iteration_budget():+ disabled_specs = build_member_subagent_specs(+ {+ "react": {+ "subagents": {+ STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False},+ }+ }+ },+ "team",+ "leader",+ )+ assert disabled_specs == []++ configured_specs = build_member_subagent_specs(+ {+ "react": {+ "max_iterations": 100,+ "subagents": {+ STATUSLINE_SETUP_AGENT_TYPE: {+ "enabled": True,+ "max_iterations": 7,+ },+ },+ }+ },+ "team",+ "leader",+ )+ assert len(configured_specs) == 1+ assert configured_specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE+ assert configured_specs[0].factory_kwargs["max_iterations"] == 7diff --git a/tests/unit_tests/agentserver/test_subagent_history_routing.py b/tests/unit_tests/agentserver/test_subagent_history_routing.pynew file mode 100644index 0000000000..8123e782ba--- /dev/null+++ b/tests/unit_tests/agentserver/test_subagent_history_routing.py@@ -0,0 +1,116 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Regression tests for parent-owned subagent history persistence."""++from __future__ import annotations++from jiuwenswarm.common.schema.message import EventType+from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (+ _WEB_FULL_PAYLOAD_EVENT_TYPES,+)+from jiuwenswarm.server.runtime.session import session_history, session_metadata+++def test_subagent_history_writes_use_dedicated_child_bucket(monkeypatch) -> None:+ persisted: list[tuple[str, str, list[dict], str | None]] = []+ metadata_updates: list[dict] = []+ monkeypatch.setattr(+ session_history,+ "_batch_write_subagent_items",+ lambda sid, child_id, items, root: persisted.append((sid, child_id, items, root)),+ )+ monkeypatch.setattr(+ session_metadata,+ "update_session_metadata",+ lambda **kwargs: metadata_updates.append(kwargs),+ )++ session_history.append_history_record(+ session_id="parent-session",+ request_id="request-1",+ channel_id="web",+ role="assistant",+ content="result",+ timestamp=1.0,+ event_type="chat.final",+ task_id="task-1",+ subagent_id="subagent-1",+ mode="subagent",+ )++ assert len(persisted) == 1+ sid, child_id, items, _root = persisted[0]+ assert sid == "parent-session"+ assert child_id == "subagent-1"+ assert len(items) == 1+ assert items[0]["session_id"] == "parent-session"+ assert items[0]["subagent_id"] == "subagent-1"+ assert items[0]["mode"] == "subagent"+ assert metadata_updates == []+++def test_subagent_rows_go_under_parent_subagents_dir(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)+ session_history.append_history_record(+ session_id="parent1",+ request_id="r-parent",+ channel_id="web",+ role="user",+ content="hello",+ timestamp=1.0,+ )+ session_history.append_history_record(+ session_id="parent1",+ subagent_id="sa-explore-1",+ request_id="sa-explore-1:1",+ channel_id="subagent",+ role="assistant",+ content="child note",+ timestamp=2.0,+ event_type="chat.delta",+ mode="subagent",+ extra={"parent_session_id": "parent1"},+ )++ parent_rows = session_history.load_history_records("parent1")+ child_rows = session_history.load_history_records(+ "parent1",+ subagent_id="sa-explore-1",+ )+ assert [row.get("content") for row in parent_rows] == ["hello"]+ assert any(row.get("content") == "child note" for row in child_rows)+ child_path, error = session_history.resolve_subagent_history_path(+ "parent1",+ "sa-explore-1",+ create=False,+ )+ assert error is None+ assert child_path is not None+ assert child_path.exists()+ assert "subagents" in child_path.parts+ assert not session_history.history_exists("parent1", subagent_id="../escape")+++def test_empty_subagent_activity_is_persistable(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)+ session_history.append_history_record(+ session_id="parent1",+ subagent_id="sa-1",+ request_id="sa-1:activity:turn:1",+ channel_id="subagent",+ role="assistant",+ content="",+ timestamp=3.0,+ event_type="chat.subagent_activity",+ extra={"subagent_activity": {"subagent_id": "sa-1", "summary": ""}},+ mode="subagent",+ )+ rows = session_history.load_history_records("parent1", subagent_id="sa-1")+ assert len(rows) == 1+ assert rows[0]["event_type"] == "chat.subagent_activity"+++def test_web_allowlist_includes_subagent_activity() -> None:+ assert EventType.CHAT_SUBAGENT_ACTIVITY.value == "chat.subagent_activity"+ assert "chat.subagent_activity" in _WEB_FULL_PAYLOAD_EVENT_TYPES+ assert "task.start" in _WEB_FULL_PAYLOAD_EVENT_TYPESdiff --git a/tests/unit_tests/runtime/test_runtime_host_services.py b/tests/unit_tests/runtime/test_runtime_host_services.pynew file mode 100644index 0000000000..50350f4fae--- /dev/null+++ b/tests/unit_tests/runtime/test_runtime_host_services.py@@ -0,0 +1,68 @@+from __future__ import annotations++import pytest++from jiuwenswarm.runtime import host_services++[email protected](autouse=True)+def _isolate_host_handlers(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(host_services, "_runtime_push_handler", None)+ monkeypatch.setattr(host_services, "_runtime_push_handlers", [])+++async def test_push_owner_out_of_order_restore_does_not_revive_stale_owner() -> None:+ calls: list[str] = []++ async def first(_message: dict) -> None:+ calls.append("first")++ async def second(_message: dict) -> None:+ calls.append("second")++ first_previous = host_services.install_runtime_push_handler(first)+ second_previous = host_services.install_runtime_push_handler(second)++ host_services.restore_runtime_push_handler(first, first_previous)+ assert await host_services.send_runtime_push({"value": 1}) is True+ assert calls == ["second"]++ host_services.restore_runtime_push_handler(second, second_previous)+ assert await host_services.send_runtime_push({"value": 2}) is False+ assert calls == ["second"]+++async def test_runtime_host_push_transport_has_explicit_unavailable_contract() -> None:+ transport = host_services.RuntimeHostPushTransport()++ with pytest.raises(RuntimeError, match="without a resident host"):+ await transport.send_push({"value": 1})++ captured: list[dict] = []++ async def capture(message: dict) -> None:+ captured.append(message)++ previous = host_services.install_runtime_push_handler(capture)+ try:+ await transport.send_push({"value": 2})+ finally:+ host_services.restore_runtime_push_handler(capture, previous)++ assert captured == [{"value": 2}]+++async def test_runtime_push_propagates_explicit_delivery_failure() -> None:+ async def reject(_message: dict) -> bool:+ return False++ previous = host_services.install_runtime_push_handler(reject)+ try:+ assert await host_services.send_runtime_push({"value": 1}) is False+ with pytest.raises(RuntimeError, match="without a resident host"):+ await host_services.RuntimeHostPushTransport().send_push({"value": 2})+ finally:+ host_services.restore_runtime_push_handler(reject, previous)