@@ -847,6 +1425,8 @@ export function initSituationalCopilot({
${pinned ? `${escape(text("已置顶", "Pinned"))}` : ""}
- ${bodyContentHtml}
- ${exportNotice ? `
task_alt${escape(exportNotice)}
` : ""}
- ${exportError ? `
warning${escape(exportError)}
` : ""}
+
+ ${historyDrawerOpen
+ ? renderDrawerHtml()
+ : `
+ ${bodyContentHtml}
+ ${exportNotice ? `
task_alt${escape(exportNotice)}
` : ""}
+ ${exportError ? `
warning${escape(exportError)}
` : ""}
+
+
`}
${turns.length ? `
${focusTagsHtml}
` : ""}
${prompts.length ? `
@@ -907,9 +1495,17 @@ export function initSituationalCopilot({
if (msgContainer) {
if (scrollToBottom) {
scrollMessagesToBottom();
+ } else if (savedScrollBeforeDrawer !== null) {
+ msgContainer.scrollTop = savedScrollBeforeDrawer;
+ savedScrollBeforeDrawer = null;
} else if (prevScrollTop !== null) {
msgContainer.scrollTop = prevScrollTop;
}
+ lastMsgScrollTop = msgContainer.scrollTop || 0;
+ if (typeof msgContainer.addEventListener === "function") {
+ msgContainer.addEventListener("scroll", () => syncJumpLatestButton(msgContainer), { passive: true });
+ }
+ syncJumpLatestButton(msgContainer);
}
const tagScroller = panel.querySelector("[data-copilot-drag-scroll]");
@@ -959,7 +1555,7 @@ export function initSituationalCopilot({
}
let changed = false;
for (const t of turns) {
- if (t.status === "loading") {
+ if (t.status === "loading" || t.status === "streaming") {
t.status = "cancelled";
changed = true;
}
@@ -968,13 +1564,78 @@ export function initSituationalCopilot({
if (changed) render();
}
- async function askQuestion(question, { presetOverride = null } = {}) {
+ function applyTurnContextUpdate(turn, data) {
+ if (!data) return;
+ if (data.session_token) {
+ sessionToken = data.session_token;
+ }
+ if (data.context_state) {
+ ctx.domain = data.context_state.domain || ctx.domain;
+ ctx.selectedCodes = data.context_state.selected_codes || ctx.selectedCodes;
+ ctx.mode = data.context_state.mode || ctx.mode;
+ ctx.focusYear = data.context_state.focus_year ?? ctx.focusYear;
+ ctx.entityId = data.context_state.entity_id ?? ctx.entityId;
+ if (data.context_state.visible_layers) ctx.visibleLayers = data.context_state.visible_layers;
+ ctx.timeBasis = data.context_state.time_basis || ctx.timeBasis;
+ ctx.cutoffAt = data.context_state.cutoff_at ?? ctx.cutoffAt;
+ ctx.includeDrill = Boolean(data.context_state.include_drill);
+ }
+ if (data.domain) {
+ ctx.domain = data.domain;
+ turn.domain = data.domain;
+ }
+ if (data.view_spec !== undefined) turn.viewSpec = data.view_spec || null;
+ if (data.scene_spec !== undefined) turn.sceneSpec = data.scene_spec || null;
+ if (data.result_id || data.subject_key) {
+ turn.resultId = data.result_id || data.subject_key || ctx.resultId;
+ ctx.resultId = turn.resultId;
+ }
+ if (data.revision !== undefined && data.revision !== null) {
+ turn.revision = data.revision;
+ ctx.revision = data.revision;
+ }
+ if (data.evidence) {
+ turn.evidence = data.evidence;
+ ctx.evidence = { ...(ctx.evidence || {}), ...(turn.evidence || {}) };
+ }
+ if (data.provider) turn.provider = data.provider;
+ if (data.model) turn.model = data.model;
+ if (typeof data.conversation_summary === "string") {
+ conversationSummary = data.conversation_summary;
+ }
+ if (data.compacted) {
+ compactedCount += 1;
+ }
+ }
+
+ function syncSceneEffectsForTurn(turn, data) {
+ if (turn.sceneSpec) {
+ onApplySceneSpec?.(turn.sceneSpec);
+ if (turn.sceneSpec.auto_play_presentation && turn.sceneSpec.presentation_key) {
+ onPlayPresentation?.(turn.sceneSpec.presentation_key);
+ }
+ }
+ const highlights = turn.sceneSpec?.highlight_entities || data?.reply?.highlight_entities || [];
+ if (Array.isArray(highlights) && highlights.length && !turn.sceneSpec?.auto_play_presentation) {
+ onHighlightEntities?.(highlights);
+ }
+ }
+
+ async function askQuestion(question, { presetOverride = null, newsContextOverride = undefined } = {}) {
const trimmed = String(question || "").trim();
if (trimmed.length < 2) return;
focusTagOverridden = false;
+ historyDrawerOpen = false;
+ autoRestoreBlocked = true;
onPreemptStage?.("user_investigation");
inlinePinnedPreviewId = null;
+ const priorHistoryPayload = buildTurnHistoryPayload(turns, { maxMessages: 24 });
+ const pinnedSummariesPayload = pinnedItems
+ .map((p) => `${p.shortLabel}: ${p.title || ""}`.trim())
+ .filter(Boolean)
+ .slice(0, 8);
+
if (activeRunId) {
const prevRunId = activeRunId;
void fetchImpl(`${RUNS_API}/${encodeURIComponent(prevRunId)}/cancel`, {
@@ -997,13 +1658,24 @@ export function initSituationalCopilot({
const inputEl = panel.querySelector('input[name="question"]');
if (inputEl) inputEl.value = "";
+ const activeNewsContext = newsContextOverride !== undefined ? newsContextOverride : ctx.newsContext;
const turn = {
id: `turn-${++turnCounter}`,
runId: clientRunId,
domain: ctx.domain || "compute",
question: trimmed,
status: "loading",
+ stageText: sessionId
+ ? text("正在连接 AI 参谋并核验上下文…", "Connecting AI copilot and verifying telemetry…")
+ : text("正在建立会话上下文…", "Creating session context…"),
+ stageBadge: "",
reply: null,
+ rawText: "",
+ rawReasoning: "",
+ provider: null,
+ model: null,
+ generationMode: null,
+ thinkingUserToggled: null,
viewSpec: null,
sceneSpec: null,
resultId: ctx.resultId,
@@ -1013,6 +1685,7 @@ export function initSituationalCopilot({
activeEvidenceId: null,
matrixModeOverride: null,
collapsedBlocks: {},
+ errorIcon: "error",
errorText: "",
};
turns.push(turn);
@@ -1021,31 +1694,260 @@ export function initSituationalCopilot({
}
render({ scrollToBottom: true });
+ let streamRenderTimer = null;
+ let slowHintTimer = null;
+ let streamAutoFollow = true;
+ const clearStreamRenderTimer = () => {
+ if (streamRenderTimer !== null) {
+ clearTimeout(streamRenderTimer);
+ streamRenderTimer = null;
+ }
+ };
+ const clearSlowHintTimer = () => {
+ if (slowHintTimer !== null) {
+ clearTimeout(slowHintTimer);
+ slowHintTimer = null;
+ }
+ };
+ const isNearBottom = () => {
+ const msgBox = panel.querySelector(".situational-copilot__messages");
+ if (!msgBox || msgBox.clientHeight <= 0) return true;
+ const remaining = msgBox.scrollHeight - msgBox.scrollTop - msgBox.clientHeight;
+ if (msgBox.scrollTop < lastMsgScrollTop - 2 && remaining > 16) {
+ streamAutoFollow = false;
+ } else if (remaining <= 16) {
+ streamAutoFollow = true;
+ }
+ return streamAutoFollow && remaining <= 64;
+ };
+ const msgContainerForStream = panel.querySelector?.(".situational-copilot__messages");
+ const onStreamContainerScroll = () => {
+ if (!msgContainerForStream) return;
+ const remaining = msgContainerForStream.scrollHeight - msgContainerForStream.scrollTop - msgContainerForStream.clientHeight;
+ if (msgContainerForStream.scrollTop < lastMsgScrollTop - 2 && remaining > 16) {
+ streamAutoFollow = false;
+ } else if (remaining <= 16) {
+ streamAutoFollow = true;
+ }
+ lastMsgScrollTop = msgContainerForStream.scrollTop;
+ };
+ if (typeof msgContainerForStream?.addEventListener === "function") {
+ msgContainerForStream.addEventListener("scroll", onStreamContainerScroll, { passive: true });
+ }
+ const setStage = (nextStageText, nextStageBadge = "") => {
+ if (myEpoch !== requestEpoch || turn.status !== "loading" || !nextStageText) return;
+ if (turn.stageText === nextStageText && turn.stageBadge === nextStageBadge) return;
+ turn.stageText = nextStageText;
+ turn.stageBadge = nextStageBadge;
+ const follow = isNearBottom();
+ if (!patchStreamingTurnInPlace(turn, follow)) {
+ render({ scrollToBottom: follow });
+ }
+ };
+ const armSlowHintTimer = (activeBadge = "") => {
+ clearSlowHintTimer();
+ if (timeouts.slowHintMs > 0) {
+ slowHintTimer = setTimeout(() => {
+ slowHintTimer = null;
+ setStage(
+ text(
+ "服务端响应较慢,仍在等待返回(可点击停止)…",
+ "Server response is slow, still waiting (click Stop to cancel)…",
+ ),
+ activeBadge,
+ );
+ }, timeouts.slowHintMs);
+ }
+ };
+ const scheduleStreamRender = () => {
+ if (streamRenderTimer !== null) return;
+ streamRenderTimer = setTimeout(() => {
+ streamRenderTimer = null;
+ if (myEpoch !== requestEpoch) return;
+ const follow = isNearBottom();
+ if (!patchStreamingTurnInPlace(turn, follow)) {
+ render({ scrollToBottom: follow });
+ }
+ }, 45);
+ };
+
+ const maxRetries = Math.max(0, Number(timeouts.maxRetries ?? 0));
+ let retriesAttempted = 0;
+
try {
- const sid = await ensureSession();
+ armSlowHintTimer();
+ if (hydratePromise) {
+ await hydratePromise;
+ if (myEpoch !== requestEpoch) return;
+ }
+ const sid = await ensureSession(signal);
if (myEpoch !== requestEpoch) return;
+ setStage(text("正在连接 AI 参谋并核验上下文…", "Connecting AI copilot and verifying telemetry…"), "");
+
+ const memoryNoteTextsPayload = memoryNotes.map((n) => n.text).filter(Boolean).slice(0, 12);
+
+ const legacyRequestPayload = {
+ run_id: clientRunId,
+ question: trimmed,
+ domain: ctx.domain || null,
+ selected_codes: ctx.selectedCodes || null,
+ mode: ctx.mode || null,
+ focus_year: Number.isFinite(ctx.focusYear) ? ctx.focusYear : null,
+ entity_id: ctx.entityId || null,
+ visible_layers: ctx.visibleLayers || {},
+ time_basis: ctx.timeBasis || "retrospective",
+ cutoff_at: ctx.cutoffAt || null,
+ include_drill: ctx.includeDrill ?? null,
+ preset: presetOverride || null,
+ prefer_llm: presetOverride ? false : "auto",
+ ...(activeNewsContext ? { news_context: activeNewsContext } : {}),
+ };
+ const streamRequestPayload = {
+ ...legacyRequestPayload,
+ ...(priorHistoryPayload.length ? { history: priorHistoryPayload } : {}),
+ ...(conversationSummary ? { conversation_summary: conversationSummary } : {}),
+ ...(memoryNoteTextsPayload.length ? { memory_notes: memoryNoteTextsPayload } : {}),
+ ...(pinnedSummariesPayload.length ? { pinned_summaries: pinnedSummariesPayload } : {}),
+ };
+ const legacyRequestBody = JSON.stringify(legacyRequestPayload);
+ const streamRequestBody = JSON.stringify(streamRequestPayload);
+
+ let res = null;
+ let streamUnsupported = Boolean(presetOverride);
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
+ const currentRetryBadge = attempt > 0
+ ? text(`重试 ${attempt}/${maxRetries}`, `Retry ${attempt}/${maxRetries}`)
+ : "";
+ armSlowHintTimer(currentRetryBadge);
+ try {
+ let attemptRes = null;
+ if (!streamUnsupported) {
+ attemptRes = await fetchWithTimeout(
+ `${SESSIONS_API}/${encodeURIComponent(sid)}/turns/stream`,
+ {
+ method: "POST",
+ headers: { ...buildRequestHeaders(true), Accept: "text/event-stream" },
+ signal,
+ body: streamRequestBody,
+ },
+ timeouts.streamMs,
+ );
+ if (attemptRes.status === 404 || attemptRes.status === 405) {
+ void attemptRes.body?.cancel?.().catch?.(() => {});
+ attemptRes = null;
+ streamUnsupported = true;
+ setStage(
+ text(
+ "当前服务端不支持流式输出,正切换标准模式获取结果…",
+ "Streaming endpoint unavailable on server, switching to standard mode…",
+ ),
+ currentRetryBadge,
+ );
+ }
+ }
+ if (!attemptRes) {
+ attemptRes = await fetchWithTimeout(
+ `${SESSIONS_API}/${encodeURIComponent(sid)}/turns`,
+ {
+ method: "POST",
+ headers: buildRequestHeaders(true),
+ signal,
+ body: legacyRequestBody,
+ },
+ timeouts.turnMs,
+ );
+ }
+ if (!attemptRes.ok) {
+ const httpErr = new Error(`HTTP ${attemptRes.status}`);
+ httpErr.status = attemptRes.status;
+ throw httpErr;
+ }
+ res = attemptRes;
+ break;
+ } catch (attemptErr) {
+ clearSlowHintTimer();
+ if (myEpoch !== requestEpoch || signal.aborted || attemptErr?.name === "AbortError") {
+ throw attemptErr;
+ }
+ if (attempt < maxRetries && isRetryableError(attemptErr)) {
+ retriesAttempted = attempt + 1;
+ const retryStage = describeRetryStage(attemptErr, retriesAttempted, maxRetries);
+ setStage(retryStage.label, retryStage.badge);
+ await sleepWithAbort((timeouts.retryDelayMs || 0) * retriesAttempted, signal);
+ continue;
+ }
+ if (attemptErr && typeof attemptErr === "object") {
+ attemptErr.retriesAttempted = retriesAttempted;
+ attemptErr.maxRetries = maxRetries;
+ }
+ throw attemptErr;
+ }
+ }
+ clearSlowHintTimer();
+
+ const contentType = String(res.headers?.get?.("content-type") || "").toLowerCase();
+ if (contentType.includes("text/event-stream") && res.body?.getReader) {
+ turn.status = "streaming";
+ render({ scrollToBottom: true });
+ await consumeCopilotStream(
+ res,
+ {
+ onMeta: (meta) => {
+ if (myEpoch !== requestEpoch) return;
+ activeRunId = meta.run_id || clientRunId;
+ turn.runId = meta.run_id || clientRunId;
+ applyTurnContextUpdate(turn, meta);
+ syncSceneEffectsForTurn(turn, meta);
+ render({ scrollToBottom: isNearBottom() });
+ },
+ onReasoningDelta: (delta) => {
+ if (myEpoch !== requestEpoch) return;
+ turn.rawReasoning += delta;
+ scheduleStreamRender();
+ },
+ onTextDelta: (delta) => {
+ if (myEpoch !== requestEpoch) return;
+ turn.rawText += delta;
+ scheduleStreamRender();
+ },
+ onDone: (done) => {
+ if (myEpoch !== requestEpoch) return;
+ clearStreamRenderTimer();
+ turn.status = "done";
+ turn.generationMode = done.generation_mode || "llm_verified";
+ turn.zeroToken = done.zero_token !== false;
+ if (done.provider !== undefined) turn.provider = done.provider;
+ if (done.model !== undefined) turn.model = done.model;
+ if (typeof done.conversation_summary === "string") {
+ conversationSummary = done.conversation_summary;
+ }
+ if (done.compacted) {
+ compactedCount += 1;
+ }
+ const finalMarkdown = done.answer_markdown || turn.rawText;
+ if (done.reasoning_markdown && !turn.rawReasoning) {
+ turn.rawReasoning = done.reasoning_markdown;
+ }
+ turn.rawText = finalMarkdown;
+ turn.reply = {
+ answer_markdown: finalMarkdown,
+ evidence_ids: Object.keys(turn.evidence || {}),
+ };
+ },
+ },
+ { signal },
+ );
+ clearStreamRenderTimer();
+ if (myEpoch === requestEpoch && turn.status === "streaming") {
+ turn.status = "done";
+ turn.reply = {
+ answer_markdown: turn.rawText,
+ evidence_ids: Object.keys(turn.evidence || {}),
+ };
+ }
+ return;
+ }
- const res = await fetchImpl(`${SESSIONS_API}/${encodeURIComponent(sid)}/turns`, {
- method: "POST",
- headers: buildRequestHeaders(true),
- signal,
- body: JSON.stringify({
- run_id: clientRunId,
- question: trimmed,
- domain: ctx.domain || null,
- selected_codes: ctx.selectedCodes || null,
- mode: ctx.mode || null,
- focus_year: Number.isFinite(ctx.focusYear) ? ctx.focusYear : null,
- entity_id: ctx.entityId || null,
- visible_layers: ctx.visibleLayers || {},
- time_basis: ctx.timeBasis || "retrospective",
- cutoff_at: ctx.cutoffAt || null,
- include_drill: ctx.includeDrill ?? null,
- preset: presetOverride || null,
- prefer_llm: presetOverride ? false : "auto",
- }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data?.session_token) {
sessionToken = data.session_token;
@@ -1071,57 +1973,52 @@ export function initSituationalCopilot({
turn.runId = data.run_id || clientRunId;
turn.status = "done";
turn.reply = data.reply || null;
- turn.viewSpec = data.view_spec || null;
- turn.sceneSpec = data.scene_spec || null;
- turn.resultId = data.result_id || data.subject_key || ctx.resultId;
- turn.revision = data.revision ?? ctx.revision;
+ turn.rawText = data.reply?.answer_markdown || "";
+ turn.generationMode = data.generation_mode || null;
+ turn.provider = data.llm_usage?.provider || null;
+ turn.model = data.llm_usage?.model || data.model || null;
turn.zeroToken = data.zero_token !== false;
- turn.evidence = data.evidence || {};
+ applyTurnContextUpdate(turn, data);
turn.activeEvidenceId = null;
-
- if (data.context_state) {
- ctx.domain = data.context_state.domain || ctx.domain;
- ctx.selectedCodes = data.context_state.selected_codes || ctx.selectedCodes;
- ctx.mode = data.context_state.mode || ctx.mode;
- ctx.focusYear = data.context_state.focus_year ?? ctx.focusYear;
- ctx.entityId = data.context_state.entity_id ?? ctx.entityId;
- if (data.context_state.visible_layers) ctx.visibleLayers = data.context_state.visible_layers;
- ctx.timeBasis = data.context_state.time_basis || ctx.timeBasis;
- ctx.cutoffAt = data.context_state.cutoff_at ?? ctx.cutoffAt;
- ctx.includeDrill = Boolean(data.context_state.include_drill);
- }
- if (data.domain) {
- ctx.domain = data.domain;
- turn.domain = data.domain;
- }
- ctx.resultId = turn.resultId;
- ctx.revision = turn.revision;
- ctx.evidence = { ...(ctx.evidence || {}), ...(turn.evidence || {}) };
-
- if (turn.sceneSpec) {
- onApplySceneSpec?.(turn.sceneSpec);
- if (turn.sceneSpec.auto_play_presentation && turn.sceneSpec.presentation_key) {
- onPlayPresentation?.(turn.sceneSpec.presentation_key);
- }
- }
- const highlights = turn.sceneSpec?.highlight_entities || data.reply?.highlight_entities || [];
- if (Array.isArray(highlights) && highlights.length && !turn.sceneSpec?.auto_play_presentation) {
- onHighlightEntities?.(highlights);
- }
+ syncSceneEffectsForTurn(turn, data);
} catch (err) {
+ clearSlowHintTimer();
+ clearStreamRenderTimer();
if (myEpoch !== requestEpoch || err?.name === "AbortError") {
- if (turn.status === "loading") {
+ if (turn.status === "loading" || turn.status === "streaming") {
turn.status = "cancelled";
}
return;
}
+ if (turn.rawText && err?.partial) {
+ turn.status = "done";
+ turn.reply = { answer_markdown: turn.rawText, evidence_ids: Object.keys(turn.evidence || {}) };
+ exportError = text("流式响应意外中断,已保留已生成内容。", "Stream interrupted; partial output preserved.");
+ return;
+ }
+ if (err?.status === 401) {
+ sessionId = null;
+ sessionToken = null;
+ }
+ const errInfo = classifyRequestError(err, {
+ retriesAttempted: err?.retriesAttempted ?? retriesAttempted,
+ maxRetries,
+ });
turn.status = "error";
- turn.errorText = text("工作台取证请求暂不可用,请稍后重试。", "Workbench turn unavailable. Please retry.");
+ turn.errorIcon = errInfo.icon;
+ turn.errorText = errInfo.text;
} finally {
+ clearSlowHintTimer();
+ clearStreamRenderTimer();
+ if (typeof msgContainerForStream?.removeEventListener === "function") {
+ msgContainerForStream.removeEventListener("scroll", onStreamContainerScroll);
+ }
if (myEpoch === requestEpoch) {
+ const shouldScrollBottom = isNearBottom();
activeRunId = null;
loading = false;
- render({ scrollToBottom: true });
+ render({ scrollToBottom: shouldScrollBottom });
+ void persistCurrentSession();
}
}
}
@@ -1330,6 +2227,74 @@ export function initSituationalCopilot({
} else if (action === "toggle-collapse") {
collapsed = !collapsed;
render();
+ } else if (action === "new-session") {
+ void startNewSession();
+ } else if (action === "toggle-history") {
+ if (!historyDrawerOpen) {
+ savedScrollBeforeDrawer = panel.querySelector(".situational-copilot__messages")?.scrollTop ?? null;
+ historyDrawerOpen = true;
+ collapsed = false;
+ render();
+ void refreshStoreCache().then(() => {
+ if (!panel.hidden && historyDrawerOpen) render();
+ });
+ } else {
+ historyDrawerOpen = false;
+ render();
+ }
+ } else if (action === "open-memory") {
+ savedScrollBeforeDrawer = panel.querySelector(".situational-copilot__messages")?.scrollTop ?? null;
+ historyDrawerOpen = true;
+ drawerTab = "memory";
+ collapsed = false;
+ render();
+ void refreshStoreCache().then(() => {
+ if (!panel.hidden && historyDrawerOpen) render();
+ });
+ } else if (action === "jump-latest") {
+ jumpMessagesToLatest();
+ }
+ return;
+ }
+
+ const drawerTabBtn = event.target.closest("[data-copilot-drawer-tab]");
+ if (drawerTabBtn) {
+ drawerTab = drawerTabBtn.dataset.copilotDrawerTab === "memory" ? "memory" : "history";
+ render();
+ return;
+ }
+
+ const loadSessionBtn = event.target.closest("[data-copilot-load-session]");
+ if (loadSessionBtn) {
+ void switchToSavedSession(loadSessionBtn.dataset.copilotLoadSession);
+ return;
+ }
+
+ const deleteSessionBtn = event.target.closest("[data-copilot-delete-session]");
+ if (deleteSessionBtn) {
+ void deleteSavedSession(deleteSessionBtn.dataset.copilotDeleteSession);
+ return;
+ }
+
+ if (event.target.closest("[data-copilot-clear-summary]")) {
+ conversationSummary = "";
+ compactedCount = 0;
+ render();
+ void persistCurrentSession();
+ return;
+ }
+
+ const deleteMemoryBtn = event.target.closest("[data-copilot-delete-memory]");
+ if (deleteMemoryBtn) {
+ void removeMemoryNote(deleteMemoryBtn.dataset.copilotDeleteMemory);
+ return;
+ }
+
+ const retryTurnBtn = event.target.closest("[data-copilot-retry-turn]");
+ if (retryTurnBtn) {
+ const targetTurn = turns.find((t) => t.id === retryTurnBtn.dataset.copilotRetryTurn);
+ if (targetTurn?.question) {
+ void askQuestion(targetTurn.question);
}
return;
}
@@ -1425,6 +2390,25 @@ export function initSituationalCopilot({
return;
}
+ const thinkToggleBtn = event.target.closest("[data-copilot-toggle-thinking]");
+ if (thinkToggleBtn) {
+ const tid = thinkToggleBtn.dataset.copilotToggleThinking;
+ const targetTurn = turns.find((item) => item.id === tid);
+ if (targetTurn) {
+ const parts = splitCopilotResponse(
+ targetTurn.rawText || targetTurn.reply?.answer_markdown || "",
+ targetTurn.rawReasoning || "",
+ );
+ const currentlyActive = targetTurn.status === "streaming" && (parts.reasoningActive || (Boolean(parts.reasoning) && !parts.markdown));
+ const currentlyOpen = targetTurn.thinkingUserToggled !== null
+ ? Boolean(targetTurn.thinkingUserToggled)
+ : Boolean(currentlyActive);
+ targetTurn.thinkingUserToggled = !currentlyOpen;
+ render();
+ }
+ return;
+ }
+
const focusTagBtn = event.target.closest("[data-copilot-focus-tag]");
if (focusTagBtn) {
if (Date.now() < suppressFocusTagClickUntil) return;
@@ -1491,6 +2475,16 @@ export function initSituationalCopilot({
});
panel.addEventListener("submit", (event) => {
+ if (event.target.matches("[data-copilot-memory-form]")) {
+ event.preventDefault();
+ const memInput = event.target.querySelector('input[name="memoryNote"]');
+ const val = memInput?.value || "";
+ if (val.trim()) {
+ if (memInput) memInput.value = "";
+ void addMemoryNoteText(val);
+ }
+ return;
+ }
if (!event.target.matches("[data-copilot-form]")) return;
event.preventDefault();
const input = event.target.querySelector('input[name="question"]');
@@ -1521,6 +2515,9 @@ export function initSituationalCopilot({
const prevDomain = ctx.domain;
const prevEntity = ctx.entityId;
const nextDomain = incomingContext.domain ?? prevDomain;
+ if (incomingContext.newsContext === undefined && !preserveActiveContext && nextDomain !== "news") {
+ incomingContext.newsContext = null;
+ }
const entityChanged = Boolean(incomingContext.entityId && prevEntity !== incomingContext.entityId);
const keepSessionContext = Boolean(preserveActiveContext)
&& turns.length > 0
@@ -1542,10 +2539,22 @@ export function initSituationalCopilot({
|| (ctx.domain === "bgp" && prevEntity !== ctx.entityId)
|| (!keepSessionContext && entityChanged)
) {
+ if (turns.some((t) => t.status === "done" || t.status === "error" || t.status === "cancelled")) {
+ void persistCurrentSession({ markActive: false });
+ }
cancelActiveRun();
+ localSessionId = makeLocalSessionId();
+ localSessionCreatedAt = Date.now();
sessionId = null;
+ sessionToken = null;
turns = [];
+ conversationSummary = "";
+ compactedCount = 0;
}
+ autoRestoreBlocked = Boolean(
+ nextContext.initialQuestion || incomingContext.entityId || incomingContext.newsContext,
+ );
+ historyDrawerOpen = false;
exportNotice = "";
exportError = "";
collapsed = false;
@@ -1554,6 +2563,7 @@ export function initSituationalCopilot({
onOpenStateChange?.(true);
focusStack?.focus(panel, { source: "user" });
render({ scrollToBottom: true });
+ void hydrateStoreIfNeeded();
if (nextContext.initialQuestion) {
void askQuestion(nextContext.initialQuestion);
} else if (!turns.length && nextContext.autoAsk !== false) {
@@ -1564,6 +2574,9 @@ export function initSituationalCopilot({
ask(question, opts) {
return askQuestion(question, opts);
},
+ newSession() {
+ return startNewSession();
+ },
cancelActiveRun,
close() {
cancelActiveRun();
@@ -1582,12 +2595,17 @@ export function initSituationalCopilot({
getState() {
return {
sessionId,
+ localSessionId,
activeRunId,
loading,
domain: ctx.domain,
pinnedCount: pinnedItems.length,
dualSlotActive: !pinnedSlot.hidden,
turnsCount: turns.length,
+ savedSessionsCount: savedSessions.length,
+ memoryNotesCount: memoryNotes.length,
+ hasCompactedSummary: Boolean(conversationSummary),
+ historyDrawerOpen,
};
},
destroy() {
diff --git a/frontend/public/earth/js/situational-copilot.test.js b/frontend/public/earth/js/situational-copilot.test.js
index b582e089..25b822db 100644
--- a/frontend/public/earth/js/situational-copilot.test.js
+++ b/frontend/public/earth/js/situational-copilot.test.js
@@ -1,5 +1,6 @@
import { describe, expect, it } from "bun:test";
import { createTimeBasisMenu } from "./hud-select-menu.js";
+import { createCopilotStore } from "./copilot-store.js";
import {
initSituationalCopilot,
normalizeCopilotMarkdown,
@@ -478,7 +479,7 @@ describe("Dynamic Workbench Slot Budget & Late-Response Isolation", () => {
const panelEl = root.children[0];
expect(panelEl.innerHTML).toContain('');
expect(panelEl.innerHTML).toContain("实际模型合成说明");
- expect(panelEl.innerHTML).toContain("LLM 核验合成");
+ expect(panelEl.innerHTML).toContain("答案由 AI 参谋提供");
// Reopening with preserveActiveContext keeps conversation-selected participants & mode intact
await copilot.ask("只看中美智算");
@@ -1007,4 +1008,628 @@ describe("Shared HUD Select Menu for Time Basis", () => {
globalThis.window = prevWin;
}
});
+
+ it("streams SSE thinking process + answer with model badge and forwards newsContext", async () => {
+ const prevDoc = globalThis.document;
+ const prevWin = globalThis.window;
+ const { root, mockDoc, mockWin } = createMockDomEnv();
+ globalThis.document = mockDoc;
+ globalThis.window = mockWin;
+
+ const capturedBodies = [];
+ const encoder = new TextEncoder();
+
+ const mockFetch = async (url, opts = {}) => {
+ if (String(url).endsWith("/sessions") && opts.method === "POST") {
+ return { ok: true, json: async () => ({ session_id: "sess-stream-1" }) };
+ }
+ if (String(url).includes("/turns/stream")) {
+ capturedBodies.push(JSON.parse(opts.body));
+ const frames = [
+ 'event: meta\ndata: {"run_id":"run-s1","domain":"news","provider":"minimax","model":"MiniMax-M2.7","ai_enabled":true,"evidence":{"ev-news-focus":{"id":"ev-news-focus","title":"测试新闻"}}}\n\n',
+ 'event: reasoning\ndata: {"delta":"思考过程第一行"}\n\n',
+ 'event: text\ndata: {"delta":"### AI 新闻研判\\n\\n- **核心结论**:影响可控。"}\n\n',
+ 'event: done\ndata: {"generation_mode":"llm_verified","zero_token":false,"provider":"minimax","model":"MiniMax-M2.7"}\n\n',
+ ];
+ let idx = 0;
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers({ "content-type": "text/event-stream" }),
+ body: {
+ getReader() {
+ return {
+ async read() {
+ if (idx >= frames.length) return { done: true, value: undefined };
+ return { done: false, value: encoder.encode(frames[idx++]) };
+ },
+ async cancel() {},
+ releaseLock() {},
+ };
+ },
+ },
+ };
+ }
+ return { ok: true, json: async () => ({}) };
+ };
+
+ try {
+ const copilot = initSituationalCopilot({
+ rootParent: root,
+ focusStack: { register() {}, focus() {}, setPinned() {} },
+ fetchImpl: mockFetch,
+ });
+
+ copilot.open({
+ domain: "news",
+ entityId: "news-42",
+ newsContext: { id: "news-42", title: "测试新闻标题", summary: "测试摘要", source: "NPR" },
+ autoAsk: false,
+ });
+
+ await copilot.ask("请分析这条新闻");
+ const panelEl = root.children[0];
+ expect(capturedBodies).toHaveLength(1);
+ expect(capturedBodies[0].domain).toBe("news");
+ expect(capturedBodies[0].news_context?.id).toBe("news-42");
+ expect(panelEl.innerHTML).toContain("答案由 MiniMax-M2.7 提供");
+ expect(panelEl.innerHTML).toContain("copilot-model-badge--ai");
+ expect(panelEl.innerHTML).not.toContain("auto_awesome");
+ expect(panelEl.innerHTML).toContain("copilot-thinking");
+ expect(panelEl.innerHTML).toContain("AI 新闻研判");
+ expect(panelEl.innerHTML).toContain("核心结论");
+
+ // Thinking auto-collapses when complete; toggling expands thought process body cleanly
+ expect(panelEl.innerHTML).not.toContain("思考过程第一行");
+ panelEl.dispatchClick({
+ selector: "[data-copilot-toggle-thinking]",
+ node: { dataset: { copilotToggleThinking: "turn-1" } },
+ });
+ expect(panelEl.innerHTML).toContain("思考过程第一行");
+
+ copilot.destroy();
+ } finally {
+ globalThis.document = prevDoc;
+ globalThis.window = prevWin;
+ }
+ });
+
+ it("surfaces stage feedback, bounded retries (x/N), categorized errors, and one-click retry action", async () => {
+ const prevDoc = globalThis.document;
+ const prevWin = globalThis.window;
+ const { root, mockDoc, mockWin } = createMockDomEnv();
+ globalThis.document = mockDoc;
+ globalThis.window = mockWin;
+
+ try {
+ // 1) Slow response hint + 404 stream fallback stage feedback before /turns succeeds (404 does not count as retry)
+ const observedStages = [];
+ let releaseTurn;
+ const slowFallbackFetch = async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-fb-1" }) };
+ }
+ if (String(url).includes("/turns/stream")) {
+ observedStages.push(root.children[0].innerHTML);
+ return { ok: false, status: 404, body: { cancel: async () => {} } };
+ }
+ observedStages.push(root.children[0].innerHTML);
+ return await new Promise((resolve) => {
+ releaseTurn = resolve;
+ });
+ };
+
+ const copilot = initSituationalCopilot({
+ rootParent: root,
+ fetchImpl: slowFallbackFetch,
+ requestTimeouts: { sessionMs: 200, streamMs: 200, turnMs: 500, slowHintMs: 12, maxRetries: 2, retryDelayMs: 5 },
+ });
+ copilot.open({ domain: "global", autoAsk: false });
+ const panelEl = root.children[0];
+ const pendingAsk = copilot.ask("测试阶段提示");
+ await new Promise((r) => setTimeout(r, 25));
+ expect(observedStages.some((html) => html.includes("正切换标准模式获取结果"))).toBe(true);
+ expect(panelEl.innerHTML).toContain("服务端响应较慢");
+ releaseTurn({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ session_id: "sess-fb-1",
+ run_id: "run-fb-1",
+ revision: 4,
+ zero_token: true,
+ reply: { answer_markdown: "### 降级完成" },
+ view_spec: { view_id: "v4", active_preset: "default", available_presets: [], headline: "总览", blocks: [] },
+ }),
+ });
+ await pendingAsk;
+ expect(panelEl.innerHTML).toContain('·Rev.4');
+ copilot.destroy();
+
+ // 2) Transient network error retries 1/2 -> 2/2 and fails after maxRetries, with clickable retry button
+ const envRetryFail = createMockDomEnv();
+ globalThis.document = envRetryFail.mockDoc;
+ globalThis.window = envRetryFail.mockWin;
+ let turnCallCount = 0;
+ const retrySnapshots = [];
+ const retryFailCopilot = initSituationalCopilot({
+ rootParent: envRetryFail.root,
+ requestTimeouts: { sessionMs: 200, streamMs: 200, turnMs: 200, slowHintMs: 0, maxRetries: 2, retryDelayMs: 8 },
+ fetchImpl: async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-rf-1" }) };
+ }
+ turnCallCount += 1;
+ if (turnCallCount > 1) {
+ retrySnapshots.push(envRetryFail.root.children[0].innerHTML);
+ }
+ if (turnCallCount <= 3) {
+ throw new TypeError("Failed to fetch");
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ session_id: "sess-rf-1",
+ run_id: "run-rf-ok",
+ zero_token: true,
+ reply: { answer_markdown: "### 手动重试成功" },
+ }),
+ };
+ },
+ });
+ retryFailCopilot.open({ domain: "global", autoAsk: false });
+ await retryFailCopilot.ask("测试连接重试失败");
+ expect(turnCallCount).toBe(3); // 1 initial + 2 retries
+ expect(retrySnapshots.some((h) => h.includes("重试 1/2"))).toBe(true);
+ expect(retrySnapshots.some((h) => h.includes("重试 2/2"))).toBe(true);
+ expect(envRetryFail.root.children[0].innerHTML).toContain("wifi_off");
+ expect(envRetryFail.root.children[0].innerHTML).toContain("重试 2/2 后仍无法连接态势服务");
+ expect(envRetryFail.root.children[0].innerHTML).toContain('data-copilot-retry-turn="turn-1"');
+ // Click manual retry button -> 4th call succeeds
+ envRetryFail.root.children[0].dispatchClick({
+ selector: "[data-copilot-retry-turn]",
+ node: { dataset: { copilotRetryTurn: "turn-1" } },
+ });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(turnCallCount).toBe(4);
+ expect(envRetryFail.root.children[0].innerHTML).toContain("手动重试成功");
+ retryFailCopilot.destroy();
+
+ // 3) Transient failure recovers automatically on retry 1/2
+ const envRecover = createMockDomEnv();
+ globalThis.document = envRecover.mockDoc;
+ globalThis.window = envRecover.mockWin;
+ let recoverCalls = 0;
+ const recoverCopilot = initSituationalCopilot({
+ rootParent: envRecover.root,
+ requestTimeouts: { sessionMs: 200, streamMs: 200, turnMs: 200, slowHintMs: 0, maxRetries: 2, retryDelayMs: 5 },
+ fetchImpl: async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-rec-1" }) };
+ }
+ recoverCalls += 1;
+ if (recoverCalls === 1) {
+ return { ok: false, status: 503 };
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ session_id: "sess-rec-1",
+ run_id: "run-rec-1",
+ zero_token: true,
+ reply: { answer_markdown: "### 重试恢复成功" },
+ }),
+ };
+ },
+ });
+ recoverCopilot.open({ domain: "global", autoAsk: false });
+ await recoverCopilot.ask("测试自动恢复");
+ expect(recoverCalls).toBe(2);
+ expect(envRecover.root.children[0].innerHTML).toContain("重试恢复成功");
+ recoverCopilot.destroy();
+
+ // 4) Timeout retries 1/2 -> 2/2 and fails with schedule icon
+ const env2 = createMockDomEnv();
+ globalThis.document = env2.mockDoc;
+ globalThis.window = env2.mockWin;
+ let timeoutCalls = 0;
+ const timeoutCopilot = initSituationalCopilot({
+ rootParent: env2.root,
+ requestTimeouts: { sessionMs: 15, streamMs: 15, turnMs: 15, slowHintMs: 0, maxRetries: 2, retryDelayMs: 5 },
+ fetchImpl: async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-to-1" }) };
+ }
+ timeoutCalls += 1;
+ return await new Promise(() => {});
+ },
+ });
+ timeoutCopilot.open({ domain: "global", autoAsk: false });
+ await timeoutCopilot.ask("测试超时");
+ expect(timeoutCalls).toBe(3);
+ expect(env2.root.children[0].innerHTML).toContain("schedule");
+ expect(env2.root.children[0].innerHTML).toContain("重试 2/2 后仍请求超时");
+ timeoutCopilot.destroy();
+
+ // 5) Non-retryable 429 & 401 (no retry, 1 call each), plus retryable 502 (3 calls)
+ for (const scenario of [
+ { status: 429, expectIcon: "bolt", expectText: "调用上限", expectCalls: 1, clearsSession: false },
+ { status: 401, expectIcon: "lock", expectText: "鉴权已失效", expectCalls: 1, clearsSession: true },
+ { status: 502, expectIcon: "cloud_off", expectText: "重试 2/2 后仍无法连接服务(HTTP 502)", expectCalls: 3, clearsSession: false },
+ ]) {
+ const envX = createMockDomEnv();
+ globalThis.document = envX.mockDoc;
+ globalThis.window = envX.mockWin;
+ let statusCalls = 0;
+ const errCopilot = initSituationalCopilot({
+ rootParent: envX.root,
+ requestTimeouts: { sessionMs: 200, streamMs: 200, turnMs: 200, slowHintMs: 0, maxRetries: 2, retryDelayMs: 5 },
+ fetchImpl: async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-err-1" }) };
+ }
+ statusCalls += 1;
+ return { ok: false, status: scenario.status };
+ },
+ });
+ errCopilot.open({ domain: "global", autoAsk: false });
+ await errCopilot.ask("测试分类错误");
+ expect(statusCalls).toBe(scenario.expectCalls);
+ expect(envX.root.children[0].innerHTML).toContain(scenario.expectIcon);
+ expect(envX.root.children[0].innerHTML).toContain(scenario.expectText);
+ if (scenario.clearsSession) {
+ expect(errCopilot.getState().sessionId).toBeNull();
+ }
+ errCopilot.destroy();
+ }
+ } finally {
+ globalThis.document = prevDoc;
+ globalThis.window = prevWin;
+ }
+ });
+
+ it("shows jump-to-latest button when scrolled above bottom and scrolls to bottom on click", async () => {
+ const prevDoc = globalThis.document;
+ const prevWin = globalThis.window;
+ const env = createMockDomEnv();
+ const panelListeners = new Map();
+ const msgListeners = new Map();
+ const jumpBtnStub = { hidden: true };
+ const msgBoxStub = {
+ scrollHeight: 900,
+ clientHeight: 320,
+ scrollTop: 80,
+ scrollToCalledWith: null,
+ addEventListener: (type, fn) => {
+ if (!msgListeners.has(type)) msgListeners.set(type, []);
+ msgListeners.get(type).push(fn);
+ },
+ querySelectorAll: () => [],
+ scrollTo(opts) {
+ this.scrollToCalledWith = opts;
+ this.scrollTop = opts.top;
+ },
+ };
+ const panelStub = {
+ tagName: "ASIDE",
+ id: "situational-copilot",
+ className: "",
+ hidden: false,
+ innerHTML: "",
+ dataset: {},
+ style: { setProperty() {} },
+ classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
+ append() {},
+ remove() {},
+ addEventListener(type, fn) {
+ if (!panelListeners.has(type)) panelListeners.set(type, []);
+ panelListeners.get(type).push(fn);
+ },
+ removeEventListener() {},
+ querySelector(sel) {
+ if (sel === ".situational-copilot__messages") return msgBoxStub;
+ if (sel === '[data-copilot-action="jump-latest"]') return jumpBtnStub;
+ return null;
+ },
+ querySelectorAll: () => [],
+ getBoundingClientRect: () => ({ top: 100, bottom: 980, left: 1200, right: 1900, width: 396, height: 556 }),
+ children: [],
+ };
+ let createdCount = 0;
+ const origCreate = env.mockDoc.createElement;
+ env.mockDoc.createElement = (tag) => (++createdCount === 1 ? panelStub : origCreate(tag));
+ globalThis.document = env.mockDoc;
+ globalThis.window = env.mockWin;
+
+ try {
+ const copilot = initSituationalCopilot({
+ rootParent: env.root,
+ fetchImpl: async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-jump-1" }) };
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ session_id: "sess-jump-1",
+ run_id: "run-jump-1",
+ zero_token: true,
+ reply: { answer_markdown: "长回复完成" },
+ }),
+ };
+ },
+ });
+ copilot.open({ domain: "global", autoAsk: false });
+ expect(panelStub.innerHTML).toContain('class="situational-copilot__stage"');
+ expect(panelStub.innerHTML).toContain('data-copilot-action="jump-latest"');
+
+ await copilot.ask("测试回到底部按钮");
+ // Simulate scrolling upward away from the latest message
+ msgBoxStub.scrollTop = 100;
+ for (const fn of msgListeners.get("scroll") || []) fn();
+ expect(jumpBtnStub.hidden).toBe(false);
+
+ // Click jump-latest -> smooth-scrolls to scrollHeight and hides button
+ const actionNode = { dataset: { copilotAction: "jump-latest" } };
+ for (const fn of panelListeners.get("click") || []) {
+ fn({ target: { closest: (sel) => (sel === "[data-copilot-action]" ? actionNode : null) } });
+ }
+ expect(msgBoxStub.scrollToCalledWith).toEqual({ top: 900, behavior: "smooth" });
+ expect(jumpBtnStub.hidden).toBe(true);
+
+ copilot.destroy();
+ } finally {
+ globalThis.document = prevDoc;
+ globalThis.window = prevWin;
+ }
+ });
+
+ it("persists sessions, restores across restarts, opens history/memory drawer, and sends multi-turn context only to /turns/stream", async () => {
+ const prevDoc = globalThis.document;
+ const prevWin = globalThis.window;
+ const sharedStore = createCopilotStore({ useIndexedDb: false });
+ await sharedStore.saveMemoryNotes([{ id: "m-init", text: "重点关注亚太海缆冗余" }]);
+
+ const capturedStreamPayloads = [];
+ const capturedLegacyPayloads = [];
+ const encoder = new TextEncoder();
+
+ const makeStreamMockFetch = ({ supportStream = true } = {}) => async (url, opts = {}) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, status: 200, json: async () => ({ session_id: "sess-mem-1" }) };
+ }
+ if (String(url).includes("/turns/stream")) {
+ capturedStreamPayloads.push(JSON.parse(opts.body));
+ if (!supportStream) {
+ return { ok: false, status: 404, body: { cancel: async () => {} } };
+ }
+ const q = JSON.parse(opts.body).question;
+ const frames = [
+ 'event: meta\ndata: {"run_id":"run-m1","domain":"global","provider":"minimax","model":"MiniMax-M2.7","compacted":true,"conversation_summary":"已压缩:讨论海缆冗余"}\n\n',
+ `event: text\ndata: ${JSON.stringify({ delta: `已结合记忆回答:${q}` })}\n\n`,
+ 'event: done\ndata: {"generation_mode":"llm_verified","zero_token":false,"provider":"minimax","model":"MiniMax-M2.7","compacted":true,"conversation_summary":"已压缩:讨论海缆冗余"}\n\n',
+ ];
+ let idx = 0;
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers({ "content-type": "text/event-stream" }),
+ body: {
+ getReader() {
+ return {
+ async read() {
+ if (idx >= frames.length) return { done: true, value: undefined };
+ return { done: false, value: encoder.encode(frames[idx++]) };
+ },
+ async cancel() {},
+ releaseLock() {},
+ };
+ },
+ },
+ };
+ }
+ if (String(url).includes("/turns")) {
+ capturedLegacyPayloads.push(JSON.parse(opts.body));
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ session_id: "sess-mem-1",
+ run_id: "run-leg-1",
+ zero_token: true,
+ reply: { answer_markdown: "标准模式兼容回答" },
+ }),
+ };
+ }
+ return { ok: true, status: 200, json: async () => ({}) };
+ };
+
+ try {
+ // Session 1 with 2 turns -> persisted + compacted chip displayed
+ const env1 = createMockDomEnv();
+ globalThis.document = env1.mockDoc;
+ globalThis.window = env1.mockWin;
+ const copilot1 = initSituationalCopilot({
+ rootParent: env1.root,
+ store: sharedStore,
+ fetchImpl: makeStreamMockFetch({ supportStream: true }),
+ });
+ copilot1.open({ domain: "global", autoAsk: false });
+ await copilot1.ask("分析亚太海缆第一轮");
+ await copilot1.ask("继续展开第二轮");
+ await new Promise((r) => setTimeout(r, 15));
+
+ expect(capturedStreamPayloads).toHaveLength(2);
+ expect(capturedStreamPayloads[0].memory_notes).toEqual(["重点关注亚太海缆冗余"]);
+ expect(capturedStreamPayloads[1].history).toEqual([
+ { role: "user", content: "分析亚太海缆第一轮" },
+ { role: "assistant", content: "已结合记忆回答:分析亚太海缆第一轮" },
+ ]);
+ expect(capturedStreamPayloads[1].conversation_summary).toBe("已压缩:讨论海缆冗余");
+ expect(env1.root.children[0].innerHTML).toContain("copilot-compacted-chip");
+ copilot1.destroy();
+
+ // Simulated client restart with a brand-new copilot instance sharing the same store
+ const env2 = createMockDomEnv();
+ globalThis.document = env2.mockDoc;
+ globalThis.window = env2.mockWin;
+ const copilot2 = initSituationalCopilot({
+ rootParent: env2.root,
+ store: sharedStore,
+ fetchImpl: makeStreamMockFetch({ supportStream: false }),
+ });
+ copilot2.open({ domain: "global", autoAsk: false });
+ await new Promise((r) => setTimeout(r, 15));
+
+ // Automatically restored the previous 2-turn conversation
+ expect(copilot2.getState().turnsCount).toBe(2);
+ const panel2 = env2.root.children[0];
+ expect(panel2.innerHTML).toContain("分析亚太海缆第一轮");
+ expect(panel2.innerHTML).toContain("已结合记忆回答:继续展开第二轮");
+
+ // Open history drawer & switch to memory tab -> verifies saved session and summary UI
+ panel2.dispatchClick({
+ selector: "[data-copilot-action]",
+ node: { dataset: { copilotAction: "toggle-history" } },
+ });
+ expect(panel2.innerHTML).toContain("copilot-drawer");
+ expect(panel2.innerHTML).toContain("分析亚太海缆第一轮");
+ panel2.dispatchClick({
+ selector: "[data-copilot-drawer-tab]",
+ node: { dataset: { copilotDrawerTab: "memory" } },
+ });
+ expect(panel2.innerHTML).toContain("已压缩:讨论海缆冗余");
+ expect(panel2.innerHTML).toContain("重点关注亚太海缆冗余");
+
+ // Start new conversation while keeping old session saved, then test legacy /turns fallback omits history
+ await copilot2.newSession();
+ expect(copilot2.getState().turnsCount).toBe(0);
+ await copilot2.ask("兼容旧后端第三问");
+ expect(capturedLegacyPayloads).toHaveLength(1);
+ expect(capturedLegacyPayloads[0].history).toBeUndefined();
+ expect(capturedLegacyPayloads[0].memory_notes).toBeUndefined();
+
+ const allSaved = await sharedStore.listSessions();
+ expect(allSaved.length).toBe(2);
+ copilot2.destroy();
+ } finally {
+ globalThis.document = prevDoc;
+ globalThis.window = prevWin;
+ }
+ });
+
+ it("preserves user scroll position during SSE streaming without snapping back to top", async () => {
+ const prevDoc = globalThis.document;
+ const prevWin = globalThis.window;
+ const env = createMockDomEnv();
+ const msgListeners = new Map();
+ const turnElStub = { innerHTML: "" };
+ const jumpBtnStub = { hidden: true };
+ const msgBoxStub = {
+ scrollHeight: 1600,
+ clientHeight: 320,
+ scrollTop: 1280,
+ addEventListener: (type, fn) => {
+ if (!msgListeners.has(type)) msgListeners.set(type, []);
+ msgListeners.get(type).push(fn);
+ },
+ removeEventListener: (type, fn) => {
+ const list = msgListeners.get(type) || [];
+ msgListeners.set(type, list.filter((item) => item !== fn));
+ },
+ querySelector: (sel) => (String(sel).startsWith("[data-turn=") ? turnElStub : null),
+ querySelectorAll: () => [],
+ };
+ const panelStub = {
+ tagName: "ASIDE",
+ id: "situational-copilot",
+ className: "",
+ hidden: false,
+ innerHTML: "",
+ dataset: {},
+ style: { setProperty() {} },
+ classList: { add() {}, remove() {}, toggle() {}, contains: () => false },
+ append() {},
+ remove() {},
+ addEventListener() {},
+ removeEventListener() {},
+ querySelector(sel) {
+ if (sel === ".situational-copilot__messages") return msgBoxStub;
+ if (sel === '[data-copilot-action="jump-latest"]') return jumpBtnStub;
+ return null;
+ },
+ querySelectorAll: () => [],
+ getBoundingClientRect: () => ({ top: 100, bottom: 980, left: 1200, right: 1900, width: 396, height: 556 }),
+ children: [],
+ };
+ let createdCount = 0;
+ const origCreateElement = env.mockDoc.createElement.bind(env.mockDoc);
+ env.mockDoc.createElement = (tag) => {
+ createdCount += 1;
+ return createdCount === 1 ? panelStub : origCreateElement(tag);
+ };
+ globalThis.document = env.mockDoc;
+ globalThis.window = env.mockWin;
+
+ let releaseSecondChunk;
+ const secondChunkGate = new Promise((r) => { releaseSecondChunk = r; });
+
+ const streamFetch = async (url) => {
+ if (String(url).endsWith("/sessions")) {
+ return { ok: true, json: async () => ({ session_id: "s-scroll", session_token: "tok-scroll" }) };
+ }
+ if (String(url).includes("/turns/stream")) {
+ const enc = new TextEncoder();
+ const stream = new ReadableStream({
+ async start(controller) {
+ controller.enqueue(enc.encode('event: meta\ndata: {"run_id":"r-scroll","model":"MiniMax-M3.1-Flash"}\n\n'));
+ controller.enqueue(enc.encode('event: text\ndata: {"delta":"第一段流式正文内容"}\n\n'));
+ await secondChunkGate;
+ controller.enqueue(enc.encode('event: text\ndata: {"delta":",继续输出更多内容"}\n\n'));
+ controller.enqueue(enc.encode('event: done\ndata: {"generation_mode":"llm_verified","zero_token":false,"model":"MiniMax-M3.1-Flash","answer_markdown":"第一段流式正文内容,继续输出更多内容"}\n\n'));
+ controller.close();
+ },
+ });
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers({ "content-type": "text/event-stream" }),
+ body: stream,
+ };
+ }
+ return { ok: true, json: async () => ({}) };
+ };
+
+ try {
+ const copilot = initSituationalCopilot({
+ rootParent: env.root,
+ fetchImpl: streamFetch,
+ });
+ copilot.open({ domain: "global", autoAsk: false });
+ const askPromise = copilot.ask("测试流式滚动位置保持");
+ await new Promise((r) => setTimeout(r, 80));
+
+ // User was at bottom on first delta -> followed to scrollHeight (1600)
+ expect(turnElStub.innerHTML).toContain("第一段流式正文内容");
+ expect(msgBoxStub.scrollTop).toBe(1600);
+
+ // User scrolls upward manually during SSE streaming
+ msgBoxStub.scrollTop = 360;
+ for (const fn of msgListeners.get("scroll") || []) fn();
+
+ releaseSecondChunk();
+ await askPromise;
+
+ expect(panelStub.innerHTML).toContain("答案由 MiniMax-M3.1-Flash 提供");
+ expect(msgBoxStub.scrollTop).toBe(360);
+ expect(jumpBtnStub.hidden).toBe(false);
+ copilot.destroy();
+ } finally {
+ globalThis.document = prevDoc;
+ globalThis.window = prevWin;
+ }
+ });
});
diff --git a/frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task b/frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task
new file mode 100644
index 00000000..09576a93
Binary files /dev/null and b/frontend/public/earth/vendor/mediapipe/pose_landmarker_lite.task differ
diff --git a/frontend/scripts/earth-runtime-plugin.mjs b/frontend/scripts/earth-runtime-plugin.mjs
index 11164e26..df9cb87e 100644
--- a/frontend/scripts/earth-runtime-plugin.mjs
+++ b/frontend/scripts/earth-runtime-plugin.mjs
@@ -1,11 +1,22 @@
-import { basename, join } from 'node:path'
+import { cpSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { basename, dirname, join, resolve } from 'node:path'
import { compileEarthRuntime } from './compile-earth-runtime.mjs'
+const MEDIAPIPE_MIME_TYPES = {
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.wasm': 'application/wasm',
+}
+
// Earth remains a standalone public page with its pinned import map. Bundle
// only project modules, retaining the /earth/js/ base for assets and workers.
export function earthRuntimePlugin(root) {
const earth = join(root, 'public/earth')
+ const require = createRequire(join(root, 'package.json'))
+ const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json'))
+ let outDir = 'dist'
let compilation = null
async function compile() {
@@ -19,6 +30,9 @@ export function earthRuntimePlugin(root) {
return {
name: 'earth-runtime',
+ configResolved(config) {
+ outDir = config.build?.outDir || 'dist'
+ },
configureServer(server) {
server.watcher.on('change', (file) => {
if (file.startsWith(earth) && (file.endsWith('.js') || file === join(earth, 'index.html'))) {
@@ -27,6 +41,24 @@ export function earthRuntimePlugin(root) {
})
server.middlewares.use(async (req, res, next) => {
const url = (req.url || '').split('?')[0]
+ if (url === '/earth/vendor/mediapipe/vision_bundle.mjs') {
+ const filePath = join(mediaPipePkgDir, 'vision_bundle.mjs')
+ if (!existsSync(filePath)) return next()
+ res.setHeader('Cache-Control', 'no-cache')
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8')
+ res.end(readFileSync(filePath))
+ return
+ }
+ if (url.startsWith('/earth/vendor/mediapipe/wasm/')) {
+ const relName = basename(url)
+ const filePath = join(mediaPipePkgDir, 'wasm', relName)
+ if (!relName || !existsSync(filePath)) return next()
+ const ext = relName.slice(relName.lastIndexOf('.'))
+ res.setHeader('Cache-Control', 'no-cache')
+ res.setHeader('Content-Type', MEDIAPIPE_MIME_TYPES[ext] || 'application/octet-stream')
+ res.end(readFileSync(filePath))
+ return
+ }
const isPage = url === '/earth/index.html' || url === '/earth/'
const isRuntime = /^\/earth\/js\/runtime-[\w-]+\.js$/.test(url)
if (!isPage && !isRuntime) return next()
@@ -60,5 +92,17 @@ export function earthRuntimePlugin(root) {
}
this.emitFile({ type: 'asset', fileName: 'earth/index.html', source: html })
},
+ closeBundle() {
+ const targetMediaPipeDir = resolve(root, outDir, 'earth/vendor/mediapipe')
+ mkdirSync(targetMediaPipeDir, { recursive: true })
+ const bundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs')
+ if (existsSync(bundleSrc)) {
+ cpSync(bundleSrc, join(targetMediaPipeDir, 'vision_bundle.mjs'))
+ }
+ const wasmSrcDir = join(mediaPipePkgDir, 'wasm')
+ if (existsSync(wasmSrcDir)) {
+ cpSync(wasmSrcDir, join(targetMediaPipeDir, 'wasm'), { recursive: true })
+ }
+ },
}
}
diff --git a/frontend/src/pages/Earth/Earth.tsx b/frontend/src/pages/Earth/Earth.tsx
index 18b2d6ce..494290cb 100644
--- a/frontend/src/pages/Earth/Earth.tsx
+++ b/frontend/src/pages/Earth/Earth.tsx
@@ -5,6 +5,7 @@ function Earth() {
)
diff --git a/pyproject.toml b/pyproject.toml
index a56ca6ce..0b4cb4b2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "planet"
-version = "0.79.2"
+version = "0.80.0"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
diff --git a/uv.lock b/uv.lock
index 4f529896..87213d0b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
-version = "0.79.2"
+version = "0.80.0"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },