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 Windows ARM64 support

Giorgio Ughini68aca5b95676
diff --git a/.github/workflows/non-windows.yml b/.github/workflows/non-windows.yml
new file mode 100644
index 0000000..34ad809
--- /dev/null
+++ b/.github/workflows/non-windows.yml
@@ -0,0 +1,37 @@
+name: Non-Windows
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - macos-latest
+ - ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+
+ - run: npm ci
+ - name: Verify optional window provider
+ run: >-
+ node --input-type=module -e
+ "const m = await import('get-windows');
+ if (typeof m.activeWindow !== 'function')
+ throw new Error('get-windows activeWindow export is unavailable')"
+ - run: npm test
+ - run: npm run build
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
new file mode 100644
index 0000000..76bccba
--- /dev/null
+++ b/.github/workflows/windows.yml
@@ -0,0 +1,55 @@
+name: Windows
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ native:
+ name: Windows ${{ matrix.arch }}
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x64
+ runner: windows-latest
+ dist_script: dist:win:x64
+ - arch: arm64
+ runner: windows-11-arm
+ dist_script: dist:win:arm64
+
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ architecture: ${{ matrix.arch }}
+ cache: npm
+
+ - name: Install native dependencies
+ shell: pwsh
+ run: |
+ if ((node -p "process.arch") -ne "${{ matrix.arch }}") {
+ throw "Expected Node ${{ matrix.arch }}"
+ }
+ npm ci
+ node -e "require('sharp'); require('onnxruntime-node'); require('koffi')"
+ if (Select-String -Path package-lock.json -Pattern 'ffmpeg-static' -Quiet) {
+ throw "ffmpeg-static remains in the lockfile"
+ }
+
+ - name: Test and build
+ run: |
+ npm test
+ npm run build
+
+ - name: Package native installer
+ run: npm run ${{ matrix.dist_script }}
+
+ - name: Verify packaged architecture
+ run: node scripts/verify-windows-package.mjs ${{ matrix.arch }}
diff --git a/README.md b/README.md
index ca2adf5..0e276cd 100644
--- a/README.md
+++ b/README.md
@@ -32,10 +32,11 @@ can repeat.
Everything is captured and processed **locally**. The in-app "Records your screen and
activity" panel shows exactly what's collected:
-- **Window tracking** — active-app / window switches (native, via `get-windows`).
+- **Window tracking** — active-app / window switches (Koffi/Win32 on Windows,
+ `get-windows` elsewhere).
- **Browser URLs** — the page you're on (macOS, via AppleScript).
-- **Screen video** — recorded with a bundled `ffmpeg`; frames are pulled only at
- meaningful moments to disambiguate the steps.
+- **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).
@@ -43,12 +44,14 @@ activity" panel shows exactly what's collected:
## Requirements
-- **macOS** (primary target). Core recording is also validated on Windows 11; see
+- **macOS** (primary target). Windows 11 x64 and ARM64 are also supported; see
[`WINDOWS-VALIDATION.md`](WINDOWS-VALIDATION.md).
- **Node.js 22+**.
- **GitHub Copilot CLI** installed and signed in — the `copilot` command must be on
your `PATH`. This powers the analysis and the skill/automation builders.
-- `ffmpeg` is **bundled** — no separate install needed.
+- No system media tools are required. Chromium handles screen snapshots and narration
+ audio decoding. A system `ffmpeg` is used only when opening a recording created by
+ an older Skill Recorder version that has no snapshot manifest.
On first launch macOS will prompt for **Screen Recording** (required) and, if you use
Narrate, **Microphone** permission.
@@ -71,7 +74,9 @@ Other useful scripts:
```bash
npm run typecheck # tsc --noEmit
npm run build # typecheck + production build (dist/ + dist-electron/)
-npm run dist # build a distributable via electron-builder (dmg/zip on macOS)
+npm run dist # build a non-Windows distributable via electron-builder
+npm run dist:win:x64 # requires native Windows x64
+npm run dist:win:arm64 # requires native Windows ARM64
npm start # run the last build with `electron .`
```
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index d2b3f7e..15bec55 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -4,8 +4,9 @@ Skill Recorder is licensed under the MIT License (see [`LICENSE`](./LICENSE)).
Packaged/distributed builds include third-party components that are covered by
their own license terms. This file summarizes the notable ones. The complete
-license text for every dependency lives in its own directory under
-`node_modules/<package>/` (for example `LICENSE` or `LICENSE.md`).
+license notices retained by Electron are distributed as `LICENSE.electron.txt`
+and `LICENSES.chromium.html`; package metadata and the source links below cover
+the other native runtime components.
The dependency tree is otherwise permissive (MIT, ISC, Apache-2.0, BSD,
BlueOak-1.0.0) and compatible with distributing this application under MIT.
@@ -22,23 +23,50 @@ BlueOak-1.0.0) and compatible with distributing this application under MIT.
application's own license, including distribution under an open-source (MIT)
license.
-### FFmpeg — via `ffmpeg-static`
-- ⚠️ `ffmpeg-static` currently ships a **GPL-3.0-or-later** FFmpeg build. This is
- the one bundled component that is **not** compatible with an MIT-only
- distribution.
-- Tracked in **issue #11**: planned replacement with an **LGPL-2.1** FFmpeg build
- (e.g. `@ffmpeg-installer/ffmpeg`). This project only decodes VP8/VP9 WebM and
- writes JPEG frames, so an LGPL build is fully sufficient.
-- FFmpeg is invoked as a separate subprocess; it is not linked into the app.
+### Electron / Chromium media codecs
+- License: Electron is **MIT**. Its Chromium runtime includes `ffmpeg.dll`
+ (`libffmpeg.dylib` / `libffmpeg.so` on other platforms), a dynamically loaded
+ codec library whose bundled notice identifies FFmpeg as **LGPL-2.1-or-later**.
+ GPL portions require an explicit non-default FFmpeg build configuration.
+- Electron's `LICENSE.electron.txt` and `LICENSES.chromium.html` are retained in
+ every packaged application.
+- The currently pinned source is Electron
+ [`v43.1.1`](https://github.com/electron/electron/tree/v43.1.1), Chromium
+ [`150.0.7871.114`](https://chromium.googlesource.com/chromium/src/+/150.0.7871.114),
+ and Chromium FFmpeg revision
+ [`ad41607c61898cf7150e0fb20fe4bbabd44922a3`](https://chromium.googlesource.com/chromium/third_party/ffmpeg/+/ad41607c61898cf7150e0fb20fe4bbabd44922a3).
+- Chromium records the WebM media, captures screen snapshots, and decodes
+ narration audio. Skill Recorder does **not** distribute `ffmpeg-static` or a
+ standalone FFmpeg executable.
+- A user-installed standalone FFmpeg may be invoked only to read a recording
+ created before snapshot manifests were introduced. That executable is not part
+ of this app.
-### libvips — via `sharp` / `@img/sharp-libvips-*`
-- License: **LGPL-3.0-or-later** — a prebuilt shared library loaded dynamically
- by `sharp`. Compatible with MIT distribution; the library remains replaceable.
-- `sharp` itself is **Apache-2.0**.
+### Sharp / libvips — `sharp` and `@img/sharp-*`
+- `sharp` is **Apache-2.0**. Its Windows native packages are
+ **Apache-2.0 AND LGPL-3.0-or-later**; other platforms load the corresponding
+ **LGPL-3.0-or-later** `@img/sharp-libvips-*` package.
+- The currently pinned source is Sharp
+ [`v0.34.5`](https://github.com/lovell/sharp/tree/v0.34.5), its reproducible
+ packaging scripts
+ [`sharp-libvips v1.2.4`](https://github.com/lovell/sharp-libvips/tree/v1.2.4),
+ and libvips
+ [`v8.17.3`](https://github.com/libvips/libvips/tree/v8.17.3). The unpacked
+ native module remains replaceable in the packaged application.
+
+### LGPL release materials
+
+Before publishing an installer, its release must provide archives of the exact
+source revisions above, the applicable LGPL text, and any build/object material needed
+to relink modified LGPL components. These materials must be available beside
+the installer, or through a written offer valid for at least three years; do
+not rely only on third-party hosting remaining available.
### Other native modules
- `get-windows` — MIT
-- `sharp` — Apache-2.0 (retain its `LICENSE` / `NOTICE`)
+- `koffi` / `@koromix/koffi-*` — MIT; used for Win32 foreground-window calls,
+ including the native Windows ARM64 build.
+- `sharp` — Apache-2.0; see the Sharp/libvips section for native payload terms
## Apache-2.0 components
Some dependencies (e.g. `sharp`) are Apache-2.0, which requires retaining their
diff --git a/WINDOWS-VALIDATION.md b/WINDOWS-VALIDATION.md
index 7b65049..f80af53 100644
--- a/WINDOWS-VALIDATION.md
+++ b/WINDOWS-VALIDATION.md
@@ -1,92 +1,99 @@
-# Windows Validation Report
-
-**Tested on:** Windows 11, Node 22, Electron 43
-**Date:** 2025-07-25
-
-## Summary
-
-The skill-recorder **works on Windows** for core recording. Install, typecheck, build, and the recording pipeline all pass. The main gap is the AI describer (Copilot SDK server crashes at launch) and the absence of video capture (likely a Screen Recording permission / `desktopCapturer` sourcing issue in the headless test context — requires manual re-test with a visible desktop).
-
----
-
-## ✅ Passing
-
-| Area | Status | Notes |
-|------|--------|-------|
-| `npm install` | ✅ | All native modules (sharp, get-windows, ffmpeg-static) install correctly |
-| `tsc --noEmit` | ✅ | Zero type errors |
-| `vite build` | ✅ | Client + electron main both bundle |
-| App launch | ✅ | Electron window opens, tray created, global shortcut registered |
-| `get-windows` | ✅ | Active window polling works (app names, PIDs, paths, bounds all captured) |
-| Clipboard collector | ✅ | Detects clipboard changes, hashes + previews correctly |
-| Session store | ✅ | Creates `%APPDATA%/skill-recorder/sessions/<id>/` with correct files |
-| Event stream | ✅ | `events.jsonl` written with well-formed JSON lines |
-| Pipeline (bundle + description) | ✅ | `bundle.json` and `description.md` generated post-stop |
-| ffmpeg-static | ✅ | Binary exists at `node_modules/ffmpeg-static/ffmpeg.exe`, runs `ffmpeg -version` |
-| Path handling | ✅ | All `path.join` usage is OS-agnostic; no hardcoded `/` separators found |
-| Terminal hooks (pwsh) | ➖ | Removed after this report. The always-on shell hook was dropped; a safer recorded-terminal (PTY) approach is tracked in #7 |
-
----
-
-## ⚠️ Issues Found
-
-### 1. Copilot SDK describer fails to start (BLOCKING for AI analysis)
-
-**Symptom:** `[IPC] analyze failed: CLI server exited unexpectedly with code 0`
-**Root cause:** `@github/copilot-sdk` `CopilotClient.start()` spawns a child server process that exits immediately. The `copilot` CLI is not installed on this machine (`where copilot` → not found).
-**Impact:** The AI-powered session analysis (intent extraction, step refinement, feedback loop) is completely unavailable.
-**Fix:** Install the GitHub Copilot CLI (`copilot`) and sign in. The doctor UI already surfaces this requirement — no code change needed, just a prerequisite.
-
-### 2. No video captured during test recording
-
-**Symptom:** Session directory has no `video.webm` or `video.json`. The `frames/` directory is empty.
-**Likely cause:** `desktopCapturer.getSources({ types: ["screen"] })` may return an empty array when running without a visible desktop session, or Screen Recording permission equivalent is missing. In normal interactive use this should work — needs confirmation in a full desktop session.
-**Impact:** Frame extraction and visual correlation are skipped. The event-only pipeline still produces a valid bundle.
-**Fix:** No code change needed — this is expected degradation. The `VideoRecorder.start()` already handles this gracefully (line 88-90: logs "no screen source available; skipping video").
-
-### 3. URL provider returns `null` on Windows — ✅ FIXED
-
-**Symptom:** No `browser.url` events emitted even when Edge is frontmost.
-**Root cause:** `createUrlProvider()` returned `null` for non-darwin platforms.
-**Fix:** Implemented `WindowsUrlProvider` using a persistent PowerShell sidecar with Windows UI Automation. Reads the address bar of Chromium browsers via `Chrome_WidgetWin_1` UIA tree traversal. ~70ms response time per query.
-**Verified:** 4 browser.url events captured during a test recording (Bing searches + site navigation).
-
-### 4. Window titles are empty strings at `basic` capture level
-
-**Symptom:** All `app.activate` events show `"title": ""`.
-**Root cause:** This is **by design** — `basic` level sets `windowTitles: false` (confirmed in `common/config.ts`). The `ActiveWindowCollector` respects this and passes empty titles.
-**Impact:** None — working as intended. Titles appear at `standard` or `full` levels.
-**Not a bug.**
-
----
-
-## 🔍 Code Review: Windows-Specific Considerations
-
-### Things that already work correctly
-
-1. **`doctor.ts`** — uses `where` (Windows) vs `which` (Unix) for binary detection ✅
-2. **`terminal-hooks.ts`** — _(removed after this report; terminal capture dropped, see #7)_ included a PowerShell hook (`PWSH_HOOK`) alongside zsh/bash
-3. **`session-store.ts`** — uses `path.join()` everywhere, no hardcoded separators ✅
-4. **`vite.config.ts`** — uses `path.join()` for all asset copying ✅
-5. **`video/recorder.ts`** — uses `path.join()` for preload and capture.html paths ✅
-6. **Session ID validation** — regex `[A-Za-z0-9._-]` is safe on Windows filesystems ✅
-7. **`ffmpeg-static`** — ships platform-specific binary (`ffmpeg.exe` on Windows) ✅
-8. **`sharp`** — has Windows native bindings, installed and loadable ✅
-
-### Potential issues for production/packaging
-
-| Issue | File | Detail |
-|-------|------|--------|
-| `electron-builder` packaging | `package.json` | Untested — `npm run dist` was not run. Native modules (sharp, ffmpeg-static, get-windows) may need special `asarUnpack` config for Windows `.exe`/`.dll` files |
-| `get-windows` binary | `node_modules/get-windows` | Ships a Windows binary; needs to survive asar packing or be unpacked |
-| Long path risk | `session-store.ts` | `%APPDATA%` paths can be deep; session dirs with many nested frames could exceed 260-char limit on older Windows builds without long path support |
-
----
-
-## Recommendations
-
-1. ~~**Install Copilot CLI**~~ to unblock the describer — no code changes needed.
-2. ~~**Test video capture**~~ — ✅ works in full interactive desktop session.
-3. ~~**Implement Windows URL provider**~~ — ✅ Done (UI Automation sidecar).
-4. **Test `npm run dist`** (electron-builder) to verify native module packaging with `asarUnpack`.
-5. **Consider enabling long paths** in the app manifest or documenting the requirement for Windows users.
+# Windows validation
+
+Skill Recorder supports native Windows 11 builds for both x64 and ARM64. The
+architecture gate lives in [`.github/workflows/windows.yml`](.github/workflows/windows.yml)
+and runs on GitHub's `windows-latest` and native `windows-11-arm` images.
+
+## Architecture-sensitive components
+
+| Component | Windows x64 | Windows ARM64 | Notes |
+|---|---:|---:|---|
+| Electron 43 | Yes | Yes | Official Electron archives |
+| Koffi / foreground-window FFI | Yes | Yes | Prebuilt N-API packages; no compiler |
+| Sharp / libvips | Yes | Yes | `@img/sharp-win32-*` packages |
+| ONNX Runtime | Yes | Yes | Both payloads ship in `onnxruntime-node` |
+| GitHub Copilot CLI | Yes | Yes | `@github/copilot-win32-*` packages |
+| TypeScript, Rolldown, Lightning CSS | Yes | Yes | Native development packages exist for both |
+| Standalone FFmpeg / `ffmpeg-static` | No | No | Chromium replaced all current media uses |
+| Electron `ffmpeg.dll` codec library | Yes | Yes | LGPL-2.1+; standard Electron component and notices |
+
+`get-windows` remains an optional dependency for macOS/Linux. Windows uses Koffi
+to call `user32`, `dwmapi`, and `kernel32` directly, so a missing Windows
+`get-windows` prebuild cannot break installation or runtime capture.
+
+## Why native ARM64 installation now works
+
+The previous install blocker was `ffmpeg-static`, whose postinstall script had no
+Windows ARM64 binary. It has been removed from `package.json`, the lockfile,
+Vite externals, electron-builder unpack rules, and packaged output.
+
+Screen recording still uses Chromium's VP8/VP9 `MediaRecorder`. In parallel, the
+capture renderer reads the desktop track, deduplicates 1 fps snapshots, and writes
+a heartbeat at least every five seconds. Post-processing selects, crops, and
+deduplicates those JPEGs without decoding the WebM.
+
+Narration no longer shells out to FFmpeg either. A hidden Chromium renderer
+decodes Opus/WebM with `AudioContext`, downmixes/resamples to 16 kHz mono, and the
+main process performs silence detection before Whisper transcription.
+
+## Automated gate
+
+For each Windows architecture, CI:
+
+1. Installs native Node 24 and runs `npm ci`.
+2. Loads Sharp, ONNX Runtime, and Koffi.
+3. Runs unit tests and the production build.
+4. Builds the architecture-specific NSIS installer.
+5. Verifies the packaged PE machine type and the Sharp, ONNX, Koffi, and Copilot
+ payload architecture.
+6. Inspects loose and `app.asar` paths, fails if `ffmpeg-static` or a standalone
+ FFmpeg executable appears, and verifies Electron's codec DLL and license notices.
+
+Release publication is additionally gated on attaching the pinned LGPL source
+and relinking materials listed in [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).
+
+Local equivalents:
+
+```powershell
+npm ci
+npm test
+npm run build
+npm run dist:win:arm64 # on native Windows ARM64
+node scripts/verify-windows-package.mjs arm64
+```
+
+Use `dist:win:x64` and `x64` for the x64 package. Building each installer on its
+native runner ensures npm selects the correct optional native packages. The package
+scripts reject cross-architecture builds instead of producing an installer containing
+host-architecture Koffi, Sharp, or Copilot binaries.
+
+## Manual Windows ARM64 smoke test
+
+Automated packaging cannot validate desktop permissions or real foreground apps.
+Before a release, run this checklist on a physical Windows 11 ARM64 machine:
+
+1. Confirm `node -p "process.arch"` and the running Electron process both report
+ `arm64`.
+2. Start a two-minute recording, leave the screen static for at least 15 seconds,
+ then switch among a Win32 app, Settings, a browser, and an elevated app.
+3. Confirm `app.activate` records the owning process (not
+ `ApplicationFrameHost.exe` for Settings) and does not crash on the elevated app.
+4. Confirm `video.webm`, `video-frames.json`, periodic files under
+ `video-frames/`, and retained JPEGs under `frames/`.
+5. Request cropped frames from the Sessions analysis and verify exact crop
+ dimensions and readable text.
+6. Record narration, transcribe it, and confirm timestamped segments without a
+ system FFmpeg installation.
+7. Open a pre-change recording. With system FFmpeg installed, legacy frame
+ extraction should work; without it, the event-only analysis must still work
+ and log one actionable compatibility warning.
+
+## Known limitations
+
+- Browser URL capture still uses the existing Windows PowerShell UI Automation
+ sidecar. Core app/window tracking does not depend on PowerShell.
+- Snapshot information is capped by the intentional 1 fps desktop capture rate.
+ Asking for a higher sampling density cannot create additional visual detail.
+- A standalone system FFmpeg is optional and legacy-only; it is never downloaded,
+ bundled, or required for new recordings. Electron's standard LGPL codec DLL
+ remains part of the Chromium runtime.
diff --git a/common/correlation.ts b/common/correlation.ts
index 7975c74..e35e781 100644
--- a/common/correlation.ts
+++ b/common/correlation.ts
@@ -93,11 +93,11 @@ export const CORRELATION_DEFAULTS: Required<CorrelationOptions> = {
/** Sampling defaults for the two kinds of opportunistic probe. */
export const PROBE_DEFAULTS = {
- /** Unexplained-change probes: zoom in, sample densely. */
- padFps: 6,
+ /** Unexplained-change probes: inspect every available source snapshot. */
+ padFps: 1,
padMaxFrames: 24,
/** Event-less gap probes: cheap low-fps sweep just to notice change. */
- gapFps: 1.5,
+ gapFps: 1,
gapMaxFrames: 12,
} as const;
diff --git a/common/frames.ts b/common/frames.ts
index a457544..58c2e92 100644
--- a/common/frames.ts
+++ b/common/frames.ts
@@ -2,6 +2,28 @@
* optimization loop (correlation heuristic or the describer asking for more). */
export type FrameSource = "event" | "scene" | "probe";
+export const CAPTURED_FRAME_MANIFEST_VERSION = 1;
+
+/** One low-rate screen snapshot captured alongside the WebM recording. */
+export interface CapturedVideoFrame {
+ /** Path relative to the session directory. */
+ file: string;
+ /** Wall-clock epoch derived from the recorder's monotonic start anchor. */
+ tMs: number;
+ /** Monotonic offset from MediaRecorder start. */
+ offsetMs: number;
+ width: number;
+ height: number;
+}
+
+/** Versioned source-frame index written by the video recorder. */
+export interface CapturedFrameManifest {
+ version: typeof CAPTURED_FRAME_MANIFEST_VERSION;
+ format: "jpeg";
+ heartbeatMs: number;
+ frames: CapturedVideoFrame[];
+}
+
export interface FrameRecord {
/** Filename within the session's `frames/` directory. */
file: string;
diff --git a/common/ipc.ts b/common/ipc.ts
index 78a7036..7765e11 100644
--- a/common/ipc.ts
+++ b/common/ipc.ts
@@ -198,22 +198,16 @@ export interface DeleteSessionResult {
error?: string;
}
-export interface FfmpegInfo {
- ok: boolean;
- path: string | null;
- source: "system" | "bundled" | "missing";
-}
-
export interface CopilotInfo {
ok: boolean;
path: string | null;
}
-/** Whether the native window-tracking addon (get-windows) loaded for this platform. */
+/** Which foreground-window provider is available on this platform. */
export interface ActiveWindowInfo {
ok: boolean;
- /** The prebuilt binding path we resolved, for troubleshooting. */
- bindingPath: string | null;
+ provider: "koffi" | "get-windows" | "missing";
+ path: string | null;
error?: string;
}
@@ -237,7 +231,6 @@ export interface DoctorSource {
export interface DoctorReport {
platform: NodeJS.Platform;
- ffmpeg: FfmpegInfo;
copilotCli: CopilotInfo;
activeWindow: ActiveWindowInfo;
browserUrl: BrowserUrlInfo;
diff --git a/docs/windows-capture.md b/docs/windows-capture.md
index 1db3413..4f37a04 100644
--- a/docs/windows-capture.md
+++ b/docs/windows-capture.md
@@ -10,12 +10,12 @@ before trusting a Windows build.
| Source | Mechanism on Windows | Parity vs macOS | Permission |
|--------|----------------------|-----------------|------------|
-| App switches | `get-windows` native addon | Full | None |
-| Window titles | `get-windows` native addon | Full (better: no grant needed) | None |
+| App switches | Koffi calls to Win32 `user32` / `kernel32` | Full | None |
+| Window titles | Koffi calls to Win32 `user32` | Full (better: no grant needed) | None |
| Browser URLs | UI Automation address bar read (`powershell.exe` host) | Functional, not byte exact | None |
| Clipboard | Electron clipboard | Full | None |
-| Screen video + frames | `desktopCapturer` + ffmpeg + sharp | Full | Screen capture |
-| Voice narration (opt-in) | hidden-window `getUserMedia` mic + `MediaRecorder`, transcribed offline (Whisper via transformers.js) | Verified on Windows 11 ARM64 with the x64 Electron build | Microphone |
+| Screen video + frames | `desktopCapturer` + Chromium snapshots + Sharp | Full | Screen capture |
+| Voice narration (opt-in) | hidden-window `getUserMedia` + `MediaRecorder`; Chromium decode + offline Whisper | Full | Microphone |
Notes:
@@ -28,26 +28,21 @@ Notes:
## Prerequisites
-1. **Native window addon.** `get-windows` ships a prebuilt N-API binary per
- platform. On a Windows build/dev machine, `npm install` fetches
- `napi-*-win32-*-x64/node-get-windows.node`. If it is missing, `get-windows`
- silently returns no-op stubs and app-switch tracking dies with no error, so
- the doctor check below exists specifically to catch that.
+1. **Native window FFI.** Koffi ships prebuilt N-API packages for both
+ `win32-x64` and `win32-arm64`; no compiler is needed.
2. **Windows PowerShell.** `powershell.exe` (Windows PowerShell 5.1, in-box on
every Windows 10/11) is used to host the UI Automation URL reader. No install
needed.
3. **Copilot CLI** on `PATH` for the describer (`copilot`).
-4. **ffmpeg** is bundled via `ffmpeg-static`; no system install needed.
+4. No system media package is needed for new recordings.
## Doctor signals
Open the recorder HUD and read the doctor rows (or call `doctor()` over IPC).
On Windows, confirm:
-- **window tracking** = `native` (not `addon missing`). `addon missing` means the
- `get-windows` `.node` did not resolve, which is a packaging or install problem.
+- **window tracking** = `koffi` (not `provider missing`).
- **browser URLs** = `uia` when the capture level includes URLs.
-
## Live smoke test
Run a real recording on Windows and verify each source lands in the session's
@@ -62,7 +57,8 @@ Run a real recording on Windows and verify each source lands in the session's
Typing a partial URL or a search term should not emit a bogus event.
4. **Clipboard.** Copy some text. Expect a `clipboard.change` event with a
preview and hash.
-5. **Video.** Confirm a `.webm` is written and `frame.captured` events appear.
+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 &
@@ -79,24 +75,27 @@ unavailable on this platform", or a reduced-capture notice).
## Packaging
-`package.json` `build` configures electron-builder for both `mac` and `win`
-(nsis x64). Native modules (`get-windows`, `sharp`, `@img/*`, `ffmpeg-static`,
-`@huggingface/transformers`, `onnxruntime-node`) are listed under `asarUnpack` so
+`package.json` configures electron-builder for macOS and Windows NSIS. Native
+modules (`koffi`, `@koromix/*`, `sharp`, `@img/*`,
+`@huggingface/transformers`, `onnxruntime-node`, and Copilot platform packages)
+are listed under `asarUnpack` so
their binaries load from disk rather than from inside the asar archive. The
Whisper model itself is not bundled. It downloads to the app's user-data
`models` folder only after the user approves the one-time ~250 MB download from
the HUD or Sessions; recording and core session processing do not wait for it.
-Build the Windows installer on Windows (or a Windows CI runner) so the native
-binaries for `win32-x64` are present:
+Build each Windows installer on its matching native machine or CI runner so npm
+selects the correct optional packages:
```powershell
npm ci
-npm run dist
+npm run dist:win:x64
+# or, on Windows ARM64:
+npm run dist:win:arm64
```
-Cross building the Windows target from macOS will not fetch the Windows native
-binaries and is not supported here.
+The Windows workflow uses `windows-latest` and `windows-11-arm`, then verifies the
+PE architecture and packaged native payloads.
## Known limitations
@@ -105,15 +104,11 @@ binaries and is not supported here.
approach is tracked in issue #7.
- Semantic UI events (focus/invoke/value via UI Automation) are not implemented
on either platform yet.
-- Voice narration is verified end to end on macOS and Windows 11 ARM64 running the
- supported x64 Electron build (mic capture -> `audio.webm` -> offline Whisper
- transcription -> `narration.json`). `onnxruntime-node` ships prebuilt binaries
- for `win32-x64`/`win32-arm64`, so no compiler is needed there.
-- A live smoke test on Windows 11 ARM64 covered the supported x64 Electron build,
- `get-windows` native-addon loading, ffmpeg-backed video and frames, microphone
- audio persistence, explicit Whisper download and offline transcription, and
- Copilot analysis. Browser URL and clipboard capture were not re-verified in
- that test; use the checklist above when validating those sources.
+- `onnxruntime-node` ships prebuilt binaries for `win32-x64` and
+ `win32-arm64`, so narration transcription needs no compiler.
+- A standalone system FFmpeg is consulted only for frame extraction from recordings
+ created before `video-frames.json` existed. It is never bundled or downloaded;
+ Electron's standard LGPL `ffmpeg.dll` codec component remains in the runtime.
- The Windows paths are also validated by typecheck, a PowerShell parse check of
the UIA script, and a `win32` describer eval
(`evals/scenarios/windows-deploy.ts`).
diff --git a/electron/audio/capture-preload.cjs b/electron/audio/capture-preload.cjs
index ab55241..17cd8f4 100644
--- a/electron/audio/capture-preload.cjs
+++ b/electron/audio/capture-preload.cjs
@@ -4,6 +4,7 @@
// chunks back to the main process, which writes them to disk. Channel names
// mirror electron/audio/recorder.ts.
const { ipcRenderer } = require("electron");
+const { readFile } = require("node:fs/promises");
/** @type {MediaRecorder | null} */
let recorder = null;
@@ -84,3 +85,64 @@ ipcRenderer.on("audio:stop", () => {
ipcRenderer.send("audio:stopped");
}
});
+
+ipcRenderer.on("audio:decode", async (_event, opts) => {
+ const { id, audioPath, sampleRate, chunkSamples } = opts || {};
+ let context = null;
+ try {
+ if (
+ typeof id !== "string" ||
+ typeof audioPath !== "string" ||
+ !Number.isSafeInteger(sampleRate) ||
+ !Number.isSafeInteger(chunkSamples)
+ ) {
+ throw new Error("Invalid audio decode request.");
+ }
+ const encoded = await readFile(audioPath);
+ const input = encoded.buffer.slice(
+ encoded.byteOffset,
+ encoded.byteOffset + encoded.byteLength,
+ );
+ const AudioContextClass = globalThis.AudioContext || globalThis.webkitAudioContext;
+ if (!AudioContextClass) throw new Error("Chromium AudioContext is unavailable.");
+ // Let Chromium's audio pipeline perform the band-limited resample. Linear
+ // interpolation here would alias frequencies above the 8 kHz Nyquist limit.
+ context = new AudioContextClass({ sampleRate });
+ const decoded = await context.decodeAudioData(input);
+ if (decoded.sampleRate !== sampleRate) {
+ throw new Error(
+ `Chromium decoded narration at ${decoded.sampleRate} Hz instead of ${sampleRate} Hz.`,
+ );
+ }
+ const outputLength = decoded.length;
+ if (outputLength <= 0) throw new Error("Narration audio decoded to zero samples.");
+
+ const channels = Array.from(
+ { length: decoded.numberOfChannels },
+ (_unused, index) => decoded.getChannelData(index),
+ );
+ ipcRenderer.send("audio:decode-meta", id, outputLength);
+ for (let offset = 0; offset < outputLength; offset += chunkSamples) {
+ const length = Math.min(chunkSamples, outputLength - offset);
+ const output = new Float32Array(length);
+ for (let index = 0; index < length; index++) {
+ let value = 0;
+ for (const channel of channels) {
+ value += channel[offset + index];
+ }
+ output[index] = value / channels.length;
+ }
+ ipcRenderer.send("audio:decode-chunk", id, offset, output);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ ipcRenderer.send("audio:decode-done", id);
+ } catch (err) {
+ ipcRenderer.send(
+ "audio:decode-error",
+ id,
+ err instanceof Error ? err.message : String(err),
+ );
+ } finally {
+ if (context) await context.close().catch(() => undefined);
+ }
+});
diff --git a/electron/audio/decode.ts b/electron/audio/decode.ts
new file mode 100644
index 0000000..a809b77
--- /dev/null
+++ b/electron/audio/decode.ts
@@ -0,0 +1,114 @@
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { BrowserWindow, ipcMain, type IpcMainEvent } from "electron";
+
+const dirname = path.dirname(fileURLToPath(import.meta.url));
+const SAMPLE_RATE = 16_000;
+const CHUNK_SAMPLES = 256 * 1024;
+const MAX_SAMPLES = 256 * 1024 * 1024;
+const DECODE_TIMEOUT_MS = 10 * 60_000;
+
+/** Decode and downmix a WebM narration file through Chromium's built-in codecs. */
+export async function decodeAudioFile(audioPath: string): Promise<Float32Array> {
+ const id = randomUUID();
+ const win = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ preload: path.join(dirname, "audio", "capture-preload.cjs"),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: false,
+ backgroundThrottling: false,
+ },
+ });
+
+ let samples: Float32Array | null = null;
+ let received = 0;
+ let settled = false;
+ let timeout: NodeJS.Timeout | undefined;
+ let removeListeners = () => undefined;
+
+ const result = new Promise<Float32Array>((resolve, reject) => {
+ const finish = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ if (timeout) clearTimeout(timeout);
+ if (error) reject(error);
+ else if (!samples || received < samples.length) {
+ reject(new Error(`Audio decoder returned ${received} of ${samples?.length ?? 0} samples.`));
+ } else {
+ resolve(samples);
+ }
+ };
+
+ const owns = (event: IpcMainEvent, jobId: string) =>
+ event.sender === win.webContents && jobId === id;
+
+ const onMeta = (event: IpcMainEvent, jobId: string, length: number) => {
+ if (!owns(event, jobId)) return;
+ if (!Number.isSafeInteger(length) || length <= 0 || length > MAX_SAMPLES) {
+ finish(new Error(`Decoded narration length is invalid: ${length}.`));
+ return;
+ }
+ samples = new Float32Array(length);
+ };
+ const onChunk = (
+ event: IpcMainEvent,
+ jobId: string,
+ offset: number,
+ chunk: Float32Array,
+ ) => {
+ if (!owns(event, jobId) || !samples || !(chunk instanceof Float32Array)) return;
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + chunk.length > samples.length) {
+ finish(new Error("Audio decoder returned an out-of-range sample chunk."));
+ return;
+ }
+ samples.set(chunk, offset);
+ received += chunk.length;
+ };
+ const onDone = (event: IpcMainEvent, jobId: string) => {
+ if (owns(event, jobId)) finish();
+ };
+ const onError = (event: IpcMainEvent, jobId: string, error: string) => {
+ if (owns(event, jobId)) finish(new Error(error || "Chromium audio decode failed."));
+ };
+
+ ipcMain.on("audio:decode-meta", onMeta);
+ ipcMain.on("audio:decode-chunk", onChunk);
+ ipcMain.on("audio:decode-done", onDone);
+ ipcMain.on("audio:decode-error", onError);
+ win.once("closed", () => finish(new Error("Audio decoder window closed unexpectedly.")));
+ removeListeners = () => {
+ ipcMain.removeListener("audio:decode-meta", onMeta);
+ ipcMain.removeListener("audio:decode-chunk", onChunk);
+ ipcMain.removeListener("audio:decode-done", onDone);
+ ipcMain.removeListener("audio:decode-error", onError);
+ };
+
+ timeout = setTimeout(
+ () => finish(new Error("Narration audio decode timed out.")),
+ DECODE_TIMEOUT_MS,
+ );
+
+ void win
+ .loadFile(path.join(dirname, "audio", "capture.html"))
+ .then(() => {
+ win.webContents.send("audio:decode", {
+ id,
+ audioPath,
+ sampleRate: SAMPLE_RATE,
+ chunkSamples: CHUNK_SAMPLES,
+ });
+ })
+ .catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
+ });
+
+ try {
+ return await result;
+ } finally {
+ removeListeners();
+ if (!win.isDestroyed()) win.destroy();
+ }
+}
diff --git a/electron/collectors/active-window.ts b/electron/collectors/active-window.ts
index 4c2a34b..aa7c6d1 100644
--- a/electron/collectors/active-window.ts
+++ b/electron/collectors/active-window.ts
@@ -1,7 +1,6 @@
-import { activeWindow, type Result } from "get-windows";
-
import type { Collector, CollectorContext } from "../recorder/collector";
import { createUrlProvider, type UrlProvider } from "./url-provider";
+import type { ActiveWindowResult } from "./window-info";
/** Base cadence for app/title polling. Browsers poll slower (see below). */
const POLL_MS = 1000;
@@ -19,6 +18,11 @@ const URL_MIN_INTERVAL_MS = 1500;
/** get-windows options for each capture mode. */
const FULL = { accessibilityPermission: true, screenRecordingPermission: true } as const;
const DEGRADED = { accessibilityPermission: false, screenRecordingPermission: false } as const;
+const GET_WINDOWS_PACKAGE = "get-windows";
+
+interface GetWindowsModule {
+ activeWindow(options: typeof FULL | typeof DEGRADED): Promise<ActiveWindowResult | undefined>;
+}
interface Bounds {
x: number;
@@ -106,16 +110,25 @@ export class ActiveWindowCollector implements Collector {
this.timer = setTimeout(() => void this.poll(), delay);
}
- private async read(): Promise<Result | undefined> {
+ private async readPlatform(): Promise<ActiveWindowResult | undefined> {
+ if (process.platform === "win32") {
+ const { readWindowsActiveWindow } = await import("./windows-active-window");
+ return readWindowsActiveWindow();
+ }
+ const { activeWindow } = await import(GET_WINDOWS_PACKAGE) as GetWindowsModule;
+ return activeWindow(this.mode === "full" ? FULL : DEGRADED);
+ }
+
+ private async read(): Promise<ActiveWindowResult | undefined> {
try {
- return await activeWindow(this.mode === "full" ? FULL : DEGRADED);
+ return await this.readPlatform();
} catch (err) {
- if (this.mode === "full") {
+ if (process.platform !== "win32" && this.mode === "full") {
this.mode = "degraded";
this.ctx?.log.warn(
"Reduced capture: window titles/URLs need a screen-capture / accessibility permission.",
);
- return activeWindow(DEGRADED);
+ return this.readPlatform();
}
throw err;
}
@@ -138,7 +151,7 @@ export class ActiveWindowCollector implements Collector {
}
}
- private process(win: Result): void {
+ private process(win: ActiveWindowResult): void {
if (!this.ctx) return;
const owner = (win.owner ?? {}) as {
name?: string;
@@ -148,7 +161,7 @@ export class ActiveWindowCollector implements Collector {
};
const app = owner.name || "unknown";
const title = this.captureTitles ? (win.title ?? "") : "";
- const bounds = (win as { bounds?: Bounds }).bounds;
+ const bounds = win.bounds as Bounds | undefined;
const appChanged = app !== this.lastApp;
const titleChanged = !!title && title !== this.lastTitle;
diff --git a/electron/collectors/window-info.ts b/electron/collectors/window-info.ts
new file mode 100644
index 0000000..f494c7e
--- /dev/null
+++ b/electron/collectors/window-info.ts
@@ -0,0 +1,16 @@
+export interface ActiveWindowResult {
+ title: string;
+ id: number;
+ bounds?: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ owner?: {
+ name?: string;
+ processId?: number;
+ path?: string;
+ bundleId?: string;
+ };
+}
diff --git a/electron/collectors/windows-active-window.ts b/electron/collectors/windows-active-window.ts
new file mode 100644
index 0000000..5170b4c
--- /dev/null
+++ b/electron/collectors/windows-active-window.ts
@@ -0,0 +1,156 @@
+import path from "node:path";
+
+import koffi from "koffi";
+
+import type { ActiveWindowResult } from "./window-info";
+
+const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
+const GW_CHILD = 5;
+const GW_HWNDNEXT = 2;
+const DWMWA_EXTENDED_FRAME_BOUNDS = 9;
+const MAX_TEXT_CHARS = 32_768;
+const MAX_UWP_CHILDREN = 256;
+
+const user32 = koffi.load("user32.dll");
+const kernel32 = koffi.load("kernel32.dll");
+const dwmapi = koffi.load("dwmapi.dll");
+
+const getForegroundWindow = user32.func("GetForegroundWindow", "void *", []);
+const getWindow = user32.func("GetWindow", "void *", ["void *", "uint32"]);
+const getWindowThreadProcessId = user32.func(
+ "GetWindowThreadProcessId",
+ "uint32",
+ ["void *", "void *"],
+);
+const getWindowTextLength = user32.func("GetWindowTextLengthW", "int32", ["void *"]);
+const getWindowText = user32.func(
+ "GetWindowTextW",
+ "int32",
+ ["void *", "void *", "int32"],
+);
+const getWindowRect = user32.func("GetWindowRect", "int32", ["void *", "void *"]);
+const dwmGetWindowAttribute = dwmapi.func(
+ "DwmGetWindowAttribute",
+ "int32",
+ ["void *", "uint32", "void *", "uint32"],
+);
+const openProcess = kernel32.func(
+ "OpenProcess",
+ "void *",
+ ["uint32", "int32", "uint32"],
+);
+const queryFullProcessImageName = kernel32.func(
+ "QueryFullProcessImageNameW",
+ "int32",
+ ["void *", "uint32", "void *", "void *"],
+);
+const closeHandle = kernel32.func("CloseHandle", "int32", ["void *"]);
+
+const DISPLAY_NAMES: Record<string, string> = {
+ chrome: "Google Chrome",
+ msedge: "Microsoft Edge",
+ firefox: "Firefox",
+ brave: "Brave",
+ opera: "Opera",
+ vivaldi: "Vivaldi",
+ code: "Visual Studio Code",
+ explorer: "File Explorer",
+ applicationframehost: "Windows app",
+};
+
+/** Native Win32 foreground-window lookup with a prebuilt ARM64 N-API FFI. */
+export function readWindowsActiveWindow(): ActiveWindowResult | undefined {
+ let window = getForegroundWindow();
+ if (!window) return undefined;
+
+ let processId = processIdFor(window);
+ let processPath = processPathFor(processId);
+ if (path.win32.basename(processPath).toLowerCase() === "applicationframehost.exe") {
+ const child = findUwpOwner(window, processId);
+ if (child) {
+ window = child;
+ processId = processIdFor(child);
+ processPath = processPathFor(processId);
+ }
+ }
+
+ const executable = path.win32.basename(processPath, path.win32.extname(processPath));
+ const normalized = executable.toLowerCase();
+ const name = (DISPLAY_NAMES[normalized] ?? executable) || "unknown";
+ return {
+ title: windowTitle(window),
+ id: Number(koffi.address(window)),
+ bounds: windowBounds(window),
+ owner: {
+ name,
+ processId,
+ path: processPath,
+ },
+ };
+}
+
+function processIdFor(window: unknown): number {
+ const output = Buffer.alloc(4);
+ getWindowThreadProcessId(window, output);
+ return output.readUInt32LE(0);
+}
+
+function processPathFor(processId: number): string {
+ if (!processId) return "";
+ const processHandle = openProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, processId);
+ if (!processHandle) return "";
+ try {
+ const output = Buffer.alloc(MAX_TEXT_CHARS * 2);
+ const size = Buffer.alloc(4);
+ size.writeUInt32LE(MAX_TEXT_CHARS);
+ if (!queryFullProcessImageName(processHandle, 0, output, size)) return "";
+ return output.subarray(0, size.readUInt32LE(0) * 2).toString("utf16le");
+ } finally {
+ closeHandle(processHandle);
+ }
+}
+
+function windowTitle(window: unknown): string {
+ const length = Math.min(MAX_TEXT_CHARS - 1, Math.max(0, getWindowTextLength(window)));
+ if (length === 0) return "";
+ const output = Buffer.alloc((length + 1) * 2);
+ const written = getWindowText(window, output, length + 1);
+ return written > 0 ? output.subarray(0, written * 2).toString("utf16le") : "";
+}
+
+function windowBounds(window: unknown): ActiveWindowResult["bounds"] {
+ const rect = Buffer.alloc(16);
+ const dwmResult = dwmGetWindowAttribute(
+ window,
+ DWMWA_EXTENDED_FRAME_BOUNDS,
+ rect,
+ rect.byteLength,
+ );
+ if (dwmResult !== 0 && !getWindowRect(window, rect)) return undefined;
+ const left = rect.readInt32LE(0);
+ const top = rect.readInt32LE(4);
+ const right = rect.readInt32LE(8);
+ const bottom = rect.readInt32LE(12);
+ return {
+ x: left,
+ y: top,
+ width: Math.max(0, right - left),
+ height: Math.max(0, bottom - top),
+ };
+}
+
+function findUwpOwner(root: unknown, frameHostProcessId: number): unknown | null {
+ const queue: unknown[] = [root];
+ let visited = 0;
+ while (queue.length > 0 && visited < MAX_UWP_CHILDREN) {
+ const parent = queue.shift();
+ let child = getWindow(parent, GW_CHILD);
+ while (child && visited++ < MAX_UWP_CHILDREN) {
+ const childProcessId = processIdFor(child);
+ if (childProcessId && childProcessId !== frameHostProcessId) return child;
+ queue.push(child);
+ child = getWindow(child, GW_HWNDNEXT);
+ }
+ }
+ return null;
+}
diff --git a/electron/describer/describer.ts b/electron/describer/describer.ts
index 3b00f3f..eec0774 100644
--- a/electron/describer/describer.ts
+++ b/electron/describer/describer.ts
@@ -1,6 +1,7 @@
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import path from "node:path";
+import { CAPTURED_FRAME_MANIFEST_VERSION } from "../../common/frames";
import { approveAll, CopilotClient, type CopilotSession } from "@github/copilot-sdk";
import {
@@ -41,6 +42,8 @@ interface VideoMeta {
file: string;
startEpoch: number;
durationMs: number;
+ framesFile?: string;
+ framesVersion?: number;
}
/** A live, resumable analysis session for one recording. */
@@ -365,9 +368,16 @@ function buildExtractor(sessionDir: string): FrameExtractor | null {
const video = readJson<VideoMeta>(path.join(sessionDir, "video.json"));
if (!video) return null;
const videoPath = path.join(sessionDir, video.file);
- if (!existsSync(videoPath)) return null;
+ const capturedFramesPath = video.framesFile
+ ? path.join(sessionDir, video.framesFile)
+ : undefined;
+ const hasVideo = existsSync(videoPath);
+ const hasCapturedFrames = Boolean(capturedFramesPath && existsSync(capturedFramesPath));
+ if (!hasVideo && !hasCapturedFrames) return null;
return new FrameExtractor({
- videoPath,
+ ...(hasVideo ? { videoPath } : {}),
+ ...(hasCapturedFrames ? { capturedFramesPath } : {}),
+ capturedFramesExpected: video.framesVersion === CAPTURED_FRAME_MANIFEST_VERSION,
framesDir: path.join(sessionDir, "frames"),
anchorEpochMs: video.startEpoch,
durationSec: video.durationMs > 0 ? video.durationMs / 1000 : undefined,
diff --git a/electron/describer/tools.ts b/electron/describer/tools.ts
index c764222..8362bab 100644
--- a/electron/describer/tools.ts
+++ b/electron/describer/tools.ts
@@ -187,13 +187,13 @@ export function createDescriberTools(ctx: ToolContext): Tool[] {
const getFrames: Tool = {
name: "get_frames",
description:
- "Sample and VIEW screen frames within a time window [fromMs, toMs] (atMs, ms since recording start). Densely re-samples the window if needed (optional `fps`, default 6) and returns the frames inline as images so you can see the screen. Optional `crop` {x,y,w,h} zooms a region. Use only where events are ambiguous.",
+ "Sample and VIEW the available 1 fps screen snapshots within a time window [fromMs, toMs] (atMs, ms since recording start) and return them inline as images. Optional `fps` can reduce sampling density but cannot add detail beyond the 1 fps capture. Optional `crop` {x,y,w,h} zooms a region. Use only where events are ambiguous.",
parameters: {
type: "object",
properties: {
fromMs: { type: "number", description: "Window start (atMs)." },
toMs: { type: "number", description: "Window end (atMs)." },
- fps: { type: "number", description: "Sampling density (frames/sec). Default 6." },
+ fps: { type: "number", description: "Sampling density up to the 1 fps source rate. Default 1." },
crop: {
type: "object",
properties: {
diff --git a/electron/doctor.ts b/electron/doctor.ts
index 3b5be6d..cc8231d 100644
--- a/electron/doctor.ts
+++ b/electron/doctor.ts
@@ -1,7 +1,6 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { createRequire } from "node:module";
-import path from "node:path";
import { CAPTURE_SOURCES, FULL_CAPTURE } from "../common/config";
import type {
@@ -10,7 +9,6 @@ import type {
CopilotInfo,
DoctorReport,
DoctorSource,
- FfmpegInfo,
} from "../common/ipc";
import { browserUrlProviderKind } from "./collectors/url-provider";
import { sessionsRoot } from "./recorder/session-store";
@@ -29,43 +27,27 @@ function which(cmd: string): string | null {
}
}
-function checkFfmpeg(): FfmpegInfo {
- let bundled: string | null = null;
- try {
- // ffmpeg-static's default export is the absolute path to a bundled binary.
- bundled = require("ffmpeg-static") as string;
- } catch {
- bundled = null;
- }
- if (bundled && existsSync(bundled)) return { ok: true, path: bundled, source: "bundled" };
- const sys = which("ffmpeg");
- if (sys) return { ok: true, path: sys, source: "system" };
- return { ok: false, path: null, source: "missing" };
-}
-
function checkCopilot(): CopilotInfo {
const p = which("copilot");
return { ok: Boolean(p), path: p };
}
-/**
- * Verify the get-windows native addon is actually present for this platform.
- * get-windows silently falls back to no-op stubs when its prebuilt `.node` is
- * missing (e.g. a packaging miss), which would make app-switch tracking die
- * with no error — so we resolve the exact binding path and check it exists.
- */
function checkActiveWindow(): ActiveWindowInfo {
try {
- const gwIndex = require.resolve("get-windows");
- // Resolve node-pre-gyp from get-windows's own scope so we find the exact copy
- // it uses, whether the dependency is hoisted or nested.
- const gwRequire = createRequire(gwIndex);
- const preGyp = gwRequire("@mapbox/node-pre-gyp") as { find(pkg: string): string };
- const pkgJson = path.join(path.dirname(gwIndex), "package.json");
- const bindingPath = preGyp.find(pkgJson);
- return { ok: existsSync(bindingPath), bindingPath };
+ if (process.platform === "win32") {
+ const modulePath = require.resolve("koffi");
+ require("koffi");
+ return { ok: true, provider: "koffi", path: modulePath };
+ }
+ const modulePath = require.resolve("get-windows");
+ return { ok: existsSync(modulePath), provider: "get-windows", path: modulePath };
} catch (err) {
- return { ok: false, bindingPath: null, error: err instanceof Error ? err.message : String(err) };
+ return {
+ ok: false,
+ provider: "missing",
+ path: null,
+ error: err instanceof Error ? err.message : String(err),
+ };
}
}
@@ -94,7 +76,6 @@ export function runDoctor(): DoctorReport {
return {
platform: process.platform,
- ffmpeg: checkFfmpeg(),
copilotCli: checkCopilot(),
activeWindow: checkActiveWindow(),
browserUrl,
diff --git a/electron/frames/extractor.test.ts b/electron/frames/extractor.test.ts
new file mode 100644
index 0000000..122a14e
--- /dev/null
+++ b/electron/frames/extractor.test.ts
@@ -0,0 +1,171 @@
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import sharp from "sharp";
+
+import type { CapturedVideoFrame } from "../../common/frames";
+import { FrameExtractor, nearestCapturedFrame, sampleCapturedFrames } from "./extractor";
+
+const frame = (file: string, tMs: number): CapturedVideoFrame => ({
+ file,
+ tMs,
+ offsetMs: tMs - 1000,
+ width: 1280,
+ height: 720,
+});
+
+test("nearestCapturedFrame chooses the closest source and prefers the earlier tie", () => {
+ const frames = [frame("a.jpg", 1000), frame("b.jpg", 2000), frame("c.jpg", 3000)];
+ assert.equal(nearestCapturedFrame(frames, 1750)?.file, "b.jpg");
+ assert.equal(nearestCapturedFrame(frames, 2500)?.file, "b.jpg");
+ assert.equal(nearestCapturedFrame(frames, 500)?.file, "a.jpg");
+ assert.equal(nearestCapturedFrame(frames, 5000)?.file, "c.jpg");
+});
+
+test("sampleCapturedFrames never duplicates a 1 fps source when asked for 6 fps", () => {
+ const frames = [
+ frame("a.jpg", 1000),
+ frame("b.jpg", 2000),
+ frame("c.jpg", 3000),
+ frame("d.jpg", 4000),
+ ];
+ const samples = sampleCapturedFrames(frames, 1000, 4000, 6, 24);
+ assert.deepEqual(samples.map((sample) => sample.frame.file), [
+ "a.jpg",
+ "b.jpg",
+ "c.jpg",
+ "d.jpg",
+ ]);
+ assert.equal(new Set(samples.map((sample) => sample.frame.file)).size, samples.length);
+});
+
+test("sampleCapturedFrames returns the nearest static heartbeat for an empty window", () => {
+ const samples = sampleCapturedFrames([frame("only.jpg", 1000)], 5000, 6000, 1, 4);
+ assert.equal(samples.length, 1);
+ assert.equal(samples[0].frame.file, "only.jpg");
+ assert.equal(samples[0].targetMs, 5000);
+});
+
+test("FrameExtractor safely reuses one portable source snapshot for multiple events", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "skill-recorder-frames-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const sourceDir = path.join(root, "video-frames");
+ const framesDir = path.join(root, "frames");
+ await Promise.all([
+ mkdir(sourceDir, { recursive: true }),
+ mkdir(framesDir, { recursive: true }),
+ ]);
+ await writeFile(path.join(sourceDir, "source.jpg"), "test frame");
+ const manifestPath = path.join(root, "video-frames.json");
+ await writeFile(
+ manifestPath,
+ JSON.stringify({
+ version: 1,
+ format: "jpeg",
+ heartbeatMs: 5000,
+ frames: [
+ null,
+ {
+ file: "video-frames\\source.jpg",
+ tMs: 1600,
+ offsetMs: 600,
+ width: 1280,
+ height: 720,
+ },
+ ],
+ }),
+ );
+
+ const extractor = new FrameExtractor({
+ capturedFramesPath: manifestPath,
+ framesDir,
+ anchorEpochMs: 1000,
+ });
+ const added = await extractor.extractAtEpochs([{ tMs: 1500 }, { tMs: 2500 }]);
+
+ assert.equal(added.length, 1);
+ assert.equal(extractor.manifest.length, 1);
+ assert.equal(added[0].tMs, 1600);
+ assert.equal(added[0].offsetSec, 0.6);
+ assert.equal(existsSync(path.join(framesDir, added[0].file)), true);
+});
+
+test("FrameExtractor drops malformed retained frame records", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "skill-recorder-retained-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ await mkdir(root, { recursive: true });
+ await writeFile(
+ path.join(root, "frames.json"),
+ JSON.stringify([
+ null,
+ {
+ file: "event_500.jpg",
+ tMs: 1500,
+ offsetSec: 0.5,
+ source: "event",
+ phash: "",
+ },
+ ]),
+ );
+
+ const extractor = new FrameExtractor({ framesDir: root, anchorEpochMs: 1000 });
+ assert.deepEqual(extractor.manifest.map((entry) => entry.file), ["event_500.jpg"]);
+});
+
+test("FrameExtractor deduplicates identical source JPEGs without deleting retained files", async (t) => {
+ const root = await mkdtemp(path.join(tmpdir(), "skill-recorder-dedupe-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const sourceDir = path.join(root, "video-frames");
+ const framesDir = path.join(root, "frames");
+ await Promise.all([
+ mkdir(sourceDir, { recursive: true }),
+ mkdir(framesDir, { recursive: true }),
+ ]);
+ const jpeg = await sharp({
+ create: {
+ width: 32,
+ height: 32,
+ channels: 3,
+ background: { r: 30, g: 90, b: 150 },
+ },
+ })
+ .jpeg()
+ .toBuffer();
+ await Promise.all([
+ writeFile(path.join(sourceDir, "one.jpg"), jpeg),
+ writeFile(path.join(sourceDir, "two.jpg"), jpeg),
+ ]);
+ const manifestPath = path.join(root, "video-frames.json");
+ await writeFile(
+ manifestPath,
+ JSON.stringify({
+ version: 1,
+ format: "jpeg",
+ heartbeatMs: 5000,
+ frames: [
+ { file: "video-frames/one.jpg", tMs: 1600, offsetMs: 600, width: 32, height: 32 },
+ { file: "video-frames/two.jpg", tMs: 3600, offsetMs: 2600, width: 32, height: 32 },
+ ],
+ }),
+ );
+ const options = {
+ capturedFramesPath: manifestPath,
+ framesDir,
+ anchorEpochMs: 1000,
+ };
+ const events = [{ tMs: 1600 }, { tMs: 3600 }];
+ const extractor = new FrameExtractor(options);
+
+ assert.equal((await extractor.extractAtEpochs(events)).length, 1);
+ assert.equal(extractor.manifest.length, 1);
+ assert.equal(existsSync(path.join(framesDir, extractor.manifest[0].file)), true);
+ assert.equal((await extractor.extractAtEpochs(events)).length, 0);
+
+ const reloaded = new FrameExtractor(options);
+ assert.equal((await reloaded.extractAtEpochs(events)).length, 0);
+ assert.equal(reloaded.manifest.length, 1);
+ assert.equal(existsSync(path.join(framesDir, reloaded.manifest[0].file)), true);
+});
diff --git a/electron/frames/extractor.ts b/electron/frames/extractor.ts
index e591593..eabefe3 100644
--- a/electron/frames/extractor.ts
+++ b/electron/frames/extractor.ts
@@ -1,20 +1,23 @@
-import { execFile } from "node:child_process";
+import { execFile, execFileSync } from "node:child_process";
+import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
-import { unlink } from "node:fs/promises";
+import { copyFile, unlink } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { promisify } from "node:util";
-import type { FrameRecord, FrameSource } from "../../common/frames";
+import {
+ CAPTURED_FRAME_MANIFEST_VERSION,
+ type CapturedVideoFrame,
+ type FrameRecord,
+ type FrameSource,
+} from "../../common/frames";
import { createLogger } from "../logger";
const log = createLogger("Frames");
const require = createRequire(import.meta.url);
const execFileAsync = promisify(execFile);
-const ffmpegPath = require("ffmpeg-static") as string;
-// sharp is native and externalized; require it lazily so a load failure degrades
-// to "no dedupe" rather than crashing extraction.
type Sharp = typeof import("sharp");
let sharpMod: Sharp | null | undefined;
function sharp(): Sharp | null {
@@ -22,15 +25,24 @@ function sharp(): Sharp | null {
try {
sharpMod = require("sharp") as Sharp;
} catch (err) {
- log.warn("sharp unavailable; perceptual dedupe disabled:", err instanceof Error ? err.message : err);
+ log.warn("sharp unavailable; frame crops and perceptual dedupe disabled:", message(err));
sharpMod = null;
}
}
return sharpMod;
}
+interface SourceFrame extends CapturedVideoFrame {
+ absolutePath: string;
+}
+
export interface ExtractorOptions {
- videoPath: string;
+ /** Retained for pre-change recordings that need a system-FFmpeg fallback. */
+ videoPath?: string;
+ /** Absolute path to the versioned source-frame manifest. */
+ capturedFramesPath?: string;
+ /** Suppress the system-FFmpeg legacy path for current recordings with no snapshots. */
+ capturedFramesExpected?: boolean;
framesDir: string;
/** `video.json` startEpoch — the wall-clock anchor for offset↔epoch mapping. */
anchorEpochMs: number;
@@ -38,61 +50,121 @@ export interface ExtractorOptions {
durationSec?: number;
/** dHash Hamming distance under which two frames count as duplicates. */
dedupeThreshold?: number;
- /** Hard cap on retained frames, so the adaptive loop can't run away. */
+ /** Hard cap on retained frames, so the adaptive loop cannot run away. */
maxFrames?: number;
- /** Event anchors within this many seconds of each other collapse to one
- * extraction (≈ one source frame at the video's low fps). Default 0.5. */
+ /** Event anchors within this many seconds collapse to one extraction. */
frameGridSec?: number;
}
export interface WindowRequest {
- /** Window start/end as wall-clock epochs (ms). */
startMs: number;
endMs: number;
- /** Sampling density within the window (frames per second). */
+ /** Requested density; source information is capped by the 1 fps recorder. */
fps?: number;
- /** Upper bound on frames pulled from this window. */
maxFrames?: number;
- /** Optional pixel crop to "zoom" into a region of interest. */
crop?: { x: number; y: number; w: number; h: number };
reason?: string;
}
-const DEFAULTS = { dedupeThreshold: 8, maxFrames: 300, sceneThreshold: 0.4, frameGridSec: 0.5 };
+export interface CapturedFrameSample<T extends CapturedVideoFrame = CapturedVideoFrame> {
+ frame: T;
+ targetMs: number;
+}
+
+const DEFAULTS = { dedupeThreshold: 8, maxFrames: 300, frameGridSec: 0.5 };
+const DEFAULT_WINDOW_FPS = 1;
+const DEFAULT_WINDOW_MAX_FRAMES = 24;
+
+export function nearestCapturedFrame<T extends CapturedVideoFrame>(
+ frames: readonly T[],
+ targetMs: number,
+): T | null {
+ if (frames.length === 0) return null;
+ let low = 0;
+ let high = frames.length - 1;
+ while (low <= high) {
+ const mid = Math.floor((low + high) / 2);
+ if (frames[mid].tMs < targetMs) low = mid + 1;
+ else high = mid - 1;
+ }
+ if (low === 0) return frames[0];
+ if (low === frames.length) return frames[frames.length - 1];
+ const before = frames[low - 1];
+ const after = frames[low];
+ return targetMs - before.tMs <= after.tMs - targetMs ? before : after;
+}
+
+export function sampleCapturedFrames<T extends CapturedVideoFrame>(
+ frames: readonly T[],
+ startMs: number,
+ endMs: number,
+ fps = DEFAULT_WINDOW_FPS,
+ maxFrames = DEFAULT_WINDOW_MAX_FRAMES,
+): CapturedFrameSample<T>[] {
+ if (frames.length === 0) return [];
+ const start = Math.max(0, Math.min(startMs, endMs));
+ const end = Math.max(start, endMs);
+ const density = Number.isFinite(fps) && fps > 0 ? Math.min(fps, 30) : DEFAULT_WINDOW_FPS;
+ const cap = Number.isFinite(maxFrames)
+ ? Math.max(1, Math.min(Math.floor(maxFrames), DEFAULTS.maxFrames))
+ : DEFAULT_WINDOW_MAX_FRAMES;
+ const stepMs = 1000 / density;
+ const samples: CapturedFrameSample<T>[] = [];
+ const used = new Set<string>();
+
+ for (let targetMs = start; targetMs <= end && samples.length < cap; targetMs += stepMs) {
+ const frame = nearestCapturedFrame(frames, targetMs);
+ if (!frame || used.has(frame.file)) continue;
+ used.add(frame.file);
+ samples.push({ frame, targetMs: Math.round(targetMs) });
+ }
+ if (samples.length === 0) {
+ const targetMs = Math.round((start + end) / 2);
+ const frame = nearestCapturedFrame(frames, targetMs);
+ if (frame) samples.push({ frame, targetMs });
+ }
+ return samples;
+}
/**
- * Extracts a *sparse* set of visually-distinct frames from the session video and
- * correlates them to wall-clock time. It is deliberately **re-entrant and
- * additive**: every `extract*` call appends to a single deduplicated manifest
- * (`frames.json`), so callers can keep asking for more frames without producing
- * duplicates. This is what enables the optimization loop — when the correlation
- * engine flags an unexplained gap, or the describer model is unsure about a
- * moment, it calls `extractWindow(...)` to densely (and optionally zoomed-in)
- * sample just that slice, and only genuinely-new frames are kept.
+ * Extracts sparse, visually distinct JPEGs from the snapshots captured alongside
+ * the WebM. Pre-change sessions can still use a user-installed FFmpeg, but the
+ * application no longer downloads or distributes any FFmpeg binary.
*/
export class FrameExtractor {
- private readonly opts: Required<Omit<ExtractorOptions, "durationSec">> & { durationSec?: number };
+ private readonly opts: {
+ videoPath?: string;
+ capturedFramesPath?: string;
+ framesDir: string;
+ anchorEpochMs: number;
+ durationSec?: number;
+ dedupeThreshold: number;
+ maxFrames: number;
+ frameGridSec: number;
+ };
private readonly manifestPath: string;
+ private readonly sourceFrames: SourceFrame[];
+ private readonly usesCapturedFramePipeline: boolean;
private frames: FrameRecord[] = [];
+ private warnedLegacy = false;
constructor(opts: ExtractorOptions) {
this.opts = {
- dedupeThreshold: DEFAULTS.dedupeThreshold,
- maxFrames: DEFAULTS.maxFrames,
- frameGridSec: DEFAULTS.frameGridSec,
...opts,
+ dedupeThreshold: opts.dedupeThreshold ?? DEFAULTS.dedupeThreshold,
+ maxFrames: opts.maxFrames ?? DEFAULTS.maxFrames,
+ frameGridSec: opts.frameGridSec ?? DEFAULTS.frameGridSec,
};
this.manifestPath = path.join(opts.framesDir, "frames.json");
+ this.usesCapturedFramePipeline =
+ opts.capturedFramesExpected === true ||
+ Boolean(opts.capturedFramesPath && existsSync(opts.capturedFramesPath));
+ this.sourceFrames = loadSourceFrames(opts.capturedFramesPath);
if (existsSync(this.manifestPath)) {
- try {
- this.frames = JSON.parse(readFileSync(this.manifestPath, "utf8")) as FrameRecord[];
- } catch {
- this.frames = [];
- }
+ this.frames = loadRetainedFrames(this.manifestPath);
}
}
- /** Current manifest (sorted by time). */
get manifest(): readonly FrameRecord[] {
return [...this.frames].sort((a, b) => a.tMs - b.tMs);
}
@@ -105,79 +177,169 @@ export class FrameExtractor {
return Math.round(this.opts.anchorEpochMs + offsetSec * 1000);
}
- /**
- * Extract one frame at each event's wall-clock time. Anchors that land on the
- * same low-fps video frame are collapsed (grid-dedupe) so a burst of events
- * doesn't fire many redundant ffmpeg decodes — event-anchored extraction stays
- * cheap even when the non-video stream is dense.
- */
async extractAtEpochs(
events: { tMs: number; reason?: string }[],
source: FrameSource = "event",
): Promise<FrameRecord[]> {
const gridSec = this.opts.frameGridSec;
const seen = new Set<number>();
+ const seenCapturedFiles = new Set<string>();
const added: FrameRecord[] = [];
const sorted = [...events].sort((a, b) => a.tMs - b.tMs);
- for (const ev of sorted) {
- const offsetSec = this.offsetForEpoch(ev.tMs);
+ for (const event of sorted) {
+ const offsetSec = this.offsetForEpoch(event.tMs);
if (this.opts.durationSec != null && offsetSec > this.opts.durationSec) continue;
const cell = Math.round(offsetSec / gridSec);
if (seen.has(cell)) continue;
seen.add(cell);
- const rec = await this.extractSingle(offsetSec, source, ev.reason);
- if (rec) added.push(rec);
+ try {
+ const record =
+ this.sourceFrames.length > 0
+ ? await this.extractCapturedAt(
+ event.tMs,
+ source,
+ event.reason,
+ seenCapturedFiles,
+ )
+ : this.usesCapturedFramePipeline
+ ? null
+ : await this.extractLegacySingle(offsetSec, source, event.reason);
+ if (record) added.push(record);
+ } catch (err) {
+ log.warn(`frame extraction at ${offsetSec.toFixed(2)}s failed:`, message(err));
+ }
}
this.persist();
return added;
}
- /** One-pass scene-change detection → keep only visually-distinct frames. */
- async extractScenes(threshold = DEFAULTS.sceneThreshold): Promise<FrameRecord[]> {
- const stamp = Date.now();
- const pattern = path.join(this.opts.framesDir, `scene_${stamp}_%04d.jpg`);
- // showinfo prints pts_time for each selected frame to stderr, in output order.
- const filter = `select='gt(scene,${threshold})',showinfo`;
- let stderr = "";
- try {
- const res = await execFileAsync(
- ffmpegPath,
- ["-hide_banner", "-i", this.opts.videoPath, "-vf", filter, "-vsync", "vfr", "-q:v", "3", pattern],
- { maxBuffer: 32 * 1024 * 1024 },
- );
- stderr = res.stderr;
- } catch (err) {
- stderr = (err as { stderr?: string }).stderr ?? "";
+ async extractWindow(req: WindowRequest): Promise<FrameRecord[]> {
+ if (this.sourceFrames.length === 0) {
+ return this.usesCapturedFramePipeline ? [] : this.extractLegacyWindow(req);
}
- const times = [...stderr.matchAll(/pts_time:([0-9.]+)/g)].map((m) => Number(m[1]));
+ const startMs = Math.max(this.opts.anchorEpochMs, req.startMs);
+ const endMs = Math.max(startMs, req.endMs);
+ const cap = req.maxFrames ?? DEFAULT_WINDOW_MAX_FRAMES;
+ const samples = sampleCapturedFrames(
+ this.sourceFrames,
+ startMs,
+ endMs,
+ req.fps ?? DEFAULT_WINDOW_FPS,
+ cap,
+ );
+ const stamp = randomUUID();
const added: FrameRecord[] = [];
- for (let i = 0; i < times.length; i++) {
- const file = path.join(this.opts.framesDir, `scene_${stamp}_${String(i + 1).padStart(4, "0")}.jpg`);
- if (!existsSync(file)) continue;
- const rec = await this.keepOrDrop(file, times[i], "scene", `scene>${threshold.toFixed(2)}`);
- if (rec) added.push(rec);
+ for (let index = 0; index < samples.length; index++) {
+ const sample = samples[index];
+ const file = path.join(
+ this.opts.framesDir,
+ `probe_${stamp}_${String(index + 1).padStart(4, "0")}.jpg`,
+ );
+ try {
+ const rendered = await this.renderCaptured(sample.frame, file, req.crop);
+ if (!rendered) continue;
+ const record = await this.keepOrDrop(
+ file,
+ this.offsetForEpoch(sample.frame.tMs),
+ "probe",
+ req.reason ?? "probe:window",
+ );
+ if (record) added.push(record);
+ } catch (err) {
+ log.warn("probe frame failed:", message(err));
+ }
}
this.persist();
- log.info(`scene pass: ${times.length} candidates → ${added.length} kept`);
+ log.info(
+ `probe [${this.offsetForEpoch(startMs).toFixed(1)}–${this.offsetForEpoch(endMs).toFixed(1)}s]: ` +
+ `${added.length} new frames`,
+ );
return added;
}
- /**
- * The adaptive primitive: densely sample a sub-window (optionally zoomed via
- * crop) and keep only new frames. Used by the correlation heuristic and the
- * describer's "I need a closer look" tool.
- */
- async extractWindow(req: WindowRequest): Promise<FrameRecord[]> {
- const fps = req.fps ?? 6;
+ private async extractCapturedAt(
+ targetMs: number,
+ source: FrameSource,
+ reason?: string,
+ seenCapturedFiles?: Set<string>,
+ ): Promise<FrameRecord | null> {
+ const captured = nearestCapturedFrame(this.sourceFrames, targetMs) as SourceFrame | null;
+ if (!captured) return null;
+ if (seenCapturedFiles?.has(captured.file)) return null;
+
+ const offsetSec = this.offsetForEpoch(captured.tMs);
+ const name = retainedCapturedName(captured, source);
+ const file = path.join(this.opts.framesDir, name);
+ const existingIndex = this.frames.findIndex((frame) => frame.file === name);
+ if (existingIndex >= 0 && existsSync(file)) {
+ seenCapturedFiles?.add(captured.file);
+ return null;
+ }
+ if (existingIndex >= 0) this.frames.splice(existingIndex, 1);
+
+ try {
+ await copyFile(captured.absolutePath, file);
+ const record = await this.keepOrDrop(file, offsetSec, source, reason);
+ seenCapturedFiles?.add(captured.file);
+ return record;
+ } catch (err) {
+ log.warn("captured frame copy failed:", message(err));
+ return null;
+ }
+ }
+
+ private async renderCaptured(
+ captured: SourceFrame,
+ output: string,
+ crop?: WindowRequest["crop"],
+ ): Promise<boolean> {
+ if (!crop) {
+ await copyFile(captured.absolutePath, output);
+ return true;
+ }
+ const image = sharp();
+ if (!image) {
+ log.warn("probe crop skipped because sharp is unavailable");
+ return false;
+ }
+ const left = Math.round(crop.x);
+ const top = Math.round(crop.y);
+ const width = Math.round(crop.w);
+ const height = Math.round(crop.h);
+ if (
+ ![left, top, width, height].every(Number.isFinite) ||
+ left < 0 ||
+ top < 0 ||
+ width <= 0 ||
+ height <= 0 ||
+ left + width > captured.width ||
+ top + height > captured.height
+ ) {
+ throw new Error(
+ `Crop ${left},${top},${width},${height} is outside ${captured.width}x${captured.height}.`,
+ );
+ }
+ await image(captured.absolutePath)
+ .extract({ left, top, width, height })
+ .jpeg({ quality: 88 })
+ .toFile(output);
+ return true;
+ }
+
+ private async extractLegacyWindow(req: WindowRequest): Promise<FrameRecord[]> {
+ const ffmpegPath = this.legacyFfmpegPath();
+ const videoPath = this.opts.videoPath;
+ if (!ffmpegPath || !videoPath) return [];
+
+ const fps = req.fps ?? DEFAULT_WINDOW_FPS;
const startSec = this.offsetForEpoch(req.startMs);
const endSec = Math.max(startSec, this.offsetForEpoch(req.endMs));
- const cap = req.maxFrames ?? 24;
- const stamp = Date.now();
+ const cap = req.maxFrames ?? DEFAULT_WINDOW_MAX_FRAMES;
+ const stamp = randomUUID();
const pattern = path.join(this.opts.framesDir, `probe_${stamp}_%04d.jpg`);
-
- const vf = [`fps=${fps}`];
- if (req.crop) vf.push(`crop=${req.crop.w}:${req.crop.h}:${req.crop.x}:${req.crop.y}`);
+ const filters = [`fps=${fps}`];
+ if (req.crop) filters.push(`crop=${req.crop.w}:${req.crop.h}:${req.crop.x}:${req.crop.y}`);
try {
await execFileAsync(
@@ -186,8 +348,8 @@ export class FrameExtractor {
"-hide_banner",
"-ss", startSec.toFixed(3),
"-to", endSec.toFixed(3),
- "-i", this.opts.videoPath,
- "-vf", vf.join(","),
+ "-i", videoPath,
+ "-vf", filters.join(","),
"-vsync", "vfr",
"-frames:v", String(cap),
"-q:v", "3",
@@ -196,45 +358,71 @@ export class FrameExtractor {
{ maxBuffer: 32 * 1024 * 1024 },
);
} catch (err) {
- log.warn("probe window failed:", err instanceof Error ? err.message : err);
+ log.warn("legacy probe window failed:", message(err));
return [];
}
const added: FrameRecord[] = [];
- for (let i = 1; i <= cap; i++) {
- const file = path.join(this.opts.framesDir, `probe_${stamp}_${String(i).padStart(4, "0")}.jpg`);
+ for (let index = 1; index <= cap; index++) {
+ const file = path.join(
+ this.opts.framesDir,
+ `probe_${stamp}_${String(index).padStart(4, "0")}.jpg`,
+ );
if (!existsSync(file)) break;
- const offsetSec = startSec + (i - 1) / fps;
- const rec = await this.keepOrDrop(file, offsetSec, "probe", req.reason ?? "probe:window");
- if (rec) added.push(rec);
+ const offsetSec = startSec + (index - 1) / fps;
+ const record = await this.keepOrDrop(
+ file,
+ offsetSec,
+ "probe",
+ req.reason ?? "probe:legacy-system-ffmpeg",
+ );
+ if (record) added.push(record);
}
this.persist();
- log.info(`probe [${startSec.toFixed(1)}–${endSec.toFixed(1)}s @${fps}fps]: ${added.length} new frames`);
return added;
}
- private async extractSingle(
+ private async extractLegacySingle(
offsetSec: number,
source: FrameSource,
reason?: string,
): Promise<FrameRecord | null> {
+ const ffmpegPath = this.legacyFfmpegPath();
+ const videoPath = this.opts.videoPath;
+ if (!ffmpegPath || !videoPath) return null;
const file = path.join(this.opts.framesDir, `${source}_${Math.round(offsetSec * 1000)}.jpg`);
try {
- // Output-seek (decode from start) is reliable on non-seekable MediaRecorder webm.
await execFileAsync(
ffmpegPath,
- ["-hide_banner", "-i", this.opts.videoPath, "-ss", offsetSec.toFixed(3), "-frames:v", "1", "-q:v", "3", "-y", file],
+ [
+ "-hide_banner",
+ "-i", videoPath,
+ "-ss", offsetSec.toFixed(3),
+ "-frames:v", "1",
+ "-q:v", "3",
+ "-y", file,
+ ],
{ maxBuffer: 16 * 1024 * 1024 },
);
} catch (err) {
- log.warn(`frame at ${offsetSec.toFixed(2)}s failed:`, err instanceof Error ? err.message : err);
+ log.warn(`legacy frame at ${offsetSec.toFixed(2)}s failed:`, message(err));
return null;
}
if (!existsSync(file)) return null;
return this.keepOrDrop(file, offsetSec, source, reason);
}
- /** Compute the hash, drop near-duplicates and over-budget frames, else record. */
+ private legacyFfmpegPath(): string | null {
+ const resolved = systemFfmpegPath();
+ if (!resolved && !this.warnedLegacy) {
+ this.warnedLegacy = true;
+ log.warn(
+ "This recording predates captured source frames. Install FFmpeg to extract legacy video frames.",
+ );
+ }
+ return resolved;
+ }
+
private async keepOrDrop(
file: string,
offsetSec: number,
@@ -254,7 +442,7 @@ export class FrameExtractor {
}
}
}
- const rec: FrameRecord = {
+ const record: FrameRecord = {
file: path.basename(file),
tMs: this.epochForOffset(offsetSec),
offsetSec: Number(offsetSec.toFixed(3)),
@@ -262,35 +450,159 @@ export class FrameExtractor {
phash: phash ?? "",
...(reason ? { reason } : {}),
};
- this.frames.push(rec);
- return rec;
+ this.frames.push(record);
+ return record;
}
private persist(): void {
try {
writeFileSync(this.manifestPath, JSON.stringify(this.manifest, null, 2));
} catch (err) {
- log.warn("failed to persist frames.json:", err instanceof Error ? err.message : err);
+ log.warn("failed to persist frames.json:", message(err));
+ }
+ }
+}
+
+function loadSourceFrames(manifestPath?: string): SourceFrame[] {
+ if (!manifestPath || !existsSync(manifestPath)) return [];
+ try {
+ const manifest: unknown = JSON.parse(readFileSync(manifestPath, "utf8"));
+ if (
+ !isRecord(manifest) ||
+ manifest.version !== CAPTURED_FRAME_MANIFEST_VERSION ||
+ manifest.format !== "jpeg" ||
+ !Array.isArray(manifest.frames)
+ ) {
+ throw new Error("Unsupported captured-frame manifest.");
+ }
+
+ const root = path.dirname(manifestPath);
+ const frames: SourceFrame[] = [];
+ for (const candidate of manifest.frames) {
+ if (!isCapturedVideoFrame(candidate)) continue;
+ const absolutePath = resolvePortableRelativePath(root, candidate.file);
+ if (!absolutePath || !existsSync(absolutePath)) continue;
+ frames.push({ ...candidate, absolutePath });
+ }
+ const ignored = manifest.frames.length - frames.length;
+ if (ignored > 0) log.warn(`ignored ${ignored} invalid or missing captured frame(s)`);
+ return frames.sort((a, b) => a.tMs - b.tMs);
+ } catch (err) {
+ log.warn("unreadable captured-frame manifest:", message(err));
+ return [];
+ }
+}
+
+function retainedCapturedName(frame: CapturedVideoFrame, source: FrameSource): string {
+ const stem =
+ path
+ .basename(frame.file, path.extname(frame.file))
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
+ .slice(0, 80) || "frame";
+ return `${source}_${Math.max(0, Math.round(frame.offsetMs))}_${stem}.jpg`;
+}
+
+function loadRetainedFrames(manifestPath: string): FrameRecord[] {
+ try {
+ const manifest: unknown = JSON.parse(readFileSync(manifestPath, "utf8"));
+ if (!Array.isArray(manifest)) throw new Error("Expected a frame-record array.");
+ const frames = manifest.filter(isFrameRecord);
+ if (frames.length !== manifest.length) {
+ log.warn(`ignored ${manifest.length - frames.length} invalid retained frame record(s)`);
}
+ return frames;
+ } catch (err) {
+ log.warn("unreadable retained-frame manifest:", message(err));
+ return [];
+ }
+}
+
+function resolvePortableRelativePath(root: string, file: string): string | null {
+ if (path.win32.isAbsolute(file) || path.posix.isAbsolute(file)) return null;
+ const segments = file.split(/[\\/]+/).filter((segment) => segment && segment !== ".");
+ if (segments.length === 0 || segments.includes("..")) return null;
+ const absolute = path.resolve(root, ...segments);
+ const relative = path.relative(root, absolute);
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ return null;
}
+ return absolute;
+}
+
+function isCapturedVideoFrame(value: unknown): value is CapturedVideoFrame {
+ return (
+ isRecord(value) &&
+ typeof value.file === "string" &&
+ value.file.length > 0 &&
+ finiteNumber(value.tMs) &&
+ finiteNumber(value.offsetMs) &&
+ finitePositiveNumber(value.width) &&
+ finitePositiveNumber(value.height)
+ );
+}
+
+function isFrameRecord(value: unknown): value is FrameRecord {
+ return (
+ isRecord(value) &&
+ typeof value.file === "string" &&
+ finiteNumber(value.tMs) &&
+ finiteNumber(value.offsetSec) &&
+ (value.source === "event" || value.source === "scene" || value.source === "probe") &&
+ typeof value.phash === "string" &&
+ (value.phash === "" || /^[0-9a-f]{16}$/i.test(value.phash)) &&
+ (value.reason === undefined || typeof value.reason === "string")
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function finiteNumber(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value);
+}
+
+function finitePositiveNumber(value: unknown): value is number {
+ return finiteNumber(value) && value > 0;
+}
+
+let ffmpegPath: string | null | undefined;
+function systemFfmpegPath(): string | null {
+ if (ffmpegPath !== undefined) return ffmpegPath;
+ try {
+ const finder = process.platform === "win32" ? "where" : "which";
+ ffmpegPath =
+ execFileSync(finder, ["ffmpeg"], { encoding: "utf8" })
+ .trim()
+ .split(/\r?\n/)[0] || null;
+ } catch {
+ ffmpegPath = null;
+ }
+ return ffmpegPath;
}
-/** 64-bit difference hash (dHash) as 16 hex chars; "" when sharp is unavailable. */
async function dhash(file: string): Promise<string> {
- const s = sharp();
- if (!s) return "";
+ const image = sharp();
+ if (!image) return "";
try {
- const w = 9;
- const h = 8;
- const buf = await s(file).grayscale().resize(w, h, { fit: "fill" }).raw().toBuffer();
+ const width = 9;
+ const height = 8;
+ const buffer = await image(file)
+ .grayscale()
+ .resize(width, height, { fit: "fill" })
+ .raw()
+ .toBuffer();
let bits = "";
- for (let row = 0; row < h; row++) {
- for (let col = 0; col < w - 1; col++) {
- bits += buf[row * w + col] < buf[row * w + col + 1] ? "1" : "0";
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width - 1; column++) {
+ bits +=
+ buffer[row * width + column] < buffer[row * width + column + 1] ? "1" : "0";
}
}
let hex = "";
- for (let i = 0; i < 64; i += 4) hex += parseInt(bits.slice(i, i + 4), 2).toString(16);
+ for (let index = 0; index < 64; index += 4) {
+ hex += parseInt(bits.slice(index, index + 4), 2).toString(16);
+ }
return hex;
} catch {
return "";
@@ -299,13 +611,17 @@ async function dhash(file: string): Promise<string> {
function hamming(a: string, b: string): number {
if (!a || !b || a.length !== b.length) return Number.MAX_SAFE_INTEGER;
- let d = 0;
- for (let i = 0; i < a.length; i++) {
- let x = parseInt(a[i], 16) ^ parseInt(b[i], 16);
- while (x) {
- d += x & 1;
- x >>= 1;
+ let distance = 0;
+ for (let index = 0; index < a.length; index++) {
+ let value = parseInt(a[index], 16) ^ parseInt(b[index], 16);
+ while (value) {
+ distance += value & 1;
+ value >>= 1;
}
}
- return d;
+ return distance;
+}
+
+function message(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
}
diff --git a/electron/narration/audio-analysis.test.ts b/electron/narration/audio-analysis.test.ts
new file mode 100644
index 0000000..d9750c0
--- /dev/null
+++ b/electron/narration/audio-analysis.test.ts
@@ -0,0 +1,23 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { detectSilence } from "./audio-analysis";
+
+const SAMPLE_RATE = 1000;
+
+test("detectSilence keeps only spans that meet the minimum duration", () => {
+ const samples = new Float32Array(2400);
+ samples.fill(0.2, 0, 400);
+ samples.fill(0, 400, 1200);
+ samples.fill(0.2, 1200, 1600);
+ samples.fill(0, 1600, 2000);
+ samples.fill(0.2, 2000);
+
+ assert.deepEqual(detectSilence(samples, SAMPLE_RATE), [{ start: 0.4, end: 1.2 }]);
+});
+
+test("detectSilence closes a trailing silent span", () => {
+ const samples = new Float32Array(1500);
+ samples.fill(0.2, 0, 500);
+ assert.deepEqual(detectSilence(samples, SAMPLE_RATE), [{ start: 0.5, end: 1.5 }]);
+});
diff --git a/electron/narration/audio-analysis.ts b/electron/narration/audio-analysis.ts
new file mode 100644
index 0000000..3381296
--- /dev/null
+++ b/electron/narration/audio-analysis.ts
@@ -0,0 +1,42 @@
+export interface SilenceSpan {
+ start: number;
+ end: number;
+}
+
+const DEFAULT_SAMPLE_RATE = 16_000;
+const DEFAULT_THRESHOLD_DB = -35;
+const DEFAULT_MIN_SILENCE_SEC = 0.6;
+const DEFAULT_WINDOW_SEC = 0.02;
+
+/** Find sustained low-RMS spans in decoded mono audio. */
+export function detectSilence(
+ samples: Float32Array,
+ sampleRate = DEFAULT_SAMPLE_RATE,
+ thresholdDb = DEFAULT_THRESHOLD_DB,
+ minSilenceSec = DEFAULT_MIN_SILENCE_SEC,
+): SilenceSpan[] {
+ const threshold = 10 ** (thresholdDb / 20);
+ const minSamples = Math.round(minSilenceSec * sampleRate);
+ const windowSamples = Math.max(1, Math.round(DEFAULT_WINDOW_SEC * sampleRate));
+ const spans: SilenceSpan[] = [];
+ let pendingStart = -1;
+
+ for (let offset = 0; offset < samples.length; offset += windowSamples) {
+ const end = Math.min(samples.length, offset + windowSamples);
+ let energy = 0;
+ for (let index = offset; index < end; index++) energy += samples[index] ** 2;
+ const rms = Math.sqrt(energy / Math.max(1, end - offset));
+ if (rms < threshold) {
+ if (pendingStart < 0) pendingStart = offset;
+ } else if (pendingStart >= 0) {
+ if (offset - pendingStart >= minSamples) {
+ spans.push({ start: pendingStart / sampleRate, end: offset / sampleRate });
+ }
+ pendingStart = -1;
+ }
+ }
+ if (pendingStart >= 0 && samples.length - pendingStart >= minSamples) {
+ spans.push({ start: pendingStart / sampleRate, end: samples.length / sampleRate });
+ }
+ return spans;
+}
diff --git a/electron/narration/transcribe.ts b/electron/narration/transcribe.ts
index 5c20360..b5c9bda 100644
--- a/electron/narration/transcribe.ts
+++ b/electron/narration/transcribe.ts
@@ -1,27 +1,13 @@
-import { execFile } from "node:child_process";
-import { createRequire } from "node:module";
-import { promisify } from "node:util";
-
import type { NarrationSegment } from "../../common/narration";
+import { decodeAudioFile } from "../audio/decode";
import { createLogger } from "../logger";
+import { detectSilence, type SilenceSpan } from "./audio-analysis";
import { narrationModelId, type AsrPipeline } from "./whisper";
const log = createLogger("Narration/transcribe");
-const require = createRequire(import.meta.url);
-const execFileAsync = promisify(execFile);
-
-const ffmpegPath = require("ffmpeg-static") as string;
// Whisper is trained on 16 kHz mono audio.
const SAMPLE_RATE = 16_000;
-// f32le at 16 kHz mono is 64 KB per second; 1 GB covers ~4.5 h of narration.
-const MAX_PCM_BUFFER = 1024 * 1024 * 1024;
-
-/** A silence interval in the decoded audio's own clock (seconds). */
-interface SilenceSpan {
- start: number;
- end: number;
-}
/**
* Transcribe one session's narration webm into session-clock segments.
@@ -37,14 +23,12 @@ export async function transcribeNarration(
durationMs: number,
pipe: AsrPipeline,
): Promise<{ model: string; segments: NarrationSegment[] }> {
- const samples = await decodePcm(audioPath);
+ const samples = await decodeAudioFile(audioPath);
if (samples.length === 0) {
throw new Error("Narration audio decoded to zero samples.");
}
- // Silence detection runs on the same file and only reads the audio, so its
- // intervals line up with the decoded samples and never shift timestamps.
- const silences = await detectSilence(audioPath);
+ const silences = detectSilence(samples);
const result = await pipe(samples, {
return_timestamps: true,
@@ -78,68 +62,6 @@ export async function transcribeNarration(
return { model: narrationModelId(), segments };
}
-/** Decode any container into raw 16 kHz mono float samples (no WAV/dep needed). */
-async function decodePcm(audioPath: string): Promise<Float32Array> {
- const { stdout } = await execFileAsync(
- ffmpegPath,
- [
- "-hide_banner",
- "-loglevel", "error",
- "-i", audioPath,
- "-ac", "1",
- "-ar", String(SAMPLE_RATE),
- "-f", "f32le",
- "pipe:1",
- ],
- { encoding: "buffer", maxBuffer: MAX_PCM_BUFFER },
- );
-
- const buf = stdout as unknown as Buffer;
- // Copy into a fresh, 4-byte-aligned ArrayBuffer before viewing as Float32:
- // execFile's Buffer offset is not guaranteed aligned.
- const usableBytes = buf.byteLength - (buf.byteLength % 4);
- const ab = new ArrayBuffer(usableBytes);
- new Uint8Array(ab).set(buf.subarray(0, usableBytes));
- return new Float32Array(ab);
-}
-
-/** Run ffmpeg's silencedetect and parse the intervals it logs to stderr. */
-async function detectSilence(audioPath: string): Promise<SilenceSpan[]> {
- let stderr = "";
- try {
- const res = await execFileAsync(
- ffmpegPath,
- [
- "-hide_banner",
- "-i", audioPath,
- "-af", "silencedetect=noise=-35dB:d=0.6",
- "-f", "null",
- "-",
- ],
- { maxBuffer: 8 * 1024 * 1024 },
- );
- stderr = res.stderr;
- } catch (err) {
- // silencedetect over the null muxer normally exits 0; treat any failure as
- // "no silence info" rather than aborting transcription.
- stderr = (err as { stderr?: string }).stderr ?? "";
- }
-
- const spans: SilenceSpan[] = [];
- let pendingStart: number | null = null;
- for (const m of stderr.matchAll(/silence_(start|end):\s*(-?[0-9.]+)/g)) {
- const kind = m[1];
- const value = Number(m[2]);
- if (kind === "start") {
- pendingStart = value;
- } else if (pendingStart != null) {
- spans.push({ start: pendingStart, end: value });
- pendingStart = null;
- }
- }
- return spans;
-}
-
/** A chunk is dropped when its midpoint sits inside a detected silence span. */
function isMostlySilent(startSec: number, endSec: number, silences: SilenceSpan[]): boolean {
const mid = (startSec + endSec) / 2;
diff --git a/electron/pipeline.ts b/electron/pipeline.ts
index 30e939c..1149833 100644
--- a/electron/pipeline.ts
+++ b/electron/pipeline.ts
@@ -5,6 +5,7 @@ import { buildBundle } from "../common/bundle";
import { MEANINGFUL_EVENT_TYPES } from "../common/correlation";
import type { CorrelationResult } from "../common/correlation";
import { renderDescription } from "../common/describe";
+import { CAPTURED_FRAME_MANIFEST_VERSION } from "../common/frames";
import type { SessionMeta } from "../common/types";
import { CorrelationEngine, readEvents } from "./frames/correlate";
import { FrameExtractor } from "./frames/extractor";
@@ -44,13 +45,20 @@ async function runFrameStage(sessionDir: string): Promise<CorrelationResult | nu
}
const videoPath = path.join(sessionDir, video.file);
- if (!existsSync(videoPath)) {
- log.warn("video file missing; skipping frame stage");
+ const capturedFramesPath = video.framesFile
+ ? path.join(sessionDir, video.framesFile)
+ : undefined;
+ const hasVideo = existsSync(videoPath);
+ const hasCapturedFrames = Boolean(capturedFramesPath && existsSync(capturedFramesPath));
+ if (!hasVideo && !hasCapturedFrames) {
+ log.warn("video and captured frames missing; skipping frame stage");
return null;
}
const extractor = new FrameExtractor({
- videoPath,
+ ...(hasVideo ? { videoPath } : {}),
+ ...(hasCapturedFrames ? { capturedFramesPath } : {}),
+ capturedFramesExpected: video.framesVersion === CAPTURED_FRAME_MANIFEST_VERSION,
framesDir: path.join(sessionDir, "frames"),
anchorEpochMs: video.startEpoch,
durationSec: video.durationMs > 0 ? video.durationMs / 1000 : undefined,
diff --git a/electron/video/capture-preload.cjs b/electron/video/capture-preload.cjs
index 770eaf5..799c207 100644
--- a/electron/video/capture-preload.cjs
+++ b/electron/video/capture-preload.cjs
@@ -13,6 +13,246 @@ let stream = null;
// fully forwarded before we tell main the recording stopped — otherwise the
// last cluster is lost and the webm ends prematurely.
let sendChain = Promise.resolve();
+/** @type {ReadableStreamDefaultReader | null} */
+let frameReader = null;
+/** @type {Promise<void> | null} */
+let framePump = null;
+/** @type {Promise<void> | null} */
+let frameEncoding = null;
+/** @type {ReturnType<typeof setInterval> | null} */
+let frameTimer = null;
+/** @type {OffscreenCanvas | HTMLCanvasElement | null} */
+let frameCanvas = null;
+/** @type {OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null} */
+let frameContext = null;
+/** @type {OffscreenCanvas | HTMLCanvasElement | null} */
+let hashCanvas = null;
+/** @type {OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null} */
+let hashContext = null;
+/** @type {HTMLVideoElement | null} */
+let previewVideo = null;
+let capturingFrames = false;
+let frameReady = false;
+let recordingStarted = false;
+let startEpoch = 0;
+let startMonotonic = 0;
+/** @type {number | null} */
+let firstFrameTimestampUs = null;
+let firstFrameEpoch = 0;
+let lastFrameHash = "";
+let lastFrameEmitAt = 0;
+let frameErrorReported = false;
+
+const FRAME_HEARTBEAT_MS = 5000;
+const FRAME_START_TIMEOUT_MS = 5000;
+const FRAME_DEDUPE_DISTANCE = 8;
+const FRAME_JPEG_QUALITY = 0.78;
+
+function reportFrameError(error) {
+ if (frameErrorReported) return;
+ frameErrorReported = true;
+ ipcRenderer.send(
+ "video:frame-error",
+ error instanceof Error ? error.message : String(error),
+ );
+}
+
+function currentEpoch() {
+ return recordingStarted
+ ? startEpoch + (performance.now() - startMonotonic)
+ : Date.now();
+}
+
+function createCanvas(width, height) {
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+}
+
+function ensureCanvases(width, height) {
+ if (!frameCanvas || frameCanvas.width !== width || frameCanvas.height !== height) {
+ frameCanvas = createCanvas(width, height);
+ frameContext = frameCanvas.getContext("2d", { alpha: false });
+ }
+ if (!hashCanvas) {
+ hashCanvas = createCanvas(9, 8);
+ hashContext = hashCanvas.getContext("2d", { alpha: false, willReadFrequently: true });
+ }
+ if (!frameContext || !hashContext) throw new Error("Could not create frame capture canvases.");
+}
+
+function dhash() {
+ if (!frameCanvas || !hashContext) return "";
+ hashContext.drawImage(frameCanvas, 0, 0, 9, 8);
+ const pixels = hashContext.getImageData(0, 0, 9, 8).data;
+ let bits = "";
+ for (let row = 0; row < 8; row++) {
+ for (let col = 0; col < 8; col++) {
+ const left = (row * 9 + col) * 4;
+ const right = left + 4;
+ const leftLuma = pixels[left] * 0.299 + pixels[left + 1] * 0.587 + pixels[left + 2] * 0.114;
+ const rightLuma = pixels[right] * 0.299 + pixels[right + 1] * 0.587 + pixels[right + 2] * 0.114;
+ bits += leftLuma < rightLuma ? "1" : "0";
+ }
+ }
+ let hex = "";
+ for (let i = 0; i < 64; i += 4) hex += parseInt(bits.slice(i, i + 4), 2).toString(16);
+ return hex;
+}
+
+function hamming(a, b) {
+ if (!a || !b || a.length !== b.length) return Number.MAX_SAFE_INTEGER;
+ let distance = 0;
+ for (let i = 0; i < a.length; i++) {
+ let value = parseInt(a[i], 16) ^ parseInt(b[i], 16);
+ while (value) {
+ distance += value & 1;
+ value >>= 1;
+ }
+ }
+ return distance;
+}
+
+function canvasToJpeg(canvas) {
+ if ("convertToBlob" in canvas) {
+ return canvas.convertToBlob({ type: "image/jpeg", quality: FRAME_JPEG_QUALITY });
+ }
+ return new Promise((resolve, reject) => {
+ canvas.toBlob(
+ (blob) => blob ? resolve(blob) : reject(new Error("JPEG encoding returned no data.")),
+ "image/jpeg",
+ FRAME_JPEG_QUALITY,
+ );
+ });
+}
+
+async function maybeEmitFrame(tMs, force = false) {
+ if (!recordingStarted || !frameReady || !frameCanvas || frameEncoding) return;
+ const hash = dhash();
+ const heartbeatDue = performance.now() - lastFrameEmitAt >= FRAME_HEARTBEAT_MS;
+ if (!force && !heartbeatDue && hamming(hash, lastFrameHash) <= FRAME_DEDUPE_DISTANCE) return;
+
+ frameEncoding = (async () => {
+ const blob = await canvasToJpeg(frameCanvas);
+ const data = new Uint8Array(await blob.arrayBuffer());
+ const roundedEpoch = Math.round(tMs);
+ ipcRenderer.send("video:frame", {
+ data,
+ tMs: roundedEpoch,
+ offsetMs: Math.max(0, Math.round(roundedEpoch - startEpoch)),
+ width: frameCanvas.width,
+ height: frameCanvas.height,
+ });
+ lastFrameHash = hash;
+ lastFrameEmitAt = performance.now();
+ })();
+ try {
+ await frameEncoding;
+ } finally {
+ frameEncoding = null;
+ }
+}
+
+async function drawFrame(source, width, height, timestampUs) {
+ if (!capturingFrames || width <= 0 || height <= 0) return;
+ ensureCanvases(width, height);
+ frameContext.drawImage(source, 0, 0, width, height);
+ frameReady = true;
+ if (!recordingStarted) return;
+
+ let tMs = currentEpoch();
+ if (Number.isFinite(timestampUs)) {
+ if (firstFrameTimestampUs == null) {
+ firstFrameTimestampUs = timestampUs;
+ firstFrameEpoch = tMs;
+ }
+ tMs = firstFrameEpoch + (timestampUs - firstFrameTimestampUs) / 1000;
+ }
+ await maybeEmitFrame(tMs);
+}
+
+async function pumpTrack(track) {
+ const Processor = globalThis.MediaStreamTrackProcessor;
+ if (typeof Processor !== "function" || typeof OffscreenCanvas === "undefined") return false;
+
+ const processor = new Processor({ track });
+ frameReader = processor.readable.getReader();
+ framePump = (async () => {
+ while (capturingFrames && frameReader) {
+ const { done, value: frame } = await frameReader.read();
+ if (done || !frame) break;
+ try {
+ await drawFrame(
+ frame,
+ frame.displayWidth || frame.codedWidth,
+ frame.displayHeight || frame.codedHeight,
+ frame.timestamp,
+ );
+ } finally {
+ frame.close();
+ }
+ }
+ })();
+ framePump.catch((err) => {
+ if (capturingFrames) reportFrameError(err);
+ });
+ return true;
+}
+
+async function startTimerFallback(track) {
+ const video = document.createElement("video");
+ previewVideo = video;
+ video.muted = true;
+ video.playsInline = true;
+ video.srcObject = new MediaStream([track]);
+ await withTimeout(
+ video.play(),
+ FRAME_START_TIMEOUT_MS,
+ "Timed out starting fallback snapshot capture.",
+ );
+ if (!capturingFrames || previewVideo !== video) {
+ video.pause();
+ video.srcObject = null;
+ return;
+ }
+ frameTimer = setInterval(() => {
+ if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) return;
+ void drawFrame(video, video.videoWidth, video.videoHeight, null)
+ .catch(reportFrameError);
+ }, 1000);
+}
+
+async function startFrameCapture(track) {
+ capturingFrames = true;
+ frameTimer = setInterval(() => {
+ if (frameReady) void maybeEmitFrame(currentEpoch(), true).catch(reportFrameError);
+ }, FRAME_HEARTBEAT_MS);
+ if (!(await pumpTrack(track))) {
+ clearInterval(frameTimer);
+ frameTimer = null;
+ await startTimerFallback(track);
+ }
+}
+
+async function stopFrameCapture() {
+ capturingFrames = false;
+ if (frameTimer) clearInterval(frameTimer);
+ frameTimer = null;
+ const reader = frameReader;
+ frameReader = null;
+ if (reader) await reader.cancel().catch(() => undefined);
+ if (framePump) await framePump.catch(() => undefined);
+ framePump = null;
+ if (frameReady) await maybeEmitFrame(currentEpoch(), true).catch(reportFrameError);
+ if (frameEncoding) await frameEncoding.catch(reportFrameError);
+ if (previewVideo) {
+ previewVideo.pause();
+ previewVideo.srcObject = null;
+ }
+ previewVideo = null;
+}
function cleanup() {
try {
@@ -22,11 +262,23 @@ function cleanup() {
}
stream = null;
recorder = null;
+ frameCanvas = null;
+ frameContext = null;
+ hashCanvas = null;
+ hashContext = null;
+ frameReady = false;
+ capturingFrames = false;
+ recordingStarted = false;
+ firstFrameTimestampUs = null;
+ lastFrameHash = "";
+ lastFrameEmitAt = 0;
+ frameErrorReported = false;
}
ipcRenderer.on("video:start", async (_event, opts) => {
const { sourceId, fps, bitsPerSecond, maxWidth, maxHeight } = opts;
try {
+ sendChain = Promise.resolve();
// Electron desktop capture uses the legacy mandatory-constraints form.
stream = await navigator.mediaDevices.getUserMedia({
audio: false,
@@ -47,7 +299,8 @@ ipcRenderer.on("video:start", async (_event, opts) => {
? "video/webm;codecs=vp8"
: "video/webm;codecs=vp9";
recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: bitsPerSecond });
-
+ const [track] = stream.getVideoTracks();
+ if (!track) throw new Error("Desktop capture returned no video track.");
recorder.ondataavailable = (e) => {
if (!e.data || e.data.size === 0) return;
// Preserve order and completion; Uint8Array survives IPC structured clone.
@@ -56,11 +309,20 @@ ipcRenderer.on("video:start", async (_event, opts) => {
ipcRenderer.send("video:chunk", new Uint8Array(buf));
});
};
- recorder.onstart = () => ipcRenderer.send("video:started", Date.now());
+ recorder.onstart = () => {
+ startEpoch = Date.now();
+ startMonotonic = performance.now();
+ recordingStarted = true;
+ ipcRenderer.send("video:started", startEpoch);
+ };
recorder.onstop = () => {
- // Wait for every queued chunk (including the final one) to be sent.
- sendChain.then(() => {
+ // Wait for every queued chunk and snapshot before acknowledging stop.
+ Promise.all([sendChain, stopFrameCapture()]).then(() => {
+ cleanup();
+ ipcRenderer.send("video:stopped");
+ }).catch((err) => {
cleanup();
+ ipcRenderer.send("video:error", err instanceof Error ? err.message : String(err));
ipcRenderer.send("video:stopped");
});
};
@@ -70,21 +332,36 @@ ipcRenderer.on("video:start", async (_event, opts) => {
// Emit a chunk every second so long sessions stream to disk incrementally.
recorder.start(1000);
+ void startFrameCapture(track).catch((err) => {
+ reportFrameError(err);
+ void stopFrameCapture().catch(reportFrameError);
+ });
} catch (err) {
+ await stopFrameCapture();
cleanup();
ipcRenderer.send("video:error", err instanceof Error ? err.message : String(err));
}
});
-ipcRenderer.on("video:stop", () => {
+function withTimeout(promise, timeoutMs, message) {
+ let timeout;
+ const expired = new Promise((_resolve, reject) => {
+ timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
+ });
+ return Promise.race([promise, expired]).finally(() => clearTimeout(timeout));
+}
+
+ipcRenderer.on("video:stop", async () => {
try {
if (recorder && recorder.state !== "inactive") {
recorder.requestData();
recorder.stop();
} else {
+ await stopFrameCapture();
ipcRenderer.send("video:stopped");
}
} catch (err) {
+ await stopFrameCapture().catch(() => undefined);
ipcRenderer.send("video:error", err instanceof Error ? err.message : String(err));
ipcRenderer.send("video:stopped");
}
diff --git a/electron/video/recorder.ts b/electron/video/recorder.ts
index edb8068..dd8319a 100644
--- a/electron/video/recorder.ts
+++ b/electron/video/recorder.ts
@@ -1,14 +1,21 @@
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, desktopCapturer, ipcMain, type IpcMainEvent } from "electron";
+import {
+ CAPTURED_FRAME_MANIFEST_VERSION,
+ type CapturedFrameManifest,
+ type CapturedVideoFrame,
+} from "../../common/frames";
import { createLogger } from "../logger";
const log = createLogger("Video");
const dirname = path.dirname(fileURLToPath(import.meta.url));
+export const VIDEO_FRAMES_FILE = "video-frames.json";
+export const VIDEO_FRAMES_DIR = "video-frames";
/** Result metadata written alongside the webm as `video.json`. */
export interface VideoResult {
@@ -20,6 +27,11 @@ export interface VideoResult {
durationMs: number;
bytes: number;
fps: number;
+ /** Present on recordings that use captured snapshots, even when capture yielded none. */
+ framesVersion?: number;
+ /** Versioned source-frame manifest captured alongside the WebM. */
+ framesFile?: string;
+ frameCount?: number;
}
// Screen capture's real cost is WindowServer (the OS compositor) grabbing the
@@ -31,7 +43,17 @@ const FPS = 1;
const BITS_PER_SECOND = 500_000;
const MAX_WIDTH = 1280;
const MAX_HEIGHT = 720;
-const STOP_TIMEOUT_MS = 4000;
+const STOP_TIMEOUT_MS = 10_000;
+const MAX_FRAME_BYTES = 5 * 1024 * 1024;
+const FRAME_HEARTBEAT_MS = 5000;
+
+interface FrameMessage {
+ data: Uint8Array;
+ tMs: number;
+ offsetMs: number;
+ width: number;
+ height: number;
+}
/**
* Captures a low-fps screen recording for a session. The heavy lifting
@@ -51,6 +73,10 @@ export class VideoRecorder {
private startEpoch: number | null = null;
private stoppedResolve: (() => void) | null = null;
private failed = false;
+ private frameDir = "";
+ private frameSequence = 0;
+ private readonly capturedFrames: CapturedVideoFrame[] = [];
+ private readonly frameWrites = new Set<Promise<void>>();
private readonly onChunk = (e: IpcMainEvent, chunk: Uint8Array) => {
if (e.sender !== this.win?.webContents || !this.stream) return;
@@ -65,6 +91,45 @@ export class VideoRecorder {
log.info("recording started; anchor epoch", epoch);
};
+ private readonly onFrame = (e: IpcMainEvent, frame: FrameMessage) => {
+ if (e.sender !== this.win?.webContents || !this.frameDir) return;
+ if (
+ !(frame?.data instanceof Uint8Array) ||
+ frame.data.byteLength === 0 ||
+ frame.data.byteLength > MAX_FRAME_BYTES ||
+ !Number.isFinite(frame.tMs) ||
+ !Number.isFinite(frame.offsetMs) ||
+ !validFrameDimension(frame.width) ||
+ !validFrameDimension(frame.height)
+ ) {
+ log.warn("ignored captured frame with invalid payload or metadata");
+ return;
+ }
+
+ const name = `frame_${String(++this.frameSequence).padStart(6, "0")}.jpg`;
+ const absolute = path.join(this.frameDir, name);
+ const relative = path.posix.join(VIDEO_FRAMES_DIR, name);
+ const pending = writeFile(absolute, Buffer.from(frame.data))
+ .then(() => {
+ this.capturedFrames.push({
+ file: relative,
+ tMs: Math.round(frame.tMs),
+ offsetMs: Math.max(0, Math.round(frame.offsetMs)),
+ width: Math.round(frame.width),
+ height: Math.round(frame.height),
+ });
+ })
+ .catch((err) => {
+ log.warn("failed to persist captured frame:", err instanceof Error ? err.message : err);
+ });
+ this.frameWrites.add(pending);
+ void pending.finally(() => this.frameWrites.delete(pending));
+ };
+
+ private readonly onFrameError = (e: IpcMainEvent, message: string) => {
+ if (e.sender === this.win?.webContents) log.warn("snapshot capture unavailable:", message);
+ };
+
private readonly onStopped = (e: IpcMainEvent) => {
if (e.sender !== this.win?.webContents) return;
this.stoppedResolve?.();
@@ -96,9 +161,16 @@ export class VideoRecorder {
this.bytes = 0;
this.startEpoch = null;
this.failed = false;
+ this.frameDir = path.join(sessionDir, VIDEO_FRAMES_DIR);
+ this.frameSequence = 0;
+ this.capturedFrames.length = 0;
+ this.frameWrites.clear();
+ await mkdir(this.frameDir, { recursive: true });
this.stream = createWriteStream(this.file);
ipcMain.on("video:chunk", this.onChunk);
+ ipcMain.on("video:frame", this.onFrame);
+ ipcMain.on("video:frame-error", this.onFrameError);
ipcMain.on("video:started", this.onStarted);
ipcMain.on("video:stopped", this.onStopped);
ipcMain.on("video:error", this.onError);
@@ -110,6 +182,7 @@ export class VideoRecorder {
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
+ backgroundThrottling: false,
},
});
await this.win.loadFile(path.join(dirname, "video", "capture.html"));
@@ -143,6 +216,7 @@ export class VideoRecorder {
const stopEpoch = Date.now();
await this.closeStream();
+ await Promise.allSettled([...this.frameWrites]);
const bytes = this.bytes;
const startEpoch = this.startEpoch;
@@ -150,13 +224,16 @@ export class VideoRecorder {
const failed = this.failed;
await this.teardown();
- if (failed || bytes === 0 || startEpoch == null) {
+ if (bytes === 0 || startEpoch == null) {
// Remove a useless/empty file so the session folder stays clean.
if (existsSync(file)) await unlink(file).catch(() => undefined);
+ await rm(this.frameDir, { recursive: true, force: true });
log.warn("no usable video captured");
return null;
}
+ if (failed) log.warn("capture ended with an error; preserving the usable partial recording");
+ const framesFile = await this.writeFrameManifest();
const result: VideoResult = {
file: path.basename(file),
startEpoch,
@@ -164,14 +241,41 @@ export class VideoRecorder {
durationMs: stopEpoch - startEpoch,
bytes,
fps: FPS,
+ framesVersion: CAPTURED_FRAME_MANIFEST_VERSION,
+ ...(framesFile ? { framesFile, frameCount: this.capturedFrames.length } : {}),
};
await writeFile(path.join(this.dirFor(file), "video.json"), JSON.stringify(result, null, 2)).catch(
(err) => log.warn("failed to write video.json:", err instanceof Error ? err.message : err),
);
- log.info(`video saved: ${result.file} (${(bytes / 1_000_000).toFixed(1)} MB, ${result.durationMs} ms)`);
+ log.info(
+ `video saved: ${result.file} (${(bytes / 1_000_000).toFixed(1)} MB, ` +
+ `${result.durationMs} ms, ${this.capturedFrames.length} source frames)`,
+ );
return result;
}
+ private async writeFrameManifest(): Promise<string | null> {
+ if (this.capturedFrames.length === 0) {
+ await rm(this.frameDir, { recursive: true, force: true });
+ return null;
+ }
+ const manifest: CapturedFrameManifest = {
+ version: CAPTURED_FRAME_MANIFEST_VERSION,
+ format: "jpeg",
+ heartbeatMs: FRAME_HEARTBEAT_MS,
+ frames: [...this.capturedFrames].sort((a, b) => a.tMs - b.tMs),
+ };
+ const file = path.join(this.dir, VIDEO_FRAMES_FILE);
+ const temp = `${file}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ await writeFile(temp, JSON.stringify(manifest, null, 2));
+ await rename(temp, file);
+ return VIDEO_FRAMES_FILE;
+ } finally {
+ await rm(temp, { force: true });
+ }
+ }
+
private dirFor(file: string): string {
return this.dir || path.dirname(file);
}
@@ -185,6 +289,8 @@ export class VideoRecorder {
private async teardown(): Promise<void> {
ipcMain.removeListener("video:chunk", this.onChunk);
+ ipcMain.removeListener("video:frame", this.onFrame);
+ ipcMain.removeListener("video:frame-error", this.onFrameError);
ipcMain.removeListener("video:started", this.onStarted);
ipcMain.removeListener("video:stopped", this.onStopped);
ipcMain.removeListener("video:error", this.onError);
@@ -199,3 +305,7 @@ export class VideoRecorder {
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+
+function validFrameDimension(value: number): boolean {
+ return Number.isFinite(value) && value > 0 && value <= 16_384;
+}
diff --git a/package-lock.json b/package-lock.json
index b40c692..4a1c413 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7,17 +7,18 @@
"": {
"name": "skill-recorder",
"version": "0.1.0",
+ "license": "MIT",
"dependencies": {
"@github/copilot-sdk": "^1.0.6",
"@huggingface/transformers": "^4.2.0",
- "ffmpeg-static": "^5.3.0",
- "get-windows": "^9.3.0",
+ "koffi": "^3.1.1",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"sharp": "^0.34.5",
"zod": "^4.3.6"
},
"devDependencies": {
+ "@electron/asar": "^3.4.1",
"@types/node": "^22.10.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
@@ -27,21 +28,9 @@
"typescript": "^7.0.0",
"vite": "^8.0.16",
"vite-plugin-electron": "1.0.4"
- }
- },
- "node_modules/@derhuerst/http-basic": {
- "version": "8.2.4",
- "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@derhuerst/http-basic/-/http-basic-8.2.4.tgz",
- "integrity": "sha1-0CHruPZdVL6mga5vSoczzonn9Zs=",
- "license": "MIT",
- "dependencies": {
- "caseless": "^0.12.0",
- "concat-stream": "^2.0.0",
- "http-response-object": "^3.0.1",
- "parse-cache-control": "^1.0.1"
},
- "engines": {
- "node": ">=6.0.0"
+ "optionalDependencies": {
+ "get-windows": "^9.3.0"
}
},
"node_modules/@electron-internal/extract-zip": {
@@ -316,7 +305,6 @@
"dev": true,
"license": "BSD-2-Clause",
"optional": true,
- "peer": true,
"dependencies": {
"cross-dirname": "^0.1.0",
"debug": "^4.3.4",
@@ -338,7 +326,6 @@
"dev": true,
"license": "MIT",
"optional": true,
- "peer": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
@@ -348,28 +335,6 @@
"node": ">=14.14"
}
},
- "node_modules/@emnapi/core": {
- "version": "1.11.1",
- "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/core/-/core-1.11.1.tgz",
- "integrity": "sha1-ueEGTzprFjHiQeY460jXNr/TcqY=",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/wasi-threads": "1.2.2",
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@emnapi/runtime": {
- "version": "1.11.2",
- "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/runtime/-/runtime-1.11.2.tgz",
- "integrity": "sha1-6yLwTXb+v99Ph/2v9UyKU/a/Db0=",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.2",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
@@ -1998,6 +1963,18 @@
"node": "^20.19.0 || >=22.12.0"
}
},
+ "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.11.1",
+ "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/core/-/core-1.11.1.tgz",
+ "integrity": "sha1-ueEGTzprFjHiQeY460jXNr/TcqY=",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.11.1",
"resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/runtime/-/runtime-1.11.1.tgz",
@@ -2159,6 +2136,7 @@
"integrity": "sha1-3MrDZbqg8XNOwnD/S1HIlGXo3H8=",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -2965,6 +2943,7 @@
"version": "1.1.2",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha1-KxRqb9cugLT1XSVfNe1Zo6mkG9U=",
+ "dev": true,
"license": "MIT"
},
"node_modules/builder-util": {
@@ -3264,12 +3243,6 @@
"node": ">= 0.4"
}
},
- "node_modules/caseless": {
- "version": "0.12.0",
- "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/caseless/-/caseless-0.12.0.tgz",
- "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=",
- "license": "Apache-2.0"
- },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/chalk/-/chalk-4.1.2.tgz",
@@ -3428,21 +3401,6 @@
"devOptional": true,
"license": "MIT"
},
- "node_modules/concat-stream": {
- "version": "2.0.0",
- "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/concat-stream/-/concat-stream-2.0.0.tgz",
- "integrity": "sha1-QUz1r3kKSMYKub5FJ9VtXkETPLE=",
- "engines": [
- "node >= 6.0"
- ],
- "license": "MIT",
- "dependencies": {
- "buffer-from": "^1.0.0",
- "inherits": "^2.0.3",
- "readable-stream": "^3.0.2",
- "typedarray": "^0.0.6"
- }
- },
"node_modules/confbox": {
"version": "0.2.4",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/confbox/-/confbox-0.2.4.tgz",
@@ -3470,8 +3428,7 @@
"integrity": "sha1-uJlZnzClOJ9Z54wVDhn5V60Wo3w=",
"dev": true,
"license": "MIT",
- "optional": true,
- "peer": true
+ "optional": true
},
"node_modules/cross-spawn": {
"version": "7.0.6",
@@ -3522,6 +3479,7 @@
"version": "4.4.3",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/debug/-/debug-4.4.3.tgz",
"integrity": "sha1-xq5DLZvZZiWC/OCHCbA4xY6ePWo=",
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -3688,6 +3646,7 @@
"integrity": "sha1-PQy/HT3GumvxmDaOW9rPGnNLYPw=",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"app-builder-lib": "26.15.6",
"builder-util": "26.15.3",
@@ -3888,7 +3847,6 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@electron/asar": "^3.2.1",
"debug": "^4.1.1",
@@ -3909,7 +3867,6 @@
"integrity": "sha1-TxicRKoSO4lfcigE9V6iPq3DSOk=",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"graceful-fs": "^4.1.2",
"jsonfile": "^4.0.0",
@@ -3925,7 +3882,6 @@
"integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=",
"dev": true,
"license": "MIT",
- "peer": true,
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
@@ -3936,7 +3892,6 @@
"integrity": "sha1-tkb2m+OULavOzJ1mOcgNwQXvqmY=",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 4.0.0"
}
@@ -3965,16 +3920,6 @@
"devOptional": true,
"license": "MIT"
},
- "node_modules/encoding": {
- "version": "0.1.13",
- "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/encoding/-/encoding-0.1.13.tgz",
- "integrity": "sha1-VldK/deR9UqOmyeFwFgqLSYhD6k=",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "iconv-lite": "^0.6.2"
- }
- },
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/end-of-stream/-/end-of-stream-1.4.5.tgz",
@@ -4136,56 +4081,6 @@
}
}
},
- "node_modules/ffmpeg-static": {
- "version": "5.3.0",
- "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ffmpeg-static/-/ffmpeg-static-5.3.0.tgz",
- "integrity": "sha1-MIn8AdG7nFjL50YxmG/ay9htixQ=",
- "hasInstallScript": true,
- "license": "GPL-3.0-or-later",
- "dependencies": {
- "@derhuerst/http-basic": "^8.2.0",
- "env-paths": "^2.2.0",
- "https-proxy-agent": "^5.0.0",
- "progress": "^2.0.3"
- },
- "engines": {
- "node": ">=16"
- }
- },
- "node_modules/ffmpeg-static/node_modules/agent-base": {
- "version": "6.0.2",
- "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/agent-base/-/agent-base-6.0.2.tgz",
- "integrity": "sha1-Sf/1hXfP7j83F2/qtMIuAPhtf3c=",
- "license": "MIT",
- "dependencies": {
- "debug": "4"
- },
- "engines": {
- "node": ">= 6.0.0"
- }
- },
- "node_modules/ffmpeg-static/node_modules/env-paths": {
- "version": "2.2.1",
- "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/env-paths/-/env-paths-2.2.1.tgz",
- "integrity": "sha1-QgOZ1BbOH76bwKB8Yvpo1n/Q+PI=",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/ffmpeg-static/node_modules/https-proxy-agent": {
- "version": "5.0.1",
- "resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
- "integrity": "sha1-xZ7yJKBP6LdU89sAY6Jeow0ABdY=",
- "license": "MIT",
- "dependencies": {
- "agent-base": "6",
- "debug": "4"
- },
- "engines": {
- "node": ">= 6"
- }
- },
"node_modules/filelist": {
"version": "1.0.6",
"resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/filelist/-/filelist-1.0.6.tgz",
@@ -4444,6 +4339,7 @@
"integrity": "sha1-waEA4kcjEctVIWomIIMqL4ooGrw=",
"hasInstallScript": true,
"license": "MIT",
+ "optional": true,
"engines": {
"node": ">=18.18"
},
@@ -4927,21 +4823,6 @@
"node": ">= 14"
}
},
- "node_modules/http-response-object": {
- "version": "3.0.2",
- "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/http-response-object/-/http-response-object-3.0.2.tgz",
- "integrity": "sha1-f0NbshBFTkNg0HTvH5idXqiqmBA=",
- "license": "MIT",
- "dependencies": {
- "@types/node": "^10.0.3"
- }
- },
- "node_modules/http-response-object/node_modules/@types/node": {
- "version": "10.17.60",
- "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@types/node/-/node-10.17.60.tgz",
- "integrity": "sha1-NfPWIT2u2V2n8Pc+dbzGmA6QWXs=",
- "license": "MIT"
- },
"node_modules/http2-wrapper": {
"version": "1.0.3",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/http2-wrapper/-/http2-wrapper-1.0.3.tgz",
@@ -5019,6 +4900,7 @@
"version": "2.0.4",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha1-D6LGT5MpF8NDOg3tVTY6rjdBa3w=",
+ "devOptional": true,
"license": "ISC"
},
"node_modules/ip-address": {
@@ -5869,7 +5751,6 @@
"integrity": "sha1-fe8D0kMtyuS6HWEURcSDlgYiVfY=",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"minimist": "^1.2.6"
},
@@ -5913,6 +5794,7 @@
"version": "2.1.3",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/ms/-/ms-2.1.3.tgz",
"integrity": "sha1-V0yBOM4dK1hh8LRFedut1gxmFbI=",
+ "devOptional": true,
"license": "MIT"
},
"node_modules/nanoid": {
@@ -6266,11 +6148,6 @@
"license": "BlueOak-1.0.0",
"optional": true
},
- "node_modules/parse-cache-control": {
- "version": "1.0.1",
- "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/parse-cache-control/-/parse-cache-control-1.0.1.tgz",
- "integrity": "sha1-juqz5U+laSD+Fro493+iGqzC104="
- },
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
@@ -6350,6 +6227,7 @@
"integrity": "sha1-UepXoX2G9gX4EDlZX7xA7QalX6s=",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -6457,7 +6335,6 @@
"dev": true,
"license": "MIT",
"optional": true,
- "peer": true,
"dependencies": {
"commander": "^9.4.0"
},
@@ -6475,7 +6352,6 @@
"dev": true,
"license": "MIT",
"optional": true,
- "peer": true,
"engines": {
"node": "^12.20.0 || >=14"
}
@@ -6501,6 +6377,7 @@
"version": "2.0.3",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/progress/-/progress-2.0.3.tgz",
"integrity": "sha1-foz42PW48jnBvGi+tOt4Vn1XLvg=",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
@@ -6621,6 +6498,7 @@
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/react/-/react-19.2.7.tgz",
"integrity": "sha1-H0ehv8BvjsiFdSxvSvFDaan4Jgs=",
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -6655,6 +6533,7 @@
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha1-VqmzbqllwAxak+8x6xEaDxEFaWc=",
"license": "MIT",
+ "optional": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
@@ -6818,7 +6697,8 @@
"url": "https://feross.org/support"
}
],
- "license": "MIT"
+ "license": "MIT",
+ "optional": true
},
"node_modules/safer-buffer": {
"version": "2.1.2",
@@ -7086,6 +6966,7 @@
"resolved": "https://ms-feed-2.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha1-QvEUWUpGzxqOMLCoT1bHjD7awh4=",
"license": "MIT",
+ "optional": true,
"dependencies": {
"safe-buffer": "~5.2.0"
}
@@ -7207,7 +7088,6 @@
"integrity": "sha1-zSCoWAy2NjXQ5OnUvZidRChudiA=",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"mkdirp": "^0.5.1",
"rimraf": "~2.6.2"
@@ -7234,7 +7114,6 @@
"deprecated": "Rimraf versions prior to v4 are no longer supported",
"dev": true,
"license": "ISC",
- "peer": true,
"dependencies": {
"glob": "^7.1.3"
},
@@ -7335,12 +7214,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/typedarray": {
- "version": "0.0.6",
- "resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/typedarray/-/typedarray-0.0.6.tgz",
- "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
- "license": "MIT"
- },
"node_modules/typescript": {
"version": "7.0.2",
"resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/typescript/-/typescript-7.0.2.tgz",
@@ -7476,6 +7349,7 @@
"version": "1.0.2",
"resolved": "https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
+ "devOptional": true,
"license": "MIT"
},
"node_modules/vite": {
@@ -7484,6 +7358,7 @@
"integrity": "sha1-zP/OPuSHsYhiI7JOuye5FnSCfTA=",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.5",
diff --git a/package.json b/package.json
index 2a625d7..e422b37 100644
--- a/package.json
+++ b/package.json
@@ -3,6 +3,7 @@
"version": "0.1.0",
"description": "Records a user's on-screen work session and derives a structured description for building AI-agent skills.",
"author": "Skill Recorder",
+ "repository": "github:adilei/skill-recorder",
"license": "MIT",
"private": true,
"type": "module",
@@ -13,23 +14,29 @@
"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",
"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",
- "dist": "vite build && electron-builder",
+ "dist": "node scripts/assert-generic-dist-platform.mjs && vite build && electron-builder",
+ "dist:win:x64": "node scripts/assert-native-windows-arch.mjs x64 && vite build && electron-builder --win nsis --x64",
+ "dist:win:arm64": "node scripts/assert-native-windows-arch.mjs arm64 && vite build && electron-builder --win nsis --arm64",
"start": "electron ."
},
"dependencies": {
"@github/copilot-sdk": "^1.0.6",
"@huggingface/transformers": "^4.2.0",
- "ffmpeg-static": "^5.3.0",
- "get-windows": "^9.3.0",
+ "koffi": "^3.1.1",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"sharp": "^0.34.5",
"zod": "^4.3.6"
},
+ "optionalDependencies": {
+ "get-windows": "^9.3.0"
+ },
"devDependencies": {
+ "@electron/asar": "^3.4.1",
"@types/node": "^22.10.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
@@ -46,13 +53,17 @@
"files": [
"dist/**",
"dist-electron/**",
- "package.json"
+ "package.json",
+ "LICENSE",
+ "THIRD-PARTY-NOTICES.md"
],
"asarUnpack": [
"node_modules/get-windows/**",
"node_modules/sharp/**",
"node_modules/@img/**",
- "node_modules/ffmpeg-static/**",
+ "node_modules/koffi/**",
+ "node_modules/@koromix/**",
+ "node_modules/@github/copilot-*/**",
"node_modules/@huggingface/transformers/**",
"node_modules/onnxruntime-node/**"
],
@@ -61,20 +72,32 @@
"dmg",
"zip"
],
+ "extraResources": [
+ {
+ "from": "node_modules/electron/dist/LICENSE",
+ "to": "LICENSE.electron.txt"
+ },
+ {
+ "from": "node_modules/electron/dist/LICENSES.chromium.html",
+ "to": "LICENSES.chromium.html"
+ }
+ ],
"category": "public.app-category.developer-tools",
"extendInfo": {
"NSMicrophoneUsageDescription": "Skill Recorder uses your microphone only while you turn on Narrate during a recording, to transcribe your spoken narration on this computer."
}
},
"win": {
- "target": [
- {
- "target": "nsis",
- "arch": [
- "x64"
- ]
- }
- ]
+ "files": [
+ "dist/**",
+ "dist-electron/**",
+ "package.json",
+ "LICENSE",
+ "THIRD-PARTY-NOTICES.md",
+ "!node_modules/get-windows/**"
+ ],
+ "target": "nsis",
+ "artifactName": "${productName}-${version}-windows-${arch}.${ext}"
},
"nsis": {
"oneClick": false,
diff --git a/scripts/assert-generic-dist-platform.mjs b/scripts/assert-generic-dist-platform.mjs
new file mode 100644
index 0000000..2993f6b
--- /dev/null
+++ b/scripts/assert-generic-dist-platform.mjs
@@ -0,0 +1,5 @@
+if (process.platform === "win32") {
+ throw new Error(
+ `Use npm run dist:win:${process.arch} on Windows so Electron and native optional dependencies have the same architecture.`,
+ );
+}
diff --git a/scripts/assert-native-windows-arch.mjs b/scripts/assert-native-windows-arch.mjs
new file mode 100644
index 0000000..976a419
--- /dev/null
+++ b/scripts/assert-native-windows-arch.mjs
@@ -0,0 +1,11 @@
+const requestedArch = process.argv[2];
+if (requestedArch !== "x64" && requestedArch !== "arm64") {
+ throw new Error("Usage: node scripts/assert-native-windows-arch.mjs <x64|arm64>");
+}
+
+if (process.platform !== "win32" || process.arch !== requestedArch) {
+ throw new Error(
+ `Windows ${requestedArch} packages must be built with ${requestedArch} Node.js on ${requestedArch} Windows. ` +
+ `The current host is ${process.platform}-${process.arch}; cross-packaging would embed native dependencies for the wrong architecture.`,
+ );
+}
diff --git a/scripts/verify-windows-package.mjs b/scripts/verify-windows-package.mjs
new file mode 100644
index 0000000..6ab170c
--- /dev/null
+++ b/scripts/verify-windows-package.mjs
@@ -0,0 +1,138 @@
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+
+const require = createRequire(import.meta.url);
+const { listPackage } = require("@electron/asar");
+
+const arch = process.argv[2];
+if (arch !== "x64" && arch !== "arm64") {
+ throw new Error("Usage: node scripts/verify-windows-package.mjs <x64|arm64>");
+}
+
+const outputRoot = path.resolve("dist");
+const unpacked = readdirSync(outputRoot)
+ .map((name) => path.join(outputRoot, name))
+ .find(
+ (entry) =>
+ statSync(entry).isDirectory() &&
+ path.basename(entry) === (arch === "arm64" ? "win-arm64-unpacked" : "win-unpacked"),
+ );
+if (!unpacked) throw new Error(`Could not find the ${arch} unpacked Windows application.`);
+
+const appExe = path.join(unpacked, "Skill Recorder.exe");
+const expectedMachine = arch === "arm64" ? 0xaa64 : 0x8664;
+verifyPeMachine(appExe, expectedMachine);
+verifyPeMachine(path.join(unpacked, "ffmpeg.dll"), expectedMachine);
+
+const asarPath = path.join(unpacked, "resources", "app.asar");
+const asarEntries = listPackage(asarPath).map((entry) =>
+ entry.replace(/^[\\/]+/, "").replaceAll("\\", "/").toLowerCase(),
+);
+const asarFiles = asarEntries.map((entry) => `${asarPath}!${entry}`);
+const files = [...walk(unpacked), ...asarFiles];
+const normalizedFiles = files.map((file) => file.toLowerCase().replaceAll("\\", "/"));
+const expectedPayloads = [
+ {
+ packagePath: `/@koromix/koffi-win32-${arch}/`,
+ executable: `/@koromix/koffi-win32-${arch}/win32_${arch}/koffi.node`,
+ },
+ {
+ packagePath: `/@img/sharp-win32-${arch}/`,
+ executable: `/@img/sharp-win32-${arch}/lib/sharp-win32-${arch}.node`,
+ },
+ {
+ packagePath: `/onnxruntime-node/bin/napi-v6/win32/${arch}/`,
+ executable: `/onnxruntime-node/bin/napi-v6/win32/${arch}/onnxruntime_binding.node`,
+ },
+ {
+ packagePath: `/@github/copilot-win32-${arch}/`,
+ executable: `/@github/copilot-win32-${arch}/copilot.exe`,
+ },
+];
+for (const payload of expectedPayloads) {
+ if (!normalizedFiles.some((file) => file.includes(payload.packagePath))) {
+ throw new Error(`Packaged ${arch} application is missing ${payload.packagePath}.`);
+ }
+
+ const executableIndex = normalizedFiles.findIndex((file) => file.endsWith(payload.executable));
+ if (executableIndex === -1) {
+ throw new Error(`Packaged ${arch} application is missing ${payload.executable}.`);
+ }
+ verifyPeMachine(files[executableIndex], expectedMachine);
+}
+
+const otherArch = arch === "arm64" ? "x64" : "arm64";
+const wrongArchitecturePayloads = [
+ `/@koromix/koffi-win32-${otherArch}/`,
+ `/@img/sharp-win32-${otherArch}/`,
+ `/@github/copilot-win32-${otherArch}/copilot.exe`,
+];
+for (const wrongPayload of wrongArchitecturePayloads) {
+ if (normalizedFiles.some((file) => file.includes(wrongPayload))) {
+ throw new Error(`Packaged ${arch} application contains ${wrongPayload}.`);
+ }
+}
+
+const forbiddenStandaloneFfmpeg = normalizedFiles.filter(
+ (file) =>
+ file.includes("/ffmpeg-static/") ||
+ /\/ffmpeg(?:\.exe)?$/.test(file),
+);
+if (forbiddenStandaloneFfmpeg.length > 0) {
+ throw new Error(
+ `Packaged application contains a forbidden standalone FFmpeg payload:\n${forbiddenStandaloneFfmpeg.join("\n")}`,
+ );
+}
+
+for (const notice of ["LICENSE.electron.txt", "LICENSES.chromium.html"]) {
+ if (!normalizedFiles.includes(path.join(unpacked, notice).toLowerCase().replaceAll("\\", "/"))) {
+ throw new Error(`Packaged application is missing Electron license notice ${notice}.`);
+ }
+}
+for (const notice of ["third-party-notices.md", "license"]) {
+ if (!normalizedFiles.some((file) => file.endsWith(`app.asar!${notice}`))) {
+ throw new Error(`Packaged application is missing application notice ${notice}.`);
+ }
+}
+const forbiddenSourceRoots = ["common", "docs", "electron", "evals", "scripts", "src"];
+for (const root of forbiddenSourceRoots) {
+ if (asarEntries.some((entry) => entry === root || entry.startsWith(`${root}/`))) {
+ throw new Error(`Packaged application contains source-only directory ${root}/.`);
+ }
+}
+
+console.log(
+ `Verified native ${arch} package, asar contents, license notices, and no standalone FFmpeg: ` +
+ path.relative(process.cwd(), unpacked),
+);
+
+function verifyPeMachine(file, expected) {
+ const executable = readFileSync(file);
+ if (executable.length < 0x40) throw new Error(`${file} is too short to be a PE executable.`);
+
+ const peOffset = executable.readUInt32LE(0x3c);
+ if (peOffset + 6 > executable.length) {
+ throw new Error(`${file} has an invalid PE header offset.`);
+ }
+
+ const signature = executable.toString("ascii", peOffset, peOffset + 4);
+ if (signature !== "PE\u0000\u0000") throw new Error(`${file} is not a PE executable.`);
+
+ const machine = executable.readUInt16LE(peOffset + 4);
+ if (machine !== expected) {
+ throw new Error(
+ `${file} has PE machine 0x${machine.toString(16)}, expected 0x${expected.toString(16)}.`,
+ );
+ }
+}
+
+function walk(root) {
+ const output = [];
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
+ const absolute = path.join(root, entry.name);
+ if (entry.isDirectory()) output.push(...walk(absolute));
+ else output.push(absolute);
+ }
+ return output;
+}
diff --git a/src/Recorder.tsx b/src/Recorder.tsx
index ab55ada..062f1b0 100644
--- a/src/Recorder.tsx
+++ b/src/Recorder.tsx
@@ -252,7 +252,7 @@ export function Recorder() {
<Row
label="window tracking"
status={doctor.activeWindow.ok ? "good" : "bad"}
- note={doctor.activeWindow.ok ? "native" : "addon missing"}
+ note={doctor.activeWindow.ok ? doctor.activeWindow.provider : "provider missing"}
/>
{doctor.activeSources.some((s) => s.key === "browserUrls") && (
<Row
@@ -261,11 +261,6 @@ export function Recorder() {
note={doctor.browserUrl.supported ? doctor.browserUrl.kind : "not on this OS"}
/>
)}
- <Row
- label="ffmpeg"
- status={doctor.ffmpeg.ok ? "good" : "bad"}
- note={doctor.ffmpeg.ok ? doctor.ffmpeg.source : "missing"}
- />
<Row
label="copilot CLI"
status={doctor.copilotCli.ok ? "good" : "bad"}
diff --git a/vite.config.ts b/vite.config.ts
index 2b46ac3..53ae27b 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -58,8 +58,8 @@ export default defineConfig({
"electron",
"@github/copilot-sdk",
"get-windows",
+ "koffi",
"sharp",
- "ffmpeg-static",
"@huggingface/transformers",
"onnxruntime-node",
],