Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(ai): persist Agent chat sessions per project
wuzixuan06c4f439d81a37
diff --git a/electron/ai-edition/chat-persistence.test.ts b/electron/ai-edition/chat-persistence.test.tsnew file mode 100644index 000000000..a617d92b9--- /dev/null+++ b/electron/ai-edition/chat-persistence.test.ts@@ -0,0 +1,179 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createEmptyDocument } from "../../src/lib/ai-edition/schema";++vi.mock("./deep-agent/service", () => ({ invokeOpenScreenAgent: vi.fn() }));+vi.mock("./deep-agent/chat-model", () => ({+ createOpenScreenChatModel: vi.fn(),+ messageContentToText: (content: unknown) => String(content),+}));++import {+ compactSessionNow,+ configureChatPersistence,+ createSession,+ deleteProjectChat,+ deleteSession,+ listSessions,+ renameSession,+ rewindToMessage,+ runChat,+ selectSession,+} from "./chat-service";+import { createOpenScreenChatModel } from "./deep-agent/chat-model";+import { invokeOpenScreenAgent } from "./deep-agent/service";+import { DocumentService } from "./document-service";+import type { LlmConfigStore } from "./llm-config-store";++const invokeMock = vi.mocked(invokeOpenScreenAgent);+const modelMock = vi.mocked(createOpenScreenChatModel);+const key = "sk-test-secret-must-not-be-saved";+let root: string;++function config(): LlmConfigStore {+ return {+ getConfig: () => ({ provider: "openai", model: "gpt-4o" }),+ getCredential: () => ({ value: key, entry: { kind: "api-key", apiKey: key } }),+ } as unknown as LlmConfigStore;+}++function restart() {+ configureChatPersistence(root);+}++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), "openscreen-chat-"));+ restart();+ invokeMock.mockReset();+ modelMock.mockReset();+ invokeMock.mockImplementation(async (args) => ({+ text: "reply",+ document: args.document,+ mutated: false,+ }));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe("local Agent chat history", () => {+ it("restores multiple sessions and persists rename and delete per project", () => {+ const first = createSession("proj_a", "First");+ const deleted = createSession("proj_a", "Deleted");+ const other = createSession("proj_b", "Other");+ renameSession("proj_a", first.id, "Renamed");+ expect(deleteSession("proj_a", deleted.id)).toBe(true);++ restart();+ expect(listSessions("proj_a")).toEqual([{ ...first, title: "Renamed" }]);+ expect(selectSession("proj_a", deleted.id)).toBeNull();+ expect(listSessions("proj_b")).toEqual([other]);+ expect(selectSession("proj_b", first.id)).toBeNull();+ });++ it("restores transcript and model context without credentials or stale rewind controls", async () => {+ const session = createSession("proj_chat");+ const document = createEmptyDocument({ title: "Test", projectId: "proj_chat" });+ await runChat("proj_chat", session.id, "first question", config(), document);+ expect(selectSession("proj_chat", session.id)?.messages[0]?.checkpointId).toBeTruthy();+ const file = path.join(root, "proj_chat.chat.json");+ expect(readFileSync(file, "utf8")).not.toContain(key);+ expect(readFileSync(file, "utf8")).not.toContain("checkpointId");++ restart();+ const restored = selectSession("proj_chat", session.id);+ expect(restored?.messages.map((m) => m.content)).toEqual(["first question", "reply"]);+ expect(restored?.messages[0]?.checkpointId).toBeNull();+ expect(rewindToMessage("proj_chat", session.id, restored?.messages[0]?.id ?? "").success).toBe(+ false,+ );+ await runChat("proj_chat", session.id, "follow up", config());+ expect(invokeMock.mock.lastCall?.[0].history.map((m) => m.content)).toEqual([+ "first question",+ "reply",+ "follow up",+ ]);+ });++ it("restores compaction boundary for the model while keeping the full transcript", async () => {+ modelMock.mockImplementation(+ async () =>+ ({+ invoke: async () => ({ content: "Earlier goals and decisions" }),+ }) as unknown as Awaited<ReturnType<typeof createOpenScreenChatModel>>,+ );+ const session = createSession("proj_compact");+ for (let i = 0; i < 4; i++) {+ await runChat("proj_compact", session.id, "question " + i + " ".repeat(100), config());+ }+ const compacted = await compactSessionNow("proj_compact", session.id, config());+ expect(compacted?.summary).toBe("Earlier goals and decisions");+ restart();+ expect(selectSession("proj_compact", session.id)?.messages).toHaveLength(8);+ await runChat("proj_compact", session.id, "continue", config());+ const history = invokeMock.mock.lastCall?.[0].history ?? [];+ expect(history[0]?.content).toBe("Earlier goals and decisions");+ expect(history.some((m) => m.content.startsWith("question 0"))).toBe(false);+ expect(history.at(-1)?.content).toBe("continue");+ });++ it("ignores malformed, old, and cross-project files without blocking document opening", async () => {+ const documents = new DocumentService(root, root);+ const doc = await documents.createProject("Still opens");+ const file = path.join(root, doc.project.id + ".chat.json");+ for (const bad of [+ "{broken",+ JSON.stringify({ version: 0, projectId: doc.project.id, sessions: [] }),+ JSON.stringify({ version: 1, projectId: "proj_other", sessions: [] }),+ ]) {+ writeFileSync(file, bad);+ restart();+ expect(listSessions(doc.project.id)).toEqual([]);+ await expect(documents.getProject(doc.project.id)).resolves.toMatchObject({+ project: { id: doc.project.id },+ });+ }+ });++ it("does not trust a checkpoint id found in a saved transcript", () => {+ const session = createSession("proj_false_rewind");+ const file = path.join(root, "proj_false_rewind.chat.json");+ const saved = JSON.parse(readFileSync(file, "utf8"));+ saved.sessions[0].messages = [+ {+ id: "user_1",+ role: "user",+ content: "old message",+ createdAt: new Date().toISOString(),+ checkpointId: "missing",+ },+ ];+ writeFileSync(file, JSON.stringify(saved));+ restart();+ expect(selectSession("proj_false_rewind", session.id)?.messages[0]?.checkpointId).toBeNull();+ expect(rewindToMessage("proj_false_rewind", session.id, "user_1").success).toBe(false);+ });++ it("skips a damaged session while retaining valid siblings", () => {+ const good = createSession("proj_partial", "Good");+ const file = path.join(root, "proj_partial.chat.json");+ const saved = JSON.parse(readFileSync(file, "utf8"));+ saved.sessions.push({ id: "broken", projectId: "proj_partial", messages: "wrong" });+ writeFileSync(file, JSON.stringify(saved));+ restart();+ expect(listSessions("proj_partial")).toEqual([good]);+ });++ it("removes chat history when the owning project is deleted", () => {+ createSession("proj_removed", "Disposable");+ const file = path.join(root, "proj_removed.chat.json");+ expect(existsSync(file)).toBe(true);+ deleteProjectChat("proj_removed");+ expect(existsSync(file)).toBe(false);+ restart();+ expect(listSessions("proj_removed")).toEqual([]);+ });+});diff --git a/electron/ai-edition/chat-persistence.ts b/electron/ai-edition/chat-persistence.tsnew file mode 100644index 000000000..82fa16a18--- /dev/null+++ b/electron/ai-edition/chat-persistence.ts@@ -0,0 +1,107 @@+// Local Agent chat sidecars live beside the project's .openscreen document.+// Keep this format separate from the document schema: a bad or newer chat file+// must never stop the project itself from opening.++import { randomUUID } from "node:crypto";+import {+ closeSync,+ existsSync,+ fsyncSync,+ mkdirSync,+ openSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import path from "node:path";+import { z } from "zod";++const toolCallSchema = z.object({ name: z.string(), summary: z.string() });+const messageSchema = z.object({+ id: z.string().min(1),+ role: z.enum(["user", "assistant"]),+ content: z.string(),+ createdAt: z.string().min(1),+ toolCalls: z.array(toolCallSchema).optional(),+});+const sessionSchema = z.object({+ id: z.string().min(1),+ projectId: z.string().min(1),+ title: z.string().min(1),+ createdAt: z.string().min(1),+ messages: z.array(messageSchema),+ compaction: z+ .object({+ summary: messageSchema,+ coveredCount: z.number().int().positive(),+ })+ .optional(),+});+const fileSchema = z.object({+ version: z.literal(1),+ projectId: z.string(),+ sessions: z.array(z.unknown()),+});++export type StoredChatSession = z.infer<typeof sessionSchema>;++export class ChatPersistence {+ constructor(private readonly projectsRoot: string) {}++ fileFor(projectId: string): string {+ if (!/^[A-Za-z0-9_-]+$/.test(projectId)) throw new Error("Invalid project id");+ return path.join(this.projectsRoot, `${projectId}.chat.json`);+ }++ read(projectId: string): StoredChatSession[] {+ const file = this.fileFor(projectId);+ if (!existsSync(file)) return [];+ try {+ const parsed = fileSchema.parse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.projectId !== projectId) return [];+ const seen = new Set<string>();+ const sessions: StoredChatSession[] = [];+ for (const rawSession of parsed.sessions) {+ const result = sessionSchema.safeParse(rawSession);+ if (!result.success) continue;+ const session = result.data;+ if (session.projectId !== projectId || seen.has(session.id)) continue;+ if (session.compaction && session.compaction.coveredCount > session.messages.length)+ continue;+ seen.add(session.id);+ sessions.push(session);+ }+ return sessions;+ } catch (error) {+ console.warn(`[ai-edition] ignoring unreadable chat history for ${projectId}:`, error);+ return [];+ }+ }++ write(projectId: string, sessions: StoredChatSession[]): void {+ const destination = this.fileFor(projectId);+ mkdirSync(this.projectsRoot, { recursive: true });+ const temporary = `${destination}.tmp-${process.pid}-${randomUUID()}`;+ // Explicitly choose fields; provider configuration and API keys never enter+ // the chat format. Checkpoints remain process-local and are never serialized.+ const sanitized = sessions.map((session) => sessionSchema.parse(session));+ const json = JSON.stringify({ version: 1, projectId, sessions: sanitized });+ let fd: number | undefined;+ try {+ fd = openSync(temporary, "w");+ writeFileSync(fd, json, "utf8");+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(temporary, destination);+ } finally {+ if (fd !== undefined) closeSync(fd);+ rmSync(temporary, { force: true });+ }+ }++ delete(projectId: string): void {+ rmSync(this.fileFor(projectId), { force: true });+ }+}diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.tsindex 067b957ed..41ffe9bef 100644--- a/electron/ai-edition/chat-service.ts+++ b/electron/ai-edition/chat-service.ts@@ -1,4 +1,4 @@-// In-memory chat service. ponytail: chat sessions live in a nested Map; the+// Agent chat service. Sessions are cached by project and persisted locally; the// agentic loop itself lives in `deep-agent/service.ts` and is a port of// axcut's AxcutDeepAgentService (LangGraph stateful thread via// `createDeepAgent`). The IPC bridge streams `text` deltas + `toolStart` /@@ -30,12 +30,33 @@ import {compactionSplitIndex,DEFAULT_BUDGET_TOKENS,} from "./chat-compaction";+import { ChatPersistence } from "./chat-persistence";import type { CursorTelemetryReader } from "./deep-agent/service";import type { DocumentService } from "./document-service";import type { LlmConfigStore } from "./llm-config-store";import { PROVIDER_DEFINITIONS } from "./provider-registry";const sessionsByProject = new Map<string, Map<string, ChatSession>>();+let persistence: ChatPersistence | null = null;++/** Called once in the main process. Reconfiguration simulates a restart in tests. */+export function configureChatPersistence(projectsRoot: string): void {+ persistence = new ChatPersistence(projectsRoot);+ sessionsByProject.clear();+ messageCheckpointsBySession.clear();+}++function persistProject(projectId: string): void {+ if (persistence) persistence.write(projectId, [...getProjectSessions(projectId).values()]);+}++export function deleteProjectChat(projectId: string): void {+ persistence?.delete(projectId);+ sessionsByProject.delete(projectId);+ for (const key of messageCheckpointsBySession.keys()) {+ if (key.startsWith(projectId + "::")) messageCheckpointsBySession.delete(key);+ }+}// ponytail: per-message checkpoints, stored as an ordered list per session// (insertion order == the session's message order). Each entry captures the@@ -116,7 +137,7 @@ function dropCheckpointsFrom(// ponytail: what compaction leaves behind. `coveredCount` counts the leading// transcript messages the summary stands in for — the transcript itself is// never rewritten, so the user keeps every message they wrote while the model-// gets the shortened list. Sessions are in-memory only; deleting the messages+// gets the shortened list. Deleting the messages// the renderer shows would be unrecoverable, and nothing in the UI would say// it happened.interface SessionCompaction {@@ -181,7 +202,7 @@ function toSummary(s: ChatSession): ChatSessionSummary {function getProjectSessions(projectId: string): Map<string, ChatSession> {let m = sessionsByProject.get(projectId);if (!m) {- m = new Map();+ m = new Map(persistence?.read(projectId).map((session) => [session.id, session]) ?? []);sessionsByProject.set(projectId, m);}return m;@@ -192,8 +213,7 @@ function defaultSessionTitle(index: number): string {}export function listSessions(projectId: string): ChatSessionSummary[] {- const m = sessionsByProject.get(projectId);- if (!m) return [];+ const m = getProjectSessions(projectId);return Array.from(m.values()).map(toSummary).sort((a, b) => a.createdAt.localeCompare(b.createdAt));@@ -211,14 +231,14 @@ export function createSession(projectId: string, title?: string): ChatSessionSummessages: [],};m.set(id, session);+ persistProject(projectId);return toSummary(session);}export function selectSession(projectId: string, sessionId: string): ChatSession | null {- const m = sessionsByProject.get(projectId);- const s = m?.get(sessionId);+ const s = getProjectSessions(projectId).get(sessionId);if (!s) return null;- // ponytail: shallow-copy messages so the caller can't mutate the live array.+ // Return copies and expose a rewind id only while its checkpoint still exists.// The compaction boundary stays behind: it is main-process bookkeeping, and// every caller of this wants the transcript as the user sees it.return {@@ -226,7 +246,13 @@ export function selectSession(projectId: string, sessionId: string): ChatSessionprojectId: s.projectId,title: s.title,createdAt: s.createdAt,- messages: [...s.messages],+ messages: s.messages.map((message) => ({+ ...message,+ checkpointId:+ message.checkpointId && findCheckpointForMessage(projectId, sessionId, message.checkpointId)+ ? message.checkpointId+ : null,+ })),};}@@ -235,18 +261,22 @@ export function renameSession(sessionId: string,title: string,): ChatSessionSummary | null {- const m = sessionsByProject.get(projectId);- const s = m?.get(sessionId);+ const s = getProjectSessions(projectId).get(sessionId);if (!s) return null;const trimmed = title.trim();- if (trimmed) s.title = trimmed;+ if (trimmed && trimmed !== s.title) {+ s.title = trimmed;+ persistProject(projectId);+ }return toSummary(s);}export function deleteSession(projectId: string, sessionId: string): boolean {- const m = sessionsByProject.get(projectId);- if (!m?.has(sessionId)) return false;+ const m = getProjectSessions(projectId);+ if (!m.has(sessionId)) return false;m.delete(sessionId);+ messageCheckpointsBySession.delete(sessionKey(projectId, sessionId));+ persistProject(projectId);return true;}@@ -358,11 +388,12 @@ export async function runChat(? structuredClone(workingDocument): null;if (documentForCheckpoint) {- recordMessageCheckpoint(projectId, sessionId, userMessage.id, documentForCheckpoint);+ recordMessageCheckpoint(projectId, session.id, userMessage.id, documentForCheckpoint);}userMessage.checkpointId = documentForCheckpoint ? userMessage.id : null;session.messages.push(userMessage);+ persistProject(projectId);const editsAllowed = config.allowAgentEdits !== false;@@ -436,6 +467,7 @@ export async function runChat(toolCalls: appliedToolCalls.length ? appliedToolCalls : undefined,};session.messages.push(assistantMessage);+ persistProject(projectId);return {success: true,@@ -471,7 +503,7 @@ export function rewindToMessage(success: false;error: string;} {- const session = sessionsByProject.get(projectId)?.get(sessionId);+ const session = getProjectSessions(projectId).get(sessionId);if (!session) return { success: false, error: "Chat session not found." };const messageIndex = session.messages.findIndex((m) => m.id === messageId);if (messageIndex === -1) {@@ -504,12 +536,21 @@ export function rewindToMessage(session.compaction = undefined;}dropCheckpointsFrom(projectId, sessionId, target.checkpointId);+ for (const message of session.messages) {+ if (+ message.checkpointId &&+ !findCheckpointForMessage(projectId, sessionId, message.checkpointId)+ ) {+ message.checkpointId = null;+ }+ }+ persistProject(projectId);return {success: true,prompt: target.content,document: cp.document,- messages: [...survived],+ messages: selectSession(projectId, sessionId)?.messages ?? [],};}@@ -533,11 +574,10 @@ export async function runTimelineOperation(conversationMessage: string,documents: DocumentService,): Promise<{ success: true; result: TimelineOperationResult } | { success: false; error: string }> {- let session = sessionsByProject.get(projectId)?.get(sessionId);- const created = !session;- if (created) {+ let session = getProjectSessions(projectId).get(sessionId);+ if (!session) {const summary = createSession(projectId);- session = selectSession(projectId, summary.id) ?? undefined;+ session = getProjectSessions(projectId).get(summary.id);if (!session) return { success: false, error: "Could not create session." };}@@ -571,6 +611,7 @@ export async function runTimelineOperation(createdAt: new Date().toISOString(),};session.messages.push(assistantMessage);+ persistProject(projectId);}return {@@ -590,7 +631,7 @@ export async function compactSessionNow(sessionId: string,llmConfig: LlmConfigStore,): Promise<{ summaryMessageId: string | null; summary: string; session: ChatSession } | null> {- const session = sessionsByProject.get(projectId)?.get(sessionId);+ const session = getProjectSessions(projectId).get(sessionId);if (!session) return null;const config = llmConfig.getConfig();if (!config) return null;@@ -615,6 +656,7 @@ export async function compactSessionNow(reasoningEffort: config.reasoningEffort,});if (!ok) return null;+ persistProject(projectId);return {summaryMessageId: ok.summaryMessageId,summary: ok.summary,@@ -631,7 +673,7 @@ export function getSessionContextUsage(sessionId: string,budgetTokens: number = DEFAULT_BUDGET_TOKENS,): { usedTokens: number; budgetTokens: number; ratio: number; fillPercent: number } | null {- const session = sessionsByProject.get(projectId)?.get(sessionId);+ const session = getProjectSessions(projectId).get(sessionId);if (!session) return null;// Measured on what the model is given, not on the transcript -- after a// compaction those differ, and the number that matters is the one that@@ -672,7 +714,7 @@ export function getSessionBudget(sessionId: string,budgetTokens: number = DEFAULT_BUDGET_TOKENS,): SessionBudgetSnapshot | null {- const s = sessionsByProject.get(projectId)?.get(sessionId);+ const s = getProjectSessions(projectId).get(sessionId);if (!s) return null;// Same window the model is actually sent — see `getSessionContextUsage`.const snap = budgetSnapshot(modelHistory(s), budgetTokens);@@ -693,7 +735,7 @@ export async function compactSession(sessionId: string,llmConfig: LlmConfigStore,): Promise<{ summaryMessageId: string | null; summary: string } | null> {- const session = sessionsByProject.get(projectId)?.get(sessionId);+ const session = getProjectSessions(projectId).get(sessionId);if (!session) return null;const config = llmConfig.getConfig();if (!config) return null;@@ -713,6 +755,7 @@ export async function compactSession(baseUrl: config.baseUrl,reasoningEffort: config.reasoningEffort,});+ if (ok) persistProject(projectId);return ok;}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 843d76301..7b9177c2c 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -52,6 +52,7 @@ import type {import { PRODUCT_NAME } from "../about";import {compactSessionNow,+ configureChatPersistence,createSession,deleteSession,getSessionContextUsage,@@ -4863,8 +4864,10 @@ export function registerIpcHandlers(// race destroyed two real project files), so a second instance means a second// queue racing for the same path: temp+rename still keeps the file valid, but// a save can land under a concurrent one and be silently lost.+ const chatProjectsRoot = path.join(app.getPath("userData"), "projects");+ configureChatPersistence(chatProjectsRoot);const aiEditionDocuments = new DocumentService(- path.join(app.getPath("userData"), "projects"),+ chatProjectsRoot,RECORDINGS_DIR,approveDocumentMedia,() => stylePresets.newProjectAppearance(),diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.tsindex 954cc834f..065aaa4b5 100644--- a/electron/ipc/nativeBridge.ts+++ b/electron/ipc/nativeBridge.ts@@ -10,7 +10,7 @@ import {type ProjectFileResult,type ProjectPathResult,} from "../../src/native/contracts";-import type { ChatEventSink } from "../ai-edition/chat-service";+import { type ChatEventSink, deleteProjectChat } from "../ai-edition/chat-service";import type { DocumentService } from "../ai-edition/document-service";import { StylePresetError, type StylePresetService } from "../ai-edition/style-preset-service";import { isValidMcpPort } from "../mcp/mcp-settings-store";@@ -234,6 +234,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {const compositorViewService = new CompositorViewService();const aiEditionService = new AiEditionService({documents: context.getAiEditionDocuments(),+ deleteChatHistory: deleteProjectChat,// Passed uncalled on purpose — invoking it here would build the store (and// hit the macOS Keychain) while wiring the bridge at startup.llmConfig: context.getAiEditionLlmConfig,diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.tsindex 579ba59a3..f06d79c67 100644--- a/electron/native-bridge/services/aiEditionService.ts+++ b/electron/native-bridge/services/aiEditionService.ts@@ -36,6 +36,7 @@ import type { McpController } from "../../mcp/mcp-controller";export interface AiEditionServiceOptions {documents: DocumentService;+ deleteChatHistory?: (projectId: string) => void;/*** A factory, not an instance: building `LlmConfigStore` does two sync* readFileSync plus a `safeStorage` decrypt, and on macOS that decrypt is@@ -146,6 +147,7 @@ export class AiEditionService {async deleteProject(projectId: string): Promise<AiEditionDocumentResult> {try {await this.options.documents.deleteProject(projectId);+ this.options.deleteChatHistory?.(projectId);return { success: true };} catch (error) {return {