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.
TypeScript agent-skillsai-agentsautomationcopilotcopilot-clicopilot-coworkcopilot-studioelectronmicrosoft-scoutscreen-recording
Fix H1/H2: contain stream errors and recover recorder state on I/O failure
adilei9bdfaa4a7ec4
diff --git a/electron/crash-guards.test.ts b/electron/crash-guards.test.tsnew file mode 100644index 0000000..1428eb0--- /dev/null+++ b/electron/crash-guards.test.ts@@ -0,0 +1,48 @@+import assert from "node:assert/strict";+import test from "node:test";++import { installCrashGuards } from "./crash-guards";++function fakeLog() {+ const errors: string[] = [];+ return {+ log: {+ info: () => undefined,+ warn: () => undefined,+ error: (...args: unknown[]) => {+ errors.push(args.map(String).join(" "));+ },+ },+ errors,+ };+}++test("installCrashGuards registers process handlers and removes them on dispose", () => {+ const before = process.listenerCount("uncaughtException");+ const beforeRejections = process.listenerCount("unhandledRejection");++ const dispose = installCrashGuards(fakeLog().log);+ assert.equal(process.listenerCount("uncaughtException"), before + 1);+ assert.equal(process.listenerCount("unhandledRejection"), beforeRejections + 1);++ dispose();+ assert.equal(process.listenerCount("uncaughtException"), before);+ assert.equal(process.listenerCount("unhandledRejection"), beforeRejections);+});++test("the uncaughtException guard logs the error and does not rethrow", () => {+ const { log, errors } = fakeLog();+ const before = process.listeners("uncaughtException");+ const dispose = installCrashGuards(log);+ try {+ const added = process+ .listeners("uncaughtException")+ .filter((handler) => !before.includes(handler));+ assert.equal(added.length, 1);+ const handler = added[0] as (err: unknown) => void;+ assert.doesNotThrow(() => handler(new Error("simulated write EPIPE")));+ assert.ok(errors.some((message) => /EPIPE/.test(message)));+ } finally {+ dispose();+ }+});diff --git a/electron/crash-guards.ts b/electron/crash-guards.tsnew file mode 100644index 0000000..e9b8595--- /dev/null+++ b/electron/crash-guards.ts@@ -0,0 +1,37 @@+import { createLogger } from "./logger";++type Logger = ReturnType<typeof createLogger>;++/**+ * Last-resort process-level guards for the main process.+ *+ * The primary defense against a lost stream 'error' listener is to attach one at+ * each write stream (see SessionStore / VideoRecorder). This is the safety net for+ * anything that still slips through: a stray asynchronous failure is logged and+ * contained instead of taking down the whole main process — and with it any+ * recording in progress. It intentionally does NOT force-exit.+ *+ * Returns a disposer that removes the handlers (used by tests).+ */+export function installCrashGuards(log: Logger): () => void {+ const onUncaughtException = (err: unknown) => {+ log.error(+ "uncaught exception (contained):",+ err instanceof Error ? (err.stack ?? err.message) : String(err),+ );+ };+ const onUnhandledRejection = (reason: unknown) => {+ log.error(+ "unhandled rejection (contained):",+ reason instanceof Error ? (reason.stack ?? reason.message) : String(reason),+ );+ };++ process.on("uncaughtException", onUncaughtException);+ process.on("unhandledRejection", onUnhandledRejection);++ return () => {+ process.off("uncaughtException", onUncaughtException);+ process.off("unhandledRejection", onUnhandledRejection);+ };+}diff --git a/electron/main.ts b/electron/main.tsindex 2a622f9..17e86ad 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -3,6 +3,7 @@ import { app, BrowserWindow, globalShortcut, ipcMain, Menu, screen } from "electimport { FULL_CAPTURE } from "../common/config";import { IPC, type RecorderStatus, type StartResult } from "../common/ipc";import { createCollectors } from "./collectors";+import { installCrashGuards } from "./crash-guards";import { Describer } from "./describer/describer";import { processSession } from "./pipeline";import { registerIpc } from "./ipc";@@ -28,6 +29,10 @@ import {const log = createLogger("Main");+// Contain stray async failures so a lost stream error can't crash the main+// process (and the recording in progress). Registered before any window/IO work.+installCrashGuards(log);+/** Static red-dot tile used for the macOS Dock icon. */const dock = dockIcon();diff --git a/electron/recorder/controller.test.ts b/electron/recorder/controller.test.tsindex fef1c2e..797592d 100644--- a/electron/recorder/controller.test.ts+++ b/electron/recorder/controller.test.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { access, mkdtemp, rm } from "node:fs/promises";+import { access, mkdir, mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import test from "node:test";@@ -365,6 +365,67 @@ test("stop waits behind an in-flight microphone enable", async () => {});});+test("stop recovers to idle when finalizing the session fails", async () => {+ await withSessionsRoot(async (root) => {+ const controller = new RecorderController({+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),+ buildCollectors: () => [],+ deleteSession: async () => undefined,+ });++ const started = await controller.start();+ assert.equal(started.ok, true);+ const id = started.sessionId;+ assert.ok(id);++ // Force finalize() to throw the way a real disk failure would: replace the+ // metadata file with a directory so writeMeta()'s writeFileSync hits EISDIR.+ // A regression here leaves the state machine wedged in "stopping" forever.+ await rm(path.join(root, id, "session.json"), { force: true });+ await mkdir(path.join(root, id, "session.json"));++ const stopped = await controller.stop();+ assert.equal(stopped.ok, false);+ assert.match(stopped.error ?? "", /finaliz/i);+ assert.equal(controller.status().state, "idle");+ assert.equal(controller.status().transition, "none");++ // The recorder must accept a brand-new recording afterwards (not stay wedged).+ const restarted = await controller.start();+ assert.equal(restarted.ok, true);+ assert.equal(controller.status().state, "recording");+ assert.equal((await controller.stop()).ok, true);+ });+});++test("start recovers to idle when collector setup throws", async () => {+ await withSessionsRoot(async () => {+ let attempts = 0;+ const controller = new RecorderController({+ resolveConfig: () => ({ ...FULL_CAPTURE, video: false }),+ buildCollectors: () => {+ attempts += 1;+ if (attempts === 1) throw new Error("collector build failed");+ return [];+ },+ deleteSession: async () => undefined,+ });++ // The throw lands after the store is attached and the transition is "starting";+ // a regression leaves the machine reporting "recording" with no way to recover.+ const first = await controller.start();+ assert.equal(first.ok, false);+ assert.match(first.error ?? "", /collector build failed/i);+ assert.equal(controller.status().state, "idle");+ assert.equal(controller.status().transition, "none");++ const second = await controller.start();+ assert.equal(second.ok, true);+ assert.equal(controller.status().state, "recording");+ assert.equal((await controller.stop()).ok, true);+ });+});+async function withSessionsRoot(run: (root: string) => Promise<void>,): Promise<void> {diff --git a/electron/recorder/controller.ts b/electron/recorder/controller.tsindex 2490558..328b6d7 100644--- a/electron/recorder/controller.ts+++ b/electron/recorder/controller.ts@@ -325,45 +325,98 @@ export class RecorderController {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);+ try {+ const config = this.deps.resolveConfig();+ this.activeCollectors = this.deps.buildCollectors(config);+ await this.host.startAll(this.activeCollectors, store.dir);++ // 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 (error) {+ log.warn("video start failed:", error instanceof Error ? error.message : error);+ this.video = null;+ }+ }++ // 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, store.meta.startedAt, this.narrationLanguage);+ } 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, activeDevice: null };+ }+ }++ if (options?.narration && this.audio) {+ await this.setMicrophoneInternal(+ true,+ options.microphoneDeviceId ?? SYSTEM_DEFAULT_MICROPHONE_ID,+ );+ }+ } catch (error) {+ // Startup failed after the store was attached; roll back to idle instead of+ // wedging the machine in "starting" (which would reject every later start()).+ const message = error instanceof Error ? error.message : String(error);+ log.warn("recording startup failed:", message);+ await this.rollbackFailedStart(store);+ return { ok: false, error: message };+ }++ this.transition = "none";+ this.emit();+ return { ok: true, sessionId: store.meta.id };+ }- // Video remains a best-effort sidecar; it never blocks the event recording.- if (config.video && this.deps.createVideoRecorder) {- this.video = this.deps.createVideoRecorder();+ /**+ * Best-effort teardown when startInternal() throws after the store is attached.+ * Releases every producer and the event stream, then resets the machine to idle+ * so a subsequent start() can succeed.+ */+ private async rollbackFailedStart(store: SessionStore): Promise<void> {+ try {+ await this.host.stopAll();+ } catch (error) {+ log.warn("collector rollback failed:", error instanceof Error ? error.message : error);+ }+ if (this.video) {try {- await this.video.start(store.dir);+ await this.video.stop();} catch (error) {- log.warn("video start failed:", error instanceof Error ? error.message : error);- this.video = null;+ log.warn("video rollback failed:", error instanceof Error ? error.message : error);}+ this.video = null;}-- // 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));+ if (this.audio) {try {- await this.audio.start(store.dir, store.meta.startedAt, this.narrationLanguage);+ await this.audio.disable();} 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, activeDevice: null };+ log.warn("microphone rollback failed:", error instanceof Error ? error.message : error);}+ this.audio = null;}-- if (options?.narration && this.audio) {- await this.setMicrophoneInternal(- true,- options.microphoneDeviceId ?? SYSTEM_DEFAULT_MICROPHONE_ID,+ this.bus.detach();+ try {+ store.finalize(Date.now());+ } catch (error) {+ log.warn(+ "session cleanup after failed start failed:",+ error instanceof Error ? error.message : error,);+ store.dispose();}-+ this.store = null;+ this.activeCollectors = [];+ this.microphone = { state: "off", error: null, activeDevice: null };this.transition = "none";this.emit();- return { ok: true, sessionId: store.meta.id };}private async setMicrophoneInternal(@@ -440,7 +493,11 @@ export class RecorderController {// 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();+ try {+ await this.host.stopAll();+ } catch (error) {+ log.warn("collector stop failed:", error instanceof Error ? error.message : error);+ }if (this.audio) {try {await this.audio.disable();@@ -471,8 +528,18 @@ export class RecorderController {this.bus.publish({ type: EventType.SessionStop, source: "recorder", payload: {} });this.bus.detach();- store.finalize(Date.now());- await store.whenClosed();+ // A finalize failure (disk full, session dir removed) must not wedge the state+ // machine in "stopping": capture it, release the stream, and fall through to a+ // clean idle state below so the recorder can start again.+ let finalizeError: string | null = null;+ try {+ store.finalize(Date.now());+ await store.whenClosed();+ } catch (error) {+ finalizeError = error instanceof Error ? error.message : String(error);+ log.warn("session finalization failed:", finalizeError);+ store.dispose();+ }this.microphone = { state: "off", error: null, activeDevice: null };if (intent === "discard") {@@ -515,6 +582,13 @@ export class RecorderController {this.emit();// Frames + correlation run in the background so the UI returns promptly.this.schedulePostProcess(store.dir);+ if (finalizeError) {+ return {+ ok: false,+ sessionId: store.meta.id,+ error: `Recording stopped, but finalizing its files failed: ${finalizeError}`,+ };+ }return { ok: true, sessionId: store.meta.id, sessionDir: store.dir };}diff --git a/electron/recorder/session-store.test.ts b/electron/recorder/session-store.test.tsnew file mode 100644index 0000000..e2eb111--- /dev/null+++ b/electron/recorder/session-store.test.ts@@ -0,0 +1,62 @@+import assert from "node:assert/strict";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import test from "node:test";++import type { SessionMeta } from "../../common/types";+import { SessionStore } from "./session-store";++function makeMeta(id: string): SessionMeta {+ return {+ id,+ startedAt: Date.now(),+ stoppedAt: null,+ platform: process.platform,+ appVersion: "0.0.0-test",+ };+}++type ErrorEmitter = { eventsStream: { emit(event: string, error: Error): boolean } };++test("a write-stream error is captured, not thrown as an uncaught exception", async () => {+ await withSessionsRoot(async () => {+ const store = new SessionStore(makeMeta("20250101-000000-aaaabbbb"));+ const stream = (store as unknown as ErrorEmitter).eventsStream;++ // A Node Writable with no 'error' listener rethrows the error as an uncaught+ // exception — in the main process that is a hard crash of the whole app,+ // mid-recording. The store must own the failure instead of letting it escape.+ assert.doesNotThrow(() =>+ stream.emit("error", new Error("ENOSPC: no space left on device, write")),+ );+ assert.match(store.writeError?.message ?? "", /ENOSPC/);++ // And it must still finalize cleanly afterwards (no hang waiting on close).+ store.finalize(Date.now());+ await store.whenClosed();+ });+});++test("dispose releases the events stream without hanging", async () => {+ await withSessionsRoot(async () => {+ const store = new SessionStore(makeMeta("20250101-000000-ccccdddd"));+ store.append("marker", "test");+ store.dispose();+ await store.whenClosed();+ assert.equal(store.writeError, null);+ });+});++async function withSessionsRoot(run: () => Promise<void>): Promise<void> {+ const root = await mkdtemp(path.join(tmpdir(), "skill-recorder-store-"));+ const previous = process.env.SKILL_RECORDER_SESSIONS_DIR;+ process.env.SKILL_RECORDER_SESSIONS_DIR = root;+ try {+ await run();+ } finally {+ if (previous === undefined) delete process.env.SKILL_RECORDER_SESSIONS_DIR;+ else process.env.SKILL_RECORDER_SESSIONS_DIR = previous;+ await rm(root, { recursive: true, force: true });+ }+}diff --git a/electron/recorder/session-store.ts b/electron/recorder/session-store.tsindex 8c2a288..27310ac 100644--- a/electron/recorder/session-store.ts+++ b/electron/recorder/session-store.ts@@ -4,6 +4,9 @@ import path from "node:path";import { app } from "electron";import type { RecEvent, SessionMeta } from "../../common/types";+import { createLogger } from "../logger";++const log = createLogger("SessionStore");/** Root folder that holds one sub-directory per recorded session. */export function sessionsRoot(): string {@@ -50,12 +53,20 @@ export class SessionStore {private readonly startMonotonic: number;private readonly closed: Promise<void>;private count = 0;+ private streamError: Error | null = null;constructor(meta: SessionMeta) {this.meta = meta;this.dir = path.join(sessionsRoot(), meta.id);mkdirSync(path.join(this.dir, "frames"), { recursive: true });this.eventsStream = createWriteStream(path.join(this.dir, "events.jsonl"), { flags: "a" });+ // Own the stream's failures: a Writable with no 'error' listener rethrows the+ // error as an uncaught exception, which crashes the whole main process (and the+ // recording in progress). Capture it instead so callers can react.+ this.eventsStream.on("error", (err) => {+ this.streamError = err instanceof Error ? err : new Error(String(err));+ log.error("events stream write failed:", this.streamError.message);+ });this.closed = new Promise<void>((resolve) => {this.eventsStream.once("close", () => resolve());});@@ -67,6 +78,11 @@ export class SessionStore {return this.count;}+ /** The first error the events stream reported, if any. */+ get writeError(): Error | null {+ return this.streamError;+ }+/** Resolves once the events stream has fully flushed to disk (after finalize). */whenClosed(): Promise<void> {return this.closed;@@ -95,4 +111,9 @@ export class SessionStore {this.writeMeta();this.eventsStream.end();}++ /** Force-release the events stream — used to recover from a finalize failure. */+ dispose(): void {+ this.eventsStream.destroy();+ }}diff --git a/electron/video/recorder.ts b/electron/video/recorder.tsindex e32d546..7645f7b 100644--- a/electron/video/recorder.ts+++ b/electron/video/recorder.ts@@ -176,6 +176,10 @@ export class VideoRecorder {this.frameWrites.clear();await mkdir(this.frameDir, { recursive: true });this.stream = createWriteStream(this.file);+ this.stream.on("error", (err) => {+ this.failed = true;+ log.warn("video stream write failed:", err instanceof Error ? err.message : err);+ });ipcMain.on("video:chunk", this.onChunk);ipcMain.on("video:frame", this.onFrame);diff --git a/package.json b/package.jsonindex 7193247..fa4c23c 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 common/audio.test.ts common/microphone.test.ts common/narration.test.ts electron/recording-controls-bounds.test.ts electron/recording-privacy.test.ts electron/recorder/controller.test.ts electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts scripts/compliance.test.mjs",+ "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test common/audio.test.ts common/microphone.test.ts common/narration.test.ts electron/recording-controls-bounds.test.ts electron/recording-privacy.test.ts electron/crash-guards.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts scripts/compliance.test.mjs","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",