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(web): 会话管理四项修复——历史页移除/切换跳闪/置顶持久化/MySQL 建表

jiangchenglin45364a8cbd61
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index aa3b32bdfc..219c371d8a 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -11,7 +11,6 @@ import { SkillPanel } from './components/SkillPanel';
import { AgentPanel } from './components/AgentPanel/index';
import { TeamPanel } from './components/TeamPanel';
import { SessionsPanel } from './components/SessionsPanel';
-import { HistoryPanel } from './components/HistoryPanel';
import CronPanel from './components/CronPanel';
import { ToolPanel } from './components/ToolPanel';
import { ConfigPanel } from './components/ConfigPanel';
@@ -262,6 +261,9 @@ async function saveShareImage(dataUrl: string, filename: string): Promise<boolea
return true;
}
+/** 切换会话时等待历史预载的上限:超过则放弃预载直接翻转视图,由 bootstrap effect 兜底 */
+const HISTORY_PRELOAD_MAX_WAIT_MS = 1500;
+
function AppContent() {
const { t, i18n } = useTranslation();
const { route, navigate } = useChatRoute();
@@ -1314,48 +1316,19 @@ function AppContent() {
.catch(() => {});
}, [isConnected]);
- // 当会话 ID 变化或页面加载时,自动加载历史会话
- useEffect(() => {
- if (!isConnected || !sessionId || sessionId === NEW_CONVERSATION_ID) return;
-
- if (promotedFromNewSessionIdsRef.current.has(sessionId)) {
- setHistoryPagerMeta(sessionId, null);
- setHistoryLoadingMore(false);
- setLoadingHistory(sessionId, false);
- return;
- }
-
- // 新建会话时跳过历史加载
- const isNew = useChatStore.getState().runtimes[sessionId]?.isNewSession ?? false;
- if (isNew) {
- useChatStore.getState().setNewSession(sessionId, false);
- setHistoryPagerMeta(sessionId, null); // 新会话无历史,不显示分页栏
- setLoadingHistory(sessionId, false);
- return;
- }
-
- // 已有完整历史恢复状态则跳过历史加载,直接使用内存数据。
- // historyPagerMeta 是唯一可靠的"history 是否完整加载过"标记。
- const existingRuntime = useChatStore.getState().getRuntime(sessionId);
- if (existingRuntime && existingRuntime.historyPagerMeta) {
- setLoadingHistory(sessionId, false);
- startBackgroundHistoryPrefetch(
- sessionId,
- existingRuntime.historyPagerMeta.loadedPages,
- existingRuntime.historyPagerMeta.totalPages
- );
- return;
- }
-
- // 清理之前的历史加载句柄
- disposeInFlightHistoryHandles(sessionId);
- setHistoryPagerMeta(sessionId, null);
- setHistoryLoadingMore(false);
-
- setLoadingHistory(sessionId, true);
- // 开始历史会话加载
+ /**
+ * 发起一次全量历史恢复:订阅 history.message 流 + 发送 history.get,最后一帧 done 后
+ * 一次性 replaceHistoryMessages 落库。bootstrap effect 与"切换会话预载"共用这套回放
+ * 回调,保证两种入口行为一致——预载在视图翻转前把目标会话消息填进 runtime,翻转后
+ * ChatPanel 直接渲染完整时间线,消除"空态 loading → 时间线整块弹出"的切换跳闪;
+ * 预载超时/失败则交给 sessionId 变化后的 bootstrap effect 走常规恢复路径兜底。
+ * 返回 done:resolve(true)=恢复完成(含空会话),resolve(false)=恢复失败。
+ */
+ const startHistoryRestore = useCallback((sid: string): { done: Promise<boolean> } => {
+ let settleDone!: (ok: boolean) => void;
+ const done = new Promise<boolean>((resolve) => { settleDone = resolve; });
const restoreHandle = beginHistoryRestore({
- sessionId: sessionId,
+ sessionId: sid,
onReady: (messages, totalPages) => {
historyRestoreFromPanelHintRef.current = false;
// "目标完成"回显消息纯前端合成,从未写进后端 session 历史,history.get 拉回来的
@@ -1364,51 +1337,53 @@ function AppContent() {
// 同时给命中"曾经设置过目标"的 user 消息回填 isGoalObjectiveMessage 徽章标记,
// 见 stampGoalObjectiveMessages。
replaceHistoryMessages(
- sessionId,
- stampGoalObjectiveMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, messages))
+ sid,
+ stampGoalObjectiveMessages(sid, mergePersistedGoalCompletionMessages(sid, messages))
);
const restoredTotalPages = totalPages ?? 1;
- setHistoryPagerMeta(sessionId, {
+ setHistoryPagerMeta(sid, {
loadedPages: 1,
totalPages: restoredTotalPages,
});
- setLoadingHistory(sessionId, false);
- startBackgroundHistoryPrefetch(sessionId, 1, restoredTotalPages);
+ setLoadingHistory(sid, false);
+ startBackgroundHistoryPrefetch(sid, 1, restoredTotalPages);
queueMicrotask(() => {
- if (historyRestoreHandlesRef.current.get(sessionId) === restoreHandle) {
- historyRestoreHandlesRef.current.delete(sessionId);
+ if (historyRestoreHandlesRef.current.get(sid) === restoreHandle) {
+ historyRestoreHandlesRef.current.delete(sid);
}
});
+ settleDone(true);
},
onEmpty: (emptyTotalPages) => {
- replaceHistoryMessages(sessionId, mergePersistedGoalCompletionMessages(sessionId, []));
+ replaceHistoryMessages(sid, mergePersistedGoalCompletionMessages(sid, []));
const restoredTotalPages = emptyTotalPages ?? 1;
- setHistoryPagerMeta(sessionId, {
+ setHistoryPagerMeta(sid, {
loadedPages: 1,
totalPages: restoredTotalPages,
});
if (historyRestoreFromPanelHintRef.current) {
historyRestoreFromPanelHintRef.current = false;
- addMessage(sessionId, {
+ addMessage(sid, {
id: `history-restore-empty-${Date.now()}`,
role: 'system',
content: tRef.current('sessions.restoreEmpty'),
timestamp: new Date().toISOString(),
});
}
- setLoadingHistory(sessionId, false);
- startBackgroundHistoryPrefetch(sessionId, 1, restoredTotalPages);
- if (historyRestoreHandlesRef.current.get(sessionId) === restoreHandle) {
- historyRestoreHandlesRef.current.delete(sessionId);
+ setLoadingHistory(sid, false);
+ startBackgroundHistoryPrefetch(sid, 1, restoredTotalPages);
+ if (historyRestoreHandlesRef.current.get(sid) === restoreHandle) {
+ historyRestoreHandlesRef.current.delete(sid);
}
+ settleDone(true);
},
onToolReplay: (items) => {
- clearSubtasks(sessionId);
+ clearSubtasks(sid);
for (const item of items) {
if (item.kind === 'tool_call') {
const n = normalizeToolCallPayload(item.payload);
addToolCall(
- sessionId,
+ sid,
{
id: n.id,
name: n.name,
@@ -1423,7 +1398,7 @@ function AppContent() {
} else {
const n = normalizeToolResultPayload(item.payload);
addToolResult(
- sessionId,
+ sid,
{
toolName: n.toolName,
result: n.result,
@@ -1438,22 +1413,22 @@ function AppContent() {
);
}
}
- settleHistoricalToolExecutions(sessionId);
+ settleHistoricalToolExecutions(sid);
},
onHarnessReplay: (items: HistoryHarnessReplayItem[]) => {
const harnessStore = useHarnessStore.getState();
- const harnessRuntime = harnessStore.getRuntime(sessionId);
+ const harnessRuntime = harnessStore.getRuntime(sid);
for (const item of items) {
if (item.kind === 'harness_message') {
const content = typeof item.payload.content === 'string' ? item.payload.content : '';
const stage = typeof item.payload.stage === 'string' ? item.payload.stage : undefined;
if (content) {
- harnessStore.addHarnessMessage(sessionId, content, stage);
+ harnessStore.addHarnessMessage(sid, content, stage);
// Update stage result with running status and label from message
if (stage) {
const existingStage = harnessRuntime?.stageResults.find((s) => s.stage === stage);
if (existingStage?.status !== 'running') {
- harnessStore.updateStageResult(sessionId, {
+ harnessStore.updateStageResult(sid, {
stage,
stageLabel: content,
status: 'running',
@@ -1470,7 +1445,7 @@ function AppContent() {
const messages = Array.isArray(item.payload.messages) ? item.payload.messages : [];
const metrics = item.payload.metrics || {};
if (stage) {
- harnessStore.updateStageResult(sessionId, {
+ harnessStore.updateStageResult(sid, {
stage,
status: status as 'success' | 'failed' | 'timeout',
error,
@@ -1482,49 +1457,49 @@ function AppContent() {
}
},
onReasoningReplay: (items) => {
- restoreReasoningSegments(sessionId, items);
+ restoreReasoningSegments(sid, items);
},
onError: (message) => {
console.warn('[history.restore]', message);
- setLoadingHistory(sessionId, false);
+ setLoadingHistory(sid, false);
+ settleDone(false);
},
});
- historyRestoreHandlesRef.current.set(sessionId, restoreHandle);
+ historyRestoreHandlesRef.current.set(sid, restoreHandle);
// 调用历史会话接口
void (async () => {
try {
await request(HISTORY_GET_METHOD, {
- session_id: sessionId,
+ session_id: sid,
page_idx: 1,
});
} catch (error) {
historyRestoreFromPanelHintRef.current = false;
restoreHandle.dispose();
- if (historyRestoreHandlesRef.current.get(sessionId) === restoreHandle) {
- historyRestoreHandlesRef.current.delete(sessionId);
+ if (historyRestoreHandlesRef.current.get(sid) === restoreHandle) {
+ historyRestoreHandlesRef.current.delete(sid);
}
// 发生错误时,设置 historyPagerMeta 为 null,显示欢迎信息
- setHistoryPagerMeta(sessionId, null);
+ setHistoryPagerMeta(sid, null);
console.error('Failed to load history:', error);
- setLoadingHistory(sessionId, false);
+ setLoadingHistory(sid, false);
// 忽略 "invalid page_idx or session history not found" 错误,因为这是新会话的正常情况
const errorMessage = error instanceof Error ? error.message : String(error);
- if (sessionIdRef.current === sessionId && !errorMessage.includes('invalid page_idx or session history not found')) {
- clearMessages(sessionId);
- addMessage(sessionId, {
+ if (sessionIdRef.current === sid && !errorMessage.includes('invalid page_idx or session history not found')) {
+ clearMessages(sid);
+ addMessage(sid, {
id: `history-load-failed-${Date.now()}`,
role: 'system',
- content: tRef.current('sessions.errors.restoreFailed', { sessionId }),
+ content: tRef.current('sessions.errors.restoreFailed', { sessionId: sid }),
timestamp: new Date().toISOString(),
});
}
+ settleDone(false);
}
})();
+ return { done };
}, [
- isConnected,
- sessionId,
- historyBootstrapKey,
request,
addMessage,
addToolCall,
@@ -1532,7 +1507,6 @@ function AppContent() {
settleHistoricalToolExecutions,
clearMessages,
clearSubtasks,
- disposeInFlightHistoryHandles,
setLoadingHistory,
setHistoryPagerMeta,
replaceHistoryMessages,
@@ -1540,6 +1514,56 @@ function AppContent() {
startBackgroundHistoryPrefetch,
]);
+ // 当会话 ID 变化或页面加载时,自动加载历史会话
+ useEffect(() => {
+ if (!isConnected || !sessionId || sessionId === NEW_CONVERSATION_ID) return;
+
+ if (promotedFromNewSessionIdsRef.current.has(sessionId)) {
+ setHistoryPagerMeta(sessionId, null);
+ setHistoryLoadingMore(false);
+ setLoadingHistory(sessionId, false);
+ return;
+ }
+
+ // 新建会话时跳过历史加载
+ const isNew = useChatStore.getState().runtimes[sessionId]?.isNewSession ?? false;
+ if (isNew) {
+ useChatStore.getState().setNewSession(sessionId, false);
+ setHistoryPagerMeta(sessionId, null); // 新会话无历史,不显示分页栏
+ setLoadingHistory(sessionId, false);
+ return;
+ }
+
+ // 已有完整历史恢复状态则跳过历史加载,直接使用内存数据。
+ // historyPagerMeta 是唯一可靠的"history 是否完整加载过"标记。
+ const existingRuntime = useChatStore.getState().getRuntime(sessionId);
+ if (existingRuntime && existingRuntime.historyPagerMeta) {
+ setLoadingHistory(sessionId, false);
+ startBackgroundHistoryPrefetch(
+ sessionId,
+ existingRuntime.historyPagerMeta.loadedPages,
+ existingRuntime.historyPagerMeta.totalPages
+ );
+ return;
+ }
+
+ // 清理之前的历史加载句柄
+ disposeInFlightHistoryHandles(sessionId);
+ setHistoryPagerMeta(sessionId, null);
+ setHistoryLoadingMore(false);
+
+ setLoadingHistory(sessionId, true);
+ startHistoryRestore(sessionId);
+ }, [
+ isConnected,
+ sessionId,
+ historyBootstrapKey,
+ disposeInFlightHistoryHandles,
+ setLoadingHistory,
+ setHistoryPagerMeta,
+ startHistoryRestore,
+ ]);
+
// 会话切换/页面加载时主动拉一次当前 Goal 状态(协议文档 v2 §11 推荐流程)——不然刷新页面
// 后 GoalBar 要等下一次 goal.updated 推送才会重新出现,目标 paused/静默期时甚至会一直缺失
// (2026-07-21 真机联调发现,见 backend-requests.md #1 末尾)。新会话(promoted from 'new')
@@ -1896,26 +1920,6 @@ function AppContent() {
useSessionStore.getState().getRuntime(previousSessionId)?.mode ?? mode;
const resolvedMode = targetMode ?? targetSession?.mode ?? previousMode;
disposeInFlightHistoryHandles(targetSessionId);
- if (previousSessionId && previousSessionId !== targetSessionId) {
- try {
- await request('session.switch', {
- session_id: targetSessionId,
- previous_session_id: previousSessionId,
- previous_mode: previousMode,
- mode: resolvedMode,
- });
- } catch (error) {
- if (isTeamMode(resolvedMode)) {
- console.error('Failed to switch team session:', error);
- window.alert(t('sessions.errors.switchSession'));
- return;
- }
- console.warn('Session switch lifecycle hook failed; continuing restore:', error);
- }
- }
-
- setHistoryPagerMeta(targetSessionId, null);
- setHistoryLoadingMore(false);
const existingRuntime = useChatStore.getState().getRuntime(targetSessionId);
if (!existingRuntime) {
useChatStore.getState().ensureRuntime(targetSessionId);
@@ -1932,7 +1936,61 @@ function AppContent() {
// 确保 session runtime 存在;否则 useSessionStore.setMode 会因找不到 runtime 而直接跳过,
// 导致从会话页签恢复后前端 mode 不会切换到目标会话对应的 mode。
ensureSessionRuntimes(targetSessionId);
+ // historyLoadingMore 是全局单例(非按会话),切换后一律复位,避免上一会话遗留的
+ // "加载更多"转圈挂到新会话上。但 historyPagerMeta 是按会话的"历史已完整加载"标记:
+ // 目标会话已加载过就别清——清了会让翻转后的 bootstrap effect 把它当成从未加载过而
+ // 整页重拉历史,replaceHistoryMessages 换掉整条时间线(render key 重排+滚动效果
+ // 重跑),这就是"切回已访问会话时的跳闪"。只有即将走预载/重载路径的会话才清旧状态。
+ setHistoryLoadingMore(false);
+ const willLoadHistory =
+ !options?.skipHistoryLoad &&
+ !existingRuntime?.historyPagerMeta &&
+ !existingRuntime?.isNewSession &&
+ !promotedFromNewSessionIdsRef.current.has(targetSessionId);
+ if (willLoadHistory) {
+ setHistoryPagerMeta(targetSessionId, null);
+ setLoadingHistory(targetSessionId, true);
+ }
+
+ // 切换原子化:并行发起 session.switch 生命周期与目标会话历史预载,两者都就绪后再翻转
+ // 视图。旧实现先翻转 sessionId,ChatPanel 会先渲染一帧"空时间线+加载中",history
+ // 到达后整块时间线弹出并滚底——即切换会话后的跳闪。预载 1.5s 封顶:超时/失败不再
+ // 等待,翻转后由 bootstrap effect 走常规恢复路径兜底(等价旧行为)。
+ let switchError: unknown = null;
+ const switchPromise =
+ previousSessionId && previousSessionId !== targetSessionId
+ ? request('session.switch', {
+ session_id: targetSessionId,
+ previous_session_id: previousSessionId,
+ previous_mode: previousMode,
+ mode: resolvedMode,
+ }).catch((error: unknown) => {
+ switchError = error;
+ return null;
+ })
+ : Promise.resolve(true as const);
+ const preloadPromise = willLoadHistory ? startHistoryRestore(targetSessionId).done : null;
+
+ const switchOk = await switchPromise;
+ if (switchOk === null) {
+ if (isTeamMode(resolvedMode)) {
+ console.error('Failed to switch team session:', switchError);
+ window.alert(t('sessions.errors.switchSession'));
+ return;
+ }
+ console.warn('Session switch lifecycle hook failed; continuing restore:', switchError);
+ }
+ if (preloadPromise) {
+ await Promise.race([
+ preloadPromise,
+ new Promise<void>((resolve) => { window.setTimeout(resolve, HISTORY_PRELOAD_MAX_WAIT_MS); }),
+ ]);
+ }
+
sessionIdRef.current = targetSessionId;
+ // 同步切 activeSessionId(缺省由 effect 在渲染后才补同步):否则切换后首帧
+ // ChatPanel 仍按上一个会话读取消息,旧会话内容会在新会话标题下闪回一帧。
+ useChatStore.getState().setActiveSessionId(targetSessionId);
setSessionId(targetSessionId);
if (targetSession) {
upsertSessionMetadata(targetSession, { setCurrent: true });
@@ -1973,11 +2031,13 @@ function AppContent() {
setCurrentSession,
setHistoryLoadingMore,
setHistoryPagerMeta,
+ setLoadingHistory,
setMode,
setPaused,
setProcessing,
setSessionId,
setThinking,
+ startHistoryRestore,
t,
upsertSessionMetadata,
]
@@ -2210,7 +2270,7 @@ function AppContent() {
isConnected={isConnected}
onNewSession={handleNewSession}
showNewSession={false}
- hiddenNavItems={enterpriseMode ? ['sessions', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions', 'history']}
+ hiddenNavItems={enterpriseMode ? ['sessions', 'history', ...ENTERPRISE_HIDDEN_NAV_ITEMS] : ['sessions', 'history']}
onMorePanelOpenChange={setSidebarMorePanelOpen}
/>
@@ -2354,16 +2414,6 @@ function AppContent() {
/>
</div>
)}
- {enterpriseMode && (
- <div
- className={`app-section ${activeNav === 'history' ? '' : 'hidden'}`}
- aria-hidden={activeNav !== 'history'}
- >
- {/* 企业版历史页保持挂载,切换导航时不丢失已加载的会话列表和详情。
- 个人版不挂载该旁路历史组件,维持原有个人版行为。 */}
- <HistoryPanel />
- </div>
- )}
{activeNav === 'cron' && (
<div className="chat-layout flex-1 flex min-h-0 overflow-hidden">
<ConversationSidebar
diff --git a/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsx
deleted file mode 100644
index ea6b6af233..0000000000
--- a/jiuwenswarm/channels/web/frontend/src/components/HistoryPanel/index.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * HistoryPanel —— Web Pod 本地会话历史浏览(只读)。
- *
- * 列表态:GET /api/sessions,展示标题 / 预览 / 时间 / 消息数。
- * 详情态:GET /api/sessions/{id},复用 MessageItem 渲染完整对话。
- * 数据源为 Web Pod 落库的会话历史(企业版 ChatHistoryStore),独立于 WS(AgentServer)链路。
- */
-
-import { useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import {
- fetchSessionDetail,
- fetchSessions,
- type HistoryDetail,
- type HistoryMessage,
- type HistorySession,
-} from '../../services/api';
-import { getRuntimeScope } from '../../services/runtimeScope';
-import type { Message } from '../../types';
-import { formatRelativeTime } from '../../utils';
-import { MessageItem } from '../ChatPanel/MessageItem';
-
-function toMessage(msg: HistoryMessage, sessionId: string, index: number): Message {
- return {
- id: msg.request_id || `${sessionId}-${index}`,
- role: msg.role,
- content: msg.content,
- timestamp: new Date(msg.timestamp * 1000).toISOString(),
- };
-}
-
-const BTN =
- 'px-3 py-1.5 rounded-md border border-border text-sm text-text hover:bg-secondary transition-colors';
-
-export function HistoryPanel() {
- const { t } = useTranslation();
- const [sessions, setSessions] = useState<HistorySession[]>([]);
- const [loadingList, setLoadingList] = useState(true);
- const [errorList, setErrorList] = useState<string | null>(null);
-
- const [selectedId, setSelectedId] = useState<string | null>(null);
- const [detail, setDetail] = useState<HistoryDetail | null>(null);
- const [loadingDetail, setLoadingDetail] = useState(false);
- const [errorDetail, setErrorDetail] = useState<string | null>(null);
-
- const loadList = useCallback(async () => {
- setLoadingList(true);
- setErrorList(null);
- try {
- // 多用户隔离:显式传入当前 user_id,确保只返回当前用户的会话
- // (defense-in-depth;即使后端已按认证过滤也显式传递)。
- const userId = getRuntimeScope().userId;
- setSessions(await fetchSessions(50, 0, userId));
- } catch (e) {
- setErrorList(e instanceof Error ? e.message : String(e));
- } finally {
- setLoadingList(false);
- }
- }, []);
-
- useEffect(() => {
- void loadList();
- }, [loadList]);
-
- const openDetail = useCallback(
- async (id: string) => {
- setSelectedId(id);
- setDetail(null);
- setErrorDetail(null);
- setLoadingDetail(true);
- try {
- const d = await fetchSessionDetail(id, getRuntimeScope().userId);
- if (d === null) {
- setErrorDetail(t('history.notFound'));
- } else {
- setDetail(d);
- }
- } catch (e) {
- setErrorDetail(e instanceof Error ? e.message : String(e));
- } finally {
- setLoadingDetail(false);
- }
- },
- [t],
- );
-
- const closeDetail = useCallback(() => {
- setSelectedId(null);
- setDetail(null);
- setErrorDetail(null);
- }, []);
-
- // ---- 详情态 ----
- if (selectedId) {
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center gap-3 p-3 border-b border-border">
- <button onClick={closeDetail} className={BTN}>
- {t('history.back')}
- </button>
- <div className="font-medium text-text truncate">{detail?.title || selectedId}</div>
- </div>
- <div className="flex-1 overflow-y-auto p-4">
- {loadingDetail && <div className="text-text-muted">{t('history.loading')}</div>}
- {errorDetail && <div className="text-danger">{errorDetail}</div>}
- {detail && detail.messages.length === 0 && (
- <div className="text-text-muted">{t('history.emptyMessages')}</div>
- )}
- {detail &&
- detail.messages.map((m, i) => (
- <MessageItem key={`${selectedId}-${i}`} message={toMessage(m, selectedId, i)} />
- ))}
- </div>
- </div>
- );
- }
-
- // ---- 列表态 ----
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center justify-between p-3 border-b border-border">
- <div>
- <div className="text-lg font-semibold text-text">{t('history.title')}</div>
- <div className="text-xs text-text-muted">{t('history.subtitle')}</div>
- </div>
- <button onClick={loadList} className={BTN}>
- {t('history.refresh')}
- </button>
- </div>
- <div className="flex-1 overflow-y-auto p-3 space-y-2">
- {loadingList && <div className="text-text-muted">{t('history.loading')}</div>}
- {errorList && <div className="text-danger">{errorList}</div>}
- {!loadingList && !errorList && sessions.length === 0 && (
- <div className="text-text-muted">{t('history.empty')}</div>
- )}
- {sessions.map((s) => (
- <button
- key={s.session_id}
- onClick={() => openDetail(s.session_id)}
- className="w-full text-left rounded-lg border border-border bg-card/70 p-3 hover:border-[var(--color-border-accent)] hover:shadow-sm transition-colors"
- >
- <div className="flex items-center justify-between gap-2">
- <div className="font-medium text-text truncate">{s.title || s.session_id}</div>
- <div className="text-xs text-text-muted shrink-0">
- {formatRelativeTime(new Date(s.updated_at * 1000).toISOString())}
- </div>
- </div>
- {s.last_preview && (
- <div className="text-sm text-text-muted truncate mt-1">{s.last_preview}</div>
- )}
- <div className="text-xs text-text-muted mt-1">
- {t('history.messageCount', { count: s.message_count })}
- </div>
- </button>
- ))}
- </div>
- </div>
- );
-}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
index 352fb7895c..a53ebbd331 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
@@ -55,23 +55,12 @@ const teamNavIcon = (
</svg>
);
-const historyNavIcon = (
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M3 3v5h5M3.05 13A9 9 0 1 0 6 5.3L3 8"
- />
- </svg>
-);
-
const mainNavItems: NavItem[] = [
{ key: 'chat', labelKey: 'nav.work', icon: <WorkIcon aria-hidden /> },
{ key: 'skills', labelKey: 'nav.skills', icon: <SkillDesignIcon aria-hidden /> },
{ key: 'channels', labelKey: 'nav.channels', icon: <ChannelIcon aria-hidden /> },
{ key: 'agents', labelKey: 'nav.agent', icon: <AgentDesignIcon aria-hidden /> },
{ key: 'teams', labelKey: 'nav.teams', icon: teamNavIcon },
- { key: 'history', labelKey: 'nav.history', icon: historyNavIcon },
];
const moreNavItems: NavItem[] = [
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 0b07ccd8bb..b285be019b 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -34,7 +34,6 @@
"agent": "Agent",
"teams": "Teams",
"sessions": "Sessions",
- "history": "History",
"cron": "Scheduled Tasks",
"skills": "Skills",
"channels": "Channels",
@@ -544,17 +543,6 @@
"language": "Language",
"moreSettings": "More Settings"
},
- "history": {
- "title": "Session History",
- "subtitle": "Browse session history stored on the Web Pod",
- "refresh": "Refresh",
- "loading": "Loading...",
- "empty": "No session history",
- "emptyMessages": "This session has no messages",
- "notFound": "Session not found",
- "back": "Back to list",
- "messageCount": "{{count}} messages"
- },
"a2aIngress": {
"title": "A2A Control Center",
"subtitle": "Manage the A2A service exposed by JiuwenSwarm.",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 742a64783f..379ca5a81d 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -34,7 +34,6 @@
"agent": "智能体",
"teams": "团队",
"sessions": "会话",
- "history": "会话历史",
"cron": "定时任务",
"skills": "技能",
"channels": "频道",
@@ -545,17 +544,6 @@
"language": "语言",
"moreSettings": "更多设置"
},
- "history": {
- "title": "会话历史",
- "subtitle": "浏览 Web Pod 落库的会话历史",
- "refresh": "刷新",
- "loading": "加载中...",
- "empty": "暂无会话历史",
- "emptyMessages": "该会话没有消息记录",
- "notFound": "未找到该会话",
- "back": "返回列表",
- "messageCount": "{{count}} 条消息"
- },
"a2aIngress": {
"title": "A2A 调度中心",
"subtitle": "管理 JiuwenSwarm 对外提供的 A2A 服务。",
diff --git a/jiuwenswarm/channels/web/frontend/src/services/api.ts b/jiuwenswarm/channels/web/frontend/src/services/api.ts
deleted file mode 100644
index 4ebd07a5c6..0000000000
--- a/jiuwenswarm/channels/web/frontend/src/services/api.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * HTTP API 客户端:会话历史(企业 MySQL 库 web)。
- *
- * 与 webClient(WS 通道)并列;仅用于读取 Web Pod 落库的会话历史:
- * GET /api/sessions(列表)、GET /api/sessions/{id}(详情)。
- *
- * 个人版后端已在 web_http_sessions_compat.py 注册了 GET /api/sessions* 路由,
- * 但只有在企业版(is_enterprise()=true)时 ChatHistoryStore 才会写入数据,
- * 因此个人版下接口可调但通常返回空列表——前端按企业模式才展示 HistoryPanel。
- */
-
-const API_BASE = '/api';
-
-export interface HistorySession {
- session_id: string;
- user: string | null;
- title: string | null;
- message_count: number;
- last_preview: string | null;
- created_at: number;
- updated_at: number;
-}
-
-export interface HistoryMessage {
- role: 'user' | 'assistant';
- content: string;
- event_type: string | null;
- timestamp: number;
- request_id: string;
-}
-
-export interface HistoryDetail extends HistorySession {
- messages: HistoryMessage[];
-}
-
-export async function fetchSessions(limit = 50, offset = 0, user?: string): Promise<HistorySession[]> {
- const params = new URLSearchParams({ limit: String(limit), offset: String(offset) });
- if (user) params.set('user', user);
- const res = await fetch(`${API_BASE}/sessions?${params.toString()}`);
- if (!res.ok) throw new Error(`fetchSessions failed: HTTP ${res.status}`);
- const data = (await res.json()) as { sessions?: HistorySession[] };
- return data.sessions ?? [];
-}
-
-export async function fetchSessionDetail(sessionId: string, user?: string): Promise<HistoryDetail | null> {
- const target =
- `${API_BASE}/sessions/${encodeURIComponent(sessionId)}` +
- (user ? `?user=${encodeURIComponent(user)}` : '');
- const res = await fetch(target);
- if (res.status === 404) return null;
- if (!res.ok) throw new Error(`fetchSessionDetail failed: HTTP ${res.status}`);
- return (await res.json()) as HistoryDetail;
-}
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
index d4a4b9dbae..912f44becc 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
@@ -284,7 +284,7 @@ function errorFields(error: unknown): { message: string; code?: string } {
return { message: 'request failed' };
}
-export function unwrapHttpUnary(input: unknown): UnaryResult {
+export function unwrapHttpUnary(input: unknown, status?: number): UnaryResult {
if (!isRecord(input)) {
return { ok: false, message: 'empty http response', code: 'HTTP_ERROR' };
}
@@ -300,6 +300,18 @@ export function unwrapHttpUnary(input: unknown): UnaryResult {
if (input.agent_ready !== undefined) {
return { ok: true, payload: input, requestId };
}
+ // 鉴权代理层(manager-web 同源反代等)返回 FastAPI/Starlette 的 {"detail": ...}
+ // 错误形状——不是标准信封,但要给出真实原因而非笼统的 "invalid http envelope"。
+ if (input.detail !== undefined) {
+ const detail = input.detail;
+ const message =
+ typeof detail === 'string' && detail.trim()
+ ? detail
+ : 'request rejected';
+ const code =
+ status === 401 ? 'UNAUTHORIZED' : status === 403 ? 'FORBIDDEN' : 'HTTP_ERROR';
+ return { ok: false, message, code, requestId };
+ }
return { ok: false, message: 'invalid http envelope', code: 'HTTP_ERROR', requestId };
}
@@ -670,7 +682,7 @@ export class WebHttpClient {
if (assembled.kind === 'sse' || assembled.kind === 'history-stream') {
if (isSseContentType(response.headers.get('content-type'))) {
if (!response.ok) {
- const unwrapped = unwrapHttpUnary(await this.readJson(response));
+ const unwrapped = unwrapHttpUnary(await this.readJson(response), response.status);
throw this.createWebError(
unwrapped.ok ? i18n.t('network.requestFailed') : unwrapped.message,
unwrapped.ok ? 'HTTP_ERROR' : unwrapped.code,
@@ -790,7 +802,7 @@ export class WebHttpClient {
headers: this.identityHeaders(requestId, {}),
signal: this.connectAbort.signal,
});
- const unwrapped = unwrapHttpUnary(await this.readJson(response));
+ const unwrapped = unwrapHttpUnary(await this.readJson(response), response.status);
if (!unwrapped.ok) {
throw this.createWebError(
unwrapped.message,
@@ -907,7 +919,7 @@ export class WebHttpClient {
}
private async readUnaryPayload(response: Response, requestId: string): Promise<unknown> {
- const unwrapped = unwrapHttpUnary(await this.readJson(response));
+ const unwrapped = unwrapHttpUnary(await this.readJson(response), response.status);
if (!unwrapped.ok) {
throw this.createWebError(
unwrapped.message,
diff --git a/jiuwenswarm/channels/web/history_store/api.py b/jiuwenswarm/channels/web/history_store/api.py
index e5024f5993..7977baf2fd 100644
--- a/jiuwenswarm/channels/web/history_store/api.py
+++ b/jiuwenswarm/channels/web/history_store/api.py
@@ -110,3 +110,35 @@ def delete_session_sync(
if st is None:
return False
return st.delete_session_blocking(str(session_id), user=user)
+
+
+def set_session_pinned_sync(
+ session_id: str,
+ pinned: bool,
+ store: ChatHistoryStore | None = None,
+ *,
+ user: str | None = None,
+) -> tuple[bool, int] | None:
+ """同步置顶/取消置顶会话(remote 模式 session.pin 用)。
+
+ 严格版语义:store/DB 不可用抛异常(调用方区分故障与不存在);
+ 会话不存在返回 ``None``;成功返回 ``(pinned, pin_order)``。
+ """
+ if not session_id:
+ return None
+ st = _coerce_store(store)
+ if st is None:
+ raise RuntimeError("web history store unavailable")
+ return st.set_session_pinned_blocking(str(session_id), bool(pinned), user=user)
+
+
+def list_pinned_sessions_sync(
+ store: ChatHistoryStore | None = None,
+ *,
+ user: str | None = None,
+) -> list[dict[str, Any]]:
+ """同步读全部置顶会话(remote 模式 project.pinned_sessions 用)。库不可用返回空。"""
+ st = _coerce_store(store)
+ if st is None:
+ return []
+ return st.list_pinned_sessions_blocking(user=user)
diff --git a/jiuwenswarm/channels/web/history_store/db_actor.py b/jiuwenswarm/channels/web/history_store/db_actor.py
index 513e24cecb..c00f57e78c 100644
--- a/jiuwenswarm/channels/web/history_store/db_actor.py
+++ b/jiuwenswarm/channels/web/history_store/db_actor.py
@@ -103,6 +103,7 @@ class HistoryDbActor:
await handler.init_database()
await handler.connect()
await init_web_history_tables(handler)
+ await self._ensure_pin_columns()
self._handler = handler
logger.info(
"[history] %s store 初始化完成 %s:%s/%s%s",
@@ -221,6 +222,132 @@ class HistoryDbActor:
)
return {**_row_to_dict(s), "messages": [_row_to_dict(m) for m in msgs]}
+ async def _ensure_pin_columns(self) -> None:
+ """存量表列迁移:sessions 表补 ``pinned`` / ``pin_order`` 列(幂等)。
+
+ foundation ``init_table`` 只 create_all,不给已存在的表加列(与
+ service_config_template 缺列事故同型);ORM 模型带上新列后,任何 SELECT
+ 都会引用它们,存量表缺列会直接 UndefinedColumn。这里按方言直连 information_schema
+ 探测后 ALTER 补列;失败仅告警(新库由 create_all 直接建出,不需要迁移)。
+ """
+ if self._settings is None:
+ return
+ try:
+ if self._db_type == "postgresql":
+ import asyncpg
+
+ conn = await asyncpg.connect(
+ host=self._settings.host,
+ port=int(self._settings.port),
+ user=self._settings.user,
+ password=self._settings.password,
+ database=self._settings.database,
+ )
+ try:
+ schema = self._settings.pg_schema or "public"
+ rows = await conn.fetch(
+ "SELECT column_name FROM information_schema.columns"
+ " WHERE table_schema=$1 AND table_name='sessions'",
+ schema,
+ )
+ names = {r["column_name"] for r in rows}
+ table = f'"{schema}"."sessions"'
+ if "pinned" not in names:
+ await conn.execute(
+ f'ALTER TABLE {table} ADD COLUMN "pinned" BOOLEAN NOT NULL DEFAULT FALSE'
+ )
+ if "pin_order" not in names:
+ await conn.execute(
+ f'ALTER TABLE {table} ADD COLUMN "pin_order" INTEGER NOT NULL DEFAULT 0'
+ )
+ finally:
+ await conn.close()
+ elif self._db_type == "mysql":
+ import aiomysql
+
+ conn = await aiomysql.connect(
+ host=self._settings.host,
+ port=int(self._settings.port),
+ user=self._settings.user,
+ password=self._settings.password,
+ db=self._settings.database,
+ )
+ try:
+ cur = await conn.cursor()
+ await cur.execute(
+ "SELECT column_name FROM information_schema.columns"
+ " WHERE table_schema=%s AND table_name='sessions'",
+ (self._settings.database,),
+ )
+ names = {r[0] for r in await cur.fetchall()}
+ if "pinned" not in names:
+ await cur.execute(
+ "ALTER TABLE `sessions` ADD COLUMN `pinned` TINYINT(1) NOT NULL DEFAULT 0"
+ )
+ if "pin_order" not in names:
+ await cur.execute(
+ "ALTER TABLE `sessions` ADD COLUMN `pin_order` INT NOT NULL DEFAULT 0"
+ )
+ await conn.commit()
+ finally:
+ conn.close()
+ else:
+ return
+ logger.info("[history] sessions 置顶列迁移完成 db_type=%s", self._db_type)
+ except Exception: # noqa: BLE001
+ logger.warning("[history] sessions 置顶列迁移失败(可能已存在)", exc_info=True)
+
+ async def _set_session_pinned(
+ self, session_id: str, pinned: bool, *, user: str,
+ ) -> tuple[bool, int] | None:
+ """remote 模式置顶/取消置顶(语义与本地 ``set_session_pinned`` 一致)。
+
+ 目标行不存在返回 ``None``(调用方回 NOT_FOUND);成功返回 ``(pinned, pin_order)``。
+ 重编号与目标状态写入共用 handler CRUD,pg/mysql 通用。
+ """
+ if not user:
+ user = "guest"
+ handler = await self._get_handler()
+ target = await handler.get("sessions", {"session_id": session_id, "user": user})
+ if target is None:
+ return None
+ # 1. 写目标状态:置顶保留原 pin_order 供排序(新置顶为 0 → 排最前);取消清零
+ if pinned:
+ await handler.update("sessions", {"session_id": session_id}, {"pinned": True})
+ else:
+ await handler.update(
+ "sessions", {"session_id": session_id}, {"pinned": False, "pin_order": 0}
+ )
+ # 2. 收集该用户全部置顶会话(含刚置顶的),按 pin_order 稳定排序
+ rows = await handler.list_records(
+ "sessions", {"user": user, "pinned": True}, limit=10_000, offset=0, order_by="pin_order"
+ )
+ ordered = sorted(
+ (_row_to_dict(r) for r in rows),
+ key=lambda d: int(d.get("pin_order") or 0),
+ )
+ # 3. 紧凑重编号 1..N(幂等:已在位则跳过写)
+ new_orders: dict[str, int] = {}
+ for idx, d in enumerate(ordered, start=1):
+ sid = str(d.get("session_id") or "")
+ if int(d.get("pin_order") or 0) != idx:
+ await handler.update(
+ "sessions", {"session_id": sid}, {"pinned": True, "pin_order": idx}
+ )
+ if sid:
+ new_orders[sid] = idx
+ return pinned, new_orders.get(session_id, 0)
+
+ async def _list_pinned_sessions(self, *, user: str) -> list[dict[str, Any]]:
+ """该用户全部置顶会话,按 pin_order 升序。"""
+ if not user:
+ user = "guest"
+ handler = await self._get_handler()
+ rows = await handler.list_records(
+ "sessions", {"user": user, "pinned": True}, limit=10_000, offset=0, order_by="pin_order"
+ )
+ return [_row_to_dict(r) for r in rows]
+
async def record_message(self, **kw: Any) -> bool:
return await self.run_async(self._record_message(**kw))
@@ -260,6 +387,22 @@ class HistoryDbActor:
def delete_session_sync(self, session_id: str, *, user: str | None = None) -> bool:
return self.run_sync(self._delete_session(session_id, user=user))
+ async def set_session_pinned(
+ self, session_id: str, pinned: bool, *, user: str | None = None
+ ) -> tuple[bool, int] | None:
+ return await self.run_async(self._set_session_pinned(session_id, pinned, user=user or ""))
+
+ def set_session_pinned_sync(
+ self, session_id: str, pinned: bool, *, user: str | None = None
+ ) -> tuple[bool, int] | None:
+ return self.run_sync(self._set_session_pinned(session_id, pinned, user=user or ""))
+
+ async def list_pinned_sessions(self, *, user: str | None = None) -> list[dict[str, Any]]:
+ return await self.run_async(self._list_pinned_sessions(user=user or ""))
+
+ def list_pinned_sessions_sync(self, *, user: str | None = None) -> list[dict[str, Any]]:
+ return self.run_sync(self._list_pinned_sessions(user=user or ""))
+
def stop(self) -> None:
if not self._started:
return
diff --git a/jiuwenswarm/channels/web/history_store/store.py b/jiuwenswarm/channels/web/history_store/store.py
index ff96c6bcbc..258a53c646 100644
--- a/jiuwenswarm/channels/web/history_store/store.py
+++ b/jiuwenswarm/channels/web/history_store/store.py
@@ -362,6 +362,51 @@ class ChatHistoryStore:
logger.exception("[history] %s 删除会话失败", self.backend.upper())
return False
+ def set_session_pinned_blocking(
+ self, session_id: str, pinned: bool, *, user: str | None,
+ ) -> tuple[bool, int] | None:
+ """置顶/取消置顶并紧凑重编号;目标会话不存在返回 None。"""
+ if not user:
+ user = "guest"
+ if self._memory:
+ with self._mem_lock:
+ s = self._mem_sessions.get(session_id)
+ if s is None or s.get("user") != user:
+ return None
+ s["pinned"] = bool(pinned)
+ s["pin_order"] = int(s.get("pin_order") or 0) if pinned else 0
+ pinned_list = sorted(
+ (x for x in self._mem_sessions.values() if x.get("pinned")),
+ key=lambda x: int(x.get("pin_order") or 0),
+ )
+ orders: dict[str, int] = {}
+ for idx, x in enumerate(pinned_list, start=1):
+ x["pinned"] = True
+ x["pin_order"] = idx
+ orders[str(x.get("session_id"))] = idx
+ return pinned, orders.get(session_id, 0)
+ return self._get_actor().set_session_pinned_sync(session_id, pinned, user=user)
+
+ def list_pinned_sessions_blocking(
+ self, *, user: str | None,
+ ) -> list[dict[str, Any]]:
+ """该用户全部置顶会话,按 pin_order 升序。库不可用返回空。"""
+ if not user:
+ user = "guest"
+ if self._memory:
+ with self._mem_lock:
+ rows = [
+ dict(s) for s in self._mem_sessions.values()
+ if s.get("user") == user and s.get("pinned")
+ ]
+ rows.sort(key=lambda r: int(r.get("pin_order") or 0))
+ return rows
+ try:
+ return self._get_actor().list_pinned_sessions_sync(user=user)
+ except Exception:
+ logger.exception("[history] %s 读取置顶会话失败", self.backend.upper())
+ return []
+
async def delete_session(
self, session_id: str, *, user: str | None = None,
) -> bool:
diff --git a/jiuwenswarm/channels/web/history_store/tables.py b/jiuwenswarm/channels/web/history_store/tables.py
index 4d5707ad91..10f1d26d68 100644
--- a/jiuwenswarm/channels/web/history_store/tables.py
+++ b/jiuwenswarm/channels/web/history_store/tables.py
@@ -19,17 +19,23 @@ from openjiuwen_runtime.foundation.db.table_def import (
# 时间戳列用 float(DOUBLE / REAL epoch 秒),与现有数据模型一致。
# content 用 mediumtext:mysql → MEDIUMTEXT(16MB),pg → TEXT(无界)。
+# string 列必须带 length:MySQL 的 VARCHAR 不允许省略长度(PG 的裸 VARCHAR
+# 合法,会掩盖问题),缺 length 会让 create_all 在 MySQL 上直接编译失败——
+# 即企业版 MySQL 部署下历史列表为空的根因。长度对齐平台惯例(64/128/255)。
SESSIONS_TABLE_DEF = TableDefinition(
table_name="sessions",
columns=[
- ColumnDefinition("session_id", "string", primary_key=True, nullable=False),
- ColumnDefinition("user", "string", nullable=False, default="guest"),
- ColumnDefinition("title", "string", nullable=True),
+ ColumnDefinition("session_id", "string", length=128, primary_key=True, nullable=False),
+ ColumnDefinition("user", "string", length=64, nullable=False, default="guest"),
+ ColumnDefinition("title", "string", length=255, nullable=True),
ColumnDefinition("message_count", "integer", nullable=False, default=0),
- ColumnDefinition("last_preview", "string", nullable=True),
+ ColumnDefinition("last_preview", "string", length=255, nullable=True),
ColumnDefinition("created_at", "float", nullable=False),
ColumnDefinition("updated_at", "float", nullable=False),
+ # 置顶状态(remote 模式 session.pin 的持久化字段;本地模式存 agent/sessions 元数据)
+ ColumnDefinition("pinned", "boolean", nullable=False, default=False),
+ ColumnDefinition("pin_order", "integer", nullable=False, default=0),
],
indexes=[
IndexDefinition(["user", "updated_at"], unique=False),
@@ -40,11 +46,11 @@ MESSAGES_TABLE_DEF = TableDefinition(
table_name="messages",
columns=[
ColumnDefinition("id", "integer", primary_key=True, nullable=False, autoincrement=True),
- ColumnDefinition("session_id", "string", nullable=False),
- ColumnDefinition("request_id", "string", nullable=False),
- ColumnDefinition("role", "string", nullable=False),
+ ColumnDefinition("session_id", "string", length=128, nullable=False),
+ ColumnDefinition("request_id", "string", length=128, nullable=False),
+ ColumnDefinition("role", "string", length=32, nullable=False),
ColumnDefinition("content", "mediumtext", nullable=False),
- ColumnDefinition("event_type", "string", nullable=True),
+ ColumnDefinition("event_type", "string", length=64, nullable=True),
ColumnDefinition("timestamp", "float", nullable=False),
],
indexes=[
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index fb790f30ef..1f95fed45c 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -3318,6 +3318,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
"created_at": row.get("created_at", 0),
"last_message_at": row.get("updated_at", 0),
"message_count": row.get("message_count", 0),
+ "pinned": bool(row.get("pinned")),
+ "pin_order": int(row.get("pin_order") or 0),
"mode": "web",
})
@@ -3418,8 +3420,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
"message_count": int(detail.get("message_count") or 0),
"mode": "unknown",
"team_name": "",
- "pinned": False,
- "pin_order": 0,
+ "pinned": bool(detail.get("pinned")),
+ "pin_order": int(detail.get("pin_order") or 0),
"project_dir": "",
"project_id": "",
"cron_id": "",
@@ -3534,10 +3536,13 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
ws, req_id, ok=False, error=err or "session.rename failed", code=code,
)
- async def _session_pin(ws, req_id, params, session_id):
+ async def _session_pin(ws, req_id, params, session_id, user_id=None):
"""置顶/取消置顶会话,操作后对所有置顶会话紧凑重编号为 1..N。幂等。
置顶时会话从项目分组剥离,进入全局置顶区;取消置顶时回归原项目。
+ remote(PG) 模式下 Gateway 本地没有会话目录(元数据在按会话拉起的
+ AgentServer pod 上),置顶状态持久化到 Web 历史库 sessions 行,与
+ session.list / project.pinned_sessions 的 remote 读取同源。
"""
if not isinstance(params, dict):
await channel.send_response(
@@ -3558,6 +3563,32 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
)
return
+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage
+
+ if is_remote_storage():
+ from jiuwenswarm.channels.web.history_store.api import set_session_pinned_sync
+
+ _uid = (str(user_id).strip() if isinstance(user_id, str) and user_id.strip() else "") or "guest"
+ try:
+ result = await asyncio.to_thread(set_session_pinned_sync, sid, raw_pinned, user=_uid)
+ except Exception: # noqa: BLE001
+ logger.exception("[session.pin] remote(PG) 置顶失败: session_id=%s", sid)
+ await channel.send_response(
+ ws, req_id, ok=False,
+ error="session pin failed: history store unavailable", code="INTERNAL_ERROR",
+ )
+ return
+ if result is None:
+ await channel.send_response(
+ ws, req_id, ok=False, error="session not found", code="NOT_FOUND",
+ )
+ return
+ new_pinned, new_order = result
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"pinned": new_pinned, "pin_order": new_order},
+ )
+ return
+
from jiuwenswarm.server.runtime.session.session_metadata import set_session_pinned
result = set_session_pinned(sid, raw_pinned)
@@ -4557,12 +4588,36 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
})
await channel.send_response(ws, req_id, ok=True, payload={"project": info, **info})
- async def _project_pinned_sessions(ws, req_id, params, session_id):
+ async def _project_pinned_sessions(ws, req_id, params, session_id, user_id=None):
"""获取全部置顶会话,按 ``pin_order`` 升序排列。
置顶会话已从项目分组中剥离,通过本接口独立获取。``project_dir`` 仍指向
原归属项目。不接受任何参数。
+ remote(PG) 模式从 Web 历史库 sessions 行读取(与 session.pin 写入同源)。
"""
+ from jiuwenswarm.gateway.routing.session_index import is_remote_storage
+
+ if is_remote_storage():
+ from jiuwenswarm.channels.web.history_store.api import list_pinned_sessions_sync
+
+ _uid = (str(user_id).strip() if isinstance(user_id, str) and user_id.strip() else "") or "guest"
+ try:
+ rows = await asyncio.to_thread(list_pinned_sessions_sync, user=_uid)
+ except Exception: # noqa: BLE001
+ logger.exception("[project.pinned_sessions] remote(PG) 读取失败")
+ rows = []
+ pinned = sorted(rows, key=lambda s: int(s.get("pin_order") or 0))
+ # 历史库行的时间字段是 updated_at,而 _to_session_info 读 last_message_at——
+ # 不补映射前端会把置顶会话时间渲染成 epoch 0(与 session.list 的
+ # _db_row_to_session_info 是同一处映射,两条 remote 读路径须保持一致)。
+ await channel.send_response(ws, req_id, ok=True, payload={
+ "sessions": [
+ _to_session_info({**s, "last_message_at": s.get("updated_at", 0), "mode": "web"})
+ for s in pinned
+ ],
+ })
+ return
+
from jiuwenswarm.server.runtime.session.session_metadata import collect_all_sessions_metadata
sessions = collect_all_sessions_metadata()