"use client"; import { useCallback, useMemo, useSyncExternalStore } from "react"; import { newId } from "@/lib/random-id"; import { isKnownStorageMode, normalizeMemoryRunId, type StorageMode, } from "@/lib/memory-storage-mode"; import { clampWikiEvidence, clampWikiRetrievalError, clampWikiRetrievalGroup, MAX_WIKI_ERRORS, MAX_WIKI_EVIDENCE, MAX_WIKI_GROUPS, MAX_WIKI_SOURCES, normalizeRequiredWikiMetadata, } from "@/lib/wiki-metadata-limits"; import type { ChatMessage, MemoryFilesCacheSummary, RetrievedChunk, RetrievalGroup, WikiEvidence, WikiRetrievalError, WikiRetrievalGroup, } from "@/types/llm-chat"; import type { MemoryScope, MemorySearchHit, MemoryUnit, SourceTurnRef, } from "@/types/memory"; /** Legacy global key kept for read-only migration. */ export const CHAT_HISTORY_LEGACY_STORAGE_KEY = "tsagent.chat.sessions.v1"; /** Backwards-compatible alias for older tests/imports. */ export const CHAT_HISTORY_STORAGE_KEY = CHAT_HISTORY_LEGACY_STORAGE_KEY; /** v2 stores sessions under a project-scoped localStorage key. */ export const CHAT_HISTORY_STORAGE_KEY_PREFIX = "tsagent.chat.sessions.v2"; const UNBOUND_SCOPE = "unbound"; /** Soft cap on the number of retained sessions per project; the oldest ones * are dropped on upsert to keep localStorage usage bounded. */ const MAX_SESSIONS = 50; /** Upper bound on messages preserved per session. Long-running chats would * otherwise grow unbounded and eventually blow past the 5 MiB localStorage * quota on every browser. When a session exceeds this cap we keep the tail * (most recent messages) because older turns have little value once the * conversation has drifted. */ const MAX_MESSAGES_PER_SESSION = 200; const MAX_BACKUP_CHARACTERS = 2_000_000; /** Soft cap on a single session title, truncated from the first user turn. */ const TITLE_MAX_LENGTH = 24; /** Mount configuration captured per-session so switching sessions can restore * the exact retrieval setup the user had. Kept structural (not depending on * the context module) so this hook remains free of UI layer imports. * * Per-KB `retrieval` / `topK` 为可选 override:留空则在请求组装阶段继承会话级 * 全局参数,单 KB 自定义并不会破坏跨 KB 排序——上层在合并前就已经按 KB 各自 * 的配置打分,再由聚合 topK 统一截断。 */ export interface ChatSessionMount { id: string; knowledgeBaseName: string; subspace?: string[]; /** Per-mount retrieval override; falls back to session-wide config when omitted. */ retrieval?: ChatRetrievalConfig; /** Per-mount per-KB topK override; falls back to session-wide perKbTopK when omitted. */ topK?: number; } /** Flat retrieval configuration that mirrors a subset of `RetrievalInput`. * Kept flat (not the nested `retrievalConfiguration` shape) so it binds * directly to `RetrievalParamsFields` without an extra transform. */ export interface ChatRetrievalConfig { searchType?: ("DENSE_VECTOR" | "FULL_TEXT")[]; rerankType?: "RRF" | "WEIGHT" | "MODEL"; rrfK?: number; rrfDenseWeight?: number; rrfFullTextWeight?: number; weightDense?: number; weightFullText?: number; modelName?: string; modelProvider?: string; } export interface ChatSessionMemoryScope { appId: string; tenantId: string; agentId: string; runId: string; } export interface ChatSessionMemoryBinding { id: string; memoryStoreName: string; storageMode?: StorageMode; scope: ChatSessionMemoryScope; topK?: number; autoSave: boolean; /** 记忆检索模式(search|local)。缺省按 search 处理。 */ retrievalMode?: "search" | "local"; } export interface ChatSessionConfig { providerId?: string; model?: string; systemPrompt?: string; temperature?: number; /** Cap applied after merging and sorting results across all mounted KBs. */ aggregateTopK?: number; /** Per-KB topK passed to each `retrieve` call. Defaults to 10. */ perKbTopK?: number; /** Session-wide retrieval params shared by every mounted KB. */ retrieval?: ChatRetrievalConfig; mounts: ChatSessionMount[]; memory?: ChatSessionMemoryBinding; /** Allowlisted scalar config for the single Wiki owned by `memory` Scope. */ wiki?: { enabled: true; topK: number }; } export interface ChatSession { id: string; title: string; updatedAt: number; /** Active project at the time of the save. `null` means raw-token/env mode. */ activeInstance?: string | null; config: ChatSessionConfig; messages: ChatMessage[]; } export interface ChatHistoryScope { activeInstance: string | null; ready: boolean; } // --------------------------------------------------------------------------- // Scope + migration helpers // --------------------------------------------------------------------------- function normalizeActiveInstance(activeInstance: string | null | undefined) { return activeInstance && activeInstance.length > 0 ? activeInstance : null; } function scopeSuffix(activeInstance: string | null | undefined): string { const normalized = normalizeActiveInstance(activeInstance); return normalized ? `project.${encodeURIComponent(normalized)}` : UNBOUND_SCOPE; } export function getChatHistoryStorageKey( activeInstance: string | null | undefined, ): string { return `${CHAT_HISTORY_STORAGE_KEY_PREFIX}.${scopeSuffix(activeInstance)}`; } function belongsToScope( session: ChatSession, activeInstance: string | null | undefined, ): boolean { return ( normalizeActiveInstance(session.activeInstance) === normalizeActiveInstance(activeInstance) ); } function isRecord(raw: unknown): raw is Record { return !!raw && typeof raw === "object" && !Array.isArray(raw); } function isFiniteNumber(raw: unknown): raw is number { return typeof raw === "number" && Number.isFinite(raw); } function sanitizeRetrievedChunk(raw: unknown): RetrievedChunk | null { if (!isRecord(raw)) return null; if ( typeof raw.docId !== "string" || !isFiniteNumber(raw.chunkId) || typeof raw.ossKey !== "string" || !isFiniteNumber(raw.score) || typeof raw.content !== "string" || typeof raw.chunkType !== "string" ) { return null; } const chunk: RetrievedChunk = { docId: raw.docId, chunkId: raw.chunkId, ossKey: raw.ossKey, score: raw.score, content: raw.content, chunkType: raw.chunkType, }; if (typeof raw.imageBase64 === "string") chunk.imageBase64 = raw.imageBase64; if (typeof raw.subspace === "string") chunk.subspace = raw.subspace; if (typeof raw.knowledgeBaseName === "string") { chunk.knowledgeBaseName = raw.knowledgeBaseName; } return chunk; } function sanitizeRetrievalGroup(raw: unknown): RetrievalGroup | null { if ( !isRecord(raw) || typeof raw.knowledgeBaseName !== "string" || !Array.isArray(raw.chunks) ) { return null; } const group: RetrievalGroup = { knowledgeBaseName: raw.knowledgeBaseName, chunks: raw.chunks .map(sanitizeRetrievedChunk) .filter((chunk): chunk is RetrievedChunk => chunk !== null), }; if (typeof raw.error === "string") group.error = raw.error; return group; } function sanitizeMemoryScope(raw: unknown): MemoryScope | undefined { if (!isRecord(raw) || typeof raw.appId !== "string") return undefined; const scope: MemoryScope = { appId: raw.appId }; if (typeof raw.tenantId === "string") scope.tenantId = raw.tenantId; if (typeof raw.agentId === "string") scope.agentId = raw.agentId; if (typeof raw.runId === "string") scope.runId = raw.runId; return scope; } function sanitizeSourceTurnRef(raw: unknown): SourceTurnRef | null { if ( !isRecord(raw) || typeof raw.messageId !== "string" || !isFiniteNumber(raw.timestampMs) ) { return null; } return { messageId: raw.messageId, timestampMs: raw.timestampMs }; } function sanitizeMemoryUnit(raw: unknown): MemoryUnit | null { if (!isRecord(raw) || typeof raw.text !== "string") return null; const unit: MemoryUnit = { text: raw.text }; if (typeof raw.id === "string") unit.id = raw.id; if (typeof raw.memoryId === "string") unit.memoryId = raw.memoryId; if (typeof raw.conversation_key === "string") { unit.conversation_key = raw.conversation_key; } const scope = sanitizeMemoryScope(raw.scope); if (scope) unit.scope = scope; if (typeof raw.memcell_id === "string") unit.memcell_id = raw.memcell_id; if (typeof raw.unit_type === "string") unit.unit_type = raw.unit_type; if (Array.isArray(raw.source_turn_ids)) { unit.source_turn_ids = raw.source_turn_ids.filter( (item): item is string => typeof item === "string", ); } if (Array.isArray(raw.source_turn_refs)) { unit.source_turn_refs = raw.source_turn_refs .map(sanitizeSourceTurnRef) .filter((item): item is SourceTurnRef => item !== null); } if (typeof raw.search_text === "string") unit.search_text = raw.search_text; if (isFiniteNumber(raw.salience)) unit.salience = raw.salience; if (isFiniteNumber(raw.version)) unit.version = raw.version; if (typeof raw.deleted === "boolean") unit.deleted = raw.deleted; if (typeof raw.created_at === "string") unit.created_at = raw.created_at; if (typeof raw.updated_at === "string") unit.updated_at = raw.updated_at; if (isFiniteNumber(raw.score)) unit.score = raw.score; if (typeof raw.createdAt === "string" || isFiniteNumber(raw.createdAt)) { unit.createdAt = raw.createdAt; } if (typeof raw.updatedAt === "string" || isFiniteNumber(raw.updatedAt)) { unit.updatedAt = raw.updatedAt; } return unit; } function sanitizeMemorySearchHit(raw: unknown): MemorySearchHit | null { if (!isRecord(raw)) return null; const unit = sanitizeMemoryUnit(raw.unit); if (!unit) return null; const hit: MemorySearchHit = { unit }; if (isFiniteNumber(raw.score)) hit.score = raw.score; if (isFiniteNumber(raw.similarity)) hit.similarity = raw.similarity; if (typeof raw.source === "string") hit.source = raw.source; return hit; } function sanitizeMemoryFiles(raw: unknown): ChatMessage["memoryFiles"] { if (!Array.isArray(raw)) return undefined; return raw.flatMap((item) => { if ( !isRecord(item) || typeof item.rel !== "string" || !isFiniteNumber(item.size) ) { return []; } return [ { rel: item.rel, size: item.size, ...(typeof item.sha256 === "string" ? { sha256: item.sha256 } : {}), }, ]; }); } function sanitizeMemoryFilesCache( raw: unknown, ): MemoryFilesCacheSummary | undefined { if ( !isRecord(raw) || typeof raw.ok !== "boolean" || !isFiniteNumber(raw.listed) || !isFiniteNumber(raw.loaded) || !isFiniteNumber(raw.reused) || !isFiniteNumber(raw.totalBytes) || typeof raw.truncated !== "boolean" ) { return undefined; } const cache: MemoryFilesCacheSummary = { ok: raw.ok, listed: raw.listed, loaded: raw.loaded, reused: raw.reused, totalBytes: raw.totalBytes, truncated: raw.truncated, }; if (typeof raw.error === "string") cache.error = raw.error; return cache; } function sanitizeSessionWikiConfig( raw: unknown, hasValidMemoryBinding: boolean, ): ChatSessionConfig["wiki"] | undefined { if (!hasValidMemoryBinding || !isRecord(raw)) return undefined; if ( raw.enabled !== true || !Number.isInteger(raw.topK) || (raw.topK as number) < 1 || (raw.topK as number) > 10 ) { return undefined; } return { enabled: true, topK: raw.topK as number }; } function sanitizeWikiEvidence(raw: unknown): WikiEvidence | null { if (!raw || typeof raw !== "object") return null; const value = raw as Record; const wikiName = normalizeRequiredWikiMetadata(value.wikiName); const path = normalizeRequiredWikiMetadata(value.path); if ( typeof value.reference !== "string" || !/^W[1-6]$/.test(value.reference) || !wikiName || !path || typeof value.truncated !== "boolean" || !Number.isInteger(value.injectedChars) || (value.injectedChars as number) < 0 || (value.injectedChars as number) > 8_000 ) { return null; } return clampWikiEvidence({ reference: value.reference as `W${number}`, wikiName, path, ...(typeof value.title === "string" ? { title: value.title } : {}), ...(typeof value.type === "string" ? { type: value.type } : {}), ...(typeof value.description === "string" ? { description: value.description } : {}), ...(typeof value.score === "number" ? { score: value.score } : {}), ...(Array.isArray(value.sources) ? { sources: value.sources .slice(0, MAX_WIKI_SOURCES) .filter((item): item is string => typeof item === "string"), } : {}), truncated: value.truncated, injectedChars: value.injectedChars as number, }); } function sanitizeWikiRetrievalError(raw: unknown): WikiRetrievalError | null { if (!raw || typeof raw !== "object") return null; const value = raw as Record; const code = normalizeRequiredWikiMetadata(value.code); const message = normalizeRequiredWikiMetadata(value.message); if ( !code || !message || (value.stage !== "validate" && value.stage !== "search" && value.stage !== "read" && value.stage !== "budget") ) { return null; } return clampWikiRetrievalError({ code, message, ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), ...(typeof value.httpStatus === "number" ? { httpStatus: value.httpStatus } : {}), stage: value.stage, ...(typeof value.path === "string" ? { path: value.path } : {}), }); } function sanitizeWikiRetrievalGroup(raw: unknown): WikiRetrievalGroup | null { if (!raw || typeof raw !== "object") return null; const value = raw as Record; const wikiName = normalizeRequiredWikiMetadata(value.wikiName); if (!wikiName || !Array.isArray(value.pages)) { return null; } return clampWikiRetrievalGroup({ wikiName, pages: value.pages .slice(0, MAX_WIKI_EVIDENCE) .map(sanitizeWikiEvidence) .filter((page): page is WikiEvidence => page !== null), ...(Array.isArray(value.errors) ? { errors: value.errors .slice(0, MAX_WIKI_ERRORS) .map(sanitizeWikiRetrievalError) .filter((error): error is WikiRetrievalError => error !== null), } : {}), }); } function sanitizeWikiScope(raw: unknown): ChatMessage["wikiScope"] | null { if (!raw || typeof raw !== "object") return null; const value = raw as Record; if ( typeof value.appId !== "string" || typeof value.tenantId !== "string" || typeof value.agentId !== "string" || typeof value.runId !== "string" ) { return null; } return { appId: value.appId, tenantId: value.tenantId, agentId: value.agentId, runId: value.runId, }; } function sanitizeSessionMessages(messages: unknown[]): ChatMessage[] { return messages.flatMap((message) => { if (!isRecord(message)) return []; const { id, role, content, createdAt } = message; if ( typeof id !== "string" || (role !== "user" && role !== "assistant" && role !== "system") || typeof content !== "string" || !isFiniteNumber(createdAt) ) { return []; } const value = message; const sanitized: ChatMessage = { id, role, content, createdAt, }; if (typeof value.reasoning === "string") sanitized.reasoning = value.reasoning; if (isFiniteNumber(value.reasoningStartedAt)) { sanitized.reasoningStartedAt = value.reasoningStartedAt; } if (isFiniteNumber(value.reasoningCompletedAt)) { sanitized.reasoningCompletedAt = value.reasoningCompletedAt; } if (typeof value.usingRag === "boolean") sanitized.usingRag = value.usingRag; if (typeof value.queryRewriteFailed === "boolean") { sanitized.queryRewriteFailed = value.queryRewriteFailed; } if (typeof value.queryRewriteError === "string") { sanitized.queryRewriteError = value.queryRewriteError; } if (typeof value.retrievalQuery === "string") { sanitized.retrievalQuery = value.retrievalQuery; } if (typeof value.retrievalQueryRewritten === "boolean") { sanitized.retrievalQueryRewritten = value.retrievalQueryRewritten; } if (Array.isArray(value.retrievedChunks)) { sanitized.retrievedChunks = value.retrievedChunks .map(sanitizeRetrievedChunk) .filter((chunk): chunk is RetrievedChunk => chunk !== null); } if (Array.isArray(value.retrievalGroups)) { sanitized.retrievalGroups = value.retrievalGroups .map(sanitizeRetrievalGroup) .filter((group): group is RetrievalGroup => group !== null); } if (Array.isArray(value.memoryHits)) { sanitized.memoryHits = value.memoryHits .map(sanitizeMemorySearchHit) .filter((hit): hit is MemorySearchHit => hit !== null); } if (typeof value.memoryQuery === "string") { sanitized.memoryQuery = value.memoryQuery; } if (typeof value.wikiQuery === "string") { sanitized.wikiQuery = value.wikiQuery; } if (Number.isInteger(value.wikiCount) && (value.wikiCount as number) >= 0) { sanitized.wikiCount = value.wikiCount as number; } if (typeof value.wikiRetrievalDone === "boolean") { sanitized.wikiRetrievalDone = value.wikiRetrievalDone; } if (Array.isArray(value.wikiEvidence)) { sanitized.wikiEvidence = value.wikiEvidence .slice(0, MAX_WIKI_EVIDENCE) .map(sanitizeWikiEvidence) .filter((page): page is WikiEvidence => page !== null); } if (Array.isArray(value.wikiRetrievalGroups)) { sanitized.wikiRetrievalGroups = value.wikiRetrievalGroups .slice(0, MAX_WIKI_GROUPS) .map(sanitizeWikiRetrievalGroup) .filter((group): group is WikiRetrievalGroup => group !== null); } if ( Number.isInteger(value.wikiTotalContextChars) && (value.wikiTotalContextChars as number) >= 0 ) { sanitized.wikiTotalContextChars = value.wikiTotalContextChars as number; } if (typeof value.wikiMemoryStoreName === "string") { sanitized.wikiMemoryStoreName = value.wikiMemoryStoreName; } const wikiScope = sanitizeWikiScope(value.wikiScope); if (wikiScope) sanitized.wikiScope = wikiScope; const memoryFiles = sanitizeMemoryFiles(value.memoryFiles); if (memoryFiles) sanitized.memoryFiles = memoryFiles; const memoryFilesCache = sanitizeMemoryFilesCache(value.memoryFilesCache); if (memoryFilesCache) sanitized.memoryFilesCache = memoryFilesCache; if (typeof value.memoryFilesStoreName === "string") { sanitized.memoryFilesStoreName = value.memoryFilesStoreName; } if (typeof value.memoryFilesWritable === "boolean") { sanitized.memoryFilesWritable = value.memoryFilesWritable; } const memoryFilesScope = sanitizeWikiScope(value.memoryFilesScope); if (memoryFilesScope) sanitized.memoryFilesScope = memoryFilesScope; if ( value.memorySaveStatus === "saving" || value.memorySaveStatus === "saved" || value.memorySaveStatus === "unchanged" || value.memorySaveStatus === "error" ) { sanitized.memorySaveStatus = value.memorySaveStatus; } if (typeof value.memorySavePath === "string") { sanitized.memorySavePath = value.memorySavePath; } if (isFiniteNumber(value.memorySaveCount)) { sanitized.memorySaveCount = value.memorySaveCount; } if (typeof value.memorySaveError === "string") { sanitized.memorySaveError = value.memorySaveError; } if (typeof value.turnId === "string") sanitized.turnId = value.turnId; if ( value.status === "streaming" || value.status === "done" || value.status === "error" ) { sanitized.status = value.status; } if (typeof value.errorMessage === "string") { sanitized.errorMessage = value.errorMessage; } if (sanitized.memorySaveStatus === "saving") { delete sanitized.memorySaveStatus; delete sanitized.memorySavePath; delete sanitized.memorySaveCount; delete sanitized.memorySaveError; } return [sanitized]; }); } const FNV64_OFFSET_BASIS = BigInt("14695981039346656037"); const FNV64_PRIME = BigInt("1099511628211"); function createLegacyRunId(seed: string): string { let hash = FNV64_OFFSET_BASIS; for (const byte of new TextEncoder().encode(seed)) { hash ^= BigInt(byte); hash = BigInt.asUintN(64, hash * FNV64_PRIME); } return `run_legacy_${hash.toString(16).padStart(16, "0")}`; } function sanitizeRetrievalConfig( raw: unknown, ): ChatRetrievalConfig | undefined { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; const value = raw as Record; const retrieval: ChatRetrievalConfig = {}; if (Array.isArray(value.searchType)) { retrieval.searchType = value.searchType.filter( (item): item is "DENSE_VECTOR" | "FULL_TEXT" => item === "DENSE_VECTOR" || item === "FULL_TEXT", ); } if ( value.rerankType === "RRF" || value.rerankType === "WEIGHT" || value.rerankType === "MODEL" ) { retrieval.rerankType = value.rerankType; } if (isFiniteNumber(value.rrfK)) retrieval.rrfK = value.rrfK; if (isFiniteNumber(value.rrfDenseWeight)) { retrieval.rrfDenseWeight = value.rrfDenseWeight; } if (isFiniteNumber(value.rrfFullTextWeight)) { retrieval.rrfFullTextWeight = value.rrfFullTextWeight; } if (isFiniteNumber(value.weightDense)) { retrieval.weightDense = value.weightDense; } if (isFiniteNumber(value.weightFullText)) { retrieval.weightFullText = value.weightFullText; } if (typeof value.modelName === "string") { retrieval.modelName = value.modelName; } if (typeof value.modelProvider === "string") { retrieval.modelProvider = value.modelProvider; } return retrieval; } function sanitizeSessionMounts(raw: unknown): ChatSessionMount[] { if (!Array.isArray(raw)) return []; return raw.flatMap((item) => { if (!item || typeof item !== "object") return []; const value = item as Record; if ( typeof value.id !== "string" || typeof value.knowledgeBaseName !== "string" ) { return []; } const mount: ChatSessionMount = { id: value.id, knowledgeBaseName: value.knowledgeBaseName, }; if ( Array.isArray(value.subspace) && value.subspace.length > 0 && value.subspace.every((entry) => typeof entry === "string") ) { mount.subspace = value.subspace as string[]; } const retrieval = sanitizeRetrievalConfig(value.retrieval); if (retrieval) mount.retrieval = retrieval; if (isFiniteNumber(value.topK)) mount.topK = value.topK; return [mount]; }); } function sanitizeSessionConfig( raw: unknown, sessionId: string, normalizeRunId: boolean, ): ChatSessionConfig { const value = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {}; const memory = sanitizeMemoryBinding(value.memory, sessionId, normalizeRunId); const config: ChatSessionConfig = { mounts: sanitizeSessionMounts(value.mounts), }; if (typeof value.providerId === "string") config.providerId = value.providerId; if (typeof value.model === "string") config.model = value.model; if (typeof value.systemPrompt === "string") { config.systemPrompt = value.systemPrompt; } if (isFiniteNumber(value.temperature)) { config.temperature = value.temperature; } if (isFiniteNumber(value.aggregateTopK)) { config.aggregateTopK = value.aggregateTopK; } if (isFiniteNumber(value.perKbTopK)) { config.perKbTopK = value.perKbTopK; } const retrieval = sanitizeRetrievalConfig(value.retrieval); if (retrieval) config.retrieval = retrieval; if (memory) config.memory = memory; const wiki = sanitizeSessionWikiConfig( value.wiki, memory?.storageMode !== undefined, ); if (wiki) config.wiki = wiki; return config; } function sanitizeSessions(parsed: unknown): ChatSession[] { if (!Array.isArray(parsed)) return []; const sessions = parsed.filter( (s): s is ChatSession => !!s && typeof s === "object" && typeof (s as ChatSession).id === "string" && typeof (s as ChatSession).title === "string" && isFiniteNumber((s as ChatSession).updatedAt) && Array.isArray((s as ChatSession).messages), ); return sessions.map((s) => { return { id: s.id, title: s.title, updatedAt: s.updatedAt, activeInstance: normalizeActiveInstance(s.activeInstance), config: sanitizeSessionConfig(s.config, s.id, true), messages: sanitizeSessionMessages(s.messages), }; }); } function sanitizeMemoryBinding( raw: unknown, sessionId: string, normalizeRunId = true, ): ChatSessionMemoryBinding | undefined { if (!raw || typeof raw !== "object") return undefined; const r = raw as Partial; if (typeof r.memoryStoreName !== "string" || !r.memoryStoreName) return undefined; const s = r.scope; if ( !s || typeof s.appId !== "string" || typeof s.tenantId !== "string" || typeof s.agentId !== "string" || typeof s.runId !== "string" || !s.appId || !s.tenantId || !s.agentId ) { return undefined; } const runId = normalizeRunId ? normalizeMemoryRunId(r.storageMode, s.runId, () => createLegacyRunId( JSON.stringify([ sessionId, r.memoryStoreName, s.appId, s.tenantId, s.agentId, ]), ), ) : s.runId; return { // 缺失 binding id 只可能来自老快照或手动损坏的数据;写 scope 的 runId // 则在上方用会话与 scope seed 做确定性修复,不依赖这个临时 UI key。 id: typeof r.id === "string" && r.id ? r.id : newId("memory"), memoryStoreName: r.memoryStoreName, ...(isKnownStorageMode(r.storageMode) ? { storageMode: r.storageMode } : {}), scope: { appId: s.appId, tenantId: s.tenantId, agentId: s.agentId, runId, }, ...(Number.isInteger(r.topK) && (r.topK as number) > 0 ? { topK: r.topK as number } : {}), autoSave: r.autoSave !== false, // 保留检索模式,否则文件记忆选择在会话重载后会丢失(回退到语义检索)。 ...(r.retrievalMode === "local" || r.retrievalMode === "search" ? { retrievalMode: r.retrievalMode } : {}), }; } interface ChatHistorySnapshotRead { token: string; sessions: ChatSession[]; } function rawSessionBelongsToScope( candidate: unknown, activeInstance: string | null, ): boolean { if (!candidate || typeof candidate !== "object") return false; return ( normalizeActiveInstance( (candidate as Partial).activeInstance, ) === activeInstance ); } function readChatHistorySnapshot( activeInstance: string | null, ): ChatHistorySnapshotRead { if (typeof window === "undefined") { return { token: "server", sessions: [] }; } const scopedKey = getChatHistoryStorageKey(activeInstance); try { const scopedRaw = window.localStorage.getItem(scopedKey); const usesLegacy = scopedRaw === null; const raw = usesLegacy ? window.localStorage.getItem(CHAT_HISTORY_LEGACY_STORAGE_KEY) : scopedRaw; const parsed = raw ? JSON.parse(raw) : []; const candidates = Array.isArray(parsed) ? parsed : []; const scopedCandidates = usesLegacy ? candidates.filter((candidate) => rawSessionBelongsToScope(candidate, activeInstance), ) : candidates; const sessions = sanitizeSessions(scopedCandidates) .filter((candidate) => belongsToScope(candidate, activeInstance)) .sort((a, b) => b.updatedAt - a.updatedAt); const token = usesLegacy ? `legacy\0${JSON.stringify(scopedCandidates)}` : `v2\0${raw ?? ""}`; return { token, sessions }; } catch { return { token: "storage-error", sessions: [] }; } } function readAll(activeInstance: string | null): ChatSession[] { return readChatHistorySnapshot(activeInstance).sessions; } function isQuotaError(err: unknown): boolean { // Firefox uses `NS_ERROR_DOM_QUOTA_REACHED`, Safari/Chrome use // `QuotaExceededError`; both surface as a DOMException with one of those // names. Guard on both so the recovery path triggers consistently. if (!err || typeof err !== "object") return false; const name = (err as { name?: unknown }).name; return name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED"; } function dispatchStorageEvent(storageKey: string): void { if (typeof window === "undefined") return; try { window.dispatchEvent(new StorageEvent("storage", { key: storageKey })); } catch { window.dispatchEvent(new Event("storage")); } } function writeStorageKey(storageKey: string, sessions: ChatSession[]): void { if (typeof window === "undefined") return; // Try the full list first; on quota failure, progressively drop the // oldest sessions and retry. We bottom out at the newest single session // — below that the caller's write was itself too large and there is // nothing we can do besides swallow the error. let remaining = sessions; for (let attempt = 0; attempt < 3; attempt += 1) { try { const serialized = JSON.stringify(remaining); window.localStorage.setItem(storageKey, serialized); // Manually dispatch so same-tab subscribers react without relying on // the native `storage` event, which only fires cross-tab. dispatchStorageEvent(storageKey); return; } catch (err) { if (!isQuotaError(err) || remaining.length <= 1) { // Non-quota errors (disabled storage, private-mode restrictions) // or an already-minimal payload: nothing we can meaningfully do. return; } // Drop the oldest quarter and retry. `remaining` is assumed sorted // newest-first by the caller (`upsertSession` trims and sorts // before calling writeStorageKey). const keep = Math.max(1, Math.floor(remaining.length * 0.75)); remaining = remaining.slice(0, keep); } } } function writeAll( activeInstance: string | null, sessions: ChatSession[], ): void { writeStorageKey(getChatHistoryStorageKey(activeInstance), sessions); } // --------------------------------------------------------------------------- // Pure helpers // --------------------------------------------------------------------------- /** Build a human-readable title from the first user message, truncated. */ export function deriveSessionTitle( messages: ChatMessage[], fallback = "新对话", ): string { const firstUser = messages.find((m) => m.role === "user"); if (!firstUser) return fallback; const clean = firstUser.content.replace(/\s+/g, " ").trim(); if (!clean) return fallback; return clean.length > TITLE_MAX_LENGTH ? `${clean.slice(0, TITLE_MAX_LENGTH)}…` : clean; } export function listSessions( activeInstance: string | null | undefined, ): ChatSession[] { return readAll(normalizeActiveInstance(activeInstance)); } /** Portable snapshots keep the original messages, evidence, and config. */ export function exportChatSessions(sessions: ChatSession[]): string { const backup = JSON.stringify( { format: "agent-storage-chat", version: 1, sessions: sanitizeSessions(sessions), }, null, 2, ); if (backup.length > MAX_BACKUP_CHARACTERS) throw new Error("backupLimit"); return backup; } /** Compare JSON values without depending on object-key insertion order. */ function sameBackupValue(left: unknown, right: unknown): boolean { if (left === right) return true; if (Array.isArray(left) && Array.isArray(right)) return ( left.length === right.length && left.every((value, i) => sameBackupValue(value, right[i])) ); if (!isRecord(left) || !isRecord(right)) return false; const keys = Object.keys(left); return ( keys.length === Object.keys(right).length && keys.every( (key) => Object.hasOwn(right, key) && sameBackupValue(left[key], right[key]), ) ); } /** Import atomically; never overwrite a local conversation or evict history. */ export function importChatSessions( text: string, activeInstance: string | null, ): { imported: number; skipped: number } { if (text.length > MAX_BACKUP_CHARACTERS) throw new Error("backupLimit"); let parsed: unknown; try { parsed = JSON.parse(text); } catch { throw new Error("invalidBackup"); } if ( !isRecord(parsed) || parsed.format !== "agent-storage-chat" || parsed.version !== 1 || !Array.isArray(parsed.sessions) || !parsed.sessions.length ) { throw new Error("invalidBackup"); } const rawSessions = parsed.sessions; if (rawSessions.length > MAX_SESSIONS) throw new Error("backupLimit"); const incoming = sanitizeSessions(rawSessions); if ( !sameBackupValue(rawSessions, JSON.parse(JSON.stringify(incoming))) || new Set(incoming.map((session) => session.id)).size !== incoming.length || incoming.some( (session, index) => !session.id || session.messages.length !== rawSessions[index].messages.length || new Set(session.messages.map((message) => message.id)).size !== session.messages.length, ) ) throw new Error("invalidBackup"); const scope = normalizeActiveInstance(activeInstance); if (incoming.some((session) => !belongsToScope(session, scope))) throw new Error("backupProject"); if ( incoming.some( (session) => session.messages.length > MAX_MESSAGES_PER_SESSION, ) ) throw new Error("backupLimit"); const merged = new Map( readAll(scope).map((session) => [session.id, session]), ); let imported = 0; for (const session of incoming) { if (!merged.has(session.id)) { merged.set(session.id, session); imported++; } } if (merged.size > MAX_SESSIONS) throw new Error("backupLimit"); const storageKey = getChatHistoryStorageKey(scope); try { window.localStorage.setItem( storageKey, JSON.stringify( [...merged.values()].sort((a, b) => b.updatedAt - a.updatedAt), ), ); } catch { throw new Error("backupStorage"); } dispatchStorageEvent(storageKey); return { imported, skipped: incoming.length - imported }; } export function getSession( id: string, activeInstance: string | null | undefined, ): ChatSession | null { return listSessions(activeInstance).find((s) => s.id === id) ?? null; } export function upsertSession( session: ChatSession, activeInstance: string | null | undefined, ): void { if ( typeof session.id !== "string" || typeof session.title !== "string" || !isFiniteNumber(session.updatedAt) || !Array.isArray(session.messages) ) { return; } const scope = normalizeActiveInstance(activeInstance); const all = readAll(scope); // Truncate the session's message list to the tail so a single runaway // conversation cannot consume the whole localStorage budget. const scopedSession: ChatSession = { id: session.id, title: session.title, updatedAt: session.updatedAt, activeInstance: scope, config: sanitizeSessionConfig(session.config, session.id, false), messages: sanitizeSessionMessages(session.messages), }; if (scopedSession.messages.length > MAX_MESSAGES_PER_SESSION) { scopedSession.messages = scopedSession.messages.slice( -MAX_MESSAGES_PER_SESSION, ); } const capped = scopedSession; const idx = all.findIndex((s) => s.id === capped.id); if (idx >= 0) { all[idx] = capped; } else { all.push(capped); } // Evict oldest beyond the cap after sorting newest-first. const trimmed = all .sort((a, b) => b.updatedAt - a.updatedAt) .slice(0, MAX_SESSIONS); writeAll(scope, trimmed); } export function deleteSession( id: string, activeInstance: string | null | undefined, ): void { const scope = normalizeActiveInstance(activeInstance); const all = readAll(scope).filter((s) => s.id !== id); writeAll(scope, all); } export function clearAllSessions( activeInstance: string | null | undefined, ): void { writeAll(normalizeActiveInstance(activeInstance), []); } // --------------------------------------------------------------------------- // React hook // --------------------------------------------------------------------------- type Listener = () => void; function subscribeToStorageKeys( storageKey: string | null, listener: Listener, ): () => void { if (!storageKey || typeof window === "undefined") return () => {}; const handler = (event: StorageEvent) => { if ( event.key && event.key !== storageKey && event.key !== CHAT_HISTORY_LEGACY_STORAGE_KEY ) { return; } listener(); }; window.addEventListener("storage", handler); return () => { window.removeEventListener("storage", handler); }; } // Cache snapshots per storage key so `useSyncExternalStore` can return a // stable reference when nothing changed. const snapshotCache = new Map< string, { token: string; snapshot: ChatSession[] } >(); const EMPTY_SESSIONS: ChatSession[] = []; /** * Cached read-only snapshot used by `useSyncExternalStore`. Exported so * identity-sensitive consumers can verify that unrelated project changes do * not replace a scope's array reference. */ export function getChatHistorySnapshot( activeInstance: string | null | undefined, ): ChatSession[] { const scope = normalizeActiveInstance(activeInstance); const storageKey = getChatHistoryStorageKey(scope); const { token, sessions } = readChatHistorySnapshot(scope); const cached = snapshotCache.get(storageKey); if (cached?.token === token) return cached.snapshot; snapshotCache.set(storageKey, { token, snapshot: sessions }); return sessions; } function getServerSnapshot(): ChatSession[] { return EMPTY_SESSIONS; } export interface UseChatHistoryResult { sessions: ChatSession[]; upsert(session: ChatSession): void; remove(id: string): void; clear(): void; get(id: string): ChatSession | null; } export function useChatHistory(scope: ChatHistoryScope): UseChatHistoryResult { const activeInstance = normalizeActiveInstance(scope.activeInstance); const storageKey = scope.ready ? getChatHistoryStorageKey(activeInstance) : null; const subscribe = useCallback( (listener: Listener) => subscribeToStorageKeys(storageKey, listener), [storageKey], ); const getSnapshot = useCallback( () => scope.ready ? getChatHistorySnapshot(activeInstance) : EMPTY_SESSIONS, [activeInstance, scope.ready], ); const sessions = useSyncExternalStore( subscribe, getSnapshot, getServerSnapshot, ); const upsert = useCallback( (session: ChatSession) => { if (!scope.ready) return; upsertSession(session, activeInstance); }, [activeInstance, scope.ready], ); const remove = useCallback( (id: string) => { if (!scope.ready) return; deleteSession(id, activeInstance); }, [activeInstance, scope.ready], ); const clear = useCallback(() => { if (!scope.ready) return; clearAllSessions(activeInstance); }, [activeInstance, scope.ready]); const get = useCallback( (id: string) => (scope.ready ? getSession(id, activeInstance) : null), [activeInstance, scope.ready], ); return useMemo( () => ({ sessions, upsert, remove, clear, get }), [sessions, upsert, remove, clear, get], ); }