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: 刷新后恢复未完成的 ask_user 交互卡 将 chat.ask_user_question 写入当前 session 历史并在 history.get 回放;同一轮的铺垫 chat.final 不再误判为已答完。
GYHHelloworldfbff536bbc22
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex a103a964cd..68af630fae 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -582,6 +582,7 @@ function AppContent() {const isLoadingHistory = useChatStore((s) => s.runtimes[sessionId]?.isLoadingHistory ?? false);const replaceHistoryMessages = useChatStore((s) => s.replaceHistoryMessages);const restoreReasoningSegments = useChatStore((s) => s.restoreReasoningSegments);+ const setPendingQuestion = useChatStore((s) => s.setPendingQuestion);const isRestoringHistorySession = isLoadingHistory && !historyPagerMeta && messages.length === 0;const isRestoringTeamHistory = mode === 'team' && isRestoringHistorySession;@@ -1347,9 +1348,12 @@ function AppContent() {prevProcessingBySessionRef.current.set(sessionId, isProcessing);}, [sessionId, isProcessing, hasPendingQuestion, loadSessionMetadata]);- // 连接成功后从 config.yaml 同步 preferred_language 到前端显示+ // 连接成功后从服务端同步 preferred_language 到前端显示。+ // 企业版 preferred_language 无独立持久化(personal-only YAML overlay),+ // get_conf 只能读到全局只读 config.yaml 默认 zh;若仍用它覆盖 i18n,+ // 会冲掉 localStorage 里用户刚选的 en,刷新后语言回中文。useEffect(() => {- if (!isConnected) return;+ if (!isConnected || isEnterprise()) return;void webRequest<{ preferred_language?: string }>('locale.get_conf').then((payload) => {const lang = payload?.preferred_language;@@ -1504,6 +1508,14 @@ function AppContent() {onReasoningReplay: (items) => {restoreReasoningSegments(sid, items);},+ onAskUserReplay: (question) => {+ // replaceHistoryMessages 会把 pendingQuestion 清掉;回放必须在它之后。+ setPendingQuestion(sid, question);+ if (question) {+ setProcessing(sid, true);+ setThinking(sid, false);+ }+ },onError: (message) => {console.warn('[history.restore]', message);setLoadingHistory(sid, false);@@ -1557,6 +1569,9 @@ function AppContent() {replaceHistoryMessages,restoreReasoningSegments,startBackgroundHistoryPrefetch,+ setPendingQuestion,+ setProcessing,+ setThinking,]);// 轮询兜底刷新:企业版 HTTP 无 cron 结果 push,立即执行跳转后 skipHistoryLoad,diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsxindex 1d5d6535e5..8e9ba0ebda 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx@@ -26,6 +26,7 @@ import {formatAgentContextLabel,useEnterpriseContext,} from '../../services/enterpriseContext';+import { isEnterprise } from '../../edition';import { isClickOutside } from './clickOutside';import { EditableCombobox } from './EditableCombobox';import type { MainNavKey } from '../../features/mainNavigationState';@@ -107,7 +108,10 @@ function AdvancedConfigPanel({}, [isOpen, onClose, buttonRef]);const handleLanguageChange = (lang: 'zh' | 'en') => {+ // i18n LanguageDetector 会写入 localStorage,刷新后靠它恢复。i18n.changeLanguage(lang);+ // 企业版 set_conf 只能回写共享只读/全局 config.yaml,既不可靠又会串用户,跳过。+ if (isEnterprise()) return;void webRequest('locale.set_conf', { preferred_language: lang }).catch(() => {});};diff --git a/jiuwenswarm/channels/web/frontend/src/features/askUserQuestion.ts b/jiuwenswarm/channels/web/frontend/src/features/askUserQuestion.tsnew file mode 100644index 0000000000..5274d52271--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/askUserQuestion.ts@@ -0,0 +1,73 @@+import type { AskUserQuestionPayload } from '../types';++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++/**+ * Normalize a live `chat.ask_user_question` payload or a flattened history+ * record into the pending-question shape used by InteractionSlot / InlineQuestionCard.+ */+export function normalizeAskUserQuestionPayload(raw: unknown): AskUserQuestionPayload | null {+ if (!isRecord(raw)) {+ return null;+ }+ const nested = isRecord(raw.payload) ? raw.payload : null;+ const questionPayload: Record<string, unknown> = nested ? { ...raw, ...nested } : { ...raw };++ const questions = Array.isArray(questionPayload.questions) ? questionPayload.questions : [];+ if (questions.length === 0) {+ return null;+ }++ const requestId =+ typeof questionPayload.request_id === 'string' ? questionPayload.request_id.trim() : '';+ if (!requestId) {+ return null;+ }++ const evolutionMeta =+ questionPayload.evolution_meta && typeof questionPayload.evolution_meta === 'object'+ ? (questionPayload.evolution_meta as Record<string, unknown>)+ : questionPayload._evolution_meta && typeof questionPayload._evolution_meta === 'object'+ ? (questionPayload._evolution_meta as Record<string, unknown>)+ : undefined;+ const approvalSchema =+ typeof questionPayload.approval_schema === 'string'+ ? questionPayload.approval_schema+ : undefined;+ const planApprovalKind =+ typeof questionPayload.plan_approval_kind === 'string'+ ? questionPayload.plan_approval_kind+ : undefined;+ const planContent =+ typeof questionPayload.plan_content === 'string'+ ? questionPayload.plan_content+ : undefined;+ const planLanguage =+ questionPayload.plan_language === 'cn' || questionPayload.plan_language === 'en'+ ? questionPayload.plan_language+ : undefined;+ const agentScopeId =+ typeof questionPayload.agent_scope_id === 'string'+ ? questionPayload.agent_scope_id+ : undefined;+ const rawCard = questionPayload['x-skill-approval-card'] ?? questionPayload['skill_approval_card'];+ const skillApprovalCard =+ rawCard && typeof rawCard === 'object'+ ? (rawCard as AskUserQuestionPayload['skill_approval_card'])+ : undefined;++ return {+ request_id: requestId,+ source: typeof questionPayload.source === 'string' ? questionPayload.source : undefined,+ questions,+ ...(approvalSchema ? { approvalSchema } : {}),+ ...(evolutionMeta ? { evolutionMeta } : {}),+ ...(planApprovalKind ? { planApprovalKind } : {}),+ ...(planContent !== undefined ? { planContent } : {}),+ ...(planLanguage ? { planLanguage } : {}),+ ...(agentScopeId ? { agent_scope_id: agentScopeId } : {}),+ ...(skillApprovalCard ? { skill_approval_card: skillApprovalCard } : {}),+ };+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex 67b591563d..9055f20bc4 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -1,10 +1,11 @@-import { Message, MessageRole, UsageSummary, FileDownloadItem, MediaItem, WsEvent, ToolExecution } from '../types';+import { Message, MessageRole, UsageSummary, FileDownloadItem, MediaItem, WsEvent, ToolExecution, AskUserQuestionPayload } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';import { mergeFileDownloadItems } from '../utils/fileDownloadDedup';import { parseTimestampToMs, timestampMsToIso } from '../utils/timestamp';import { isA2UIClientEventContent } from './a2ui/a2uiContent';import { normalizeToolCallPayload, normalizeToolResultPayload } from './tool-events/toolEventNormalizer';+import { normalizeAskUserQuestionPayload } from './askUserQuestion';import {buildGoalCompletedContent,isGoalCompletedContent,@@ -25,7 +26,10 @@ const ALLOWED_ASSISTANT_EVENT_TYPES = new Set(['team.task','harness.message','harness.stage_result',- 'harness.extension_ready'+ 'harness.extension_ready',+ 'chat.ask_user_question',+ 'chat.ask_user_question_expired',+ 'chat.ask_user_answered',]);/** 后端约定:最后一帧 `history.message` 使用 `payload.status: done`(兼容旧版 `payload.content: done`) */@@ -74,7 +78,10 @@ type HistoryTimelineEntry =| { kind: 'team_task'; at: string; payload: { event: Record<string, unknown> } }| { kind: 'harness_message'; at: string; content: string; stage?: string }| { kind: 'harness_stage_result'; at: string; stage: string; status: string; error: string; messages: string[]; metrics: Record<string, unknown> }- | { kind: 'reasoning'; at: string; text: string };+ | { kind: 'reasoning'; at: string; text: string }+ | { kind: 'ask_user_question'; at: string; payload: AskUserQuestionPayload }+ | { kind: 'ask_user_question_expired'; at: string; requestId: string }+ | { kind: 'ask_user_answered'; at: string; requestId: string };interface BeginHistoryRestoreOptions {sessionId: string;@@ -88,6 +95,8 @@ interface BeginHistoryRestoreOptions {onTeamReplay?: (items: HistoryTeamReplayItem[]) => void;/** 与消息同一时间线顺序,用于恢复模型思考块(chat.reasoning) */onReasoningReplay?: (items: HistoryReasoningReplayItem[]) => void;+ /** 刷新后回放仍未作答的 HITL 卡片(ask_user / 权限确认) */+ onAskUserReplay?: (question: AskUserQuestionPayload | null) => void;/** 无消息且无工具回放时调用;`totalPages` 来自流中最后一帧(若有) */onEmpty?: (totalPages: number | null) => void;onError?: (message: string) => void;@@ -460,6 +469,33 @@ function parseHistoryTimelineEntry(};}+ if (eventType === 'chat.ask_user_question') {+ const payload = normalizeAskUserQuestionPayload(record);+ if (!payload) {+ return null;+ }+ return {+ kind: 'ask_user_question',+ at,+ payload,+ };+ }++ if (eventType === 'chat.ask_user_question_expired' || eventType === 'chat.ask_user_answered') {+ const requestId =+ pickFirstString(record, ['request_id']) ??+ (isRecord(record.payload) ? pickFirstString(record.payload, ['request_id']) : undefined) ??+ '';+ if (!requestId) {+ return null;+ }+ return {+ kind: eventType === 'chat.ask_user_answered' ? 'ask_user_answered' : 'ask_user_question_expired',+ at,+ requestId,+ };+ }+const payload = buildEventPayloadForRecord(record);if (eventType === 'chat.final') {@@ -643,6 +679,7 @@ interface MaterializedHistoryTimeline {harnessReplay: HistoryHarnessReplayItem[];teamReplay: HistoryTeamReplayItem[];reasoningReplay: HistoryReasoningReplayItem[];+ pendingAskUser: AskUserQuestionPayload | null;}/** 将已按时间升序的 history 条目折叠成消息/工具/思考,供 restore / page / 文件预览共用。 */@@ -652,9 +689,25 @@ function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): Materializconst harnessReplay: HistoryHarnessReplayItem[] = [];const teamReplay: HistoryTeamReplayItem[] = [];const reasoningReplay: HistoryReasoningReplayItem[] = [];+ let pendingAskUser: AskUserQuestionPayload | null = null;for (const e of entries) {+ if (e.kind === 'ask_user_question') {+ pendingAskUser = e.payload;+ continue;+ }+ if (e.kind === 'ask_user_question_expired' || e.kind === 'ask_user_answered') {+ if (pendingAskUser?.request_id === e.requestId) {+ pendingAskUser = null;+ }+ continue;+ }if (e.kind === 'message') {+ // 同一轮里 ask_user 前后常有 chat.final 铺垫句(如「好的,那我认真问一个」),+ // 不能把它当成「已经答完」。只有用户又发了新消息才收起卡片。+ if (e.message.role === 'user') {+ pendingAskUser = null;+ }messages.push(e.message);continue;}@@ -697,6 +750,7 @@ function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): Materializcontinue;}if (e.kind === 'file_items') {+ pendingAskUser = null;if (!attachFilesToPreviousAssistant(messages, e.files)) {messages.push(createFileOnlyAssistantMessage(e.at, e.files));}@@ -710,10 +764,11 @@ function materializeHistoryTimeline(entries: HistoryTimelineEntry[]): MaterializreasoningReplay.push({ at: e.at, text: e.text });continue;}+ pendingAskUser = null;toolReplay.push({ kind: e.kind, at: e.at, payload: e.payload });}- return { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay };+ return { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay, pendingAskUser };}/**@@ -1040,12 +1095,18 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historfunction finalize(): void {if (disposed) return;- const { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay } =+ const { messages, toolReplay, harnessReplay, teamReplay, reasoningReplay, pendingAskUser } =materializeHistoryTimeline(entries);dispose();- if (messages.length === 0 && toolReplay.length === 0 && harnessReplay.length === 0 && teamReplay.length === 0) {+ if (+ messages.length === 0 &&+ toolReplay.length === 0 &&+ harnessReplay.length === 0 &&+ teamReplay.length === 0 &&+ !pendingAskUser+ ) {options.onEmpty?.(totalPages);return;}@@ -1062,6 +1123,9 @@ export function beginHistoryRestore(options: BeginHistoryRestoreOptions): Historif (reasoningReplay.length > 0) {options.onReasoningReplay?.(reasoningReplay);}+ if (pendingAskUser) {+ options.onAskUserReplay?.(pendingAskUser);+ }}const handle: HistoryRestoreHandle = { generation, dispose };diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex c94205a2a8..9d09d876c7 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -15,7 +15,6 @@ import {InterruptResultPayload,InterruptIntent,SubtaskUpdatePayload,- AskUserQuestionPayload,EvolutionStatusPayload,UserAnswer,UserAnswerStatus,@@ -33,6 +32,7 @@ import {GoalAction,Message,} from '../types';+import { normalizeAskUserQuestionPayload } from '../features/askUserQuestion';import {ensureSessionRuntimes,useChatStore,@@ -3691,53 +3691,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('chat.ask_user_question', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;- const questionPayload = payload as Record<string, unknown>;- const evolutionMeta =- questionPayload.evolution_meta && typeof questionPayload.evolution_meta === 'object'- ? (questionPayload.evolution_meta as Record<string, unknown>)- : questionPayload._evolution_meta && typeof questionPayload._evolution_meta === 'object'- ? (questionPayload._evolution_meta as Record<string, unknown>)- : undefined;- const questions = Array.isArray(questionPayload.questions) ? questionPayload.questions : [];- const approvalSchema =- typeof questionPayload.approval_schema === 'string'- ? questionPayload.approval_schema- : undefined;- const planApprovalKind =- typeof questionPayload.plan_approval_kind === 'string'- ? questionPayload.plan_approval_kind- : undefined;- const planContent =- typeof questionPayload.plan_content === 'string'- ? questionPayload.plan_content- : undefined;- const planLanguage =- questionPayload.plan_language === 'cn' || questionPayload.plan_language === 'en'- ? questionPayload.plan_language- : undefined;- const agentScopeId =- typeof questionPayload.agent_scope_id === 'string'- ? questionPayload.agent_scope_id- : undefined;- // Skill 加载审批卡:透传结构化数据(payload_schema["x-skill-approval-card"],- // 若后端通道已携带);缺失时由卡片组件回退渲染 message markdown。- const rawCard = questionPayload['x-skill-approval-card'] ?? questionPayload['skill_approval_card'];- const skillApprovalCard =- rawCard && typeof rawCard === 'object'- ? (rawCard as AskUserQuestionPayload['skill_approval_card'])- : undefined;- const normalizedPayload: AskUserQuestionPayload = {- request_id: typeof questionPayload.request_id === 'string' ? questionPayload.request_id : '',- source: typeof questionPayload.source === 'string' ? questionPayload.source : undefined,- questions,- ...(approvalSchema ? { approvalSchema } : {}),- ...(evolutionMeta ? { evolutionMeta } : {}),- ...(planApprovalKind ? { planApprovalKind } : {}),- ...(planContent !== undefined ? { planContent } : {}),- ...(planLanguage ? { planLanguage } : {}),- ...(agentScopeId ? { agent_scope_id: agentScopeId } : {}),- ...(skillApprovalCard ? { skill_approval_card: skillApprovalCard } : {}),- };+ const normalizedPayload = normalizeAskUserQuestionPayload(payload);+ if (!normalizedPayload) return;useChatStore.getState().setPendingQuestion(sessionId, normalizedPayload);}),webClient.on('chat.ask_user_question_expired', ({ payload }) => {diff --git a/jiuwenswarm/gateway/config/locale/access.py b/jiuwenswarm/gateway/config/locale/access.pyindex 5af107252c..3ee117207c 100644--- a/jiuwenswarm/gateway/config/locale/access.py+++ b/jiuwenswarm/gateway/config/locale/access.py@@ -52,7 +52,16 @@ async def get_preferred_language_in_config() -> str:async def update_preferred_language_in_config(lang: str) -> None:- """更新顶层 preferred_language 并写回。"""+ """更新顶层 preferred_language 并写回。++ 企业版无 preferred_language 同构表,且 config.yaml 为只读/全局共享挂载,+ 禁止回写(会失败或污染整实例所有用户的语言)。企业版 UI 语言由前端+ localStorage 持久化。+ """+ from jiuwenswarm.edition import is_enterprise++ if is_enterprise():+ returnrepo = get_preferred_language_config_repository()if repo is None:from jiuwenswarm.common.config import (diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 8fb4e4d107..29ce0b4abb 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -193,6 +193,15 @@ def _should_record_user_history(params: Any) -> bool:return str(params.get("source") or "") != "proactive_recommendation"+def _ask_user_answer_request_id(params: dict[str, Any], fallback: str) -> str:+ rid = str(params.get("request_id") or "").strip()+ if isinstance(rid, str):+ matched = re.search(r"^(?P<base>.+)#\d+$", rid)+ if matched and matched.group("base").strip():+ rid = matched.group("base").strip()+ return rid or str(fallback or "").strip()++def _history_media_string(item: dict[str, Any], *keys: str) -> str | None:for key in keys:value = item.get(key)@@ -1110,6 +1119,40 @@ class JiuWenSwarm:kwargs.update(self._history_kwargs())append_history_record(**kwargs)+ def _append_ask_user_answered_history(+ self,+ *,+ request: AgentRequest,+ session_id: str,+ ) -> None:+ """Record HITL resume so refresh does not revive an already-answered card."""+ params = request.params if isinstance(request.params, dict) else {}+ answers = params.get("answers")+ status = params.get("status")+ has_answers = isinstance(answers, list) and bool(answers)+ has_status = isinstance(status, str) and bool(status.strip())+ if not has_answers and not has_status:+ return+ rid = _ask_user_answer_request_id(params, request.request_id)+ if not rid:+ return+ extra: dict[str, Any] = {"request_id": rid}+ source = str(params.get("source") or "").strip()+ if source:+ extra["source"] = source+ extra["status"] = str(status).strip() if has_status else "answered"+ self._append_history_record(+ session_id=session_id,+ request_id=rid,+ channel_id=request.channel_id,+ role="assistant",+ event_type="chat.ask_user_answered",+ content="",+ timestamp=time.time(),+ extra=extra,+ mode=params.get("mode", "unknown"),+ )+def _get_skilldev_service(self):"""懒初始化并返回 SkillDevService 实例.@@ -2587,6 +2630,8 @@ class JiuWenSwarm:channel_metadata=request.metadata,mode=request.params.get("mode", "unknown"),)+ else:+ self._append_ask_user_answered_history(request=request, session_id=session_id)logger.info("[JiuWenSwarm] 处理请求: request_id=%s channel_id=%s session_id=%s sdk=%s",@@ -2924,6 +2969,8 @@ class JiuWenSwarm:channel_metadata=request.metadata,mode=params_for_history.get("mode", "unknown"),)+ elif request.req_method != ReqMethod.COMMAND_GOAL:+ self._append_ask_user_answered_history(request=request, session_id=session_id)logger.info("[JiuWenSwarm] 处理流式请求: request_id=%s channel_id=%s session_id=%s sdk=%s",diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex d048d529aa..0a4ab01476 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -176,6 +176,12 @@ def _has_persistable_assistant_payload(or payload.get("metadata")or payload.get("usage_metadata"))+ # HITL cards have empty content; questions / expiry live in extras.+ if et == "chat.ask_user_question":+ questions = payload.get("questions")+ return isinstance(questions, list) and bool(questions)+ if et in {"chat.ask_user_question_expired", "chat.ask_user_answered"}:+ return True# Empty chat.final / chat.* status shells and other blank assistants: skip.if et.startswith("chat.") or et in {"", "chat.final"}:return Falsediff --git a/jiuwenswarm/server/wire_truncate.py b/jiuwenswarm/server/wire_truncate.pyindex 39c8f44576..3382f9a27f 100644--- a/jiuwenswarm/server/wire_truncate.py+++ b/jiuwenswarm/server/wire_truncate.py@@ -55,6 +55,9 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset("chat.tool_result","chat.usage_summary","chat.file",+ "chat.ask_user_question",+ "chat.ask_user_question_expired",+ "chat.ask_user_answered","team.message","context.compact_boundary","context.compact_summary",@@ -80,6 +83,17 @@ _HISTORY_COLLAPSE_KEEP_KEYS = {"is_goal_objective_message","is_goal_completed_message","evidence",+ # HITL cards: keep structured extras if the record has to be collapsed.+ "questions",+ "source",+ "agent_scope_id",+ "approval_schema",+ "evolution_meta",+ "plan_approval_kind",+ "plan_content",+ "plan_language",+ "skill_approval_card",+ "x-skill-approval-card",}_WORKFLOW_SNAPSHOT_KEEP_KEYS = {