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

fix(goal): 历史记录里goal任务不显示徽章

wncbdj942757b7b4bb
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index e56c148820..8da98bfa9c 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -622,7 +622,10 @@ function AppContent() {
});
const applyHistoryPageResult = useCallback((sid: string, result: FetchHistoryPageResult) => {
- prependMessages(sid, result.messages);
+ // 只 stamp 徽章:merge 完成卡只适合整页 replace(首次 history 恢复)。
+ // 这里若再 merge,localStorage 里的完成卡不在本页 messages 里就会被再次注入,
+ // prepend 又不按 id 去重,导致完成卡重复。
+ prependMessages(sid, stampGoalObjectiveMessages(sid, result.messages));
for (const item of result.toolReplay) {
if (item.kind === 'tool_call') {
const n = normalizeToolCallPayload(item.payload);
diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
index 49d5921ffd..295fb2ec39 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts
@@ -5,6 +5,10 @@ import { mergeFileDownloadItems } from '../utils/fileDownloadDedup';
import { parseTimestampToMs, timestampMsToIso } from '../utils/timestamp';
import { isA2UIClientEventContent } from './a2ui/a2uiContent';
import { normalizeToolCallPayload, normalizeToolResultPayload } from './tool-events/toolEventNormalizer';
+import {
+ buildGoalCompletedContent,
+ isGoalCompletedContent,
+} from '../components/GoalBar/goalCompletedMessage';
export const HISTORY_GET_METHOD = 'history.get';
export const HISTORY_MESSAGE_EVENT = 'history.message';
@@ -355,6 +359,10 @@ function extractHistoryMediaItems(record: Record<string, unknown>): MediaItem[]
return mediaItems;
}
+function isTruthyHistoryFlag(value: unknown): boolean {
+ return value === true || value === 'true' || value === 1 || value === '1';
+}
+
function parseHistoryTimelineEntry(
record: Record<string, unknown>,
sessionId: string
@@ -375,6 +383,9 @@ function parseHistoryTimelineEntry(
}
const id =
pickFirstString(record, ['id', 'message_id', 'msg_id']) ?? `hist-user-${sessionId}-${at}`;
+ const isGoalObjectiveMessage =
+ isTruthyHistoryFlag(record.is_goal_objective_message) ||
+ isTruthyHistoryFlag(record.isGoalObjectiveMessage);
return {
kind: 'message',
message: {
@@ -383,6 +394,7 @@ function parseHistoryTimelineEntry(
content,
timestamp: at,
...(mediaItems.length > 0 ? { mediaItems } : {}),
+ ...(isGoalObjectiveMessage ? { isGoalObjectiveMessage: true } : {}),
},
};
}
@@ -438,7 +450,21 @@ function parseHistoryTimelineEntry(
const payload = buildEventPayloadForRecord(record);
if (eventType === 'chat.final') {
- const content = normalizeFinalContent(payload);
+ let content = normalizeFinalContent(payload);
+ const isGoalCompletedMessage =
+ isTruthyHistoryFlag(record.is_goal_completed_message) ||
+ isTruthyHistoryFlag(record.isGoalCompletedMessage) ||
+ isTruthyHistoryFlag(payload.is_goal_completed_message) ||
+ isTruthyHistoryFlag(payload.isGoalCompletedMessage);
+ if (isGoalCompletedMessage && !isGoalCompletedContent(content)) {
+ const evidenceRaw =
+ (typeof record.evidence === 'string' && record.evidence) ||
+ (typeof payload.evidence === 'string' && payload.evidence) ||
+ content;
+ content = buildGoalCompletedContent({
+ evidence: typeof evidenceRaw === 'string' ? evidenceRaw.trim() : '',
+ });
+ }
if (!content.trim()) {
return null;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index f4623c92b5..8a48c54bcc 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -355,9 +355,9 @@ export function mergePersistedGoalCompletionMessages(sessionId: string, messages
/**
* 会话历史加载完成后调用:给命中 goalStore 持久化 objective 文本列表的 user 消息回填
- * `isGoalObjectiveMessage`(见 goalStore.ts objectiveMessageTexts 的注释)。history.get
- * 返回的消息不带任何前端专属字段,本地回显时打的标记刷新后会被这批新对象整体替换掉,只能
- * 在这里按 content 重新核对一次——不依赖当前 Goal 状态,即使目标已被清除/替换也照样命中。
+ * `isGoalObjectiveMessage`(见 goalStore.ts objectiveMessageTexts 的注释)。优先尊重后端
+ * history 已下发的 `is_goal_objective_message`(historyRestore 已映射到该字段);没有后端
+ * 标记时再按 content 与本地 objective 文本列表核对——兼容旧会话 / 清过缓存前的数据。
*/
export function stampGoalObjectiveMessages(sessionId: string, messages: Message[]): Message[] {
const objectiveTexts = useGoalStore.getState().getGoalObjectiveTextsForSession(sessionId);
diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.ts
index 1a2e5d2bde..174528d0d5 100644
--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts
+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts
@@ -83,10 +83,11 @@ export interface Message {
proactiveType?: 'skill_recommend' | 'task_reminder' | 'need_exploration';
/**
* 这条用户消息是否曾经用于设置/修改持续目标("设为目标"徽章)。发送那一刻本地回显消息
- * 直接置 true;历史消息刷新后重新加载时,靠 goalStore 持久化的 objective 文本列表按
- * content 一次性回填(history.get 不会回传任何前端专用字段,见 useWebSocket.ts
- * stampGoalObjectiveMessages)——不能靠实时比对"当前 Goal 的 objective",目标被清除/
- * 替换后旧消息也该继续保留这个标记,这是消息自身的历史事实,不是当前 Goal 状态的派生值。
+ * 直接置 true;历史消息刷新后重新加载时,优先读后端 history 字段
+ * `is_goal_objective_message`,没有时再靠 goalStore 持久化的 objective 文本列表按
+ * content 回填(见 useWebSocket.ts stampGoalObjectiveMessages)——不能靠实时比对
+ * "当前 Goal 的 objective",目标被清除/替换后旧消息也该继续保留这个标记,这是消息自身的
+ * 历史事实,不是当前 Goal 状态的派生值。
*/
isGoalObjectiveMessage?: boolean;
}
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 71611f2b08..c159be09ca 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1847,6 +1847,12 @@ class JiuWenSwarm:
if ok and str(action or "").strip().lower() == "set":
objective = str(params.get("objective") or "").strip()
if objective:
+ goal_obj = goal_result.get("goal")
+ goal_id = (
+ str(goal_obj.get("goal_id") or "").strip() or None
+ if isinstance(goal_obj, dict)
+ else None
+ )
append_history_record(
session_id=session_id,
request_id=request.request_id,
@@ -1856,6 +1862,10 @@ class JiuWenSwarm:
timestamp=time.time(),
channel_metadata=request.metadata,
mode=params.get("mode", "unknown"),
+ extra={
+ "goal_id": goal_id,
+ "is_goal_objective_message": True,
+ },
)
# Keep message for callers that read payload.message; also
# mirror into error on failure so Gateway top-level error
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index b3b4108f6a..34e8a1966d 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -5696,17 +5696,32 @@ class JiuWenSwarmDeepAdapter:
return None
return str(getattr(kind, "value", kind))
- def _begin_visible_chat_content(self) -> dict[str, Any] | None:
+ def _begin_visible_chat_content(
+ self, stream_is_user_originated: bool = False
+ ) -> dict[str, Any] | None:
"""Stamp content provenance; inject a bubble-split final on user→goal.
When the shared stream switches from user-round text to goal-round text
without a terminal ``chat.final`` in between, emit an empty final so the
frontend can ``stopStreaming`` and open a new bubble.
+
+ ``stream_is_user_originated`` marks a *plain user chat* consumer stream
+ (i.e. not a ``command.goal`` / attach-goal stream). Such a stream can be
+ hijacked by a goal round **before** the user round emits its first
+ visible token (slow first token + an early goal insert). In that timing
+ ``prev`` is still ``None`` yet a boundary final is still required, so the
+ goal answer opens its own bubble instead of merging into the (empty) user
+ bubble. Non-user-originated streams keep the strict ``prev == "user"``
+ rule so a pure goal stream never gets a spurious final at its head.
"""
kind = self._current_interaction_run_kind()
prev = self._stream_content_run_kind
boundary: dict[str, Any] | None = None
- if prev == "user" and kind == "goal":
+ switched_from_user = prev == "user" and kind == "goal"
+ hijacked_before_user_token = (
+ stream_is_user_originated and kind == "goal" and prev is None
+ )
+ if switched_from_user or hijacked_before_user_token:
boundary = {"event_type": "chat.final", "content": ""}
self._stream_content_run_kind = None
if kind is not None:
@@ -6965,6 +6980,7 @@ class JiuWenSwarmDeepAdapter:
if not objective:
return
params = request.params if isinstance(request.params, dict) else {}
+ goal_id = str(goal_payload.get("goal_id") or "").strip() or None
append_history_record(
session_id=request.session_id or "default",
request_id=request.request_id,
@@ -6974,6 +6990,79 @@ class JiuWenSwarmDeepAdapter:
timestamp=time.time(),
channel_metadata=request.metadata,
mode=params.get("mode", "unknown"),
+ extra={
+ "goal_id": goal_id,
+ "is_goal_objective_message": True,
+ },
+ )
+
+ @staticmethod
+ def _goal_completed_history_exists(session_id: str, goal_id: str) -> bool:
+ """Return True when this session already persisted a completion card for goal_id."""
+ message_id = f"goal-completed-{goal_id}"
+ try:
+ for rec in load_history_records(session_id):
+ if not isinstance(rec, dict):
+ continue
+ if str(rec.get("id") or "") == message_id:
+ return True
+ if rec.get("is_goal_completed_message") and str(rec.get("goal_id") or "") == goal_id:
+ return True
+ except Exception:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] goal completed history lookup failed: session_id=%s goal_id=%s",
+ session_id,
+ goal_id,
+ exc_info=True,
+ )
+ return False
+
+ @staticmethod
+ def _record_goal_completed_history_if_needed(
+ *,
+ session_id: str,
+ channel_id: str,
+ channel_metadata: dict[str, Any] | None,
+ mode: str | None,
+ goal_payload: dict[str, Any] | None,
+ ) -> None:
+ """Persist a goal-completed card once when status first becomes completed."""
+ if not isinstance(goal_payload, dict):
+ return
+ status = goal_payload.get("status")
+ status_value = getattr(status, "value", status)
+ if str(status_value or "").strip().lower() != "completed":
+ return
+ goal_id = str(goal_payload.get("goal_id") or "").strip()
+ if not goal_id:
+ return
+ sid = (session_id or "default").strip() or "default"
+ if JiuWenSwarmDeepAdapter._goal_completed_history_exists(sid, goal_id):
+ return
+
+ evidence = ""
+ last_assessment = goal_payload.get("last_assessment")
+ if isinstance(last_assessment, dict):
+ evidence = str(last_assessment.get("evidence") or "").strip()
+ # Keep the existing frontend GoalCompletedCard wire format so history
+ # restore / localStorage merge keep working without a content-parser fork.
+ content = "goal.completed:" + json.dumps({"evidence": evidence}, ensure_ascii=False)
+ message_id = f"goal-completed-{goal_id}"
+ append_history_record(
+ session_id=sid,
+ request_id=message_id,
+ channel_id=channel_id,
+ role="assistant",
+ content=content,
+ timestamp=time.time(),
+ channel_metadata=channel_metadata,
+ mode=mode,
+ extra={
+ "id": message_id,
+ "goal_id": goal_id,
+ "is_goal_completed_message": True,
+ "evidence": evidence,
+ },
)
@staticmethod
@@ -7863,6 +7952,18 @@ class JiuWenSwarmDeepAdapter:
had_assistant_output = True
if event_type == "chat.final":
emitted_terminal_chat_final = True
+ # Persist goal-completed cards at the stream yield choke point so
+ # every goal.updated path (typed chunk / dict chunk) is covered once
+ # without touching the pure payload parser.
+ if event_type == GOAL_UPDATED_EVENT_TYPE:
+ goal_obj = payload.get("goal")
+ self._record_goal_completed_history_if_needed(
+ session_id=session_id,
+ channel_id=cid,
+ channel_metadata=request.metadata if isinstance(request.metadata, dict) else None,
+ mode=mode,
+ goal_payload=goal_obj if isinstance(goal_obj, dict) else None,
+ )
return payload
cron_context_tokens = self._bind_runtime_cron_context(
@@ -8155,6 +8256,16 @@ class JiuWenSwarmDeepAdapter:
)
)
run_failure: tuple[str, str] | None = None
+ # A plain user-chat consumer stream (not a command.goal / attach-goal
+ # stream). Only these may be hijacked by a goal round before the user
+ # round produces its first visible token; used to allow a bubble
+ # split even when ``prev`` is still None. Pure goal streams keep the
+ # strict prev=="user" rule inside ``_begin_visible_chat_content``.
+ stream_is_user_originated = (
+ pending_goal_op is None
+ and not attach_goal_request
+ and not goal_stream_request
+ )
async for chunk in interaction_stream:
if _debug_logger is not None:
_debug_logger.feed(chunk)
@@ -8168,7 +8279,7 @@ class JiuWenSwarmDeepAdapter:
# Only stamp provenance / inject split on new visible deltas.
# A late user-round chat.final must keep the prior content kind.
if isinstance(parsed, dict) and parsed.get("event_type") == "chat.delta":
- boundary = self._begin_visible_chat_content()
+ boundary = self._begin_visible_chat_content(stream_is_user_originated)
if boundary is not None:
yield AgentResponseChunk(
request_id=rid,
@@ -8248,7 +8359,7 @@ class JiuWenSwarmDeepAdapter:
)
if reasoning_payload is None:
continue
- boundary = self._begin_visible_chat_content()
+ boundary = self._begin_visible_chat_content(stream_is_user_originated)
if boundary is not None:
yield AgentResponseChunk(
request_id=rid,
@@ -8286,7 +8397,7 @@ class JiuWenSwarmDeepAdapter:
is_complete=False,
)
accumulated_reasoning = ""
- boundary = self._begin_visible_chat_content()
+ boundary = self._begin_visible_chat_content(stream_is_user_originated)
if boundary is not None:
yield AgentResponseChunk(
request_id=rid,
@@ -9458,6 +9569,10 @@ class JiuWenSwarmDeepAdapter:
if role == "user":
recapworthy.append(SimpleNamespace(role="user", content=content))
elif role == "assistant":
+ # Goal-completed cards are UI-only history facts; never feed them
+ # back into model recap context.
+ if rec.get("is_goal_completed_message"):
+ continue
event_type = rec.get("event_type")
# 只包含 assistant 的最终回复和 compact summary
if event_type in ("chat.final", "context.compact_summary") or not event_type:
@@ -9835,6 +9950,8 @@ class JiuWenSwarmDeepAdapter:
if cleaned:
messages.append(UserMessage(content=cleaned))
elif role == "assistant":
+ if rec.get("is_goal_completed_message"):
+ continue
if event_type in ("chat.final", "context.compact_summary", "context.rewind_summary") or not event_type:
if event_type in ("context.compact_boundary",):
continue
diff --git a/jiuwenswarm/server/wire_truncate.py b/jiuwenswarm/server/wire_truncate.py
index 93ae1408f8..39c8f44576 100644
--- a/jiuwenswarm/server/wire_truncate.py
+++ b/jiuwenswarm/server/wire_truncate.py
@@ -76,6 +76,10 @@ _HISTORY_COLLAPSE_KEEP_KEYS = {
"source_member",
"name",
"status",
+ "goal_id",
+ "is_goal_objective_message",
+ "is_goal_completed_message",
+ "evidence",
}
_WORKFLOW_SNAPSHOT_KEEP_KEYS = {
diff --git a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py b/tests/unit_tests/agentserver/test_goal_runtime_adapter.py
index 86dc29e6d9..6aeab88276 100644
--- a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py
+++ b/tests/unit_tests/agentserver/test_goal_runtime_adapter.py
@@ -601,3 +601,94 @@ def test_stream_end_skips_final_when_already_emitted() -> None:
had_assistant_output=True,
emitted_terminal_chat_final=True,
)
+
+
+def test_record_goal_set_history_writes_objective_flags(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: list[dict] = []
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.append_history_record",
+ lambda **kwargs: captured.append(kwargs),
+ )
+ req = AgentRequest(
+ request_id="r1",
+ channel_id="web",
+ session_id="s1",
+ req_method=ReqMethod.COMMAND_GOAL,
+ params={"mode": "agent"},
+ )
+ JiuWenSwarmDeepAdapter._record_goal_set_history_if_needed(
+ req,
+ action="set",
+ result_type="goal_stream",
+ goal_payload={"goal_id": "g1", "objective": "ship it"},
+ )
+ assert len(captured) == 1
+ assert captured[0]["role"] == "user"
+ assert captured[0]["content"] == "ship it"
+ assert captured[0]["extra"]["is_goal_objective_message"] is True
+ assert captured[0]["extra"]["goal_id"] == "g1"
+
+ captured.clear()
+ JiuWenSwarmDeepAdapter._record_goal_set_history_if_needed(
+ req,
+ action="pause",
+ result_type="ok",
+ goal_payload={"goal_id": "g1", "objective": "ship it"},
+ )
+ assert captured == []
+
+
+def test_record_goal_completed_history_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: list[dict] = []
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.append_history_record",
+ lambda **kwargs: captured.append(kwargs),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.load_history_records",
+ lambda _sid: [],
+ )
+ JiuWenSwarmDeepAdapter._record_goal_completed_history_if_needed(
+ session_id="s1",
+ channel_id="web",
+ channel_metadata=None,
+ mode="agent",
+ goal_payload={
+ "goal_id": "g1",
+ "status": "completed",
+ "last_assessment": {"evidence": "all done"},
+ },
+ )
+ assert len(captured) == 1
+ assert captured[0]["extra"]["is_goal_completed_message"] is True
+ assert captured[0]["extra"]["id"] == "goal-completed-g1"
+ assert captured[0]["content"].startswith("goal.completed:")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.load_history_records",
+ lambda _sid: [
+ {
+ "id": "goal-completed-g1",
+ "is_goal_completed_message": True,
+ "goal_id": "g1",
+ }
+ ],
+ )
+ captured.clear()
+ JiuWenSwarmDeepAdapter._record_goal_completed_history_if_needed(
+ session_id="s1",
+ channel_id="web",
+ channel_metadata=None,
+ mode="agent",
+ goal_payload={"goal_id": "g1", "status": "completed"},
+ )
+ assert captured == []
+
+ JiuWenSwarmDeepAdapter._record_goal_completed_history_if_needed(
+ session_id="s1",
+ channel_id="web",
+ channel_metadata=None,
+ mode="agent",
+ goal_payload={"goal_id": "g2", "status": "active"},
+ )
+ assert captured == []