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_jinduoxia6f347094e0b9
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex afa80f3bc7..9d77c05b83 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -40,7 +40,7 @@ import {normalizeToolCallPayload,normalizeToolResultPayload,} from './features/tool-events/toolEventNormalizer';-import { useWebSocket, mergePersistedGoalCompletionMessages } from './hooks';+import { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } from './hooks';import { webRequest } from './services/webClient';import { useTeamPanelState } from './features/teamPanelState';import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session } from './types';@@ -1308,7 +1308,12 @@ function AppContent() {// "目标完成"回显消息纯前端合成,从未写进后端 session 历史,history.get 拉回来的// messages 里不会有它——按时间戳把本地持久化的记录补回去,见// hooks/useWebSocket.ts 的 applyIncomingGoal/mergePersistedGoalCompletionMessages。- replaceHistoryMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, messages));+ // 同时给命中"曾经设置过目标"的 user 消息回填 isGoalObjectiveMessage 徽章标记,+ // 见 stampGoalObjectiveMessages。+ replaceHistoryMessages(+ sessionId,+ stampGoalObjectiveMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, messages))+ );const restoredTotalPages = totalPages ?? 1;setHistoryPagerMeta(sessionId, {loadedPages: 1,@@ -1622,6 +1627,7 @@ function AppContent() {role: 'user',content,timestamp: new Date().toISOString(),+ isGoalObjectiveMessage: true,});setGoalObjective(newSid, content);} else {@@ -1686,8 +1692,12 @@ function AppContent() {const handleCancel = useCallback(() => {const currentSessionId = sessionIdRef.current;if (!currentSessionId || currentSessionId === NEW_CONVERSATION_ID) return;+ // 目标是否 active 决定停止按钮要不要顺带把目标转为 paused——约定行为:其它状态+ // (paused/blocked/completed/无目标)下,停止只结束会话,不碰目标本身。+ const isGoalActive = useGoalStore.getState().runtimes[currentSessionId]?.goal?.status === 'active';if (mode === 'team') {void pause(currentSessionId);+ if (isGoalActive) void pauseGoal(currentSessionId);return;}// agent 模式下有队列任务时,暂停队列自动发送@@ -1698,7 +1708,28 @@ function AppContent() {}}void cancel(currentSessionId);- }, [cancel, mode, pause]);+ if (isGoalActive) void pauseGoal(currentSessionId);+ }, [cancel, mode, pause, pauseGoal]);++ /**+ * 删除目标:active 时除了清目标,还要顺带结束当前会话输出——复用停止按钮同一套中断调用+ * (team 走 pause、其余走 cancel)。先清目标再补发中断,避免目标还没清掉那个空档被+ * "ACTIVE 目标保持交互打开"的后端逻辑又续上一轮。非 active 状态下只清目标,不打断当前+ * 会话(如果还有一轮在自然跑完,让它继续)。+ */+ const handleClearGoal = useCallback(+ (sessionId: string) => {+ const isGoalActive = useGoalStore.getState().runtimes[sessionId]?.goal?.status === 'active';+ void clearGoal(sessionId);+ if (!isGoalActive) return;+ if (mode === 'team') {+ void pause(sessionId);+ } else {+ void cancel(sessionId);+ }+ },+ [cancel, clearGoal, mode, pause]+ );const handleUserAnswer = useCallback((requestId: string, answers: UserAnswer[], source?: string) => {const currentSessionId = sessionIdRef.current;@@ -2067,7 +2098,7 @@ function AppContent() {onSetGoal={setGoalObjective}onPauseGoal={pauseGoal}onResumeGoal={resumeGoal}- onClearGoal={clearGoal}+ onClearGoal={handleClearGoal}onDrainTaskQueueIfIdle={drainTaskQueueIfIdle}/></div>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex 2b663aaa79..6278d21292 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -1391,6 +1391,21 @@ overflow: hidden;color: var(--color-text-strong);}+.chat-mode-select__option:disabled {+ color: var(--color-text-placeholder);+ cursor: not-allowed;+}++.chat-mode-select__option:disabled:hover,+.chat-mode-select__option:disabled:focus-visible {+ background: transparent;+ color: var(--color-text-placeholder);+}++.chat-mode-select__option:disabled .chat-mode-select__icon {+ color: var(--color-text-placeholder);+}+/* Trigger turns red when full_access is selected */.chat-mode-select__trigger--danger,.chat-mode-select__trigger--danger .chat-mode-select__icon {diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsxindex fd519c22f1..4333e07550 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InputArea.tsx@@ -317,6 +317,8 @@ export function InputArea({// 用户明确要求改成这个语义(steer 目前收不到任何反馈,体验上等同于消息发出去石沉大海,// 见 backend-requests.md #1)。走排队后消息复用现有的通用队列机制,行为和普通排队一致。const isGoalActive = currentGoal?.status === 'active';+ // 未完成目标:active/paused/blocked 都算,只有 completed(或没有目标)才能再设新目标+ const hasUnfinishedGoal = currentGoal != null && currentGoal.status !== 'completed';const isInterruptible = isProcessing || isPaused || isGoalActive;const isAgentMode = mode === 'agent';const isTeamMode = mode === 'team';@@ -433,6 +435,9 @@ export function InputArea({});const imageInputDisabled = isListening || (isInterruptible && !isTeamMode);+ // "+" 触发按钮本身不跟图片/目标的可用性挂钩:菜单以后可能挂其他跟图片/目标无关的功能,+ // 触发按钮只要不在录音就该能点开;具体某一项能不能选,交给菜单里每一项各自的禁用态处理。+ const attachTriggerDisabled = isListening;const readyAttachments = useMemo(() => attachments.filter((attachment) => attachment.status === 'ready' && attachment.base64Data),[attachments],@@ -816,6 +821,7 @@ export function InputArea({role: 'user',content: trimmed,timestamp: new Date().toISOString(),+ isGoalObjectiveMessage: true,});useGoalStore.getState().setArmed(sid, false);onSetGoal(sid, trimmed);@@ -1564,19 +1570,19 @@ export function InputArea({<buttontype="button"onClick={() => {- if (imageInputDisabled) return;+ if (attachTriggerDisabled) return;if (!attachMenuOpen && attachMenuRef.current) {setAttachMenuAnchor(attachMenuRef.current.getBoundingClientRect());}setAttachMenuOpen((open) => !open);}}- disabled={imageInputDisabled}+ disabled={attachTriggerDisabled}className={cx('chat-input-btn chat-input-btn--add-file',- imageInputDisabled && 'chat-input-btn--disabled',+ attachTriggerDisabled && 'chat-input-btn--disabled',)}- title={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}- aria-label={imageInputDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ title={attachTriggerDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}+ aria-label={attachTriggerDisabled ? t('chat.addImageDisabled') : t('chat.addImage')}aria-haspopup="menu"aria-expanded={attachMenuOpen}>@@ -1615,7 +1621,10 @@ export function InputArea({type="button"className="chat-mode-select__option"role="menuitem"+ disabled={imageInputDisabled}+ title={imageInputDisabled ? t('chat.addImageDisabled') : undefined}onClick={() => {+ if (imageInputDisabled) return;setAttachMenuOpen(false);fileInputRef.current?.click();}}@@ -1632,7 +1641,10 @@ export function InputArea({type="button"className="chat-mode-select__option"role="menuitem"+ disabled={hasUnfinishedGoal}+ title={hasUnfinishedGoal ? t('goal.toolbarUnavailable') : undefined}onClick={() => {+ if (hasUnfinishedGoal) return;setAttachMenuOpen(false);if (activeSessionId) {useGoalStore.getState().setArmed(activeSessionId, true);diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex f317348d9a..527b565e8a 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -214,8 +214,6 @@ interface MessageItemProps {autoSpeak?: boolean;showAvatar?: boolean;disableA2UIInteraction?: boolean;- /** 当前会话的目标文本;message.content 与其完全匹配时显示"设为目标"徽章(纯前端字符串匹配派生,不依赖后端字段) */- goalObjective?: string | null;}export const MessageItem = memo(function MessageItem({@@ -223,7 +221,6 @@ export const MessageItem = memo(function MessageItem({autoSpeak = false,showAvatar = true,disableA2UIInteraction = false,- goalObjective,}: MessageItemProps) {const { t } = useTranslation();const {@@ -238,6 +235,7 @@ export const MessageItem = memo(function MessageItem({audioMime,mediaItems,fileItems,+ isGoalObjectiveMessage,} = message;const [hasAutoSpoken, setHasAutoSpoken] = useState(false);const [isAudioPlaying, setIsAudioPlaying] = useState(false);@@ -633,8 +631,8 @@ 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">+ {isUser && isGoalObjectiveMessage && (+ <span className="inline-flex items-center gap-1 rounded-full bg-secondary px-2 py-0.5 text-xs text-text-muted"><Target className="w-3 h-3" strokeWidth={2} />{t('goal.badge')}</span>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex a9df9ead07..791e7f6755 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 { Fragment, useMemo, type ReactNode } from 'react';import { Message, ToolExecution } from '../../types';import { MessageItem, getMessageActor } from './MessageItem';import { ToolGroupDisplay, collectViewedSkillIds } from './ToolGroupDisplay';-import { useChatStore, useGoalStore, useSessionStore } from '../../stores';+import { useChatStore, useSessionStore } from '../../stores';import { isTeamMemberCollaborationMessage } from './teamEventUtils';import { isA2UIClientEventContent } from '../../features/a2ui/a2uiContent';@@ -38,8 +38,6 @@ interface ChatTimelineListProps {executions?: ToolExecution[];mode?: string;disableA2UIInteraction?: boolean;- /** 当前会话的目标文本,透传给 MessageItem 用于渲染"设为目标"徽章 */- goalObjective?: string | null;renderAfterMessage?: (message: Message) => ReactNode;}@@ -339,7 +337,6 @@ export function ChatTimelineList({executions = [],mode = 'default',disableA2UIInteraction = false,- goalObjective = null,renderAfterMessage,}: ChatTimelineListProps) {const isTeamMode = mode === 'team';@@ -362,7 +359,6 @@ export function ChatTimelineList({message={item.message}showAvatar={item.showAvatar}disableA2UIInteraction={disableA2UIInteraction}- goalObjective={goalObjective}/>{renderAfterMessage?.(item.message)}</Fragment>@@ -389,7 +385,6 @@ export function MessageList({ messages, renderAfterMessage }: 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))@@ -402,7 +397,6 @@ export function MessageList({ messages, renderAfterMessage }: MessageListProps)messages={messages}executions={executions}mode={mode}- goalObjective={goalObjective}renderAfterMessage={renderAfterMessage}/>);diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.css b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.cssindex 1368af1063..9532e22f39 100644--- a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.css+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/GoalBar.css@@ -63,6 +63,10 @@.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); }+/* disconnected/unknown 是前端专属展示态(真实环境联调方案),用中性色区分于 blocked 的+ danger 色——断联/查询失败不是"目标出错了",不该带上出错的观感。 */+.goal-bar__status--disconnected { color: var(--color-text-secondary); }+.goal-bar__status--unknown { color: var(--color-text-secondary); }.goal-bar__objective {min-width: 0;diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsxindex 6002c941b4..86cdf18cb9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx@@ -18,7 +18,7 @@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 { useChatStore, useGoalStore, useSessionStore } from '../../stores';import type { GoalStatus } from '../../types';import { EditGoalModal } from './EditGoalModal';import './GoalBar.css';@@ -30,7 +30,10 @@ interface GoalBarProps {onClearGoal: (sessionId: string) => void;}-const STATUS_TONE: Record<string, 'active' | 'paused' | 'completed' | 'blocked'> = {+/** disconnected/unknown 是纯前端展示态,跟后端 goal.status 无关,见真实环境联调方案。 */+type DisplayTone = 'active' | 'paused' | 'completed' | 'blocked' | 'disconnected' | 'unknown';++const STATUS_TONE: Record<string, DisplayTone> = {active: 'active',paused: 'paused',completed: 'completed',@@ -52,6 +55,10 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: Gconst activeSessionId = useChatStore((s) => s.activeSessionId);const goal = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.goal ?? null);const pendingAction = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.pendingAction ?? null);+ const queryStatus = useGoalStore((s) => s.runtimes[activeSessionId ?? '']?.queryStatus ?? 'ok');+ // 前后端连接是否正常,复用 webClient 原生 WS 状态机的镜像(不是心跳消息判断,见真实环境+ // 联调方案)——跟专门播报 agent 心跳的 HeartbeatPanel/connection.heartbeat 是两回事。+ const isConnected = useSessionStore((s) => s.isConnected);// 后端不下发 created_at(backend-requests.md #2),优先用真实值,没有时退回本地兜底时间const localCreatedAt = useGoalStore((s) => (goal ? s.localCreatedAt[goal.goal_id] : undefined));// completed 目标的 GoalBar 显隐单独用这个标记控制,不再靠 goal 是否存在于 store 里判断——@@ -60,6 +67,10 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: Gconst bannerHidden = useGoalStore((s) => (goal ? Boolean(s.bannerHiddenGoalIds[goal.goal_id]) : false));const [editing, setEditing] = useState(false);const [now, setNow] = useState(() => Date.now());+ // 暂停/恢复点击后的乐观图标翻转:只影响图标选哪个,不影响按钮是否可点(仍然沿用下面的+ // isDisabled 整组置灰)、也不影响状态文字颜色(那个继续等权威数据)。pendingAction 落地+ // (不管成功还是失败兜底完)后清空,让真实 goal.status 接管。+ const [optimisticPausable, setOptimisticPausable] = useState<boolean | null>(null);useEffect(() => {// completed/blocked 是终态,不再有新的 attempt,耗时不该继续跳字——冻结在跳变那一刻附近的值@@ -68,8 +79,12 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: Greturn () => window.clearInterval(timer);}, [goal]);+ useEffect(() => {+ if (pendingAction === null) setOptimisticPausable(null);+ }, [pendingAction]);+// 编辑弹窗打开期间目标在后台跑完了(用户可能没注意到,弹窗内容也不会自动同步最新状态)——- // 与其等 4 秒自动隐藏把弹窗连带 GoalBar 一起悄悄拽没(那样用户完全不知道发生了什么,编辑内容+ // 与其等自动隐藏把弹窗连带 GoalBar 一起悄悄拽没(那样用户完全不知道发生了什么,编辑内容// 也白写了),不如一发现就主动关掉并提示,避免用户点保存把一个已经结束的目标悄悄"复活"。useEffect(() => {if (editing && goal?.status === 'completed' && activeSessionId) {@@ -83,13 +98,29 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: G}}, [editing, goal?.status, activeSessionId, t]);+ // 没有目标(goal 为 null)时严格"不用管"——即使当前处于断联/查询失败,也不展示任何占位条;+ // 只有"这个会话之前已经查到过目标"(goal 非空,数据在断联/查询失败期间原样保留,不会被清空)+ // 才叠加 disconnected/unknown 展示态。goal 是否非空天然承担了这个判断,不需要额外的标记位。if (!activeSessionId || !goal) return null;if (goal.status === 'completed' && bannerHidden) return null;- const tone = STATUS_TONE[goal.status as GoalStatus] ?? 'active';+ // completed 是终态,不需要叠加断联/未知态(已完成的目标不再自动更新,见真实环境联调方案 9a)。+ const degraded: 'disconnected' | 'unknown' | null =+ goal.status === 'completed'+ ? null+ : !isConnected+ ? 'disconnected'+ : queryStatus === 'unknown'+ ? 'unknown'+ : null;++ const tone: DisplayTone = degraded ?? STATUS_TONE[goal.status as GoalStatus] ?? 'active';const isPausable = goal.status === 'active';const isResumable = goal.status === 'paused' || goal.status === 'blocked';const isBusy = pendingAction !== null;+ const isDisabled = isBusy || degraded !== null;+ // 图标显示用的"是否展示为可暂停":乐观值优先,否则用真实状态。+ const displayAsPausable = optimisticPausable ?? isPausable;return (<div className="goal-bar-attached">@@ -97,7 +128,7 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: G<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)}+ {t(`goal.status.${degraded ?? goal.status}`, degraded ?? goal.status)}</span><span className="goal-bar__objective" title={goal.objective}>{goal.objective}@@ -110,6 +141,7 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: Gtype="button"title={t('goal.action.editTooltip')}className="goal-bar__action-btn"+ disabled={isDisabled}onClick={() => setEditing(true)}><Pencil size={14} strokeWidth={2} />@@ -118,19 +150,27 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: G{(isPausable || isResumable) && (<buttontype="button"- title={isPausable ? t('goal.action.pauseTooltip') : t('goal.action.resumeTooltip')}+ title={displayAsPausable ? t('goal.action.pauseTooltip') : t('goal.action.resumeTooltip')}className="goal-bar__action-btn"- disabled={isBusy}- onClick={() => (isPausable ? onPauseGoal(activeSessionId) : onResumeGoal(activeSessionId))}+ disabled={isDisabled}+ onClick={() => {+ if (isPausable) {+ setOptimisticPausable(false);+ onPauseGoal(activeSessionId);+ } else {+ setOptimisticPausable(true);+ onResumeGoal(activeSessionId);+ }+ }}>- {isPausable ? <Pause size={14} strokeWidth={2} /> : <Play size={14} strokeWidth={2} />}+ {displayAsPausable ? <Pause size={14} strokeWidth={2} /> : <Play size={14} strokeWidth={2} />}</button>)}<buttontype="button"title={t('goal.action.deleteTooltip')}className="goal-bar__action-btn goal-bar__action-btn--danger"- disabled={isBusy}+ disabled={isDisabled}onClick={() => onClearGoal(activeSessionId)}><Trash2 size={14} strokeWidth={2} />diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts b/jiuwenswarm/channels/web/frontend/src/hooks/index.tsindex b3f845b3ba..65737d0c2e 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, mergePersistedGoalCompletionMessages } from './useWebSocket';+export { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } 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 41f25f4e6b..d2cdca8739 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -75,6 +75,25 @@ function isCompletedResumeResult(interruptResult: unknown): boolean {const GOAL_COMPLETED_AUTO_HIDE_MS = 4000;const GOAL_COMPLETED_SETTLE_FALLBACK_MS = 8000;+/** get 失败后的重试间隔(毫秒):首次失败后再试 2 次,都失败才判定为 unknown(真实环境联调方案)。 */+const GOAL_GET_RETRY_DELAYS_MS = [3000, 5000];+/** 目标处于 active/paused/blocked 期间,超过这个时长没收到新的 goal.snapshot/goal.updated 就主动 get 兜底。 */+const GOAL_STALE_REFRESH_MS = 60000;+const GOAL_STALE_REFRESH_CHECK_INTERVAL_MS = 15000;+/**+ * 已经判定为 unknown(performGoalGet 自己的 3 次重试都失败过)之后,巡检 effect 不再按+ * GOAL_STALE_REFRESH_MS 的节奏重试——那样等于每 15s 就重新打一轮 3 连击,事实上会无限循环+ * 高频重试一个已知连不上的后端。改成退避到这个更长的间隔再试一次,只要某次 get 成功+ * (queryStatus 收敛回 'ok'),下一次巡检就会自动切回正常的 GOAL_STALE_REFRESH_MS 节奏。+ */+const GOAL_UNKNOWN_RETRY_INTERVAL_MS = 5 * 60 * 1000;+/**+ * set 发出后,等这么久还没等到 goal.snapshot/execution.error 把 pendingAction 清掉,才补一次+ * 兜底 get——正常路径下 snapshot 应该早就到了,不必让这个兜底跟它赛跑(赛跑赢了反而会用 set+ * 落地前的旧数据提前清掉 pendingAction,重新打开"按钮提前解禁、能打出冲突指令"的窗口)。这个值+ * 只是给首次设置目标时快照丢包这种小概率情况兜底,不需要很短。+ */+const GOAL_SET_CONVERGENCE_DELAY_MS = 4000;/*** 目标完成事件(goal.updated)和它所在这一轮回复的正文(chat.delta/chat.final),走的是两条@@ -124,9 +143,13 @@ function scheduleAfterTurnSettles(sessionId: string, run: () => void): void {function applyIncomingGoal(sessionId: string,goal: GoalRecord | null,- hideTimerMap: Map<string, ReturnType<typeof window.setTimeout>>+ hideTimerMap: Map<string, ReturnType<typeof window.setTimeout>>,+ lastGoalEventAtMap?: Map<string, number>): void {const goalStore = useGoalStore.getState();+ // 任何一次成功落地(不管是 get 的响应,还是 goal.snapshot/goal.updated 事件)都说明查询链路+ // 是通的,把"多次 get 失败"攒出来的 unknown 态收敛回 ok——见 goalStore.ts queryStatus 注释。+ goalStore.setQueryStatus(sessionId, 'ok');if (!goal) {const prevGoalId = goalStore.runtimes[sessionId]?.goal?.goal_id;@@ -141,11 +164,20 @@ function applyIncomingGoal(hideTimerMap.delete(prevGoalId);}}+ lastGoalEventAtMap?.delete(sessionId);goalStore.setGoal(sessionId, null);goalStore.setPendingAction(sessionId, null);return;}+ // 未完成目标才需要参与"1 分钟无更新兜底 get"的巡检(见 useWebSocket 里的巡检 effect),+ // completed 记一次时间戳没有意义,巡检本身也会按 status 过滤掉,这里顺手不记,语义更清楚。+ if (goal.status !== 'completed') {+ lastGoalEventAtMap?.set(sessionId, Date.now());+ } else {+ lastGoalEventAtMap?.delete(sessionId);+ }+goalStore.setLocalCreatedAt(goal.goal_id, new Date().toISOString());if (goal.status !== 'completed') {@@ -185,6 +217,9 @@ function applyIncomingGoal(// GoalCompletedCard(卡片+头部标签样式),跟普通回复气泡明显区分开。scheduleAfterTurnSettles(sessionId, () => {const messageId = `goal-completed-${goal.goal_id}`;+ // "现在"必然晚于它引用的那条回复——回复的时间戳是收到第一个 chat.delta 时盖的章,不会再被+ // chat.final 收尾时改动(见 chat.final 处理里去掉时间戳覆盖的注释),早于整轮跑完+判定目标+ // 完成的这一刻,不需要额外兜底。const timestamp = new Date().toISOString();const content = buildGoalCompletedContent({ evidence: goal.last_assessment?.evidence?.trim() });useChatStore.getState().addMessage(sessionId, {@@ -214,6 +249,45 @@ function applyIncomingGoal(});}+/**+ * 目标查询(command.goal get)的统一入口,带重试 + unknown 兜底(真实环境联调方案 C.e):+ * 失败先按 GOAL_GET_RETRY_DELAYS_MS 重试,全部重试完还失败就把 queryStatus 置 'unknown'+ * (GoalBar 据此展示"状态未知"、全部操作按钮置灰),不再抛错、不插聊天错误消息——这是背景+ * 巡检性质的调用(会话切换、断线重连、1 分钟无更新兜底都会触发),不是用户主动点击的操作,+ * 不需要用系统消息打扰聊天记录。+ *+ * 也被 goalAction 的 pause/resume/clear 失败兜底复用:一元 RPC 失败时 webClient 目前不会把+ * payload.goal 透传进 WebError(见 webClient.ts resolvePending 只读顶层 error/code),拿不到+ * 失败当时的目标快照,索性直接用这个函数重新问一次权威状态。+ *+ * lastAttemptAtMap 记录的是"每次调用本函数的时刻"(不管这轮 3 连击最终成没成功),只给巡检+ * effect 在 unknown 态下判断退避窗口用;跟 lastGoalEventAtMap(只在成功时更新,判断数据新鲜度)+ * 是两回事,不要混用。+ */+async function performGoalGet(+ sessionId: string,+ mode: string,+ hideTimerMap: Map<string, ReturnType<typeof window.setTimeout>>,+ lastGoalEventAtMap?: Map<string, number>,+ lastAttemptAtMap?: Map<string, number>+): Promise<void> {+ lastAttemptAtMap?.set(sessionId, Date.now());+ for (let attempt = 0; ; attempt += 1) {+ try {+ const goal = await requestGoalAction({ sessionId, action: 'get', mode });+ applyIncomingGoal(sessionId, goal, hideTimerMap, lastGoalEventAtMap);+ return;+ } catch {+ if (attempt >= GOAL_GET_RETRY_DELAYS_MS.length) {+ useGoalStore.getState().setQueryStatus(sessionId, 'unknown');+ useGoalStore.getState().setPendingAction(sessionId, null);+ return;+ }+ await new Promise((resolve) => window.setTimeout(resolve, GOAL_GET_RETRY_DELAYS_MS[attempt]));+ }+ }+}+/*** 会话历史加载完成后调用:把 localStorage 里持久化的"目标完成"消息(见 applyIncomingGoal 的* 实时跳变分支)按时间戳合并回刚加载的历史消息数组里——这些消息从未写进后端 session 历史,@@ -239,6 +313,26 @@ export function mergePersistedGoalCompletionMessages(sessionId: string, messagesreturn merged;}+/**+ * 会话历史加载完成后调用:给命中 goalStore 持久化 objective 文本列表的 user 消息回填+ * `isGoalObjectiveMessage`(见 goalStore.ts objectiveMessageTexts 的注释)。history.get+ * 返回的消息不带任何前端专属字段,本地回显时打的标记刷新后会被这批新对象整体替换掉,只能+ * 在这里按 content 重新核对一次——不依赖当前 Goal 状态,即使目标已被清除/替换也照样命中。+ */+export function stampGoalObjectiveMessages(sessionId: string, messages: Message[]): Message[] {+ const objectiveTexts = useGoalStore.getState().getGoalObjectiveTextsForSession(sessionId);+ if (objectiveTexts.length === 0) return messages;+ const objectiveTextSet = new Set(objectiveTexts);+ let changed = false;+ const stamped = messages.map((message) => {+ if (message.role !== 'user' || message.isGoalObjectiveMessage) return message;+ if (!objectiveTextSet.has(message.content)) return message;+ changed = true;+ return { ...message, isGoalObjectiveMessage: true };+ });+ return changed ? stamped : messages;+}+function getConnectSignature(options: WebConnectOptions): string {return JSON.stringify({provider: options.provider || '',@@ -771,6 +865,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {);// goal_id -> 本地"完成后自动隐藏"定时器句柄,见 applyIncomingGoalconst goalCompletedHideTimerRef = useRef<Map<string, ReturnType<typeof window.setTimeout>>>(new Map());+ /** session_id -> 最近一次成功落地 goal.snapshot/goal.updated 的时间戳,供 1 分钟无更新兜底巡检用 */+ const lastGoalEventAtRef = useRef<Map<string, number>>(new Map());+ /** session_id -> 最近一次调用 performGoalGet 的时间戳(不管成败),供 unknown 态退避巡检用 */+ const lastGoalGetAttemptAtRef = useRef<Map<string, number>>(new Map());+ const wasConnectedRef = useRef(false);const contextCompressionSummaryRef = useRef<Map<string, ContextCompressionSummary>>(new Map());const pendingContextCompressionStartRef =useRef<Map<string, PendingContextCompressionStart>>(new Map());@@ -1126,42 +1225,95 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {ensureSessionRuntimes(sessionId);useGoalStore.getState().setPendingAction(sessionId, action === 'get' ? null : action);const mode = useSessionStore.getState().getRuntime(sessionId)?.mode ?? 'agent';- try {- if (action === 'set' || action === 'resume') {++ const reportFailure = (error: unknown) => {+ 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(),+ });+ };++ if (action === 'get') {+ // 查询本身的失败/重试/unknown 兜底统一交给 performGoalGet,这里不需要额外 try/catch。+ await performGoalGet(sessionId, mode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);+ return;+ }++ if (action === 'set' || action === 'resume') {+ if (action === 'set' && objective) {+ // "设为目标"徽章要靠这份历史记录复原(见 goalStore.ts objectiveMessageTexts 的+ // 注释),发送这一刻就是唯一能拿到 objective 原文的地方,不能等回包再记。+ useGoalStore.getState().recordGoalObjectiveText(sessionId, objective);+ }+ try {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 事件清。+ } catch (error) {+ // WS 层直接发送失败(未连接等):这是能明确识别的失败,弹提示;set 不做进一步兜底+ // ("没有创建"本来就成立,不需要额外收敛),resume 按 b/c 步骤的约定补一次 get 兜底。+ useGoalStore.getState().setPendingAction(sessionId, null);+ reportFailure(error);+ if (action === 'resume') {+ await performGoalGet(sessionId, mode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);+ }+ return;+ }+ // 没有数据可落——pendingAction 会在 goal.snapshot/goal.updated/execution.error 事件到达时+ // 清掉(applyGoalSnapshot -> applyIncomingGoal)。协议文档确认这条流式失败事件的 payload+ // 也一定带 goal 字段(哪怕是 null),所以 resume 的业务层失败不需要额外兜底 get。+ if (action === 'set') {+ // set 是 fire-and-forget,正常路径下应该很快会收到 goal.snapshot/execution.error+ // 把 pendingAction 清掉。这里延迟 GOAL_SET_CONVERGENCE_DELAY_MS 后补一次兜底 get,+ // 只覆盖"事件真的丢了"这类小概率情况(尤其是这个 session 第一次设置目标时,1 分钟+ // 无更新兜底轮询要求 store 里已有非空 goal 才会巡检,覆盖不到这个场景)——不在发送后+ // 立刻发,是因为立刻发会跟真正的 snapshot 赛跑,赢了反而用 set 落地前的旧数据提前+ // 清掉 pendingAction,重新打开"按钮提前解禁、能打出冲突指令"的窗口,等于没解决问题。+ window.setTimeout(() => {+ // 到点一看 pendingAction 已经不是 'set' 了,说明真正的事件已经收敛过一次,不需要+ // 再补——不管是被这次 set 自己的事件清的,还是用户切走后又发起了别的操作。+ if (useGoalStore.getState().runtimes[sessionId]?.pendingAction !== 'set') return;void requestGoalAction({ sessionId, action: 'get', mode })- .then((goal) => applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current))+ .then((goal) => applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current)).catch(() => {// 静默失败:这只是收敛用的兜底 get,真正的状态最终仍由 goal.updated 事件驱动。});- }- return;+ }, GOAL_SET_CONVERGENCE_DELAY_MS);}+ return;+ }++ if (action === 'clear') {+ try {+ const goal = await requestGoalAction({ sessionId, action, mode });+ applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current);+ // active 目标被删除时的会话结束由 App.tsx handleClearGoal 显式补发 cancel/pause 负责+ // (真机联调确认只重置前端本地态不够,得发真信号),这里不用再管会话态。+ } catch (error) {+ // 一元 clear 失败时 webClient 目前不会把 payload.goal 透传进 WebError(见 webClient.ts+ // resolvePending),拿不到失败当时的目标快照,主动补一次 get 收敛。+ reportFailure(error);+ await performGoalGet(sessionId, mode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);+ }+ return;+ }++ // action === 'pause':同样是一元 RPC,失败兜底同 clear。+ try {const goal = await requestGoalAction({ sessionId, action, mode });- applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current);+ applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current, lastGoalEventAtRef.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(),- });+ // code: invalid_state 说明目标这会儿已经不是 active 了(常见于跟 handleCancel 触发的+ // 后端"中断顺带暂停"竞态:两边几乎同时发,谁先到不确定,晚到的这次 pause 打过去时+ // 目标已经被另一条路径转过去了)——这只是提示"已经不需要再暂停",不是真错误,不弹+ // 系统消息;其余失败(如 no_goal、网络异常)照常提示。+ if (webError.code !== 'invalid_state') {+ reportFailure(error);+ }+ await performGoalGet(sessionId, mode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);}},[t]@@ -1846,7 +1998,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {undefined;if (!sessionId) return;ensureSessionRuntimes(sessionId);- applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current);+ applyIncomingGoal(sessionId, goal, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current);};const unsubs = [@@ -2051,6 +2203,10 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().setExecutionError(sessionId, null);if (currentMode !== 'team') {useChatStore.getState().setProcessing(sessionId, false);+ // 正常情况下排空由 chat.processing_status(false) 负责;这里是它丢帧时的兜底+ // 重置,同样可能是"目标这一轮真正结束"的那个信号,一并兜底排空一次排队消息+ // (见问题3:目标完成后队列消息没有紧接着发出去)。已经排空过则是空操作,不会重复发送。+ drainTaskQueueIfIdle(sessionId);}useChatStore.getState().setThinking(sessionId, false);useChatStore.getState().clearSubtasks(sessionId);@@ -2094,10 +2250,14 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {// 定时任务等广播的 session_id 为空/null,若仍走 currentStreamId 会写到错误气泡甚至”无可见更新”。const streamId = currentStreamId;if (streamId && payloadSessionId) {+ // 注意:这里不能再用 payload.timestamp 覆盖消息的 timestamp——它是"开始输出那一刻"+ // 盖的章,收尾只应该改 content/isStreaming。目标模式下 chat.final 和 goal.updated+ // (completed) 走的是两条独立通道、到达顺序不定,用后端 chat.final 自带的时间戳覆盖会+ // 让这条回复的时间戳跟"整轮真正跑完"(含目标评估)的时刻赛跑,一旦覆盖后的新时间戳+ // 晚于目标完成提示卡的时间戳,消息排序就会翻车(真机复现过,提示卡跑到回复上方)。useChatStore.getState().updateMessage(sessionId, streamId, {...(content ? { content } : {}),isStreaming: false,- timestamp: normalizeEventTimestampIso(payload.timestamp),...(isProactiveRecommendation ? { isProactiveRecommendation, ...(proactiveType ? { proactiveType: proactiveType as 'skill_recommend' | 'task_reminder' | 'need_exploration' } : {}) } : {}),});useChatStore.getState().stopStreaming(sessionId);@@ -2757,6 +2917,11 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {useChatStore.getState().setPaused(sessionId, false);useChatStore.getState().setProcessing(sessionId, false);useChatStore.getState().setThinking(sessionId, false);+ // chat.interrupt_result 是一元响应,跟流式分片的 goal_intermediate 判断走的是完全+ // 独立的通道——不依赖后端把"目标已清除/暂停后这一轮该不该被当成中间态"判断对,+ // 用户主动点了停止/删除就该让当前气泡收尾,不再等一个可能被误判、永远不会来的+ // 真正 chat.final。+ useChatStore.getState().stopStreaming(sessionId);} else if (resultPayload.intent === 'supplement') {useChatStore.getState().setPaused(sessionId, false);}@@ -3353,6 +3518,18 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (!connected && (state === 'reconnecting' || state === 'closed')) {onDisconnectRef.current?.();}+ // 断线恢复(false -> true 跳变):真实环境联调方案 B.8——对"曾经查到过目标"的会话主动+ // get 一次,把 GoalBar 从 disconnected 收敛回真实状态。只挑非 completed 的目标查,+ // completed 不需要(也不参与下面的 1 分钟无更新巡检)。+ if (connected && !wasConnectedRef.current) {+ const runtimes = useGoalStore.getState().runtimes;+ for (const [sid, runtime] of Object.entries(runtimes)) {+ if (!runtime.goal || runtime.goal.status === 'completed') continue;+ const goalMode = useSessionStore.getState().getRuntime(sid)?.mode ?? 'agent';+ void performGoalGet(sid, goalMode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);+ }+ }+ wasConnectedRef.current = connected;});return () => {unsub();@@ -3370,6 +3547,39 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {};}, [setConnectionStats]);+ useEffect(() => {+ // 真实环境联调方案 9c:未完成目标超过 1 分钟没收到新的 goal.snapshot/goal.updated 事件,+ // 主动 get 一次兜底,避免长时间静默期间前端展示的状态跟后端实际状态脱节。用一个共享轮询+ // 巡检所有 session,而不是给每个 session 单独起 setTimeout——避免目标频繁切换 session 时+ // 需要额外维护一堆定时器的生命周期。+ //+ // unknown 态用不同的判断依据:lastGoalEventAtRef 只在成功时更新,一直失败的话这个时间戳+ // 永远不动,会导致每 15s 巡检都判定"超过 60s 未更新"、无限重触发 performGoalGet 自己的+ // 3 连击重试——变成每 15s 打一轮 3 连击轰炸一个已知连不上的后端。已经 unknown 的 session+ // 改用 lastGoalGetAttemptAtRef(记录"最近一次尝试",不管成败)+ 更长的退避间隔,直到某次+ // get 成功、queryStatus 收敛回 'ok',才会自动切回上面 60s 节奏的正常巡检。+ const timer = window.setInterval(() => {+ if (webClient.getState() !== 'ready') return;+ const runtimes = useGoalStore.getState().runtimes;+ const now = Date.now();+ for (const [sid, runtime] of Object.entries(runtimes)) {+ if (!runtime.goal || runtime.goal.status === 'completed') continue;+ if (runtime.queryStatus === 'unknown') {+ const lastAttempt = lastGoalGetAttemptAtRef.current.get(sid) ?? 0;+ if (now - lastAttempt < GOAL_UNKNOWN_RETRY_INTERVAL_MS) continue;+ } else {+ const lastAt = lastGoalEventAtRef.current.get(sid) ?? 0;+ if (now - lastAt < GOAL_STALE_REFRESH_MS) continue;+ }+ const goalMode = useSessionStore.getState().getRuntime(sid)?.mode ?? 'agent';+ void performGoalGet(sid, goalMode, goalCompletedHideTimerRef.current, lastGoalEventAtRef.current, lastGoalGetAttemptAtRef.current);+ }+ }, GOAL_STALE_REFRESH_CHECK_INTERVAL_MS);+ return () => {+ window.clearInterval(timer);+ };+ }, []);+useEffect(() => {const markAllRuntimes = () => {const runtimes = useChatStore.getState().runtimes;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex e7e918f188..c685bf3673 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -427,13 +427,16 @@"formCancel": "Cancel","editTitle": "Edit goal","toolbarTag": "Goal",+ "toolbarUnavailable": "A goal is already in progress. Finish or clear it first.","closeTag": "Cancel goal",- "badge": "Set as goal",+ "badge": "Goal","status": {"active": "Active","paused": "Paused","completed": "Completed",- "blocked": "Blocked"+ "blocked": "Blocked",+ "disconnected": "Disconnected",+ "unknown": "Status unknown"},"action": {"editTooltip": "Edit goal",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 10cdc103ec..bf2b8327dc 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -428,13 +428,16 @@"formCancel": "取消","editTitle": "编辑目标","toolbarTag": "目标",+ "toolbarUnavailable": "当前已有进行中的目标,请先完成或清除","closeTag": "取消目标",- "badge": "设为目标",+ "badge": "目标","status": {"active": "进行中","paused": "已暂停","completed": "已完成",- "blocked": "已阻塞"+ "blocked": "已阻塞",+ "disconnected": "连接已断开",+ "unknown": "状态未知"},"action": {"editTooltip": "编辑目标",diff --git a/jiuwenswarm/channels/web/frontend/src/stores/goalStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/goalStore.tsindex 3b7b787ca9..9f1ead3494 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/goalStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/goalStore.ts@@ -17,10 +17,17 @@ interface GoalRuntime {* tag 就该消失——目标存在时的展示/控制已经由 GoalBar 常驻覆盖,不需要工具栏再重复一份。*/armed: boolean;+ /**+ * 'unknown':连续多次 get 都失败(见 useWebSocket.ts performGoalGet)——不代表目标真的没了,+ * 只是暂时确认不了状态。任何一次成功的 get/goal.snapshot/goal.updated 都会把它收敛回 'ok'+ * (在 applyIncomingGoal 里统一清)。GoalBar 展示层用它叠加一层"未知"态,跟 goal.status 本身+ * 是否 completed/active 无关。+ */+ queryStatus: 'ok' | 'unknown';}function createEmptyRuntime(): GoalRuntime {- return { goal: null, pendingAction: null, armed: false };+ return { goal: null, pendingAction: null, armed: false, queryStatus: 'ok' };}/**@@ -130,6 +137,49 @@ function saveCompletedGoalMessagesToStorage(map: Record<string, CompletedGoalMes}}+/**+ * session_id -> 该会话历史上所有设置过目标的 objective 原文列表,落 localStorage。+ *+ * "设为目标"徽章之前靠实时比对 `message.content === 当前 goal.objective`,目标被清除/替换后+ * 旧的设置消息就再也匹配不上了——这其实是设计错误:"这条消息历史上设置过目标"是不可变事实,+ * 不该随当前 Goal 状态漂移。`command.goal set` 请求发出的那一刻就把 objective 原文记进这里+ * (不去重、不因为目标后来被清除/编辑/替换而移除),history.get 重新加载历史后按 content 命中+ * 这个列表给对应消息回填 `isGoalObjectiveMessage`(见 useWebSocket.ts+ * stampGoalObjectiveMessages)——不依赖消息 id:本地回显消息和 history.get 返回的同一条消息+ * id 本来就对不上,而且历史消息也没有任何后端专属字段能天然扛过刷新,见 types/message.ts 里+ * 这个字段的注释。+ */+const OBJECTIVE_MESSAGE_TEXTS_STORAGE_KEY = 'jiuwenswarm.goal.objectiveMessageTexts.v1';+const OBJECTIVE_MESSAGE_TEXTS_MAX_SESSIONS = 50;+const OBJECTIVE_MESSAGE_TEXTS_MAX_PER_SESSION = 20;++function loadObjectiveMessageTextsFromStorage(): Record<string, string[]> {+ try {+ const raw = window.localStorage.getItem(OBJECTIVE_MESSAGE_TEXTS_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 saveObjectiveMessageTextsToStorage(map: Record<string, string[]>): void {+ try {+ const entries = Object.entries(map);+ // Record 的键插入顺序近似写入的时间顺序(sessionId 不是类数组索引字符串,JS 引擎会保留+ // 插入顺序),超出上限时丢最早写入的 session,避免 localStorage 无限增长。+ const trimmed =+ entries.length > OBJECTIVE_MESSAGE_TEXTS_MAX_SESSIONS+ ? entries.slice(entries.length - OBJECTIVE_MESSAGE_TEXTS_MAX_SESSIONS)+ : entries;+ window.localStorage.setItem(OBJECTIVE_MESSAGE_TEXTS_STORAGE_KEY, JSON.stringify(Object.fromEntries(trimmed)));+ } catch {+ // localStorage 不可用时静默降级:这次记录的 objective 刷新后徽章可能找不回来,但不影响主流程。+ }+}+interface GoalState {runtimes: Record<string, GoalRuntime>;localCreatedAt: Record<string, string>;@@ -137,6 +187,7 @@ interface GoalState {/** completed 目标的 GoalBar 是否已经隐藏(跟 goal 数据是否还在 store 里是两回事,见上方注释) */bannerHiddenGoalIds: Record<string, true>;completedGoalMessages: Record<string, CompletedGoalMessageRecord>;+ objectiveMessageTexts: Record<string, string[]>;ensureRuntime: (sessionId: string) => GoalRuntime;getRuntime: (sessionId: string | null) => GoalRuntime | undefined;@@ -145,6 +196,7 @@ interface GoalState {setGoal: (sessionId: string, goal: GoalRecord | null) => void;setPendingAction: (sessionId: string, action: GoalAction | null) => void;setArmed: (sessionId: string, armed: boolean) => void;+ setQueryStatus: (sessionId: string, status: 'ok' | 'unknown') => void;/** 只在该 goal_id 还没有记录时才写入,避免编辑目标(同 goal_id 的 set 覆盖)时把计时重置 */setLocalCreatedAt: (goalId: string, iso: string) => void;/** 目标被清除时调用,避免 localStorage 里堆积再也用不到的 goal_id */@@ -161,6 +213,10 @@ interface GoalState {recordCompletedGoalMessage: (record: CompletedGoalMessageRecord) => void;getCompletedGoalMessagesForSession: (sessionId: string) => CompletedGoalMessageRecord[];clearCompletedGoalMessage: (goalId: string) => void;++ /** command.goal set 发出的那一刻调用,把 objective 原文记进这个 session 的历史列表 */+ recordGoalObjectiveText: (sessionId: string, objective: string) => void;+ getGoalObjectiveTextsForSession: (sessionId: string) => string[];}export const useGoalStore = create<GoalState>((set, get) => ({@@ -169,6 +225,7 @@ export const useGoalStore = create<GoalState>((set, get) => ({goalCompletionPhase: {},bannerHiddenGoalIds: {},completedGoalMessages: loadCompletedGoalMessagesFromStorage(),+ objectiveMessageTexts: loadObjectiveMessageTextsFromStorage(),ensureRuntime: (sessionId) => {const existing = get().runtimes[sessionId];@@ -229,6 +286,19 @@ export const useGoalStore = create<GoalState>((set, get) => ({});},+ setQueryStatus: (sessionId, status) => {+ set((state) => {+ const runtime = state.runtimes[sessionId] ?? createEmptyRuntime();+ if (runtime.queryStatus === status) return state;+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, queryStatus: status },+ },+ };+ });+ },+setLocalCreatedAt: (goalId, iso) => {set((state) => {if (state.localCreatedAt[goalId]) return state;@@ -315,4 +385,17 @@ export const useGoalStore = create<GoalState>((set, get) => ({return { completedGoalMessages: next };});},++ recordGoalObjectiveText: (sessionId, objective) => {+ set((state) => {+ const existing = state.objectiveMessageTexts[sessionId] ?? [];+ if (existing.includes(objective)) return state;+ const updated = [...existing, objective].slice(-OBJECTIVE_MESSAGE_TEXTS_MAX_PER_SESSION);+ const next = { ...state.objectiveMessageTexts, [sessionId]: updated };+ saveObjectiveMessageTextsToStorage(next);+ return { objectiveMessageTexts: next };+ });+ },++ getGoalObjectiveTextsForSession: (sessionId) => get().objectiveMessageTexts[sessionId] ?? [],}));diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex e5ba1dcb7a..a5f1489384 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -79,6 +79,14 @@ export interface Message {// 主动推荐消息标记isProactiveRecommendation?: boolean;proactiveType?: 'skill_recommend' | 'task_reminder' | 'need_exploration';+ /**+ * 这条用户消息是否曾经用于设置/修改持续目标("设为目标"徽章)。发送那一刻本地回显消息+ * 直接置 true;历史消息刷新后重新加载时,靠 goalStore 持久化的 objective 文本列表按+ * content 一次性回填(history.get 不会回传任何前端专用字段,见 useWebSocket.ts+ * stampGoalObjectiveMessages)——不能靠实时比对"当前 Goal 的 objective",目标被清除/+ * 替换后旧消息也该继续保留这个标记,这是消息自身的历史事实,不是当前 Goal 状态的派生值。+ */+ isGoalObjectiveMessage?: boolean;}export interface ToolCall {