Skip to content

Desktop app that records your on-screen work session and uses the GitHub Copilot SDK to reconstruct it as an intent + ordered steps, then builds a reusable Skill or Automation for Microsoft Autopilots like Scout, Microsoft Copilot Cowork, or Copilot Studio.

Add recording control overlay

Giorgio Ughini12a058e48c33
diff --git a/README.md b/README.md
index 0e276cd..1f6f6ad 100644
--- a/README.md
+++ b/README.md
@@ -16,10 +16,13 @@ can repeat.
1. **Record** — hit record (or `⌘⇧R` / `Ctrl+Shift+R` from anywhere) and do your task.
Skill Recorder captures the screen and your activity in the background.
-2. **Analyze** — on stop, it correlates the signals and a Copilot agent reconstructs
+2. **Control** — while recording, a movable always-on-top bar shows capture and
+ microphone state. Use it to toggle the microphone, finish, or discard the
+ recording; discard always asks for confirmation.
+3. **Analyze** — on stop, it correlates the signals and a Copilot agent reconstructs
*what you did*: one overall intent plus an ordered list of steps. You can review
and edit the result.
-3. **Create** — from an approved analysis, generalize the one run into a:
+4. **Create** — from an approved analysis, generalize the one run into a:
- **Skill** — a `SKILL.md` procedure an agent runs on demand, and
- **Automation** — the same procedure on a schedule/trigger.
@@ -38,9 +41,11 @@ activity" panel shows exactly what's collected:
- **Screen video** — recorded by Chromium; low-rate snapshots are captured alongside
it and retained only when the screen changes or a heartbeat is due.
- **Clipboard** — copy/paste content that ties steps together.
-- **Narration** *(optional)* — turn on **Narrate** to explain out loud; audio is
- saved immediately and can be transcribed **on-device** (Whisper via transformers.js).
- The first transcription uses an explicit, one-time ~250 MB model download.
+- **Narration** *(optional)* — turn on **Narrate** before capture or toggle the
+ microphone from the floating recording bar. Each microphone-on interval is
+ timestamped on the video timeline, saved locally, and can be transcribed
+ **on-device** (Whisper via transformers.js). The first transcription uses an
+ explicit, one-time ~250 MB model download.
## Requirements
diff --git a/common/audio.test.ts b/common/audio.test.ts
new file mode 100644
index 0000000..8091ec7
--- /dev/null
+++ b/common/audio.test.ts
@@ -0,0 +1,82 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ AUDIO_MANIFEST_VERSION,
+ alignAudioSegmentsToVideo,
+ isAudioManifestV2,
+ readAudioSources,
+ type AudioSegment,
+} from "./audio";
+
+test("segmented audio manifests are distinguished from legacy metadata", () => {
+ assert.equal(
+ isAudioManifestV2({
+ version: AUDIO_MANIFEST_VERSION,
+ segments: [],
+ }),
+ true,
+ );
+ assert.equal(
+ isAudioManifestV2({
+ file: "audio.webm",
+ startEpoch: 100,
+ stopEpoch: 200,
+ durationMs: 100,
+ bytes: 12,
+ }),
+ false,
+ );
+});
+
+test("audio segments retain signed offsets against the real video start", () => {
+ const segment: AudioSegment = {
+ file: "audio/segment-0001.webm",
+ startEpoch: 950.4,
+ stopEpoch: 1_250.6,
+ durationMs: 300.2,
+ sessionStartMs: 150,
+ sessionEndMs: 450,
+ videoStartMs: null,
+ videoEndMs: null,
+ bytes: 40,
+ };
+ const [aligned] = alignAudioSegmentsToVideo([segment], 1_000.2);
+ assert.equal(aligned.videoStartMs, -50);
+ assert.equal(aligned.videoEndMs, 250);
+ assert.equal(aligned.sessionStartMs, segment.sessionStartMs);
+});
+
+test("legacy and segmented metadata normalize to timestamped transcription sources", () => {
+ assert.deepEqual(
+ readAudioSources({
+ file: "audio.webm",
+ startEpoch: 1_100,
+ stopEpoch: 1_500,
+ durationMs: 400,
+ bytes: 12,
+ }),
+ [{ file: "audio.webm", startEpoch: 1_100, durationMs: 400 }],
+ );
+
+ const first = {
+ file: "audio/segment-0001.webm",
+ startEpoch: 1_200,
+ stopEpoch: 1_400,
+ durationMs: 200,
+ sessionStartMs: 200,
+ sessionEndMs: 400,
+ videoStartMs: 100,
+ videoEndMs: 300,
+ bytes: 20,
+ };
+ const second = { ...first, file: "audio/segment-0002.webm", startEpoch: 1_800 };
+ assert.deepEqual(
+ readAudioSources({ version: AUDIO_MANIFEST_VERSION, segments: [first, second] }),
+ [
+ { file: first.file, startEpoch: first.startEpoch, durationMs: first.durationMs },
+ { file: second.file, startEpoch: second.startEpoch, durationMs: second.durationMs },
+ ],
+ );
+ assert.throws(() => readAudioSources({ version: AUDIO_MANIFEST_VERSION, segments: [{}] }));
+});
diff --git a/common/audio.ts b/common/audio.ts
new file mode 100644
index 0000000..3edb0bc
--- /dev/null
+++ b/common/audio.ts
@@ -0,0 +1,84 @@
+/** Version written by new recordings that can toggle the microphone mid-session. */
+export const AUDIO_MANIFEST_VERSION = 2 as const;
+
+/** One continuous interval in which the microphone was actively capturing. */
+export interface AudioSegment {
+ file: string;
+ startEpoch: number;
+ stopEpoch: number;
+ durationMs: number;
+ /** Segment bounds relative to `session.json.startedAt`. */
+ sessionStartMs: number;
+ sessionEndMs: number;
+ /** Segment bounds relative to `video.json.startEpoch`, when video was available. */
+ videoStartMs: number | null;
+ videoEndMs: number | null;
+ bytes: number;
+}
+
+export interface AudioManifestV2 {
+ version: typeof AUDIO_MANIFEST_VERSION;
+ segments: AudioSegment[];
+}
+
+/** Metadata written by recordings created before live microphone toggling existed. */
+export interface LegacyAudioMetadata {
+ file: string;
+ startEpoch: number;
+ stopEpoch: number;
+ durationMs: number;
+ bytes: number;
+}
+
+export type AudioMetadata = AudioManifestV2 | LegacyAudioMetadata;
+export type AudioSource = Pick<LegacyAudioMetadata, "file" | "startEpoch" | "durationMs">;
+
+export function isAudioManifestV2(value: unknown): value is AudioManifestV2 {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<AudioManifestV2>;
+ return candidate.version === AUDIO_MANIFEST_VERSION && Array.isArray(candidate.segments);
+}
+
+/** Normalize legacy and segmented metadata into the files the transcriber reads. */
+export function readAudioSources(value: unknown): AudioSource[] {
+ const sources = isAudioManifestV2(value) ? value.segments : [value];
+ const normalized: AudioSource[] = [];
+ for (const source of sources) {
+ if (
+ !source ||
+ typeof source !== "object" ||
+ !("file" in source) ||
+ typeof source.file !== "string" ||
+ !source.file ||
+ !("startEpoch" in source) ||
+ typeof source.startEpoch !== "number" ||
+ !Number.isFinite(source.startEpoch) ||
+ !("durationMs" in source) ||
+ typeof source.durationMs !== "number" ||
+ !Number.isFinite(source.durationMs) ||
+ source.durationMs < 0
+ ) {
+ throw new Error("Narration metadata contains an invalid audio segment.");
+ }
+ normalized.push({
+ file: source.file,
+ startEpoch: source.startEpoch,
+ durationMs: source.durationMs,
+ });
+ }
+ return normalized;
+}
+
+/** Add video-relative offsets without altering the session-relative timeline. */
+export function alignAudioSegmentsToVideo(
+ segments: readonly AudioSegment[],
+ videoStartEpoch: number | null,
+): AudioSegment[] {
+ return segments.map((segment) => ({
+ ...segment,
+ videoStartMs:
+ videoStartEpoch == null ? null : Math.round(segment.startEpoch - videoStartEpoch),
+ videoEndMs:
+ videoStartEpoch == null ? null : Math.round(segment.stopEpoch - videoStartEpoch),
+ }));
+}
diff --git a/common/ipc.ts b/common/ipc.ts
index 42ce81e..fca66e5 100644
--- a/common/ipc.ts
+++ b/common/ipc.ts
@@ -68,6 +68,15 @@ export interface RecorderStatus {
sessionId: string | null;
startedAt: number | null;
eventCount: number;
+ transition: "none" | "starting" | "stopping" | "discarding";
+ microphone: {
+ state: "off" | "starting" | "on" | "stopping" | "error";
+ error: string | null;
+ };
+ lastFinish: {
+ sessionId: string;
+ outcome: "saved" | "discarded";
+ } | null;
/** Set after a recording stops; drives the "Analyze" affordance. */
lastSession: LastSession | null;
}
@@ -190,6 +199,18 @@ export interface StopResult {
error?: string;
}
+export interface DiscardResult {
+ ok: boolean;
+ sessionId?: string;
+ error?: string;
+}
+
+export interface MicrophoneResult {
+ ok: boolean;
+ state?: RecorderStatus["microphone"]["state"];
+ error?: string;
+}
+
export interface MarkerResult {
ok: boolean;
error?: string;
@@ -244,6 +265,8 @@ export interface DoctorReport {
export const IPC = {
start: "recorder:start",
stop: "recorder:stop",
+ discard: "recorder:discard",
+ microphone: "recorder:microphone",
status: "recorder:status",
marker: "recorder:marker",
doctor: "doctor:check",
@@ -274,12 +297,15 @@ export const IPC = {
automationProgress: "automation:progress",
openLibrary: "ui:open-library",
closeLibrary: "ui:close-library",
+ recordingControlsExpanded: "ui:recording-controls-expanded",
} as const;
/** Shape exposed on `window.skillRecorder` by the preload bridge. */
export interface SkillRecorderApi {
start(options?: StartOptions): Promise<StartResult>;
stop(): Promise<StopResult>;
+ discard(): Promise<DiscardResult>;
+ setMicrophoneEnabled(enabled: boolean): Promise<MicrophoneResult>;
status(): Promise<RecorderStatus>;
marker(note: string): Promise<MarkerResult>;
doctor(): Promise<DoctorReport>;
@@ -341,4 +367,6 @@ export interface SkillRecorderApi {
openLibrary(): Promise<void>;
/** Close the Sessions library window from within it. */
closeLibrary(): Promise<void>;
+ /** Resize the recording-controls window while its confirmation is visible. */
+ setRecordingControlsExpanded(expanded: boolean): Promise<void>;
}
diff --git a/docs/windows-capture.md b/docs/windows-capture.md
index 4f37a04..0633cb2 100644
--- a/docs/windows-capture.md
+++ b/docs/windows-capture.md
@@ -59,14 +59,22 @@ Run a real recording on Windows and verify each source lands in the session's
preview and hash.
5. **Video.** Confirm `video.webm`, `video-frames.json`, snapshots under
`video-frames/`, and retained images under `frames/`.
-6. **Voice narration.** Turn on the **Narrate** switch before starting, then speak
- a sentence or two during the recording. After Stop, confirm `audio.webm` +
- `audio.json` are written. If the model is not installed, use **Download &
+6. **Voice narration.** Turn on the **Narrate** switch before starting or use the
+ microphone control in the floating recording bar. Toggle it off and on around
+ two spoken sentences. After Stop, confirm `audio.json` contains a version-2
+ segment manifest and the referenced `audio/segment-*.webm` files exist. Their
+ session/video offsets should preserve the silent gap while the microphone was
+ off. If the model is not installed, use **Download &
transcribe** in Sessions (or the actionable HUD readiness row) to approve the
one-time ~250 MB Whisper download. Confirm `narration.json` then contains your
words with `atMs` offsets. Later runs are offline. On Windows the mic grant is
requested by the OS on first use.
-7. **Stop.** The recording should show up in the library as `recorded`, and
+7. **Recording controls.** Confirm the floating bar stays above the active app,
+ can be dragged without making its buttons unclickable, and does not appear in
+ captured frames where Windows capture protection is supported. Canceling the
+ discard confirmation must continue the same recording; confirming it must
+ leave no saved session.
+8. **Stop.** The recording should show up in the library as `recorded`, and
analysis should produce a coherent intent + ordered steps.
If a source produces nothing, check the doctor row for it first, then the main
diff --git a/electron/audio/capture-preload.cjs b/electron/audio/capture-preload.cjs
index 17cd8f4..23b91ed 100644
--- a/electron/audio/capture-preload.cjs
+++ b/electron/audio/capture-preload.cjs
@@ -10,6 +10,9 @@ const { readFile } = require("node:fs/promises");
let recorder = null;
/** @type {MediaStream | null} */
let stream = null;
+/** @type {string | null} */
+let captureId = null;
+let requestedStopEpoch = 0;
// Serialises chunk sends so the final blob (dispatched just before `stop`) is
// fully forwarded before we tell main the recording stopped — otherwise the last
// cluster is lost and the webm ends prematurely.
@@ -23,14 +26,27 @@ function cleanup() {
}
stream = null;
recorder = null;
+ captureId = null;
+ requestedStopEpoch = 0;
}
ipcRenderer.on("audio:start", async (_event, opts) => {
- const { bitsPerSecond } = opts || {};
+ const { id, bitsPerSecond } = opts || {};
+ if (typeof id !== "string" || !id) {
+ ipcRenderer.send("audio:error", "", "Invalid microphone segment id.");
+ return;
+ }
+ if (recorder && recorder.state !== "inactive") {
+ ipcRenderer.send("audio:error", id, "Microphone capture is already active.");
+ return;
+ }
try {
+ captureId = id;
+ requestedStopEpoch = 0;
+ sendChain = Promise.resolve();
// A plain microphone request. Echo cancellation / noise suppression keep the
// narration clean for the transcriber without us touching the samples.
- stream = await navigator.mediaDevices.getUserMedia({
+ const nextStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
@@ -38,6 +54,18 @@ ipcRenderer.on("audio:start", async (_event, opts) => {
},
video: false,
});
+ if (captureId !== id) {
+ for (const track of nextStream.getTracks()) track.stop();
+ return;
+ }
+ stream = nextStream;
+ for (const track of stream.getAudioTracks()) {
+ track.addEventListener("ended", () => {
+ if (!requestedStopEpoch) {
+ ipcRenderer.send("audio:error", id, "The microphone disconnected.");
+ }
+ }, { once: true });
+ }
const mimeType = MediaRecorder.isTypeSupported("audio/webm;codecs=opus")
? "audio/webm;codecs=opus"
@@ -46,46 +74,62 @@ ipcRenderer.on("audio:start", async (_event, opts) => {
recorder.ondataavailable = (e) => {
if (!e.data || e.data.size === 0) return;
+ const segmentId = id;
// Preserve order and completion; Uint8Array survives IPC structured clone.
sendChain = sendChain.then(async () => {
const buf = await e.data.arrayBuffer();
- ipcRenderer.send("audio:chunk", new Uint8Array(buf));
+ ipcRenderer.send("audio:chunk", segmentId, new Uint8Array(buf));
});
};
- recorder.onstart = () => ipcRenderer.send("audio:started", Date.now());
+ recorder.onstart = () => {
+ ipcRenderer.send("audio:started", id, epochNow());
+ };
recorder.onstop = () => {
// Wait for every queued chunk (including the final one) to be sent.
sendChain.then(() => {
+ const stopEpoch = requestedStopEpoch || epochNow();
cleanup();
- ipcRenderer.send("audio:stopped");
+ ipcRenderer.send("audio:stopped", id, stopEpoch);
});
};
recorder.onerror = (e) => {
- ipcRenderer.send("audio:error", String((e && e.error) || e));
+ ipcRenderer.send("audio:error", id, String((e && e.error) || e));
};
// Emit a chunk every second so long sessions stream to disk incrementally.
recorder.start(1000);
} catch (err) {
- cleanup();
- ipcRenderer.send("audio:error", err instanceof Error ? err.message : String(err));
+ if (captureId === id) cleanup();
+ ipcRenderer.send("audio:error", id, err instanceof Error ? err.message : String(err));
+ ipcRenderer.send("audio:stopped", id, epochNow());
}
});
-ipcRenderer.on("audio:stop", () => {
+ipcRenderer.on("audio:stop", (_event, opts) => {
+ const id = opts && opts.id;
+ if (typeof id !== "string" || id !== captureId) return;
try {
if (recorder && recorder.state !== "inactive") {
+ requestedStopEpoch = epochNow();
recorder.requestData();
recorder.stop();
} else {
- ipcRenderer.send("audio:stopped");
+ const stopEpoch = requestedStopEpoch || epochNow();
+ cleanup();
+ ipcRenderer.send("audio:stopped", id, stopEpoch);
}
} catch (err) {
- ipcRenderer.send("audio:error", err instanceof Error ? err.message : String(err));
- ipcRenderer.send("audio:stopped");
+ const stopEpoch = requestedStopEpoch || epochNow();
+ cleanup();
+ ipcRenderer.send("audio:error", id, err instanceof Error ? err.message : String(err));
+ ipcRenderer.send("audio:stopped", id, stopEpoch);
}
});
+function epochNow() {
+ return performance.timeOrigin + performance.now();
+}
+
ipcRenderer.on("audio:decode", async (_event, opts) => {
const { id, audioPath, sampleRate, chunkSamples } = opts || {};
let context = null;
diff --git a/electron/audio/recorder.ts b/electron/audio/recorder.ts
index caa3590..fa19bf9 100644
--- a/electron/audio/recorder.ts
+++ b/electron/audio/recorder.ts
@@ -1,162 +1,335 @@
import { createWriteStream, existsSync, type WriteStream } from "node:fs";
-import { unlink, writeFile } from "node:fs/promises";
+import { mkdir, rename, rm, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { BrowserWindow, ipcMain, type IpcMainEvent } from "electron";
+import {
+ AUDIO_MANIFEST_VERSION,
+ alignAudioSegmentsToVideo,
+ type AudioManifestV2,
+ type AudioSegment,
+ type LegacyAudioMetadata,
+} from "../../common/audio";
import { createLogger } from "../logger";
+import type { AudioCaptureEnded } from "../recorder/controller";
const log = createLogger("Narration/audio");
const dirname = path.dirname(fileURLToPath(import.meta.url));
-/** Result metadata written alongside the webm as `audio.json`. */
-export interface AudioResult {
- file: string;
- /** Wall-clock epoch (ms) when MediaRecorder actually started — the anchor that
- * maps a transcript segment's offset back onto the session clock. */
- startEpoch: number;
- stopEpoch: number;
- durationMs: number;
- bytes: number;
-}
+/** Kept as a source-compatible name for readers of legacy `audio.json` files. */
+export type AudioResult = LegacyAudioMetadata;
// Opus at 24 kbps mono is transparent for speech and keeps narration files tiny.
const BITS_PER_SECOND = 24_000;
-const STOP_TIMEOUT_MS = 4000;
+const START_TIMEOUT_MS = 10_000;
+const STOP_TIMEOUT_MS = 4_000;
+const AUDIO_DIR = "audio";
+
+interface PendingSegment {
+ id: string;
+ file: string;
+ relativeFile: string;
+ stream: WriteStream;
+ bytes: number;
+ startEpoch: number | null;
+ stopEpoch: number | null;
+ failed: boolean;
+ error: string | null;
+ ended: boolean;
+ stopRequested: boolean;
+ startedResolve: (() => void) | null;
+ startedReject: ((error: Error) => void) | null;
+ stoppedResolve: (() => void) | null;
+}
/**
- * Captures the user's microphone narration for a session, mirroring the video
- * sidecar: the heavy lifting (getUserMedia + MediaRecorder) happens in a hidden
- * renderer window (electron/audio/capture.html + capture-preload.cjs); this class
- * orchestrates it from the main process and writes the webm + `audio.json` to the
- * session folder. Capture is strictly opt-in (started only when the user enabled
- * narration for the session) and best-effort: if there is no microphone or the
- * permission is denied, it logs and the session proceeds without narration.
+ * Owns microphone capture for one recording session. The hidden renderer stays
+ * alive for the session, but each microphone-on interval gets a fresh
+ * MediaStream, MediaRecorder, and WebM file so off-periods remain real timeline
+ * gaps and the OS microphone device is released between intervals.
*/
export class AudioRecorder {
private win: BrowserWindow | null = null;
- private stream: WriteStream | null = null;
- private file = "";
private dir = "";
- private bytes = 0;
- private startEpoch: number | null = null;
- private stoppedResolve: (() => void) | null = null;
- private failed = false;
-
- private readonly onChunk = (e: IpcMainEvent, chunk: Uint8Array) => {
- if (e.sender !== this.win?.webContents || !this.stream) return;
- const buf = Buffer.from(chunk);
- this.bytes += buf.byteLength;
- this.stream.write(buf);
+ private sessionStartedAt = 0;
+ private sequence = 0;
+ private active: PendingSegment | null = null;
+ private disableTask: Promise<AudioSegment | null> | null = null;
+ private readonly segments: AudioSegment[] = [];
+
+ constructor(
+ private readonly onCaptureEnded: (event: AudioCaptureEnded) => void = () => undefined,
+ ) {}
+
+ private readonly onChunk = (event: IpcMainEvent, id: string, chunk: Uint8Array) => {
+ const active = this.ownedSegment(event, id);
+ if (!active || !(chunk instanceof Uint8Array) || chunk.byteLength === 0) return;
+ const buffer = Buffer.from(chunk);
+ active.bytes += buffer.byteLength;
+ active.stream.write(buffer);
};
- private readonly onStarted = (e: IpcMainEvent, epoch: number) => {
- if (e.sender !== this.win?.webContents) return;
- this.startEpoch = epoch;
- log.info("narration started; anchor epoch", epoch);
+ private readonly onStarted = (event: IpcMainEvent, id: string, epoch: number) => {
+ const active = this.ownedSegment(event, id);
+ if (!active || !Number.isFinite(epoch)) return;
+ active.startEpoch = epoch;
+ active.startedResolve?.();
+ active.startedResolve = null;
+ active.startedReject = null;
+ log.info("microphone segment started; anchor epoch", epoch);
};
- private readonly onStopped = (e: IpcMainEvent) => {
- if (e.sender !== this.win?.webContents) return;
- this.stoppedResolve?.();
+ private readonly onStopped = (event: IpcMainEvent, id: string, epoch: number) => {
+ const active = this.ownedSegment(event, id);
+ if (!active) return;
+ const unexpected = !active.stopRequested && active.startEpoch != null;
+ active.stopEpoch = Number.isFinite(epoch) ? epoch : Date.now();
+ active.ended = true;
+ active.stoppedResolve?.();
+ active.stoppedResolve = null;
+ if (unexpected) {
+ this.finishUnexpected(active, "The microphone stopped unexpectedly.", false);
+ }
};
- private readonly onError = (e: IpcMainEvent, message: string) => {
- if (e.sender !== this.win?.webContents) return;
- this.failed = true;
- log.warn("microphone unavailable:", message);
- // Unblock a pending stop() if the recorder never really started.
- this.stoppedResolve?.();
+ private readonly onError = (event: IpcMainEvent, id: string, error: string) => {
+ const active = this.ownedSegment(event, id);
+ if (!active) return;
+ const reason = error || "Microphone capture failed.";
+ active.error = reason;
+ log.warn("microphone unavailable:", reason);
+ if (active.startEpoch == null) {
+ active.failed = true;
+ active.startedReject?.(new Error(reason));
+ active.startedResolve = null;
+ active.startedReject = null;
+ return;
+ }
+ this.finishUnexpected(active, reason, true);
};
- /** Begin capturing into `<sessionDir>/audio.webm`. Never throws. */
- async start(sessionDir: string): Promise<void> {
+ /** Prepare the session's hidden audio utility window without touching the mic. */
+ async start(sessionDir: string, sessionStartedAt: number): Promise<void> {
+ if (this.win) throw new Error("Microphone recorder is already initialized.");
+ this.dir = sessionDir;
+ this.sessionStartedAt = sessionStartedAt;
+ this.sequence = 0;
+ this.segments.length = 0;
+ await mkdir(path.join(this.dir, AUDIO_DIR), { recursive: true });
+
+ ipcMain.on("audio:chunk", this.onChunk);
+ ipcMain.on("audio:started", this.onStarted);
+ ipcMain.on("audio:stopped", this.onStopped);
+ ipcMain.on("audio:error", this.onError);
+
+ this.win = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ preload: path.join(dirname, "audio", "capture-preload.cjs"),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: false,
+ backgroundThrottling: false,
+ },
+ });
+ this.win.once("closed", () => {
+ const active = this.active;
+ if (!active || active.ended) return;
+ active.failed = true;
+ active.error = "Microphone capture window closed unexpectedly.";
+ active.startedReject?.(new Error(active.error));
+ active.ended = true;
+ active.stoppedResolve?.();
+ this.finishUnexpected(active, active.error, true);
+ });
+
try {
- this.dir = sessionDir;
- this.file = path.join(sessionDir, "audio.webm");
- this.bytes = 0;
- this.startEpoch = null;
- this.failed = false;
- this.stream = createWriteStream(this.file);
-
- ipcMain.on("audio:chunk", this.onChunk);
- ipcMain.on("audio:started", this.onStarted);
- ipcMain.on("audio:stopped", this.onStopped);
- ipcMain.on("audio:error", this.onError);
-
- this.win = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: path.join(dirname, "audio", "capture-preload.cjs"),
- contextIsolation: true,
- nodeIntegration: false,
- sandbox: false,
- },
- });
await this.win.loadFile(path.join(dirname, "audio", "capture.html"));
-
- this.win.webContents.send("audio:start", { bitsPerSecond: BITS_PER_SECOND });
- log.info("narration capture requested ->", this.file);
- } catch (err) {
- log.warn("failed to start narration:", err instanceof Error ? err.message : err);
+ } catch (error) {
await this.teardown();
+ throw error;
}
}
- /** Stop capturing and return the result, or null if no usable audio was produced. */
- async stop(): Promise<AudioResult | null> {
- if (!this.win || !this.stream) {
- await this.teardown();
- return null;
+ /** Request microphone access and begin a new independently timestamped segment. */
+ async enable(): Promise<void> {
+ if (!this.win || this.win.isDestroyed()) {
+ throw new Error("Microphone capture is not available for this recording.");
}
+ if (this.active) throw new Error("Microphone capture is already active.");
- const stopped = new Promise<void>((resolve) => {
- this.stoppedResolve = resolve;
- this.win?.webContents.send("audio:stop");
+ const number = ++this.sequence;
+ const id = `segment-${String(number).padStart(4, "0")}`;
+ const name = `${id}.webm`;
+ const file = path.join(this.dir, AUDIO_DIR, name);
+ const stream = createWriteStream(file);
+ const active: PendingSegment = {
+ id,
+ file,
+ relativeFile: path.posix.join(AUDIO_DIR, name),
+ stream,
+ bytes: 0,
+ startEpoch: null,
+ stopEpoch: null,
+ failed: false,
+ error: null,
+ ended: false,
+ stopRequested: false,
+ startedResolve: null,
+ startedReject: null,
+ stoppedResolve: null,
+ };
+ stream.once("error", (error) => {
+ active.failed = true;
+ active.error = error.message;
+ active.startedReject?.(error);
+ log.warn("microphone segment write failed:", error.message);
+ if (active.startEpoch != null) this.finishUnexpected(active, error.message, true);
});
- await Promise.race([stopped, delay(STOP_TIMEOUT_MS)]);
+ this.active = active;
- const stopEpoch = Date.now();
- await this.closeStream();
+ const started = new Promise<void>((resolve, reject) => {
+ active.startedResolve = resolve;
+ active.startedReject = reject;
+ });
+ this.win.webContents.send("audio:start", {
+ id,
+ bitsPerSecond: BITS_PER_SECOND,
+ });
- const bytes = this.bytes;
- const startEpoch = this.startEpoch;
- const file = this.file;
- const failed = this.failed;
- await this.teardown();
+ try {
+ await withTimeout(started, START_TIMEOUT_MS, "Timed out starting microphone capture.");
+ } catch (error) {
+ await this.disable();
+ throw error;
+ }
+ }
+
+ /** Flush and close the active segment, releasing the microphone device. */
+ async disable(): Promise<AudioSegment | null> {
+ if (this.disableTask) return this.disableTask;
+ const task = this.disableInternal();
+ this.disableTask = task;
+ try {
+ return await task;
+ } finally {
+ if (this.disableTask === task) this.disableTask = null;
+ }
+ }
+
+ private async disableInternal(): Promise<AudioSegment | null> {
+ const active = this.active;
+ if (!active) return null;
- if (failed || bytes === 0 || startEpoch == null) {
- // Remove a useless/empty file so the session folder stays clean.
- if (existsSync(file)) await unlink(file).catch(() => undefined);
- log.warn("no usable narration captured");
+ active.stopRequested = true;
+ if (!active.ended) {
+ const stopped = new Promise<void>((resolve) => {
+ active.stoppedResolve = resolve;
+ });
+ if (this.win && !this.win.isDestroyed()) {
+ this.win.webContents.send("audio:stop", { id: active.id });
+ } else {
+ active.failed = true;
+ active.error ??= "Microphone capture window is unavailable.";
+ active.ended = true;
+ active.stoppedResolve?.();
+ }
+
+ try {
+ await withTimeout(stopped, STOP_TIMEOUT_MS, "Timed out stopping microphone capture.");
+ } catch (error) {
+ log.warn(error instanceof Error ? error.message : String(error));
+ active.stopEpoch ??= Date.now();
+ if (this.win && !this.win.isDestroyed()) this.win.destroy();
+ }
+ }
+
+ await closeStream(active.stream);
+ this.active = null;
+
+ if (
+ active.failed ||
+ active.bytes === 0 ||
+ active.startEpoch == null ||
+ active.stopEpoch == null
+ ) {
+ if (existsSync(active.file)) await unlink(active.file).catch(() => undefined);
+ if (active.error) log.warn("discarded unusable microphone segment:", active.error);
return null;
}
- const result: AudioResult = {
- file: path.basename(file),
+ const startEpoch = active.startEpoch;
+ const stopEpoch = Math.max(startEpoch, active.stopEpoch);
+ const segment: AudioSegment = {
+ file: active.relativeFile,
startEpoch,
stopEpoch,
durationMs: stopEpoch - startEpoch,
- bytes,
+ sessionStartMs: Math.round(startEpoch - this.sessionStartedAt),
+ sessionEndMs: Math.round(stopEpoch - this.sessionStartedAt),
+ videoStartMs: null,
+ videoEndMs: null,
+ bytes: active.bytes,
};
- await writeFile(
- path.join(this.dirFor(file), "audio.json"),
- JSON.stringify(result, null, 2),
- ).catch((err) => log.warn("failed to write audio.json:", err instanceof Error ? err.message : err));
- log.info(`narration saved: ${result.file} (${(bytes / 1000).toFixed(0)} KB, ${result.durationMs} ms)`);
- return result;
+ this.segments.push(segment);
+ log.info(
+ `microphone segment saved: ${segment.file} (${(segment.bytes / 1000).toFixed(0)} KB, ` +
+ `${segment.durationMs} ms)`,
+ );
+ return segment;
+ }
+
+ /** Finish the session and atomically persist its segment manifest. */
+ async finish(videoStartEpoch: number | null): Promise<AudioManifestV2 | null> {
+ if (this.active) await this.disable();
+
+ const segments = alignAudioSegmentsToVideo(this.segments, videoStartEpoch);
+ const manifest: AudioManifestV2 | null =
+ segments.length > 0 ? { version: AUDIO_MANIFEST_VERSION, segments } : null;
+
+ try {
+ if (manifest) {
+ const file = path.join(this.dir, "audio.json");
+ const temp = `${file}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ await writeFile(temp, JSON.stringify(manifest, null, 2));
+ await rename(temp, file);
+ } finally {
+ await rm(temp, { force: true });
+ }
+ } else {
+ await rm(path.join(this.dir, "audio.json"), { force: true });
+ await rm(path.join(this.dir, AUDIO_DIR), { recursive: true, force: true });
+ }
+ return manifest;
+ } finally {
+ await this.teardown();
+ }
}
- private dirFor(file: string): string {
- return this.dir || path.dirname(file);
+ private ownedSegment(event: IpcMainEvent, id: string): PendingSegment | null {
+ if (event.sender !== this.win?.webContents || this.active?.id !== id) return null;
+ return this.active;
}
- private closeStream(): Promise<void> {
- return new Promise((resolve) => {
- if (!this.stream) return resolve();
- this.stream.end(() => resolve());
- });
+ private finishUnexpected(
+ active: PendingSegment,
+ error: string,
+ discardSegment: boolean,
+ ): void {
+ if (this.active !== active || active.stopRequested) return;
+ if (discardSegment) active.failed = true;
+ active.stopRequested = true;
+ void this.disable()
+ .catch((disableError) => {
+ log.warn(
+ "failed to release microphone after capture ended:",
+ disableError instanceof Error ? disableError.message : disableError,
+ );
+ })
+ .finally(() => this.onCaptureEnded({ error }));
}
private async teardown(): Promise<void> {
@@ -164,14 +337,38 @@ export class AudioRecorder {
ipcMain.removeListener("audio:started", this.onStarted);
ipcMain.removeListener("audio:stopped", this.onStopped);
ipcMain.removeListener("audio:error", this.onError);
- this.stoppedResolve = null;
- await this.closeStream();
- this.stream = null;
+ if (this.active) {
+ await closeStream(this.active.stream);
+ this.active = null;
+ }
if (this.win && !this.win.isDestroyed()) this.win.destroy();
this.win = null;
}
}
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
+function closeStream(stream: WriteStream): Promise<void> {
+ return new Promise((resolve) => {
+ if (stream.closed || stream.destroyed) {
+ resolve();
+ return;
+ }
+ let settled = false;
+ const done = () => {
+ if (settled) return;
+ settled = true;
+ resolve();
+ };
+ stream.once("close", done);
+ stream.end(done);
+ });
+}
+
+function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
+ let timeout: NodeJS.Timeout | undefined;
+ const expired = new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
+ });
+ return Promise.race([promise, expired]).finally(() => {
+ if (timeout) clearTimeout(timeout);
+ });
}
diff --git a/electron/describer/instructions.ts b/electron/describer/instructions.ts
index 5809237..0b1a9cb 100644
--- a/electron/describer/instructions.ts
+++ b/electron/describer/instructions.ts
@@ -74,8 +74,9 @@ All times are **\`atMs\` = milliseconds since the recording started**.
part of their task. In particular, the FIRST step (focusing Skill Recorder to press Start,
usually at \`atMs\` ≈ 0) and the LAST step (returning to Skill Recorder to press Stop) are
recorder bracketing, not user actions — do NOT emit them as steps. Also drop any mid-session
- flick back to Skill Recorder just to add a marker. The real task starts with the first
- non-recorder app the user works in.
+ focus on Skill Recorder's floating controls to toggle the microphone, cancel a discard, or
+ operate another recording control. The real task starts with the first non-recorder app the
+ user works in.
- \`UserNotificationCenter\` / OS permission dialogs (e.g. "requesting to record the
screen") are the recorder's own consent prompts — NOT user actions. Skip them.
- URL tracking params (\`gclid\`, \`gad_source\`, \`utm_*\`) and ad-redirect hops carry no
diff --git a/electron/ipc.ts b/electron/ipc.ts
index 04cb6ec..fb629ee 100644
--- a/electron/ipc.ts
+++ b/electron/ipc.ts
@@ -39,6 +39,10 @@ export function registerIpc(
): void {
ipcMain.handle(IPC.start, (_event, options?: StartOptions) => recorder.start(options));
ipcMain.handle(IPC.stop, () => recorder.stop());
+ ipcMain.handle(IPC.discard, () => recorder.discard());
+ ipcMain.handle(IPC.microphone, (_event, enabled: boolean) =>
+ recorder.setMicrophoneEnabled(enabled),
+ );
ipcMain.handle(IPC.status, () => recorder.status());
ipcMain.handle(IPC.marker, (_event, note: string) => recorder.marker(note));
ipcMain.handle(IPC.doctor, () => runDoctor());
diff --git a/electron/main.ts b/electron/main.ts
index 3df826e..7f0ca18 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -1,7 +1,7 @@
-import { app, globalShortcut, ipcMain, BrowserWindow } from "electron";
+import { app, globalShortcut, ipcMain, BrowserWindow, screen } from "electron";
import { FULL_CAPTURE } from "../common/config";
-import { IPC } from "../common/ipc";
+import { IPC, type RecorderStatus } from "../common/ipc";
import { createCollectors } from "./collectors";
import { Describer } from "./describer/describer";
import { processSession } from "./pipeline";
@@ -9,18 +9,30 @@ import { registerIpc } from "./ipc";
import { createLogger } from "./logger";
import { NarrationManager } from "./narration/manager";
import { RecorderController } from "./recorder/controller";
+import { deleteSession } from "./sessions";
import { SkillBuilder } from "./skillbuilder/builder";
import { AutomationBuilder } from "./automationbuilder/builder";
import { createTray } from "./tray";
import { AudioRecorder } from "./audio/recorder";
import { VideoRecorder } from "./video/recorder";
-import { createLibraryWindow, createRecorderWindow, redockLibrary } from "./window";
+import {
+ clampRecordingControlsWindow,
+ createLibraryWindow,
+ createRecorderWindow,
+ createRecordingControlsWindow,
+ redockLibrary,
+ setRecordingControlsExpanded,
+} from "./window";
const log = createLogger("Main");
let recorderWindow: BrowserWindow | null = null;
let libraryWindow: BrowserWindow | null = null;
+let recordingControlsWindow: BrowserWindow | null = null;
let recorderHome: Electron.Rectangle | null = null;
+let controlsExpanded = false;
+let quitReady = false;
+let quitTask: Promise<void> | null = null;
const narration = new NarrationManager((status) =>
broadcast(IPC.narrationStatusChanged, status),
);
@@ -28,12 +40,15 @@ const recorder = new RecorderController({
resolveConfig: () => ({ ...FULL_CAPTURE }),
buildCollectors: createCollectors,
createVideoRecorder: () => new VideoRecorder(),
- createAudioRecorder: () => new AudioRecorder(),
+ createAudioRecorder: (onCaptureEnded) => new AudioRecorder(onCaptureEnded),
+ deleteSession,
postProcess: async (dir) => {
await processSession(dir);
- void narration.transcribeIfCached(dir).catch((err) =>
- log.warn("Cached narration processing failed:", err),
- );
+ try {
+ await narration.transcribeIfCached(dir);
+ } catch (err) {
+ log.warn("Cached narration processing failed:", err);
+ }
},
});
@@ -52,6 +67,7 @@ const automationBuilder = new AutomationBuilder((progress) =>
/** Open, focus, and re-dock the Sessions library window (creating it lazily). */
function openLibrary(): void {
+ if (recorder.state === "recording") return;
if (!recorderWindow || recorderWindow.isDestroyed()) return;
if (libraryWindow && !libraryWindow.isDestroyed()) {
redockLibrary(recorderWindow, libraryWindow);
@@ -75,6 +91,78 @@ function openLibrary(): void {
});
}
+function ensureRecordingControlsWindow(): BrowserWindow {
+ if (recordingControlsWindow && !recordingControlsWindow.isDestroyed()) {
+ return recordingControlsWindow;
+ }
+ controlsExpanded = false;
+ recordingControlsWindow = createRecordingControlsWindow();
+ recordingControlsWindow.on("closed", () => {
+ recordingControlsWindow = null;
+ controlsExpanded = false;
+ });
+ return recordingControlsWindow;
+}
+
+function showRecordingControls(): void {
+ const win = ensureRecordingControlsWindow();
+ clampRecordingControlsWindow(win);
+ if (!win.isVisible()) win.showInactive();
+ win.moveTop();
+}
+
+function showRecorderWindow(): void {
+ if (!recorderWindow || recorderWindow.isDestroyed()) {
+ recorderWindow = createRecorderWindow();
+ }
+ recorderWindow.show();
+ recorderWindow.focus();
+}
+
+/** Keep the full HUD and compact overlay mutually exclusive. */
+function syncRecordingWindows(status: RecorderStatus): void {
+ if (status.state === "recording") {
+ if (libraryWindow && !libraryWindow.isDestroyed()) libraryWindow.close();
+ if (recorderWindow && !recorderWindow.isDestroyed()) recorderWindow.hide();
+ showRecordingControls();
+ return;
+ }
+ // A start emits an idle/starting status before the session folder exists.
+ if (status.transition === "starting") return;
+
+ if (recordingControlsWindow && !recordingControlsWindow.isDestroyed()) {
+ const controls = recordingControlsWindow;
+ if (controlsExpanded) {
+ setRecordingControlsExpanded(controls, false);
+ controlsExpanded = false;
+ }
+ controls.hide();
+ // Let an overlay-originated stop/discard IPC reply reach its renderer before
+ // tearing that renderer down. A recording restarted in the same turn reuses it.
+ setTimeout(() => {
+ if (
+ recorder.state === "idle" &&
+ recordingControlsWindow === controls &&
+ !controls.isDestroyed()
+ ) {
+ controls.destroy();
+ recordingControlsWindow = null;
+ }
+ }, 500);
+ }
+ if (recorderWindow && !recorderWindow.isDestroyed()) {
+ const wasHidden = !recorderWindow.isVisible();
+ recorderWindow.show();
+ if (wasHidden) recorderWindow.focus();
+ }
+}
+
+function clampControlsToDisplay(): void {
+ if (recordingControlsWindow && !recordingControlsWindow.isDestroyed()) {
+ clampRecordingControlsWindow(recordingControlsWindow);
+ }
+}
+
app.whenReady().then(() => {
narration.initialize();
registerIpc(recorder, describer, builder, automationBuilder, narration);
@@ -84,31 +172,52 @@ app.whenReady().then(() => {
ipcMain.handle(IPC.closeLibrary, () => {
if (libraryWindow && !libraryWindow.isDestroyed()) libraryWindow.close();
});
+ ipcMain.handle(IPC.recordingControlsExpanded, (event, expanded: boolean) => {
+ const win = recordingControlsWindow;
+ if (
+ !win ||
+ win.isDestroyed() ||
+ event.sender !== win.webContents ||
+ typeof expanded !== "boolean" ||
+ recorder.state !== "recording"
+ ) {
+ return;
+ }
+ controlsExpanded = expanded;
+ setRecordingControlsExpanded(win, expanded);
+ });
- recorder.onStatusChanged((status) => broadcast(IPC.statusChanged, status));
-
+ recorder.onStatusChanged((status) => {
+ broadcast(IPC.statusChanged, status);
+ syncRecordingWindows(status);
+ });
recorderWindow = createRecorderWindow();
+ screen.on("display-added", clampControlsToDisplay);
+ screen.on("display-removed", clampControlsToDisplay);
+ screen.on("display-metrics-changed", clampControlsToDisplay);
+
try {
- createTray(recorder, recorderWindow);
+ createTray(recorder, showRecorderWindow, showRecordingControls);
} catch (err) {
log.warn("Tray unavailable:", err);
}
const toggle = () => {
- void (recorder.state === "recording" ? recorder.stop() : recorder.start());
+ const status = recorder.status();
+ if (status.transition !== "none") return;
+ void (status.state === "recording" ? recorder.stop() : recorder.start());
};
if (!globalShortcut.register("CommandOrControl+Shift+R", toggle)) {
log.warn("Global shortcut registration failed");
}
app.on("activate", () => {
- if (!recorderWindow || recorderWindow.isDestroyed()) {
- recorderWindow = createRecorderWindow();
- } else {
- recorderWindow.show();
- recorderWindow.focus();
+ if (recorder.state === "recording") {
+ showRecordingControls();
+ return;
}
+ showRecorderWindow();
});
});
@@ -116,11 +225,29 @@ app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
+app.on("before-quit", (event) => {
+ if (quitReady) return;
+ event.preventDefault();
+ if (quitTask) return;
+ recorder.beginShutdown();
+ quitTask = (async () => {
+ // stop() is serialized behind any start/mic/discard operation already in
+ // flight, and is a harmless "Not recording" result when the app is idle.
+ await recorder.stop();
+ await recorder.whenProcessed();
+ })()
+ .catch((error) => {
+ log.warn("graceful shutdown failed:", error);
+ })
+ .finally(() => {
+ quitReady = true;
+ app.quit();
+ });
+});
+
app.on("will-quit", () => {
globalShortcut.unregisterAll();
- if (recorder.state === "recording") void recorder.stop();
void describer.dispose();
void builder.dispose();
void automationBuilder.dispose();
});
-
diff --git a/electron/narration/manager.ts b/electron/narration/manager.ts
index fec52fb..d352a48 100644
--- a/electron/narration/manager.ts
+++ b/electron/narration/manager.ts
@@ -2,13 +2,16 @@ import { existsSync, readFileSync } from "node:fs";
import { readdir, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
+import {
+ readAudioSources,
+ type AudioSource,
+} from "../../common/audio";
import type {
NarrationActionResult,
NarrationStatus,
} from "../../common/ipc";
import { NARRATION_FILE, type NarrationTranscript } from "../../common/narration";
import type { SessionMeta } from "../../common/types";
-import type { AudioResult } from "../audio/recorder";
import { createLogger } from "../logger";
import { isValidSessionId, sessionDir } from "../recorder/session-store";
import { transcribeNarration } from "./transcribe";
@@ -41,6 +44,15 @@ function readTranscript(file: string): NarrationTranscript | null {
}
}
+function resolveSessionFile(dir: string, relativeFile: string): string {
+ const resolved = path.resolve(dir, relativeFile);
+ const prefix = `${path.resolve(dir)}${path.sep}`;
+ if (!resolved.startsWith(prefix)) {
+ throw new Error("Narration metadata points outside the recording folder.");
+ }
+ return resolved;
+}
+
async function writeTranscript(file: string, transcript: NarrationTranscript): Promise<void> {
const temp = `${file}.tmp.${process.pid}.${Date.now()}`;
try {
@@ -192,16 +204,29 @@ export class NarrationManager {
if (!existsSync(audioJson)) return { ok: false, error: "This recording has no saved narration." };
let meta: SessionMeta;
- let audio: AudioResult;
+ let audioSources: AudioSource[];
try {
meta = readJson<SessionMeta>(path.join(dir, "session.json"));
- audio = readJson<AudioResult>(audioJson);
+ audioSources = readAudioSources(readJson<unknown>(audioJson));
} catch (err) {
return { ok: false, error: `Could not read narration metadata: ${message(err)}` };
}
- const audioPath = path.join(dir, audio.file);
- if (!existsSync(audioPath)) return { ok: false, error: "The saved narration audio is missing." };
+ if (audioSources.length === 0) {
+ return { ok: false, error: "This recording has no saved narration." };
+ }
+ let sourceFiles: Array<AudioSource & { audioPath: string }>;
+ try {
+ sourceFiles = audioSources.map((source) => ({
+ ...source,
+ audioPath: resolveSessionFile(dir, source.file),
+ }));
+ } catch (err) {
+ return { ok: false, error: message(err) };
+ }
+ if (sourceFiles.some((source) => !existsSync(source.audioPath))) {
+ return { ok: false, error: "One or more saved narration segments are missing." };
+ }
if (!allowDownload && !isNarrationModelCached()) {
this.update({
@@ -224,12 +249,18 @@ export class NarrationManager {
activeSessionId: sessionId,
error: null,
});
- const transcript: NarrationTranscript = await transcribeNarration(
- audioPath,
- audio.startEpoch - meta.startedAt,
- audio.durationMs,
- pipe,
- );
+ const transcript: NarrationTranscript = { model: "", segments: [] };
+ for (const source of sourceFiles) {
+ const segmentTranscript = await transcribeNarration(
+ source.audioPath,
+ source.startEpoch - meta.startedAt,
+ source.durationMs,
+ pipe,
+ );
+ transcript.model ||= segmentTranscript.model;
+ transcript.segments.push(...segmentTranscript.segments);
+ }
+ transcript.segments.sort((a, b) => a.atMs - b.atMs);
await writeTranscript(narrationFile, transcript);
log.info(`transcribed ${sessionId}: ${transcript.segments.length} segment(s)`);
this.update({
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 72ac046..6db5f3d 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -5,6 +5,8 @@ const { contextBridge, ipcRenderer } = require("electron");
const IPC = {
start: "recorder:start",
stop: "recorder:stop",
+ discard: "recorder:discard",
+ microphone: "recorder:microphone",
status: "recorder:status",
marker: "recorder:marker",
doctor: "doctor:check",
@@ -35,11 +37,14 @@ const IPC = {
automationProgress: "automation:progress",
openLibrary: "ui:open-library",
closeLibrary: "ui:close-library",
+ recordingControlsExpanded: "ui:recording-controls-expanded",
};
contextBridge.exposeInMainWorld("skillRecorder", {
start: (options) => ipcRenderer.invoke(IPC.start, options),
stop: () => ipcRenderer.invoke(IPC.stop),
+ discard: () => ipcRenderer.invoke(IPC.discard),
+ setMicrophoneEnabled: (enabled) => ipcRenderer.invoke(IPC.microphone, enabled),
status: () => ipcRenderer.invoke(IPC.status),
marker: (note) => ipcRenderer.invoke(IPC.marker, note),
doctor: () => ipcRenderer.invoke(IPC.doctor),
@@ -90,4 +95,6 @@ contextBridge.exposeInMainWorld("skillRecorder", {
},
openLibrary: () => ipcRenderer.invoke(IPC.openLibrary),
closeLibrary: () => ipcRenderer.invoke(IPC.closeLibrary),
+ setRecordingControlsExpanded: (expanded) =>
+ ipcRenderer.invoke(IPC.recordingControlsExpanded, expanded),
});
diff --git a/electron/recorder/controller.test.ts b/electron/recorder/controller.test.ts
new file mode 100644
index 0000000..f5fb32e
--- /dev/null
+++ b/electron/recorder/controller.test.ts
@@ -0,0 +1,309 @@
+import assert from "node:assert/strict";
+import { access, mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { FULL_CAPTURE } from "../../common/config";
+import { RecorderController, type SessionAudioRecorder } from "./controller";
+
+class FakeAudioRecorder implements SessionAudioRecorder {
+ readonly calls: string[] = [];
+ finishVideoStartEpoch: number | null | undefined;
+ failEnable = false;
+
+ async start(): Promise<void> {
+ this.calls.push("start");
+ }
+
+ async enable(): Promise<void> {
+ this.calls.push("enable");
+ if (this.failEnable) throw new Error("Microphone permission denied.");
+ }
+
+ async disable(): Promise<void> {
+ this.calls.push("disable");
+ }
+
+ async finish(videoStartEpoch: number | null): Promise<void> {
+ this.calls.push("finish");
+ this.finishVideoStartEpoch = videoStartEpoch;
+ }
+}
+
+test("microphone toggles are serialized and finalized on save", async () => {
+ await withSessionsRoot(async () => {
+ const audio = new FakeAudioRecorder();
+ let processed = 0;
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE }),
+ buildCollectors: () => [],
+ createVideoRecorder: () => ({
+ start: async () => undefined,
+ stop: async () => ({ startEpoch: 1_234 }),
+ }),
+ createAudioRecorder: () => audio,
+ deleteSession: async () => undefined,
+ postProcess: async () => {
+ processed++;
+ },
+ });
+
+ const started = await controller.start();
+ assert.equal(started.ok, true);
+ assert.equal(controller.status().microphone.state, "off");
+
+ assert.equal((await controller.setMicrophoneEnabled(true)).ok, true);
+ assert.equal(controller.status().microphone.state, "on");
+ assert.equal((await controller.setMicrophoneEnabled(false)).ok, true);
+ assert.equal((await controller.setMicrophoneEnabled(true)).ok, true);
+
+ const stopped = await controller.stop();
+ assert.equal(stopped.ok, true);
+ assert.equal(controller.status().state, "idle");
+ assert.equal(controller.status().transition, "none");
+ assert.equal(controller.status().lastSession?.id, started.sessionId);
+ assert.deepEqual(controller.status().lastFinish, {
+ sessionId: started.sessionId,
+ outcome: "saved",
+ });
+ assert.deepEqual(audio.calls, [
+ "start",
+ "enable",
+ "disable",
+ "enable",
+ "disable",
+ "finish",
+ ]);
+ assert.equal(audio.finishVideoStartEpoch, 1_234);
+
+ await controller.whenProcessed();
+ assert.equal(processed, 1);
+ });
+});
+
+test("discard removes the active session and skips post-processing", async () => {
+ await withSessionsRoot(async (root) => {
+ const audio = new FakeAudioRecorder();
+ let processed = 0;
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ createAudioRecorder: () => audio,
+ deleteSession: async (id) => rm(path.join(root, id), { recursive: true }),
+ postProcess: async () => {
+ processed++;
+ },
+ });
+
+ const started = await controller.start({ narration: true });
+ assert.equal(started.ok, true);
+ const id = started.sessionId;
+ assert.ok(id);
+ assert.equal(controller.status().microphone.state, "on");
+
+ const discarded = await controller.discard();
+ assert.equal(discarded.ok, true);
+ assert.equal(discarded.sessionId, id);
+ assert.equal(controller.status().state, "idle");
+ assert.equal(controller.status().lastSession, null);
+ assert.deepEqual(controller.status().lastFinish, {
+ sessionId: id,
+ outcome: "discarded",
+ });
+ assert.equal(processed, 0);
+ await assert.rejects(access(path.join(root, id)), { code: "ENOENT" });
+ assert.deepEqual(audio.calls, ["start", "enable", "disable", "finish"]);
+ });
+});
+
+test("failed discard retains and post-processes the finalized session", async () => {
+ await withSessionsRoot(async () => {
+ let processed = 0;
+ let releaseProcessing: () => void = () => undefined;
+ const processingGate = new Promise<void>((resolve) => {
+ releaseProcessing = resolve;
+ });
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ deleteSession: async () => {
+ throw new Error("Access denied.");
+ },
+ postProcess: async () => {
+ processed++;
+ await processingGate;
+ },
+ });
+
+ const started = await controller.start();
+ assert.equal(started.ok, true);
+
+ const discarded = await controller.discard();
+ assert.equal(discarded.ok, false);
+ assert.match(discarded.error ?? "", /could not be discarded.*access denied/i);
+ assert.deepEqual(controller.status().lastFinish, {
+ sessionId: started.sessionId,
+ outcome: "saved",
+ });
+ assert.deepEqual(controller.status().lastSession, {
+ id: started.sessionId,
+ processed: false,
+ });
+
+ assert.equal(processed, 1);
+ const drained = controller.whenProcessed();
+ releaseProcessing();
+ await drained;
+ assert.deepEqual(controller.status().lastSession, {
+ id: started.sessionId,
+ processed: true,
+ });
+ });
+});
+
+test("unexpected microphone termination updates live status without ending video capture", async () => {
+ await withSessionsRoot(async () => {
+ const audio = new FakeAudioRecorder();
+ let notifyEnded: (event: { error: string | null }) => void = () => {
+ throw new Error("Microphone callback was not registered.");
+ };
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ createAudioRecorder: (notify) => {
+ notifyEnded = notify;
+ return audio;
+ },
+ deleteSession: async () => undefined,
+ });
+
+ assert.equal((await controller.start()).ok, true);
+ assert.equal((await controller.setMicrophoneEnabled(true)).ok, true);
+ notifyEnded({ error: "The microphone disconnected." });
+ assert.equal(controller.status().state, "recording");
+ assert.deepEqual(controller.status().microphone, {
+ state: "error",
+ error: "The microphone disconnected.",
+ });
+ assert.equal((await controller.stop()).ok, true);
+ });
+});
+
+test("shutdown rejects queued and future recording starts", async () => {
+ await withSessionsRoot(async () => {
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ deleteSession: async () => undefined,
+ });
+
+ controller.beginShutdown();
+ const result = await controller.start();
+ assert.equal(result.ok, false);
+ assert.match(result.error ?? "", /shutting down/i);
+ assert.equal(controller.status().state, "idle");
+ });
+});
+
+test("discard outcome is not confused with an earlier saved session", async () => {
+ await withSessionsRoot(async (root) => {
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ deleteSession: async (id) => rm(path.join(root, id), { recursive: true }),
+ });
+
+ const saved = await controller.start();
+ assert.equal(saved.ok, true);
+ assert.equal((await controller.stop()).ok, true);
+
+ const discarded = await controller.start();
+ assert.equal(discarded.ok, true);
+ assert.equal((await controller.discard()).ok, true);
+ assert.equal(controller.status().lastSession?.id, saved.sessionId);
+ assert.deepEqual(controller.status().lastFinish, {
+ sessionId: discarded.sessionId,
+ outcome: "discarded",
+ });
+ });
+});
+
+test("microphone failure is surfaced without stopping screen capture", async () => {
+ await withSessionsRoot(async () => {
+ const audio = new FakeAudioRecorder();
+ audio.failEnable = true;
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ createAudioRecorder: () => audio,
+ deleteSession: async () => undefined,
+ });
+
+ assert.equal((await controller.start()).ok, true);
+ const result = await controller.setMicrophoneEnabled(true);
+ assert.equal(result.ok, false);
+ assert.match(result.error ?? "", /permission denied/i);
+ assert.equal(controller.status().state, "recording");
+ assert.equal(controller.status().microphone.state, "error");
+ assert.equal((await controller.stop()).ok, true);
+ });
+});
+
+test("stop waits behind an in-flight microphone enable", async () => {
+ await withSessionsRoot(async () => {
+ let releaseEnable: () => void = () => undefined;
+ const enableGate = new Promise<void>((resolve) => {
+ releaseEnable = resolve;
+ });
+ const calls: string[] = [];
+ const audio: SessionAudioRecorder = {
+ start: async () => {
+ calls.push("start");
+ },
+ enable: async () => {
+ calls.push("enable:start");
+ await enableGate;
+ calls.push("enable:end");
+ },
+ disable: async () => {
+ calls.push("disable");
+ },
+ finish: async () => {
+ calls.push("finish");
+ },
+ };
+ const controller = new RecorderController({
+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),
+ buildCollectors: () => [],
+ createAudioRecorder: () => audio,
+ deleteSession: async () => undefined,
+ });
+
+ assert.equal((await controller.start()).ok, true);
+ const enabling = controller.setMicrophoneEnabled(true);
+ const stopping = controller.stop();
+ await Promise.resolve();
+ assert.deepEqual(calls, ["start", "enable:start"]);
+
+ releaseEnable();
+ assert.equal((await enabling).ok, true);
+ assert.equal((await stopping).ok, true);
+ assert.deepEqual(calls, ["start", "enable:start", "enable:end", "disable", "finish"]);
+ });
+});
+
+async function withSessionsRoot(
+ run: (root: string) => Promise<void>,
+): Promise<void> {
+ const root = await mkdtemp(path.join(tmpdir(), "skill-recorder-controller-"));
+ const previousRoot = process.env.SKILL_RECORDER_SESSIONS_DIR;
+ process.env.SKILL_RECORDER_SESSIONS_DIR = root;
+ try {
+ await run(root);
+ } finally {
+ if (previousRoot === undefined) delete process.env.SKILL_RECORDER_SESSIONS_DIR;
+ else process.env.SKILL_RECORDER_SESSIONS_DIR = previousRoot;
+ await rm(root, { recursive: true, force: true });
+ }
+}
diff --git a/electron/recorder/controller.ts b/electron/recorder/controller.ts
index b5434df..6b7d315 100644
--- a/electron/recorder/controller.ts
+++ b/electron/recorder/controller.ts
@@ -4,7 +4,15 @@ import { app } from "electron";
import type { CaptureConfig } from "../../common/config";
import { EventType } from "../../common/events";
-import type { MarkerResult, RecorderStatus, StartOptions, StartResult, StopResult } from "../../common/ipc";
+import type {
+ DiscardResult,
+ MarkerResult,
+ MicrophoneResult,
+ RecorderStatus,
+ StartOptions,
+ StartResult,
+ StopResult,
+} from "../../common/ipc";
import type { RecorderState, SessionMeta } from "../../common/types";
import { createLogger } from "../logger";
import type { Collector } from "./collector";
@@ -22,41 +30,62 @@ function makeSessionId(d = new Date()): string {
return `${stamp}-${randomUUID().slice(0, 8)}`;
}
-/** A best-effort media sidecar (e.g. screen video) tied to a session's lifecycle. */
-export interface SessionMediaRecorder {
+/** A best-effort screen-video sidecar tied to a session's lifecycle. */
+export interface SessionVideoRecorder {
start(sessionDir: string): Promise<void>;
stop(): Promise<unknown>;
}
+/** Microphone sidecar that can create multiple capture intervals per session. */
+export interface SessionAudioRecorder {
+ start(sessionDir: string, sessionStartedAt: number): Promise<void>;
+ enable(): Promise<void>;
+ disable(): Promise<unknown>;
+ finish(videoStartEpoch: number | null): Promise<unknown>;
+}
+
+export interface AudioCaptureEnded {
+ error: string | null;
+}
+
export interface RecorderDeps {
/** Resolves the capture config in effect for the next session. */
resolveConfig: () => CaptureConfig;
/** Builds the collectors enabled by a config. */
buildCollectors: (config: CaptureConfig) => readonly Collector[];
/** Optional factory for the video sidecar; only used when `config.video`. */
- createVideoRecorder?: () => SessionMediaRecorder;
- /** Optional factory for the narration sidecar; only used when the user opts in. */
- createAudioRecorder?: () => SessionMediaRecorder;
- /** Optional best-effort post-processing (frames + correlation) after stop. */
+ createVideoRecorder?: () => SessionVideoRecorder;
+ /** Optional factory for the live-toggle microphone sidecar. */
+ createAudioRecorder?: (
+ onCaptureEnded: (event: AudioCaptureEnded) => void,
+ ) => SessionAudioRecorder;
+ /** Permanently removes a finalized session when the user discards it. */
+ deleteSession?: (sessionId: string) => Promise<void>;
+ /** Optional best-effort post-processing (frames + correlation) after save. */
postProcess?: (sessionDir: string) => Promise<void>;
}
+type FinishIntent = "save" | "discard";
+type FinishResult = StopResult & DiscardResult;
+
/**
- * The recorder state machine. It owns session lifecycle, the shared event bus,
- * and the collector host. Capture sources are resolved from the current config
- * at each `start()`, so the user can change the capture level between sessions
- * without restarting the app. When `config.video` is set, an optional video
- * sidecar is started and stopped alongside the collectors (best-effort).
+ * The recorder state machine. All lifecycle mutations are serialized so UI,
+ * tray, shortcut, microphone, and app-shutdown commands cannot race each other.
*/
export class RecorderController {
private store: SessionStore | null = null;
- private readonly listeners = new Set<(s: RecorderStatus) => void>();
+ private readonly listeners = new Set<(status: RecorderStatus) => void>();
private readonly bus = new EventBus();
private readonly host: CollectorHost;
private activeCollectors: readonly Collector[] = [];
- private video: SessionMediaRecorder | null = null;
- private audio: SessionMediaRecorder | null = null;
- private processing: Promise<void> | null = null;
+ private video: SessionVideoRecorder | null = null;
+ private audio: SessionAudioRecorder | null = null;
+ private transition: RecorderStatus["transition"] = "none";
+ private microphone: RecorderStatus["microphone"] = { state: "off", error: null };
+ private lastFinish: RecorderStatus["lastFinish"] = null;
+ private shuttingDown = false;
+ private operations: Promise<void> = Promise.resolve();
+ private readonly processing = new Set<Promise<void>>();
private lastCompleted: { id: string; dir: string } | null = null;
private lastProcessed = false;
@@ -84,6 +113,7 @@ export class RecorderController {
if (this.lastCompleted?.id !== id) return;
this.lastCompleted = null;
this.lastProcessed = false;
+ if (this.lastFinish?.sessionId === id) this.lastFinish = null;
this.emit();
}
@@ -93,120 +123,283 @@ export class RecorderController {
sessionId: this.store?.meta.id ?? null,
startedAt: this.store?.meta.startedAt ?? null,
eventCount: this.store?.eventCount ?? 0,
+ transition: this.transition,
+ microphone: { ...this.microphone },
+ lastFinish: this.lastFinish ? { ...this.lastFinish } : null,
lastSession: this.lastCompleted
? { id: this.lastCompleted.id, processed: this.lastProcessed }
: null,
};
}
- onStatusChanged(cb: (s: RecorderStatus) => void): () => void {
+ onStatusChanged(cb: (status: RecorderStatus) => void): () => void {
this.listeners.add(cb);
return () => {
this.listeners.delete(cb);
};
}
- private emit(): void {
- const s = this.status();
- for (const cb of this.listeners) cb(s);
+ start(options?: StartOptions): Promise<StartResult> {
+ return this.enqueue(() =>
+ this.shuttingDown
+ ? Promise.resolve({ ok: false, error: "Skill Recorder is shutting down." })
+ : this.startInternal(options),
+ );
}
- async start(options?: StartOptions): Promise<StartResult> {
+ stop(): Promise<StopResult> {
+ return this.enqueue(() => this.finish("save"));
+ }
+
+ discard(): Promise<DiscardResult> {
+ return this.enqueue(() => this.finish("discard"));
+ }
+
+ setMicrophoneEnabled(enabled: boolean): Promise<MicrophoneResult> {
+ return this.enqueue(async () => {
+ if (!this.store || this.transition !== "none") {
+ return { ok: false, error: "Microphone controls are only available while recording." };
+ }
+ return this.setMicrophoneInternal(enabled);
+ });
+ }
+
+ // Marker capture is intentionally retained even though the "Add marker" HUD
+ // button was removed in favor of voice narration (see docs/future-features.md).
+ marker(note: string): MarkerResult {
+ if (!this.store || this.transition !== "none") {
+ return { ok: false, error: "Not recording" };
+ }
+ this.bus.publish({ type: EventType.Marker, source: "user", payload: { note } });
+ return { ok: true };
+ }
+
+ /** Resolves when every saved session still being post-processed has finished. */
+ whenProcessed(): Promise<void> {
+ return Promise.all([...this.processing]).then(() => undefined);
+ }
+
+ /** Reject new recordings while the app drains capture and post-processing. */
+ beginShutdown(): void {
+ this.shuttingDown = true;
+ }
+
+ private async startInternal(options?: StartOptions): Promise<StartResult> {
if (this.store) return { ok: false, error: "Already recording" };
- const meta: SessionMeta = {
- id: makeSessionId(),
- startedAt: Date.now(),
- stoppedAt: null,
- platform: process.platform,
- appVersion: app.getVersion(),
- };
- const store = new SessionStore(meta);
+
+ this.transition = "starting";
+ this.microphone = { state: "off", error: null };
+ this.lastFinish = null;
+ this.emit();
+
+ let store: SessionStore;
+ try {
+ const meta: SessionMeta = {
+ id: makeSessionId(),
+ startedAt: Date.now(),
+ stoppedAt: null,
+ platform: process.platform,
+ appVersion: app.getVersion(),
+ };
+ store = new SessionStore(meta);
+ } catch (error) {
+ this.transition = "none";
+ this.emit();
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
this.store = store;
this.bus.attach(store);
this.bus.publish({
type: EventType.SessionStart,
source: "recorder",
- payload: { platform: meta.platform },
+ payload: { platform: store.meta.platform },
});
- log.info("Recording started:", meta.id, "->", store.dir);
+ log.info("Recording started:", store.meta.id, "->", store.dir);
this.emit();
const config = this.deps.resolveConfig();
this.activeCollectors = this.deps.buildCollectors(config);
await this.host.startAll(this.activeCollectors, store.dir);
- // Video is a best-effort sidecar; never let it block or fail the session.
+ // Video remains a best-effort sidecar; it never blocks the event recording.
if (config.video && this.deps.createVideoRecorder) {
this.video = this.deps.createVideoRecorder();
try {
await this.video.start(store.dir);
- } catch (err) {
- log.warn("video start failed:", err instanceof Error ? err.message : err);
+ } catch (error) {
+ log.warn("video start failed:", error instanceof Error ? error.message : error);
this.video = null;
}
}
- // Narration is strictly opt-in (the HUD toggle), off by default, and just as
- // best-effort as video: a missing mic or denied permission never fails the run.
- if (options?.narration && this.deps.createAudioRecorder) {
- this.audio = this.deps.createAudioRecorder();
+ // Initialize the audio utility for every session so the overlay can turn the
+ // mic on later. This does not request microphone access until enable().
+ if (this.deps.createAudioRecorder) {
+ this.audio = this.deps.createAudioRecorder((event) => this.onAudioCaptureEnded(event));
try {
- await this.audio.start(store.dir);
- } catch (err) {
- log.warn("narration start failed:", err instanceof Error ? err.message : err);
+ await this.audio.start(store.dir, store.meta.startedAt);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.warn("microphone initialization failed:", message);
this.audio = null;
+ this.microphone = { state: "error", error: message };
}
}
- return { ok: true, sessionId: meta.id };
+
+ if (options?.narration && this.audio) {
+ await this.setMicrophoneInternal(true);
+ }
+
+ this.transition = "none";
+ this.emit();
+ return { ok: true, sessionId: store.meta.id };
}
- // Marker capture is intentionally retained even though the "Add marker" HUD
- // button was removed in favor of voice narration (see docs/future-features.md).
- // The full path (IPC -> event bus -> bundle -> describer) stays wired so a
- // future UI (e.g. a silent hotkey flag) can re-enable it without backend work.
- marker(note: string): MarkerResult {
- if (!this.store) return { ok: false, error: "Not recording" };
- this.bus.publish({ type: EventType.Marker, source: "user", payload: { note } });
- return { ok: true };
+ private async setMicrophoneInternal(enabled: boolean): Promise<MicrophoneResult> {
+ if (enabled) {
+ if (this.microphone.state === "on") return { ok: true, state: "on" };
+ if (!this.audio) {
+ const error = "Microphone capture is unavailable for this recording.";
+ this.microphone = { state: "error", error };
+ this.emit();
+ return { ok: false, state: "error", error };
+ }
+
+ this.microphone = { state: "starting", error: null };
+ this.emit();
+ try {
+ await this.audio.enable();
+ this.microphone = { state: "on", error: null };
+ this.emit();
+ return { ok: true, state: "on" };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.microphone = { state: "error", error: message };
+ this.emit();
+ return { ok: false, state: "error", error: message };
+ }
+ }
+
+ if (this.microphone.state === "off") return { ok: true, state: "off" };
+ if (!this.audio) {
+ this.microphone = { state: "off", error: null };
+ this.emit();
+ return { ok: true, state: "off" };
+ }
+
+ this.microphone = { state: "stopping", error: null };
+ this.emit();
+ try {
+ await this.audio.disable();
+ this.microphone = { state: "off", error: null };
+ this.emit();
+ return { ok: true, state: "off" };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.microphone = { state: "error", error: message };
+ this.emit();
+ return { ok: false, state: "error", error: message };
+ }
}
- async stop(): Promise<StopResult> {
+ private async finish(intent: FinishIntent): Promise<FinishResult> {
const store = this.store;
if (!store) return { ok: false, error: "Not recording" };
- // Stop collectors first so nothing publishes after the stream is finalized.
+
+ this.transition = intent === "save" ? "stopping" : "discarding";
+ if (this.microphone.state !== "off") {
+ this.microphone = { state: "stopping", error: null };
+ }
+ this.emit();
+
+ // Stop producers before finalizing the event stream. Audio is flushed before
+ // video so the mic-off boundary is anchored as close as possible to the click.
await this.host.stopAll();
+ if (this.audio) {
+ try {
+ await this.audio.disable();
+ } catch (error) {
+ log.warn("microphone stop failed:", error instanceof Error ? error.message : error);
+ }
+ }
+
+ let videoStartEpoch: number | null = null;
if (this.video) {
try {
- await this.video.stop();
- } catch (err) {
- log.warn("video stop failed:", err instanceof Error ? err.message : err);
+ const result = await this.video.stop();
+ videoStartEpoch = readStartEpoch(result);
+ } catch (error) {
+ log.warn("video stop failed:", error instanceof Error ? error.message : error);
}
this.video = null;
}
+
if (this.audio) {
try {
- await this.audio.stop();
- } catch (err) {
- log.warn("narration stop failed:", err instanceof Error ? err.message : err);
+ await this.audio.finish(videoStartEpoch);
+ } catch (error) {
+ log.warn("microphone finalization failed:", error instanceof Error ? error.message : error);
}
this.audio = null;
}
+
this.bus.publish({ type: EventType.SessionStop, source: "recorder", payload: {} });
this.bus.detach();
- this.store = null;
store.finalize(Date.now());
+ await store.whenClosed();
+ this.microphone = { state: "off", error: null };
+
+ if (intent === "discard") {
+ try {
+ if (!this.deps.deleteSession) {
+ throw new Error("Session deletion is not configured.");
+ }
+ await this.deps.deleteSession(store.meta.id);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.store = null;
+ this.lastCompleted = { id: store.meta.id, dir: store.dir };
+ this.lastProcessed = false;
+ this.lastFinish = { sessionId: store.meta.id, outcome: "saved" };
+ this.transition = "none";
+ this.emit();
+ this.schedulePostProcess(store.dir);
+ log.warn("discard cleanup failed:", message);
+ return {
+ ok: false,
+ sessionId: store.meta.id,
+ error: `Recording stopped, but its files could not be discarded: ${message}`,
+ };
+ }
+
+ this.store = null;
+ this.transition = "none";
+ this.lastFinish = { sessionId: store.meta.id, outcome: "discarded" };
+ log.info("Recording discarded:", store.meta.id);
+ this.emit();
+ return { ok: true, sessionId: store.meta.id };
+ }
+
+ this.store = null;
this.lastCompleted = { id: store.meta.id, dir: store.dir };
this.lastProcessed = false;
+ this.lastFinish = { sessionId: store.meta.id, outcome: "saved" };
+ this.transition = "none";
log.info("Recording stopped:", store.meta.id, `(${store.eventCount} events)`);
this.emit();
// Frames + correlation run in the background so the UI returns promptly.
- this.processing = this.runPostProcess(store.dir, store.whenClosed());
+ this.schedulePostProcess(store.dir);
return { ok: true, sessionId: store.meta.id, sessionDir: store.dir };
}
- /** Resolves when the most recent session's post-processing finishes. */
- whenProcessed(): Promise<void> {
- return this.processing ?? Promise.resolve();
+ private schedulePostProcess(dir: string): void {
+ const processing = this.runPostProcess(dir, Promise.resolve());
+ this.processing.add(processing);
+ void processing.finally(() => this.processing.delete(processing));
}
private async runPostProcess(dir: string, closed: Promise<void>): Promise<void> {
@@ -216,13 +409,40 @@ export class RecorderController {
return;
}
try {
- await closed; // ensure events.jsonl is fully flushed before reading it
+ await closed;
await this.deps.postProcess(dir);
- } catch (err) {
- log.warn("post-processing failed:", err instanceof Error ? err.message : err);
+ } catch (error) {
+ log.warn("post-processing failed:", error instanceof Error ? error.message : error);
} finally {
if (this.lastCompleted?.dir === dir) this.lastProcessed = true;
this.emit();
}
}
+
+ private emit(): void {
+ const status = this.status();
+ for (const listener of this.listeners) listener(status);
+ }
+
+ private onAudioCaptureEnded(event: AudioCaptureEnded): void {
+ if (!this.store || this.transition !== "none") return;
+ const error = event.error ?? "The microphone stopped unexpectedly.";
+ this.microphone = { state: "error", error };
+ this.emit();
+ }
+
+ private enqueue<T>(work: () => Promise<T>): Promise<T> {
+ const operation = this.operations.then(work, work);
+ this.operations = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+ return operation;
+ }
+}
+
+function readStartEpoch(value: unknown): number | null {
+ if (!value || typeof value !== "object" || !("startEpoch" in value)) return null;
+ const startEpoch = value.startEpoch;
+ return typeof startEpoch === "number" && Number.isFinite(startEpoch) ? startEpoch : null;
}
diff --git a/electron/recording-controls-bounds.test.ts b/electron/recording-controls-bounds.test.ts
new file mode 100644
index 0000000..8eee7d3
--- /dev/null
+++ b/electron/recording-controls-bounds.test.ts
@@ -0,0 +1,50 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ RECORDING_CONTROLS_SIZE,
+ clampRecordingControlsBounds,
+ initialRecordingControlsBounds,
+ resizeRecordingControlsBounds,
+} from "./recording-controls-bounds";
+
+test("recording controls start bottom-center inside the work area", () => {
+ const workArea = { x: -1920, y: 0, width: 1920, height: 1040 };
+ assert.deepEqual(initialRecordingControlsBounds(workArea), {
+ x: -1194,
+ y: 946,
+ width: RECORDING_CONTROLS_SIZE.width,
+ height: RECORDING_CONTROLS_SIZE.collapsedHeight,
+ });
+});
+
+test("recording controls clamp to negative-coordinate and small displays", () => {
+ assert.deepEqual(
+ clampRecordingControlsBounds(
+ { x: -2500, y: 1300, width: 468, height: 232 },
+ { x: -1920, y: 0, width: 1280, height: 720 },
+ ),
+ { x: -1920, y: 488, width: 468, height: 232 },
+ );
+
+ assert.deepEqual(
+ clampRecordingControlsBounds(
+ { x: 10, y: 10, width: 468, height: 232 },
+ { x: 0, y: 0, width: 320, height: 180 },
+ ),
+ { x: 0, y: 0, width: 320, height: 180 },
+ );
+});
+
+test("confirmation expansion preserves the bar's bottom edge", () => {
+ const workArea = { x: 0, y: 0, width: 1440, height: 900 };
+ const collapsed = { x: 486, y: 806, width: 468, height: 76 };
+ const expanded = resizeRecordingControlsBounds(collapsed, true, workArea);
+ assert.deepEqual(expanded, { x: 486, y: 650, width: 468, height: 232 });
+ assert.equal(expanded.y + expanded.height, collapsed.y + collapsed.height);
+ assert.deepEqual(
+ resizeRecordingControlsBounds(expanded, false, workArea),
+ collapsed,
+ );
+});
+
diff --git a/electron/recording-controls-bounds.ts b/electron/recording-controls-bounds.ts
new file mode 100644
index 0000000..66a4913
--- /dev/null
+++ b/electron/recording-controls-bounds.ts
@@ -0,0 +1,74 @@
+export interface WindowBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export const RECORDING_CONTROLS_SIZE = {
+ width: 468,
+ collapsedHeight: 76,
+ expandedHeight: 232,
+ margin: 18,
+} as const;
+
+/** Place a new control bar at the bottom center of a display's usable work area. */
+export function initialRecordingControlsBounds(
+ workArea: WindowBounds,
+ expanded = false,
+): WindowBounds {
+ const height = expanded
+ ? RECORDING_CONTROLS_SIZE.expandedHeight
+ : RECORDING_CONTROLS_SIZE.collapsedHeight;
+ return {
+ x: Math.round(workArea.x + (workArea.width - RECORDING_CONTROLS_SIZE.width) / 2),
+ y: Math.round(workArea.y + workArea.height - RECORDING_CONTROLS_SIZE.margin - height),
+ width: RECORDING_CONTROLS_SIZE.width,
+ height,
+ };
+}
+
+/** Keep the full overlay visible after dragging, scaling, or display removal. */
+export function clampRecordingControlsBounds(
+ bounds: WindowBounds,
+ workArea: WindowBounds,
+): WindowBounds {
+ const width = Math.min(bounds.width, workArea.width);
+ const height = Math.min(bounds.height, workArea.height);
+ return {
+ x: Math.round(clamp(bounds.x, workArea.x, workArea.x + workArea.width - width)),
+ y: Math.round(clamp(bounds.y, workArea.y, workArea.y + workArea.height - height)),
+ width,
+ height,
+ };
+}
+
+/**
+ * Resize the transparent overlay above its fixed bar. Its bottom edge remains
+ * stationary, so opening confirmation never makes the control bar jump.
+ */
+export function resizeRecordingControlsBounds(
+ bounds: WindowBounds,
+ expanded: boolean,
+ workArea: WindowBounds,
+): WindowBounds {
+ const height = expanded
+ ? RECORDING_CONTROLS_SIZE.expandedHeight
+ : RECORDING_CONTROLS_SIZE.collapsedHeight;
+ const bottom = bounds.y + bounds.height;
+ return clampRecordingControlsBounds(
+ {
+ x: bounds.x,
+ y: bottom - height,
+ width: RECORDING_CONTROLS_SIZE.width,
+ height,
+ },
+ workArea,
+ );
+}
+
+function clamp(value: number, min: number, max: number): number {
+ if (max < min) return min;
+ return Math.max(min, Math.min(max, value));
+}
+
diff --git a/electron/sessions.test.ts b/electron/sessions.test.ts
index b53df25..e87adc3 100644
--- a/electron/sessions.test.ts
+++ b/electron/sessions.test.ts
@@ -16,11 +16,20 @@ test("session size includes every artifact and deletion removes the whole direct
const dir = path.join(root, id);
await mkdir(path.join(dir, "video-frames"), { recursive: true });
await mkdir(path.join(dir, "frames"), { recursive: true });
+ await mkdir(path.join(dir, "audio"), { recursive: true });
const artifacts: [string, string | Uint8Array][] = [
["session.json", JSON.stringify({ id, startedAt: 1_000, stoppedAt: 2_000 })],
["video.webm", Buffer.alloc(17, 1)],
- ["audio.webm", Buffer.alloc(19, 2)],
+ [
+ "audio.json",
+ JSON.stringify({
+ version: 2,
+ segments: [{ file: "audio/segment-0001.webm" }, { file: "audio/segment-0002.webm" }],
+ }),
+ ],
+ [path.join("audio", "segment-0001.webm"), Buffer.alloc(19, 2)],
+ [path.join("audio", "segment-0002.webm"), Buffer.alloc(13, 2)],
[path.join("video-frames", "frame_000001.jpg"), Buffer.alloc(23, 3)],
[path.join("frames", "event_1000.jpg"), Buffer.alloc(29, 4)],
];
@@ -32,6 +41,7 @@ test("session size includes every artifact and deletion removes the whole direct
0,
);
assert.equal(summary?.sizeBytes, expectedBytes);
+ assert.equal(summary?.hasAudio, true);
await deleteSession(id);
await assert.rejects(access(dir), { code: "ENOENT" });
diff --git a/electron/tray.ts b/electron/tray.ts
index 020ac55..1e80f2c 100644
--- a/electron/tray.ts
+++ b/electron/tray.ts
@@ -1,4 +1,4 @@
-import { Menu, Tray, nativeImage, type BrowserWindow } from "electron";
+import { Menu, Tray, nativeImage } from "electron";
import type { RecorderController } from "./recorder/controller";
@@ -21,7 +21,11 @@ function trayIcon(): Electron.NativeImage {
return nativeImage.createFromBitmap(buf, { width: size, height: size });
}
-export function createTray(recorder: RecorderController, win: BrowserWindow): Tray {
+export function createTray(
+ recorder: RecorderController,
+ showRecorderWindow: () => void,
+ showRecordingControls: () => void,
+): Tray {
const tray = new Tray(trayIcon());
tray.setToolTip("Skill Recorder");
@@ -35,10 +39,13 @@ export function createTray(recorder: RecorderController, win: BrowserWindow): Tr
},
{ type: "separator" },
{
- label: "Show window",
+ label: recording ? "Show recording controls" : "Show window",
click: () => {
- win.show();
- win.focus();
+ if (recording) {
+ showRecordingControls();
+ return;
+ }
+ showRecorderWindow();
},
},
{ label: "Quit", role: "quit" },
diff --git a/electron/video/capture-preload.cjs b/electron/video/capture-preload.cjs
index 799c207..0f93acf 100644
--- a/electron/video/capture-preload.cjs
+++ b/electron/video/capture-preload.cjs
@@ -36,6 +36,7 @@ let frameReady = false;
let recordingStarted = false;
let startEpoch = 0;
let startMonotonic = 0;
+let requestedStopEpoch = 0;
/** @type {number | null} */
let firstFrameTimestampUs = null;
let firstFrameEpoch = 0;
@@ -63,6 +64,10 @@ function currentEpoch() {
: Date.now();
}
+function epochNow() {
+ return performance.timeOrigin + performance.now();
+}
+
function createCanvas(width, height) {
if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
const canvas = document.createElement("canvas");
@@ -269,6 +274,7 @@ function cleanup() {
frameReady = false;
capturingFrames = false;
recordingStarted = false;
+ requestedStopEpoch = 0;
firstFrameTimestampUs = null;
lastFrameHash = "";
lastFrameEmitAt = 0;
@@ -310,7 +316,7 @@ ipcRenderer.on("video:start", async (_event, opts) => {
});
};
recorder.onstart = () => {
- startEpoch = Date.now();
+ startEpoch = epochNow();
startMonotonic = performance.now();
recordingStarted = true;
ipcRenderer.send("video:started", startEpoch);
@@ -318,12 +324,14 @@ ipcRenderer.on("video:start", async (_event, opts) => {
recorder.onstop = () => {
// Wait for every queued chunk and snapshot before acknowledging stop.
Promise.all([sendChain, stopFrameCapture()]).then(() => {
+ const stopEpoch = requestedStopEpoch || currentEpoch();
cleanup();
- ipcRenderer.send("video:stopped");
+ ipcRenderer.send("video:stopped", stopEpoch);
}).catch((err) => {
+ const stopEpoch = requestedStopEpoch || currentEpoch();
cleanup();
ipcRenderer.send("video:error", err instanceof Error ? err.message : String(err));
- ipcRenderer.send("video:stopped");
+ ipcRenderer.send("video:stopped", stopEpoch);
});
};
recorder.onerror = (e) => {
@@ -354,15 +362,17 @@ function withTimeout(promise, timeoutMs, message) {
ipcRenderer.on("video:stop", async () => {
try {
if (recorder && recorder.state !== "inactive") {
+ requestedStopEpoch = currentEpoch();
recorder.requestData();
recorder.stop();
} else {
await stopFrameCapture();
- ipcRenderer.send("video:stopped");
+ ipcRenderer.send("video:stopped", requestedStopEpoch || currentEpoch());
}
} catch (err) {
+ const stopEpoch = requestedStopEpoch || currentEpoch();
await stopFrameCapture().catch(() => undefined);
ipcRenderer.send("video:error", err instanceof Error ? err.message : String(err));
- ipcRenderer.send("video:stopped");
+ ipcRenderer.send("video:stopped", stopEpoch);
}
});
diff --git a/electron/video/recorder.ts b/electron/video/recorder.ts
index dd8319a..e32d546 100644
--- a/electron/video/recorder.ts
+++ b/electron/video/recorder.ts
@@ -43,6 +43,7 @@ const FPS = 1;
const BITS_PER_SECOND = 500_000;
const MAX_WIDTH = 1280;
const MAX_HEIGHT = 720;
+const START_TIMEOUT_MS = 10_000;
const STOP_TIMEOUT_MS = 10_000;
const MAX_FRAME_BYTES = 5 * 1024 * 1024;
const FRAME_HEARTBEAT_MS = 5000;
@@ -71,6 +72,8 @@ export class VideoRecorder {
private dir = "";
private bytes = 0;
private startEpoch: number | null = null;
+ private stopEpoch: number | null = null;
+ private startedResolve: (() => void) | null = null;
private stoppedResolve: (() => void) | null = null;
private failed = false;
private frameDir = "";
@@ -88,6 +91,8 @@ export class VideoRecorder {
private readonly onStarted = (e: IpcMainEvent, epoch: number) => {
if (e.sender !== this.win?.webContents) return;
this.startEpoch = epoch;
+ this.startedResolve?.();
+ this.startedResolve = null;
log.info("recording started; anchor epoch", epoch);
};
@@ -130,8 +135,9 @@ export class VideoRecorder {
if (e.sender === this.win?.webContents) log.warn("snapshot capture unavailable:", message);
};
- private readonly onStopped = (e: IpcMainEvent) => {
+ private readonly onStopped = (e: IpcMainEvent, epoch: number) => {
if (e.sender !== this.win?.webContents) return;
+ this.stopEpoch = Number.isFinite(epoch) ? epoch : Date.now();
this.stoppedResolve?.();
};
@@ -139,6 +145,8 @@ export class VideoRecorder {
if (e.sender !== this.win?.webContents) return;
this.failed = true;
log.warn("capture unavailable:", message);
+ this.startedResolve?.();
+ this.startedResolve = null;
// Unblock a pending stop() if the recorder never really started.
this.stoppedResolve?.();
};
@@ -160,6 +168,7 @@ export class VideoRecorder {
this.file = path.join(sessionDir, "video.webm");
this.bytes = 0;
this.startEpoch = null;
+ this.stopEpoch = null;
this.failed = false;
this.frameDir = path.join(sessionDir, VIDEO_FRAMES_DIR);
this.frameSequence = 0;
@@ -187,6 +196,9 @@ export class VideoRecorder {
});
await this.win.loadFile(path.join(dirname, "video", "capture.html"));
+ const started = new Promise<void>((resolve) => {
+ this.startedResolve = resolve;
+ });
this.win.webContents.send("video:start", {
sourceId: source.id,
fps: FPS,
@@ -195,9 +207,16 @@ export class VideoRecorder {
maxHeight: MAX_HEIGHT,
});
log.info("capture requested for screen source", source.id, "->", this.file);
+ await Promise.race([started, delay(START_TIMEOUT_MS)]);
+ if (this.startEpoch == null) {
+ log.warn("screen capture did not start; continuing without video");
+ await this.teardown();
+ await this.removeEmptyArtifacts();
+ }
} catch (err) {
log.warn("failed to start video:", err instanceof Error ? err.message : err);
await this.teardown();
+ await this.removeEmptyArtifacts();
}
}
@@ -205,6 +224,7 @@ export class VideoRecorder {
async stop(): Promise<VideoResult | null> {
if (!this.win || !this.stream) {
await this.teardown();
+ await this.removeEmptyArtifacts();
return null;
}
@@ -214,7 +234,7 @@ export class VideoRecorder {
});
await Promise.race([stopped, delay(STOP_TIMEOUT_MS)]);
- const stopEpoch = Date.now();
+ const stopEpoch = this.stopEpoch ?? Date.now();
await this.closeStream();
await Promise.allSettled([...this.frameWrites]);
@@ -295,11 +315,17 @@ export class VideoRecorder {
ipcMain.removeListener("video:stopped", this.onStopped);
ipcMain.removeListener("video:error", this.onError);
this.stoppedResolve = null;
+ this.startedResolve = null;
await this.closeStream();
this.stream = null;
if (this.win && !this.win.isDestroyed()) this.win.destroy();
this.win = null;
}
+
+ private async removeEmptyArtifacts(): Promise<void> {
+ if (this.file && existsSync(this.file)) await unlink(this.file).catch(() => undefined);
+ if (this.frameDir) await rm(this.frameDir, { recursive: true, force: true });
+ }
}
function delay(ms: number): Promise<void> {
diff --git a/electron/window.ts b/electron/window.ts
index 5ddebd9..8829689 100644
--- a/electron/window.ts
+++ b/electron/window.ts
@@ -3,6 +3,13 @@ import { fileURLToPath } from "node:url";
import { BrowserWindow, screen } from "electron";
+import {
+ RECORDING_CONTROLS_SIZE,
+ clampRecordingControlsBounds,
+ initialRecordingControlsBounds,
+ resizeRecordingControlsBounds,
+} from "./recording-controls-bounds";
+
const dirname = path.dirname(fileURLToPath(import.meta.url));
/** Compact recording HUD — fixed footprint, never resizes. */
@@ -13,6 +20,7 @@ const MARGIN = 12;
const GAP = 10;
type Bounds = { x: number; y: number; width: number; height: number };
+let recordingControlsAnchor: { x: number; bottom: number } | null = null;
function loadRoute(win: BrowserWindow, hash?: string): void {
const devUrl = process.env.VITE_DEV_SERVER_URL;
@@ -43,6 +51,79 @@ export function createRecorderWindow(): BrowserWindow {
return win;
}
+/** Always-on-top recording transport shown without stealing focus from the task. */
+export function createRecordingControlsWindow(): BrowserWindow {
+ let bounds: Bounds;
+ if (recordingControlsAnchor) {
+ const preferred = {
+ x: recordingControlsAnchor.x,
+ y: recordingControlsAnchor.bottom - RECORDING_CONTROLS_SIZE.collapsedHeight,
+ width: RECORDING_CONTROLS_SIZE.width,
+ height: RECORDING_CONTROLS_SIZE.collapsedHeight,
+ };
+ const display = screen.getDisplayMatching(preferred);
+ bounds = clampRecordingControlsBounds(preferred, display.workArea);
+ } else {
+ const display = screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
+ bounds = initialRecordingControlsBounds(display.workArea);
+ }
+ const win = new BrowserWindow({
+ ...bounds,
+ show: false,
+ frame: false,
+ transparent: true,
+ backgroundColor: "#00000000",
+ resizable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ closable: false,
+ skipTaskbar: true,
+ title: "Skill Recorder: Recording controls",
+ webPreferences: {
+ preload: path.join(dirname, "preload.cjs"),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: false,
+ backgroundThrottling: false,
+ },
+ });
+ win.setAlwaysOnTop(true, "floating");
+ win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
+ // Supported platforms exclude this window from desktop capture; on older
+ // systems Electron falls back to protecting its content.
+ win.setContentProtection(true);
+ const rememberPosition = () => {
+ if (win.isDestroyed()) return;
+ const current = win.getBounds();
+ recordingControlsAnchor = { x: current.x, bottom: current.y + current.height };
+ };
+ win.on("move", rememberPosition);
+ win.on("resize", rememberPosition);
+ rememberPosition();
+ loadRoute(win, "recording-controls");
+ return win;
+}
+
+/** Resize confirmation above the bar while preserving its on-screen bottom edge. */
+export function setRecordingControlsExpanded(
+ win: BrowserWindow,
+ expanded: boolean,
+): void {
+ if (win.isDestroyed()) return;
+ const bounds = win.getBounds();
+ const display = screen.getDisplayMatching(bounds);
+ win.setBounds(resizeRecordingControlsBounds(bounds, expanded, display.workArea), false);
+}
+
+/** Bring a dragged overlay back onto an available display. */
+export function clampRecordingControlsWindow(win: BrowserWindow): void {
+ if (win.isDestroyed()) return;
+ const bounds = win.getBounds();
+ const display = screen.getDisplayMatching(bounds);
+ win.setBounds(clampRecordingControlsBounds(bounds, display.workArea), false);
+}
+
/**
* Lay the recorder and library out as an attached pair that is always fully
* visible. The recorder keeps its place and the library docks to its right
diff --git a/package.json b/package.json
index 39bc9ef..ab18bd9 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,7 @@
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
"typecheck:evals": "tsc --noEmit -p evals/tsconfig.json",
- "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/sessions.test.ts",
+ "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test common/audio.test.ts electron/recording-controls-bounds.test.ts electron/recorder/controller.test.ts electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/sessions.test.ts",
"eval": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts",
"eval:builder": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/builder/run.ts",
"eval:skill": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/skillbuilder/run.ts",
diff --git a/src/App.css b/src/App.css
index 748dac8..e8004bf 100644
--- a/src/App.css
+++ b/src/App.css
@@ -68,6 +68,18 @@ body {
-webkit-font-smoothing: antialiased;
}
+body[data-route="recording-controls"] {
+ width: 100vw;
+ height: 100vh;
+ overflow: hidden;
+ background: transparent;
+}
+
+body[data-route="recording-controls"] #root {
+ width: 100%;
+ height: 100%;
+}
+
/* --- Shared primitives ---------------------------------------------------- */
.eyebrow {
@@ -725,6 +737,253 @@ button:focus-visible,
}
}
+/* =========================================================================
+ In-recording control overlay
+ ========================================================================= */
+
+ .recording-controls {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ gap: 8px;
+ width: 100%;
+ height: 100%;
+ padding: 4px 6px 2px;
+ color: #f7f7f7;
+ }
+
+ .recording-bar-wrap {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ -webkit-app-region: drag;
+ }
+
+ .recording-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ min-height: 58px;
+ padding: 8px 9px 8px 14px;
+ border: 1px solid rgba(255, 255, 255, 0.13);
+ border-radius: 14px;
+ background: rgba(32, 32, 34, 0.97);
+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.42), 0 2px 6px rgba(0, 0, 0, 0.3);
+ -webkit-app-region: drag;
+ }
+
+ .recording-bar button,
+ .recording-discard-confirm,
+ .recording-discard-confirm button {
+ -webkit-app-region: no-drag;
+ }
+
+ .recording-live {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 118px;
+ -webkit-app-region: drag;
+ }
+
+ .recording-live-dot {
+ width: 7px;
+ height: 7px;
+ flex: none;
+ border-radius: 50%;
+ background: #ef594b;
+ box-shadow: 0 0 0 3px rgba(239, 89, 75, 0.14);
+ animation: pulse 1.2s ease-in-out infinite;
+ }
+
+ .recording-live-copy {
+ display: flex;
+ align-items: baseline;
+ gap: 7px;
+ min-width: 0;
+ }
+
+ .recording-live-copy strong {
+ font-size: 12px;
+ font-weight: 650;
+ color: #f7f7f7;
+ }
+
+ .recording-live-copy span {
+ font-family: var(--mono);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ color: #aaa;
+ }
+
+ .recording-divider {
+ width: 1px;
+ height: 26px;
+ flex: none;
+ background: rgba(255, 255, 255, 0.13);
+ }
+
+ .recording-microphone {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ min-width: 67px;
+ height: 36px;
+ padding: 0 8px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 9px;
+ background: #2d2d30;
+ color: #b8b8bc;
+ font-size: 10px;
+ }
+
+ .recording-microphone.on {
+ border-color: rgba(239, 89, 75, 0.5);
+ background: rgba(239, 89, 75, 0.15);
+ color: #ff8a80;
+ }
+
+ .recording-microphone.error {
+ border-color: rgba(255, 184, 77, 0.55);
+ color: #ffc269;
+ }
+
+ .recording-microphone:not(:disabled):hover,
+ .recording-discard:not(:disabled):hover {
+ filter: brightness(1.16);
+ }
+
+ .recording-discard,
+ .recording-done {
+ height: 36px;
+ padding: 0 13px;
+ border-radius: 9px;
+ font-size: 11.5px;
+ font-weight: 600;
+ }
+
+ .recording-discard {
+ margin-left: auto;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: #343438;
+ color: #e6e6e8;
+ }
+
+ .recording-done {
+ min-width: 62px;
+ background: #fff;
+ color: #202024;
+ }
+
+ .recording-done:not(:disabled):hover {
+ background: #f0f0f1;
+ }
+
+ .recording-bar button:disabled,
+ .recording-discard-confirm button:disabled {
+ opacity: 0.52;
+ }
+
+ .recording-bar button:focus-visible,
+ .recording-discard-confirm button:focus-visible {
+ outline: 2px solid #ff766a;
+ outline-offset: 2px;
+ }
+
+ .recording-drag-handle {
+ display: block;
+ width: 34px;
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(67, 67, 70, 0.74);
+ -webkit-app-region: drag;
+ }
+
+ .recording-discard-confirm {
+ display: flex;
+ flex-direction: column;
+ gap: 13px;
+ width: 100%;
+ padding: 15px 16px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 13px;
+ background: rgba(37, 37, 40, 0.98);
+ box-shadow: 0 14px 34px rgba(0, 0, 0, 0.42);
+ color: #f7f7f7;
+ animation: recording-confirm-in 0.15s ease-out;
+ }
+
+ .recording-discard-confirm h2 {
+ margin: 0 0 4px;
+ font-size: 13px;
+ font-weight: 650;
+ }
+
+ .recording-discard-confirm p {
+ margin: 0;
+ color: #b8b8bc;
+ font-size: 11.5px;
+ line-height: 1.4;
+ }
+
+ .recording-discard-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ }
+
+ .recording-keep,
+ .recording-confirm-discard {
+ min-height: 34px;
+ padding: 0 12px;
+ border-radius: 8px;
+ font-size: 11.5px;
+ font-weight: 600;
+ }
+
+ .recording-keep {
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ background: #343438;
+ color: #efeff1;
+ }
+
+ .recording-confirm-discard {
+ background: #d9473b;
+ color: #fff;
+ }
+
+ .recording-confirm-discard:not(:disabled):hover {
+ background: #c43c32;
+ }
+
+ .recording-controls-live {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ }
+
+ @keyframes recording-confirm-in {
+ from {
+ opacity: 0;
+ transform: translateY(6px);
+ }
+ }
+
+@media (prefers-reduced-motion: reduce) {
+ .recording-live-dot,
+ .recording-discard-confirm {
+ animation: none;
+ }
+}
+
.sessions-open {
display: flex;
align-items: center;
diff --git a/src/Recorder.tsx b/src/Recorder.tsx
index 062f1b0..eaef7f9 100644
--- a/src/Recorder.tsx
+++ b/src/Recorder.tsx
@@ -46,8 +46,10 @@ export function Recorder() {
}, [refreshCount]);
const recording = status?.state === "recording";
+ const transitioning = status?.transition !== "none";
const startedAt = status?.startedAt ?? null;
- const justSaved = !recording && status?.lastSession != null;
+ const justSaved = !recording && status?.lastFinish?.outcome === "saved";
+ const justDiscarded = !recording && status?.lastFinish?.outcome === "discarded";
// Refresh the library count whenever a recording finishes.
useEffect(() => {
@@ -97,6 +99,7 @@ export function Recorder() {
<button
className={`record ${recording ? "on" : ""}`}
onClick={toggle}
+ disabled={transitioning}
aria-label={recording ? "Stop recording" : "Start recording"}
>
<span className="record-glyph" />
@@ -109,6 +112,8 @@ export function Recorder() {
? `${status?.eventCount ?? 0} events captured`
: justSaved
? "Capture saved. Open Sessions to analyze"
+ : justDiscarded
+ ? "Recording discarded"
: "Ready to capture"}
</div>
</div>
@@ -118,7 +123,7 @@ export function Recorder() {
role="switch"
aria-checked={narrate}
onClick={() => setNarrate((v) => !v)}
- disabled={recording}
+ disabled={recording || transitioning}
>
<span className="narrate-icon" aria-hidden>
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
diff --git a/src/RecordingControls.tsx b/src/RecordingControls.tsx
new file mode 100644
index 0000000..e2c09f1
--- /dev/null
+++ b/src/RecordingControls.tsx
@@ -0,0 +1,239 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import type { RecorderStatus } from "../common/ipc";
+import { formatMs } from "./format";
+
+export function RecordingControls() {
+ const [status, setStatus] = useState<RecorderStatus | null>(null);
+ const [elapsed, setElapsed] = useState(0);
+ const [confirmDiscard, setConfirmDiscard] = useState(false);
+ const [microphonePending, setMicrophonePending] = useState(false);
+ const [finishPending, setFinishPending] = useState<"done" | "discard" | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const keepRecordingRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ void window.skillRecorder.status().then(setStatus);
+ return window.skillRecorder.onStatusChanged(setStatus);
+ }, []);
+
+ const recording = status?.state === "recording";
+ const startedAt = status?.startedAt ?? null;
+ useEffect(() => {
+ if (!recording || startedAt == null) {
+ setElapsed(0);
+ return;
+ }
+ const update = () => setElapsed(Math.max(0, Date.now() - startedAt));
+ update();
+ const timer = setInterval(update, 250);
+ return () => clearInterval(timer);
+ }, [recording, startedAt]);
+
+ useEffect(() => {
+ if (recording) return;
+ if (confirmDiscard) setConfirmDiscard(false);
+ setMicrophonePending(false);
+ setFinishPending(null);
+ }, [confirmDiscard, recording]);
+
+ useEffect(() => {
+ void window.skillRecorder.setRecordingControlsExpanded(confirmDiscard);
+ }, [confirmDiscard]);
+
+ useEffect(() => {
+ if (!confirmDiscard) return;
+ keepRecordingRef.current?.focus({ preventScroll: true });
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setConfirmDiscard(false);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [confirmDiscard]);
+
+ const toggleMicrophone = useCallback(async () => {
+ if (!status) return;
+ setMicrophonePending(true);
+ setActionError(null);
+ const enable = status.microphone.state !== "on";
+ const result = await window.skillRecorder.setMicrophoneEnabled(enable);
+ if (!result.ok) setActionError(result.error ?? "Could not change the microphone.");
+ setMicrophonePending(false);
+ }, [status]);
+
+ const done = useCallback(async () => {
+ setFinishPending("done");
+ setActionError(null);
+ const result = await window.skillRecorder.stop();
+ if (!result.ok) {
+ setActionError(result.error ?? "Could not stop the recording.");
+ setFinishPending(null);
+ }
+ }, []);
+
+ const discard = useCallback(async () => {
+ setFinishPending("discard");
+ setActionError(null);
+ const result = await window.skillRecorder.discard();
+ if (!result.ok) {
+ const error = result.error ?? "Could not discard the recording.";
+ setActionError(error);
+ setFinishPending(null);
+ window.alert(error);
+ }
+ }, []);
+
+ const transitionBusy = status?.transition !== "none";
+ const microphoneBusy =
+ microphonePending ||
+ status?.microphone.state === "starting" ||
+ status?.microphone.state === "stopping";
+ const lifecycleBusy = finishPending !== null || transitionBusy || !recording;
+ const microphoneOn = status?.microphone.state === "on";
+ const microphoneError = status?.microphone.state === "error";
+ const microphoneLabel =
+ status?.microphone.state === "starting"
+ ? "Starting"
+ : status?.microphone.state === "stopping"
+ ? "Stopping"
+ : microphoneOn
+ ? "On"
+ : microphoneError
+ ? "Retry"
+ : "Off";
+ const error = actionError ?? status?.microphone.error ?? null;
+ const captureLabel =
+ status?.transition === "starting"
+ ? "Starting"
+ : status?.transition === "stopping"
+ ? "Saving"
+ : status?.transition === "discarding"
+ ? "Discarding"
+ : "Capturing";
+
+ return (
+ <div
+ className={`recording-controls ${confirmDiscard ? "expanded" : ""}`}
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget && confirmDiscard) setConfirmDiscard(false);
+ }}
+ >
+ {confirmDiscard && (
+ <section
+ className="recording-discard-confirm"
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="recording-discard-title"
+ aria-describedby="recording-discard-description"
+ >
+ <div>
+ <h2 id="recording-discard-title">Discard this recording?</h2>
+ <p id="recording-discard-description">
+ Screen video, activity, and recorded voice segments will be permanently deleted.
+ </p>
+ </div>
+ <div className="recording-discard-actions">
+ <button
+ ref={keepRecordingRef}
+ className="recording-keep"
+ disabled={finishPending === "discard"}
+ onClick={() => setConfirmDiscard(false)}
+ >
+ Keep recording
+ </button>
+ <button
+ className="recording-confirm-discard"
+ disabled={finishPending === "discard"}
+ onClick={() => void discard()}
+ >
+ {finishPending === "discard" ? "Discarding..." : "Discard recording"}
+ </button>
+ </div>
+ </section>
+ )}
+
+ <div className="recording-bar-wrap">
+ <div className="recording-bar">
+ <div className="recording-live" role="status" aria-label={`${captureLabel} ${formatMs(elapsed)}`}>
+ <span className="recording-live-dot" aria-hidden />
+ <span className="recording-live-copy">
+ <strong>{captureLabel}</strong>
+ <span>{formatMs(elapsed)}</span>
+ </span>
+ </div>
+
+ <span className="recording-divider" aria-hidden />
+
+ <button
+ className={`recording-microphone ${microphoneOn ? "on" : ""} ${
+ microphoneError ? "error" : ""
+ }`}
+ disabled={lifecycleBusy || microphoneBusy}
+ aria-label={
+ microphoneOn
+ ? "Turn microphone off"
+ : microphoneError
+ ? `Retry microphone. ${status?.microphone.error ?? ""}`
+ : "Turn microphone on"
+ }
+ aria-pressed={microphoneOn}
+ title={microphoneOn ? "Microphone on" : "Microphone off"}
+ onClick={() => void toggleMicrophone()}
+ >
+ <MicrophoneIcon off={!microphoneOn} />
+ <span>{microphoneLabel}</span>
+ </button>
+
+ <button
+ className="recording-discard"
+ disabled={lifecycleBusy}
+ onClick={() => {
+ setActionError(null);
+ setConfirmDiscard(true);
+ }}
+ >
+ Discard
+ </button>
+ <button className="recording-done" disabled={lifecycleBusy} onClick={() => void done()}>
+ {finishPending === "done" || status?.transition === "stopping" ? "Saving..." : "Done"}
+ </button>
+ </div>
+ <span className="recording-drag-handle" aria-hidden />
+ </div>
+
+ <span className="recording-controls-live" aria-live="polite">
+ {error ?? ""}
+ </span>
+ </div>
+ );
+}
+
+function MicrophoneIcon({ off }: { off: boolean }) {
+ return (
+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden>
+ <rect x="7.5" y="2.5" width="5" height="9" rx="2.5" stroke="currentColor" strokeWidth="1.5" />
+ <path
+ d="M5 9.2a5 5 0 0 0 8.9 3.1M10 14.2v3"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ {!off && (
+ <path
+ d="M15 9.2c0 .7-.14 1.36-.4 1.96"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
+ )}
+ {off && (
+ <path
+ d="M3.2 3.2 16.8 16.8"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ />
+ )}
+ </svg>
+ );
+}
diff --git a/src/WhatsRecorded.tsx b/src/WhatsRecorded.tsx
index 6c2a8d2..3f2880f 100644
--- a/src/WhatsRecorded.tsx
+++ b/src/WhatsRecorded.tsx
@@ -71,14 +71,20 @@ export function WhatsRecorded({ onClose }: { onClose: () => void }) {
<section className="sheet-block">
<h3>Voice narration (only if you turn it on)</h3>
- <p className="sheet-note">Off by default. The Narrate switch is your choice, per recording.</p>
+ <p className="sheet-note">
+ Off by default. Choose the initial state with Narrate, then use the floating recording bar.
+ </p>
<ul>
- <li>Your microphone is used only while Narrate is on and a recording is running.</li>
+ <li>Your microphone is used only while it is on and a recording is running.</li>
+ <li>
+ Turning the microphone off ends that voice segment and releases the device. Turning it
+ on again starts a new segment linked to the same recording timeline.
+ </li>
<li>
The recording can be turned into text on this computer using an offline model. The
first transcription needs a one-time ~250 MB download that you choose when to start.
</li>
- <li>Turn Narrate off and your microphone is never touched.</li>
+ <li>Leave the microphone off and it is never touched.</li>
</ul>
</section>
diff --git a/src/main.tsx b/src/main.tsx
index a2a52fc..dc51c5b 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -3,14 +3,23 @@ import { createRoot } from "react-dom/client";
import { Library } from "./Library";
import { Recorder } from "./Recorder";
+import { RecordingControls } from "./RecordingControls";
import "./App.css";
const root = document.getElementById("root");
if (!root) throw new Error("Missing #root");
-const isLibrary = window.location.hash.replace("#", "") === "library";
-document.body.dataset.route = isLibrary ? "library" : "recorder";
+const route = window.location.hash.replace("#", "");
+const isLibrary = route === "library";
+const isRecordingControls = route === "recording-controls";
+document.body.dataset.route = isLibrary
+ ? "library"
+ : isRecordingControls
+ ? "recording-controls"
+ : "recorder";
createRoot(root).render(
- <React.StrictMode>{isLibrary ? <Library /> : <Recorder />}</React.StrictMode>,
+ <React.StrictMode>
+ {isLibrary ? <Library /> : isRecordingControls ? <RecordingControls /> : <Recorder />}
+ </React.StrictMode>,
);