Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
355 changes: 355 additions & 0 deletions docs/architecture/ai-edition-collision-analysis.md

Large diffs are not rendered by default.

420 changes: 420 additions & 0 deletions docs/architecture/ai-edition-merge-plan.md

Large diffs are not rendered by default.

458 changes: 458 additions & 0 deletions docs/architecture/axcut-inventory.md

Large diffs are not rendered by default.

707 changes: 707 additions & 0 deletions docs/architecture/openscreen-inventory.md

Large diffs are not rendered by default.

72 changes: 72 additions & 0 deletions electron/ai-edition/chat-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// In-memory chat service. ponytail: no SQLite, no LangGraph, no checkpoints
// for Phase 6 scaffolding. Stores messages per project in a Map. The actual
// LLM call needs @langchain/* deps + API keys — the runChat function is a
// stub that returns "AI features require LLM dependencies" until the deps
// are installed and a provider is configured.
//
// Phase 8 upgrades this to SQLite-backed sessions with checkpoint restore.

import { v4 as uuidv4 } from "uuid";
import type { AiEditionChatMessage, AiEditionChatResult } from "../../src/native/contracts";
import type { LlmConfigStore } from "./llm-config-store";
import { PROVIDER_DEFINITIONS } from "./provider-registry";

const messagesByProject = new Map<string, AiEditionChatMessage[]>();

export async function runChat(
projectId: string,
message: string,
llmConfig: LlmConfigStore,
): Promise<AiEditionChatResult> {
const config = llmConfig.getConfig();
if (!config) {
return {
success: false,
error: "No LLM provider configured. Open Settings → AI to configure.",
};
}

const def = PROVIDER_DEFINITIONS.find((d) => d.id === config.provider);
if (!def) {
return { success: false, error: `Unknown provider: ${config.provider}` };
}

const apiKey = llmConfig.getApiKey(def.id, def.envKeys);
if (!apiKey && def.authKind === "api-key") {
return {
success: false,
error: `No API key for ${def.label}. Add one in Settings → AI.`,
};
}

const messages = messagesByProject.get(projectId) ?? [];
const userMessage: AiEditionChatMessage = {
id: uuidv4(),
role: "user",
content: message,
createdAt: new Date().toISOString(),
};
messages.push(userMessage);

// ponytail: stub response. The actual LLM call needs @langchain/openai,
// @langchain/anthropic, etc. installed + imported. This scaffolding lets
// the UI work end-to-end (message appears, history persists) without the
// heavy deps. Replace with create-chat-model.ts port when deps land.
const assistantMessage: AiEditionChatMessage = {
id: uuidv4(),
role: "assistant",
content: `AI features are scaffolding-ready but need @langchain/* dependencies to make real LLM calls. Configure your provider in Settings, then install the deps to enable chat. Your message was: "${message}"`,
createdAt: new Date().toISOString(),
};
messages.push(assistantMessage);
messagesByProject.set(projectId, messages);

return {
success: true,
assistantMessage,
};
}

export async function getChatHistory(projectId: string): Promise<AiEditionChatMessage[]> {
return messagesByProject.get(projectId) ?? [];
}
193 changes: 193 additions & 0 deletions electron/ai-edition/document-service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { DocumentNotFoundError, DocumentService, ProjectFileError } from "./document-service";

async function makeTempDir(): Promise<string> {
const base = await fs.mkdtemp(path.join(os.tmpdir(), "openscreen-ai-edition-"));
return base;
}

describe("DocumentService", () => {
let tempDir: string;
let service: DocumentService;

beforeEach(async () => {
tempDir = await makeTempDir();
service = new DocumentService(tempDir);
});

afterEach(async () => {
await fs.rm(tempDir, { recursive: true, force: true });
});

describe("createProject", () => {
it("creates a v3 doc with the given title and writes it to disk", async () => {
const doc = await service.createProject("Demo Project");
expect(doc.schemaVersion).toBe(3);
expect(doc.project.title).toBe("Demo Project");
expect(doc.project.id).toMatch(/^proj_/);
expect(doc.assets).toEqual([]);

const filePath = path.join(tempDir, `${doc.project.id}.axcut`);
const raw = await fs.readFile(filePath, "utf8");
expect(JSON.parse(raw)).toMatchObject({
schemaVersion: 3,
project: { title: "Demo Project" },
});
});

it("falls back to 'Untitled Project' for empty titles", async () => {
const doc = await service.createProject(" ");
expect(doc.project.title).toBe("Untitled Project");
});
});

describe("getProject", () => {
it("returns the doc by id", async () => {
const created = await service.createProject("Round trip");
const fetched = await service.getProject(created.project.id);
expect(fetched.project.id).toBe(created.project.id);
});

it("throws DocumentNotFoundError for missing projects", async () => {
await expect(service.getProject("proj_does-not-exist")).rejects.toBeInstanceOf(
DocumentNotFoundError,
);
});

it("rejects project ids with path-traversal characters", async () => {
await expect(service.getProject("../etc/passwd")).rejects.toBeInstanceOf(ProjectFileError);
await expect(service.getProject("proj/with/slash")).rejects.toBeInstanceOf(ProjectFileError);
});
});

describe("listProjects", () => {
it("returns summaries sorted by updatedAt desc", async () => {
const a = await service.createProject("A");
await new Promise((r) => setTimeout(r, 5));
const b = await service.createProject("B");
const summaries = await service.listProjects();
expect(summaries.map((s) => s.id)).toEqual([b.project.id, a.project.id]);
expect(summaries[0]?.title).toBe("B");
});

it("skips files that fail to parse rather than throwing", async () => {
const a = await service.createProject("OK");
await fs.writeFile(path.join(tempDir, "garbage.axcut"), "not json", "utf8");
const summaries = await service.listProjects();
expect(summaries.map((s) => s.id)).toEqual([a.project.id]);
});
});

describe("addAsset", () => {
it("appends a video asset and sets primaryAssetId on the first add", async () => {
const doc = await service.createProject("P");
const updated = await service.addAsset(doc.project.id, {
path: "/tmp/screen.mp4",
label: "Screen",
});
expect(updated.assets).toHaveLength(1);
const asset = updated.assets[0];
expect(asset?.kind).toBe("video");
expect(asset?.originalPath).toBe("/tmp/screen.mp4");
expect(asset?.label).toBe("Screen");
expect(updated.project.primaryAssetId).toBe(asset?.id);
});

it("resolves relative paths against the cwd", async () => {
const doc = await service.createProject("P");
const updated = await service.addAsset(doc.project.id, { path: "recording.webm" });
expect(path.isAbsolute(updated.assets[0]?.originalPath ?? "")).toBe(true);
});

it("rejects unsupported video extensions", async () => {
const doc = await service.createProject("P");
await expect(
service.addAsset(doc.project.id, { path: "/tmp/audio.mp3" }),
).rejects.toBeInstanceOf(ProjectFileError);
});

it("preserves primaryAssetId when adding a second asset", async () => {
const doc = await service.createProject("P");
const first = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });
const after = await service.addAsset(doc.project.id, { path: "/tmp/b.mp4" });
expect(after.project.primaryAssetId).toBe(first.project.primaryAssetId);
expect(after.assets).toHaveLength(2);
});
});

describe("removeAsset", () => {
it("removes the asset and cascades clips + skipRanges", async () => {
const doc = await service.createProject("P");
const withAsset = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });
const assetId = withAsset.assets[0]?.id;
expect(assetId).toBeTruthy();

// Manually add a clip + skipRange so we can verify cascade
const docWithTimeline = await service.saveProject({
...withAsset,
timeline: {
...withAsset.timeline,
clips: [
{
id: "clip_1",
assetId,
sourceStartSec: 0,
timelineStartSec: 0,
timelineEndSec: 1,
wordRefs: [],
origin: "system",
},
],
skipRanges: [
{
id: "skip_1",
assetId,
startSec: 0,
endSec: 1,
origin: "user",
},
],
},
});

const after = await service.removeAsset(docWithTimeline.project.id, assetId ?? "");
expect(after.assets).toHaveLength(0);
expect(after.timeline.clips).toHaveLength(0);
expect(after.timeline.skipRanges).toHaveLength(0);
});
Comment on lines +122 to +160

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Coverage gap: removing the primary/last asset doesn't assert primaryAssetId is cleared.

This cascade test removes the only asset but never checks after.project.primaryAssetId. As written it would pass even though the source leaves a stale primaryAssetId pointing at the deleted asset (see comment on document-service.ts removeAsset). Add an assertion to lock the intended behavior.

expect(after.project.primaryAssetId).toBeUndefined();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/ai-edition/document-service.test.ts` around lines 122 - 160, The
removeAsset cascade test only verifies assets, clips, and skipRanges, but it
misses the primary asset cleanup path. In the document-service.test.ts case
around service.removeAsset, add an assertion on after.project.primaryAssetId to
ensure it is cleared when the last/primary asset is deleted, using the existing
createProject/addAsset/saveProject/removeAsset flow to locate the test.


it("reassigns primaryAssetId when removing the primary", async () => {
const doc = await service.createProject("P");
const a = await service.addAsset(doc.project.id, { path: "/tmp/a.mp4" });
const b = await service.addAsset(doc.project.id, { path: "/tmp/b.mp4" });
const primaryId = a.project.primaryAssetId;
expect(primaryId).toBeTruthy();
const after = await service.removeAsset(doc.project.id, primaryId ?? "");
expect(after.project.primaryAssetId).toBe(b.assets[1]?.id);
});

it("throws when removing a missing asset", async () => {
const doc = await service.createProject("P");
await expect(service.removeAsset(doc.project.id, "asset_x")).rejects.toBeInstanceOf(
ProjectFileError,
);
});
});

describe("deleteProject", () => {
it("removes the .axcut file", async () => {
const doc = await service.createProject("Bye");
await service.deleteProject(doc.project.id);
await expect(service.getProject(doc.project.id)).rejects.toBeInstanceOf(
DocumentNotFoundError,
);
});

it("is a no-op when the file doesn't exist", async () => {
await expect(service.deleteProject("proj_never-existed")).resolves.toBeUndefined();
});
});
});
Loading
Loading