Desktop app that records your on-screen work session and uses the GitHub Copilot SDK to reconstruct it as an intent + ordered steps, then builds a reusable Skill or Automation for Microsoft Autopilots like Scout, Microsoft Copilot Cowork, or Copilot Studio.
TypeScript agent-skillsai-agentsautomationcopilotcopilot-clicopilot-coworkcopilot-studioelectronmicrosoft-scoutscreen-recording
feat: add screen selection for recordings
Giorgio Ughini68ced22e12b0
diff --git a/common/ipc.ts b/common/ipc.tsindex 827f568..2533a4d 100644--- a/common/ipc.ts+++ b/common/ipc.ts@@ -2,6 +2,7 @@ import type { Analysis, AnalysisFeedback, AnalysisStep, Confidence } from "./anaimport type { AutomationPlan, BuiltAutomation } from "./automation";import type { MicrophoneDevice } from "./microphone";import type { NarrationLanguage } from "./narration";+import type { ScreenSource } from "./screen";import type { SensitiveReport } from "./sensitive";import type {BuiltSkill,@@ -262,6 +263,10 @@ export interface StartOptions {narrationLanguage?: NarrationLanguage;/** Device selected for the initial narration segment; defaults to the OS input. */microphoneDeviceId?: string;+ /** Electron desktop-capture source selected for this recording. */+ screenSourceId?: string;+ /** Stable OS display identity used to validate the final Electron source. */+ screenDisplayId?: string;}export interface StopResult {@@ -313,6 +318,26 @@ export interface MicrophoneSettingsResult {error?: string;}+/** Shared pre-recording screen preference and current display catalog. */+export interface ScreenSettingsStatus {+ screens: ScreenSource[];+ /** The preferred source, retained even while its display is disconnected. */+ preferredSourceId: string;+ preferredSourceLabel: string;+ /** The source that will actually be recorded in the next session. */+ selectedSourceId: string;+ selectedSourceLabel: string;+ preferredSourceUnavailable: boolean;+ fallback: string | null;+ error: string | null;+}++export interface ScreenSettingsResult {+ ok: boolean;+ status: ScreenSettingsStatus;+ error?: string;+}+export interface MarkerResult {ok: boolean;error?: string;@@ -407,6 +432,9 @@ export const IPC = {microphoneNarration: "microphone:narration",microphoneDevice: "microphone:device",microphoneSettingsChanged: "microphone:settings-changed",+ screenSettings: "screen:settings",+ screenSource: "screen:source",+ screenSettingsChanged: "screen:settings-changed",status: "recorder:status",marker: "recorder:marker",doctor: "doctor:check",@@ -468,6 +496,11 @@ export interface SkillRecorderApi {onMicrophoneSettingsChanged(cb: (status: MicrophoneSettingsStatus) => void,): () => void;+ screenSettings(): Promise<ScreenSettingsStatus>;+ selectScreen(sourceId: string): Promise<ScreenSettingsResult>;+ onScreenSettingsChanged(+ cb: (status: ScreenSettingsStatus) => void,+ ): () => void;status(): Promise<RecorderStatus>;marker(note: string): Promise<MarkerResult>;doctor(): Promise<DoctorReport>;diff --git a/common/screen.test.ts b/common/screen.test.tsnew file mode 100644index 0000000..e8a827d--- /dev/null+++ b/common/screen.test.ts@@ -0,0 +1,115 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ applyDisplayLabels,+ resolveScreenPreference,+ type ScreenSource,+} from "./screen";++const sources: ScreenSource[] = [+ { id: "screen:1:0", label: "Screen 1", displayId: "101" },+ { id: "screen:2:0", label: "Screen 2", displayId: "202" },+];++test("screen preference resolves exact and changed source ids", () => {+ const exact = resolveScreenPreference(+ { id: "screen:1:0", label: "Screen 1", displayId: "101" },+ sources,+ );+ assert.equal(exact.source?.id, "screen:1:0");+ assert.equal(exact.unavailable, false);+ assert.equal(exact.changed, false);++ const changedId = resolveScreenPreference(+ { id: "screen:old:0", label: "Screen 2", displayId: "202" },+ sources,+ );+ assert.equal(changedId.source?.id, "screen:2:0");+ assert.equal(changedId.preference?.id, "screen:2:0");+ assert.equal(changedId.unavailable, false);+ assert.equal(changedId.changed, true);+});++test("stable display identity wins when Electron reassigns source ids", () => {+ const reassigned: ScreenSource[] = [+ { id: "screen:1:0", label: "Screen 2", displayId: "202" },+ { id: "screen:2:0", label: "Screen 1", displayId: "101" },+ ];+ const resolved = resolveScreenPreference(+ { id: "screen:1:0", label: "Screen 1", displayId: "101" },+ reassigned,+ );++ assert.equal(resolved.source?.id, "screen:2:0");+ assert.equal(resolved.source?.displayId, "101");+ assert.equal(resolved.changed, true);+});++test("a reassigned source id does not impersonate a disconnected display", () => {+ const preference = {+ id: "screen:1:0",+ label: "Travel display",+ displayId: "303",+ };+ const resolved = resolveScreenPreference(preference, [+ { id: "screen:1:0", label: "Travel display", displayId: "101" },+ sources[1],+ ]);++ assert.equal(resolved.unavailable, true);+ assert.deepEqual(resolved.preference, preference);+});++test("missing screen visibly falls back without forgetting the preference", () => {+ const preference = {+ id: "screen:travel:0",+ label: "Travel display",+ displayId: "303",+ };+ const resolved = resolveScreenPreference(preference, sources);++ assert.equal(resolved.source?.id, "screen:1:0");+ assert.deepEqual(resolved.preference, preference);+ assert.equal(resolved.unavailable, true);+ assert.equal(resolved.changed, false);+});++test("first available screen becomes the initial preference", () => {+ const resolved = resolveScreenPreference(null, sources);++ assert.deepEqual(resolved.source, sources[0]);+ assert.deepEqual(resolved.preference, sources[0]);+ assert.equal(resolved.unavailable, false);+ assert.equal(resolved.changed, true);+});++test("an empty catalog has no selected screen", () => {+ const resolved = resolveScreenPreference(null, []);++ assert.equal(resolved.source, null);+ assert.equal(resolved.preference, null);+ assert.equal(resolved.unavailable, true);+ assert.equal(resolved.changed, false);+});++test("screen sources use display model labels and disambiguate duplicates", () => {+ const labeled = applyDisplayLabels(sources, new Map([+ ["101", "HP E27 G5"],+ ["202", "HP E27 G5"],+ ]));++ assert.deepEqual(+ labeled.map((source) => source.label),+ ["HP E27 G5 (1)", "HP E27 G5 (2)"],+ );+});++test("screen sources retain capture labels when display metadata is unavailable", () => {+ const labeled = applyDisplayLabels(sources, new Map());++ assert.deepEqual(+ labeled.map((source) => source.label),+ ["Screen 1", "Screen 2"],+ );+});diff --git a/common/screen.ts b/common/screen.tsnew file mode 100644index 0000000..3ff0b39--- /dev/null+++ b/common/screen.ts@@ -0,0 +1,126 @@+export interface ScreenSource {+ id: string;+ label: string;+ displayId: string;+}++export interface ScreenPreference {+ id: string;+ label: string;+ displayId: string;+}++export interface ResolvedScreenPreference {+ source: ScreenSource | null;+ preference: ScreenPreference | null;+ unavailable: boolean;+ changed: boolean;+}++/** Replace generic capture names with platform-provided monitor model labels. */+export function applyDisplayLabels(+ sources: readonly ScreenSource[],+ displayLabels: ReadonlyMap<string, string>,+): ScreenSource[] {+ const baseLabels = sources.map((source, index) => {+ const displayLabel = displayLabels.get(source.displayId)?.trim();+ return displayLabel || source.label.trim() || `Screen ${index + 1}`;+ });+ const counts = new Map<string, number>();+ for (const label of baseLabels) {+ counts.set(label, (counts.get(label) ?? 0) + 1);+ }+ const occurrences = new Map<string, number>();+ return sources.map((source, index) => {+ const base = baseLabels[index];+ if ((counts.get(base) ?? 0) === 1) return { ...source, label: base };+ const occurrence = (occurrences.get(base) ?? 0) + 1;+ occurrences.set(base, occurrence);+ return { ...source, label: `${base} (${occurrence})` };+ });+}++/**+ * Resolve a persisted preference against Electron's current screen sources.+ * Source ids may change between launches, while display ids generally remain+ * stable for the same connected monitor.+ */+export function resolveScreenPreference(+ preference: ScreenPreference | null,+ sources: readonly ScreenSource[],+): ResolvedScreenPreference {+ if (sources.length === 0) {+ return {+ source: null,+ preference,+ unavailable: true,+ changed: false,+ };+ }++ if (!preference) {+ const source = sources[0];+ return {+ source,+ preference: screenPreference(source),+ unavailable: false,+ changed: true,+ };+ }++ const displayMatch = preference.displayId+ ? uniqueMatch(sources.filter((source) => source.displayId === preference.displayId))+ : null;+ // Electron source ids are sequential and can be reassigned after a topology+ // change. Only trust an id by itself for legacy/platform sources without a+ // stable display id.+ const exact =+ displayMatch ??+ (!preference.displayId+ ? sources.find((source) => source.id === preference.id) ?? null+ : null);+ const labelMatch =+ exact ??+ (!preference.displayId && preference.label+ ? uniqueMatch(sources.filter((source) => source.label === preference.label))+ : null);++ if (labelMatch) {+ return {+ source: labelMatch,+ preference: screenPreference(labelMatch),+ unavailable: false,+ changed: !samePreference(preference, labelMatch),+ };+ }++ return {+ source: sources[0],+ preference,+ unavailable: true,+ changed: false,+ };+}++export function screenPreference(source: ScreenSource): ScreenPreference {+ return {+ id: source.id,+ label: source.label,+ displayId: source.displayId,+ };+}++function uniqueMatch(sources: readonly ScreenSource[]): ScreenSource | null {+ return sources.length === 1 ? sources[0] : null;+}++function samePreference(+ preference: ScreenPreference,+ source: ScreenSource,+): boolean {+ return (+ preference.id === source.id &&+ preference.label === source.label &&+ preference.displayId === source.displayId+ );+}diff --git a/electron/ipc.ts b/electron/ipc.tsindex 89fa6e0..73d9ccf 100644--- a/electron/ipc.ts+++ b/electron/ipc.ts@@ -19,6 +19,7 @@ import type {DebugBundleResult,DeleteSessionResult,MicrophoneSettingsResult,+ ScreenSettingsResult,SkillBuildInput,SkillCreateResult,SkillPlacement,@@ -39,6 +40,7 @@ import { createLogger } from "./logger";import type { AudioRecorder } from "./audio/recorder";import type { NarrationManager } from "./narration/manager";import type { RecorderController } from "./recorder/controller";+import type { ScreenSourceService } from "./video/sources";import { isValidSessionId } from "./recorder/session-store";import {INACTIVE_FRAME_REDACTOR,@@ -60,7 +62,9 @@ export function registerIpc(automationBuilder: AutomationBuilder,narration: NarrationManager,microphones: AudioRecorder,+ screens: ScreenSourceService,sensitiveModels: SensitiveModelManager,+ isRecordingStartPending: () => boolean,): void {ipcMain.handle(IPC.stop, () => recorder.stop());ipcMain.handle(IPC.discard, () => recorder.discard());@@ -78,7 +82,7 @@ export function registerIpc(error: "Invalid narration preference.",};}- if (recorder.state === "recording") {+ if (recorder.state === "recording" || isRecordingStartPending()) {return {ok: false,status: microphones.settings(),@@ -88,6 +92,27 @@ export function registerIpc(return microphones.setNarrationEnabled(enabled);},);+ ipcMain.handle(IPC.screenSettings, () => screens.refresh());+ ipcMain.handle(+ IPC.screenSource,+ async (_event, sourceId: string): Promise<ScreenSettingsResult> => {+ if (typeof sourceId !== "string" || !sourceId) {+ return {+ ok: false,+ status: screens.settings(),+ error: "Invalid screen selection.",+ };+ }+ if (recorder.state === "recording") {+ return {+ ok: false,+ status: screens.settings(),+ error: "Choose the next recording's screen after this recording ends.",+ };+ }+ return screens.selectSource(sourceId);+ },+ );ipcMain.handle(IPC.microphoneDevice,async (_event, deviceId: string): Promise<MicrophoneSettingsResult> => {diff --git a/electron/main.ts b/electron/main.tsindex b406f5c..78fa3c3 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -19,6 +19,7 @@ import { createTray } from "./tray";import { dockIcon } from "./icons";import { AudioRecorder } from "./audio/recorder";import { VideoRecorder } from "./video/recorder";+import { ScreenSourceService } from "./video/sources";import {clampRecordingControlsWindow,createLibraryWindow,@@ -45,6 +46,7 @@ let recorderHome: Electron.Rectangle | null = null;let controlsExpanded = false;let quitReady = false;let quitTask: Promise<void> | null = null;+let recordingStartPending = false;const recordingPrivacy = new RecordingPrivacySession();const narration = new NarrationManager((status) =>broadcast(IPC.narrationStatusChanged, status),@@ -55,6 +57,9 @@ const sensitiveModels = new SensitiveModelManager((status) =>const microphones = new AudioRecorder((status) =>broadcast(IPC.microphoneSettingsChanged, status),);+const screens = new ScreenSourceService((status) =>+ broadcast(IPC.screenSettingsChanged, status),+);const recorder = new RecorderController({resolveConfig: () => ({ ...FULL_CAPTURE }),buildCollectors: createCollectors,@@ -73,8 +78,23 @@ const recorder = new RecorderController({});async function startRecording(): Promise<StartResult> {- await microphones.whenSettingsSettled();- return recorder.start(microphones.startOptions());+ if (recordingStartPending) {+ return { ok: false, error: "Recording is already starting." };+ }+ recordingStartPending = true;+ try {+ await Promise.all([+ microphones.whenSettingsSettled(),+ screens.whenSettingsSettled(),+ ]);+ const screenOptions = await screens.startOptions();+ return await recorder.start({+ ...microphones.startOptions(),+ ...screenOptions,+ });+ } finally {+ recordingStartPending = false;+ }}/** Send an event to every live window (recorder HUD + library, if open). */@@ -220,6 +240,14 @@ app.whenReady().then(async () => {error instanceof Error ? error.message : error,);}+ try {+ await screens.initialize();+ } catch (error) {+ log.warn(+ "Screen source initialization failed:",+ error instanceof Error ? error.message : error,+ );+ }registerIpc(recorder,describer,@@ -227,7 +255,9 @@ app.whenReady().then(async () => {automationBuilder,narration,microphones,+ screens,sensitiveModels,+ () => recordingStartPending,);sensitiveModels.initialize();ipcMain.handle(IPC.start, () => requestStartRecording());@@ -272,9 +302,13 @@ app.whenReady().then(async () => {});recorderWindow = createRecorderWindow();- screen.on("display-added", clampControlsToDisplay);- screen.on("display-removed", clampControlsToDisplay);- screen.on("display-metrics-changed", clampControlsToDisplay);+ const handleDisplayChange = () => {+ clampControlsToDisplay();+ void screens.refresh();+ };+ screen.on("display-added", handleDisplayChange);+ screen.on("display-removed", handleDisplayChange);+ screen.on("display-metrics-changed", handleDisplayChange);try {createTray(diff --git a/electron/preload.cjs b/electron/preload.cjsindex 5b17b40..cfc5a3a 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -13,6 +13,9 @@ const IPC = {microphoneNarration: "microphone:narration",microphoneDevice: "microphone:device",microphoneSettingsChanged: "microphone:settings-changed",+ screenSettings: "screen:settings",+ screenSource: "screen:source",+ screenSettingsChanged: "screen:settings-changed",status: "recorder:status",marker: "recorder:marker",doctor: "doctor:check",@@ -92,6 +95,13 @@ contextBridge.exposeInMainWorld("skillRecorder", {ipcRenderer.on(IPC.microphoneSettingsChanged, listener);return () => ipcRenderer.removeListener(IPC.microphoneSettingsChanged, listener);},+ screenSettings: () => ipcRenderer.invoke(IPC.screenSettings),+ selectScreen: (sourceId) => ipcRenderer.invoke(IPC.screenSource, sourceId),+ onScreenSettingsChanged: (cb) => {+ const listener = (_event, status) => cb(status);+ ipcRenderer.on(IPC.screenSettingsChanged, listener);+ return () => ipcRenderer.removeListener(IPC.screenSettingsChanged, listener);+ },status: () => ipcRenderer.invoke(IPC.status),marker: (note) => ipcRenderer.invoke(IPC.marker, note),doctor: () => ipcRenderer.invoke(IPC.doctor),diff --git a/electron/recorder-window-sizing.test.ts b/electron/recorder-window-sizing.test.tsindex 413b048..ecd7174 100644--- a/electron/recorder-window-sizing.test.ts+++ b/electron/recorder-window-sizing.test.ts@@ -8,9 +8,7 @@ import {class WindowsFramedWindow implements RecorderWindowSizingTarget {destroyed = false;- resizable = false;size: [number, number] = [400, 500];- readonly resizeChanges: boolean[] = [];readonly sizeChanges: Array<[number, number]> = [];isDestroyed(): boolean {@@ -18,36 +16,25 @@ class WindowsFramedWindow implements RecorderWindowSizingTarget {}getContentSize(): [number, number] {- const frame: [number, number] = this.resizable ? [16, 39] : [2, 31];- return [this.size[0] - frame[0], this.size[1] - frame[1]];+ return [this.size[0] - 2, this.size[1] - 31];}getSize(): [number, number] {return [...this.size];}- isResizable(): boolean {- return this.resizable;- }-- setResizable(resizable: boolean): void {- this.resizable = resizable;- this.resizeChanges.push(resizable);- }-setSize(width: number, height: number): void {this.size = [width, height];this.sizeChanges.push([width, height]);}}-test("recorder fitting preserves outer width across Windows frame changes", () => {+test("recorder fitting preserves its fixed outer width", () => {const win = new WindowsFramedWindow();fitRecorderHeight(win, 600);assert.deepEqual(win.size, [400, 631]);assert.deepEqual(win.getContentSize(), [398, 600]);- assert.deepEqual(win.resizeChanges, [true, false]);assert.deepEqual(win.sizeChanges, [[400, 631]]);for (let i = 0; i < 5; i++) fitRecorderHeight(win, 600);@@ -55,6 +42,17 @@ test("recorder fitting preserves outer width across Windows frame changes", () =assert.deepEqual(win.sizeChanges, [[400, 631]]);});+test("recorder fitting repairs width growth even when height already matches", () => {+ const win = new WindowsFramedWindow();+ win.size = [700, 631];++ fitRecorderHeight(win, 600);+ assert.deepEqual(win.size, [400, 631]);++ for (let i = 0; i < 5; i++) fitRecorderHeight(win, 600);+ assert.deepEqual(win.sizeChanges, [[400, 631]]);+});+test("recorder fitting clamps content height and ignores invalid requests", () => {const win = new WindowsFramedWindow();diff --git a/electron/recorder-window-sizing.ts b/electron/recorder-window-sizing.tsindex 27676ac..b49cda0 100644--- a/electron/recorder-window-sizing.ts+++ b/electron/recorder-window-sizing.ts@@ -1,20 +1,18 @@const RECORDER_MIN_HEIGHT = 320;const RECORDER_MAX_HEIGHT = 720;+export const RECORDER_WINDOW_WIDTH = 400;export interface RecorderWindowSizingTarget {isDestroyed(): boolean;getContentSize(): number[];getSize(): number[];- isResizable(): boolean;- setResizable(resizable: boolean): void;setSize(width: number, height: number, animate?: boolean): void;}/**- * Fit the recorder to its rendered content while preserving its fixed outer width.- * Windows changes the non-client frame thickness when resizability is toggled, so- * feeding a content width measured before that toggle into `setContentSize` grows- * the outer window on every ResizeObserver callback.+ * Fit the recorder to its rendered content while enforcing its fixed outer width.+ * Programmatic setSize works on non-resizable BrowserWindows; toggling resizability+ * changes the Windows frame width and creates a resize-observer feedback loop.*/export function fitRecorderHeight(win: RecorderWindowSizingTarget,@@ -25,16 +23,12 @@ export function fitRecorderHeight(const targetContentHeight = Math.round(Math.max(RECORDER_MIN_HEIGHT, Math.min(RECORDER_MAX_HEIGHT, contentHeight)),);+ const [outerWidth, outerHeight] = win.getSize();const [, currentContentHeight] = win.getContentSize();- if (Math.abs(currentContentHeight - targetContentHeight) < 1) return;+ const heightMatches =+ Math.abs(currentContentHeight - targetContentHeight) < 1;+ if (heightMatches && outerWidth === RECORDER_WINDOW_WIDTH) return;- const [outerWidth, outerHeight] = win.getSize();const targetOuterHeight = outerHeight + targetContentHeight - currentContentHeight;- const wasResizable = win.isResizable();- if (!wasResizable) win.setResizable(true);- try {- win.setSize(outerWidth, targetOuterHeight);- } finally {- if (!wasResizable && !win.isDestroyed()) win.setResizable(false);- }+ win.setSize(RECORDER_WINDOW_WIDTH, targetOuterHeight);}diff --git a/electron/recorder/controller.test.ts b/electron/recorder/controller.test.tsindex 797592d..11a6ee0 100644--- a/electron/recorder/controller.test.ts+++ b/electron/recorder/controller.test.ts@@ -64,6 +64,38 @@ test("microphone toggles are serialized and finalized on save", async () => {},});+ test("selected screen source is passed to the video recorder", async () => {+ await withSessionsRoot(async () => {+ let selectedSourceId: string | undefined;+ let selectedDisplayId: string | undefined;+ const controller = new RecorderController({+ resolveConfig: () => ({ ...FULL_CAPTURE }),+ buildCollectors: () => [],+ createVideoRecorder: () => ({+ start: async (_dir, sourceId, displayId) => {+ selectedSourceId = sourceId;+ selectedDisplayId = displayId;+ },+ stop: async () => null,+ }),+ deleteSession: async () => undefined,+ });++ assert.equal(+ (+ await controller.start({+ screenSourceId: "screen:2:0",+ screenDisplayId: "202",+ })+ ).ok,+ true,+ );+ assert.equal(selectedSourceId, "screen:2:0");+ assert.equal(selectedDisplayId, "202");+ assert.equal((await controller.stop()).ok, true);+ });+ });+const started = await controller.start();assert.equal(started.ok, true);assert.equal(audio.narrationLanguage, "en");diff --git a/electron/recorder/controller.ts b/electron/recorder/controller.tsindex 328b6d7..a7e1077 100644--- a/electron/recorder/controller.ts+++ b/electron/recorder/controller.ts@@ -42,7 +42,11 @@ function makeSessionId(d = new Date()): string {/** A best-effort screen-video sidecar tied to a session's lifecycle. */export interface SessionVideoRecorder {- start(sessionDir: string): Promise<void>;+ start(+ sessionDir: string,+ sourceId?: string,+ displayId?: string,+ ): Promise<void>;stop(): Promise<unknown>;}@@ -334,7 +338,11 @@ export class RecorderController {if (config.video && this.deps.createVideoRecorder) {this.video = this.deps.createVideoRecorder();try {- await this.video.start(store.dir);+ await this.video.start(+ store.dir,+ options?.screenSourceId,+ options?.screenDisplayId,+ );} catch (error) {log.warn("video start failed:", error instanceof Error ? error.message : error);this.video = null;diff --git a/electron/video/recorder.ts b/electron/video/recorder.tsindex 7645f7b..4f0a15a 100644--- a/electron/video/recorder.ts+++ b/electron/video/recorder.ts@@ -152,7 +152,11 @@ export class VideoRecorder {};/** Begin capturing into `<sessionDir>/video.webm`. Never throws. */- async start(sessionDir: string): Promise<void> {+ async start(+ sessionDir: string,+ sourceId?: string,+ displayId?: string,+ ): Promise<void> {try {const sources = await desktopCapturer.getSources({types: ["screen"],@@ -162,7 +166,15 @@ export class VideoRecorder {log.warn("no screen source available; skipping video");return;}- const source = sources[0];+ const source = displayId+ ? sources.find((candidate) => candidate.display_id === displayId)+ : sourceId+ ? sources.find((candidate) => candidate.id === sourceId)+ : sources[0];+ if (!source) {+ log.warn("selected screen source is unavailable; skipping video");+ return;+ }this.dir = sessionDir;this.file = path.join(sessionDir, "video.webm");diff --git a/electron/video/sources.ts b/electron/video/sources.tsnew file mode 100644index 0000000..c5924cd--- /dev/null+++ b/electron/video/sources.ts@@ -0,0 +1,253 @@+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import path from "node:path";++import { app, desktopCapturer, screen } from "electron";++import type {+ ScreenSettingsResult,+ ScreenSettingsStatus,+ StartOptions,+} from "../../common/ipc";+import {+ applyDisplayLabels,+ resolveScreenPreference,+ screenPreference,+ type ScreenPreference,+ type ScreenSource,+} from "../../common/screen";+import { createLogger } from "../logger";++const log = createLogger("Screen sources");+const PREFERENCES_FILE = "screen-preferences.json";++interface StoredPreferences {+ screen: ScreenPreference | null;+}++export class ScreenSourceService {+ private preferencesLoaded = false;+ private preferencesFile = "";+ private preferenceWrites: Promise<void> = Promise.resolve();+ private operation: Promise<void> = Promise.resolve();+ private preference: ScreenPreference | null = null;+ private sources: ScreenSource[] = [];+ private settingsError: string | null = null;++ constructor(+ private readonly onSettingsChanged: (+ status: ScreenSettingsStatus,+ ) => void = () => undefined,+ ) {}++ initialize(): Promise<void> {+ return this.run(async () => {+ await this.loadPreferences();+ await this.refreshSources();+ });+ }++ refresh(): Promise<ScreenSettingsStatus> {+ return this.run(async () => {+ await this.loadPreferences();+ await this.refreshSources();+ return this.settings();+ });+ }++ selectSource(sourceId: string): Promise<ScreenSettingsResult> {+ return this.run(async () => {+ await this.loadPreferences();+ await this.refreshSources(false);+ const source = this.sources.find((candidate) => candidate.id === sourceId);+ if (!source) {+ const error = "That screen is no longer available.";+ this.settingsError = error;+ this.emitSettings();+ return { ok: false, status: this.settings(), error };+ }++ const previous = this.preference;+ this.preference = screenPreference(source);+ this.settingsError = null;+ try {+ await this.persistPreferences();+ } catch (error) {+ this.preference = previous;+ return this.settingsFailure(error, "Could not save the screen selection");+ }+ this.emitSettings();+ return { ok: true, status: this.settings() };+ });+ }++ startOptions(): Promise<StartOptions> {+ return this.run(async () => {+ await this.loadPreferences();+ await this.refreshSources();+ const source = resolveScreenPreference(this.preference, this.sources).source;+ return source+ ? {+ screenSourceId: source.id,+ screenDisplayId: source.displayId || undefined,+ }+ : {};+ });+ }++ settings(): ScreenSettingsStatus {+ const resolved = resolveScreenPreference(this.preference, this.sources);+ const preferredLabel =+ this.preference?.label || resolved.source?.label || "Selected screen";+ return {+ screens: this.sources.map((source) => ({ ...source })),+ preferredSourceId: this.preference?.id ?? resolved.source?.id ?? "",+ preferredSourceLabel: preferredLabel,+ selectedSourceId: resolved.source?.id ?? "",+ selectedSourceLabel: resolved.source?.label ?? "No screen available",+ preferredSourceUnavailable: this.preference != null && resolved.unavailable,+ fallback:+ this.preference && resolved.unavailable && resolved.source+ ? `${preferredLabel} is unavailable. ${resolved.source.label} will be recorded.`+ : null,+ error: this.settingsError,+ };+ }++ whenSettingsSettled(): Promise<void> {+ return this.operation;+ }++ private async refreshSources(emit = true): Promise<void> {+ try {+ const sources = await desktopCapturer.getSources({+ types: ["screen"],+ thumbnailSize: { width: 0, height: 0 },+ });+ const displayLabels = new Map(+ screen.getAllDisplays().map((display) => [+ String(display.id),+ display.label,+ ]),+ );+ this.sources = applyDisplayLabels(sources.map((source) => ({+ id: source.id,+ label: source.name,+ displayId: source.display_id,+ })), displayLabels);+ this.settingsError =+ this.sources.length === 0 ? "No screens are available to record." : null;++ const resolved = resolveScreenPreference(this.preference, this.sources);+ if (resolved.changed) {+ this.preference = resolved.preference;+ try {+ await this.persistPreferences();+ } catch (error) {+ this.settingsError =+ `Could not save the restored screen selection: ${errorMessage(error)}`;+ }+ }+ } catch (error) {+ this.sources = [];+ this.settingsError = `Could not list screens: ${errorMessage(error)}`;+ log.warn(this.settingsError);+ }+ if (emit) this.emitSettings();+ }++ private async loadPreferences(): Promise<void> {+ if (this.preferencesLoaded) return;+ this.preferencesLoaded = true;+ this.preferencesFile = path.join(app.getPath("userData"), PREFERENCES_FILE);+ try {+ const raw = JSON.parse(await readFile(this.preferencesFile, "utf8")) as unknown;+ this.preference = readPreferences(raw).screen;+ } catch (error) {+ if (isNodeError(error) && error.code === "ENOENT") return;+ this.settingsError =+ `Saved screen preferences could not be read: ${errorMessage(error)}`;+ log.warn(this.settingsError);+ }+ }++ private persistPreferences(): Promise<void> {+ if (!this.preferencesFile) {+ this.preferencesFile = path.join(app.getPath("userData"), PREFERENCES_FILE);+ }+ const file = this.preferencesFile;+ const contents = JSON.stringify({ screen: this.preference }, null, 2);+ const write = this.preferenceWrites.then(async () => {+ await mkdir(path.dirname(file), { recursive: true });+ const temp = `${file}.tmp.${process.pid}.${Date.now()}`;+ try {+ await writeFile(temp, contents);+ await rename(temp, file);+ } finally {+ await rm(temp, { force: true });+ }+ });+ this.preferenceWrites = write.catch(() => undefined);+ return write;+ }++ private settingsFailure(+ error: unknown,+ prefix: string,+ ): ScreenSettingsResult {+ const message = `${prefix}: ${errorMessage(error)}`;+ this.settingsError = message;+ this.emitSettings();+ return { ok: false, status: this.settings(), error: message };+ }++ private emitSettings(): void {+ this.onSettingsChanged(this.settings());+ }++ private run<T>(task: () => Promise<T>): Promise<T> {+ const result = this.operation.then(task, task);+ this.operation = result.then(+ () => undefined,+ () => undefined,+ );+ return result;+ }+}++function readPreferences(value: unknown): StoredPreferences {+ if (!value || typeof value !== "object") {+ throw new Error("Expected an object.");+ }+ const rawScreen =+ "screen" in value && value.screen && typeof value.screen === "object"+ ? value.screen+ : null;+ if (!rawScreen) return { screen: null };++ const id =+ "id" in rawScreen && typeof rawScreen.id === "string"+ ? rawScreen.id+ : "";+ if (!id) throw new Error("The saved screen id is invalid.");+ return {+ screen: {+ id,+ label:+ "label" in rawScreen && typeof rawScreen.label === "string"+ ? rawScreen.label+ : "",+ displayId:+ "displayId" in rawScreen && typeof rawScreen.displayId === "string"+ ? rawScreen.displayId+ : "",+ },+ };+}++function isNodeError(error: unknown): error is NodeJS.ErrnoException {+ return error instanceof Error;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/electron/window.ts b/electron/window.tsindex dd77e1e..3849fc2 100644--- a/electron/window.ts+++ b/electron/window.ts@@ -9,6 +9,7 @@ import {initialRecordingControlsBounds,resizeRecordingControlsBounds,} from "./recording-controls-bounds";+import { RECORDER_WINDOW_WIDTH } from "./recorder-window-sizing";import { windowIcon } from "./icons";export { fitRecorderHeight } from "./recorder-window-sizing";@@ -17,7 +18,7 @@ const dirname = path.dirname(fileURLToPath(import.meta.url));/** Compact recording HUD — fixed width; height auto-fits its content (see* `fitRecorderHeight`). The initial height is a sensible first paint before the* renderer reports its true content height. */-const RECORDER = { width: 400, height: 500 };+const RECORDER = { width: RECORDER_WINDOW_WIDTH, height: 500 };/** Library sizing bounds; actual width adapts to the space beside the recorder. */const LIBRARY = { desiredWidth: 1140, minWidth: 720, floorWidth: 520, maxHeight: 820 };const MARGIN = 12;diff --git a/package.json b/package.jsonindex 4aed90e..d1f81ae 100644--- a/package.json+++ b/package.json@@ -19,7 +19,7 @@"check:lockfile": "node scripts/check-lockfile-portability.mjs","typecheck": "tsc --noEmit","typecheck:evals": "tsc --noEmit -p evals/tsconfig.json",- "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test evals/builder-imports.test.ts common/architecture-registry.test.ts electron/architectures/catalogue-registry.test.ts common/audio.test.ts common/microphone.test.ts common/narration.test.ts common/sensitive.test.ts electron/recording-controls-bounds.test.ts electron/recorder-window-sizing.test.ts electron/recording-privacy.test.ts electron/crash-guards.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sensitive/scanner.test.ts electron/sensitive/secrets.test.ts electron/sensitive/tessdata-source.test.ts electron/sensitive/ocr.test.ts electron/sensitive/frame-redact.test.ts electron/sensitive/frame-heuristics.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/placement.test.ts src/skill-placement.test.ts scripts/compliance.test.mjs",+ "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test evals/builder-imports.test.ts common/architecture-registry.test.ts electron/architectures/catalogue-registry.test.ts common/audio.test.ts common/microphone.test.ts common/screen.test.ts common/narration.test.ts common/sensitive.test.ts electron/recording-controls-bounds.test.ts electron/recorder-window-sizing.test.ts electron/recording-privacy.test.ts electron/crash-guards.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sensitive/scanner.test.ts electron/sensitive/secrets.test.ts electron/sensitive/tessdata-source.test.ts electron/sensitive/ocr.test.ts electron/sensitive/frame-redact.test.ts electron/sensitive/frame-heuristics.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/placement.test.ts src/skill-placement.test.ts scripts/compliance.test.mjs","eval": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts","eval:builder": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/builder/run.ts","eval:skill": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/skillbuilder/run.ts",diff --git a/src/Recorder.tsx b/src/Recorder.tsxindex bf409c4..49a11bf 100644--- a/src/Recorder.tsx+++ b/src/Recorder.tsx@@ -5,6 +5,7 @@ import type {MicrophoneSettingsStatus,NarrationStatus,RecorderStatus,+ ScreenSettingsStatus,SensitiveModelStatus,} from "../common/ipc";import {@@ -50,6 +51,8 @@ export function Recorder() {const [narrationStatus, setNarrationStatus] = useState<NarrationStatus | null>(null);const [microphoneSettings, setMicrophoneSettings] =useState<MicrophoneSettingsStatus | null>(null);+ const [screenSettings, setScreenSettings] =+ useState<ScreenSettingsStatus | null>(null);const [privacyReviewOrigin, setPrivacyReviewOrigin] =useState<PrivacyReviewOrigin | null>(null);const [showRecordingWarning, setShowRecordingWarning] = useState(false);@@ -61,6 +64,8 @@ export function Recorder() {const [advancedPending, setAdvancedPending] = useState(false);const [microphonePending, setMicrophonePending] = useState(false);const [microphoneActionError, setMicrophoneActionError] = useState<string | null>(null);+ const [screenPending, setScreenPending] = useState(false);+ const [screenActionError, setScreenActionError] = useState<string | null>(null);const [elapsed, setElapsed] = useState(0);const [sessionCount, setSessionCount] = useState(0);const [pendingCount, setPendingCount] = useState(0);@@ -83,17 +88,21 @@ export function Recorder() {void window.skillRecorder.doctor().then(setDoctor);void window.skillRecorder.narrationStatus().then(setNarrationStatus);void window.skillRecorder.microphoneSettings().then(setMicrophoneSettings);+ void window.skillRecorder.screenSettings().then(setScreenSettings);void window.skillRecorder.sensitiveModelStatus().then(setSensitive);void refreshCount();const offRecorder = window.skillRecorder.onStatusChanged(applyRecorderStatus);const offNarration = window.skillRecorder.onNarrationStatusChanged(setNarrationStatus);const offMicrophones =window.skillRecorder.onMicrophoneSettingsChanged(setMicrophoneSettings);+ const offScreens =+ window.skillRecorder.onScreenSettingsChanged(setScreenSettings);const offSensitive = window.skillRecorder.onSensitiveModelStatusChanged(setSensitive);return () => {offRecorder();offNarration();offMicrophones();+ offScreens();offSensitive();};}, [applyRecorderStatus, refreshCount]);@@ -121,6 +130,8 @@ export function Recorder() {const narrate = microphoneSettings?.narrationEnabled ?? false;const narrationLanguageName = narrationLanguageLabel(narrationLanguage);const advancedOn = sensitive?.enabled ?? true;+ const selectedScreenLabel =+ screenSettings?.selectedSourceLabel ?? "Loading screens...";useEffect(() => {if (recording) {@@ -285,6 +296,17 @@ export function Recorder() {setMicrophonePending(false);}, []);+ const selectScreen = useCallback(async (sourceId: string) => {+ setScreenPending(true);+ setScreenActionError(null);+ const result = await window.skillRecorder.selectScreen(sourceId);+ setScreenSettings(result.status);+ if (!result.ok) {+ setScreenActionError(result.error ?? "Could not select that screen.");+ }+ setScreenPending(false);+ }, []);+const openLibrary = useCallback(() => {void window.skillRecorder.openLibrary();}, []);@@ -318,7 +340,7 @@ export function Recorder() {<buttonclassName={`record ${recording ? "on" : ""}`}onClick={toggle}- disabled={transitioning || microphonePending}+ disabled={transitioning || microphonePending || screenPending}aria-label={recording ? "Stop recording" : "Start recording"}><span className="record-glyph" />@@ -333,7 +355,9 @@ export function Recorder() {? "Capture saved. Open Sessions to analyze": justDiscarded? "Recording discarded"- : "Ready to capture"}+ : screenSettings?.error+ ? "Screen capture needs attention"+ : `Ready to capture · ${selectedScreenLabel}`}</div></div>@@ -396,13 +420,14 @@ export function Recorder() {</button><buttonclassName={`narrate-settings-toggle ${showNarrationSettings ? "open" : ""}`}- aria-label="Narration settings"- aria-controls="narration-settings"+ aria-label="Recording settings"+ aria-controls="recording-settings"aria-expanded={showNarrationSettings}- title="Narration settings"- disabled={microphonePending || recording || transitioning}+ title="Recording settings"+ disabled={microphonePending || screenPending || recording || transitioning}onClick={() => {setMicrophoneActionError(null);+ setScreenActionError(null);setShowNarrationSettings((open) => !open);}}>@@ -441,7 +466,7 @@ export function Recorder() {tabIndex={-1}onClick={() => setShowNarrationSettings(false)}/>- <div id="narration-settings" className="narrate-settings">+ <div id="recording-settings" className="narrate-settings"><label htmlFor="narrate-language">Language</label><div className="narrate-select-wrap"><select@@ -486,6 +511,36 @@ export function Recorder() {▾</span></div>+ <label htmlFor="recording-screen">Screen</label>+ <div className="narrate-select-wrap">+ <select+ id="recording-screen"+ value={screenSettings?.selectedSourceId ?? ""}+ disabled={+ screenPending ||+ recording ||+ transitioning ||+ !screenSettings ||+ screenSettings.screens.length === 0+ }+ onChange={(event) => void selectScreen(event.target.value)}+ >+ {screenSettings?.screens.length ? (+ screenSettings.screens.map((source) => (+ <option key={source.id} value={source.id}>+ {source.label}+ </option>+ ))+ ) : (+ <option value="">+ {screenSettings ? "No screens available" : "Loading screens..."}+ </option>+ )}+ </select>+ <span className="narrate-select-chevron" aria-hidden>+ ▾+ </span>+ </div>{(microphoneActionError ||microphoneSettings?.error ||microphoneSettings?.fallback) && (@@ -506,6 +561,26 @@ export function Recorder() {microphoneSettings?.fallback}</p>)}+ {(screenActionError ||+ screenSettings?.error ||+ screenSettings?.fallback) && (+ <p+ className={`narrate-settings-note ${+ screenActionError || screenSettings?.error+ ? "error"+ : "warn"+ }`}+ role={+ screenActionError || screenSettings?.error+ ? "alert"+ : undefined+ }+ >+ {screenActionError ??+ screenSettings?.error ??+ screenSettings?.fallback}+ </p>+ )}</div></>)}diff --git a/src/WhatsRecorded.tsx b/src/WhatsRecorded.tsxindex f318cfb..70bc074 100644--- a/src/WhatsRecorded.tsx+++ b/src/WhatsRecorded.tsx@@ -103,7 +103,7 @@ export function WhatsRecorded({<li>Which apps you switch to, and their window and document titles.</li><li>Web addresses of the pages you open.</li><li>A short preview of text you copy, up to 120 characters.</li>- <li>A silent video of your screen at a low frame rate.</li>+ <li>A silent video of the screen you select, at a low frame rate.</li></ul><p className="sheet-caution">Do not type, paste, display, copy, or narrate passwords, access tokens, API keys,