72 lines
1.9 KiB
TypeScript
72 lines
1.9 KiB
TypeScript
import type { ChatMessage } from "../llm/types";
|
|
|
|
function sessionDir(): string {
|
|
const profile = (Zotero as any).Profile?.dir;
|
|
if (!profile || typeof profile !== "string") {
|
|
throw new Error("Cannot resolve Zotero profile directory");
|
|
}
|
|
return PathUtils.join(profile, "chatpapers", "sessions");
|
|
}
|
|
|
|
function sessionPath(itemKey: string, attachmentKey: string): string {
|
|
const safe = `${itemKey}-${attachmentKey || "none"}`.replace(
|
|
/[^a-zA-Z0-9_-]/g,
|
|
"_",
|
|
);
|
|
return PathUtils.join(sessionDir(), `${safe}.json`);
|
|
}
|
|
|
|
export async function loadSession(
|
|
itemKey: string,
|
|
attachmentKey: string,
|
|
): Promise<ChatMessage[]> {
|
|
try {
|
|
const path = sessionPath(itemKey, attachmentKey);
|
|
const exists = await IOUtils.exists(path);
|
|
if (!exists) return [];
|
|
const raw = await IOUtils.readUTF8(path);
|
|
const data = JSON.parse(raw) as { messages?: ChatMessage[] };
|
|
return (data.messages || []).filter((m) => m.role !== "system");
|
|
} catch (e) {
|
|
ztoolkit.log("loadSession failed", e);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export async function saveSession(
|
|
itemKey: string,
|
|
attachmentKey: string,
|
|
messages: ChatMessage[],
|
|
): Promise<void> {
|
|
try {
|
|
const dir = sessionDir();
|
|
await IOUtils.makeDirectory(dir, { createAncestors: true, ignoreExisting: true });
|
|
const path = sessionPath(itemKey, attachmentKey);
|
|
const payload = JSON.stringify(
|
|
{
|
|
updatedAt: Date.now(),
|
|
messages: messages.filter((m) => m.role !== "system").slice(-50),
|
|
},
|
|
null,
|
|
2,
|
|
);
|
|
await IOUtils.writeUTF8(path, payload);
|
|
} catch (e) {
|
|
ztoolkit.log("saveSession failed", e);
|
|
}
|
|
}
|
|
|
|
export async function clearSession(
|
|
itemKey: string,
|
|
attachmentKey: string,
|
|
): Promise<void> {
|
|
try {
|
|
const path = sessionPath(itemKey, attachmentKey);
|
|
if (await IOUtils.exists(path)) {
|
|
await IOUtils.remove(path);
|
|
}
|
|
} catch (e) {
|
|
ztoolkit.log("clearSession failed", e);
|
|
}
|
|
}
|