327 lines
11 KiB
JavaScript
327 lines
11 KiB
JavaScript
import { splitCopilotResponse } from "./copilot-stream.js";
|
|
|
|
const COPILOT_DB_NAME = "planet-earth-copilot-store";
|
|
const COPILOT_DB_VERSION = 1;
|
|
const SESSIONS_STORE = "sessions";
|
|
const META_STORE = "meta";
|
|
const ACTIVE_SESSION_META_KEY = "active_session_id";
|
|
const MEMORY_NOTES_META_KEY = "memory_notes";
|
|
|
|
export const MAX_SAVED_SESSIONS = 30;
|
|
export const MAX_SAVED_TURNS_PER_SESSION = 24;
|
|
export const MAX_MEMORY_NOTES = 12;
|
|
|
|
/**
|
|
* Derive a short readable title from the first completed/user question in a session.
|
|
*/
|
|
export function deriveSessionTitle(turns, fallbackLabel = "新对话") {
|
|
const firstQuestion = (Array.isArray(turns) ? turns : [])
|
|
.map((t) => String(t?.question || "").trim())
|
|
.find(Boolean);
|
|
if (!firstQuestion) return fallbackLabel;
|
|
return firstQuestion.length > 28 ? `${firstQuestion.slice(0, 28)}…` : firstQuestion;
|
|
}
|
|
|
|
/**
|
|
* Serialize completed turns into sanitized `{ role, content }` history without `<think>` blocks.
|
|
*/
|
|
export function buildTurnHistoryPayload(turns, { maxMessages = 24 } = {}) {
|
|
const out = [];
|
|
for (const turn of Array.isArray(turns) ? turns : []) {
|
|
if (!turn || turn.status !== "done") continue;
|
|
const q = String(turn.question || "").trim();
|
|
if (!q) continue;
|
|
const rawAns = String(turn.rawText || turn.reply?.answer_markdown || "").trim();
|
|
const { markdown } = splitCopilotResponse(rawAns, turn.rawReasoning || "");
|
|
const cleanAns = (markdown || rawAns).trim();
|
|
if (!cleanAns) continue;
|
|
out.push({ role: "user", content: q.slice(0, 2000) });
|
|
out.push({ role: "assistant", content: cleanAns.slice(0, 4000) });
|
|
}
|
|
return out.slice(-Math.max(2, maxMessages));
|
|
}
|
|
|
|
function sanitizeStoredTurn(turn) {
|
|
if (!turn || typeof turn !== "object") return null;
|
|
const question = String(turn.question || "").trim();
|
|
if (!question) return null;
|
|
// Never persist in-flight loading spinners across restarts.
|
|
const status = (turn.status === "done" || turn.status === "error" || turn.status === "cancelled")
|
|
? turn.status
|
|
: "cancelled";
|
|
return {
|
|
id: String(turn.id || ""),
|
|
runId: turn.runId ? String(turn.runId) : null,
|
|
domain: String(turn.domain || "global"),
|
|
question,
|
|
status,
|
|
reply: turn.reply && typeof turn.reply === "object" ? turn.reply : null,
|
|
rawText: String(turn.rawText || ""),
|
|
rawReasoning: String(turn.rawReasoning || ""),
|
|
provider: turn.provider ? String(turn.provider) : null,
|
|
model: turn.model ? String(turn.model) : null,
|
|
generationMode: turn.generationMode ? String(turn.generationMode) : null,
|
|
thinkingUserToggled: turn.thinkingUserToggled ?? null,
|
|
viewSpec: turn.viewSpec && typeof turn.viewSpec === "object" ? turn.viewSpec : null,
|
|
sceneSpec: turn.sceneSpec && typeof turn.sceneSpec === "object" ? turn.sceneSpec : null,
|
|
resultId: turn.resultId ?? null,
|
|
revision: turn.revision ?? null,
|
|
zeroToken: turn.zeroToken !== false,
|
|
evidence: turn.evidence && typeof turn.evidence === "object" ? turn.evidence : {},
|
|
activeEvidenceId: turn.activeEvidenceId ?? null,
|
|
matrixModeOverride: turn.matrixModeOverride ?? null,
|
|
collapsedBlocks: turn.collapsedBlocks && typeof turn.collapsedBlocks === "object" ? turn.collapsedBlocks : {},
|
|
errorIcon: turn.errorIcon ? String(turn.errorIcon) : "error",
|
|
errorText: String(turn.errorText || ""),
|
|
};
|
|
}
|
|
|
|
function sanitizeMemoryNotesList(items) {
|
|
const out = [];
|
|
const seen = new Set();
|
|
for (const item of Array.isArray(items) ? items : []) {
|
|
const rawText = typeof item === "string" ? item : item?.text;
|
|
const text = String(rawText || "").replace(/\s+/g, " ").trim().slice(0, 160);
|
|
if (!text || seen.has(text)) continue;
|
|
seen.add(text);
|
|
out.push({
|
|
id: String((typeof item === "object" && item?.id) || `mem-${out.length + 1}-${Date.now().toString(36)}`),
|
|
text,
|
|
updatedAt: Number(typeof item === "object" && item?.updatedAt) || Date.now(),
|
|
});
|
|
if (out.length >= MAX_MEMORY_NOTES) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Create a Desktop + Web unified conversation & memory store backed by IndexedDB
|
|
* (with automatic per-instance in-memory fallback when IndexedDB is unavailable).
|
|
*/
|
|
export function createCopilotStore({ useIndexedDb = true } = {}) {
|
|
let dbPromise = null;
|
|
const memSessions = new Map();
|
|
const memMeta = new Map();
|
|
|
|
function openDb() {
|
|
if (!useIndexedDb || typeof indexedDB === "undefined") {
|
|
return Promise.resolve(null);
|
|
}
|
|
if (dbPromise) return dbPromise;
|
|
dbPromise = new Promise((resolve) => {
|
|
try {
|
|
const request = indexedDB.open(COPILOT_DB_NAME, COPILOT_DB_VERSION);
|
|
request.onupgradeneeded = () => {
|
|
const db = request.result;
|
|
if (!db.objectStoreNames.contains(SESSIONS_STORE)) {
|
|
db.createObjectStore(SESSIONS_STORE, { keyPath: "id" });
|
|
}
|
|
if (!db.objectStoreNames.contains(META_STORE)) {
|
|
db.createObjectStore(META_STORE, { keyPath: "key" });
|
|
}
|
|
};
|
|
request.onsuccess = () => resolve(request.result);
|
|
request.onerror = () => {
|
|
dbPromise = null;
|
|
resolve(null);
|
|
};
|
|
} catch {
|
|
dbPromise = null;
|
|
resolve(null);
|
|
}
|
|
});
|
|
return dbPromise;
|
|
}
|
|
|
|
async function listSessions() {
|
|
const db = await openDb();
|
|
let rows;
|
|
if (!db) {
|
|
rows = [...memSessions.values()];
|
|
} else {
|
|
rows = await new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(SESSIONS_STORE, "readonly");
|
|
const store = tx.objectStore(SESSIONS_STORE);
|
|
const req = store.getAll();
|
|
req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []);
|
|
req.onerror = () => resolve([]);
|
|
} catch {
|
|
resolve([]);
|
|
}
|
|
});
|
|
}
|
|
return rows
|
|
.filter((r) => r && typeof r === "object" && r.id)
|
|
.sort((a, b) => (Number(b.updatedAt) || 0) - (Number(a.updatedAt) || 0));
|
|
}
|
|
|
|
async function getSession(id) {
|
|
if (!id) return null;
|
|
const db = await openDb();
|
|
if (!db) {
|
|
return memSessions.get(String(id)) || null;
|
|
}
|
|
return new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(SESSIONS_STORE, "readonly");
|
|
const req = tx.objectStore(SESSIONS_STORE).get(String(id));
|
|
req.onsuccess = () => resolve(req.result || null);
|
|
req.onerror = () => resolve(null);
|
|
} catch {
|
|
resolve(null);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function deleteSession(id) {
|
|
if (!id) return;
|
|
const key = String(id);
|
|
const db = await openDb();
|
|
if (!db) {
|
|
memSessions.delete(key);
|
|
if (memMeta.get(ACTIVE_SESSION_META_KEY) === key) {
|
|
memMeta.delete(ACTIVE_SESSION_META_KEY);
|
|
}
|
|
return;
|
|
}
|
|
await new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(SESSIONS_STORE, "readwrite");
|
|
tx.objectStore(SESSIONS_STORE).delete(key);
|
|
tx.oncomplete = () => resolve();
|
|
tx.onerror = () => resolve();
|
|
tx.onabort = () => resolve();
|
|
} catch {
|
|
resolve();
|
|
}
|
|
});
|
|
const activeId = await getActiveSessionId();
|
|
if (activeId === key) {
|
|
await setActiveSessionId(null);
|
|
}
|
|
}
|
|
|
|
async function saveSession(record) {
|
|
if (!record || !record.id) return null;
|
|
const cleanTurns = (Array.isArray(record.turns) ? record.turns : [])
|
|
.map(sanitizeStoredTurn)
|
|
.filter(Boolean)
|
|
.slice(-MAX_SAVED_TURNS_PER_SESSION);
|
|
if (!cleanTurns.length) return null;
|
|
|
|
const normalized = {
|
|
id: String(record.id),
|
|
title: String(record.title || deriveSessionTitle(cleanTurns)),
|
|
domain: String(record.domain || "global"),
|
|
serverSessionId: record.serverSessionId ? String(record.serverSessionId) : null,
|
|
serverSessionToken: record.serverSessionToken ? String(record.serverSessionToken) : null,
|
|
contextState: record.contextState && typeof record.contextState === "object" ? { ...record.contextState } : {},
|
|
pinnedItems: Array.isArray(record.pinnedItems) ? record.pinnedItems.slice(0, 12) : [],
|
|
conversationSummary: String(record.conversationSummary || ""),
|
|
compactedCount: Number(record.compactedCount) || 0,
|
|
turns: cleanTurns,
|
|
createdAt: Number(record.createdAt) || Date.now(),
|
|
updatedAt: Number(record.updatedAt) || Date.now(),
|
|
};
|
|
|
|
const db = await openDb();
|
|
if (!db) {
|
|
memSessions.set(normalized.id, normalized);
|
|
const all = await listSessions();
|
|
for (const extra of all.slice(MAX_SAVED_SESSIONS)) {
|
|
memSessions.delete(extra.id);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
await new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(SESSIONS_STORE, "readwrite");
|
|
tx.objectStore(SESSIONS_STORE).put(normalized);
|
|
tx.oncomplete = () => resolve();
|
|
tx.onerror = () => resolve();
|
|
tx.onabort = () => resolve();
|
|
} catch {
|
|
resolve();
|
|
}
|
|
});
|
|
|
|
const all = await listSessions();
|
|
for (const extra of all.slice(MAX_SAVED_SESSIONS)) {
|
|
await deleteSession(extra.id);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
async function readMeta(key, fallbackValue = null) {
|
|
const db = await openDb();
|
|
if (!db) {
|
|
return memMeta.has(key) ? memMeta.get(key) : fallbackValue;
|
|
}
|
|
return new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readonly");
|
|
const req = tx.objectStore(META_STORE).get(key);
|
|
req.onsuccess = () => resolve(req.result ? req.result.value : fallbackValue);
|
|
req.onerror = () => resolve(fallbackValue);
|
|
} catch {
|
|
resolve(fallbackValue);
|
|
}
|
|
});
|
|
}
|
|
|
|
async function writeMeta(key, value) {
|
|
const db = await openDb();
|
|
if (!db) {
|
|
if (value === null || value === undefined) memMeta.delete(key);
|
|
else memMeta.set(key, value);
|
|
return;
|
|
}
|
|
await new Promise((resolve) => {
|
|
try {
|
|
const tx = db.transaction(META_STORE, "readwrite");
|
|
const store = tx.objectStore(META_STORE);
|
|
if (value === null || value === undefined) store.delete(key);
|
|
else store.put({ key, value });
|
|
tx.oncomplete = () => resolve();
|
|
tx.onerror = () => resolve();
|
|
tx.onabort = () => resolve();
|
|
} catch {
|
|
resolve();
|
|
}
|
|
});
|
|
}
|
|
|
|
async function getActiveSessionId() {
|
|
const val = await readMeta(ACTIVE_SESSION_META_KEY, null);
|
|
return val ? String(val) : null;
|
|
}
|
|
|
|
async function setActiveSessionId(id) {
|
|
await writeMeta(ACTIVE_SESSION_META_KEY, id ? String(id) : null);
|
|
}
|
|
|
|
async function getMemoryNotes() {
|
|
const items = await readMeta(MEMORY_NOTES_META_KEY, []);
|
|
return sanitizeMemoryNotesList(items);
|
|
}
|
|
|
|
async function saveMemoryNotes(items) {
|
|
const cleaned = sanitizeMemoryNotesList(items);
|
|
await writeMeta(MEMORY_NOTES_META_KEY, cleaned);
|
|
return cleaned;
|
|
}
|
|
|
|
return {
|
|
listSessions,
|
|
getSession,
|
|
saveSession,
|
|
deleteSession,
|
|
getActiveSessionId,
|
|
setActiveSessionId,
|
|
getMemoryNotes,
|
|
saveMemoryNotes,
|
|
};
|
|
}
|