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(agent): donner au modèle la trajectoire du curseur, pas le verdict d'un détecteur

Etienne Lescotb1714a4d19b6
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 4a285394d..77d2cac1b 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -35,7 +35,6 @@ import {
import type {
CursorRecordingData,
CursorRecordingSample,
- NativeCursorAsset,
ProjectFileResult,
ProjectPathResult,
} from "../../src/native/contracts";
@@ -50,11 +49,17 @@ import {
runChat,
selectSession,
} from "../ai-edition/chat-service";
+import type { CursorTelemetryReader } from "../ai-edition/deep-agent/service";
import { DocumentService } from "../ai-edition/document-service";
import { LlmConfigStore } from "../ai-edition/llm-config-store";
import { mainLogBuffer } from "../diagnostics/main-log-buffer";
import { mainT } from "../i18n";
import { RECORDINGS_DIR } from "../main";
+import {
+ readCursorRecordingFile as readCursorRecordingFileFrom,
+ readCursorSidecar,
+ readCursorTelemetryFile as readCursorTelemetryFileFrom,
+} from "../media/cursorSidecar";
import { findMediaLinksByFingerprint, registerMediaLinks } from "../media/mediaLinksRegistry";
import { LinuxNativeCaptureSession } from "../native-bridge/capture/linuxNativeCaptureSession";
import { createCursorRecordingSession } from "../native-bridge/cursor/recording/factory";
@@ -474,7 +479,6 @@ function isTrustedProjectPath(filePath?: string | null) {
return normalizePath(filePath) === normalizePath(currentProjectPath);
}
-const CURSOR_TELEMETRY_VERSION = 2;
const CURSOR_SAMPLE_INTERVAL_MS = 33;
const MAX_CURSOR_SAMPLES = 60 * 60 * 30; // 1 hour @ 30Hz
@@ -550,171 +554,58 @@ async function writeLinuxRestoreToken(restoreToken?: string) {
}
}
-function normalizeCursorSample(sample: unknown): CursorRecordingSample | null {
- if (!sample || typeof sample !== "object") {
- return null;
- }
-
- const point = sample as Partial<CursorRecordingSample>;
- const interactionType =
- point.interactionType === "click" ||
- point.interactionType === "mouseup" ||
- point.interactionType === "move"
- ? point.interactionType
- : "move";
- return {
- timeMs:
- typeof point.timeMs === "number" && Number.isFinite(point.timeMs)
- ? Math.max(0, point.timeMs)
- : 0,
- cx: typeof point.cx === "number" && Number.isFinite(point.cx) ? point.cx : 0.5,
- cy: typeof point.cy === "number" && Number.isFinite(point.cy) ? point.cy : 0.5,
- assetId: typeof point.assetId === "string" ? point.assetId : null,
- visible: typeof point.visible === "boolean" ? point.visible : true,
- cursorType: typeof point.cursorType === "string" ? point.cursorType : null,
- interactionType,
- };
-}
-
-function normalizeCursorAsset(asset: unknown): NativeCursorAsset | null {
- if (!asset || typeof asset !== "object") {
- return null;
- }
+// ponytail: the sidecar readers used to live here, ~150 lines of parsing wedged
+// between the capture state machine and the asset-path helpers, reachable only
+// through IPC. They now live in `electron/media/cursorSidecar.ts` — Node-pure,
+// injectable, testable — because the agent needed to read the same file and
+// could not import an IPC handler. What is left here is the binding of
+// `RECORDINGS_DIR` (an `app.getPath` at main-module scope) to those readers.
+//
+// ponytail: a FUNCTION, not a captured object. `main.ts` imports this module and
+// this module imports `RECORDINGS_DIR` back from it, so at the moment this file
+// is evaluated that binding is still in its temporal dead zone — reading it here
+// threw `Cannot access 'RECORDINGS_DIR' before initialization` and the app died
+// before its first window. Every call site is already inside a handler, i.e.
+// long after both modules finished loading.
+const cursorSidecarOptions = () => ({ recordingsDir: RECORDINGS_DIR });
- const candidate = asset as Partial<NativeCursorAsset>;
- if (typeof candidate.id !== "string" || typeof candidate.imageDataUrl !== "string") {
- return null;
- }
+const readCursorRecordingFile = (targetVideoPath: string) =>
+ readCursorRecordingFileFrom(targetVideoPath, cursorSidecarOptions());
- return {
- id: candidate.id,
- platform:
- candidate.platform === "win32" ? "win32" : process.platform === "darwin" ? "darwin" : "linux",
- imageDataUrl: candidate.imageDataUrl,
- width:
- typeof candidate.width === "number" && Number.isFinite(candidate.width)
- ? Math.max(1, Math.round(candidate.width))
- : 1,
- height:
- typeof candidate.height === "number" && Number.isFinite(candidate.height)
- ? Math.max(1, Math.round(candidate.height))
- : 1,
- hotspotX:
- typeof candidate.hotspotX === "number" && Number.isFinite(candidate.hotspotX)
- ? Math.max(0, Math.round(candidate.hotspotX))
- : 0,
- hotspotY:
- typeof candidate.hotspotY === "number" && Number.isFinite(candidate.hotspotY)
- ? Math.max(0, Math.round(candidate.hotspotY))
- : 0,
- scaleFactor:
- typeof candidate.scaleFactor === "number" && Number.isFinite(candidate.scaleFactor)
- ? Math.max(0.1, candidate.scaleFactor)
- : undefined,
- cursorType: typeof candidate.cursorType === "string" ? candidate.cursorType : null,
- };
-}
+const readCursorTelemetryFile = (targetVideoPath: string) =>
+ readCursorTelemetryFileFrom(targetVideoPath, cursorSidecarOptions());
-async function readCursorRecordingFileAt(telemetryPath: string): Promise<CursorRecordingData> {
- try {
- const content = await fs.readFile(telemetryPath, "utf-8");
- const parsed = JSON.parse(content);
- const rawSamples = Array.isArray(parsed)
- ? parsed
- : Array.isArray(parsed?.samples)
- ? parsed.samples
- : [];
- const rawAssets = Array.isArray(parsed?.assets) ? parsed.assets : [];
-
- const samples = rawSamples
- .map((sample: unknown) => normalizeCursorSample(sample))
- .filter((sample: CursorRecordingSample | null): sample is CursorRecordingSample =>
- Boolean(sample),
- )
- .sort((a: CursorRecordingSample, b: CursorRecordingSample) => a.timeMs - b.timeMs);
-
- const assets = rawAssets
- .map((asset: unknown) => normalizeCursorAsset(asset))
- .filter((asset: NativeCursorAsset | null): asset is NativeCursorAsset => Boolean(asset));
-
- return {
- version:
- typeof parsed?.version === "number" && Number.isFinite(parsed.version) ? parsed.version : 1,
- provider: parsed?.provider === "native" ? "native" : "none",
- samples,
- assets,
- };
- } catch (error) {
- const nodeError = error as NodeJS.ErrnoException;
- if (nodeError.code === "ENOENT") {
+/**
+ * The agent's door onto cursor telemetry — the last mile of D-TELEM.
+ *
+ * ponytail: `resolveApprovedVideoPath` is not ceremony. The asset path comes
+ * from the DOCUMENT rather than from the model, but the document is a file on
+ * disk that the user (or a future import path) can put anything in, and the
+ * sidecar path is DERIVED from it. Reusing the same allow-list the video loaders
+ * use means a crafted `originalPath` cannot walk this into reading an arbitrary
+ * JSON file. A refused path yields "unavailable", not "no-sidecar": we did not
+ * look, and the model must not report otherwise.
+ */
+const agentCursorTelemetryReader: CursorTelemetryReader = {
+ probe: async ({ originalPath }) => {
+ const approved = resolveApprovedVideoPath(originalPath);
+ if (!approved) return false;
+ return (await readCursorSidecar(approved, cursorSidecarOptions())).found;
+ },
+ read: async ({ assetId, originalPath }) => {
+ const approved = resolveApprovedVideoPath(originalPath);
+ if (!approved) {
return {
- version: CURSOR_TELEMETRY_VERSION,
- provider: "none",
- samples: [],
- assets: [],
+ status: "unavailable",
+ assetId,
+ note: "The asset's file is outside the folders this app may read, so its cursor sidecar was not opened.",
};
}
-
- console.error("Failed to load cursor telemetry:", error);
- throw error;
- }
-}
-
-async function fileExists(filePath: string): Promise<boolean> {
- try {
- await fs.access(filePath, fsConstants.F_OK);
- return true;
- } catch {
- return false;
- }
-}
-
-// P4 — the sidecar convention (`<videoPath>.cursor.json`) only holds while the
-// video stays exactly where it was recorded. If it's missing (file moved,
-// renamed, or imported from elsewhere), fall back to the fingerprint registry
-// (electron/media/mediaLinksRegistry.ts) to re-find the same telemetry file.
-async function readCursorRecordingFile(targetVideoPath: string): Promise<CursorRecordingData> {
- const directPath = `${targetVideoPath}.cursor.json`;
- if (await fileExists(directPath)) {
- return readCursorRecordingFileAt(directPath);
- }
- try {
- const links = await findMediaLinksByFingerprint(RECORDINGS_DIR, targetVideoPath);
- if (links?.cursorTelemetryPath) {
- return readCursorRecordingFileAt(links.cursorTelemetryPath);
- }
- } catch (error) {
- console.warn("[media-links] fingerprint lookup failed for cursor telemetry:", error);
- }
- return {
- version: CURSOR_TELEMETRY_VERSION,
- provider: "none",
- samples: [],
- assets: [],
- };
-}
-
-async function readCursorTelemetryFile(targetVideoPath: string) {
- try {
- const recordingData = await readCursorRecordingFile(targetVideoPath);
- return {
- success: true,
- samples: recordingData.samples.map((sample) => ({
- timeMs: sample.timeMs,
- cx: sample.cx,
- cy: sample.cy,
- })),
- };
- } catch (error) {
- console.error("Failed to load cursor telemetry:", error);
- return {
- success: false,
- message: "Failed to load cursor telemetry",
- error: String(error),
- samples: [],
- };
- }
-}
+ const sidecar = await readCursorSidecar(approved, cursorSidecarOptions());
+ if (!sidecar.found) return { status: "no-sidecar", assetId };
+ return { status: "ok", assetId, samples: sidecar.data.samples };
+ },
+};
function resolveAssetBasePath() {
try {
@@ -3713,7 +3604,9 @@ export function registerIpcHandlers(
getAiEditionDocuments: () => aiEditionDocuments,
getAiEditionLlmConfig: () => aiEditionLlmConfig,
runAiEditionChat: (projectId, sessionId, message, document, sink) =>
- runChat(projectId, sessionId, message, aiEditionLlmConfig, document, sink),
+ runChat(projectId, sessionId, message, aiEditionLlmConfig, document, sink, {
+ cursor: agentCursorTelemetryReader,
+ }),
undoAiEditionToolBatch: (_projectId, _sessionId) => ({
success: false,
error: "Per-tool-batch undo retired in favor of per-message rewind.",
diff --git a/electron/media/cursorSidecar.test.ts b/electron/media/cursorSidecar.test.ts
new file mode 100644
index 000000000..400553819
--- /dev/null
+++ b/electron/media/cursorSidecar.test.ts
@@ -0,0 +1,152 @@
+// ponytail: these tests exist because the readers moved out of an IPC handler,
+// and the ONLY way to prove they still behave is to call them without one. That
+// was the whole obstacle: the parsing was fine, it just could not be reached (or
+// exercised) from anywhere but Electron.
+//
+// The case that matters most is the least dramatic one — a missing sidecar has
+// to come back `found: false` and NOT throw. An exception here becomes, three
+// layers up, an agent that cannot distinguish "this recording has no pointer
+// data" from "something broke", which is the exact conflation D-TELEM is about.
+
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ readCursorRecordingFileAt,
+ readCursorSidecar,
+ readCursorTelemetryFile,
+} from "./cursorSidecar";
+
+let dir: string;
+
+beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "cursor-sidecar-"));
+});
+
+afterEach(async () => {
+ await fs.rm(dir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
+async function writeSidecar(videoPath: string, payload: unknown): Promise<void> {
+ await fs.writeFile(`${videoPath}.cursor.json`, JSON.stringify(payload), "utf-8");
+}
+
+describe("readCursorSidecar", () => {
+ it("reads the sidecar next to the recording", async () => {
+ const video = path.join(dir, "rec.mp4");
+ await writeSidecar(video, {
+ version: 2,
+ provider: "native",
+ samples: [
+ { timeMs: 100, cx: 0.5, cy: 0.5, interactionType: "move" },
+ { timeMs: 0, cx: 0.1, cy: 0.2, interactionType: "click" },
+ ],
+ assets: [],
+ });
+
+ const result = await readCursorSidecar(video, {});
+
+ expect(result.found).toBe(true);
+ expect(result.source).toBe("sidecar");
+ expect(result.path).toBe(`${video}.cursor.json`);
+ // Sorted by time, and the interaction type survives — the digest counts
+ // clicks off it, and the renderer's own projection throws it away.
+ expect(result.data.samples.map((s) => s.timeMs)).toEqual([0, 100]);
+ expect(result.data.samples[0].interactionType).toBe("click");
+ });
+
+ it("reports found:false — not an error — when there is no sidecar", async () => {
+ const result = await readCursorSidecar(path.join(dir, "absent.mp4"), {});
+
+ expect(result.found).toBe(false);
+ expect(result.source).toBe("none");
+ expect(result.path).toBeNull();
+ expect(result.data.samples).toEqual([]);
+ expect(result.data.provider).toBe("none");
+ });
+
+ it("survives a malformed sidecar instead of throwing", async () => {
+ const video = path.join(dir, "broken.mp4");
+ await fs.writeFile(`${video}.cursor.json`, "{ this is not json", "utf-8");
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+
+ const result = await readCursorSidecar(video, {});
+
+ // A file we cannot parse is a file we could not read: `found:false`, so
+ // the caller reports "unavailable" rather than inventing an absence.
+ expect(result.found).toBe(false);
+ expect(result.data.samples).toEqual([]);
+ });
+
+ it("falls back to the fingerprint registry when the file has moved", async () => {
+ // The sidecar convention only holds while the video stays where it was
+ // recorded; P4's registry is the second chance, and it has to still be
+ // wired after the extraction.
+ const { registerMediaLinks } = await import("./mediaLinksRegistry");
+ const recordingsDir = path.join(dir, "recordings");
+ await fs.mkdir(recordingsDir, { recursive: true });
+
+ const original = path.join(recordingsDir, "original.mp4");
+ await fs.writeFile(original, "video-bytes-for-fingerprinting", "utf-8");
+ const telemetryPath = path.join(recordingsDir, "original.mp4.cursor.json");
+ await fs.writeFile(
+ telemetryPath,
+ JSON.stringify({
+ version: 2,
+ provider: "native",
+ samples: [{ timeMs: 5, cx: 0.4, cy: 0.4 }],
+ }),
+ "utf-8",
+ );
+ await registerMediaLinks(recordingsDir, original, { cursorTelemetryPath: telemetryPath });
+
+ // Same bytes, different name and no sidecar beside it.
+ const moved = path.join(dir, "moved.mp4");
+ await fs.copyFile(original, moved);
+
+ const result = await readCursorSidecar(moved, { recordingsDir });
+
+ expect(result.source).toBe("registry");
+ expect(result.data.samples).toHaveLength(1);
+ });
+
+ it("does not consult the registry when no recordingsDir is injected", async () => {
+ // The point of the extraction: `RECORDINGS_DIR` is an `app.getPath` call,
+ // so a reader without one must degrade rather than reach for Electron.
+ const result = await readCursorSidecar(path.join(dir, "nope.mp4"), {});
+ expect(result.source).toBe("none");
+ });
+});
+
+describe("readCursorRecordingFileAt", () => {
+ it("accepts a bare array of samples as well as the versioned envelope", async () => {
+ const file = path.join(dir, "bare.cursor.json");
+ await fs.writeFile(file, JSON.stringify([{ timeMs: 1, cx: 0.2, cy: 0.3 }]), "utf-8");
+
+ const data = await readCursorRecordingFileAt(file);
+
+ expect(data.samples).toHaveLength(1);
+ expect(data.samples[0].interactionType).toBe("move");
+ });
+});
+
+describe("readCursorTelemetryFile", () => {
+ it("drops interactionType — which is why the digest does not use it", async () => {
+ const video = path.join(dir, "clicks.mp4");
+ await writeSidecar(video, {
+ samples: [{ timeMs: 10, cx: 0.5, cy: 0.5, interactionType: "click" }],
+ });
+
+ const result = await readCursorTelemetryFile(video, {});
+
+ expect(result.success).toBe(true);
+ expect(result.samples).toEqual([{ timeMs: 10, cx: 0.5, cy: 0.5 }]);
+ // Locked deliberately: this projection is fine for the timeline overlay it
+ // feeds and useless for "where did the user act". Anything that wants
+ // clicks must go through `readCursorSidecar`, and this assertion is the
+ // reminder of why.
+ expect(Object.keys(result.samples[0])).not.toContain("interactionType");
+ });
+});
diff --git a/electron/media/cursorSidecar.ts b/electron/media/cursorSidecar.ts
new file mode 100644
index 000000000..2b6192f7b
--- /dev/null
+++ b/electron/media/cursorSidecar.ts
@@ -0,0 +1,255 @@
+// Reading the cursor-telemetry sidecar (`<videoPath>.cursor.json`), extracted
+// from `electron/ipc/handlers.ts` so it can be called by something other than an
+// IPC handler.
+//
+// ponytail: the extraction IS the fix, not a tidy-up. The readers existed and
+// worked — they were simply only ever wired to the renderer (loadCursorTelemetry
+// → CursorService → useCursorTelemetry → V4Timeline), so the ONE consumer that
+// most needed them, the agent, could not reach them. Asked what pointer data the
+// project holds, the model had no door to open and answered from the only thing
+// it could see. Nothing here changes what is parsed; it changes who may parse.
+//
+// Node-pure on purpose: no `electron` import, no `app.getPath`. `RECORDINGS_DIR`
+// comes from `electron/main.ts` (an `app.getPath` call at module scope), so
+// importing it here would drag the whole Electron runtime into anything that
+// wants to read a sidecar — the tests included. It is injected instead, exactly
+// as `mediaLinksRegistry` already injects its `baseDir`.
+
+import { constants as fsConstants } from "node:fs";
+import fs from "node:fs/promises";
+import type {
+ CursorProviderKind,
+ CursorRecordingData,
+ CursorRecordingSample,
+ NativeCursorAsset,
+} from "../../src/native/contracts";
+import { findMediaLinksByFingerprint } from "./mediaLinksRegistry";
+
+export const CURSOR_TELEMETRY_VERSION = 2;
+
+/** Where a sidecar was found, or why it was not. `"none"` means we LOOKED and
+ * there was nothing — distinct from never having looked, which this module
+ * cannot represent and its callers must not conflate. */
+export type CursorSidecarSource = "sidecar" | "registry" | "none";
+
+export interface CursorSidecarResult {
+ found: boolean;
+ source: CursorSidecarSource;
+ /** Absolute path of the file that was read; null when nothing was found. */
+ path: string | null;
+ data: CursorRecordingData;
+}
+
+function emptyRecording(): CursorRecordingData {
+ return {
+ version: CURSOR_TELEMETRY_VERSION,
+ provider: "none",
+ samples: [],
+ assets: [],
+ };
+}
+
+export function normalizeCursorSample(sample: unknown): CursorRecordingSample | null {
+ if (!sample || typeof sample !== "object") {
+ return null;
+ }
+
+ const point = sample as Partial<CursorRecordingSample>;
+ const interactionType =
+ point.interactionType === "click" ||
+ point.interactionType === "mouseup" ||
+ point.interactionType === "move"
+ ? point.interactionType
+ : "move";
+ return {
+ timeMs:
+ typeof point.timeMs === "number" && Number.isFinite(point.timeMs)
+ ? Math.max(0, point.timeMs)
+ : 0,
+ cx: typeof point.cx === "number" && Number.isFinite(point.cx) ? point.cx : 0.5,
+ cy: typeof point.cy === "number" && Number.isFinite(point.cy) ? point.cy : 0.5,
+ assetId: typeof point.assetId === "string" ? point.assetId : null,
+ visible: typeof point.visible === "boolean" ? point.visible : true,
+ cursorType: typeof point.cursorType === "string" ? point.cursorType : null,
+ interactionType,
+ };
+}
+
+export function normalizeCursorAsset(
+ asset: unknown,
+ platform: NodeJS.Platform = process.platform,
+): NativeCursorAsset | null {
+ if (!asset || typeof asset !== "object") {
+ return null;
+ }
+
+ const candidate = asset as Partial<NativeCursorAsset>;
+ if (typeof candidate.id !== "string" || typeof candidate.imageDataUrl !== "string") {
+ return null;
+ }
+
+ return {
+ id: candidate.id,
+ platform: candidate.platform === "win32" ? "win32" : platform === "darwin" ? "darwin" : "linux",
+ imageDataUrl: candidate.imageDataUrl,
+ width:
+ typeof candidate.width === "number" && Number.isFinite(candidate.width)
+ ? Math.max(1, Math.round(candidate.width))
+ : 1,
+ height:
+ typeof candidate.height === "number" && Number.isFinite(candidate.height)
+ ? Math.max(1, Math.round(candidate.height))
+ : 1,
+ hotspotX:
+ typeof candidate.hotspotX === "number" && Number.isFinite(candidate.hotspotX)
+ ? Math.max(0, Math.round(candidate.hotspotX))
+ : 0,
+ hotspotY:
+ typeof candidate.hotspotY === "number" && Number.isFinite(candidate.hotspotY)
+ ? Math.max(0, Math.round(candidate.hotspotY))
+ : 0,
+ scaleFactor:
+ typeof candidate.scaleFactor === "number" && Number.isFinite(candidate.scaleFactor)
+ ? Math.max(0.1, candidate.scaleFactor)
+ : undefined,
+ cursorType: typeof candidate.cursorType === "string" ? candidate.cursorType : null,
+ };
+}
+
+export async function readCursorRecordingFileAt(
+ telemetryPath: string,
+): Promise<CursorRecordingData> {
+ try {
+ const content = await fs.readFile(telemetryPath, "utf-8");
+ const parsed = JSON.parse(content);
+ const rawSamples = Array.isArray(parsed)
+ ? parsed
+ : Array.isArray(parsed?.samples)
+ ? parsed.samples
+ : [];
+ const rawAssets = Array.isArray(parsed?.assets) ? parsed.assets : [];
+
+ const samples = rawSamples
+ .map((sample: unknown) => normalizeCursorSample(sample))
+ .filter((sample: CursorRecordingSample | null): sample is CursorRecordingSample =>
+ Boolean(sample),
+ )
+ .sort((a: CursorRecordingSample, b: CursorRecordingSample) => a.timeMs - b.timeMs);
+
+ const assets = rawAssets
+ .map((asset: unknown) => normalizeCursorAsset(asset))
+ .filter((asset: NativeCursorAsset | null): asset is NativeCursorAsset => Boolean(asset));
+
+ return {
+ version:
+ typeof parsed?.version === "number" && Number.isFinite(parsed.version) ? parsed.version : 1,
+ provider: (parsed?.provider === "native" ? "native" : "none") as CursorProviderKind,
+ samples,
+ assets,
+ };
+ } catch (error) {
+ const nodeError = error as NodeJS.ErrnoException;
+ if (nodeError.code === "ENOENT") {
+ return emptyRecording();
+ }
+
+ console.error("Failed to load cursor telemetry:", error);
+ throw error;
+ }
+}
+
+async function fileExists(filePath: string): Promise<boolean> {
+ try {
+ await fs.access(filePath, fsConstants.F_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * P4 — the sidecar convention (`<videoPath>.cursor.json`) only holds while the
+ * video stays exactly where it was recorded. If it's missing (file moved,
+ * renamed, or imported from elsewhere), fall back to the fingerprint registry
+ * (electron/media/mediaLinksRegistry.ts) to re-find the same telemetry file.
+ *
+ * ponytail: a malformed sidecar reports `found: false` rather than throwing.
+ * The agent-facing caller has to be able to say "I looked and there is nothing
+ * usable" — turning that into an exception would make the tool loop's only
+ * honest answer indistinguishable from a crash, which is the same swap of
+ * blindness for fact this whole change exists to stop.
+ */
+export async function readCursorSidecar(
+ targetVideoPath: string,
+ options: { recordingsDir?: string },
+): Promise<CursorSidecarResult> {
+ const directPath = `${targetVideoPath}.cursor.json`;
+ if (await fileExists(directPath)) {
+ try {
+ return {
+ found: true,
+ source: "sidecar",
+ path: directPath,
+ data: await readCursorRecordingFileAt(directPath),
+ };
+ } catch {
+ return { found: false, source: "none", path: null, data: emptyRecording() };
+ }
+ }
+ if (options.recordingsDir) {
+ try {
+ const links = await findMediaLinksByFingerprint(options.recordingsDir, targetVideoPath);
+ if (links?.cursorTelemetryPath) {
+ return {
+ found: true,
+ source: "registry",
+ path: links.cursorTelemetryPath,
+ data: await readCursorRecordingFileAt(links.cursorTelemetryPath),
+ };
+ }
+ } catch (error) {
+ console.warn("[media-links] fingerprint lookup failed for cursor telemetry:", error);
+ }
+ }
+ return { found: false, source: "none", path: null, data: emptyRecording() };
+}
+
+/** The shape the renderer's `loadCursorRecordingData` has always returned: the
+ * recording data alone, with "not found" flattened into an empty payload. */
+export async function readCursorRecordingFile(
+ targetVideoPath: string,
+ options: { recordingsDir?: string },
+): Promise<CursorRecordingData> {
+ return (await readCursorSidecar(targetVideoPath, options)).data;
+}
+
+/** The renderer's `loadCursorTelemetry`: positions only, no interaction type.
+ *
+ * ponytail: this projection DROPS `interactionType`, which means it drops every
+ * click. That is fine for the timeline overlay it feeds and wrong for anything
+ * that wants to know where the user acted — the agent digest reads
+ * `readCursorSidecar` directly for exactly that reason. */
+export async function readCursorTelemetryFile(
+ targetVideoPath: string,
+ options: { recordingsDir?: string },
+) {
+ try {
+ const recordingData = await readCursorRecordingFile(targetVideoPath, options);
+ return {
+ success: true,
+ samples: recordingData.samples.map((sample) => ({
+ timeMs: sample.timeMs,
+ cx: sample.cx,
+ cy: sample.cy,
+ })),
+ };
+ } catch (error) {
+ console.error("Failed to load cursor telemetry:", error);
+ return {
+ success: false,
+ message: "Failed to load cursor telemetry",
+ error: String(error),
+ samples: [],
+ };
+ }
+}
diff --git a/src/lib/ai-edition/timeline/cursor-track.test.ts b/src/lib/ai-edition/timeline/cursor-track.test.ts
new file mode 100644
index 000000000..4286cd8ab
--- /dev/null
+++ b/src/lib/ai-edition/timeline/cursor-track.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutClip } from "../schema";
+import { buildCursorTrack, type CursorTrackSample } from "./cursor-track";
+
+const CLIPS: AxcutClip[] = [
+ {
+ id: "clip_1",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 60,
+ timelineStartSec: 0,
+ timelineEndSec: 60,
+ } as AxcutClip,
+];
+
+/** A steady 20 Hz sweep, the shape of a real capture. */
+function sweep(count: number, opts: { shape?: (i: number) => string } = {}): CursorTrackSample[] {
+ return Array.from({ length: count }, (_, i) => ({
+ timeMs: i * 50,
+ cx: 0.2 + i * 0.001,
+ cy: 0.5,
+ assetId: opts.shape ? opts.shape(i) : "arrow",
+ interactionType: "move",
+ }));
+}
+
+const build = (samples: CursorTrackSample[], hz?: number) =>
+ buildCursorTrack({ assetId: "asset_1", samples, durationSec: 60, clips: CLIPS, hz });
+
+describe("buildCursorTrack", () => {
+ it("downsamples without inventing a single point", () => {
+ const samples = sweep(400);
+ const track = build(samples, 5);
+
+ expect(track.sampleCount).toBe(400);
+ expect(track.pointCount).toBeLessThan(samples.length);
+ for (const point of track.points) {
+ const origin = samples.find((s) => Math.abs(s.timeMs / 1000 - point.atSec) < 0.01);
+ expect(origin).toBeTruthy();
+ expect(point.cx).toBeCloseTo(origin?.cx ?? -1, 3);
+ }
+ });
+
+ it("holds the requested resolution", () => {
+ const track = build(sweep(400), 5); // 400 samples @20Hz = 20s
+ // ~5 points per second, give or take the boundary point.
+ expect(track.pointCount).toBeGreaterThanOrEqual(Math.floor(20 * 5) - 2);
+ expect(track.pointCount).toBeLessThanOrEqual(Math.ceil(20 * 5) + 2);
+ expect(track.hz).toBe(5);
+ expect(track.truncated).toBe(false);
+ });
+
+ it("never drops a pointer-shape change, even between ticks", () => {
+ // One shape flip lasting a single 50 ms sample, far from any 5 Hz tick.
+ const samples = sweep(200, { shape: (i) => (i === 37 ? "hand" : "arrow") });
+ const track = build(samples, 5);
+
+ expect(track.shapeCount).toBe(2);
+ const flip = track.points.find((p) => Math.abs(p.atSec - 37 * 0.05) < 0.001);
+ expect(flip).toBeTruthy();
+ // Two distinct shapes reach the model as two distinct indices.
+ expect(new Set(track.points.map((p) => p.shape)).size).toBe(2);
+ });
+
+ it("keeps every non-move sample whatever the rate", () => {
+ const samples = sweep(200);
+ samples[13] = { ...samples[13], interactionType: "click" };
+ const track = build(samples, 2);
+
+ const click = track.points.find((p) => p.kind === "click");
+ expect(click).toBeTruthy();
+ expect(click?.atSec).toBeCloseTo(13 * 0.05, 2);
+ });
+
+ it("drops to a coarser rate rather than blowing the ceiling, and says so", () => {
+ // 40 minutes at 20 Hz: 5 Hz would be 12 000 points.
+ const track = buildCursorTrack({
+ assetId: "asset_1",
+ samples: sweep(48_000),
+ durationSec: 2400,
+ clips: CLIPS,
+ hz: 5,
+ maxPoints: 400,
+ });
+
+ expect(track.truncated).toBe(true);
+ expect(track.hz).toBeLessThan(5);
+ expect(track.pointCount).toBeLessThanOrEqual(420);
+ });
+
+ it("reports virtualSec as null where no clip carries the moment", () => {
+ const track = buildCursorTrack({
+ assetId: "asset_1",
+ samples: sweep(40),
+ durationSec: 60,
+ clips: [], // nothing placed on the timeline
+ });
+ expect(track.points.every((p) => p.virtualSec === null)).toBe(true);
+ });
+
+ it("marks the points a trim cuts out of playback", () => {
+ const track = buildCursorTrack({
+ assetId: "asset_1",
+ samples: sweep(200),
+ durationSec: 60,
+ clips: CLIPS,
+ trimRanges: [{ id: "t1", assetId: "asset_1", startSec: 2, endSec: 4 } as never],
+ hz: 5,
+ });
+
+ const inside = track.points.filter((p) => p.atSec >= 2 && p.atSec <= 4);
+ expect(inside.length).toBeGreaterThan(0);
+ expect(inside.every((p) => p.trimmed === true)).toBe(true);
+ expect(track.points.filter((p) => p.atSec < 2).every((p) => p.trimmed === undefined)).toBe(
+ true,
+ );
+ });
+
+ it("omits shape entirely when the recording used only one pointer", () => {
+ const track = build(sweep(100), 5);
+ expect(track.shapeCount).toBe(1);
+ expect(track.points.every((p) => p.shape === undefined)).toBe(true);
+ });
+});
diff --git a/src/lib/ai-edition/timeline/cursor-track.ts b/src/lib/ai-edition/timeline/cursor-track.ts
new file mode 100644
index 000000000..a7b2d3870
--- /dev/null
+++ b/src/lib/ai-edition/timeline/cursor-track.ts
@@ -0,0 +1,188 @@
+// The recorded cursor track the agent reads: where the pointer was, when, and
+// what shape it had. Pure — no fs, no IPC. The caller supplies the samples.
+//
+// ponytail: this is an OBSERVATION, not an interpretation, and the distinction
+// is the whole point of the module. Its predecessor handed the model a list of
+// "dwell moments" computed by the same stillness detector that drives the magic
+// wand. That reads as helpful and is not: it caps the model at the detector's
+// recall. Measured on a real 66s screencast, the detector reports 6 of 6
+// annotated interest zones but 8 false positives out of 16 — and it is blind by
+// construction to the one zone where the user traced slowly across an image
+// while narrating, because the cursor genuinely travelled 30% of the frame. A
+// model fed that digest can never zoom there, however good it is. So the wand
+// keeps its detector, the model gets the track, and the bench compares them.
+//
+// Downsampling is resolution, not interpretation: every kept point is a real
+// sample, nothing is summarised, and every pointer-shape change survives the
+// reduction because a shape change is an observed event, not a verdict about it.
+
+import type { AxcutClip, AxcutTrimRange } from "../schema";
+import { locateSourcePosition } from "./virtual-preview";
+
+/**
+ * Structurally compatible with `CursorRecordingSample` (src/native/contracts).
+ * Declared locally so this module — which the Electron main process imports over
+ * a relative path — never depends on the `@/` alias it cannot resolve.
+ */
+export interface CursorTrackSample {
+ timeMs: number;
+ cx: number;
+ cy: number;
+ /** The cursor BITMAP's id, not a media asset: the sidecar stores one entry per
+ * distinct pointer image (arrow, hand, text caret, resize…). A change means the
+ * pointer shape changed, which is why these points are never dropped. */
+ assetId?: string | null;
+ interactionType?: string | null;
+}
+
+export interface CursorTrackPoint {
+ /** SOURCE seconds of the asset — the recording's own clock. */
+ atSec: number;
+ /** The same instant on the edited timeline, the coordinate addZoom takes.
+ * Null when no clip currently carries it. */
+ virtualSec: number | null;
+ cx: number;
+ cy: number;
+ /** Small stable index per distinct pointer shape within THIS track. Absent when
+ * the recording carries no shape information. */
+ shape?: number;
+ /** Present only when the sample is not a plain move. */
+ kind?: string;
+ /** Present only when a trim cuts this instant out of playback. */
+ trimmed?: true;
+}
+
+export interface CursorTrack {
+ assetId: string;
+ /** Samples in the recording, before downsampling. */
+ sampleCount: number;
+ /** Points actually returned. */
+ pointCount: number;
+ /** Resolution of what is returned, in samples per second. */
+ hz: number;
+ coveredSec: number;
+ /** How many distinct pointer shapes the recording used. */
+ shapeCount: number;
+ /** True when maxPoints forced a coarser rate than `hz` would give. */
+ truncated: boolean;
+ timeBase: string;
+ points: CursorTrackPoint[];
+}
+
+/** 5 Hz keeps a slow traverse legible (a 5s sweep is 25 points) while a minute
+ * of capture stays around 300 points. Shape changes are added on top. */
+export const DEFAULT_TRACK_HZ = 5;
+/** A ceiling, not a target: long recordings drop to a coarser rate rather than
+ * returning a list nobody can read. */
+export const DEFAULT_MAX_TRACK_POINTS = 400;
+
+function round2(value: number): number {
+ return Math.round(value * 100) / 100;
+}
+
+function round3(value: number): number {
+ return Math.round(value * 1000) / 1000;
+}
+
+export interface CursorTrackOptions {
+ assetId: string;
+ samples: CursorTrackSample[];
+ /** Source duration of the asset, used to clamp stray timestamps. */
+ durationSec: number;
+ clips: AxcutClip[];
+ trimRanges?: AxcutTrimRange[];
+ hz?: number;
+ maxPoints?: number;
+}
+
+export function buildCursorTrack(options: CursorTrackOptions): CursorTrack {
+ const { assetId, samples, durationSec, clips } = options;
+ const trimRanges = options.trimRanges ?? [];
+ const maxPoints = options.maxPoints ?? DEFAULT_MAX_TRACK_POINTS;
+ const ceilingMs = Math.max(0, durationSec) * 1000 || Number.POSITIVE_INFINITY;
+
+ const ordered = samples
+ .filter((s) => Number.isFinite(s.timeMs) && Number.isFinite(s.cx) && Number.isFinite(s.cy))
+ .map((s) => ({ ...s, timeMs: Math.max(0, Math.min(s.timeMs, ceilingMs)) }))
+ .sort((a, b) => a.timeMs - b.timeMs);
+
+ // Shape ids are opaque hashes; the model has no use for 64 hex chars, only for
+ // "this is a different pointer than the previous one". Index them in order of
+ // first appearance so the numbering is stable and readable.
+ const shapeIndex = new Map<string, number>();
+ for (const s of ordered) {
+ if (typeof s.assetId === "string" && s.assetId && !shapeIndex.has(s.assetId)) {
+ shapeIndex.set(s.assetId, shapeIndex.size);
+ }
+ }
+
+ const coveredSec = ordered.length ? round2(ordered[ordered.length - 1].timeMs / 1000) : 0;
+
+ // The rate can only get coarser: asking for 5 Hz over a 40-minute capture would
+ // blow the ceiling, so the ceiling wins and `truncated` says so.
+ //
+ // ponytail: no floor on the derived rate. A `Math.max(1, …)` here reads as a
+ // sanity guard and silently defeats the ceiling — 2400 s of capture at a
+ // 400-point budget needs 0.17 Hz, and clamping that to 1 Hz returns 2400
+ // points, six times the budget. A point every six seconds is the honest
+ // answer for a recording that long; `truncated` is how the model learns it.
+ const wantedHz = options.hz ?? DEFAULT_TRACK_HZ;
+ const spanSec = coveredSec || 1;
+ const hz = Math.min(wantedHz, maxPoints / spanSec);
+ const truncated = hz < wantedHz;
+ const stepMs = 1000 / hz;
+
+ const keep: CursorTrackSample[] = [];
+ let nextTickMs = 0;
+ let lastShape: string | null | undefined;
+ for (const s of ordered) {
+ const shapeChanged = s.assetId !== lastShape && shapeIndex.size > 1;
+ const isTick = s.timeMs >= nextTickMs;
+ const notAMove = typeof s.interactionType === "string" && s.interactionType !== "move";
+ if (isTick || shapeChanged || notAMove) {
+ keep.push(s);
+ if (isTick) nextTickMs = s.timeMs + stepMs;
+ lastShape = s.assetId;
+ }
+ }
+
+ const points = keep.map((s) => {
+ const atSec = s.timeMs / 1000;
+ // `locateSourcePosition` is the existing source→virtual mapping, exact here
+ // because trims do NOT compact the document's virtual axis — a trim is a hole
+ // in playback, not a shortening of the ruler (see timeline/trim-mapping.ts).
+ const position = locateSourcePosition(clips, atSec, assetId);
+ const point: CursorTrackPoint = {
+ atSec: round2(atSec),
+ virtualSec: position ? round2(position.virtualTimeSec) : null,
+ cx: round3(s.cx),
+ cy: round3(s.cy),
+ };
+ const shape = typeof s.assetId === "string" ? shapeIndex.get(s.assetId) : undefined;
+ if (shape !== undefined && shapeIndex.size > 1) point.shape = shape;
+ if (typeof s.interactionType === "string" && s.interactionType !== "move") {
+ point.kind = s.interactionType;
+ }
+ if (trimRanges.some((t) => t.assetId === assetId && atSec >= t.startSec && atSec <= t.endSec)) {
+ point.trimmed = true;
+ }
+ return point;
+ });
+
+ return {
+ assetId,
+ sampleCount: samples.length,
+ pointCount: points.length,
+ hz: round2(hz),
+ coveredSec,
+ shapeCount: shapeIndex.size,
+ truncated,
+ timeBase:
+ "atSec is SOURCE time of the asset (the recording's own clock). virtualSec is the same " +
+ "instant on the edited timeline — that is the coordinate addZoom takes. A null virtualSec " +
+ "means no clip currently carries that moment; trimmed:true means a trim cuts it out of " +
+ "playback, so a zoom there would never be seen. `shape` is an index into the pointer " +
+ "bitmaps this recording used: equal values are the same pointer, a change is a change.",
+ points,
+ };
+}
diff --git a/src/lib/ai-edition/timeline/zoom-suggestions.ts b/src/lib/ai-edition/timeline/zoom-suggestions.ts
index e1dd2a428..0ef78d9cc 100644
--- a/src/lib/ai-edition/timeline/zoom-suggestions.ts
+++ b/src/lib/ai-edition/timeline/zoom-suggestions.ts
@@ -44,7 +44,21 @@ export function normalizeCursorTelemetry(
.map((sample) => normalizeTelemetrySample(sample, totalMs));
}
-export function detectZoomDwellCandidates(samples: CursorTelemetryPoint[]): ZoomDwellCandidate[] {
+/**
+ * `maxDwellDurationMs` exists for ONE caller and defaults to the magic wand's
+ * own ceiling so that caller is untouched.
+ *
+ * ponytail: the ceiling REJECTS a run outright rather than splitting it, so a
+ * cursor parked for eight seconds while the user reads the screen produces no
+ * candidate at all. That is a defensible auto-zoom policy — a nine-second zoom
+ * is not a zoom — and an indefensible reporting policy: the moments it drops are
+ * precisely the ones a human would name first if asked "where did the pointer
+ * sit?". The digest passes `Infinity`; nothing else does.
+ */
+export function detectZoomDwellCandidates(
+ samples: CursorTelemetryPoint[],
+ maxDwellDurationMs: number = MAX_DWELL_DURATION_MS,
+): ZoomDwellCandidate[] {
if (samples.length < 2) {
return [];
}
@@ -60,7 +74,7 @@ export function detectZoomDwellCandidates(samples: CursorTelemetryPoint[]): Zoom
const start = samples[startIndex];
const end = samples[endIndexExclusive - 1];
const runDuration = end.timeMs - start.timeMs;
- if (runDuration < MIN_DWELL_DURATION_MS || runDuration > MAX_DWELL_DURATION_MS) {
+ if (runDuration < MIN_DWELL_DURATION_MS || runDuration > maxDwellDurationMs) {
return;
}