Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 适配 Goal 后端耗时字段与 chat.final 气泡收尾

cjh_jinduoxia2e5198e48aa0
diff --git a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx
index 77f0fe1c92..3e0125de03 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/GoalBar/index.tsx
@@ -19,7 +19,7 @@ import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Pause, Pencil, Play, Target, Trash2 } from 'lucide-react';
import { useChatStore, useGoalStore, useSessionStore } from '../../stores';
-import type { GoalStatus } from '../../types';
+import type { GoalRecord, GoalStatus } from '../../types';
import { EditGoalModal } from './EditGoalModal';
import './GoalBar.css';
@@ -40,16 +40,33 @@ const STATUS_TONE: Record<string, DisplayTone> = {
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));
+function formatSeconds(totalSeconds: number): string {
+ const seconds = Math.max(0, Math.floor(totalSeconds));
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`;
}
+// 旧口径兜底:后端没下发 time_used_seconds 时,退回"创建到现在"的总时长近似
+// (created_at 后端不下发,实际几乎总是走 localCreatedAt,见 goalStore.ts 里的说明)。
+function formatElapsedFallback(createdAtIso: string | undefined, now: number): string {
+ if (!createdAtIso) return '0s';
+ const startMs = new Date(createdAtIso).getTime();
+ return formatSeconds((now - startMs) / 1000);
+}
+
+// 新口径:time_used_seconds 是后端已结算的累计耗时,active_started_at 是当前 active 计时段
+// 的起点;只有 active 时才叠加"从 active_started_at 到浏览器当前时间"这段实时增量。
+// 见 Goal持续目标Web前端对接4.md「前端耗时展示对接」。
+function formatElapsedFromGoal(goal: GoalRecord, now: number): string {
+ const base = goal.time_used_seconds ?? 0;
+ if (goal.status !== 'active' || !goal.active_started_at) return formatSeconds(base);
+ const activeStartMs = Date.parse(goal.active_started_at);
+ const activeElapsed = Number.isNaN(activeStartMs) ? 0 : Math.max(0, Math.floor((now - activeStartMs) / 1000));
+ return formatSeconds(base + activeElapsed);
+}
+
export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: GoalBarProps) {
const { t } = useTranslation();
const activeSessionId = useChatStore((s) => s.activeSessionId);
@@ -73,8 +90,10 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: G
const [optimisticPausable, setOptimisticPausable] = useState<boolean | null>(null);
useEffect(() => {
- // completed/blocked 是终态,不再有新的 attempt,耗时不该继续跳字——冻结在跳变那一刻附近的值
- if (!goal || goal.status === 'completed' || goal.status === 'blocked') return;
+ // 不管有没有后端计时字段,只有 active 才跳字——paused/blocked/completed 一律冻结在当前
+ // 展示值上,不再继续走(就算是没有 time_used_seconds 兜底走旧口径的场景,也不该在非
+ // active 期间继续累加)。
+ if (!goal || goal.status !== 'active') return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [goal]);
@@ -133,7 +152,12 @@ export function GoalBar({ onSetGoal, onPauseGoal, onResumeGoal, onClearGoal }: G
<span className="goal-bar__objective" title={goal.objective}>
{goal.objective}
</span>
- <span className="goal-bar__elapsed">· {formatElapsed(goal.created_at ?? localCreatedAt, now)}</span>
+ <span className="goal-bar__elapsed">
+ ·{' '}
+ {goal.time_used_seconds !== undefined
+ ? formatElapsedFromGoal(goal, now)
+ : formatElapsedFallback(goal.created_at ?? localCreatedAt, now)}
+ </span>
</div>
<div className="goal-bar__actions">
{goal.status !== 'completed' && (
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index f76734b9d5..96afb6b60a 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -148,6 +148,10 @@ function scheduleAfterTurnSettles(sessionId: string, run: () => void): void {
* 刷新页面最常见)一律直接不展示、不插消息——用户没看见"跳变过程",硬展示一条早就完成的
* 目标条没有意义,还可能重复插消息。
* 3) 其余状态(active/paused/blocked)照常落状态,不做特殊处理,blocked 也不会自动隐藏。
+ * 4) time_used_seconds/active_started_at 兜底——pause 等一元 RPC 的 res.payload.goal 目前不一定
+ * 带这两个字段(真机验证只有 goal.updated 事件稳定带全,见 cjh/goal 对接文档 §8.2 demo 本身
+ * 也没有这两个字段),如果直接落库会让 GoalBar 从"有后端计时"退回旧的 fallback 计时口径,
+ * 暂停后又开始跳字。这里同一个 goal_id 下如果新数据缺这两个字段、旧数据有,就沿用旧值。
*/
function applyIncomingGoal(
sessionId: string,
@@ -179,6 +183,23 @@ function applyIncomingGoal(
return;
}
+ // 见函数注释 4):同一个 goal_id,新数据缺 time_used_seconds 但旧数据有时,沿用旧值,
+ // 避免一元 RPC 的不完整快照把 GoalBar 计时打回旧口径。active_started_at 跟着 status 走——
+ // 非 active 直接钉死 null(不管新数据有没有带),active 且新数据没带时才沿用旧值。
+ const prevGoalForTiming = goalStore.runtimes[sessionId]?.goal;
+ if (
+ goal.time_used_seconds === undefined &&
+ prevGoalForTiming?.goal_id === goal.goal_id &&
+ prevGoalForTiming.time_used_seconds !== undefined
+ ) {
+ goal = {
+ ...goal,
+ time_used_seconds: prevGoalForTiming.time_used_seconds,
+ active_started_at:
+ goal.status === 'active' ? (goal.active_started_at ?? prevGoalForTiming.active_started_at ?? null) : null,
+ };
+ }
+
// 未完成目标才需要参与"1 分钟无更新兜底 get"的巡检(见 useWebSocket 里的巡检 effect),
// completed 记一次时间戳没有意义,巡检本身也会按 status 过滤掉,这里顺手不记,语义更清楚。
if (goal.status !== 'completed') {
@@ -2149,14 +2170,26 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
if (!useChatStore.getState().getRuntime(sessionId)?.isLoadingHistory) {
useChatStore.getState().setExecutionError(sessionId, null);
if (currentMode !== 'team') {
- useChatStore.getState().setProcessing(sessionId, false);
- // 正常情况下排空由 chat.processing_status(false) 负责;这里是它丢帧时的兜底
- // 重置,同样可能是"目标这一轮真正结束"的那个信号,一并兜底排空一次排队消息
- // (见问题3:目标完成后队列消息没有紧接着发出去)。已经排空过则是空操作,不会重复发送。
- drainTaskQueueIfIdle(sessionId);
+ // 有 active Goal 时,普通问答轮和 Goal 后续执行走同一条流;这次 chat.final 可能只是
+ // 普通问答轮的收尾,Goal 紧接着还要继续跑。此时不能把它当"整段彻底结束"处理——
+ // 不能关 isProcessing、不能排空任务队列、不能清 thinking/subtasks,否则会误发下一条
+ // 排队消息、或短暂闪一下"空闲"。气泡本身的收尾(下面 stopStreaming)不受影响,
+ // 该收尾还是收尾。见 Goal持续目标Web前端对接4.md「普通问答与 Goal 续跑:前端气泡收尾」。
+ const goalStillActive =
+ useGoalStore.getState().runtimes[sessionId]?.goal?.status === 'active';
+ if (!goalStillActive) {
+ useChatStore.getState().setProcessing(sessionId, false);
+ // 正常情况下排空由 chat.processing_status(false) 负责;这里是它丢帧时的兜底
+ // 重置,同样可能是"目标这一轮真正结束"的那个信号,一并兜底排空一次排队消息
+ // (见问题3:目标完成后队列消息没有紧接着发出去)。已经排空过则是空操作,不会重复发送。
+ drainTaskQueueIfIdle(sessionId);
+ useChatStore.getState().setThinking(sessionId, false);
+ useChatStore.getState().clearSubtasks(sessionId);
+ }
+ } else {
+ useChatStore.getState().setThinking(sessionId, false);
+ useChatStore.getState().clearSubtasks(sessionId);
}
- useChatStore.getState().setThinking(sessionId, false);
- useChatStore.getState().clearSubtasks(sessionId);
}
if (content) {
revealPendingContextUsage(sessionId);
diff --git a/jiuwenswarm/channels/web/frontend/src/types/goal.ts b/jiuwenswarm/channels/web/frontend/src/types/goal.ts
index 5ee79194be..ec0e0808c5 100644
--- a/jiuwenswarm/channels/web/frontend/src/types/goal.ts
+++ b/jiuwenswarm/channels/web/frontend/src/types/goal.ts
@@ -31,6 +31,10 @@ export interface GoalRecord {
attempt_count: number;
created_at?: string;
updated_at?: string;
+ // 后端已结算的累计耗时(秒);active_started_at 是当前 active 计时段的开始时间
+ // (UTC ISO-8601),非 active 状态下为 null。见 Goal持续目标Web前端对接4.md「前端耗时展示对接」。
+ time_used_seconds?: number;
+ active_started_at?: string | null;
token_usage?: GoalTokenUsage;
max_attempts?: number | null;
token_budget?: number | null;