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(goal): 目标管理前端实现
cjh_jinduoxiae97cd756c7d6
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 779954e527..70c4bd2e05 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -39,7 +39,7 @@ import {normalizeToolCallPayload,normalizeToolResultPayload,} from './features/tool-events/toolEventNormalizer';-import { useWebSocket } from './hooks';+import { useWebSocket, mergePersistedGoalCompletionMessages } from './hooks';import { webRequest } from './services/webClient';import { useTeamPanelState } from './features/teamPanelState';import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session } from './types';@@ -48,6 +48,7 @@ import {useSessionStore,useChatStore,useTodoStore,+ useGoalStore,useHarnessStore,useWorkspaceStore,useCronStore,@@ -577,6 +578,12 @@ function AppContent() {cancel,supplement,sendUserAnswer,+ setGoalObjective,+ pauseGoal,+ resumeGoal,+ clearGoal,+ refreshGoal,+ drainTaskQueueIfIdle,} = useWebSocket({activeSessionId: sessionId,onConnect: () => console.log('Connected'),@@ -1300,7 +1307,10 @@ function AppContent() {sessionId: sessionId,onReady: (messages, totalPages) => {historyRestoreFromPanelHintRef.current = false;- replaceHistoryMessages(sessionId, messages);+ // "目标完成"回显消息纯前端合成,从未写进后端 session 历史,history.get 拉回来的+ // messages 里不会有它——按时间戳把本地持久化的记录补回去,见+ // hooks/useWebSocket.ts 的 applyIncomingGoal/mergePersistedGoalCompletionMessages。+ replaceHistoryMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, messages));const restoredTotalPages = totalPages ?? 1;setHistoryPagerMeta(sessionId, {loadedPages: 1,@@ -1315,7 +1325,7 @@ function AppContent() {});},onEmpty: (emptyTotalPages) => {- replaceHistoryMessages(sessionId, []);+ replaceHistoryMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, []));const restoredTotalPages = emptyTotalPages ?? 1;setHistoryPagerMeta(sessionId, {loadedPages: 1,@@ -1465,6 +1475,29 @@ function AppContent() {startBackgroundHistoryPrefetch,]);+ // 会话切换/页面加载时主动拉一次当前 Goal 状态(协议文档 v2 §11 推荐流程)——不然刷新页面+ // 后 GoalBar 要等下一次 goal.updated 推送才会重新出现,目标 paused/静默期时甚至会一直缺失+ // (2026-07-21 真机联调发现,见 backend-requests.md #1 末尾)。新会话(promoted from 'new')+ // 同样可能已经有 Goal(欢迎页 armed 流程可以直接创建),不跳过。+ // get 完如果 status 是 active,按 §11 第4步再补发一次流式 resume——不是"目标被暂停了要恢复",+ // 是"重新抢一次输出听筒":切会话/刷新导致之前监听后端输出的那条连接断了,目标可能还在后台跑,+ // 这时候没人在听它的实时输出(chat.delta/chat.reasoning 等)。resume 对一个本来就 active 的+ // 目标发是幂等的(状态不会变),抢到听筒就能继续收到实时输出,抢不到收 runtime.accepted,+ // 都不算错误。+ useEffect(() => {+ if (!isConnected || !sessionId || sessionId === NEW_CONVERSATION_ID) return;+ if (!isRestorableSessionId(sessionId)) return;+ void (async () => {+ await refreshGoal(sessionId);+ // 等 get 落地这段时间里用户可能已经切到别的会话,避免对着旧会话发 resume。+ if (sessionIdRef.current !== sessionId) return;+ const goal = useGoalStore.getState().runtimes[sessionId]?.goal;+ if (goal?.status === 'active') {+ void resumeGoal(sessionId);+ }+ })();+ }, [isConnected, sessionId, refreshGoal, resumeGoal]);+const requestComposerFocus = useCallback(() => {setComposerFocusNonce((nonce) => nonce + 1);}, []);@@ -1582,11 +1615,25 @@ function AppContent() {sessionIdRef.current = newSid;setSessionId(newSid);navigate({ kind: 'chat-session', sessionId: newSid }, { replace: true });- const sent = await sendMessage(content, newSid, mediaItems);- newConversationProjectRef.current = null;- if (!sent) {- useChatStore.getState().setInputValue(newSid, content);+ const goalArmedOnNew = useGoalStore.getState().runtimes[NEW_CONVERSATION_ID]?.armed ?? false;+ useGoalStore.getState().setArmed(NEW_CONVERSATION_ID, false);+ if (goalArmedOnNew) {+ // 欢迎页 "+" 选了「目标」:这条内容不走普通 chat.send,+ // 本地落一条 user 消息(供徽章匹配)后改调 command.goal(见 InputArea.tsx 的同款分流逻辑)+ useChatStore.getState().addMessage(newSid, {+ id: `user-${Date.now()}`,+ role: 'user',+ content,+ timestamp: new Date().toISOString(),+ });+ setGoalObjective(newSid, content);+ } else {+ const sent = await sendMessage(content, newSid, mediaItems);+ if (!sent) {+ useChatStore.getState().setInputValue(newSid, content);+ }}+ newConversationProjectRef.current = null;} catch (error) {useChatStore.getState().setProcessing(NEW_CONVERSATION_ID, false);useChatStore.getState().setThinking(NEW_CONVERSATION_ID, false);@@ -1610,7 +1657,7 @@ function AppContent() {} else {useChatStore.getState().setInputValue(currentSessionId, content);}- }, [disposeInFlightHistoryHandles, mode, navigate, request, sendMessage, t]);+ }, [disposeInFlightHistoryHandles, mode, navigate, request, sendMessage, setGoalObjective, t]);const handlePersistMedia = useCallback((content: string, mediaItems: MediaItem[]) => {const currentSessionId = sessionIdRef.current;@@ -1791,6 +1838,7 @@ function AppContent() {useChatStore.getState().removeRuntime(deleteTarget.session_id);useTodoStore.getState().removeRuntime(deleteTarget.session_id);useHarnessStore.getState().removeRuntime(deleteTarget.session_id);+ useGoalStore.getState().removeRuntime(deleteTarget.session_id);const deletingCurrent = sessionIdRef.current === deleteTarget.session_id;setDeleteTarget(null);await useWorkspaceStore.getState().refreshSessionWorkspace(deletedSession);@@ -1989,6 +2037,11 @@ function AppContent() {onSavePermission={savePermissionSilent}historyPager={chatHistoryPager}isHistoryRestoring={isRestoringHistorySession}+ onSetGoal={setGoalObjective}+ onPauseGoal={pauseGoal}+ onResumeGoal={resumeGoal}+ onClearGoal={clearGoal}+ onDrainTaskQueueIfIdle={drainTaskQueueIfIdle}/></div></div>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex bd1481057f..76b95cf70f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -1404,6 +1404,55 @@ overflow: hidden;color: var(--color-feedback-danger);}+/* "+" 附件菜单的定位锚点,纯占位,不需要额外视觉样式 */+.chat-input-attach-menu-anchor {+ position: relative;+ display: inline-flex;+}++/* 工具栏"目标"标签:目标存续期间常驻,× 只在 hover 时出现,不占布局空间;+ hover 时标签本体腾出右侧内边距,让 × 紧跟在文字后面居中出现,而不是悬浮在右上角 */+.chat-goal-tag {+ position: relative;+ display: inline-flex;+}++.chat-goal-tag .chat-mode-select__trigger {+ transition: padding-right 0.15s;+}++.chat-goal-tag:hover .chat-mode-select__trigger {+ padding-right: 28px;+}++.chat-goal-tag__close {+ position: absolute;+ right: 8px;+ top: 50%;+ transform: translateY(-50%);+ width: 16px;+ height: 16px;+ display: flex;+ align-items: center;+ justify-content: center;+ border: none;+ border-radius: 999px;+ background: transparent;+ color: var(--color-text-secondary);+ opacity: 0;+ transition: opacity 0.15s;+ cursor: pointer;+}++.chat-goal-tag:hover .chat-goal-tag__close {+ opacity: 1;+}++.chat-goal-tag__close:hover {+ color: var(--color-text-primary);+ background: var(--color-surface-hover);+}+.chat-work-context-row {position: relative;display: flex;diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsxindex bb6ec5368b..e39f200879 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx@@ -1,11 +1,11 @@import { useState, useRef, useCallback, KeyboardEvent, useEffect, ClipboardEvent, DragEvent, ChangeEvent, useMemo } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';-import { AtSign, CircleX, FileImage, Loader2, Plus, Square, X } from 'lucide-react';+import { AtSign, CircleX, FileImage, Loader2, Plus, Square, Target, X } from 'lucide-react';import { useSpeechRecognition } from '../../hooks';// import { stopAllTts } from '../../utils';-import { useChatStore, useSessionStore, useWorkspaceStore } from '../../stores';+import { useChatStore, useGoalStore, useSessionStore, useWorkspaceStore } from '../../stores';import { AgentMode, MediaItem, Permission, type ProjectInfo } from '../../types';import { NEW_CONVERSATION_ID } from '../../multi-session/state/newConversationLifecycle';import { ProjectCreateMenu, type ProjectCreateMode } from '../../multi-session/sidebar/ProjectCreateMenu';@@ -106,6 +106,17 @@ interface InputAreaProps {onNavigateToSkills?: () => void;permissionsEnabled: boolean;onSavePermission: (updates: Record<string, string>) => Promise<void>;+ /** 目标待设置态("+"菜单选了「目标」)下发送时调用,取代普通 onSubmit/排队逻辑 */+ onSetGoal?: (sessionId: string, objective: string) => void;+ /** 工具栏"目标"标签的 × 按钮:目标已存在时点击等同删除目标 */+ onClearGoal?: (sessionId: string) => void;+ /**+ * 目标 active 时消息按设计走排队(见下方 isGoalActive 注释),但如果入队那一刻当前没有+ * 任何任务在处理,现有的自动排空触发点(chat.processing_status/interrupt_result)都要求+ * "之前在 processing",不会命中,消息会永久卡住。入队后调用它兜底:内部会判断当前是否+ * 真的空闲,空闲才会真正发送,不会重复触发。+ */+ onDrainTaskQueueIfIdle?: (sessionId: string) => void;}const ACCEPTED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);@@ -237,6 +248,9 @@ export function InputArea({onNavigateToSkills,permissionsEnabled,onSavePermission,+ onSetGoal,+ onClearGoal,+ onDrainTaskQueueIfIdle,}: InputAreaProps) {const [pendingVoiceText, setPendingVoiceText] = useState('');const [isModeMenuOpen, setIsModeMenuOpen] = useState(false);@@ -257,12 +271,16 @@ export function InputArea({const [composerSuggestion, setComposerSuggestion] = useState<ComposerSuggestionState | null>(null);const [composerSuggestionIndex, setComposerSuggestionIndex] = useState(0);const [modeMenuAnchor, setModeMenuAnchor] = useState<DOMRect | null>(null);+ const [attachMenuOpen, setAttachMenuOpen] = useState(false);+ const [attachMenuAnchor, setAttachMenuAnchor] = useState<DOMRect | null>(null);const inputRef = useRef<HTMLDivElement>(null);/** 保存技能插入前的光标位置,用于在光标处插入 chip */const savedRangeRef = useRef<Range | null>(null);const modeMenuRef = useRef<HTMLDivElement>(null);const workMenuRef = useRef<HTMLDivElement>(null);const modeMenuPortalRef = useRef<HTMLDivElement>(null);+ const attachMenuRef = useRef<HTMLDivElement>(null);+ const attachMenuPortalRef = useRef<HTMLDivElement>(null);const autoSendTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const attachmentMenuTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const attachmentMenuOpenedByLongPressRef = useRef(false);@@ -294,12 +312,24 @@ export function InputArea({} = useWorkspaceStore();const loadedMsgLen = useChatStore((s) => s.runtimes[activeSessionId ?? '']?.messages?.length ?? 0);const hasHistory = (currentSession?.message_count ?? 0) > 0 || loadedMsgLen > 0;- const isInterruptible = isProcessing || isPaused;+ const goalArmed = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.armed ?? false);+ const currentGoal = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.goal ?? null);+ // 目标 active 时普通发送改走排队,而不是文档 §5.1 原定的 input_mode:'steer' 实时插话——+ // 用户明确要求改成这个语义(steer 目前收不到任何反馈,体验上等同于消息发出去石沉大海,+ // 见 backend-requests.md #1)。走排队后消息复用现有的通用队列机制,行为和普通排队一致。+ const isGoalActive = currentGoal?.status === 'active';+ const isInterruptible = isProcessing || isPaused || isGoalActive;const isAgentMode = mode === 'agent';const isTeamMode = mode === 'team';const isAutoHarnessMode = mode === 'auto_harness';const isWorkContextLocked = Boolean(activeSessionId && activeSessionId !== NEW_CONVERSATION_ID);const showWorkContextRow = activeSessionId === NEW_CONVERSATION_ID;+ /** Goal 入口是否适用于当前上下文(agent 模式 + 已接入 onSetGoal,如欢迎页新会话就不适用) */+ const canUseGoalMenu = isAgentMode && Boolean(onSetGoal);+ // 只跟 armed 挂钩:这个 tag 是"下一条消息将用于设置目标"的过渡态指示,发送后 armed 变 false+ // 就该跟着消失,不能靠"目标是否存在"续命——目标存在与否、当前状态、编辑/暂停/删除,已经由+ // 输入框上方常驻的 GoalBar 完整覆盖,工具栏这里再挂一份重复的常驻入口只会显得"选择没解除"。+ const goalTagVisible = canUseGoalMenu && goalArmed;const mentionableMembers = useMemo(() => {return teamMembers@@ -622,6 +652,25 @@ export function InputArea({};}, [isModeMenuOpen]);+ useEffect(() => {+ if (!attachMenuOpen) return;++ const handlePointerDown = (event: PointerEvent) => {+ if (+ !attachMenuRef.current?.contains(event.target as Node) &&+ !attachMenuPortalRef.current?.contains(event.target as Node)+ ) {+ setAttachMenuOpen(false);+ }+ };++ document.addEventListener('pointerdown', handlePointerDown);++ return () => {+ document.removeEventListener('pointerdown', handlePointerDown);+ };+ }, [attachMenuOpen]);+useEffect(() => {if (!attachmentMenuId) return;@@ -760,7 +809,22 @@ export function InputArea({}const sid = useChatStore.getState().activeSessionId;- if (isTeamMode) {+ if (goalArmed && trimmed && sid && onSetGoal && sid !== NEW_CONVERSATION_ID) {+ // command.goal 是独立控制信令,不受聊天排队影响,跳过 team/queue/interrupt 判断;+ // 消息仍要本地落进 chatStore 才能在气泡上显示"设为目标"徽章(见 MessageItem.tsx)+ useChatStore.getState().addMessage(sid, {+ id: `user-${Date.now()}`,+ role: 'user',+ content: trimmed,+ timestamp: new Date().toISOString(),+ });+ useGoalStore.getState().setArmed(sid, false);+ onSetGoal(sid, trimmed);+ } else if (goalArmed && trimmed && sid === NEW_CONVERSATION_ID) {+ // 欢迎页尚无真实 session,armed 状态先保留,交给 App.tsx 的 handleSendMessage+ // 在 session.create 成功、拿到真实 session id 后再落地消息 + 调 onSetGoal+ onSubmit(trimmed, readyMediaItems);+ } else if (isTeamMode) {onSubmit(trimmed, readyMediaItems);} else if (queuePaused && isAgentMode && sid) {// 队列已暂停时,弹窗提示用户选择@@ -779,6 +843,8 @@ export function InputArea({if (isAgentMode) {if (sid) {useChatStore.getState().addToTaskQueue(sid, trimmed);+ // 目标 active 但当前没有任务在处理时,常规的自动排空触发点不会命中,主动兜底一次+ onDrainTaskQueueIfIdle?.(sid);}} else {onInterrupt(trimmed);@@ -812,6 +878,9 @@ export function InputArea({isAgentMode,isTeamMode,queuePaused,+ goalArmed,+ onSetGoal,+ onDrainTaskQueueIfIdle,t,]);@@ -1511,19 +1580,98 @@ export function InputArea({className="hidden"onChange={handleFileInputChange}/>- <button- type="button"- onClick={() => fileInputRef.current?.click()}- disabled={imageInputDisabled}- className={cx(- 'chat-input-btn chat-input-btn--add-file',- imageInputDisabled && 'chat-input-btn--disabled',+ <div ref={attachMenuRef} className="chat-input-attach-menu-anchor">+ {canUseGoalMenu ? (+ <button+ type="button"+ onClick={() => {+ if (imageInputDisabled) return;+ if (!attachMenuOpen && attachMenuRef.current) {+ setAttachMenuAnchor(attachMenuRef.current.getBoundingClientRect());+ }+ setAttachMenuOpen((open) => !open);+ }}+ disabled={imageInputDisabled}+ className={cx(+ 'chat-input-btn chat-input-btn--add-file',+ imageInputDisabled && 'chat-input-btn--disabled',+ )}+ title={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ aria-label={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ aria-haspopup="menu"+ aria-expanded={attachMenuOpen}+ >+ <Plus className="chat-input-btn-icon" strokeWidth={1.8} />+ </button>+ ) : (+ // 没有 onSetGoal(如欢迎页新会话尚未创建)时,Goal 入口本来就不适用——+ // 保持原来"+"直接打开文件选择器的单击行为,不额外套一层菜单+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={imageInputDisabled}+ className={cx(+ 'chat-input-btn chat-input-btn--add-file',+ imageInputDisabled && 'chat-input-btn--disabled',+ )}+ title={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ aria-label={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ >+ <Plus className="chat-input-btn-icon" strokeWidth={1.8} />+ </button>)}- title={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}- aria-label={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}- >- <Plus className="chat-input-btn-icon" strokeWidth={1.8} />- </button>+ {canUseGoalMenu && attachMenuOpen && attachMenuAnchor && createPortal(+ <div+ ref={attachMenuPortalRef}+ className="chat-mode-select__menu"+ role="menu"+ style={{+ position: 'fixed',+ bottom: window.innerHeight - attachMenuAnchor.top + 10,+ left: attachMenuAnchor.left,+ zIndex: 9999,+ }}+ >+ <button+ type="button"+ className="chat-mode-select__option"+ role="menuitem"+ onClick={() => {+ setAttachMenuOpen(false);+ fileInputRef.current?.click();+ }}+ >+ <span className="chat-mode-select__option-main">+ <span className="chat-mode-select__icon" aria-hidden="true">+ <FileImage className="w-4 h-4" />+ </span>+ <span className="chat-mode-select__label">{t('chat.addImage')}</span>+ </span>+ </button>+ {isAgentMode && onSetGoal && (+ <button+ type="button"+ className="chat-mode-select__option"+ role="menuitem"+ onClick={() => {+ setAttachMenuOpen(false);+ if (activeSessionId) {+ useGoalStore.getState().setArmed(activeSessionId, true);+ }+ }}+ >+ <span className="chat-mode-select__option-main">+ <span className="chat-mode-select__icon" aria-hidden="true">+ <Target className="w-4 h-4" />+ </span>+ <span className="chat-mode-select__label">{t('goal.toolbarTag')}</span>+ </span>+ </button>+ )}+ </div>,+ document.body+ )}+ </div><divref={modeMenuRef}className={clsx(@@ -1625,6 +1773,33 @@ export function InputArea({onRemoveSkill={removeSkillChip}/>}+ {goalTagVisible && (+ <div className="chat-goal-tag">+ <button type="button" className="chat-mode-select__trigger">+ <span className="chat-mode-select__value">+ <span className="chat-mode-select__icon" aria-hidden="true">+ <Target className="w-4 h-4" />+ </span>+ <span className="chat-mode-select__label">{t('goal.toolbarTag')}</span>+ </span>+ </button>+ <button+ type="button"+ className="chat-goal-tag__close"+ title={t('goal.closeTag')}+ onClick={() => {+ if (!activeSessionId) return;+ if (currentGoal) {+ onClearGoal?.(activeSessionId);+ }+ useGoalStore.getState().setArmed(activeSessionId, false);+ }}+ >+ <X size={11} strokeWidth={2.5} />+ </button>+ </div>+ )}+{evolutionLabel && (<div className="chat-input-evolution-pill" title={evolutionLabel}><span className="chat-input-evolution-pill__dot" />diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 53b05953d7..f317348d9a 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -11,6 +11,7 @@ import {Copy,Info,Square,+ Target,Volume2,} from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -26,6 +27,8 @@ import { MediaRenderer } from './MediaRenderer';import { A2UIMessageContent } from '../../features/a2ui/A2UIMessageContent';import { QaSummaryCard } from '../InteractionSlot/QaSummaryCard';import { isQaSummaryContent } from '../InteractionSlot/qaSummary';+import { GoalCompletedCard } from '../GoalBar/GoalCompletedCard';+import { isGoalCompletedContent } from '../GoalBar/goalCompletedMessage';import { a2uiContentToText } from '../../features/a2ui/a2uiContent';import { formatTimestamp, onTtsStop, sanitizeTtsText } from '../../utils';import { useSpeechSynthesis } from '../../hooks';@@ -211,6 +214,8 @@ interface MessageItemProps {autoSpeak?: boolean;showAvatar?: boolean;disableA2UIInteraction?: boolean;+ /** 当前会话的目标文本;message.content 与其完全匹配时显示"设为目标"徽章(纯前端字符串匹配派生,不依赖后端字段) */+ goalObjective?: string | null;}export const MessageItem = memo(function MessageItem({@@ -218,6 +223,7 @@ export const MessageItem = memo(function MessageItem({autoSpeak = false,showAvatar = true,disableA2UIInteraction = false,+ goalObjective,}: MessageItemProps) {const { t } = useTranslation();const {@@ -372,6 +378,11 @@ export const MessageItem = memo(function MessageItem({return <QaSummaryCard content={content} />;}+ // 目标完成回显卡(目标实时跳变到 completed 时前端合成注入)+ if (isGoalCompletedContent(content)) {+ return <GoalCompletedCard content={content} />;+ }+// 系统消息if (role === 'system') {// 检查是否为 chat.session_result 事件@@ -621,7 +632,14 @@ export const MessageItem = memo(function MessageItem({)}><span>{formatTimestamp(timestamp)}</span>-++ {isUser && goalObjective && content === goalObjective && (+ <span className="inline-flex items-center gap-1 rounded-full bg-accent-subtle px-2 py-0.5 text-xs text-accent">+ <Target className="w-3 h-3" strokeWidth={2} />+ {t('goal.badge')}+ </span>+ )}+{showCopy && (<div className="relative">{copied && (diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex 51f5ae2f77..60a68f7970 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx@@ -8,7 +8,7 @@ import { useMemo } from 'react';import { Message, ToolExecution } from '../../types';import { MessageItem, getMessageActor } from './MessageItem';import { ToolGroupDisplay, collectViewedSkillIds } from './ToolGroupDisplay';-import { useChatStore, useSessionStore } from '../../stores';+import { useChatStore, useGoalStore, useSessionStore } from '../../stores';import { isTeamMemberCollaborationMessage } from './teamEventUtils';import { isA2UIClientEventContent } from '../../features/a2ui/a2uiContent';@@ -37,6 +37,8 @@ interface ChatTimelineListProps {executions?: ToolExecution[];mode?: string;disableA2UIInteraction?: boolean;+ /** 当前会话的目标文本,透传给 MessageItem 用于渲染"设为目标"徽章 */+ goalObjective?: string | null;}type TimelineItem =@@ -335,6 +337,7 @@ export function ChatTimelineList({executions = [],mode = 'default',disableA2UIInteraction = false,+ goalObjective = null,}: ChatTimelineListProps) {const isTeamMode = mode === 'team';const renderItems = useMemo(@@ -356,6 +359,7 @@ export function ChatTimelineList({message={item.message}showAvatar={item.showAvatar}disableA2UIInteraction={disableA2UIInteraction}+ goalObjective={goalObjective}/>);}@@ -380,6 +384,7 @@ export function MessageList({ messages }: MessageListProps) {const toolExecutions = useChatStore((s) => s.runtimes[activeSessionId ?? '']?.toolExecutions ?? new Map());const toolExecutionOrder = useChatStore((s) => s.runtimes[activeSessionId ?? '']?.toolExecutionOrder ?? []);const mode = useSessionStore((s) => s.runtimes[activeSessionId ?? '']?.mode ?? 'agent');+ const goalObjective = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.goal?.objective ?? null);const executions = useMemo(() => toolExecutionOrder.map((toolCallId) => toolExecutions.get(toolCallId))@@ -387,5 +392,5 @@ export function MessageList({ messages }: MessageListProps) {[toolExecutions, toolExecutionOrder]);- return <ChatTimelineList messages={messages} executions={executions} mode={mode} />;+ return <ChatTimelineList messages={messages} executions={executions} mode={mode} goalObjective={goalObjective} />;}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex 3093a843b8..e4b4065bd0 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -26,6 +26,7 @@ import restartIcon from '../../assets/restart.svg';import { SubtaskProgress } from './SubtaskProgress';import { InlineQuestionCard } from './InlineQuestionCard';import { InteractionSlot } from '../InteractionSlot';+import { GoalBar } from '../GoalBar';import { HistoryPagerBar } from './HistoryPagerBar';import { HarnessProgressBar } from './HarnessProgressBar';import { AgentTeamActivityCard } from './TeamEventGroupDisplay';@@ -78,6 +79,13 @@ interface ChatPanelProps {onOpenCodeReview?: () => void;permissionsEnabled: boolean;onSavePermission: (updates: Record<string, string>) => Promise<void>;+ /** Goal(持续目标)控制,见 GoalBar 组件 */+ onSetGoal?: (sessionId: string, objective: string) => void;+ onPauseGoal?: (sessionId: string) => void;+ onResumeGoal?: (sessionId: string) => void;+ onClearGoal?: (sessionId: string) => void;+ /** 目标 active 但当前无处理中任务时,消息入队后主动排空一次,见 InputArea.tsx 对应调用点 */+ onDrainTaskQueueIfIdle?: (sessionId: string) => void;}function ThinkingIndicator() {@@ -670,6 +678,11 @@ export function ChatPanel({onOpenCodeReview,permissionsEnabled,onSavePermission,+ onSetGoal,+ onPauseGoal,+ onResumeGoal,+ onClearGoal,+ onDrainTaskQueueIfIdle,}: ChatPanelProps) {const { t } = useTranslation();const activeSessionId = useChatStore((s) => s.activeSessionId);@@ -1103,6 +1116,8 @@ export function ChatPanel({onNavigateToSkills={onNavigateToSkills}permissionsEnabled={permissionsEnabled}onSavePermission={onSavePermission}+ onSetGoal={onSetGoal}+ onClearGoal={onClearGoal}/></div><div className="chat-suggestions">@@ -1122,6 +1137,14 @@ export function ChatPanel({<AgentActivityCard isProcessing={isProcessing} onSendTask={handleSendMessage} /><InterruptResultBubble /><InteractionSlot onSubmit={onUserAnswer} />+ {onSetGoal && onPauseGoal && onResumeGoal && onClearGoal && (+ <GoalBar+ onSetGoal={onSetGoal}+ onPauseGoal={onPauseGoal}+ onResumeGoal={onResumeGoal}+ onClearGoal={onClearGoal}+ />+ )}<InputAreaonSubmit={handleSendMessage}onPersistMedia={onPersistMedia}@@ -1133,6 +1156,9 @@ export function ChatPanel({onNavigateToSkills={onNavigateToSkills}permissionsEnabled={permissionsEnabled}onSavePermission={onSavePermission}+ onSetGoal={onSetGoal}+ onClearGoal={onClearGoal}+ onDrainTaskQueueIfIdle={onDrainTaskQueueIfIdle}/></div>)}diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/EditGoalModal.tsx b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/EditGoalModal.tsxnew file mode 100644index 0000000000..c39e5fa7fe--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/EditGoalModal.tsx@@ -0,0 +1,69 @@+/**+ * 编辑目标 —— 独立弹窗+ *+ * 点击遮罩不关闭,只能通过右上角 × 或"取消"退出(避免误触丢失编辑内容)。+ * 保存复用已有的 command.goal set(overwrite_confirmed: true)语义,不需要新接口。+ */++import { useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';+import { Target, X } from 'lucide-react';++interface EditGoalModalProps {+ initialObjective: string;+ onCancel: () => void;+ onSave: (objective: string) => void;+}++export function EditGoalModal({ initialObjective, onCancel, onSave }: EditGoalModalProps) {+ const { t } = useTranslation();+ const [value, setValue] = useState(initialObjective);+ const canSave = Boolean(value.trim()) && value.trim() !== initialObjective.trim();++ return createPortal(+ <div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/40">+ <div className="relative w-[420px] rounded-2xl border border-border bg-card p-5 shadow-lg">+ <div className="mb-3 flex items-center justify-between">+ <div className="flex h-7 w-7 items-center justify-center rounded-full bg-secondary text-accent">+ <Target size={15} strokeWidth={2} />+ </div>+ <button+ type="button"+ onClick={onCancel}+ aria-label="close"+ className="rounded-md p-1 text-text-muted hover:bg-secondary hover:text-text"+ >+ <X size={16} strokeWidth={2} />+ </button>+ </div>+ <h3 className="mb-3 text-[15px] font-semibold text-text-strong">{t('goal.editTitle')}</h3>+ <textarea+ autoFocus+ className="w-full resize-none rounded-lg border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"+ rows={5}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ />+ <div className="mt-4 flex justify-end gap-2">+ <button+ type="button"+ onClick={onCancel}+ className="rounded-lg border border-border px-4 py-1.5 text-[13px] text-text-muted hover:bg-secondary"+ >+ {t('goal.formCancel')}+ </button>+ <button+ type="button"+ disabled={!canSave}+ onClick={() => onSave(value.trim())}+ className="rounded-lg bg-text-strong px-4 py-1.5 text-[13px] text-card disabled:opacity-50"+ >+ {t('goal.formSubmit')}+ </button>+ </div>+ </div>+ </div>,+ document.body+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.css b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.cssnew file mode 100644index 0000000000..1368af1063--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.css@@ -0,0 +1,159 @@+/* ===========================================================+ GoalBar — 输入框正上方的持续目标吸附条+ 视觉公式照抄 InteractionSlot.css `.interaction-slot--attached` /+ ChatPanel.css `.chat-active-team-group .team-event-group`(同一套"贴合输入框"的+ 吸附条实现,变量全部复用,不新增 token)。+ =========================================================== */++.goal-bar-attached {+ width: calc(100% - 48px);+ margin: 0 auto -1px;+ position: relative;+ z-index: 1;+}++.goal-bar {+ display: flex;+ align-items: center;+ gap: 10px;+ min-height: 44px;+ padding: 9px 18px;+ border: 1px solid var(--color-chat-active-group-border);+ border-radius: 18px 18px 0 0;+ background-color: var(--color-surface-page);+ background-image: linear-gradient(+ rgba(var(--color-chat-composer-surface-rgb), 0.96),+ rgba(var(--color-chat-composer-surface-rgb), 0.96)+ );+ box-shadow: var(--effect-chat-active-group-highlight);+}++/* GoalBar 上方如果还贴着消息队列(.chat-active-team-group)或审批卡片+ (.interaction-slot--attached),说明 GoalBar 不是这摞吸附条的最上面一个,+ 顶部就不该再单独画圆角——否则两个各自独立画圆角的卡片贴合处会露出方形缺口。 */+.chat-active-team-group ~ .goal-bar-attached .goal-bar,+.interaction-slot--attached ~ .goal-bar-attached .goal-bar {+ border-radius: 0;+}++.goal-bar__icon {+ flex: 0 0 auto;+ /* 参照消息队列行图标(.team-event-group-row__avatar)的中性色调,不用强调蓝,+ 避免堆叠在一起时显得突兀——目标是否 active 已经由下面的状态文字颜色表达。 */+ color: var(--color-text-secondary);+}++.goal-bar__main {+ display: flex;+ min-width: 0;+ flex: 1 1 auto;+ align-items: baseline;+ gap: 6px;+ overflow: hidden;+}++.goal-bar__status {+ flex: 0 0 auto;+ font-size: 13px;+ font-weight: 600;+ white-space: nowrap;+}++.goal-bar__status--active { color: var(--color-feedback-info); }+.goal-bar__status--paused { color: var(--color-feedback-warning); }+.goal-bar__status--completed { color: var(--color-feedback-success); }+.goal-bar__status--blocked { color: var(--color-feedback-danger); }++.goal-bar__objective {+ min-width: 0;+ font-size: 13px;+ /* 字重/颜色对齐消息队列行文字(.team-event-group-row__member:font-weight 600 ++ --color-text-strong),两行堆叠在一起时文字观感统一,不再一行粗一行细。 */+ font-weight: 600;+ color: var(--color-text-strong);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.goal-bar__elapsed {+ flex: 0 0 auto;+ font-size: 12px;+ color: var(--color-text-secondary);+}++.goal-bar__actions {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ /* 对齐消息队列行操作按钮组的间距(发送/编辑/删除三个 .chat-input-task-action 之间是 4px) */+ gap: 4px;+}++.goal-bar__action-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ /* 尺寸对齐消息队列行的 .chat-input-task-action(20x20),此前 28x28 明显比队列行的+ 图标按钮大一圈,两行堆叠时右侧按钮组大小不一致、显得割裂。 */+ width: 20px;+ height: 20px;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--color-text-secondary);+ cursor: pointer;+}++.goal-bar__action-btn:hover:not(:disabled) {+ background: var(--color-surface-hover);+ color: var(--color-text-primary);+}++.goal-bar__action-btn:disabled {+ opacity: 0.5;+ cursor: default;+}++.goal-bar__action-btn--danger:hover:not(:disabled) {+ color: var(--color-feedback-danger);+}++/* ===========================+ 目标完成回显卡 GoalCompletedCard+ 结构照抄 InteractionSlot.css 的 .qa-summary,头部改用 success 色系跟 GoalBar 的+ completed 状态色(--color-feedback-success)呼应,跟普通回复气泡明显区分开。+ =========================== */++.goal-completed-card {+ width: 100%;+ max-width: 640px;+ border: 1px solid var(--color-border-default);+ border-radius: 12px;+ background: var(--color-surface-card);+ overflow: hidden;+}++.goal-completed-card__head {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 10px 14px;+ border-bottom: 1px solid var(--color-border-default);+ background-color: rgba(var(--color-feedback-success-rgb), 0.1);+ font-size: 13px;+ font-weight: 600;+ color: var(--color-feedback-success);+}++.goal-completed-card__head-icon {+ color: var(--color-feedback-success);+}++.goal-completed-card__body {+ padding: 12px 14px;+ font-size: 13px;+ color: var(--color-text-secondary);+ line-height: 1.55;+ white-space: pre-wrap;+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalCompletedCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalCompletedCard.tsxnew file mode 100644index 0000000000..821fb15906--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalCompletedCard.tsx@@ -0,0 +1,35 @@+/**+ * GoalCompletedCard — 目标完成回显卡+ *+ * 由 MessageItem 检测到 `goal.completed:` 前缀消息时渲染,展示目标完成时模型自评的完成依据+ * (last_assessment.evidence)。跟普通回复气泡明显区分开,参照 QaSummaryCard 的卡片结构。+ */++import { Target } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { parseGoalCompletedContent } from './goalCompletedMessage';+import './GoalBar.css';++interface GoalCompletedCardProps {+ content: string;+}++export function GoalCompletedCard({ content }: GoalCompletedCardProps) {+ const { t } = useTranslation();+ const data = parseGoalCompletedContent(content);+ if (!data) return null;++ return (+ <div className="flex justify-start mb-3 animate-rise">+ <div className="goal-completed-card">+ <div className="goal-completed-card__head">+ <Target size={14} strokeWidth={2} className="goal-completed-card__head-icon" />+ <span>{t('goal.completedCardTitle')}</span>+ </div>+ <div className="goal-completed-card__body">+ {data.evidence?.trim() || t('goal.completedMessageFallback')}+ </div>+ </div>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/goalCompletedMessage.ts b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/goalCompletedMessage.tsnew file mode 100644index 0000000000..4c2756487e--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/goalCompletedMessage.ts@@ -0,0 +1,33 @@+/**+ * 目标完成「回显卡片」的消息序列化。+ *+ * 目标实时跳变到 completed 时,前端本地合成一条 assistant 消息插入对话流,+ * 内容以 `goal.completed:` 前缀 + JSON 编码。MessageItem 检测到该前缀时渲染+ * GoalCompletedCard。参照 InteractionSlot/qaSummary.ts 的同一套模式。+ */++export const GOAL_COMPLETED_PREFIX = 'goal.completed:';++export interface GoalCompletedData {+ evidence?: string;+}++export function buildGoalCompletedContent(data: GoalCompletedData): string {+ return GOAL_COMPLETED_PREFIX + JSON.stringify(data);+}++export function isGoalCompletedContent(content: string | undefined | null): boolean {+ return typeof content === 'string' && content.startsWith(GOAL_COMPLETED_PREFIX);+}++export function parseGoalCompletedContent(content: string): GoalCompletedData | null {+ if (!isGoalCompletedContent(content)) return null;+ try {+ const raw = content.slice(GOAL_COMPLETED_PREFIX.length);+ const parsed = JSON.parse(raw) as GoalCompletedData;+ if (!parsed || typeof parsed !== 'object') return null;+ return parsed;+ } catch {+ return null;+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsxnew file mode 100644index 0000000000..6002c941b4--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx@@ -0,0 +1,167 @@+/**+ * GoalBar — 持续目标(Goal)吸附条+ *+ * 位置:ChatPanel 的 chat-compose 区域内,InteractionSlot(授权/交互卡)之后、+ * InputArea 之前。视觉上是紧贴输入框的吸附条(参照 InteractionSlot.css+ * `.interaction-slot--attached` / ChatPanel.css `.chat-active-team-group` 共用的公式:+ * `width: calc(100% - 48px); margin: 0 auto -1px;` + `border-radius: 18px 18px 0 0`),+ * 不是独立悬浮卡片。+ *+ * 只在存在 goal 时渲染(不管 goal 是通过 "+" 菜单 armed 流程、还是聊天里直接说明、还是+ * 后端自动识别设置的,只要 goalStore 里有数据就显示——armed 态本身不在这里处理,那是+ * InputArea 工具栏"目标"标签的职责,见 InputArea.tsx)。goal 清除时自动消失。+ *+ * 后端协议:一个 session 同时最多一个 Goal,见+ * cjh/goal/Goal持续目标Web前端对接.md。真机联调受限于后端未实现,见 progress.md 待办清单。+ */++import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Pause, Pencil, Play, Target, Trash2 } from 'lucide-react';+import { useChatStore, useGoalStore } from '../../stores';+import type { GoalStatus } from '../../types';+import { EditGoalModal } from './EditGoalModal';+import './GoalBar.css';++interface GoalBarProps {+ onSetGoal: (sessionId: string, objective: string) => void;+ onPauseGoal: (sessionId: string) => void;+ onResumeGoal: (sessionId: string) => void;+ onClearGoal: (sessionId: string) => void;+}++const STATUS_TONE: Record<string, 'active' | 'paused' | 'completed' | 'blocked'> = {+ active: 'active',+ paused: 'paused',+ completed: 'completed',+ blocked: 'blocked',+};++function formatElapsed(createdAtIso: string | undefined, now: number): string {+ if (!createdAtIso) return '0s';+ const startMs = new Date(createdAtIso).getTime();+ const seconds = Math.max(0, Math.floor((now - startMs) / 1000));+ if (seconds < 60) return `${seconds}s`;+ const minutes = Math.floor(seconds / 60);+ const remainSeconds = seconds % 60;+ return remainSeconds > 0 ? `${minutes}m ${remainSeconds}s` : `${minutes}m`;+}++export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: GoalBarProps) {+ const { t } = useTranslation();+ const activeSessionId = useChatStore((s) => s.activeSessionId);+ const goal = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.goal ?? null);+ const pendingAction = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.pendingAction ?? null);+ // 后端不下发 created_at(backend-requests.md #2),优先用真实值,没有时退回本地兜底时间+ const localCreatedAt = useGoalStore((s) => (goal ? s.localCreatedAt[goal.goal_id] : undefined));+ // completed 目标的 GoalBar 显隐单独用这个标记控制,不再靠 goal 是否存在于 store 里判断——+ // goal 数据本身要一直保留("设为目标"徽章等消费方依赖 goal.objective),见 useWebSocket.ts+ // 的 applyIncomingGoal 注释。+ const bannerHidden = useGoalStore((s) => (goal ? Boolean(s.bannerHiddenGoalIds[goal.goal_id]) : false));+ const [editing, setEditing] = useState(false);+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ // completed/blocked 是终态,不再有新的 attempt,耗时不该继续跳字——冻结在跳变那一刻附近的值+ if (!goal || goal.status === 'completed' || goal.status === 'blocked') return;+ const timer = window.setInterval(() => setNow(Date.now()), 1000);+ return () => window.clearInterval(timer);+ }, [goal]);++ // 编辑弹窗打开期间目标在后台跑完了(用户可能没注意到,弹窗内容也不会自动同步最新状态)——+ // 与其等 4 秒自动隐藏把弹窗连带 GoalBar 一起悄悄拽没(那样用户完全不知道发生了什么,编辑内容+ // 也白写了),不如一发现就主动关掉并提示,避免用户点保存把一个已经结束的目标悄悄"复活"。+ useEffect(() => {+ if (editing && goal?.status === 'completed' && activeSessionId) {+ setEditing(false);+ useChatStore.getState().addMessage(activeSessionId, {+ id: `error-${Date.now()}`,+ role: 'system',+ content: t('goal.editStaleWarning'),+ timestamp: new Date().toISOString(),+ });+ }+ }, [editing, goal?.status, activeSessionId, t]);++ if (!activeSessionId || !goal) return null;+ if (goal.status === 'completed' && bannerHidden) return null;++ const tone = STATUS_TONE[goal.status as GoalStatus] ?? 'active';+ const isPausable = goal.status === 'active';+ const isResumable = goal.status === 'paused' || goal.status === 'blocked';+ const isBusy = pendingAction !== null;++ return (+ <div className="goal-bar-attached">+ <div className={`goal-bar goal-bar--tone-${tone}`}>+ <Target size={16} strokeWidth={2} className="goal-bar__icon" />+ <div className="goal-bar__main">+ <span className={`goal-bar__status goal-bar__status--${tone}`}>+ {t(`goal.status.${goal.status}`, goal.status)}+ </span>+ <span className="goal-bar__objective" title={goal.objective}>+ {goal.objective}+ </span>+ <span className="goal-bar__elapsed">· {formatElapsed(goal.created_at ?? localCreatedAt, now)}</span>+ </div>+ <div className="goal-bar__actions">+ {goal.status !== 'completed' && (+ <button+ type="button"+ title={t('goal.action.editTooltip')}+ className="goal-bar__action-btn"+ onClick={() => setEditing(true)}+ >+ <Pencil size={14} strokeWidth={2} />+ </button>+ )}+ {(isPausable || isResumable) && (+ <button+ type="button"+ title={isPausable ? t('goal.action.pauseTooltip') : t('goal.action.resumeTooltip')}+ className="goal-bar__action-btn"+ disabled={isBusy}+ onClick={() => (isPausable ? onPauseGoal(activeSessionId) : onResumeGoal(activeSessionId))}+ >+ {isPausable ? <Pause size={14} strokeWidth={2} /> : <Play size={14} strokeWidth={2} />}+ </button>+ )}+ <button+ type="button"+ title={t('goal.action.deleteTooltip')}+ className="goal-bar__action-btn goal-bar__action-btn--danger"+ disabled={isBusy}+ onClick={() => onClearGoal(activeSessionId)}+ >+ <Trash2 size={14} strokeWidth={2} />+ </button>+ </div>+ </div>++ {editing && (+ <EditGoalModal+ initialObjective={goal.objective}+ onCancel={() => setEditing(false)}+ onSave={(objective) => {+ // 防御性兜底:正常情况下上面那个 useEffect 会在目标转 completed 的瞬间就关掉弹窗,+ // 这里理论上不会命中,但保存动作本身是不可逆的(会把已完成的目标复活),多一层检查+ // 成本很低。+ const latestGoal = useGoalStore.getState().runtimes[activeSessionId]?.goal;+ if (!latestGoal || latestGoal.goal_id !== goal.goal_id || latestGoal.status === 'completed') {+ setEditing(false);+ useChatStore.getState().addMessage(activeSessionId, {+ id: `error-${Date.now()}`,+ role: 'system',+ content: t('goal.editStaleWarning'),+ timestamp: new Date().toISOString(),+ });+ return;+ }+ onSetGoal(activeSessionId, objective);+ setEditing(false);+ }}+ />+ )}+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts b/jiuwenswarm/channels/web/frontend/src/hooks/index.tsindex ec89dcd9a2..b3f845b3ba 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/index.ts@@ -2,5 +2,5 @@* Hooks 导出*/-export { useWebSocket } from './useWebSocket';+export { useWebSocket, mergePersistedGoalCompletionMessages } from './useWebSocket';export { useSpeechRecognition, useSpeechSynthesis } from './useSpeech';diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 037cada7e0..ddce50d3d3 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -28,18 +28,22 @@ import {ContextCompressionRuntime,ContextCompressionSummary,WsEvent,+ GoalRecord,+ GoalAction,+ Message,} from '../types';import {ensureSessionRuntimes,useChatStore,useTodoStore,+ useGoalStore,useSessionStore,useHarnessStore,useWorkspaceStore,useCronStore,} from '../stores';import type { TeamTask, TeamTaskStatus, TeamTaskUpsert } from '../stores/sessionStore';-import { webClient } from '../services/webClient';+import { webClient, requestGoalAction, sendGoalStreamCommand } from '../services/webClient';import {fetchTtsAudio,playAudioBase64,@@ -53,6 +57,7 @@ import {normalizeToolUpdatePayload,} from '../features/tool-events/toolEventNormalizer';import { findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn } from '../features/teamLeaderMessages';+import { buildGoalCompletedContent } from '../components/GoalBar/goalCompletedMessage';const WS_RECONNECT_EVENT = 'jiuwenclaw:ws-reconnect-request';@@ -68,6 +73,172 @@ function isCompletedResumeResult(interruptResult: unknown): boolean {return result.intent === 'resume' && result.success === true && result.has_active_task === false;}+const GOAL_COMPLETED_AUTO_HIDE_MS = 4000;+const GOAL_COMPLETED_SETTLE_FALLBACK_MS = 8000;++/**+ * 目标完成事件(goal.updated)和它所在这一轮回复的正文(chat.delta/chat.final),走的是两条+ * 独立的推送通道,后端不保证到达顺序——真机复现过 goal.updated 先到、回复气泡还没 flush 进+ * 消息列表的情况,这时候直接插入"目标完成"提示会出现在它引用的那条回复上方,很怪。用+ * isProcessing 变 false(chat.processing_status 事件驱动,标志这一轮真正结束)当"可以展示了"+ * 的信号:当时已经不在 processing 就立即展示;还在 processing 就等它落地。加一个兜底超时,+ * 防止极端情况下 isProcessing 迟迟不落地导致完成提示永远卡住不出现。+ */+function scheduleAfterTurnSettles(sessionId: string, run: () => void): void {+ const isProcessing = useChatStore.getState().getRuntime(sessionId)?.isProcessing ?? false;+ if (!isProcessing) {+ run();+ return;+ }+ let settled = false;+ let fallbackTimer: ReturnType<typeof window.setTimeout>;+ const finish = () => {+ if (settled) return;+ settled = true;+ unsubscribe();+ window.clearTimeout(fallbackTimer);+ run();+ };+ const unsubscribe = useChatStore.subscribe(+ (state) => state.runtimes[sessionId]?.isProcessing ?? false,+ (isProcessing) => {+ if (!isProcessing) finish();+ }+ );+ fallbackTimer = window.setTimeout(finish, GOAL_COMPLETED_SETTLE_FALLBACK_MS);+}++/**+ * goal.snapshot/goal.updated 事件、command.goal 的 RPC 响应,统一落进 goalStore 的入口+ * (被 goalAction 和事件订阅共用,定义成模块级函数而不是 hook 内的 useCallback,避免要把它塞进+ * 那个几乎跑满全文件的大 useEffect 的依赖数组)。处理三件事:+ *+ * 1) created_at 兜底(后端永久不下发,backend-requests.md #2);+ * 2) completed 展示策略——只有"本地在这次页面存活期间亲眼见过这个 goal_id 处于非 completed+ * 状态"才当成实时目睹的跳变:冻结计时、插一条完成消息、展示几秒后本地隐藏(不调用后端+ * clearGoal,后端记录原样保留)。单纯靠 get/事件第一次拿到就已经是 completed(切会话/+ * 刷新页面最常见)一律直接不展示、不插消息——用户没看见"跳变过程",硬展示一条早就完成的+ * 目标条没有意义,还可能重复插消息。+ * 3) 其余状态(active/paused/blocked)照常落状态,不做特殊处理,blocked 也不会自动隐藏。+ */+function applyIncomingGoal(+ sessionId: string,+ goal: GoalRecord | null,+ hideTimerMap: Map<string, ReturnType<typeof window.setTimeout>>+): void {+ const goalStore = useGoalStore.getState();++ if (!goal) {+ const prevGoalId = goalStore.runtimes[sessionId]?.goal?.goal_id;+ if (prevGoalId) {+ goalStore.clearLocalCreatedAt(prevGoalId);+ goalStore.clearGoalCompletionPhase(prevGoalId);+ goalStore.clearBannerHidden(prevGoalId);+ goalStore.clearCompletedGoalMessage(prevGoalId);+ const timer = hideTimerMap.get(prevGoalId);+ if (timer !== undefined) {+ window.clearTimeout(timer);+ hideTimerMap.delete(prevGoalId);+ }+ }+ goalStore.setGoal(sessionId, null);+ goalStore.setPendingAction(sessionId, null);+ return;+ }++ goalStore.setLocalCreatedAt(goal.goal_id, new Date().toISOString());++ if (goal.status !== 'completed') {+ goalStore.markGoalSeenActive(goal.goal_id);+ // 目标曾经 completed 过(编辑复活/其它途径重新进入非 completed 状态)——清掉旧的隐藏标记,+ // 不然它下次再完成时 GoalBar 会因为这个陈旧的 true 直接判定"该隐藏",一秒都不展示就消失。+ goalStore.clearBannerHidden(goal.goal_id);+ goalStore.setGoal(sessionId, goal);+ goalStore.setPendingAction(sessionId, null);+ return;+ }++ const phase = goalStore.getGoalCompletionPhase(goal.goal_id);+ goalStore.setPendingAction(sessionId, null);+ // goal 数据本身(含 objective)永远落进 store,不管是不是要展示 GoalBar——MessageItem 的+ // "设为目标"徽章靠字符串匹配 goal.objective,之前完成态曾经把 goal 整个置 null 来隐藏+ // GoalBar,副作用是刷新页面后连徽章也一起丢了。GoalBar 是否展示改用下面的 hideGoalBanner+ // 单独控制,不再靠 goal 是否存在来判断。+ goalStore.setGoal(sessionId, goal);+ if (phase === 'completed-announced') {+ // 已经宣布/判定过一次了(无论是走过完整跳变流程,还是当初就判定为"发现即完成"),不重复处理+ return;+ }++ const isLiveTransition = phase === 'seen-active';+ goalStore.markGoalCompletedAnnounced(goal.goal_id);++ if (!isLiveTransition) {+ // get/事件第一次拿到就已经是 completed——GoalBar 不展示(用户没看见跳变过程),但 goal+ // 数据保留,徽章匹配等消费方不受影响+ goalStore.hideGoalBanner(goal.goal_id);+ return;+ }++ // 实时目睹的跳变:等这一轮回复正文落地后,再一起展示冻结态 + 完成消息,避免完成提示抢跑到+ // 它引用的那条回复上方。内容用 goal.completed: 前缀 + JSON 编码,MessageItem 检测到后渲染+ // GoalCompletedCard(卡片+头部标签样式),跟普通回复气泡明显区分开。+ scheduleAfterTurnSettles(sessionId, () => {+ const messageId = `goal-completed-${goal.goal_id}`;+ const timestamp = new Date().toISOString();+ const content = buildGoalCompletedContent({ evidence: goal.last_assessment?.evidence?.trim() });+ useChatStore.getState().addMessage(sessionId, {+ id: messageId,+ role: 'assistant',+ content,+ timestamp,+ });+ // 这条消息纯前端合成,从未写进后端 session 历史——刷新页面后 history.get 拉回来的历史里+ // 没有它,会随 replaceHistoryMessages 整体覆盖消失。存一份到 localStorage,历史加载完成后+ // (App.tsx)按时间戳把它插回去,见 mergePersistedGoalCompletionMessages。+ goalStore.recordCompletedGoalMessage({ sessionId, id: messageId, content, timestamp });++ const existingTimer = hideTimerMap.get(goal.goal_id);+ if (existingTimer !== undefined) {+ window.clearTimeout(existingTimer);+ }+ const timer = window.setTimeout(() => {+ hideTimerMap.delete(goal.goal_id);+ const current = useGoalStore.getState().runtimes[sessionId]?.goal;+ // 展示期间用户没有手动清除/编辑目标才自动隐藏,避免和用户的显式操作打架+ if (current?.goal_id === goal.goal_id) {+ useGoalStore.getState().hideGoalBanner(goal.goal_id);+ }+ }, GOAL_COMPLETED_AUTO_HIDE_MS);+ hideTimerMap.set(goal.goal_id, timer);+ });+}++/**+ * 会话历史加载完成后调用:把 localStorage 里持久化的"目标完成"消息(见 applyIncomingGoal 的+ * 实时跳变分支)按时间戳合并回刚加载的历史消息数组里——这些消息从未写进后端 session 历史,+ * 单靠 history.get 的结果永远不会包含它们。已经在 messages 里的(极端情况下未来后端也开始+ * 持久化同 id 的消息)不重复插入。+ */+export function mergePersistedGoalCompletionMessages(sessionId: string, messages: Message[]): Message[] {+ const persisted = useGoalStore.getState().getCompletedGoalMessagesForSession(sessionId);+ if (persisted.length === 0) return messages;+ const existingIds = new Set(messages.map((m) => m.id));+ const missing = persisted.filter((record) => !existingIds.has(record.id));+ if (missing.length === 0) return messages;+ const merged: Message[] = [+ ...messages,+ ...missing.map((record) => ({+ id: record.id,+ role: 'assistant' as const,+ content: record.content,+ timestamp: record.timestamp,+ })),+ ];+ merged.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());+ return merged;+}+function getConnectSignature(options: WebConnectOptions): string {return JSON.stringify({provider: options.provider || '',@@ -328,6 +499,12 @@ interface UseWebSocketReturn {action: 'accept' | 'reject',feedback?: string) => Promise<void>;+ setGoalObjective: (sessionId: string, objective: string) => Promise<void>;+ pauseGoal: (sessionId: string) => Promise<void>;+ resumeGoal: (sessionId: string) => Promise<void>;+ clearGoal: (sessionId: string) => Promise<void>;+ refreshGoal: (sessionId: string) => Promise<void>;+ drainTaskQueueIfIdle: (sessionId: string) => void;getInflightCount: () => number;}@@ -574,6 +751,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const symphonyStatusTargetRef = useRef<Map<string, { messageId: string; baseContent: string }>>(new Map());+ // goal_id -> 本地"完成后自动隐藏"定时器句柄,见 applyIncomingGoal+ const goalCompletedHideTimerRef = useRef<Map<string, ReturnType<typeof window.setTimeout>>>(new Map());const contextCompressionSummaryRef = useRef<Map<string, ContextCompressionSummary>>(new Map());const pendingContextCompressionStartRef =useRef<Map<string, PendingContextCompressionStart>>(new Map());@@ -920,6 +1099,70 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {[request],);+ // Goal(持续目标)控制:get/set/pause/resume/clear 共用一套 loading + 错误处理。+ // get/pause/clear 走非流式一次性响应,真的会有 res,用 requestGoalAction() 正常等待;+ // set/resume 走流式、正常路径上永远不会有 res(见 backend-requests.md #4),改用+ // sendGoalStreamCommand() 发出去就不等,真实状态全靠 goal.snapshot/goal.updated 事件驱动。+ const goalAction = useCallback(+ async (sessionId: string, action: GoalAction | 'get', objective?: string) => {+ ensureSessionRuntimes(sessionId);+ useGoalStore.getState().setPendingAction(sessionId, action === 'get' ? null : action);+ const mode = useSessionStore.getState().getRuntime(sessionId)?.mode ?? 'agent';+ try {+ if (action === 'set' || action === 'resume') {+ await sendGoalStreamCommand({ sessionId, action, objective, mode });+ // 没有数据可落——pendingAction 会在 goal.snapshot/goal.updated 事件到达时清掉+ // (applyGoalSnapshot -> applyIncomingGoal),这里不用管。+ if (action === 'set') {+ // set 是 fire-and-forget,发出去那一刻不知道后端实际接受时目标是什么状态——编辑+ // 一个目标时,前端点保存前的检查只能基于"点击那一刻"的快照,没法完全排除目标在+ // 发送这几百毫秒到几秒内又发生变化的极端情况(用户明确要求的兜底)。发送后主动+ // 补一次 get,不管 goal.snapshot/goal.updated 事件本身有没有到、到得对不对,都用+ // 这次 get 的结果把前端状态收敛回后端权威值一次——即使因为后端还没处理完这次 set+ // 而拿到旧数据也无妨,之后真正的事件到达时会再次覆盖纠正。+ // 注意:不能直接 void goalAction(sessionId, 'get')——那会在第一行把 pendingAction+ // 清成 null(因为它是 'get'),导致 GoalBar 的 loading 态在 set 真正被后端处理完+ // 之前就恢复可点击,留出一个能打出冲突指令的窗口。这里直接调用不碰 pendingAction+ // 的底层请求 + 落状态,让 pendingAction 继续留给 set 对应的 goal.updated 事件清。+ void requestGoalAction({ sessionId, action: 'get', mode })+ .then((goal) => applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current))+ .catch(() => {+ // 静默失败:这只是收敛用的兜底 get,真正的状态最终仍由 goal.updated 事件驱动。+ });+ }+ return;+ }+ const goal = await requestGoalAction({ sessionId, action, mode });+ applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current);+ } catch (error) {+ useGoalStore.getState().setPendingAction(sessionId, null);+ const webError = error as WebError;+ const errorMsg = webError.message || t('network.sendMessageFailed');+ useChatStore.getState().addMessage(sessionId, {+ id: `error-${Date.now()}`,+ role: 'system',+ content: t('network.errorPrefix', { message: errorMsg }),+ timestamp: new Date().toISOString(),+ });+ }+ },+ [t]+ );++ const setGoalObjective = useCallback(+ (sessionId: string, objective: string) => goalAction(sessionId, 'set', objective),+ [goalAction]+ );+ const pauseGoal = useCallback((sessionId: string) => goalAction(sessionId, 'pause'), [goalAction]);+ const resumeGoal = useCallback((sessionId: string) => goalAction(sessionId, 'resume'), [goalAction]);+ const clearGoal = useCallback((sessionId: string) => goalAction(sessionId, 'clear'), [goalAction]);+ /**+ * 会话加载/切换时主动查一次当前 Goal 状态(协议文档 v2 §11 推荐流程第 3 步)——不这样做的话,+ * 刷新页面后 GoalBar 要等下一次 goal.updated 推送才会"自愈"重新出现,目标空闲/paused 时甚至+ * 会一直缺失(2026-07-21 真机联调发现,见 backend-requests.md #1 末尾)。+ */+ const refreshGoal = useCallback((sessionId: string) => goalAction(sessionId, 'get'), [goalAction]);+// 发送聊天消息const sendMessage = useCallback(async (content: string, sessionId: string, mediaItems: MediaItem[] = []): Promise<boolean> => {@@ -1013,6 +1256,9 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {outgoingFiles = persisted.files;}}+ // Goal 处于 active 时,普通输入按文档 §5.1 作为补充约束插入当前 Goal,而不是覆盖它+ const activeGoal = useGoalStore.getState().getRuntime(sessionId)?.goal;+ const inputMode = activeGoal?.status === 'active' ? 'steer' : undefined;await request('chat.send', {session_id: sessionId,content: outgoingContent,@@ -1022,6 +1268,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {...(selectedModel ? { model_name: selectedModel } : {}),...(projectDir ? { project_dir: projectDir } : {}),skills: selectedSkills,+ ...(inputMode ? { input_mode: inputMode } : {}),});return true;} catch (error) {@@ -1103,6 +1350,27 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {sendMessageRef.current = sendMessage;}, [sendMessage]);+ /**+ * 队列非空时主动尝试排空一次,供"入队那一刻本来就没有任务在处理"的场景兜底+ * (典型是目标 active 但当前无聊天在跑时用户发消息——这条消息按设计要走排队,见+ * InputArea.tsx 里 isGoalActive 相关注释,但常规的两处自动排空触发点——+ * chat.processing_status 从 true→false、interrupt_result 完成——都要求"之前在+ * processing",这种场景两个都不会触发,消息会永久卡在队列里,只能靠用户手动点+ * "恢复队列")。isProcessing 为真时直接跳过,交给已有的 processing_status 处理器+ * 在真正空闲下来时接管,不会重复发送。+ */+ const drainTaskQueueIfIdle = useCallback((sessionId: string) => {+ const currentMode = useSessionStore.getState().getRuntime(sessionId)?.mode;+ if (currentMode !== 'agent') return;+ const runtime = useChatStore.getState().getRuntime(sessionId);+ if (runtime?.isProcessing || runtime?.queuePaused) return;+ const nextTask = runtime?.taskQueue[0];+ if (nextTask && sendMessageRef.current) {+ useChatStore.getState().removeFromTaskQueue(sessionId, nextTask.id);+ sendMessageRef.current(nextTask.content, sessionId);+ }+ }, []);+// 统一中断接口 - pause/cancel/supplement/resumeconst interrupt = useCallback(async (@@ -1548,6 +1816,23 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {return Boolean(sessionId && clearedTeamPanelSessionRef.current.has(sessionId));};+ /**+ * goal.snapshot / goal.updated / execution.error(带 goal 字段) 的统一落状态入口。+ * goal 为 null 且 payload 没有顶层 session_id 时(文档 §4.4 第三种返回路径),+ * 只能退化用当前 activeSessionId 兜底——这是文档示例本身没给出 session_id 时的已知限制。+ */+ const applyGoalSnapshot = (payload: Record<string, unknown>) => {+ const goal = (payload.goal ?? null) as GoalRecord | null;+ const sessionId =+ getPayloadSessionId(payload) ||+ goal?.session_id ||+ useChatStore.getState().activeSessionId ||+ undefined;+ if (!sessionId) return;+ ensureSessionRuntimes(sessionId);+ applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current);+ };+const unsubs = [webClient.on('connection.ack', ({ payload }) => {handleConnectionAck(payload);@@ -2085,6 +2370,25 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const todos = Array.isArray(payload.todos) ? payload.todos : [];useTodoStore.getState().setTodos(sessionId, todos as Parameters<ReturnType<typeof useTodoStore.getState>['setTodos']>[1]);}),+ webClient.on('goal.snapshot', ({ payload }) => {+ if (shouldDropDuplicatedEvent('goal.snapshot', payload)) return;+ applyGoalSnapshot(payload);+ }),+ webClient.on('goal.updated', ({ payload }) => {+ if (shouldDropDuplicatedEvent('goal.updated', payload)) return;+ applyGoalSnapshot(payload);+ }),+ webClient.on('runtime.accepted', () => {+ // Goal 的 loading 结束统一以 goal.snapshot 为准(文档 §4 中 set/resume 均先于+ // runtime.accepted 下发 goal.snapshot);这里仅作为通用 ACK 占位,不做任何状态变更,+ // 不当作错误、不重试、不新增消息(文档 §6.1)。+ }),+ webClient.on('execution.error', ({ payload }) => {+ const goal = payload.goal;+ if (goal !== undefined) {+ applyGoalSnapshot(payload);+ }+ }),webClient.on('context.usage', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;@@ -3077,6 +3381,12 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {disconnect,sendUserAnswer,respondActivate,+ setGoalObjective,+ pauseGoal,+ resumeGoal,+ clearGoal,+ refreshGoal,+ drainTaskQueueIfIdle,getInflightCount: () => webClient.getInflightCount(),};}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex df81bdb3aa..a890565395 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -415,6 +415,35 @@"pending": "Pending","completed": "Completed"},+ "goal": {+ "formSubmit": "Confirm",+ "formCancel": "Cancel",+ "editTitle": "Edit goal",+ "toolbarTag": "Goal",+ "closeTag": "Cancel goal",+ "badge": "Set as goal",+ "status": {+ "active": "Active",+ "paused": "Paused",+ "completed": "Completed",+ "blocked": "Blocked"+ },+ "action": {+ "editTooltip": "Edit goal",+ "pauseTooltip": "Pause goal",+ "resumeTooltip": "Resume goal",+ "deleteTooltip": "Delete goal"+ },+ "completedCardTitle": "Goal completed",+ "completedMessageFallback": "Goal completed.",+ "editStaleWarning": "The goal was completed while you were editing it, so this change wasn't saved. Use \"+\" to set a new goal if needed.",+ "detail": {+ "attempts": "Attempts",+ "tokens": "Total tokens",+ "lastAssessment": "Last assessment",+ "lastStopReason": "Last stop reason"+ }+ },"sessions": {"title": "Session Management","subtitle": "Browse and manage sessions and files",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 1d3e8cc1e6..eb30a58462 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -416,6 +416,35 @@"pending": "待处理","completed": "已完成"},+ "goal": {+ "formSubmit": "确定",+ "formCancel": "取消",+ "editTitle": "编辑目标",+ "toolbarTag": "目标",+ "closeTag": "取消目标",+ "badge": "设为目标",+ "status": {+ "active": "进行中",+ "paused": "已暂停",+ "completed": "已完成",+ "blocked": "已阻塞"+ },+ "action": {+ "editTooltip": "编辑目标",+ "pauseTooltip": "暂停目标",+ "resumeTooltip": "恢复目标",+ "deleteTooltip": "删除目标"+ },+ "completedCardTitle": "目标已完成",+ "completedMessageFallback": "目标已完成。",+ "editStaleWarning": "目标在编辑期间已经完成,这次修改未保存。如需设置新目标,请重新通过「+」创建。",+ "detail": {+ "attempts": "已执行次数",+ "tokens": "累计 Token",+ "lastAssessment": "最近评估",+ "lastStopReason": "最近停止原因"+ }+ },"sessions": {"title": "会话管理","subtitle": "浏览并管理会话与文件",diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.tsindex bb43569c5c..fca3dc8d39 100644--- a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts@@ -1,6 +1,7 @@import {ensureSessionRuntimes,useChatStore,+ useGoalStore,useHarnessStore,useSessionStore,useTodoStore,@@ -41,6 +42,7 @@ export function resetNewConversationRuntime(settings: ConversationRuntimeSettinguseSessionStore.getState().removeRuntime(NEW_CONVERSATION_ID);useTodoStore.getState().removeRuntime(NEW_CONVERSATION_ID);useHarnessStore.getState().removeRuntime(NEW_CONVERSATION_ID);+ useGoalStore.getState().removeRuntime(NEW_CONVERSATION_ID);applyRuntimeSettings(NEW_CONVERSATION_ID, settings);if (preservedDraft) {useChatStore.getState().setInputValue(NEW_CONVERSATION_ID, preservedDraft);diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex 13d9b7036f..e7488c175c 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -10,6 +10,7 @@ import {} from '../types';import { getWsBase } from '../utils/env';import i18n from '../i18n';+import { GoalRecord } from '../types/goal';type EventHandler = (event: WsEvent) => void;type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;@@ -259,6 +260,7 @@ class WebClient {id,method,params: params ?? {},+ ...(options.isStream ? { is_stream: true } : {}),};return new Promise<T>((resolve, reject) => {@@ -299,6 +301,41 @@ class WebClient {});}+ /**+ * 发出去就不等了——给那些正常路径上压根不会有 res 的 is_stream 请求用(目前是 command.goal+ * 的 set/resume,见 backend-requests.md #4:process_stream/_chunk_to_message 对每个 chunk+ * 无条件 type="event",没有能产出 res 的分支,连"需要用户确认"这类失败也是走+ * goal.confirm_required 事件)。跟 request() 共用同一套就绪检查(没连上照样立刻抛错,这个+ * 检查本身不依赖等 res),区别只是不注册 pending/不设超时——没有 res 要等,也就没有"超时"+ * 这回事,真实状态全靠调用方自己订阅事件拿。+ */+ async sendFireAndForget(+ method: string,+ params?: Record<string, unknown>,+ options: { isStream?: boolean } = {}+ ): Promise<void> {+ await this.ensureReady();++ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ throw this.createWebError(i18n.t('network.connectionUnavailable'), 'WS_NOT_READY', undefined, true);+ }++ const message: WsRequest = {+ type: 'req',+ id: this.generateRequestId(),+ method,+ params: params ?? {},+ ...(options.isStream ? { is_stream: true } : {}),+ };++ logDevWsTraffic({+ direction: 'outgoing',+ messageType: 'req',+ data: message,+ });+ this.ws.send(JSON.stringify(message));+ }+private async ensureReady(): Promise<void> {if (this.ws?.readyState === WebSocket.OPEN && this.state === 'ready') {return;@@ -523,6 +560,68 @@ export async function webRequest<T = unknown>(return webClient.request<T>(method, params, options);}+interface GoalCommandResponsePayload {+ action?: string;+ message?: string;+ goal?: GoalRecord | null;+ record?: GoalRecord | null;+ cleared_goal?: GoalRecord | null;+ existing_goal?: GoalRecord | null;+ requested_objective?: string | null;+ code?: string | null;+}++/**+ * Goal(持续目标)控制里"有真正 res"的三个一次性动作:get/pause/clear。这三个走的是非流式+ * 一次性响应(interface.py 的 process_message()),正常应该秒回,用默认超时兜底——这里超时+ * 是真的有问题,不是误判。见 cjh/goal/Goal持续目标Web前端对接.md §4。+ * clear 成功后 goal 应视为已清空,不用 cleared_goal 兜底出一个"已清除的目标"。+ */+export async function requestGoalAction(params: {+ sessionId: string;+ action: 'get' | 'pause' | 'clear';+ /** 当前会话模式(如 'agent'),协议文档 v2 §2.1 要求带上,不要写死 'code.normal' */+ mode?: string;+}): Promise<GoalRecord | null> {+ const { sessionId, action, mode } = params;+ const payload = await webRequest<GoalCommandResponsePayload>('command.goal', {+ session_id: sessionId,+ action,+ mode: mode ?? 'agent',+ });+ if (action === 'clear') {+ return null;+ }+ return payload?.goal ?? payload?.record ?? null;+}++/**+ * set/resume:is_stream:true,抢到监听席位后正常路径上永远不会有 res——`process_stream`/+ * `_chunk_to_message`(gateway/message_handler/message_handler.py)对每个 chunk 无条件+ * `type="event"`,没有能产出 res 的分支;连"目标已存在,需要 overwrite_confirmed 确认"这类+ * 失败,协议里对应的也是 `goal.confirm_required` 事件,不是 res(见 backend-requests.md #4)。+ * 所以这两个动作干脆不等 res:发出去就返回,真实状态全靠 goal.snapshot/goal.updated 事件驱动+ * (`useWebSocket.ts` 的 `applyGoalSnapshot`),不再需要一个"等不到就超时"的 Promise。+ */+export async function sendGoalStreamCommand(params: {+ sessionId: string;+ action: 'set' | 'resume';+ objective?: string;+ mode?: string;+}): Promise<void> {+ const { sessionId, action, objective, mode } = params;+ await webClient.sendFireAndForget(+ 'command.goal',+ {+ session_id: sessionId,+ action,+ mode: mode ?? 'agent',+ ...(action === 'set' ? { objective, overwrite_confirmed: true } : {}),+ },+ { isStream: true }+ );+}+// Expose webClient to window for debugging in developmentif (import.meta.env.DEV) {(window as any).webClient = webClient;diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.tsindex 92b64fb715..9d9eee82db 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts@@ -6,6 +6,7 @@*/import { create } from 'zustand';+import { subscribeWithSelector } from 'zustand/middleware';import {Message,ToolCall,@@ -220,7 +221,7 @@ interface ChatState {) => void;}-export const useChatStore = create<ChatState>((set, get) => ({+export const useChatStore = create<ChatState>()(subscribeWithSelector((set, get) => ({runtimes: {},activeSessionId: null,globalTaskRunning: false,@@ -1263,4 +1264,4 @@ export const useChatStore = create<ChatState>((set, get) => ({};});},-}));+})));diff --git a/jiuwenswarm/channels/web/frontend/src/stores/ensureSessionRuntimes.ts b/jiuwenswarm/channels/web/frontend/src/stores/ensureSessionRuntimes.tsindex 666ab7acf8..100c9e34ef 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/ensureSessionRuntimes.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/ensureSessionRuntimes.ts@@ -1,4 +1,5 @@import { useChatStore } from './chatStore';+import { useGoalStore } from './goalStore';import { useHarnessStore } from './harnessStore';import { useSessionStore } from './sessionStore';import { useTodoStore } from './todoStore';@@ -8,4 +9,5 @@ export function ensureSessionRuntimes(sessionId: string): void {useSessionStore.getState().ensureRuntime(sessionId);useTodoStore.getState().ensureRuntime(sessionId);useHarnessStore.getState().ensureRuntime(sessionId);+ useGoalStore.getState().ensureRuntime(sessionId);}diff --git a/jiuwenswarm/channels/web/frontend/src/stores/goalStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/goalStore.tsnew file mode 100644index 0000000000..3b7b787ca9--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/stores/goalStore.ts@@ -0,0 +1,318 @@+/**+ * Goal(持续目标)状态管理(多 session 版本)+ *+ * 按 session 隔离存储在 runtimes 中,语义参照 todoStore.ts。+ */++import { create } from 'zustand';+import { GoalAction, GoalRecord } from '../types';++interface GoalRuntime {+ goal: GoalRecord | null;+ /** 当前正在等待响应的操作,用于按钮 loading;收到 goal.snapshot 或 runtime.accepted 后清空 */+ pendingAction: GoalAction | null;+ /**+ * "+" 菜单选了「目标」、还没发送确认时的过渡态;和 goal 是否存在是两回事。+ * InputArea.tsx 的工具栏「目标」tag 只跟这个字段挂钩(不跟 goal 是否存在 OR),发送后归 false+ * tag 就该消失——目标存在时的展示/控制已经由 GoalBar 常驻覆盖,不需要工具栏再重复一份。+ */+ armed: boolean;+}++function createEmptyRuntime(): GoalRuntime {+ return { goal: null, pendingAction: null, armed: false };+}++/**+ * goal_id -> 前端本地兜底的创建时间(ISO 字符串),持久化进 localStorage。+ *+ * 后端 GoalRecord 已确认永久不含 created_at/updated_at(协议文档 v2、backend-requests.md #2),+ * GoalBar 的实时计时器完全没有真实创建时间可用。这里在"前端第一次看到某个 goal_id"的那一刻+ * (set 请求发出时最精确;get/goal.snapshot/goal.updated 发现已存在的目标时次精确)记一份本地+ * 时间落进 localStorage,跨刷新/关标签页都还在——不是内存态,满足"不能刷新后就不见了"的要求。+ * 代价:这终究是前端观测到的时间,不是目标真实创建时间;如果目标是在这次浏览器打开之前、+ * 由别的客户端/别的 session 创建的,第一次拿到时已经晚于真实创建时刻,计时会偏短。这是纯前端+ * 方案能做到的最好近似,真正精确解只能等后端补 created_at。+ */+const LOCAL_CREATED_AT_STORAGE_KEY = 'jiuwenswarm.goal.localCreatedAt.v1';+const LOCAL_CREATED_AT_MAX_ENTRIES = 100;++function loadLocalCreatedAtFromStorage(): Record<string, string> {+ try {+ const raw = window.localStorage.getItem(LOCAL_CREATED_AT_STORAGE_KEY);+ if (!raw) return {};+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return {};+ return parsed as Record<string, string>;+ } catch {+ return {};+ }+}++function saveLocalCreatedAtToStorage(map: Record<string, string>): void {+ try {+ const entries = Object.entries(map);+ // 超出上限时丢最早的记录(按 ISO 时间字符串排序即时间顺序),避免 localStorage 无限增长。+ const trimmed =+ entries.length > LOCAL_CREATED_AT_MAX_ENTRIES+ ? entries.sort((a, b) => a[1].localeCompare(b[1])).slice(entries.length - LOCAL_CREATED_AT_MAX_ENTRIES)+ : entries;+ window.localStorage.setItem(LOCAL_CREATED_AT_STORAGE_KEY, JSON.stringify(Object.fromEntries(trimmed)));+ } catch {+ // localStorage 不可用(隐私模式/配额满)时静默降级为纯内存态,不影响主流程。+ }+}++/**+ * goal_id -> 本次页面存活期间观测到的完成态展示阶段,纯内存态、不落 localStorage。+ *+ * 'seen-active':本地曾经亲眼见过这个 goal_id 处于非 completed 状态(active/paused/blocked),+ * 之后再收到它变成 completed,判定为"实时目睹的跳变"——GoalBar 冻结计时 + 插一条完成消息 ++ * 展示几秒后本地隐藏。+ * 'completed-announced':已经宣布过完成(无论是走上面的跳变流程,还是压根没见过 active 状态、+ * 一上来 get/事件拿到的就已经是 completed)——之后同一个 goal_id 再出现,一律不再展示、不再+ * 重复插消息。+ *+ * 不持久化是有意为之:刷新页面/重新打开标签页后这份记忆天然清空,此时如果目标已经是 completed,+ * 会被当成"没见过 active 状态"直接判 completed-announced(静默不展示)——这正是想要的效果,+ * 避免刷新后一个早就完成的目标条又冒出来晃一下。+ */+type GoalCompletionPhase = 'seen-active' | 'completed-announced';++/**+ * goal_id -> "目标完成"这条系统消息的持久化记录,落 localStorage,跨刷新还在。+ *+ * 之前 completed 目标的展示逻辑是靠把 `runtimes[sessionId].goal` 整个置 null 来隐藏 GoalBar,+ * 副作用是连 `goal.objective` 也一起丢了——依赖它做字符串匹配的"设为目标"徽章+ * (`MessageItem.tsx` 的 `goalObjective` 逐字匹配)刷新后就跟着消失了。改成用+ * `bannerHiddenGoalIds`(见下)单独控制 GoalBar 显隐,`goal` 本身永远保留真实数据。+ *+ * 这份记录还有第二个用途:`goal.snapshot`/`goal.updated` 到达时插入聊天记录的那条"目标已完成"+ * 消息,只存在于内存态的 `chatStore` 里,从来没写进后端 session 历史——页面刷新后+ * `history.get` 拉回来的历史里根本没有这条消息,`replaceHistoryMessages` 整体覆盖后就凭空+ * 消失了。这里把消息内容也存一份到 localStorage,历史加载完成后(`App.tsx`)用+ * `getCompletedGoalMessagesForSession` 把还没出现在新加载历史里的记录按时间戳插回去。+ */+interface CompletedGoalMessageRecord {+ sessionId: string;+ id: string;+ content: string;+ timestamp: string;+}++const COMPLETED_GOAL_MESSAGES_STORAGE_KEY = 'jiuwenswarm.goal.completedMessages.v1';+const COMPLETED_GOAL_MESSAGES_MAX_ENTRIES = 50;++function loadCompletedGoalMessagesFromStorage(): Record<string, CompletedGoalMessageRecord> {+ try {+ const raw = window.localStorage.getItem(COMPLETED_GOAL_MESSAGES_STORAGE_KEY);+ if (!raw) return {};+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return {};+ return parsed as Record<string, CompletedGoalMessageRecord>;+ } catch {+ return {};+ }+}++function saveCompletedGoalMessagesToStorage(map: Record<string, CompletedGoalMessageRecord>): void {+ try {+ const entries = Object.entries(map);+ const trimmed =+ entries.length > COMPLETED_GOAL_MESSAGES_MAX_ENTRIES+ ? entries+ .sort((a, b) => a[1].timestamp.localeCompare(b[1].timestamp))+ .slice(entries.length - COMPLETED_GOAL_MESSAGES_MAX_ENTRIES)+ : entries;+ window.localStorage.setItem(COMPLETED_GOAL_MESSAGES_STORAGE_KEY, JSON.stringify(Object.fromEntries(trimmed)));+ } catch {+ // localStorage 不可用时静默降级:这条完成消息刷新后就找不回来了,但不影响主流程。+ }+}++interface GoalState {+ runtimes: Record<string, GoalRuntime>;+ localCreatedAt: Record<string, string>;+ goalCompletionPhase: Record<string, GoalCompletionPhase>;+ /** completed 目标的 GoalBar 是否已经隐藏(跟 goal 数据是否还在 store 里是两回事,见上方注释) */+ bannerHiddenGoalIds: Record<string, true>;+ completedGoalMessages: Record<string, CompletedGoalMessageRecord>;++ ensureRuntime: (sessionId: string) => GoalRuntime;+ getRuntime: (sessionId: string | null) => GoalRuntime | undefined;+ removeRuntime: (sessionId: string) => void;++ setGoal: (sessionId: string, goal: GoalRecord | null) => void;+ setPendingAction: (sessionId: string, action: GoalAction | null) => void;+ setArmed: (sessionId: string, armed: boolean) => void;+ /** 只在该 goal_id 还没有记录时才写入,避免编辑目标(同 goal_id 的 set 覆盖)时把计时重置 */+ setLocalCreatedAt: (goalId: string, iso: string) => void;+ /** 目标被清除时调用,避免 localStorage 里堆积再也用不到的 goal_id */+ clearLocalCreatedAt: (goalId: string) => void;++ markGoalSeenActive: (goalId: string) => void;+ markGoalCompletedAnnounced: (goalId: string) => void;+ getGoalCompletionPhase: (goalId: string) => GoalCompletionPhase | undefined;+ clearGoalCompletionPhase: (goalId: string) => void;++ hideGoalBanner: (goalId: string) => void;+ clearBannerHidden: (goalId: string) => void;++ recordCompletedGoalMessage: (record: CompletedGoalMessageRecord) => void;+ getCompletedGoalMessagesForSession: (sessionId: string) => CompletedGoalMessageRecord[];+ clearCompletedGoalMessage: (goalId: string) => void;+}++export const useGoalStore = create<GoalState>((set, get) => ({+ runtimes: {},+ localCreatedAt: loadLocalCreatedAtFromStorage(),+ goalCompletionPhase: {},+ bannerHiddenGoalIds: {},+ completedGoalMessages: loadCompletedGoalMessagesFromStorage(),++ ensureRuntime: (sessionId) => {+ const existing = get().runtimes[sessionId];+ if (existing) return existing;+ const runtime = createEmptyRuntime();+ set((state) => ({+ runtimes: { ...state.runtimes, [sessionId]: runtime },+ }));+ return runtime;+ },++ getRuntime: (sessionId) => {+ if (!sessionId) return undefined;+ return get().runtimes[sessionId];+ },++ removeRuntime: (sessionId) => {+ set((state) => {+ const next = { ...state.runtimes };+ delete next[sessionId];+ return { runtimes: next };+ });+ },++ setGoal: (sessionId, goal) => {+ set((state) => {+ const runtime = state.runtimes[sessionId] ?? createEmptyRuntime();+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, goal },+ },+ };+ });+ },++ setPendingAction: (sessionId, action) => {+ set((state) => {+ const runtime = state.runtimes[sessionId] ?? createEmptyRuntime();+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, pendingAction: action },+ },+ };+ });+ },++ setArmed: (sessionId, armed) => {+ set((state) => {+ const runtime = state.runtimes[sessionId] ?? createEmptyRuntime();+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, armed },+ },+ };+ });+ },++ setLocalCreatedAt: (goalId, iso) => {+ set((state) => {+ if (state.localCreatedAt[goalId]) return state;+ const next = { ...state.localCreatedAt, [goalId]: iso };+ saveLocalCreatedAtToStorage(next);+ return { localCreatedAt: next };+ });+ },++ clearLocalCreatedAt: (goalId) => {+ set((state) => {+ if (!(goalId in state.localCreatedAt)) return state;+ const next = { ...state.localCreatedAt };+ delete next[goalId];+ saveLocalCreatedAtToStorage(next);+ return { localCreatedAt: next };+ });+ },++ markGoalSeenActive: (goalId) => {+ set((state) => {+ if (state.goalCompletionPhase[goalId] === 'seen-active') return state;+ // 曾经以为"completed-announced 之后不该再倒回 seen-active,业务上不会从 completed 变回+ // active"——是错的:编辑一个刚完成的目标会把它复活成新一轮 active(哪怕后端换了新+ // goal_id,也可能复用同一个),这里必须允许倒回,否则这个 goal_id 之后再完成一次时会被+ // 误判成"已经宣布过",直接静默跳过,不出完成提示、GoalBar 也不会展示——参见+ // useWebSocket.ts 的 applyIncomingGoal,配合 bannerHiddenGoalIds 也会同步清掉。+ return { goalCompletionPhase: { ...state.goalCompletionPhase, [goalId]: 'seen-active' } };+ });+ },++ markGoalCompletedAnnounced: (goalId) => {+ set((state) => {+ if (state.goalCompletionPhase[goalId] === 'completed-announced') return state;+ return { goalCompletionPhase: { ...state.goalCompletionPhase, [goalId]: 'completed-announced' } };+ });+ },++ getGoalCompletionPhase: (goalId) => get().goalCompletionPhase[goalId],++ clearGoalCompletionPhase: (goalId) => {+ set((state) => {+ if (!(goalId in state.goalCompletionPhase)) return state;+ const next = { ...state.goalCompletionPhase };+ delete next[goalId];+ return { goalCompletionPhase: next };+ });+ },++ hideGoalBanner: (goalId) => {+ set((state) => {+ if (state.bannerHiddenGoalIds[goalId]) return state;+ return { bannerHiddenGoalIds: { ...state.bannerHiddenGoalIds, [goalId]: true } };+ });+ },++ clearBannerHidden: (goalId) => {+ set((state) => {+ if (!(goalId in state.bannerHiddenGoalIds)) return state;+ const next = { ...state.bannerHiddenGoalIds };+ delete next[goalId];+ return { bannerHiddenGoalIds: next };+ });+ },++ recordCompletedGoalMessage: (record) => {+ set((state) => {+ const next = { ...state.completedGoalMessages, [record.id]: record };+ saveCompletedGoalMessagesToStorage(next);+ return { completedGoalMessages: next };+ });+ },++ getCompletedGoalMessagesForSession: (sessionId) =>+ Object.values(get().completedGoalMessages).filter((record) => record.sessionId === sessionId),++ clearCompletedGoalMessage: (goalId) => {+ set((state) => {+ const messageId = `goal-completed-${goalId}`;+ if (!(messageId in state.completedGoalMessages)) return state;+ const next = { ...state.completedGoalMessages };+ delete next[messageId];+ saveCompletedGoalMessagesToStorage(next);+ return { completedGoalMessages: next };+ });+ },+}));diff --git a/jiuwenswarm/channels/web/frontend/src/stores/index.ts b/jiuwenswarm/channels/web/frontend/src/stores/index.tsindex e8d3a45927..de398b8f47 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/index.ts@@ -4,6 +4,7 @@export { useChatStore } from './chatStore';export { useTodoStore } from './todoStore';+export { useGoalStore } from './goalStore';export { useSessionStore } from './sessionStore';export { PROJECT_SESSION_PAGE_SIZE, useWorkspaceStore } from './workspaceStore';export { useHarnessStore } from './harnessStore';diff --git a/jiuwenswarm/channels/web/frontend/src/types/goal.ts b/jiuwenswarm/channels/web/frontend/src/types/goal.tsnew file mode 100644index 0000000000..5ee79194be--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/types/goal.ts@@ -0,0 +1,41 @@+/**+ * Goal(持续目标)类型定义+ *+ * 对应后端 GoalRecord.to_dict(),见 cjh/goal/Goal持续目标Web前端对接.md+ */++export type GoalStatus = 'active' | 'paused' | 'completed' | 'blocked' | string;++export interface GoalTokenUsage {+ input_tokens: number;+ output_tokens: number;+ cached_input_tokens: number;+ total_tokens: number;+}++// 对应后端 GoalAssessment.to_dict()(openjiuwen/harness/goal/schema.py),真机报文已核实是+// 结构化对象而不是纯字符串,见 progress.md 2026-07-21 真机验证记录。+export interface GoalAssessment {+ status: 'continue' | 'complete' | 'blocked' | string;+ evidence: string;+ remaining_work?: string | null;+ next_instruction?: string | null;+}++export interface GoalRecord {+ goal_id: string;+ session_id: string;+ objective: string;+ status: GoalStatus;+ revision: number;+ attempt_count: number;+ created_at?: string;+ updated_at?: string;+ token_usage?: GoalTokenUsage;+ max_attempts?: number | null;+ token_budget?: number | null;+ last_assessment?: GoalAssessment | null;+ last_stop_reason?: string | null;+}++export type GoalAction = 'set' | 'pause' | 'resume' | 'clear';diff --git a/jiuwenswarm/channels/web/frontend/src/types/index.ts b/jiuwenswarm/channels/web/frontend/src/types/index.tsindex d40c05a940..e0b3ae6c26 100644--- a/jiuwenswarm/channels/web/frontend/src/types/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/index.ts@@ -2,6 +2,7 @@* 类型导出*/+export * from './goal';export * from './message';export * from './skillTree';export * from './beamSearch';diff --git a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts b/jiuwenswarm/channels/web/frontend/src/types/websocket.tsindex cf29468e11..e57ff4a81a 100644--- a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts@@ -14,6 +14,7 @@ export interface WsRequest {id: string;method: string;params?: Record<string, unknown>;+ is_stream?: boolean;}export interface WsResponse {@@ -38,6 +39,8 @@ export type WebMessage = WsRequest | WsResponse | WsEvent;export interface WebRequestOptions {timeoutMs?: number;signal?: AbortSignal;+ /** 对应协议里请求消息的顶层 is_stream 字段(如 command.goal 的 set/resume) */+ isStream?: boolean;}export interface WebConnectOptions {