Skip to content

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

fix(wgc): capture per-step stop timing, bump timeout, add diagnostic tool

EtienneLescot09f6348d7eb5
diff --git a/.github/workflows/diagnostic-artifact.yml b/.github/workflows/diagnostic-artifact.yml
new file mode 100644
index 000000000..24a87c2ad
--- /dev/null
+++ b/.github/workflows/diagnostic-artifact.yml
@@ -0,0 +1,107 @@
+name: Diagnostic artifact
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build-windows:
+ name: Windows x64 diagnostic bundle
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Build native helper
+ run: npm run build:native:win
+
+ - name: Bundle diagnostic tool
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = "Stop"
+ $bundle = "openscreen-diagnostic-windows-x64"
+ $staging = New-Item -ItemType Directory -Path "$bundle"
+ Copy-Item scripts/diagnostic-tool/diagnostic.mjs -Destination $staging
+ Copy-Item scripts/diagnostic-tool/diagnostic.bat -Destination $staging
+ Copy-Item scripts/diagnostic-tool/README.md -Destination $staging
+ New-Item -ItemType Directory -Path "$staging/helpers/win32-x64" | Out-Null
+ Copy-Item electron/native/bin/win32-x64/wgc-capture.exe -Destination "$staging/helpers/win32-x64/"
+ Compress-Archive -Path "$staging" -DestinationPath "$bundle.zip"
+
+ - name: Smoke-test the bundle
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = "Stop"
+ Expand-Archive -Path openscreen-diagnostic-windows-x64.zip -DestinationPath smoke
+ $smoke = Resolve-Path "smoke/openscreen-diagnostic-windows-x64"
+ & "$smoke/diagnostic.bat" --duration 3 --output "$smoke/smoke.json"
+ $report = Get-Content "$smoke/smoke.json" -Raw | ConvertFrom-Json
+ if ($report.exitCode -ne 0) { throw "Smoke test failed: exitCode=$($report.exitCode)" }
+ if ($report.stopTiming.Count -lt 1) { throw "Smoke test produced no [stop-timing] entries" }
+
+ - name: Upload Windows diagnostic bundle
+ uses: actions/upload-artifact@v4
+ with:
+ name: openscreen-diagnostic-windows-x64
+ path: openscreen-diagnostic-windows-x64.zip
+ if-no-files-found: error
+ retention-days: 14
+
+ build-macos:
+ name: macOS ${{ matrix.arch }} diagnostic bundle
+ runs-on: macos-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: [arm64, x64]
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Build native helper
+ run: npm run build:native:mac
+ env:
+ OPENSCREEN_MAC_HELPER_ARCHS: ${{ matrix.arch }}
+
+ - name: Bundle diagnostic tool
+ run: |
+ set -euo pipefail
+ arch="${{ matrix.arch }}"
+ arch_tag="darwin-$([ "$arch" = "x64" ] && echo x64 || echo arm64)"
+ bundle="openscreen-diagnostic-macos-$arch"
+ rm -rf "$bundle" "$bundle.tar.gz"
+ mkdir -p "$bundle/helpers/$arch_tag"
+ cp scripts/diagnostic-tool/diagnostic.mjs "$bundle/"
+ cp scripts/diagnostic-tool/diagnostic.sh "$bundle/"
+ cp scripts/diagnostic-tool/README.md "$bundle/"
+ cp "electron/native/bin/$arch_tag/openscreen-screencapturekit-helper" "$bundle/helpers/$arch_tag/"
+ chmod +x "$bundle/diagnostic.sh" "$bundle/helpers/$arch_tag/openscreen-screencapturekit-helper"
+ tar -czf "$bundle.tar.gz" "$bundle"
+
+ - name: Upload macOS diagnostic bundle
+ uses: actions/upload-artifact@v4
+ with:
+ name: openscreen-diagnostic-macos-${{ matrix.arch }}
+ path: openscreen-diagnostic-macos-${{ matrix.arch }}.tar.gz
+ if-no-files-found: error
+ retention-days: 14
\ No newline at end of file
diff --git a/electron/diagnostics/main-log-buffer.test.ts b/electron/diagnostics/main-log-buffer.test.ts
new file mode 100644
index 000000000..b83511826
--- /dev/null
+++ b/electron/diagnostics/main-log-buffer.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { MainLogBuffer } from "./main-log-buffer";
+
+describe("MainLogBuffer", () => {
+ const buffers: MainLogBuffer[] = [];
+
+ function make(capacity: number) {
+ const b = new MainLogBuffer(capacity);
+ buffers.push(b);
+ return b;
+ }
+
+ afterEach(() => {
+ for (const b of buffers) b.uninstall();
+ buffers.length = 0;
+ });
+
+ it("captures every console level and routes to original", () => {
+ const buf = make(10);
+ const captured: string[] = [];
+ const original = {
+ log: (...args: unknown[]) => captured.push(`log:${args.join(",")}`),
+ info: (...args: unknown[]) => captured.push(`info:${args.join(",")}`),
+ warn: (...args: unknown[]) => captured.push(`warn:${args.join(",")}`),
+ error: (...args: unknown[]) => captured.push(`error:${args.join(",")}`),
+ };
+ Object.assign(console, original);
+ buf.install();
+ console.log("hello");
+ console.info("world");
+ console.warn("watch");
+ console.error("bad");
+ const snap = buf.snapshot();
+ expect(snap.map((e) => e.level)).toEqual(["log", "info", "warn", "error"]);
+ expect(snap.map((e) => e.text)).toEqual(["hello", "world", "watch", "bad"]);
+ expect(captured).toEqual(["log:hello", "info:world", "warn:watch", "error:bad"]);
+ });
+
+ it("stringifies non-string args", () => {
+ const buf = make(5);
+ buf.install();
+ console.info({ a: 1 });
+ const snap = buf.snapshot();
+ expect(snap[0].text).toBe('{"a":1}');
+ });
+
+ it("drops oldest entries past capacity", () => {
+ const buf = make(3);
+ buf.install();
+ for (let i = 0; i < 5; i += 1) console.info(`line ${i}`);
+ const snap = buf.snapshot();
+ expect(snap.map((e) => e.text)).toEqual(["line 2", "line 3", "line 4"]);
+ });
+
+ it("uninstall restores originals", () => {
+ const buf = make(5);
+ buf.install();
+ console.info("captured");
+ buf.uninstall();
+ console.info("after-uninstall");
+ const snap = buf.snapshot();
+ expect(snap.map((e) => e.text)).toEqual(["captured"]);
+ });
+
+ it("clear empties the buffer", () => {
+ const buf = make(5);
+ buf.install();
+ console.info("one");
+ console.info("two");
+ buf.clear();
+ expect(buf.snapshot()).toEqual([]);
+ });
+
+ it("install is idempotent", () => {
+ const buf = make(5);
+ buf.install();
+ buf.install();
+ console.info("once");
+ const snap = buf.snapshot();
+ expect(snap.map((e) => e.text)).toEqual(["once"]);
+ });
+});
diff --git a/electron/diagnostics/main-log-buffer.ts b/electron/diagnostics/main-log-buffer.ts
new file mode 100644
index 000000000..ba12ffefe
--- /dev/null
+++ b/electron/diagnostics/main-log-buffer.ts
@@ -0,0 +1,102 @@
+/**
+ * Ring buffer for main-process console output.
+ *
+ * Captures the last `capacity` lines written via console.info / console.warn /
+ * console.error / console.log into a single in-memory buffer. Disabled by
+ * default — install only when verbose diagnostics are wanted, e.g. when
+ * OPENSCREEN_DIAGNOSTIC=1 is set or when a developer wants a more complete
+ * "Save Diagnostics" payload for an upstream bug report.
+ *
+ * Cost when enabled: one array.push + occasional shift per console call,
+ * negligible against the rest of the app. Cost when disabled: zero, the
+ * original console methods are kept untouched.
+ */
+
+const DEFAULT_CAPACITY = 500;
+
+export interface MainLogEntry {
+ timestampMs: number;
+ level: "info" | "warn" | "error" | "log";
+ text: string;
+}
+
+export class MainLogBuffer {
+ private readonly capacity: number;
+ private readonly entries: MainLogEntry[] = [];
+ private installed = false;
+ private readonly originals: Partial<
+ Record<"log" | "info" | "warn" | "error", (...args: unknown[]) => void>
+ > = {};
+
+ constructor(capacity = DEFAULT_CAPACITY) {
+ this.capacity = Math.max(1, capacity);
+ }
+
+ install(): void {
+ if (this.installed) return;
+ this.installed = true;
+ const console_ = console as unknown as Record<
+ "log" | "info" | "warn" | "error",
+ (...args: unknown[]) => void
+ >;
+ for (const level of ["log", "info", "warn", "error"] as const) {
+ this.originals[level] = console_[level].bind(console);
+ console_[level] = (...args: unknown[]) => {
+ this.push(level, args);
+ this.originals[level]?.(...args);
+ };
+ }
+ }
+
+ uninstall(): void {
+ if (!this.installed) return;
+ this.installed = false;
+ const console_ = console as unknown as Record<
+ "log" | "info" | "warn" | "error",
+ (...args: unknown[]) => void
+ >;
+ for (const level of ["log", "info", "warn", "error"] as const) {
+ if (this.originals[level]) {
+ console_[level] = this.originals[level] as (...args: unknown[]) => void;
+ }
+ }
+ this.originals.log = undefined;
+ this.originals.info = undefined;
+ this.originals.warn = undefined;
+ this.originals.error = undefined;
+ }
+
+ snapshot(): MainLogEntry[] {
+ return this.entries.slice();
+ }
+
+ clear(): void {
+ this.entries.length = 0;
+ }
+
+ private push(level: MainLogEntry["level"], args: unknown[]): void {
+ const text = args
+ .map((arg) => {
+ if (typeof arg === "string") return arg;
+ try {
+ return JSON.stringify(arg);
+ } catch {
+ return String(arg);
+ }
+ })
+ .join(" ");
+ this.entries.push({ timestampMs: Date.now(), level, text });
+ if (this.entries.length > this.capacity) {
+ this.entries.splice(0, this.entries.length - this.capacity);
+ }
+ }
+}
+
+export const mainLogBuffer = new MainLogBuffer();
+
+export function isDiagnosticModeEnabled(): boolean {
+ const raw = process.env.OPENSCREEN_DIAGNOSTIC;
+ if (!raw) return false;
+ const lowered = raw.trim().toLowerCase();
+ return lowered === "1" || lowered === "true" || lowered === "yes";
+}
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index d02c6cdec..e32ef3635 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -35,6 +35,7 @@ import type {
ProjectFileResult,
ProjectPathResult,
} from "../../src/native/contracts";
+import { mainLogBuffer } from "../diagnostics/main-log-buffer";
import { mainT } from "../i18n";
import { RECORDINGS_DIR } from "../main";
import { createCursorRecordingSession } from "../native-bridge/cursor/recording/factory";
@@ -412,7 +413,7 @@ let nativeWindowsCursorRecordingStartMs = 0;
let nativeWindowsPauseStartedAtMs: number | null = null;
let nativeWindowsPauseRanges: Array<{ startMs: number; endMs: number }> = [];
let nativeWindowsIsPaused = false;
-const NATIVE_WINDOWS_CAPTURE_STOP_TIMEOUT_MS = 15_000;
+const NATIVE_WINDOWS_CAPTURE_STOP_TIMEOUT_MS = 60_000;
let nativeMacCaptureProcess: ChildProcessWithoutNullStreams | null = null;
let nativeMacCaptureOutput = "";
let nativeMacCaptureTargetPath: string | null = null;
@@ -2873,6 +2874,9 @@ export function registerIpcHandlers(
if (canceled || !filePath) return { success: false, canceled: true };
+ const HELPER_OUTPUT_MAX_BYTES = 64 * 1024;
+ const tail = (s: string, max: number) => (s.length <= max ? s : s.slice(s.length - max));
+
const diagnostic = {
timestamp: new Date().toISOString(),
appVersion: app.getVersion(),
@@ -2888,6 +2892,11 @@ export function registerIpcHandlers(
stack: payload.stack,
projectState: payload.projectState,
recentLogs: payload.logs,
+ helperOutput: {
+ windows: tail(nativeWindowsCaptureOutput, HELPER_OUTPUT_MAX_BYTES),
+ mac: tail(nativeMacCaptureOutput, HELPER_OUTPUT_MAX_BYTES),
+ },
+ mainProcessLogs: mainLogBuffer.snapshot(),
};
try {
diff --git a/electron/main.ts b/electron/main.ts
index c2d7a4d48..a8e743fc9 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -12,6 +12,7 @@ import {
Tray,
} from "electron";
import { ShortcutBinding } from "../src/lib/shortcuts";
+import { isDiagnosticModeEnabled, mainLogBuffer } from "./diagnostics/main-log-buffer";
import {
loadAndRegisterGlobalShortcut,
registerOpenAppShortcut,
@@ -478,6 +479,11 @@ app.on("will-quit", () => {
const appReady = hasSingleInstanceLock ? app.whenReady() : null;
appReady?.then(async () => {
+ if (isDiagnosticModeEnabled()) {
+ mainLogBuffer.install();
+ console.info("[diagnostic] OPENSCREEN_DIAGNOSTIC=1, capturing console.* into ring buffer");
+ }
+
// Force "regular" activation policy so the Dock icon appears. The HUD overlay
// (transparent, frameless, skipTaskbar) is the first window, and AppKit would
// otherwise classify us as an accessory app.
diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cpp
index 9ea4e59df..af73b26fc 100644
--- a/electron/native/wgc-capture/src/main.cpp
+++ b/electron/native/wgc-capture/src/main.cpp
@@ -823,19 +823,34 @@ int main(int argc, char* argv[]) {
});
}
+ const auto stopStart = std::chrono::steady_clock::now();
+ auto logStopStep = [&](const char* step) {
+ const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - stopStart).count();
+ std::cerr << "[stop-timing] step=" << step << " elapsed_ms=" << ms << std::endl;
+ };
+
microphoneCapture.stop();
+ logStopStep("microphone");
loopbackCapture.stop();
+ logStopStep("loopback");
webcamCapture.stop();
+ logStopStep("webcam");
if (audioMixer) {
audioMixer->stop();
}
+ logStopStep("audio-mixer");
stopVideoWriter();
+ logStopStep("video-writer-join");
session.stop();
+ logStopStep("wgc-session-close");
{
std::scoped_lock lock(mutex);
encoder.finalize();
+ logStopStep("encoder-finalize");
if (writeSeparateWebcam) {
webcamEncoder.finalize();
+ logStopStep("webcam-encoder-finalize");
}
}
diff --git a/package.json b/package.json
index dffae9025..e3ee24a6b 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,8 @@
"test:wgc-full:win": "node scripts/test-windows-wgc-helper.mjs --webcam --system-audio --microphone",
"capture:openscreen-preview": "node scripts/capture-openscreen-preview.mjs",
"inspect:cursor-click-bounce": "node scripts/inspect-native-cursor-click-bounce.mjs",
+ "diagnostic:run": "node scripts/diagnostic-tool/diagnostic.mjs",
+ "diagnostic:smoke:win": "node scripts/diagnostic-tool/diagnostic.mjs --duration 3",
"build-vite": "tsc && vite build",
"test:browser": "vitest --config vitest.browser.config.ts --run",
"test:browser:install": "playwright install --with-deps chromium-headless-shell",
diff --git a/scripts/diagnostic-tool/README.md b/scripts/diagnostic-tool/README.md
new file mode 100644
index 000000000..aa286210c
--- /dev/null
+++ b/scripts/diagnostic-tool/README.md
@@ -0,0 +1,65 @@
+# OpenScreen standalone diagnostic tool
+
+A small Node.js script that runs the native capture helper outside the
+Electron app, captures its stdout/stderr, and writes a JSON report.
+
+Used to capture `[stop-timing]` lines emitted by the WGC / ScreenCaptureKit
+helper when a recording stop hangs, so the issue reporter can attach the
+data without installing or rebuilding the full app.
+
+## Requirements
+
+- Node.js 22+ (OpenScreen's own engine pin)
+- The native capture helper for your platform in one of:
+ - the same directory as `diagnostic.mjs` (`wgc-capture.exe` on Windows,
+ `openscreen-screencapturekit-helper` on macOS)
+ - `helpers/<platform>-<arch>/<helper-name>` (CI artifact layout)
+ - `$OPENSCREEN_HELPER_EXE` env var
+
+Linux is not currently supported — OpenScreen has no Linux native helper.
+
+## Usage
+
+```
+node diagnostic.mjs --duration 10 --output ./diag.json
+```
+
+Flags:
+- `-d, --duration <seconds>` recording length before sending stop (default 10)
+- `-o, --output <path>` output JSON path (default `./openscreen-diagnostic-<timestamp>.json`)
+- `--window` capture a window instead of the full display (default: display)
+- `-h, --help` show help
+
+Or use the bundled launcher:
+- Windows: `diagnostic.bat`
+- macOS / Linux: `./diagnostic.sh`
+
+## Output
+
+The JSON contains:
+- system info (platform, arch, OS, CPU, memory)
+- the helper's full stdout and stderr
+- parsed `[stop-timing]` entries as a structured array
+- the JSON config that was sent to the helper
+- exit code / signal
+
+Attach the JSON to a GitHub issue. Maintainers will read the
+`stopTiming` array and the helper stderr to pinpoint which step of the
+stop cleanup is slow.
+
+## Layout
+
+```
+scripts/diagnostic-tool/
+ README.md
+ diagnostic.mjs # the tool
+ diagnostic.bat # Windows launcher
+ diagnostic.sh # macOS / Linux launcher
+```
+
+## CI artifacts
+
+`.github/workflows/diagnostic-artifact.yml` builds per-platform zips
+that bundle this directory with the prebuilt helper. The workflow runs on
+every push to main and on manual dispatch; artifacts are retained for 14
+days.
\ No newline at end of file
diff --git a/scripts/diagnostic-tool/diagnostic.bat b/scripts/diagnostic-tool/diagnostic.bat
new file mode 100644
index 000000000..d709fe751
--- /dev/null
+++ b/scripts/diagnostic-tool/diagnostic.bat
@@ -0,0 +1,3 @@
+@echo off
+setlocal
+node "%~dp0diagnostic.mjs" %*
\ No newline at end of file
diff --git a/scripts/diagnostic-tool/diagnostic.mjs b/scripts/diagnostic-tool/diagnostic.mjs
new file mode 100644
index 000000000..77875ec5e
--- /dev/null
+++ b/scripts/diagnostic-tool/diagnostic.mjs
@@ -0,0 +1,298 @@
+#!/usr/bin/env node
+// OpenScreen standalone diagnostic tool.
+//
+// Runs the native capture helper outside the Electron app, captures its
+// stdout/stderr, and writes a JSON report you can attach to a bug report.
+// Used to capture [stop-timing] lines from the helper without requiring the
+// full app to install/reproduce.
+//
+// Usage:
+// node diagnostic.mjs # 10s recording, default output
+// node diagnostic.mjs --duration 30 # 30s recording
+// node diagnostic.mjs --output ./out.json # custom output path
+// node diagnostic.mjs --window # capture a window (default: display)
+//
+// Helper discovery:
+// 1. $OPENSCREEN_HELPER_EXE (any path)
+// 2. ./wgc-capture.exe (Windows)
+// ./openscreen-screencapturekit-helper (macOS)
+// 3. ./helpers/<platform>-<arch>/<helper-name> (CI artifact layout)
+
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { fileURLToPath } from "node:url";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+const HELPER_CANDIDATES = {
+ win32: {
+ x64: { name: "wgc-capture.exe", kind: "windows" },
+ arm64: { name: "wgc-capture.exe", kind: "windows" },
+ },
+ darwin: {
+ x64: { name: "openscreen-screencapturekit-helper", kind: "mac" },
+ arm64: { name: "openscreen-screencapturekit-helper", kind: "mac" },
+ },
+};
+
+function parseArgs(argv) {
+ const opts = {
+ duration: 10_000,
+ output: null,
+ source: "display",
+ help: false,
+ };
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === "--duration" || arg === "-d") {
+ opts.duration = Number(argv[++i]) * 1000;
+ } else if (arg === "--output" || arg === "-o") {
+ opts.output = argv[++i];
+ } else if (arg === "--source") {
+ opts.source = argv[++i];
+ } else if (arg === "--window") {
+ opts.source = "window";
+ } else if (arg === "--help" || arg === "-h") {
+ opts.help = true;
+ } else if (arg.startsWith("--")) {
+ throw new Error(`Unknown flag: ${arg}`);
+ }
+ }
+ return opts;
+}
+
+function printHelp() {
+ console.log(`OpenScreen standalone diagnostic tool
+
+Usage:
+ node diagnostic.mjs [flags]
+
+Flags:
+ -d, --duration <seconds> Recording length before sending stop (default: 10)
+ -o, --output <path> Output JSON path (default: ./openscreen-diagnostic-<timestamp>.json)
+ --source <display|window> Capture source type (default: display)
+ --window Shortcut for --source window
+ -h, --help Show this help
+`);
+}
+
+function findHelper() {
+ const explicit = process.env.OPENSCREEN_HELPER_EXE?.trim();
+ if (explicit && fs.existsSync(explicit)) return { path: explicit, kind: null };
+
+ const platform = process.platform;
+ const arch = process.arch === "arm64" ? "arm64" : "x64";
+ const descriptor = HELPER_CANDIDATES[platform]?.[arch];
+ if (!descriptor) {
+ throw new Error(`Unsupported platform: ${platform}-${arch}`);
+ }
+
+ const inScriptDir = path.join(__dirname, descriptor.name);
+ if (fs.existsSync(inScriptDir)) return { path: inScriptDir, kind: descriptor.kind };
+
+ const inHelpersDir = path.join(__dirname, "helpers", `${platform}-${arch}`, descriptor.name);
+ if (fs.existsSync(inHelpersDir)) return { path: inHelpersDir, kind: descriptor.kind };
+
+ throw new Error(
+ `Native helper not found for ${platform}-${arch}. Looked for:\n` +
+ ` $OPENSCREEN_HELPER_EXE\n` +
+ ` ${inScriptDir}\n` +
+ ` ${inHelpersDir}\n` +
+ `Download the matching diagnostic bundle from the OpenScreen releases / CI artifacts.`,
+ );
+}
+
+function buildConfig(opts) {
+ const now = Date.now();
+ return {
+ schemaVersion: 2,
+ recordingId: now,
+ outputPath: path.join(os.tmpdir(), `openscreen-diag-${now}.mp4`),
+ sourceType: opts.source === "window" ? "window" : "display",
+ sourceId: opts.source === "window" ? "window:0:0" : "screen:0:0",
+ displayId: 0,
+ fps: 30,
+ videoWidth: 1280,
+ videoHeight: 720,
+ displayX: 0,
+ displayY: 0,
+ displayW: 1920,
+ displayH: 1080,
+ hasDisplayBounds: true,
+ captureSystemAudio: false,
+ captureMic: false,
+ captureCursor: false,
+ microphoneDeviceId: "default",
+ microphoneDeviceName: "",
+ microphoneGain: 1.0,
+ webcamEnabled: false,
+ outputs: { screenPath: "" },
+ };
+}
+
+function parseStopTiming(stderrText) {
+ const lines = [];
+ for (const line of stderrText.split(/\r?\n/)) {
+ const m = line.match(/\[stop-timing\]\s+step=(\S+)\s+elapsed_ms=(\d+)/);
+ if (m) lines.push({ step: m[1], elapsedMs: Number(m[2]) });
+ }
+ return lines;
+}
+
+function run(opts) {
+ const helper = findHelper();
+ console.log(`[diag] helper: ${helper.path}`);
+ console.log(`[diag] platform: ${process.platform}-${process.arch}`);
+ console.log(`[diag] duration: ${opts.duration}ms, source: ${opts.source}`);
+
+ const config = buildConfig(opts);
+ config.outputs.screenPath = config.outputPath;
+
+ const t0 = Date.now();
+ const proc = spawn(helper.path, [JSON.stringify(config)], {
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ });
+
+ let stdout = "";
+ let stderr = "";
+ let stopSent = false;
+ let stopSentAt = 0;
+
+ proc.stdout.on("data", (chunk) => {
+ const text = chunk.toString();
+ stdout += text;
+ process.stdout.write(`[helper/stdout] ${text}`);
+ });
+ proc.stderr.on("data", (chunk) => {
+ const text = chunk.toString();
+ stderr += text;
+ process.stderr.write(`[helper/stderr] ${text}`);
+ });
+
+ const stopTimer = setTimeout(() => {
+ if (stopSent) return;
+ stopSent = true;
+ stopSentAt = Date.now();
+ proc.stdin.write("stop\n");
+ console.log(`[diag] sent stop after ${stopSentAt - t0}ms`);
+ }, opts.duration);
+
+ const fallbackTimer = setTimeout(() => {
+ if (!stopSent) {
+ stopSent = true;
+ stopSentAt = Date.now();
+ proc.stdin.write("stop\n");
+ console.log(`[diag] fallback stop fired after ${opts.duration}ms`);
+ }
+ }, opts.duration + 2_000);
+
+ const killTimer = setTimeout(() => {
+ console.error(`[diag] helper did not exit after stop, killing`);
+ proc.kill("SIGKILL");
+ }, opts.duration + 95_000);
+
+ return new Promise((resolve) => {
+ proc.once("exit", (code, signal) => {
+ clearTimeout(stopTimer);
+ clearTimeout(fallbackTimer);
+ clearTimeout(killTimer);
+ const tExit = Date.now();
+ resolve({
+ code,
+ signal,
+ t0,
+ stopSentAt,
+ tExit,
+ stdout,
+ stderr,
+ config,
+ });
+ });
+ proc.once("error", (error) => {
+ clearTimeout(stopTimer);
+ clearTimeout(fallbackTimer);
+ clearTimeout(killTimer);
+ resolve({
+ code: -1,
+ signal: null,
+ t0,
+ stopSentAt,
+ tExit: Date.now(),
+ stdout,
+ stderr: stderr + `\n[spawn-error] ${error.message}\n`,
+ config,
+ spawnError: error,
+ });
+ });
+ });
+}
+
+function buildReport(result) {
+ const stopTiming = parseStopTiming(result.stderr);
+ const stopElapsedMs = result.stopSentAt > 0 ? result.tExit - result.stopSentAt : null;
+ const helperPath = process.env.OPENSCREEN_HELPER_EXE?.trim() || "(auto-resolved)";
+
+ return {
+ timestamp: new Date(result.t0).toISOString(),
+ platform: process.platform,
+ arch: process.arch,
+ osRelease: os.release(),
+ osVersion: os.version(),
+ cpuModel: os.cpus()[0]?.model ?? null,
+ cpuCount: os.cpus().length,
+ totalMemoryMB: Math.round(os.totalmem() / 1024 / 1024),
+ nodeVersion: process.versions.node,
+ helperPath,
+ durationMs: result.stopSentAt > 0 ? result.stopSentAt - result.t0 : null,
+ stopElapsedMs,
+ exitCode: result.code,
+ exitSignal: result.signal,
+ spawnError: result.spawnError?.message ?? null,
+ config: result.config,
+ helperStdout: result.stdout,
+ helperStderr: result.stderr,
+ stopTiming,
+ };
+}
+
+async function main() {
+ let opts;
+ try {
+ opts = parseArgs(process.argv.slice(2));
+ } catch (error) {
+ console.error(`[diag] ${error.message}`);
+ process.exit(2);
+ }
+ if (opts.help) {
+ printHelp();
+ process.exit(0);
+ }
+
+ let result;
+ try {
+ result = await run(opts);
+ } catch (error) {
+ console.error(`[diag] ${error.message}`);
+ process.exit(1);
+ }
+
+ const report = buildReport(result);
+ const outputPath =
+ opts.output ?? path.join(process.cwd(), `openscreen-diagnostic-${Date.now()}.json`);
+ await fs.promises.writeFile(outputPath, JSON.stringify(report, null, 2), "utf-8");
+
+ console.log("");
+ console.log(`[diag] exit code: ${report.exitCode}`);
+ console.log(`[diag] stop elapsed: ${report.stopElapsedMs}ms`);
+ console.log(`[diag] stop timing steps:`);
+ for (const entry of report.stopTiming) {
+ console.log(`[diag] ${entry.step.padEnd(28)} ${entry.elapsedMs}ms`);
+ }
+ console.log(`[diag] report: ${outputPath}`);
+}
+
+main();
diff --git a/scripts/diagnostic-tool/diagnostic.sh b/scripts/diagnostic-tool/diagnostic.sh
new file mode 100644
index 000000000..6dceac36b
--- /dev/null
+++ b/scripts/diagnostic-tool/diagnostic.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env sh
+set -e
+DIR="$(cd "$(dirname "$0")" && pwd)"
+exec node "$DIR/diagnostic.mjs" "$@"
\ No newline at end of file