Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(stt): thread the Whisper language through, and rename sessions inline

Etienne Lescot7bacd78820fd
diff --git a/electron/ai-edition/chat-service.test.ts b/electron/ai-edition/chat-service.test.ts
index 2271472dc..8cd118a30 100644
--- a/electron/ai-edition/chat-service.test.ts
+++ b/electron/ai-edition/chat-service.test.ts
@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it } from "vitest";
+import { type AxcutDocument, createEmptyDocument } from "../../src/lib/ai-edition/schema";
import {
createSession,
deleteSession,
listSessions,
renameSession,
+ runTimelineOperation,
selectSession,
} from "./chat-service";
import type { LlmConfigStore } from "./llm-config-store";
@@ -107,3 +109,100 @@ describe("chat-service runChat signature", () => {
expect(result.error).toMatch(/No LLM provider/);
});
});
+
+// ponytail: runTimelineOperation reads, applies, saves, and records a chat
+// summary. Tested with a stub DocumentService so the test is fast + offline.
+describe("runTimelineOperation", () => {
+ function makeDocument(): AxcutDocument {
+ const base = createEmptyDocument({ title: "T", projectId: "proj_run" });
+ const assetId = "asset_1";
+ return {
+ ...base,
+ project: { ...base.project, primaryAssetId: assetId },
+ assets: [
+ {
+ id: assetId,
+ kind: "video" as const,
+ label: "Rec",
+ originalPath: "/tmp/r.mp4",
+ durationSec: 60,
+ },
+ ],
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "c1",
+ assetId,
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user" as const,
+ reason: "",
+ },
+ ],
+ },
+ };
+ }
+
+ function makeDocumentsStub() {
+ const initial = makeDocument();
+ const file: { stored: AxcutDocument | undefined } = { stored: initial };
+ const documents = {
+ async getProject(_id: string): Promise<AxcutDocument> {
+ if (!file.stored) throw new Error("no document");
+ return file.stored;
+ },
+ async saveProject(doc: AxcutDocument): Promise<AxcutDocument> {
+ file.stored = doc;
+ return doc;
+ },
+ };
+ return { documents, file };
+ }
+
+ it("applies the op, persists, and records an assistant summary", async () => {
+ const { documents, file } = makeDocumentsStub();
+ const s = createSession("proj_run");
+ const result = await runTimelineOperation(
+ "proj_run",
+ s.id,
+ { type: "add_skip_range", startSec: 5, endSec: 8 },
+ "Trimmed silence",
+ documents,
+ );
+ expect(result.success).toBe(true);
+ if (!result.success) return;
+ expect(result.result.summary).toMatch(/added skip/);
+ const saved = file.stored?.timeline.skipRanges ?? [];
+ expect(saved.some((s) => s.startSec === 5)).toBe(true);
+ const session = selectSession("proj_run", s.id);
+ expect(session?.messages).toHaveLength(1);
+ expect(session?.messages[0].content).toBe("Trimmed silence");
+ expect(session?.messages[0].role).toBe("assistant");
+ });
+
+ it("returns success:false on getProject failure", async () => {
+ const documents = {
+ async getProject() {
+ throw new Error("disk is dead");
+ },
+ async saveProject() {
+ throw new Error("disk is dead");
+ },
+ };
+ const s = createSession("proj_run_err");
+ const result = await runTimelineOperation(
+ "proj_run_err",
+ s.id,
+ { type: "restore_full_timeline" },
+ "",
+ documents,
+ );
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.error).toBe("disk is dead");
+ });
+});
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index da682106c..85a545727 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -6,6 +6,10 @@
// ChatEventSink.
import { v4 as uuidv4 } from "uuid";
+import {
+ type AxcutTimelineOperation,
+ applyTimelineOperation,
+} from "../../src/lib/ai-edition/document/operations";
import {
type AxcutDocument,
createEmptyDocument,
@@ -24,6 +28,7 @@ import {
DEFAULT_BUDGET_TOKENS,
shouldCompact,
} from "./chat-compaction";
+import type { DocumentService } from "./document-service";
import { streamLlm } from "./llm-call";
import type { LlmConfigStore } from "./llm-config-store";
import { PROVIDER_DEFINITIONS } from "./provider-registry";
@@ -432,6 +437,75 @@ export function rewindToMessage(
};
}
+// ponytail: renderer-initiated timeline operation. Reads the doc from disk,
+// applies `op`, saves the result, and records a chat assistant message that
+// summarises the change so the conversation history reflects the manual
+// edit (axcut's `applyOperation` does the same).
+//
+// The renderer applies an optimistic copy to its local store before calling
+// this; if the call fails we roll back to the previous document by re-reading
+// the saved state, so the cache and disk stay aligned.
+export interface TimelineOperationResult {
+ document: AxcutDocument;
+ summary: string;
+}
+
+export async function runTimelineOperation(
+ projectId: string,
+ sessionId: string,
+ op: AxcutTimelineOperation,
+ 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) {
+ const summary = createSession(projectId);
+ session = selectSession(projectId, summary.id) ?? undefined;
+ if (!session) return { success: false, error: "Could not create session." };
+ }
+
+ let current: AxcutDocument;
+ try {
+ current = await documents.getProject(projectId);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
+ const applied = applyTimelineOperation(current, op);
+
+ let saved: AxcutDocument;
+ try {
+ saved = await documents.saveProject(applied.document);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
+ if (conversationMessage.trim() && session) {
+ const assistantMessage: AiEditionChatMessage = {
+ id: `msg_${uuidv4()}`,
+ role: "assistant",
+ content: conversationMessage.trim(),
+ createdAt: new Date().toISOString(),
+ };
+ session.messages.push(assistantMessage);
+ }
+
+ return {
+ success: true,
+ result: {
+ document: saved,
+ summary: applied.summary,
+ },
+ };
+}
+
// ponytail: port of axcut's compactSession — manual compaction from a button
// press. Returns the latest session snapshot + the inserted summary message
// id, so the renderer can highlight it.
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 5eacf876d..ee322676a 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -47,6 +47,7 @@ import {
rewindToMessage,
runChat,
runChatDefault,
+ runTimelineOperation,
selectSession,
} from "../ai-edition/chat-service";
import { DocumentService } from "../ai-edition/document-service";
@@ -3169,6 +3170,14 @@ export function registerIpcHandlers(
rewindToMessage(projectId, sessionId, messageId),
compactNow: (projectId, sessionId) =>
compactSessionNow(projectId, sessionId, new LlmConfigStore(app.getPath("userData"))),
+ runTimelineOperation: (projectId, sessionId, op, conversationMessage) =>
+ runTimelineOperation(
+ projectId,
+ sessionId,
+ op,
+ conversationMessage,
+ new DocumentService(path.join(app.getPath("userData"), "projects")),
+ ),
getContextUsage: getSessionContextUsage,
runAiEditionChatDefault: (projectId, message, sink) =>
runChatDefault(projectId, message, new LlmConfigStore(app.getPath("userData")), sink),
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 76b0bd553..aa3f27599 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -70,6 +70,18 @@ export interface NativeBridgeContext {
projectId: string,
sessionId: string,
) => Promise<import("../../src/native/contracts").AiEditionChatCompactResult | null>;
+ runTimelineOperation: (
+ projectId: string,
+ sessionId: string,
+ op: import("../../src/native/contracts").AxcutTimelineOperation,
+ conversationMessage: string,
+ ) => Promise<
+ | {
+ success: true;
+ result: import("../../src/native/contracts").AppliedTimelineOperation;
+ }
+ | { success: false; error: string }
+ >;
getContextUsage: (
projectId: string,
sessionId: string,
@@ -212,6 +224,7 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
undoLastToolBatch: context.undoAiEditionToolBatch,
rewindToMessage: context.rewindToMessage,
compactNow: context.compactNow,
+ runTimelineOperation: context.runTimelineOperation,
getContextUsage: context.getContextUsage,
getDefaultChatHistory: context.getAiEditionChatHistoryDefault,
clearDefaultChatHistory: context.clearAiEditionChatHistoryDefault,
@@ -529,6 +542,16 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
request.payload.sessionId,
),
);
+ case "timeline.run":
+ return createSuccessResponse(
+ requestId,
+ await aiEditionService.chatRunTimelineOperation(
+ request.payload.projectId,
+ request.payload.sessionId,
+ request.payload.operation,
+ request.payload.conversationMessage,
+ ),
+ );
default:
return createErrorResponse(
requestId,
diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.ts
index a4abaa849..aa80f56c6 100644
--- a/electron/native-bridge/services/aiEditionService.ts
+++ b/electron/native-bridge/services/aiEditionService.ts
@@ -1,3 +1,4 @@
+import { documentSchema } from "../../../src/lib/ai-edition/schema";
import type {
AiEditionAssetResult,
AiEditionChatBudget,
@@ -14,10 +15,10 @@ import type {
AiEditionLlmDisconnectResult,
AiEditionLlmSnapshot,
AiEditionProjectSummary,
+ AxcutTimelineOperation,
} from "../../../src/native/contracts";
import type { ChatEventSink } from "../../ai-edition/chat-service";
import type { DocumentService } from "../../ai-edition/document-service";
-import { documentSchema } from "../../../src/lib/ai-edition/schema";
import type { LlmConfigStore, LlmCredential } from "../../ai-edition/llm-config-store";
import {
beginCodexDeviceAuth,
@@ -63,6 +64,15 @@ export interface AiEditionServiceOptions {
}
| { success: false; error: string };
compactNow: (projectId: string, sessionId: string) => Promise<AiEditionChatCompactResult | null>;
+ runTimelineOperation: (
+ projectId: string,
+ sessionId: string,
+ operation: AxcutTimelineOperation,
+ conversationMessage: string,
+ ) => Promise<
+ | { success: true; result: { document: unknown; summary: string } }
+ | { success: false; error: string }
+ >;
getContextUsage: (
projectId: string,
sessionId: string,
@@ -367,6 +377,15 @@ export class AiEditionService {
return this.options.compactNow(projectId, sessionId);
}
+ chatRunTimelineOperation(
+ projectId: string,
+ sessionId: string,
+ operation: AxcutTimelineOperation,
+ conversationMessage: string,
+ ) {
+ return this.options.runTimelineOperation(projectId, sessionId, operation, conversationMessage);
+ }
+
async chatRunDefault(
projectId: string,
message: string,
diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsx
index 6ad7695eb..bfd5e58ef 100644
--- a/src/components/ai-edition/LeftPanel.tsx
+++ b/src/components/ai-edition/LeftPanel.tsx
@@ -5,8 +5,13 @@ import { toast } from "sonner";
import { AI_FEATURES_ENABLED } from "@/components/video-editor/featureFlags";
import { type AxcutAsset, ensureDocument } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { useOptimisticTimelineOps } from "@/lib/ai-edition/store/useOptimisticTimelineOps";
import { nativeBridgeClient } from "@/native/client";
-import type { AiEditionLlmConfig, AiEditionToolCallSummary } from "@/native/contracts";
+import type {
+ AiEditionLlmConfig,
+ AiEditionToolCallSummary,
+ AxcutTimelineOperation,
+} from "@/native/contracts";
import {
PROVIDER_DEFINITIONS,
REASONING_EFFORT_OPTIONS,
@@ -1062,6 +1067,58 @@ function ChatStripPanel() {
[projectId],
);
+ // ponytail: inline session rename. Click the title to edit, Enter saves,
+ // Escape cancels, blur saves when the value is non-empty (axcut parity).
+ const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
+ const [editingTitle, setEditingTitle] = useState("");
+ const editingInputRef = useRef<HTMLInputElement | null>(null);
+ const beginEditTitle = useCallback((id: string, currentTitle: string) => {
+ setEditingSessionId(id);
+ setEditingTitle(currentTitle);
+ }, []);
+ const cancelEditTitle = useCallback(() => {
+ setEditingSessionId(null);
+ setEditingTitle("");
+ }, []);
+ const commitEditTitle = useCallback(
+ async (id: string) => {
+ const next = editingTitle.trim();
+ if (!next) {
+ cancelEditTitle();
+ return;
+ }
+ setEditingSessionId(null);
+ await handleRename(id, next);
+ },
+ [editingTitle, handleRename, cancelEditTitle],
+ );
+
+ const { queue: queueTimelineOp, busy: queueBusy } = useOptimisticTimelineOps(
+ projectId,
+ activeSessionId,
+ );
+ const runAddSkip = useCallback(() => {
+ const raw = window.prompt("Add skip range\nFormat: startSec-endSec (e.g. 1.2-3.4)", "5-8");
+ if (!raw) return;
+ const m = raw.match(/^\s*(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)\s*$/);
+ if (!m) {
+ toast.error("Use startSec-endSec, e.g. 1.2-3.4");
+ return;
+ }
+ const startSec = Number(m[1]);
+ const endSec = Number(m[2]);
+ if (!Number.isFinite(startSec) || !Number.isFinite(endSec) || endSec <= startSec) {
+ toast.error("endSec must be greater than startSec.");
+ return;
+ }
+ const op: AxcutTimelineOperation = {
+ type: "add_skip_range",
+ startSec,
+ endSec,
+ };
+ void queueTimelineOp(op, `Added skip ${startSec}–${endSec}s.`);
+ }, [queueTimelineOp]);
+
return (
<aside className={styles.panel}>
<div className={styles.chatStrip}>
@@ -1176,35 +1233,65 @@ function ChatStripPanel() {
background: "var(--surface-warm)",
}}
>
- <span
- style={{
- font: "500 12px/1.3 var(--font-body)",
- color: "var(--fg-2)",
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
- flex: 1,
- cursor: "text",
- }}
- title="Click to rename"
- onClick={() => {
- const current = sessions.find((s) => s.id === activeSessionId);
- if (!current) return;
- const next = window.prompt("Rename conversation", current.title);
- if (next !== null) void handleRename(activeSessionId, next);
- }}
- >
- {sessions.find((s) => s.id === activeSessionId)?.title ?? "Conversation"}
- </span>
+ {editingSessionId === activeSessionId ? (
+ <input
+ ref={editingInputRef}
+ type="text"
+ autoFocus
+ value={editingTitle}
+ onChange={(event) => setEditingTitle(event.target.value)}
+ onFocus={(event) => event.currentTarget.select()}
+ onBlur={() => {
+ if (editingSessionId) void commitEditTitle(editingSessionId);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ if (editingSessionId) void commitEditTitle(editingSessionId);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ cancelEditTitle();
+ }
+ }}
+ style={{
+ font: "500 12px/1.3 var(--font-body)",
+ color: "var(--fg)",
+ background: "var(--surface)",
+ border: "1px solid var(--accent)",
+ borderRadius: "var(--r-sm)",
+ padding: "2px 6px",
+ flex: 1,
+ minWidth: 0,
+ }}
+ />
+ ) : (
+ <span
+ style={{
+ font: "500 12px/1.3 var(--font-body)",
+ color: "var(--fg-2)",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ flex: 1,
+ cursor: "text",
+ }}
+ title="Click to rename"
+ onClick={() => {
+ const current = sessions.find((s) => s.id === activeSessionId);
+ if (current) beginEditTitle(activeSessionId, current.title);
+ }}
+ >
+ {sessions.find((s) => s.id === activeSessionId)?.title ?? "Conversation"}
+ </span>
+ )}
<button
type="button"
title="Rename conversation"
aria-label="Rename conversation"
+ disabled={editingSessionId === activeSessionId}
onClick={() => {
const current = sessions.find((s) => s.id === activeSessionId);
- if (!current) return;
- const next = window.prompt("Rename conversation", current.title);
- if (next !== null) void handleRename(activeSessionId, next);
+ if (current) beginEditTitle(activeSessionId, current.title);
}}
style={{
background: "transparent",
@@ -1264,6 +1351,25 @@ function ChatStripPanel() {
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
</svg>
</button>
+ <button
+ type="button"
+ title="Add skip range"
+ aria-label="Add skip range"
+ disabled={!activeSessionId || queueBusy}
+ onClick={runAddSkip}
+ style={{
+ background: "transparent",
+ border: "1px solid var(--border-soft)",
+ borderRadius: "var(--r-sm)",
+ color: "var(--fg-2)",
+ font: "500 10px var(--font-body)",
+ padding: "2px 6px",
+ cursor: queueBusy ? "wait" : "pointer",
+ whiteSpace: "nowrap",
+ }}
+ >
+ + skip
+ </button>
</div>
) : null}
diff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.ts
new file mode 100644
index 000000000..6d596ef6a
--- /dev/null
+++ b/src/lib/ai-edition/document/operations.test.ts
@@ -0,0 +1,142 @@
+// ponytail: tests for the renderer-side timeline-operation union + dispatcher
+// in `src/lib/ai-edition/document/operations.ts`. Mirrors the axcut chat UI
+// parity work — same operations, same summary shape, same document mutation
+// rules. The IPC + service layer is exercised separately in
+// `electron/ai-edition/chat-service.test.ts`.
+
+import { describe, expect, it } from "vitest";
+import { type AxcutDocument, createEmptyDocument } from "../schema";
+import { applyTimelineOperation } from "./operations";
+
+function makeDoc(): AxcutDocument {
+ const base = createEmptyDocument({ title: "Test", projectId: "proj_ops" });
+ const asset = {
+ id: "asset_1",
+ kind: "video" as const,
+ label: "Recording",
+ originalPath: "C:/videos/rec.mp4",
+ durationSec: 60,
+ };
+ return {
+ ...base,
+ project: { ...base.project, primaryAssetId: asset.id },
+ assets: [asset],
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "clip_1",
+ assetId: asset.id,
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ };
+}
+
+describe("applyTimelineOperation.add_skip_range", () => {
+ it("appends a user-origin skip and returns a one-line summary", () => {
+ const result = applyTimelineOperation(makeDoc(), {
+ type: "add_skip_range",
+ startSec: 5,
+ endSec: 8,
+ });
+ expect(result.summary).toMatch(/added skip 0:05\.0.0:08\.0/);
+ const next = result.document;
+ const skips = next.timeline.skipRanges.filter((s) => s.assetId === "asset_1");
+ expect(skips).toHaveLength(1);
+ expect(skips[0]).toMatchObject({
+ startSec: 5,
+ endSec: 8,
+ origin: "user",
+ });
+ expect(next.preview.revision).toBe(1);
+ });
+
+ it("normalises reversed bounds (end < start)", () => {
+ const result = applyTimelineOperation(makeDoc(), {
+ type: "add_skip_range",
+ startSec: 10,
+ endSec: 4,
+ });
+ const skip = result.document.timeline.skipRanges.find((s) => s.assetId === "asset_1");
+ expect(skip?.startSec).toBe(4);
+ expect(skip?.endSec).toBe(10);
+ });
+});
+
+describe("applyTimelineOperation.drop_range", () => {
+ it("returns intervals that exclude the cut and a one-line summary", () => {
+ const result = applyTimelineOperation(makeDoc(), {
+ type: "drop_range",
+ assetId: "asset_1",
+ startSec: 10,
+ endSec: 20,
+ });
+ expect(result.summary).toMatch(/dropped 0:10\.0.0:20\.0/);
+ const next = result.document;
+ const asset = next.assets[0];
+ expect(asset).toBeDefined();
+ const totalKeep = next.timeline.clips
+ .filter((c) => c.assetId === "asset_1")
+ .reduce((sum, c) => sum + (c.sourceEndSec - c.sourceStartSec), 0);
+ expect(totalKeep).toBe(50);
+ });
+});
+
+describe("applyTimelineOperation.replace_timeline", () => {
+ it("rebuilds clips from the kept intervals", () => {
+ const result = applyTimelineOperation(makeDoc(), {
+ type: "replace_timeline",
+ intervals: [
+ { startSec: 0, endSec: 5 },
+ { startSec: 10, endSec: 30 },
+ ],
+ reason: "trim silences",
+ });
+ expect(result.summary).toMatch(/rebuilt timeline .2 interval/);
+ const clips = result.document.timeline.clips.filter((c) => c.assetId === "asset_1");
+ expect(clips).toHaveLength(2);
+ const totalClip = clips.reduce((s, c) => s + (c.sourceEndSec - c.sourceStartSec), 0);
+ expect(totalClip).toBe(25);
+ });
+});
+
+describe("applyTimelineOperation.restore_full_timeline", () => {
+ it("drops every skip and restores a single full clip", () => {
+ const doc = applyTimelineOperation(makeDoc(), {
+ type: "add_skip_range",
+ startSec: 5,
+ endSec: 10,
+ }).document;
+ const restored = applyTimelineOperation(doc, { type: "restore_full_timeline" });
+ expect(restored.summary).toBe("restored full timeline");
+ const asset = restored.document.assets[0];
+ expect(asset).toBeDefined();
+ const totalClip = restored.document.timeline.clips
+ .filter((c) => c.assetId === "asset_1")
+ .reduce((s, c) => s + (c.sourceEndSec - c.sourceStartSec), 0);
+ expect(totalClip).toBe(60);
+ expect(restored.document.timeline.skipRanges).toHaveLength(0);
+ });
+});
+
+describe("applyTimelineOperation.update_clip_range", () => {
+ it("trims the named clip and reseats the timeline", () => {
+ const result = applyTimelineOperation(makeDoc(), {
+ type: "update_clip_range",
+ clipId: "clip_1",
+ sourceStartSec: 10,
+ sourceEndSec: 25,
+ });
+ const clip = result.document.timeline.clips.find((c) => c.id === "clip_1");
+ expect(clip?.sourceStartSec).toBe(10);
+ expect(clip?.sourceEndSec).toBe(25);
+ });
+});
diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.ts
new file mode 100644
index 000000000..553cbb7f6
--- /dev/null
+++ b/src/lib/ai-edition/document/operations.ts
@@ -0,0 +1,226 @@
+// Timeline operation dispatcher — port of axcut's `apps/server/src/services/document-service.ts#applyOperation`
+// in the slim shape Phase 1 needs. The full union covers the 11 timeline ops
+// axcut supports; we ship the four mutating ones our agent already exposes
+// plus two structural helpers (drop range, restore full timeline).
+//
+// Each variant carries enough context to drive the document model directly
+// and to compute a one-line chat summary. Callers (renderer quick-edit UI,
+// agent tools, future renderer ops toolbar) hand `applyTimelineOperation`
+// a parsed `AxcutTimelineOperation` and get back the mutated document
+// and a summary string.
+
+import type { AxcutDocument } from "../schema";
+import {
+ byStart,
+ normalizeIntervals,
+ primaryAssetDuration,
+ replaceTimeline,
+ resequenceClips,
+} from "./timeline";
+
+export type AxcutTimelineOperation =
+ | {
+ type: "replace_timeline";
+ intervals: Array<{ startSec: number; endSec: number }>;
+ reason?: string;
+ }
+ | {
+ type: "drop_range";
+ assetId?: string;
+ startSec: number;
+ endSec: number;
+ reason?: string;
+ }
+ | {
+ type: "add_skip_range";
+ assetId?: string;
+ startSec: number;
+ endSec: number;
+ reason?: string;
+ }
+ | {
+ type: "restore_full_timeline";
+ reason?: string;
+ }
+ | {
+ type: "update_clip_range";
+ clipId: string;
+ sourceStartSec: number;
+ sourceEndSec: number;
+ reason?: string;
+ };
+
+export interface AppliedTimelineOperation {
+ document: AxcutDocument;
+ summary: string;
+}
+
+function formatSec(sec: number): string {
+ const safe = Number.isFinite(sec) && sec > 0 ? sec : 0;
+ const m = Math.floor(safe / 60);
+ const s = (safe % 60).toFixed(1);
+ return `${m}:${s.padStart(4, "0")}`;
+}
+
+function pickAssetId(document: AxcutDocument, explicit?: string): string | null {
+ if (explicit) return explicit;
+ return document.project.primaryAssetId ?? document.assets[0]?.id ?? null;
+}
+
+function dropRangeToIntervals(
+ document: AxcutDocument,
+ assetId: string,
+ startSec: number,
+ endSec: number,
+): Array<{ startSec: number; endSec: number }> {
+ // ponytail: build the kept intervals = (existing clips on this asset) − (cut).
+ // We start from the union of existing clips on the asset, normalize it, then
+ // punch out the cut. axcut's equivalent pulls from `clips[]` directly, but
+ // for the renderer quick-edit path the asset may have a single full clip
+ // (the common import-then-edit shape), so we synthesize its range first.
+ const duration = primaryAssetDuration(document);
+ if (duration <= 0) return [];
+ const existing = document.timeline.clips
+ .filter((c) => c.assetId === assetId)
+ .map((c) => ({
+ startSec: Math.min(c.sourceStartSec, c.sourceEndSec ?? c.sourceStartSec),
+ endSec: Math.max(c.sourceStartSec, c.sourceEndSec ?? c.sourceStartSec),
+ }));
+ const lo = Math.max(0, Math.min(startSec, endSec));
+ const hi = Math.max(lo, Math.max(startSec, endSec));
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || hi <= lo) {
+ // ponytail: no-op range — keep the union of existing clips (or the full
+ // duration if no clips are recorded yet).
+ if (existing.length === 0) return [{ startSec: 0, endSec: duration }];
+ return normalizeIntervals(
+ duration,
+ existing.map((e) => ({ startSec: e.startSec, endSec: e.endSec })),
+ );
+ }
+ const union = existing.length > 0 ? existing : [{ startSec: 0, endSec: duration }];
+ const cut = { startSec: lo, endSec: hi };
+ const kept: Array<{ startSec: number; endSec: number }> = [];
+ for (const iv of union) {
+ if (cut.endSec <= iv.startSec || cut.startSec >= iv.endSec) {
+ kept.push(iv);
+ continue;
+ }
+ if (iv.startSec < cut.startSec) {
+ kept.push({ startSec: iv.startSec, endSec: cut.startSec });
+ }
+ if (cut.endSec < iv.endSec) {
+ kept.push({ startSec: cut.endSec, endSec: iv.endSec });
+ }
+ }
+ return normalizeIntervals(
+ duration,
+ kept.map((e) => ({ startSec: e.startSec, endSec: e.endSec })),
+ );
+}
+
+export function applyTimelineOperation(
+ document: AxcutDocument,
+ op: AxcutTimelineOperation,
+): AppliedTimelineOperation {
+ switch (op.type) {
+ case "replace_timeline": {
+ if (!op.intervals.length) {
+ return { document, summary: "no intervals to keep" };
+ }
+ const reason = op.reason ?? "replaceTimeline";
+ const next = replaceTimeline(document, op.intervals, reason, "user");
+ const kept = op.intervals.length;
+ return {
+ document: next,
+ summary: `rebuilt timeline (${kept} interval${kept === 1 ? "" : "s"})`,
+ };
+ }
+ case "drop_range": {
+ const assetId = pickAssetId(document, op.assetId);
+ if (!assetId) return { document, summary: "no asset to drop from" };
+ const intervals = dropRangeToIntervals(document, assetId, op.startSec, op.endSec);
+ if (!intervals.length) {
+ return { document, summary: "drop range was empty" };
+ }
+ const reason = op.reason ?? `dropped ${formatSec(op.startSec)}–${formatSec(op.endSec)}`;
+ const next = replaceTimeline(document, intervals, reason, "user");
+ return {
+ document: next,
+ summary: `dropped ${formatSec(op.startSec)}–${formatSec(op.endSec)}`,
+ };
+ }
+ case "add_skip_range": {
+ const assetId = pickAssetId(document, op.assetId);
+ if (!assetId) return { document, summary: "no asset to skip" };
+ const lo = Math.max(0, Math.min(op.startSec, op.endSec));
+ const hi = Math.max(lo, Math.max(op.startSec, op.endSec));
+ const existing = document.timeline.skipRanges.filter((s) => s.assetId === assetId);
+ const merged = normalizeIntervals(primaryAssetDuration(document), [
+ { startSec: lo, endSec: hi },
+ ...existing.map((s) => ({ startSec: s.startSec, endSec: s.endSec })),
+ ]);
+ const next: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ skipRanges: merged.map((iv, i) => ({
+ id: `skip_${i + 1}`,
+ assetId,
+ startSec: iv.startSec,
+ endSec: iv.endSec,
+ origin: "user" as const,
+ reason: op.reason ?? "",
+ })),
+ },
+ preview: { ...document.preview, revision: document.preview.revision + 1 },
+ };
+ return {
+ document: next,
+ summary: `added skip ${formatSec(lo)}–${formatSec(hi)}`,
+ };
+ }
+ case "restore_full_timeline": {
+ const duration = primaryAssetDuration(document);
+ if (duration <= 0) return { document, summary: "no duration yet" };
+ const next = replaceTimeline(
+ document,
+ [{ startSec: 0, endSec: duration }],
+ op.reason ?? "restored full timeline",
+ "user",
+ );
+ return { document: next, summary: "restored full timeline" };
+ }
+ case "update_clip_range": {
+ const clips = document.timeline.clips.map((c) => {
+ if (c.id !== op.clipId) return c;
+ const lo = Math.max(0, Math.min(op.sourceStartSec, op.sourceEndSec));
+ const hi = Math.max(lo, Math.max(op.sourceStartSec, op.sourceEndSec));
+ return {
+ ...c,
+ sourceStartSec: lo,
+ sourceEndSec: hi,
+ timelineStartSec: 0,
+ timelineEndSec: 0,
+ };
+ });
+ const next: AxcutDocument = {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ clips: resequenceClips(clips),
+ },
+ preview: { ...document.preview, revision: document.preview.revision + 1 },
+ };
+ return {
+ document: next,
+ summary: `trimmed clip to ${formatSec(Math.min(op.sourceStartSec, op.sourceEndSec))}–${formatSec(Math.max(op.sourceStartSec, op.sourceEndSec))}`,
+ };
+ }
+ default: {
+ // ponytail: exhaustive — TS errors here when a new variant is added.
+ const exhaustive: never = op;
+ void exhaustive;
+ return { document, summary: "unhandled operation" };
+ }
+ }
+}
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index 826582f79..82c4a6f85 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -1,190 +1,190 @@
-// Ported from axcut/apps/server/src/lib/timeline.ts — pure interval math for
-// the clip/skip model. No DOM, no IPC, no side effects. The caller (store,
-// exporter, agent) feeds an AxcutDocument and gets back intervals or a new
-// document with updated clips.
-//
-// ponytail: only the ops Phase 1 needs (replaceTimeline, dropRange, restore).
-// The full 11-op dispatcher lands in Phase 6 with the agent runtime.
-
-import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
-
-function byStart(a: { startSec: number }, b: { startSec: number }): number {
- return a.startSec - b.startSec;
-}
-
-export interface Interval {
- startSec: number;
- endSec: number;
-}
-
-export function normalizeIntervals(durationSec: number, intervals: Interval[]): Interval[] {
- const bounded = intervals
- .map((item) => ({
- startSec: Math.max(0, Math.min(durationSec, item.startSec)),
- endSec: Math.max(0, Math.min(durationSec, item.endSec)),
- }))
- .filter((item) => item.endSec > item.startSec)
- .sort(byStart);
-
- const merged: Interval[] = [];
- for (const item of bounded) {
- const last = merged.at(-1);
- if (!last || item.startSec > last.endSec) {
- merged.push({ ...item });
- continue;
- }
- last.endSec = Math.max(last.endSec, item.endSec);
- }
- return merged;
-}
-
-export function primaryAssetDuration(document: AxcutDocument): number {
- const asset =
- document.assets.find((item) => item.id === document.project.primaryAssetId) ??
- document.assets[0];
- return asset?.durationSec ?? 0;
-}
-
-export function timelineIntervals(document: AxcutDocument): Interval[] {
- return normalizeIntervals(
- primaryAssetDuration(document),
- document.timeline.clips.map((clip) => ({
- startSec: clip.sourceStartSec,
- endSec: clip.sourceEndSec ?? primaryAssetDuration(document),
- })),
- );
-}
-
-export function buildTimelineFromIntervals(
- assetId: string,
- intervals: Interval[],
- options: {
- origin: "system" | "agent" | "user";
- reason: string;
- transcript: AxcutTranscript | null;
- },
-): AxcutClip[] {
- let cursor = 0;
- return intervals.map((interval, index) => {
- const duration = interval.endSec - interval.startSec;
- const timelineStartSec = cursor;
- const timelineEndSec = cursor + duration;
- cursor = timelineEndSec;
- return {
- id: `clip_${index + 1}`,
- assetId,
- sourceStartSec: interval.startSec,
- sourceEndSec: interval.endSec,
- timelineStartSec,
- timelineEndSec,
- wordRefs: collectWordRefs(options.transcript, interval.startSec, interval.endSec),
- origin: options.origin,
- reason: options.reason,
- };
- });
-}
-
-function collectWordRefs(
- transcript: AxcutTranscript | null,
- startSec: number,
- endSec: number,
-): string[] {
- if (!transcript) return [];
- return transcript.words
- .filter((word) => word.endSec > startSec && word.startSec < endSec)
- .map((word) => word.id);
-}
-
-// Lay clips back-to-back from t=0, preserving each clip's own length. Called
-// after any structural change (insert / move / remove / trim) so the timeline
-// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
-// the agent tool executor (main process) so both enforce the same invariant.
-export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
- let cursor = 0;
- return clips.map((c) => {
- const timelineLen = c.timelineEndSec - c.timelineStartSec;
- const sourceLen = (c.sourceEndSec ?? 0) - c.sourceStartSec;
- const len = Math.max(0.001, timelineLen > 0 ? timelineLen : sourceLen);
- const next = { ...c, timelineStartSec: cursor, timelineEndSec: cursor + len };
- cursor += len;
- return next;
- });
-}
-
-export function subtractInterval(intervals: Interval[], cut: Interval): Interval[] {
- const output: Interval[] = [];
- for (const interval of intervals) {
- if (cut.endSec <= interval.startSec || cut.startSec >= interval.endSec) {
- output.push(interval);
- continue;
- }
- if (cut.startSec > interval.startSec) {
- output.push({ startSec: interval.startSec, endSec: cut.startSec });
- }
- if (cut.endSec < interval.endSec) {
- output.push({ startSec: cut.endSec, endSec: interval.endSec });
- }
- }
- return output;
-}
-
-export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {
- const cuts: Interval[] = [];
- let cursor = 0;
- for (const interval of normalizeIntervals(durationSec, intervals)) {
- if (interval.startSec > cursor) {
- cuts.push({ startSec: cursor, endSec: interval.startSec });
- }
- cursor = Math.max(cursor, interval.endSec);
- }
- if (cursor < durationSec) {
- cuts.push({ startSec: cursor, endSec: durationSec });
- }
- return cuts;
-}
-
-export function replaceTimeline(
- document: AxcutDocument,
- intervals: Interval[],
- reason: string,
- origin: "system" | "agent" | "user" = "user",
-): AxcutDocument {
- const assetId = document.project.primaryAssetId ?? document.assets[0]?.id;
- if (!assetId) {
- throw new Error("Cannot update timeline without a primary asset.");
- }
- const duration = primaryAssetDuration(document);
- const normalized = normalizeIntervals(duration, intervals);
- const clips = buildTimelineFromIntervals(assetId, normalized, {
- origin,
- reason,
- transcript: document.transcript,
- });
- const skipRanges = invertIntervals(normalized, duration).map((cut, i) => ({
- id: `skip_${i + 1}`,
- assetId,
- startSec: cut.startSec,
- endSec: cut.endSec,
- origin,
- reason,
- }));
- return {
- ...document,
- timeline: {
- ...document.timeline,
- clips,
- skipRanges,
- gaps: [],
- },
- preview: {
- ...document.preview,
- revision: document.preview.revision + 1,
- },
- };
-}
-
-export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {
- const duration = primaryAssetDuration(document);
- if (duration <= 0) return document;
- return replaceTimeline(document, [{ startSec: 0, endSec: duration }], "Restore full timeline");
-}
+// Ported from axcut/apps/server/src/lib/timeline.ts — pure interval math for
+// the clip/skip model. No DOM, no IPC, no side effects. The caller (store,
+// exporter, agent) feeds an AxcutDocument and gets back intervals or a new
+// document with updated clips.
+//
+// ponytail: only the ops Phase 1 needs (replaceTimeline, dropRange, restore).
+// The full 11-op dispatcher lands in Phase 6 with the agent runtime.
+
+import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
+
+export function byStart(a: { startSec: number }, b: { startSec: number }): number {
+ return a.startSec - b.startSec;
+}
+
+export interface Interval {
+ startSec: number;
+ endSec: number;
+}
+
+export function normalizeIntervals(durationSec: number, intervals: Interval[]): Interval[] {
+ const bounded = intervals
+ .map((item) => ({
+ startSec: Math.max(0, Math.min(durationSec, item.startSec)),
+ endSec: Math.max(0, Math.min(durationSec, item.endSec)),
+ }))
+ .filter((item) => item.endSec > item.startSec)
+ .sort(byStart);
+
+ const merged: Interval[] = [];
+ for (const item of bounded) {
+ const last = merged.at(-1);
+ if (!last || item.startSec > last.endSec) {
+ merged.push({ ...item });
+ continue;
+ }
+ last.endSec = Math.max(last.endSec, item.endSec);
+ }
+ return merged;
+}
+
+export function primaryAssetDuration(document: AxcutDocument): number {
+ const asset =
+ document.assets.find((item) => item.id === document.project.primaryAssetId) ??
+ document.assets[0];
+ return asset?.durationSec ?? 0;
+}
+
+export function timelineIntervals(document: AxcutDocument): Interval[] {
+ return normalizeIntervals(
+ primaryAssetDuration(document),
+ document.timeline.clips.map((clip) => ({
+ startSec: clip.sourceStartSec,
+ endSec: clip.sourceEndSec ?? primaryAssetDuration(document),
+ })),
+ );
+}
+
+export function buildTimelineFromIntervals(
+ assetId: string,
+ intervals: Interval[],
+ options: {
+ origin: "system" | "agent" | "user";
+ reason: string;
+ transcript: AxcutTranscript | null;
+ },
+): AxcutClip[] {
+ let cursor = 0;
+ return intervals.map((interval, index) => {
+ const duration = interval.endSec - interval.startSec;
+ const timelineStartSec = cursor;
+ const timelineEndSec = cursor + duration;
+ cursor = timelineEndSec;
+ return {
+ id: `clip_${index + 1}`,
+ assetId,
+ sourceStartSec: interval.startSec,
+ sourceEndSec: interval.endSec,
+ timelineStartSec,
+ timelineEndSec,
+ wordRefs: collectWordRefs(options.transcript, interval.startSec, interval.endSec),
+ origin: options.origin,
+ reason: options.reason,
+ };
+ });
+}
+
+function collectWordRefs(
+ transcript: AxcutTranscript | null,
+ startSec: number,
+ endSec: number,
+): string[] {
+ if (!transcript) return [];
+ return transcript.words
+ .filter((word) => word.endSec > startSec && word.startSec < endSec)
+ .map((word) => word.id);
+}
+
+// Lay clips back-to-back from t=0, preserving each clip's own length. Called
+// after any structural change (insert / move / remove / trim) so the timeline
+// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
+// the agent tool executor (main process) so both enforce the same invariant.
+export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
+ let cursor = 0;
+ return clips.map((c) => {
+ const timelineLen = c.timelineEndSec - c.timelineStartSec;
+ const sourceLen = (c.sourceEndSec ?? 0) - c.sourceStartSec;
+ const len = Math.max(0.001, timelineLen > 0 ? timelineLen : sourceLen);
+ const next = { ...c, timelineStartSec: cursor, timelineEndSec: cursor + len };
+ cursor += len;
+ return next;
+ });
+}
+
+export function subtractInterval(intervals: Interval[], cut: Interval): Interval[] {
+ const output: Interval[] = [];
+ for (const interval of intervals) {
+ if (cut.endSec <= interval.startSec || cut.startSec >= interval.endSec) {
+ output.push(interval);
+ continue;
+ }
+ if (cut.startSec > interval.startSec) {
+ output.push({ startSec: interval.startSec, endSec: cut.startSec });
+ }
+ if (cut.endSec < interval.endSec) {
+ output.push({ startSec: cut.endSec, endSec: interval.endSec });
+ }
+ }
+ return output;
+}
+
+export function invertIntervals(intervals: Interval[], durationSec: number): Interval[] {
+ const cuts: Interval[] = [];
+ let cursor = 0;
+ for (const interval of normalizeIntervals(durationSec, intervals)) {
+ if (interval.startSec > cursor) {
+ cuts.push({ startSec: cursor, endSec: interval.startSec });
+ }
+ cursor = Math.max(cursor, interval.endSec);
+ }
+ if (cursor < durationSec) {
+ cuts.push({ startSec: cursor, endSec: durationSec });
+ }
+ return cuts;
+}
+
+export function replaceTimeline(
+ document: AxcutDocument,
+ intervals: Interval[],
+ reason: string,
+ origin: "system" | "agent" | "user" = "user",
+): AxcutDocument {
+ const assetId = document.project.primaryAssetId ?? document.assets[0]?.id;
+ if (!assetId) {
+ throw new Error("Cannot update timeline without a primary asset.");
+ }
+ const duration = primaryAssetDuration(document);
+ const normalized = normalizeIntervals(duration, intervals);
+ const clips = buildTimelineFromIntervals(assetId, normalized, {
+ origin,
+ reason,
+ transcript: document.transcript,
+ });
+ const skipRanges = invertIntervals(normalized, duration).map((cut, i) => ({
+ id: `skip_${i + 1}`,
+ assetId,
+ startSec: cut.startSec,
+ endSec: cut.endSec,
+ origin,
+ reason,
+ }));
+ return {
+ ...document,
+ timeline: {
+ ...document.timeline,
+ clips,
+ skipRanges,
+ gaps: [],
+ },
+ preview: {
+ ...document.preview,
+ revision: document.preview.revision + 1,
+ },
+ };
+}
+
+export function restoreFullTimeline(document: AxcutDocument): AxcutDocument {
+ const duration = primaryAssetDuration(document);
+ if (duration <= 0) return document;
+ return replaceTimeline(document, [{ startSec: 0, endSec: duration }], "Restore full timeline");
+}
diff --git a/src/lib/ai-edition/document/transcribe.test.ts b/src/lib/ai-edition/document/transcribe.test.ts
index 36938b47c..bde444601 100644
--- a/src/lib/ai-edition/document/transcribe.test.ts
+++ b/src/lib/ai-edition/document/transcribe.test.ts
@@ -1,6 +1,58 @@
-import { describe, expect, it } from "vitest";
-import type { AxcutTranscript } from "../schema";
-import { toAxcutTranscriptDsl } from "./transcribe";
+import { describe, expect, it, vi } from "vitest";
+import type { AxcutDocument, AxcutTranscript } from "../schema";
+import { toAxcutTranscriptDsl, transcribeAsset } from "./transcribe";
+
+vi.mock("@/components/video-editor/projectPersistence", () => ({
+ toFileUrl: (path: string) => `file://${path}`,
+}));
+
+vi.mock("@/lib/captioning", () => ({
+ extractMono16kFromVideoUrl: vi.fn(async () => ({
+ samples: new Float32Array([0, 0, 0]),
+ sampleRate: 16_000,
+ })),
+ transcribeMono16kToSegments: vi.fn(),
+}));
+
+const { transcribeMono16kToSegments } = await import("@/lib/captioning");
+const transcribeMock = vi.mocked(transcribeMono16kToSegments);
+
+function makeDoc(): AxcutDocument {
+ return {
+ schemaVersion: 3,
+ project: {
+ id: "proj_1",
+ title: "Test",
+ createdAt: "2026-07-03T00:00:00Z",
+ updatedAt: "2026-07-03T00:00:00Z",
+ primaryAssetId: "asset_1",
+ },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "demo.mp4",
+ originalPath: "/tmp/demo.mp4",
+ durationSec: 60,
+ },
+ ],
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ id: "tl_1",
+ clips: [],
+ gaps: [],
+ operations: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ legacyEditor: null,
+ agent: null,
+ preview: { revision: 0, playbackRate: 1 },
+ export: null,
+ history: { revisions: [] },
+ };
+}
describe("toAxcutTranscriptDsl", () => {
it("emits the AXCUT_TRANSCRIPT v1 header + META + segments + words", () => {
@@ -72,3 +124,71 @@ describe("toAxcutTranscriptDsl", () => {
expect(dsl).toBe('AXCUT_TRANSCRIPT v1\nMETA source_video="x.mp4" language="fr" kind="source"');
});
});
+
+describe("transcribeAsset language handling", () => {
+ it("forwards a forced language to the worker and stores it on the transcript", async () => {
+ transcribeMock.mockResolvedValueOnce({
+ segments: [{ startSec: 0, endSec: 1, text: "bonjour" }],
+ granularity: "phrase",
+ detectedLanguage: "fr",
+ });
+
+ const doc = makeDoc();
+ const t = await transcribeAsset(doc, "asset_1", { language: "fr" });
+
+ // The forced ISO code reaches the underlying worker call.
+ expect(transcribeMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ language: "fr" }),
+ );
+ // The stored transcript reports the model-confirmed language.
+ expect(t.language).toBe("fr");
+ });
+
+ it("omits the language option from the worker call when 'auto' so Whisper detects", async () => {
+ transcribeMock.mockResolvedValueOnce({
+ segments: [{ startSec: 0, endSec: 1, text: "hello" }],
+ granularity: "phrase",
+ detectedLanguage: "en",
+ });
+
+ const doc = makeDoc();
+ const t = await transcribeAsset(doc, "asset_1", { language: "auto" });
+
+ expect(transcribeMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ language: undefined }),
+ );
+ expect(t.language).toBe("en");
+ });
+
+ it("captures Whisper's auto-detected language when no option was passed", async () => {
+ transcribeMock.mockResolvedValueOnce({
+ segments: [{ startSec: 0, endSec: 1, text: "hola" }],
+ granularity: "phrase",
+ detectedLanguage: "es",
+ });
+
+ const doc = makeDoc();
+ const t = await transcribeAsset(doc, "asset_1");
+
+ expect(transcribeMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ language: undefined }),
+ );
+ expect(t.language).toBe("es");
+ });
+
+ it("falls back to 'auto' when the model reports no language token", async () => {
+ transcribeMock.mockResolvedValueOnce({
+ segments: [],
+ granularity: "phrase",
+ detectedLanguage: null,
+ });
+
+ const doc = makeDoc();
+ const t = await transcribeAsset(doc, "asset_1");
+
+ expect(t.language).toBe("auto");
+ });
+});
diff --git a/src/lib/ai-edition/document/transcribe.ts b/src/lib/ai-edition/document/transcribe.ts
index cc9cefa25..30a6abff6 100644
--- a/src/lib/ai-edition/document/transcribe.ts
+++ b/src/lib/ai-edition/document/transcribe.ts
@@ -33,9 +33,17 @@ export async function transcribeAsset(
});
options.onStatus?.("transcribing");
+ // Only pass `language` to the worker when the caller forced a specific
+ // code. `"auto"` (or any falsy value) leaves Whisper to detect from
+ // the audio. The pipeline tags every chunk with the language it used
+ // (forced or detected) and we read it back via `result.detectedLanguage`
+ // so the stored transcript reflects reality, not the input option.
+ const forcedLanguage =
+ options.language && options.language !== "auto" ? options.language : undefined;
const result = await transcribeMono16kToSegments(audioResult.samples, {
trimRegions: [],
signal: options.signal,
+ language: forcedLanguage,
});
const segments: AxcutTranscriptSegment[] = [];
@@ -76,7 +84,10 @@ export async function transcribeAsset(
return {
assetId,
- language: options.language ?? "auto",
+ // Prefer the model-reported language (covers both forced picks and
+ // auto-detect); fall back to the input option, then "auto" when
+ // nothing was detected (very rare on tiny.en — usually a no-audio run).
+ language: result.detectedLanguage ?? options.language ?? "auto",
segments,
words,
};
diff --git a/src/lib/ai-edition/store/useOptimisticTimelineOps.ts b/src/lib/ai-edition/store/useOptimisticTimelineOps.ts
new file mode 100644
index 000000000..5e981ce02
--- /dev/null
+++ b/src/lib/ai-edition/store/useOptimisticTimelineOps.ts
@@ -0,0 +1,73 @@
+// ponytail: optimistic timeline-ops state machine. Mirrors axcut's
+// `queueTimelineOperation` flow but on a smaller surface: we read the
+// project store, apply the op locally for instant UI feedback, fire
+// the IPC, then either commit the server's authoritative document or
+// roll back on failure. Session messages aren't touched locally — the
+// server appends the summary message before returning.
+
+import { useCallback, useState } from "react";
+import { toast } from "sonner";
+import { nativeBridgeClient } from "@/native/client";
+import type { AxcutTimelineOperation } from "@/native/contracts";
+import { applyTimelineOperation } from "../document/operations";
+import type { AxcutDocument } from "../schema";
+import { useProjectStore } from "./projectStore";
+
+export interface OptimisticTimelineOps {
+ queue: (operation: AxcutTimelineOperation, conversationMessage: string) => Promise<void>;
+ busy: boolean;
+}
+
+export function useOptimisticTimelineOps(
+ projectId: string | null,
+ sessionId: string | null,
+): OptimisticTimelineOps {
+ const [busy, setBusy] = useState(false);
+
+ const queue = useCallback(
+ async (operation: AxcutTimelineOperation, conversationMessage: string) => {
+ if (!projectId || !sessionId) {
+ toast.error("Open a project to run a timeline operation.");
+ return;
+ }
+ const store = useProjectStore.getState();
+ const previous = store.document;
+ if (!previous) {
+ toast.error("No project document loaded yet.");
+ return;
+ }
+ const optimistic = applyTimelineOperation(previous, operation).document;
+ store.setDocument(optimistic);
+ setBusy(true);
+ try {
+ const result = await nativeBridgeClient.aiEdition.runTimelineOperation(
+ projectId,
+ sessionId,
+ operation,
+ conversationMessage,
+ );
+ if (!result.success) {
+ store.setDocument(previous);
+ toast.error("Timeline edit failed", { description: result.error });
+ return;
+ }
+ // ponytail: keep the optimistic doc on failure-free success. The
+ // server-applied doc is byte-identical in the happy path; only
+ // when normalisation diverges do we need to swap.
+ const serverDoc = result.result.document as AxcutDocument;
+ store.setDocument(serverDoc);
+ toast.success(result.result.summary);
+ } catch (err) {
+ store.setDocument(previous);
+ toast.error("Timeline edit failed", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ setBusy(false);
+ }
+ },
+ [projectId, sessionId],
+ );
+
+ return { queue, busy };
+}
diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.ts
index a72a89673..2e887063f 100644
--- a/src/lib/captioning/transcribe.ts
+++ b/src/lib/captioning/transcribe.ts
@@ -12,6 +12,12 @@ export type CaptionTimestampGranularity = "word" | "phrase";
export interface TranscribeMono16kResult {
segments: CaptionSegment[];
granularity: CaptionTimestampGranularity;
+ /**
+ * ISO 639-1 code Whisper settled on for the chunk stream — either the
+ * forced one (when `language` was supplied) or what it auto-detected.
+ * `null` if the model produced no language token (very rare on tiny.en).
+ */
+ detectedLanguage?: string | null;
}
/** Request payload posted from the renderer to the transcription worker. */
@@ -26,12 +32,19 @@ export interface TranscribeWorkerRequest {
useLocalModels: boolean;
/** Base URL of bundled resources (packaged: resourcesPath file:// URL); used when `useLocalModels`. */
assetBaseUrl?: string;
+ /** ISO 639-1 code (e.g. "en", "fr") to force. Omit for auto-detect. */
+ language?: string;
}
/** Messages the transcription worker posts back to the renderer. */
export type TranscribeWorkerResponse =
| { type: "status"; phase: "model" | "transcribe" }
- | { type: "result"; segments: CaptionSegment[]; granularity: CaptionTimestampGranularity }
+ | {
+ type: "result";
+ segments: CaptionSegment[];
+ granularity: CaptionTimestampGranularity;
+ detectedLanguage?: string | null;
+ }
| { type: "error"; message: string };
/**
@@ -47,6 +60,7 @@ export function transcribeMono16kToSegments(
trimRegions?: TrimRegion[];
onStatus?: (phase: "model" | "transcribe") => void;
signal?: AbortSignal;
+ language?: string;
},
): Promise<TranscribeMono16kResult> {
if (options?.signal?.aborted) {
@@ -77,7 +91,13 @@ export function transcribeMono16kToSegments(
return;
}
if (msg.type === "result") {
- finish(() => resolve({ segments: msg.segments, granularity: msg.granularity }));
+ finish(() =>
+ resolve({
+ segments: msg.segments,
+ granularity: msg.granularity,
+ detectedLanguage: msg.detectedLanguage,
+ }),
+ );
return;
}
finish(() => reject(new Error(msg.message)));
@@ -100,6 +120,7 @@ export function transcribeMono16kToSegments(
trimRegions: options?.trimRegions ?? [],
useLocalModels,
assetBaseUrl,
+ language: options?.language,
};
worker.postMessage(request);
});
diff --git a/src/lib/captioning/transcribe.worker.ts b/src/lib/captioning/transcribe.worker.ts
index ab65b2eea..bfde2b118 100644
--- a/src/lib/captioning/transcribe.worker.ts
+++ b/src/lib/captioning/transcribe.worker.ts
@@ -74,19 +74,20 @@ async function loadTranscriber(opts: {
}
self.onmessage = async (event: MessageEvent<TranscribeWorkerRequest>) => {
- const { samples, trimRegions, useLocalModels, assetBaseUrl } = event.data;
+ const { samples, trimRegions, useLocalModels, assetBaseUrl, language } = event.data;
try {
post({ type: "status", phase: "model" });
const transcriber = await loadTranscriber({ useLocalModels, assetBaseUrl });
post({ type: "status", phase: "transcribe" });
- const { segments, granularity } = await runTranscription(
+ const { segments, granularity, detectedLanguage } = await runTranscription(
transcriber,
samples,
trimRegions ?? [],
+ { language },
);
- post({ type: "result", segments, granularity });
+ post({ type: "result", segments, granularity, detectedLanguage });
} catch (e) {
post({ type: "error", message: e instanceof Error ? e.message : String(e) });
}
diff --git a/src/lib/captioning/transcribeCore.ts b/src/lib/captioning/transcribeCore.ts
index 9834e3654..037105457 100644
--- a/src/lib/captioning/transcribeCore.ts
+++ b/src/lib/captioning/transcribeCore.ts
@@ -13,6 +13,23 @@ export type TranscriberFn = (
opts: Record<string, unknown>,
) => Promise<unknown>;
+/**
+ * Pull the language Whisper settled on from a chunk stream. The pipeline
+ * tags every chunk with the language code it used (forced via the
+ * `language` arg, or auto-detected when no `language` was given). We
+ * surface the first non-null value — later chunks only differ when the
+ * model genuinely switched, which is rare and we don't expose it.
+ */
+function pickDetectedLanguage(result: unknown): string | null {
+ const chunks = (result as { chunks?: unknown[] })?.chunks;
+ if (!Array.isArray(chunks)) return null;
+ for (const c of chunks) {
+ const lang = (c as { language?: unknown })?.language;
+ if (typeof lang === "string" && lang.length > 0) return lang;
+ }
+ return null;
+}
+
function segmentOverlapsTrim(startMs: number, endMs: number, trims: TrimRegion[]): boolean {
return trims.some((t) => startMs < t.endMs && endMs > t.startMs);
}
@@ -127,16 +144,29 @@ function segmentsFromTranscriberChunks(
async function runTranscriberOnSlice(
transcriber: TranscriberFn,
samples: Float32Array,
- opts: { forceFullSequences: boolean; timestampMode: "word" | "phrase" },
-): Promise<unknown> {
+ opts: {
+ forceFullSequences: boolean;
+ timestampMode: "word" | "phrase";
+ language?: string;
+ },
+): Promise<{ result: unknown; detectedLanguage: string | null }> {
const durationSec = samples.length / 16_000;
// Only chunk long clips; short-audio chunking regressed some Whisper.js runs (empty chunks).
const chunking = durationSec > 30 ? { chunk_length_s: 30, stride_length_s: 5 } : {};
- return transcriber(samples, {
+ // `return_language` makes the pipeline keep the `language` field on each
+ // output chunk so we can read back what Whisper settled on (forced or
+ // auto-detected). Without it the tokenizer strips language from chunks
+ // and we lose the detection.
+ const result = await transcriber(samples, {
return_timestamps: opts.timestampMode === "word" ? "word" : true,
force_full_sequences: opts.forceFullSequences,
+ // Only set `language` when explicitly forced. Omitting it lets Whisper
+ // auto-detect from the audio, which is what the "Auto" picker wants.
+ ...(opts.language ? { language: opts.language } : {}),
+ return_language: true,
...chunking,
});
+ return { result, detectedLanguage: pickDetectedLanguage(result) };
}
/** Flattens the various shapes a Transformers.js ASR result can take into a chunk list. */
@@ -185,29 +215,36 @@ export async function runTranscription(
transcriber: TranscriberFn,
samples: Float32Array,
trims: TrimRegion[],
+ options?: { language?: string },
): Promise<TranscribeMono16kResult> {
+ const forcedLanguage = options?.language;
const transcribeOne = async (
ignoreTrims: boolean,
forceFullSequences: boolean,
timestampMode: "word" | "phrase",
- ): Promise<CaptionSegment[]> => {
+ ): Promise<{ segments: CaptionSegment[]; detectedLanguage: string | null }> => {
try {
const activeTrims = ignoreTrims ? [] : trims;
if (samples.length <= TRANSCRIBE_SLICE_SAMPLES) {
const { slice, realDurationSec } = padTailSliceForTranscribe(samples);
- const result = await runTranscriberOnSlice(transcriber, slice, {
+ const { result, detectedLanguage } = await runTranscriberOnSlice(transcriber, slice, {
forceFullSequences,
timestampMode,
+ language: forcedLanguage,
});
- return segmentsFromTranscriberChunks(
- extractChunksFromAsrResult(result),
- 0,
- activeTrims,
- realDurationSec,
- );
+ return {
+ segments: segmentsFromTranscriberChunks(
+ extractChunksFromAsrResult(result),
+ 0,
+ activeTrims,
+ realDurationSec,
+ ),
+ detectedLanguage,
+ };
}
const all: CaptionSegment[] = [];
+ let detectedLanguage: string | null = null;
for (let offset = 0; offset < samples.length; offset += TRANSCRIBE_SLICE_SAMPLES) {
const end = Math.min(offset + TRANSCRIBE_SLICE_SAMPLES, samples.length);
const sliceRaw = samples.subarray(offset, end);
@@ -220,10 +257,16 @@ export async function runTranscription(
? padTailSliceForTranscribe(sliceRaw)
: { slice: sliceRaw, realDurationSec: sliceRaw.length / 16_000 };
- const result = await runTranscriberOnSlice(transcriber, slice, {
- forceFullSequences,
- timestampMode,
- });
+ const { result, detectedLanguage: sliceLang } = await runTranscriberOnSlice(
+ transcriber,
+ slice,
+ {
+ forceFullSequences,
+ timestampMode,
+ language: forcedLanguage,
+ },
+ );
+ if (detectedLanguage === null && sliceLang) detectedLanguage = sliceLang;
const tOff = offset / 16_000;
all.push(
...segmentsFromTranscriberChunks(
@@ -234,35 +277,37 @@ export async function runTranscription(
),
);
}
- return all;
+ return { segments: all, detectedLanguage };
} catch (e) {
console.warn("[captioning] Whisper pass failed:", e);
- return [];
+ return { segments: [], detectedLanguage: null };
}
};
const attemptModes: Array<"word" | "phrase"> = ["word", "phrase"];
for (const timestampMode of attemptModes) {
- let segments = await transcribeOne(false, true, timestampMode);
+ let pass = await transcribeOne(false, true, timestampMode);
+ let segments = pass.segments;
+ let detectedLanguage = pass.detectedLanguage;
if (segments.length === 0) {
- segments = await transcribeOne(false, false, timestampMode);
+ pass = await transcribeOne(false, false, timestampMode);
+ segments = pass.segments;
+ detectedLanguage = pass.detectedLanguage;
}
if (segments.length === 0 && trims.length > 0) {
- segments = dropSegmentsOverlappingTrimRegions(
- await transcribeOne(true, true, timestampMode),
- trims,
- );
+ pass = await transcribeOne(true, true, timestampMode);
+ segments = dropSegmentsOverlappingTrimRegions(pass.segments, trims);
+ detectedLanguage = pass.detectedLanguage;
if (segments.length === 0) {
- segments = dropSegmentsOverlappingTrimRegions(
- await transcribeOne(true, false, timestampMode),
- trims,
- );
+ pass = await transcribeOne(true, false, timestampMode);
+ segments = dropSegmentsOverlappingTrimRegions(pass.segments, trims);
+ detectedLanguage = pass.detectedLanguage;
}
}
if (segments.length > 0) {
- return { segments, granularity: timestampMode };
+ return { segments, granularity: timestampMode, detectedLanguage };
}
}
- return { segments: [], granularity: "phrase" };
+ return { segments: [], granularity: "phrase", detectedLanguage: null };
}
diff --git a/src/native/client.ts b/src/native/client.ts
index 39899001f..3fa9db5d0 100644
--- a/src/native/client.ts
+++ b/src/native/client.ts
@@ -15,6 +15,7 @@ import {
type AiEditionLlmProviderModelsResult,
type AiEditionLlmSnapshot,
type AiEditionProjectSummary,
+ type AxcutTimelineOperation,
type CursorCapabilities,
type CursorRecordingData,
type CursorTelemetryPoint,
@@ -352,5 +353,19 @@ export const nativeBridgeClient = {
action: "chat.compactNow",
payload: { projectId, sessionId },
}),
+ runTimelineOperation: (
+ projectId: string,
+ sessionId: string,
+ operation: AxcutTimelineOperation,
+ conversationMessage: string,
+ ) =>
+ requireNativeBridgeData<
+ | { success: true; result: { document: unknown; summary: string } }
+ | { success: false; error: string }
+ >({
+ domain: "aiEdition",
+ action: "timeline.run",
+ payload: { projectId, sessionId, operation, conversationMessage },
+ }),
},
};
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 915fca35a..9e5d699fb 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -227,6 +227,17 @@ export interface AiEditionChatBudget {
fillPercent: number;
}
+// ponytail: re-export of the timeline-operation discriminated union so the
+// IPC contract type and the renderer share one shape. Kept here (not in
+// src/lib/ai-edition/document/operations) so the IPC type bundle stays
+// self-contained.
+import type {
+ AppliedTimelineOperation,
+ AxcutTimelineOperation,
+} from "../lib/ai-edition/document/operations";
+
+export type { AppliedTimelineOperation, AxcutTimelineOperation };
+
export interface AiEditionChatCompactResult {
session: AiEditionChatSession;
summaryMessageId: string | null;
@@ -563,6 +574,17 @@ export type NativeBridgeRequest =
action: "chat.compactNow";
payload: { projectId: string; sessionId: string };
requestId?: string;
+ }
+ | {
+ domain: "aiEdition";
+ action: "timeline.run";
+ payload: {
+ projectId: string;
+ sessionId: string;
+ operation: AxcutTimelineOperation;
+ conversationMessage: string;
+ };
+ requestId?: string;
};
export type NativeBridgeEventName =