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
Improve Copilot sign-in routing and resume interrupted analysis
Giorgio Ughini744c70e4175b
diff --git a/README.md b/README.mdindex d25131f..9f6152c 100644--- a/README.md+++ b/README.md@@ -79,7 +79,22 @@ This adds **Skill Recorder (Source)** shortcuts to your desktop and Start Menu.1. **Grant Screen Recording.** On first launch, macOS asks for Screen Recording permission;grant it and you're ready to record.2. **Record, Analyze, Create.** Do your task, then Analyze. The first time you Analyze,- Skill Recorder offers **Sign in to Copilot** if you aren't signed in yet.+ Skill Recorder offers **Sign in to Copilot** if you aren't signed in yet. Finish+ authorization in your browser; the app verifies sign-in and automatically retries+ the interrupted analysis once. There is no login terminal window to close.+ Canceling sign-in or leaving that analysis prevents the automatic retry.++On Windows, a local Microsoft Entra tenant hint can offer a choice between+**Microsoft Enterprise SSO** and a **Personal GitHub account**. This is only a+routing hint, not proof of employment. The SSO choice opens the enterprise sign-in+page first; finish SSO, return to Skill Recorder, and choose **Continue to Copilot**+to authorize the CLI in the same browser profile. Without a hint, and on macOS/Linux,+sign-in goes directly to the standard GitHub flow. No work-email prompt is required.++Sign-in can be canceled and times out after five minutes. If browser login fails,+the app shows an error and a manual command for the bundled CLI (use PowerShell on+Windows). After manual sign-in, retry the analysis yourself. Signing in from a skill+or automation builder does not automatically repeat a build or installation.To inspect the script before running it, set install options, update, or uninstall, see[`INSTALL.md`](INSTALL.md).diff --git a/common/ipc.ts b/common/ipc.tsindex 087d11d..fac3499 100644--- a/common/ipc.ts+++ b/common/ipc.ts@@ -373,13 +373,16 @@ export interface CopilotInfo {path: string | null;}-/** Result of asking the app to open a terminal on the bundled CLI's sign-in command. */-export interface CopilotSignInResult {- ok: boolean;- /** The exact command the terminal was asked to run, so the user can run it themselves. */- command?: string;- error?: string;-}+/** Success means the bundled CLI completed login and a fresh SDK client verified it. */+export type CopilotSignInResult =+ | { ok: true; status: "authenticated" }+ | {+ ok: false;+ status: "failed" | "canceled" | "timed-out";+ /** Manual fallback; never includes credentials. */+ command?: string;+ error?: string;+ };/*** Message every Copilot-backed feature throws when the CLI has no stored credentials.@@ -449,6 +452,7 @@ export const IPC = {marker: "recorder:marker",doctor: "doctor:check",copilotSignIn: "copilot:sign-in",+ copilotSignInCancel: "copilot:sign-in-cancel",statusChanged: "recorder:status-changed",recordingPrivacyReviewed: "recorder:privacy-reviewed",recordingPrivacyWarningRequested: "recorder:privacy-warning-requested",@@ -526,10 +530,11 @@ export interface SkillRecorderApi {marker(note: string): Promise<MarkerResult>;doctor(): Promise<DoctorReport>;/**- * Open a terminal window running the bundled Copilot CLI's `login` command, so the- * user can sign in without a globally installed `copilot`.+ * Sign in through the browser using the bundled CLI and verify authentication.+ * The attempt ID scopes cancellation to the requesting panel.*/- copilotSignIn(): Promise<CopilotSignInResult>;+ copilotSignIn(attemptId: string): Promise<CopilotSignInResult>;+ cancelCopilotSignIn(attemptId: string): Promise<void>;onStatusChanged(cb: (status: RecorderStatus) => void): () => void;openTerminal(): Promise<TerminalActionResult>;terminalReady(): Promise<TerminalActionResult>;diff --git a/electron/copilot-signin-auth.test.ts b/electron/copilot-signin-auth.test.tsnew file mode 100644index 0000000..d77d37f--- /dev/null+++ b/electron/copilot-signin-auth.test.ts@@ -0,0 +1,68 @@+import assert from "node:assert/strict";+import test from "node:test";++import { verifyCopilotAuthentication } from "./copilot-signin-auth";++test("verification uses a fresh client and stops it after reading actual authentication", async () => {+ let clients = 0;+ const calls: string[] = [];+ const createClient = () => {+ clients++;+ return {+ start: async () => { calls.push("start"); },+ getAuthStatus: async () => { calls.push("status"); return { isAuthenticated: clients === 2 }; },+ forceStop: async () => { calls.push("stop"); },+ };+ };+ assert.equal(await verifyCopilotAuthentication(createClient, new AbortController().signal), false);+ assert.equal(await verifyCopilotAuthentication(createClient, new AbortController().signal), true);+ assert.equal(clients, 2);+ assert.deepEqual(calls, ["start", "status", "stop", "start", "status", "stop"]);+});++test("startup and status failures always stop the client and sanitize errors", async () => {+ for (const phase of ["start", "status"]) {+ let stopped = false;+ await assert.rejects(verifyCopilotAuthentication(() => ({+ start: async () => { if (phase === "start") throw new Error("private startup output"); },+ getAuthStatus: async () => { throw new Error("private status output"); },+ forceStop: async () => { stopped = true; },+ }), new AbortController().signal), /^Error: Could not verify Copilot authentication/);+ assert.equal(stopped, true);+ }+});++test("cancellation during startup stops the client without querying authentication", async () => {+ const controller = new AbortController();+ let stopped = false;+ await assert.rejects(verifyCopilotAuthentication(() => ({+ start: async () => { controller.abort(); },+ getAuthStatus: async () => { assert.fail("must not query canceled client"); },+ forceStop: async () => { stopped = true; },+ }), controller.signal), /Could not verify Copilot authentication/);+ assert.equal(stopped, true);+});++test("an already canceled request never constructs an SDK client", async () => {+ const controller = new AbortController();+ controller.abort();+ await assert.rejects(verifyCopilotAuthentication(() => {+ assert.fail("must not construct");+ }, controller.signal), { name: "AbortError" });+});++test("a hung SDK times out and is force-stopped", async () => {+ let stopped = false;+ // AbortSignal.timeout is unref'd; keep the mock process alive like a real CLI.+ const keepAlive = setInterval(() => {}, 1000);+ try {+ await assert.rejects(verifyCopilotAuthentication(() => ({+ start: () => new Promise<void>(() => {}),+ getAuthStatus: async () => { assert.fail("must not query unstarted client"); },+ forceStop: async () => { stopped = true; },+ }), new AbortController().signal, 10), /Could not verify Copilot authentication/);+ assert.equal(stopped, true);+ } finally {+ clearInterval(keepAlive);+ }+});diff --git a/electron/copilot-signin-auth.ts b/electron/copilot-signin-auth.tsnew file mode 100644index 0000000..675f930--- /dev/null+++ b/electron/copilot-signin-auth.ts@@ -0,0 +1,26 @@+import { abortable, SignInError } from "./copilot-signin-flow";++interface AuthClient {+ start(): Promise<void>;+ getAuthStatus(): Promise<{ isAuthenticated: boolean }>;+ forceStop(): Promise<void>;+}++export async function verifyCopilotAuthentication(+ createClient: () => AuthClient,+ signal: AbortSignal,+ timeoutMs = 30_000,+): Promise<boolean> {+ signal.throwIfAborted();+ const client = createClient();+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);+ try {+ await abortable(client.start(), bounded);+ bounded.throwIfAborted();+ return (await abortable(client.getAuthStatus(), bounded)).isAuthenticated;+ } catch {+ throw new SignInError("Could not verify Copilot authentication. Check your connection and try again.");+ } finally {+ await client.forceStop();+ }+}diff --git a/electron/copilot-signin-flow.test.ts b/electron/copilot-signin-flow.test.tsnew file mode 100644index 0000000..067ac40--- /dev/null+++ b/electron/copilot-signin-flow.test.ts@@ -0,0 +1,190 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ abortable,+ SignInCoordinator,+ SignInError,+ type SignInOperations,+} from "./copilot-signin-flow";++function fixture(overrides: Partial<SignInOperations> = {}) {+ const calls: string[] = [];+ const operations: SignInOperations = {+ hasMicrosoftHint: async () => { calls.push("hint"); return false; },+ chooseAccount: async () => { calls.push("choose"); return "microsoft"; },+ prepareEnterprise: async () => { calls.push("enterprise"); return true; },+ login: async () => { calls.push("login"); },+ verifyAuthentication: async () => { calls.push("verify"); return true; },+ manualCommand: "copilot login --web-flow",+ ...overrides,+ };+ return { calls, operations };+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}++test("unknown user sees no enterprise choice and succeeds only after verification", async () => {+ const { calls, operations } = fixture();+ const result = await new SignInCoordinator().signIn("attempt", 1, operations);+ assert.deepEqual(result, { ok: true, status: "authenticated" });+ assert.deepEqual(calls, ["hint", "login", "verify"]);+});++test("positive hint offers choice, with enterprise SSO before CLI authorization", async () => {+ const { calls, operations } = fixture({ hasMicrosoftHint: async () => true });+ assert.equal((await new SignInCoordinator().signIn("attempt", 1, operations)).ok, true);+ assert.deepEqual(calls, ["choose", "enterprise", "login", "verify"]);+});++test("personal choice does not open the enterprise URL", async () => {+ const { calls, operations } = fixture({+ hasMicrosoftHint: async () => true,+ chooseAccount: async () => "personal",+ });+ await new SignInCoordinator().signIn("attempt", 1, operations);+ assert.deepEqual(calls, ["login", "verify"]);+});++test("canceling account choice or enterprise preparation never starts login", async () => {+ for (const choice of ["canceled", "microsoft"] as const) {+ const { calls, operations } = fixture({+ hasMicrosoftHint: async () => true,+ chooseAccount: async () => choice,+ prepareEnterprise: async () => false,+ });+ assert.deepEqual(await new SignInCoordinator().signIn("attempt", 1, operations), {+ ok: false, status: "canceled",+ });+ assert.deepEqual(calls, []);+ }+});++test("launch completion cannot resolve the attempt before login exits and auth is verified", async () => {+ const login = deferred<void>();+ const verification = deferred<boolean>();+ const verifying = deferred<void>();+ const { operations } = fixture({+ login: () => login.promise,+ verifyAuthentication: () => { verifying.resolve(); return verification.promise; },+ });+ let finished = false;+ const result = new SignInCoordinator().signIn("attempt", 1, operations);+ void result.then(() => { finished = true; });+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(finished, false);+ login.resolve();+ await verifying.promise;+ assert.equal(finished, false);+ verification.resolve(true);+ assert.equal((await result).ok, true);+});++test("zero login exit with unauthenticated SDK status is a failure, not success", async () => {+ const { operations } = fixture({ verifyAuthentication: async () => false });+ const result = await new SignInCoordinator().signIn("attempt", 1, operations);+ assert.equal(result.status, "failed");+ if (!result.ok) assert.match(result.error!, /still signed out/);+});++test("auth errors do not expose raw CLI output or retry automatically", async () => {+ const { calls, operations } = fixture({+ login: async () => { throw new Error("secret raw CLI output"); },+ });+ const result = await new SignInCoordinator().signIn("attempt", 1, operations);+ assert.equal(result.status, "failed");+ assert.doesNotMatch(JSON.stringify(result), /secret raw/);+ assert.deepEqual(calls, ["hint"]);+});++test("authored errors and a non-secret manual fallback are surfaced", async () => {+ const { operations } = fixture({+ login: async () => { throw new SignInError("Could not start login."); },+ });+ assert.deepEqual(await new SignInCoordinator().signIn("attempt", 1, operations), {+ ok: false, status: "failed", error: "Could not start login.", command: operations.manualCommand,+ });+});++test("single flight rejects duplicates and cancellation requires matching attempt and owner", async () => {+ const entered = deferred<void>();+ let aborted = false;+ const { calls, operations } = fixture({+ login: async (signal) => {+ entered.resolve();+ try { await abortable(new Promise<void>(() => {}), signal); }+ finally { aborted = true; }+ },+ });+ const coordinator = new SignInCoordinator();+ const result = coordinator.signIn("first", 1, operations);+ await entered.promise;+ assert.equal((await coordinator.signIn("second", 2, operations)).status, "failed");+ coordinator.cancel("first", 2);+ coordinator.cancel("second", 1);+ assert.equal(aborted, false);+ coordinator.cancel("first", 1);+ assert.equal((await result).status, "canceled");+ assert.equal(aborted, true);+ assert.deepEqual(calls, ["hint"]);+ assert.equal((await coordinator.signIn("third", 1, fixture().operations)).ok, true);+});++test("timeout during a hint/choice cannot launch a late login", async () => {+ const hint = deferred<boolean>();+ const { calls, operations } = fixture({ hasMicrosoftHint: () => hint.promise });+ const result = await new SignInCoordinator(10).signIn("attempt", 1, operations);+ assert.equal(result.status, "timed-out");+ hint.resolve(true);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.deepEqual(calls, []);+});++test("timeout aborts active login and waits for its cleanup", async () => {+ let cleaned = false;+ const { calls, operations } = fixture({+ login: async (signal) => {+ try { await abortable(new Promise<void>(() => {}), signal); }+ finally { cleaned = true; }+ },+ });+ const result = await new SignInCoordinator(10).signIn("attempt", 1, operations);+ assert.equal(result.status, "timed-out");+ assert.equal(cleaned, true);+ assert.deepEqual(calls, ["hint"]);+});++test("shutdown invalidates login and prevents verification", async () => {+ const started = deferred<void>();+ const { calls, operations } = fixture({+ login: async (signal) => {+ started.resolve();+ await abortable(new Promise<void>(() => {}), signal);+ },+ });+ const coordinator = new SignInCoordinator();+ const result = coordinator.signIn("attempt", 1, operations);+ await started.promise;+ coordinator.dispose();+ assert.equal((await result).status, "canceled");+ assert.deepEqual(calls, ["hint"]);+});++test("cancel during SDK verification cannot report authenticated", async () => {+ const verifying = deferred<void>();+ const { operations } = fixture({+ verifyAuthentication: async (signal) => {+ verifying.resolve();+ return abortable(new Promise<boolean>(() => {}), signal);+ },+ });+ const coordinator = new SignInCoordinator();+ const result = coordinator.signIn("attempt", 1, operations);+ await verifying.promise;+ coordinator.cancel("attempt", 1);+ assert.equal((await result).status, "canceled");+});diff --git a/electron/copilot-signin-flow.ts b/electron/copilot-signin-flow.tsnew file mode 100644index 0000000..1abf574--- /dev/null+++ b/electron/copilot-signin-flow.ts@@ -0,0 +1,97 @@+import type { CopilotSignInResult } from "../common/ipc";++export type SignInAccount = "microsoft" | "personal" | "canceled";++export interface SignInOperations {+ hasMicrosoftHint(): Promise<boolean>;+ chooseAccount(signal: AbortSignal): Promise<SignInAccount>;+ prepareEnterprise(signal: AbortSignal): Promise<boolean>;+ login(signal: AbortSignal): Promise<void>;+ verifyAuthentication(signal: AbortSignal): Promise<boolean>;+ manualCommand?: string;+}++/** Only these deliberately authored messages may cross the IPC boundary. */+export class SignInError extends Error {}++export function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const abort = () => reject(signal.reason);+ if (signal.aborted) abort();+ else signal.addEventListener("abort", abort, { once: true });+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));+ });+}++export class SignInCoordinator {+ private active: { id: string; owner: number; controller: AbortController } | undefined;++ constructor(private readonly timeoutMs = 5 * 60_000) {}++ cancel(id: string, owner: number): void {+ if (this.active?.id === id && this.active.owner === owner) {+ this.active.controller.abort();+ }+ }++ dispose(): void {+ this.active?.controller.abort();+ }++ async signIn(id: string, owner: number, operations: SignInOperations): Promise<CopilotSignInResult> {+ if (this.active) {+ return { ok: false, status: "failed", error: "Another sign-in is already in progress." };+ }+ const controller = new AbortController();+ const { signal } = controller;+ this.active = { id, owner, controller };+ let timedOut = false;+ const timeout = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, this.timeoutMs);+ try {+ const hinted = await abortable(operations.hasMicrosoftHint(), signal);+ signal.throwIfAborted();+ if (hinted) {+ const account = await abortable(operations.chooseAccount(signal), signal);+ signal.throwIfAborted();+ if (account === "canceled") return { ok: false, status: "canceled" };+ if (account === "microsoft") {+ const ready = await abortable(operations.prepareEnterprise(signal), signal);+ signal.throwIfAborted();+ if (!ready) return { ok: false, status: "canceled" };+ }+ }+ // Login/verification own their subprocess cleanup; await it before releasing the lock.+ await operations.login(signal);+ signal.throwIfAborted();+ const authenticated = await operations.verifyAuthentication(signal);+ signal.throwIfAborted();+ if (!authenticated) {+ throw new SignInError("Login finished, but Copilot is still signed out. Try signing in again.");+ }+ return { ok: true, status: "authenticated" };+ } catch (error) {+ if (signal.aborted) {+ return timedOut+ ? {+ ok: false,+ status: "timed-out",+ error: "Sign-in timed out. Try again, or run the command below in a terminal.",+ command: operations.manualCommand,+ }+ : { ok: false, status: "canceled" };+ }+ return {+ ok: false,+ status: "failed",+ error: error instanceof SignInError ? error.message : "Could not complete sign-in. Please try again.",+ command: operations.manualCommand,+ };+ } finally {+ clearTimeout(timeout);+ this.active = undefined;+ }+ }+}diff --git a/electron/copilot-signin-process.test.ts b/electron/copilot-signin-process.test.tsnew file mode 100644index 0000000..0033665--- /dev/null+++ b/electron/copilot-signin-process.test.ts@@ -0,0 +1,59 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import test from "node:test";++import { copilotSignInCommand, runCopilotLogin } from "./copilot-signin-process";++test("login runs the bundled executable without a shell, terminal, or writable stdin", async () => {+ await runCopilotLogin("C:\\Program Files\\Recorder & More\\copilot.exe", new AbortController().signal,+ (file, args, options) => {+ assert.equal(file, "C:\\Program Files\\Recorder & More\\copilot.exe");+ assert.deepEqual(args, ["login", "--web-flow"]);+ assert.equal(options.windowsHide, true);+ assert.equal(options.shell, undefined);+ assert.equal(options.detached, undefined);+ assert.equal(options.stdio, "ignore");+ return spawn(process.execPath, ["-e", "process.exit(0)"], options);+ });+});++test("manual commands quote spaces and apostrophes for PowerShell and POSIX shells", () => {+ assert.equal(copilotSignInCommand("C:\\User's files\\copilot.exe", "win32"),+ "& 'C:\\User''s files\\copilot.exe' login --web-flow");+ assert.equal(copilotSignInCommand("/User's files/copilot", "darwin"),+ "'/User'\\''s files/copilot' login --web-flow");+});++test("nonzero exit surfaces a safe error and never emits buffered CLI output", async () => {+ await assert.rejects(+ runCopilotLogin("copilot", new AbortController().signal, (_file, _args, options) =>+ spawn(process.execPath, ["-e", "console.error('private output'); process.exit(1)"], options)),+ /Copilot login did not complete/,+ );+});++test("missing executable is a visible failure", async () => {+ await assert.rejects(runCopilotLogin("nonexistent-skill-recorder-test-cli", new AbortController().signal),+ /Could not start the bundled Copilot CLI/);+});++test("cancellation waits for the app-owned child to close", async () => {+ const controller = new AbortController();+ let closed = false;+ const result = runCopilotLogin("copilot", controller.signal, (_file, _args, options) => {+ const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], options);+ child.once("close", () => { closed = true; });+ child.once("spawn", () => controller.abort());+ return child;+ });+ await assert.rejects(result, { name: "AbortError" });+ assert.equal(closed, true);+});++test("an already canceled attempt does not start a process", () => {+ const controller = new AbortController();+ controller.abort();+ assert.throws(() => runCopilotLogin("copilot", controller.signal, () => {+ assert.fail("must not spawn");+ }), { name: "AbortError" });+});diff --git a/electron/copilot-signin-process.ts b/electron/copilot-signin-process.tsnew file mode 100644index 0000000..f243a87--- /dev/null+++ b/electron/copilot-signin-process.ts@@ -0,0 +1,46 @@+import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";++import { SignInError } from "./copilot-signin-flow";++export function copilotSignInCommand(cliPath: string, platform = process.platform): string {+ const quoted = platform === "win32"+ ? `& '${cliPath.replace(/'/g, "''")}'`+ : `'${cliPath.replace(/'/g, `'\\''`)}'`;+ return `${quoted} login --web-flow`;+}++/**+ * Own the actual CLI process, not a detached terminal launcher. Browser OAuth works+ * without a console; shell interpolation and a lingering cmd /k are unnecessary.+ */+export function runCopilotLogin(+ cliPath: string,+ signal: AbortSignal,+ spawnProcess: (file: string, args: string[], options: SpawnOptions) => ChildProcess = spawn,+): Promise<void> {+ signal.throwIfAborted();+ return new Promise<void>((resolve, reject) => {+ const child = spawnProcess(cliPath, ["login", "--web-flow"], {+ windowsHide: true,+ // No stdin means no automatic consent to plaintext credential storage.+ stdio: "ignore",+ });+ const abort = () => {+ child.kill("SIGKILL");+ };+ signal.addEventListener("abort", abort, { once: true });+ let launchFailed = false;+ child.once("error", () => {+ launchFailed = true;+ // Spawn failures also emit close; wait for it before releasing the sign-in lock.+ });+ child.once("close", (code) => {+ signal.removeEventListener("abort", abort);+ if (signal.aborted) reject(signal.reason);+ else if (launchFailed) reject(new SignInError("Could not start the bundled Copilot CLI. Reinstall the app or use the command below."));+ else if (code === 0) resolve();+ else reject(new SignInError("Copilot login did not complete. Try again, or run the command below in a terminal to see the CLI's instructions."));+ });+ if (signal.aborted) abort();+ });+}diff --git a/electron/copilot-signin.ts b/electron/copilot-signin.tsindex 9fdc13f..b540623 100644--- a/electron/copilot-signin.ts+++ b/electron/copilot-signin.ts@@ -1,88 +1,88 @@-import { execFileSync, spawn } from "node:child_process";+import { dialog, shell, type BrowserWindow, type MessageBoxOptions } from "electron";+import { CopilotClient } from "@github/copilot-sdk";import type { CopilotSignInResult } from "../common/ipc";-import { resolveCopilotCliPath } from "./copilot-cli-path";+import { copilotConnectionOption, resolveCopilotCliPath } from "./copilot-cli-path";+import { verifyCopilotAuthentication } from "./copilot-signin-auth";+import { SignInCoordinator, SignInError } from "./copilot-signin-flow";+import { copilotSignInCommand, runCopilotLogin } from "./copilot-signin-process";import { createLogger } from "./logger";+import { hasMicrosoftSignInHint } from "./microsoft-signin-hint";const log = createLogger("CopilotSignIn");+const coordinator = new SignInCoordinator();+const MICROSOFT_ENTERPRISE_URL = "https://github.com/enterprises/microsoft";-/** POSIX single-quoting so a path with spaces survives the shell the terminal opens. */-function shellQuote(value: string): string {- return `'${value.replace(/'/g, `'\\''`)}'`;+export function cancelCopilotSignIn(attemptId: string, owner: number): void {+ coordinator.cancel(attemptId, owner);}-/** The command that signs the user in — also shown in the UI as a manual fallback. */-export function copilotSignInCommand(cliPath: string): string {- return process.platform === "win32" ? `"${cliPath}" login` : `${shellQuote(cliPath)} login`;+export function disposeCopilotSignIn(): void {+ coordinator.dispose();}-const LINUX_TERMINALS = [- "x-terminal-emulator",- "gnome-terminal",- "konsole",- "xfce4-terminal",- "xterm",-];--function onPath(command: string): boolean {- try {- execFileSync("which", [command], { stdio: "ignore" });- return true;- } catch {- return false;- }-}--/** Spawn a terminal and let it outlive the app; ENOENT arrives as an event, not a throw. */-function launch(file: string, args: string[], verbatim = false): void {- const child = spawn(file, args, {- detached: true,- stdio: "ignore",- windowsHide: false,- windowsVerbatimArguments: verbatim,- });- child.on("error", (err) => log.warn("terminal failed to start:", err.message));- child.unref();-}--/**- * Open a terminal window running `login` on the Copilot CLI that ships with the app.- * Skill Recorder installs the CLI as a dependency, so telling users to run a global- * `copilot` doesn't work — we hand them the bundled binary's full path instead.- */-export function openCopilotSignIn(): CopilotSignInResult {+export async function openCopilotSignIn(+ attemptId: string,+ owner: number,+ parent: BrowserWindow | null,+): Promise<CopilotSignInResult> {const cliPath = resolveCopilotCliPath();if (!cliPath) {return {ok: false,+ status: "failed",error: "Skill Recorder couldn't find its bundled GitHub Copilot CLI. Reinstall the app.",};}- const command = copilotSignInCommand(cliPath);- try {- if (process.platform === "win32") {- // `start` gives the CLI its own console. The doubled quotes are cmd's required- // form when the window title and the command are both quoted.- launch("cmd.exe", ["/c", `start "Sign in to GitHub Copilot" cmd.exe /k "${command}"`], true);- } else if (process.platform === "darwin") {- const script = `tell application "Terminal"\nactivate\ndo script ${JSON.stringify(command)}\nend tell`;- launch("osascript", ["-e", script]);- } else {- const terminal = LINUX_TERMINALS.find(onPath);- if (!terminal) {- return {- ok: false,- command,- error: "No terminal emulator was found. Run the command below yourself, then try again.",- };+ const show = (options: MessageBoxOptions) =>+ parent && !parent.isDestroyed()+ ? dialog.showMessageBox(parent, options)+ : dialog.showMessageBox(options);+ const result = await coordinator.signIn(attemptId, owner, {+ hasMicrosoftHint: hasMicrosoftSignInHint,+ chooseAccount: async (signal) => {+ const { response } = await show({+ type: "question",+ title: "Sign in to GitHub Copilot",+ message: "Use Microsoft Enterprise SSO or a personal GitHub account?",+ detail: "This Windows account or device appears to be associated with Microsoft. Choose the account you want to use.",+ buttons: ["Microsoft Enterprise SSO", "Personal GitHub account", "Cancel"],+ defaultId: 0,+ cancelId: 2,+ noLink: true,+ signal,+ });+ return response === 0 ? "microsoft" : response === 1 ? "personal" : "canceled";+ },+ prepareEnterprise: async (signal) => {+ signal.throwIfAborted();+ try {+ await shell.openExternal(MICROSOFT_ENTERPRISE_URL);+ } catch {+ throw new SignInError("Could not open the enterprise sign-in page. Check your default browser and try again.");}- launch(terminal, ["-e", "sh", "-c", `${command}; exec sh`]);- }- log.info("opened a terminal for the bundled CLI's login command");- return { ok: true, command };- } catch (err) {- const error = err instanceof Error ? err.message : String(err);- log.warn("could not open a terminal:", error);- return { ok: false, command, error };- }+ signal.throwIfAborted();+ const { response } = await show({+ type: "info",+ title: "Microsoft Enterprise SSO",+ message: "Finish Microsoft SSO in your browser, then continue here.",+ detail: "Copilot authorization opens next. Use the same browser profile and the GitHub account linked to your Microsoft enterprise access.",+ buttons: ["Continue to Copilot", "Cancel"],+ defaultId: 0,+ cancelId: 1,+ noLink: true,+ signal,+ });+ return response === 0;+ },+ login: (signal) => runCopilotLogin(cliPath, signal),+ verifyAuthentication: (signal) => verifyCopilotAuthentication(+ () => new CopilotClient(copilotConnectionOption()), signal,+ ),+ manualCommand: copilotSignInCommand(cliPath),+ });+ // Do not record CLI output, account names, tenant metadata, or browser URLs.+ if (result.ok) log.info("Copilot sign-in verified");+ else if (result.status !== "canceled") log.warn("Copilot sign-in ended:", result.status);+ return result;}diff --git a/electron/ipc.ts b/electron/ipc.tsindex c803988..85b694f 100644--- a/electron/ipc.ts+++ b/electron/ipc.ts@@ -1,4 +1,5 @@import {+ app,BrowserWindow,dialog,ipcMain,@@ -32,7 +33,7 @@ import type { NarrationLanguage } from "../common/narration";import type { SensitiveReport } from "../common/sensitive";import type { SkillPlan } from "../common/skill";import { AutomationBuilder, loadPersistedAutomation } from "./automationbuilder/builder";-import { openCopilotSignIn } from "./copilot-signin";+import { cancelCopilotSignIn, disposeCopilotSignIn, openCopilotSignIn } from "./copilot-signin";import { buildDebugInfo, writeDebugBundle } from "./debug-bundle";import { Describer, loadPersistedAnalysis } from "./describer/describer";import type { RedactionContext } from "./describer/tools";@@ -163,7 +164,24 @@ export function registerIpc(ipcMain.handle(IPC.status, () => recorder.status());ipcMain.handle(IPC.marker, (_event, note: string) => recorder.marker(note));ipcMain.handle(IPC.doctor, () => runDoctor());- ipcMain.handle(IPC.copilotSignIn, () => openCopilotSignIn());+ app.once("before-quit", disposeCopilotSignIn);+ ipcMain.handle(IPC.copilotSignIn, async (event, attemptId: unknown) => {+ if (typeof attemptId !== "string" || !/^[a-zA-Z0-9-]{1,64}$/.test(attemptId)) {+ return { ok: false, status: "failed", error: "Invalid sign-in attempt." };+ }+ const owner = event.sender.id;+ const cancel = () => cancelCopilotSignIn(attemptId, owner);+ event.sender.once("destroyed", cancel);+ try {+ return await openCopilotSignIn(attemptId, owner, BrowserWindow.fromWebContents(event.sender));+ } finally {+ event.sender.removeListener("destroyed", cancel);+ }+ });+ ipcMain.handle(IPC.copilotSignInCancel, (event, attemptId: unknown) => {+ if (typeof attemptId !== "string") throw new Error("Invalid sign-in attempt.");+ cancelCopilotSignIn(attemptId, event.sender.id);+ });ipcMain.handle(IPC.narrationStatus, () => narration.status());ipcMain.handle(IPC.narrationDownload, () => narration.downloadModel());ipcMain.handle(IPC.narrationTranscribe, (_event, sessionId: string) =>diff --git a/electron/microsoft-signin-hint.test.ts b/electron/microsoft-signin-hint.test.tsnew file mode 100644index 0000000..6155e44--- /dev/null+++ b/electron/microsoft-signin-hint.test.ts@@ -0,0 +1,159 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ createMicrosoftSignInHintProbe,+ parseMicrosoftSignInHint,+ type MicrosoftSignInHintDependencies,+} from "./microsoft-signin-hint";++const microsoft = "72f988bf-86f1-41af-91ab-2d7cd011db47";+const other = "11111111-2222-3333-4444-555555555555";+const section = (name: string, fields: string) =>+ `+----------------------------------------------------------------------+\n| ${name.padEnd(69)}|\n+----------------------------------------------------------------------+\n${fields}\n`;+const joined = (tenant = microsoft, state = "YES") =>+ section("Device State", ` AzureAdJoined : ${state}\n DomainJoined : YES`) ++ section("Tenant Details", ` TenantId : ${tenant}`);+const registered = (tenant = microsoft, state = "YES") =>+ section("Device State", " AzureAdJoined : NO") ++ section("User State", ` WorkplaceJoined : ${state}`) ++ section("Work Account 1", ` WorkplaceTenantId : ${tenant}`);++test("matches the exact Microsoft joined tenant, including uppercase GUID and CRLF", () => {+ assert.equal(parseMicrosoftSignInHint(joined()), true);+ assert.equal(parseMicrosoftSignInHint(joined(microsoft.toUpperCase()).replaceAll("\n", "\r\n")), true);+});++test("rejects other tenants, tenant substrings, and unjoined/domain-only devices", () => {+ for (const output of [+ joined(other), joined(`${microsoft}-extra`), joined(`prefix-${microsoft}`),+ joined(microsoft, "NO"), joined(microsoft, "UNKNOWN"), joined(microsoft, "YES extra"),+ section("Device State", "DomainJoined : YES") + section("Tenant Details", `TenantId : ${microsoft}`),+ ]) assert.equal(parseMicrosoftSignInHint(output), false);+});++test("matches registered accounts only with user registration state", () => {+ assert.equal(parseMicrosoftSignInHint(registered()), true);+ assert.equal(parseMicrosoftSignInHint(registered(other)), false);+ assert.equal(parseMicrosoftSignInHint(registered(microsoft, "NO")), false);+ assert.equal(parseMicrosoftSignInHint(registered(other) ++ section("Work Account 2", `WorkplaceTenantId : ${microsoft}`)), true);+});++test("does not confuse joined and registered tenant fields or unrelated output", () => {+ for (const output of [+ registered().replace("WorkplaceTenantId", "TenantId"),+ joined().replace("TenantId", "WorkplaceTenantId"),+ joined(other) + registered(microsoft, "NO"),+ joined(microsoft, "NO") + registered(other),+ joined(other) + section("Diagnostic Data", `TenantId : ${microsoft}`),+ registered(other) + section("Diagnostic Data", `WorkplaceTenantId : ${microsoft}`),+ joined(other) + `\n TenantName : Microsoft\n User Identity : [email protected]\n URL : https://example.com/${microsoft}`,+ ]) assert.equal(parseMicrosoftSignInHint(output), false);+});++test("malformed, missing, duplicate, localized and oversized output fails closed", () => {+ for (const output of [+ "", "not dsregcmd output", `AzureAdJoined : YES\nTenantId : ${microsoft}`,+ section("Tenant Details", `TenantId : ${microsoft}`),+ joined(""), joined(`{${microsoft}}`), joined().replace("TenantId :", "TenantId ="),+ joined() + "\nTenantId : " + other,+ joined() + section("Tenant Details", `TenantId : ${other}`),+ joined().replace("Device State", "Gerätestatus"),+ joined() + "x".repeat(128 * 1024),+ ]) assert.equal(parseMicrosoftSignInHint(output), false);+});++function harness(overrides: Partial<MicrosoftSignInHintDependencies> = {}) {+ const logs: unknown[][] = [];+ let calls = 0;+ const deps: MicrosoftSignInHintDependencies = {+ platform: "win32",+ systemRoot: "C:\\Windows",+ log: { info: (...args) => { logs.push(args); } },+ execFile: (file, args, options, callback) => {+ calls++;+ assert.equal(file, "C:\\Windows\\System32\\dsregcmd.exe");+ assert.deepEqual(args, ["/status"]);+ assert.deepEqual(options, {+ encoding: "utf8", timeout: 3_000, maxBuffer: 128 * 1024,+ windowsHide: true, shell: false,+ });+ queueMicrotask(() => callback(null, joined(), ""));+ },+ ...overrides,+ };+ return { probe: createMicrosoftSignInHintProbe(deps), logs, calls: () => calls };+}++test("probe executes asynchronously with bounded hidden execution at a system path", async () => {+ const h = harness();+ assert.equal(await h.probe(), true);+ assert.equal(h.calls(), 1);+ assert.deepEqual(h.logs, []);+});++test("probe supports a non-default absolute Windows installation path", async () => {+ const h = harness({+ systemRoot: "D:\\Windows",+ execFile: (file, _args, _options, callback) => {+ assert.equal(file, "D:\\Windows\\System32\\dsregcmd.exe");+ callback(null, registered(), "");+ },+ });+ assert.equal(await h.probe(), true);+});++test("non-Windows platforms skip execution completely", async () => {+ for (const platform of ["darwin", "linux", "freebsd", "unknown"]) {+ const h = harness({ platform });+ assert.equal(await h.probe(), false);+ assert.equal(h.calls(), 0);+ assert.deepEqual(h.logs, [["Microsoft sign-in hint unavailable", { reason: "unsupported-platform" }]]);+ }+});++test("missing or unsupported system paths never fall back to PATH", async () => {+ for (const systemRoot of [undefined, "", "Windows", "\\Windows", "\\\\host\\share", "C:\\Windows\\..\\Users"]) {+ const h = harness({ systemRoot });+ assert.equal(await h.probe(), false);+ assert.equal(h.calls(), 0);+ assert.deepEqual(h.logs, [["Microsoft sign-in hint unavailable", { reason: "unsupported-system-path" }]]);+ }+});++test("failure, missing executable, timeout and buffer errors ignore even matching partial stdout", async () => {+ for (const [properties, reason] of [+ [{ code: "ENOENT" }, "executable-missing"],+ [{ code: 1 }, "probe-failed"],+ [{ code: "ETIMEDOUT" }, "timeout"],+ [{ killed: true, signal: "SIGTERM" }, "timeout"],+ [{ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }, "output-limit"],+ ] as const) {+ const h = harness({+ execFile: (_file, _args, _options, callback) => {+ const error = Object.assign(new Error("private account/device details"), properties, {+ stdout: joined(), stderr: "private diagnostics",+ });+ queueMicrotask(() => callback(error, joined(), "private diagnostics"));+ },+ });+ assert.equal(await h.probe(), false);+ assert.deepEqual(h.logs, [["Microsoft sign-in hint unavailable", { reason }]]);+ }+});++test("synchronous execution errors are sanitized and return false", async () => {+ const h = harness({ execFile: () => { throw new Error("private account/device details"); } });+ assert.equal(await h.probe(), false);+ assert.deepEqual(h.logs, [["Microsoft sign-in hint unavailable", { reason: "probe-failed" }]]);+});++test("successful but unsupported/unmatched output is sanitized and returns false", async () => {+ for (const output of ["unsupported command: private diagnostics", joined(other), "", joined() + "x".repeat(128 * 1024)]) {+ const h = harness({+ execFile: (_file, _args, _options, callback) => callback(null, output, "private diagnostics"),+ });+ assert.equal(await h.probe(), false);+ assert.deepEqual(h.logs, [["Microsoft sign-in hint unavailable", { reason: "no-matching-hint" }]]);+ }+});diff --git a/electron/microsoft-signin-hint.ts b/electron/microsoft-signin-hint.tsnew file mode 100644index 0000000..a09d280--- /dev/null+++ b/electron/microsoft-signin-hint.ts@@ -0,0 +1,116 @@+import { execFile, type ExecFileOptionsWithStringEncoding } from "node:child_process";+import { win32 } from "node:path";+import { createLogger } from "./logger";++// Microsoft's public microsoft.com OpenID metadata, verified 2026-09-15:+// https://login.microsoftonline.com/microsoft.com/v2.0/.well-known/openid-configuration+// This is a routing hint only, never proof of identity, employment, or authorization.+const MICROSOFT_TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47";+const MAX_OUTPUT_BYTES = 128 * 1024;+const TIMEOUT_MS = 3_000;++/**+ * Parse only dsregcmd's documented device/user state and associated tenant sections.+ * https://learn.microsoft.com/en-us/entra/identity/devices/troubleshoot-device-dsregcmd+ * Unknown/localized output deliberately produces no hint.+ */+export function parseMicrosoftSignInHint(output: string): boolean {+ if (Buffer.byteLength(output, "utf8") > MAX_OUTPUT_BYTES) return false;++ const sections = new Map<string, Map<string, string>>();+ let section: Map<string, string> | undefined;+ for (const line of output.split(/\r?\n/)) {+ const heading = /^\s*\|\s*([^|]+?)\s*\|\s*$/.exec(line);+ if (heading) {+ const name = heading[1].trim();+ section = undefined;+ if (!/^(Device State|User State|Tenant Details|Work Account \d+)$/.test(name)) continue;+ if (sections.has(name)) return false;+ section = new Map();+ sections.set(name, section);+ continue;+ }+ if (!section) continue;+ const field = /^\s*(AzureAdJoined|WorkplaceJoined|TenantId|WorkplaceTenantId)\s*:\s*(.*?)\s*$/.exec(line);+ if (!field) continue;+ if (section.has(field[1])) return false;+ section.set(field[1], field[2]);+ }++ const isMicrosoft = (tenant: string | undefined) =>+ tenant?.toLowerCase() === MICROSOFT_TENANT_ID;+ if (+ sections.get("Device State")?.get("AzureAdJoined") === "YES" &&+ isMicrosoft(sections.get("Tenant Details")?.get("TenantId"))+ ) return true;++ return sections.get("User State")?.get("WorkplaceJoined") === "YES" &&+ [...sections].some(([name, fields]) =>+ /^Work Account \d+$/.test(name) && isMicrosoft(fields.get("WorkplaceTenantId")),+ );+}++export interface MicrosoftSignInHintDependencies {+ platform: string;+ systemRoot: string | undefined;+ execFile: (+ file: string,+ args: string[],+ options: ExecFileOptionsWithStringEncoding,+ callback: (error: Error | null, stdout: string, stderr: string) => void,+ ) => void;+ log: Pick<ReturnType<typeof createLogger>, "info">;+}++/** Injectable probe for tests; it never reads credentials or searches account stores. */+export function createMicrosoftSignInHintProbe(deps: MicrosoftSignInHintDependencies) {+ return async (): Promise<boolean> => {+ const noHint = (reason: string): false => {+ deps.log.info("Microsoft sign-in hint unavailable", { reason });+ return false;+ };+ if (deps.platform !== "win32") return noHint("unsupported-platform");++ // Never fall back to PATH, the current directory, or a relative/UNC root.+ const root = deps.systemRoot;+ if (!root || !/^[a-z]:\\/i.test(root) || /[\x00-\x1f]/.test(root) ||+ root.split(/[\\/]/).some((part) => part === "..")) {+ return noHint("unsupported-system-path");+ }++ try {+ const output = await new Promise<string>((resolve, reject) => {+ deps.execFile(win32.join(root, "System32", "dsregcmd.exe"), ["/status"], {+ encoding: "utf8",+ timeout: TIMEOUT_MS,+ maxBuffer: MAX_OUTPUT_BYTES,+ windowsHide: true,+ shell: false,+ }, (error, stdout) => {+ if (error) reject(error);+ else resolve(stdout);+ });+ });+ return parseMicrosoftSignInHint(output) || noHint("no-matching-hint");+ } catch (error) {+ // Whitelist categories only: messages/stdout/stderr can contain account/device data.+ const failure = error as { code?: unknown; killed?: unknown } | null;+ const reason = failure?.code === "ENOENT" ? "executable-missing"+ : failure?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "output-limit"+ : failure?.code === "ETIMEDOUT" || failure?.killed === true ? "timeout"+ : "probe-failed";+ return noHint(reason);+ }+ };+}++export async function hasMicrosoftSignInHint(): Promise<boolean> {+ return createMicrosoftSignInHintProbe({+ platform: process.platform,+ systemRoot: process.env.SystemRoot ?? process.env.windir,+ execFile: (file, args, options, callback) => {+ execFile(file, args, options, callback);+ },+ log: createLogger("microsoft-signin-hint"),+ })();+}diff --git a/electron/preload.cjs b/electron/preload.cjsindex bc78f2c..dc4c798 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -20,6 +20,7 @@ const IPC = {marker: "recorder:marker",doctor: "doctor:check",copilotSignIn: "copilot:sign-in",+ copilotSignInCancel: "copilot:sign-in-cancel",statusChanged: "recorder:status-changed",recordingPrivacyReviewed: "recorder:privacy-reviewed",recordingPrivacyWarningRequested: "recorder:privacy-warning-requested",@@ -116,7 +117,8 @@ contextBridge.exposeInMainWorld("skillRecorder", {status: () => ipcRenderer.invoke(IPC.status),marker: (note) => ipcRenderer.invoke(IPC.marker, note),doctor: () => ipcRenderer.invoke(IPC.doctor),- copilotSignIn: () => ipcRenderer.invoke(IPC.copilotSignIn),+ copilotSignIn: (attemptId) => ipcRenderer.invoke(IPC.copilotSignIn, attemptId),+ cancelCopilotSignIn: (attemptId) => ipcRenderer.invoke(IPC.copilotSignInCancel, attemptId),onStatusChanged: (cb) => {const listener = (_event, status) => cb(status);ipcRenderer.on(IPC.statusChanged, listener);diff --git a/package.json b/package.jsonindex 23b9223..ec2f287 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/screen.test.ts common/narration.test.ts common/sensitive.test.ts common/skill.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/pipeline.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/terminal/terminal.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/plan-tools.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 common/skill.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/copilot-signin-auth.test.ts electron/copilot-signin-flow.test.ts electron/copilot-signin-process.test.ts electron/microsoft-signin-hint.test.ts src/analysis-recovery.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/pipeline.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/terminal/terminal.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/plan-tools.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:terminal": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts --only=terminal-output-required,terminal-failure-recovery,terminal-sensitive-output","eval:builder": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/builder/run.ts",diff --git a/src/Library.tsx b/src/Library.tsxindex 1e27ac0..9dd4e00 100644--- a/src/Library.tsx+++ b/src/Library.tsx@@ -40,6 +40,7 @@ import {import { formatBytes, formatDur, formatWhen, shortLabel } from "./format";import { skillPlacementModel, skillTargetFor } from "./skill-placement";import { SensitiveReview } from "./SensitiveReview";+import { AnalysisRecovery, completeSignIn, type AnalysisRun } from "./analysis-recovery";export function Library() {const [sessions, setSessions] = useState<SessionSummary[]>([]);@@ -412,17 +413,97 @@ function DebugDownload({ sessionId }: { sessionId: string }) {/*** Error banner for the Copilot-backed panels. When the CLI has no credentials the app- * offers to open a terminal on its *bundled* Copilot binary — there's no global- * `copilot` command to send people to.+ * waits for verified authentication. Only analysis supplies a recovery callback;+ * building, creating and installing always require another explicit user action.*/-function AnalysisError({ error }: { error: string }) {+function AnalysisError({+ error,+ onAuthenticated,+ onSignInStart,+ onSignInEnd,+}: {+ error: string;+ onAuthenticated?: () => void | Promise<void>;+ onSignInStart?: () => boolean;+ onSignInEnd?: (canceled: boolean) => void;+}) {const [signIn, setSignIn] = useState<CopilotSignInResult | null>(null);- const [opening, setOpening] = useState(false);+ const [waiting, setWaiting] = useState(false);+ const [failure, setFailure] = useState<string | null>(null);+ const attempt = useRef<string | null>(null);+ const generation = useRef(0);+ const live = useRef(false);+ const endCallback = useRef(onSignInEnd);+ endCallback.current = onSignInEnd;++ useEffect(() => {+ live.current = true;+ setWaiting(false);+ setSignIn(null);+ setFailure(null);+ return () => {+ live.current = false;+ generation.current++;+ const id = attempt.current;+ attempt.current = null;+ if (id) {+ endCallback.current?.(true);+ void window.skillRecorder.cancelCopilotSignIn(id).catch(() => {+ console.warn("Could not cancel Copilot sign-in during panel cleanup.");+ });+ }+ };+ }, [error]);++ const cancelSignIn = async () => {+ const id = attempt.current;+ if (!id) return;+ const canceledGeneration = generation.current;+ attempt.current = null;+ onSignInEnd?.(true);+ setWaiting(false);+ setFailure(onAuthenticated+ ? "Sign-in canceled. Analysis will not retry automatically."+ : "Sign-in canceled.");+ try {+ await window.skillRecorder.cancelCopilotSignIn(id);+ } catch (err) {+ if (live.current && generation.current === canceledGeneration) {+ setFailure(`Could not cancel sign-in: ${String(err)}`);+ }+ }+ };const openSignIn = async () => {- setOpening(true);- setSignIn(await window.skillRecorder.copilotSignIn());- setOpening(false);+ if (attempt.current) return;+ const id = crypto.randomUUID();+ generation.current++;+ attempt.current = id;+ setWaiting(true);+ setSignIn(null);+ setFailure(null);+ let canceledResult = false;+ try {+ // A false return suppresses stale recovery without suppressing sign-in itself.+ const recover = onSignInStart?.() ?? true;+ const result = await completeSignIn(+ window.skillRecorder.copilotSignIn(id),+ () => live.current && attempt.current === id,+ recover ? onAuthenticated : undefined,+ );+ if (result && live.current && attempt.current === id) {+ canceledResult = !result.ok && result.status === "canceled";+ setSignIn(result);+ }+ } catch (err) {+ if (live.current && attempt.current === id) setFailure(String(err));+ } finally {+ if (live.current && attempt.current === id) {+ attempt.current = null;+ onSignInEnd?.(canceledResult);+ setWaiting(false);+ }+ }};if (!isCopilotSignedOutError(error)) return <div className="analysis-error">{error}</div>;@@ -431,15 +512,28 @@ function AnalysisError({ error }: { error: string }) {<div className="analysis-error"><p>{error}</p><div className="signin-row">- <button className="row-action" onClick={() => void openSignIn()} disabled={opening}>- {opening ? "Opening…" : "Sign in to Copilot"}+ <button className="row-action" onClick={() => void openSignIn()} disabled={waiting}>+ {waiting ? "Waiting for browser sign-in…" : "Sign in to Copilot"}</button>+ {waiting && (+ <>+ <span role="status">Follow the app prompts and finish signing in in your browser.</span>+ <button className="linky" onClick={() => void cancelSignIn()}>Cancel sign-in</button>+ </>+ )}{signIn?.ok && (- <span>A terminal opened — finish signing in there, then try again.</span>+ <span>Signed in to Copilot. Try your action again when ready.</span>)}- {signIn && !signIn.ok && <span>{signIn.error ?? "Couldn't open a terminal."}</span>}+ {signIn && !signIn.ok && (+ <span>{signIn.error ?? (+ signIn.status === "canceled" ? "Sign-in canceled." :+ signIn.status === "timed-out" ? "Sign-in timed out. Try again." :+ "Couldn't sign in to Copilot."+ )}</span>+ )}+ {failure && <span role="alert">{failure}</span>}</div>- {signIn?.command && (+ {signIn && !signIn.ok && signIn.command && (<><p className="signin-manual">Or run this command yourself:</p><code className="signin-command">{signIn.command}</code>@@ -478,6 +572,13 @@ function AnalysisWorkspace({const [analysis, setAnalysis] = useState<Analysis | null>(null);const [analyzing, setAnalyzing] = useState(false);+ const [signInPending, setSignInPending] = useState(false);+ const signInPendingRef = useRef(false);+ const pendingRecovery = useRef<AnalysisRun | null>(null);+ const recovery = useRef(new AnalysisRecovery());+ const [failedRun, setFailedRun] = useState<AnalysisRun | null>(null);+ const latestRun = useRef<AnalysisRun | null>(null);+ const workspaceLive = useRef(false);const [statusLine, setStatusLine] = useState("");const [error, setError] = useState<string | null>(null);// Informational summary of what the on-device scan redacted before sending;@@ -505,9 +606,15 @@ function AnalysisWorkspace({: "none";const [launch, setLaunch] = useState<LaunchTarget>(initialLaunch);const [chosenArch, setChosenArch] = useState<SkillArchitecture>(DEFAULT_TARGET.architecture);- // Set while the user is deliberately canceling, so the aborted run's rejection- // doesn't surface as an error toast.- const canceled = useRef(false);+ useEffect(() => {+ workspaceLive.current = true;+ return () => {+ workspaceLive.current = false;+ recovery.current.invalidate();+ signInPendingRef.current = false;+ pendingRecovery.current = null;+ };+ }, [sessionId]);useEffect(() => {let live = true;@@ -561,40 +668,106 @@ function AnalysisWorkspace({return window.skillRecorder.onAnalyzeProgress((p: AnalyzeProgress) => {if (p.sessionId !== sessionId) return;setStatusLine(p.message);- if (p.phase === "done" || p.phase === "error") setAnalyzing(false);+ // The invocation, not a progress event, owns the busy state.});}, [sessionId]);- const run = useCallback(- async () => {- canceled.current = false;+ const executeRun = useCallback(+ async (token: AnalysisRun) => {+ latestRun.current = token;setEditing(false);setDraftTitle("");setDraftIntent("");setReview(null);setError(null);setAnalyzing(true);+ setFailedRun(null);setStatusLine("Starting…");- const res = await window.skillRecorder.analyze(sessionId);- if (res.ok && res.analysis) {- setAnalysis(res.analysis);- setSteps(res.analysis.steps);- stepsDirty.current = false;- // Non-blocking: analysis already ran. If anything was redacted before it- // was sent, show an informational summary alongside the result.- setReview(res.review ?? null);- } else if (!canceled.current) setError(res.error ?? "Analysis failed");- setAnalyzing(false);- void onChanged();+ let signedOut = false;+ try {+ const res = await window.skillRecorder.analyze(sessionId);+ if (!workspaceLive.current || !recovery.current.accepts(token)) return;+ if (res.ok && res.analysis) {+ setAnalysis(res.analysis);+ setSteps(res.analysis.steps);+ stepsDirty.current = false;+ // Preserve the existing narration/redaction pipeline and result handling.+ setReview(res.review ?? null);+ } else {+ const message = res.error ?? "Analysis failed";+ signedOut = isCopilotSignedOutError(message);+ setError(message);+ setFailedRun(token);+ }+ } catch (err) {+ if (workspaceLive.current && recovery.current.accepts(token)) {+ const message = String(err);+ signedOut = isCopilotSignedOutError(message);+ setError(message);+ setFailedRun(token);+ }+ } finally {+ if (workspaceLive.current && recovery.current.isCurrent(token)) {+ recovery.current.finishRun(token, signedOut);+ setAnalyzing(false);+ try {+ await onChanged();+ } catch (err) {+ // A refresh failure must not be mistaken for an interrupted analysis.+ if (workspaceLive.current && latestRun.current === token) {+ setFailedRun(null);+ setError(`Could not refresh recordings: ${String(err)}`);+ }+ }+ }+ }},[sessionId, onChanged],);+ const run = useCallback(async () => {+ if (signInPendingRef.current) return;+ const token = recovery.current.beginRun();+ if (token) await executeRun(token);+ }, [executeRun]);++ const onSignInStart = useCallback(() => {+ signInPendingRef.current = true;+ setSignInPending(true);+ setConfirmReanalysis(false);+ const recover = failedRun != null && recovery.current.beginSignIn(failedRun);+ pendingRecovery.current = recover ? failedRun : null;+ return recover;+ }, [failedRun]);++ const onSignInEnd = useCallback((canceled: boolean) => {+ signInPendingRef.current = false;+ if (pendingRecovery.current) recovery.current.endSignIn(pendingRecovery.current, canceled);+ pendingRecovery.current = null;+ if (workspaceLive.current) setSignInPending(false);+ }, []);++ const retryAfterSignIn = useCallback(async () => {+ if (!workspaceLive.current || !failedRun) return;+ const token = recovery.current.retry(failedRun);+ if (!token) return;+ signInPendingRef.current = false;+ setSignInPending(false);+ await executeRun(token);+ }, [failedRun, executeRun]);+const cancel = useCallback(async () => {- canceled.current = true;+ const token = latestRun.current;+ recovery.current.cancelRun();setStatusLine("Stopping…");- await window.skillRecorder.cancelAnalysis(sessionId);- setAnalyzing(false);+ try {+ await window.skillRecorder.cancelAnalysis(sessionId);+ } catch (err) {+ if (workspaceLive.current && latestRun.current === token) {+ setFailedRun(null);+ setError(`Could not cancel analysis: ${String(err)}`);+ }+ }}, [sessionId]);const startEdit = useCallback(() => {@@ -602,6 +775,7 @@ function AnalysisWorkspace({setDraftTitle(analysis.title ?? "");setDraftIntent(analysis.intent);setError(null);+ setFailedRun(null);setEditing(true);}, [analysis]);@@ -615,6 +789,7 @@ function AnalysisWorkspace({setAnalysis(res.analysis);setEditing(false);} else {+ setFailedRun(null);setError(res.error ?? "Could not save your changes");}void onChanged();@@ -681,7 +856,7 @@ function AnalysisWorkspace({</p>)}- {voiceStale && !analyzing && (+ {voiceStale && !analyzing && !signInPending && (<div className="voice-card"><div className="voice-card-copy"><strong>Voice transcript added after this analysis</strong>@@ -717,7 +892,7 @@ function AnalysisWorkspace({{summary.processed && !analysis && !analyzing && (<div className="ws-empty"><p className="ws-empty-lead">See what you did in this recording, step by step.</p>- <button className="record-cta" onClick={() => void run()}>+ <button className="record-cta" onClick={() => void run()} disabled={signInPending}>Analyze recording</button><details className="analyze-disclosure">@@ -768,9 +943,16 @@ function AnalysisWorkspace({</p>)}- {error && <AnalysisError error={error} />}+ {error && (+ <AnalysisError+ error={error}+ onSignInStart={onSignInStart}+ onSignInEnd={onSignInEnd}+ onAuthenticated={failedRun && !failedRun.retried ? retryAfterSignIn : undefined}+ />+ )}- {analysis && !analyzing && (+ {analysis && !analyzing && !signInPending && (<div className="ws-read"><div className="summary"><div className="summary-head">@@ -843,7 +1025,7 @@ function AnalysisWorkspace({)}</div>- {analysis && !analyzing && (+ {analysis && !analyzing && !signInPending && (<div className="ws-foot"><span className="foot-status">{launchFootStatus(summary)}</span><div className="ws-foot-actions">diff --git a/src/analysis-recovery.test.ts b/src/analysis-recovery.test.tsnew file mode 100644index 0000000..ba9c63a--- /dev/null+++ b/src/analysis-recovery.test.ts@@ -0,0 +1,177 @@+import assert from "node:assert/strict";+import test from "node:test";++import { AnalysisRecovery, completeSignIn } from "./analysis-recovery";+import type { CopilotSignInResult } from "../common/ipc";++function interrupted(guard: AnalysisRecovery) {+ const run = guard.beginRun();+ assert.ok(run);+ guard.finishRun(run, true);+ return run;+}++test("verified sign-in can reserve exactly one retry of the original signed-out analysis", () => {+ const guard = new AnalysisRecovery();+ const original = interrupted(guard);+ assert.equal(guard.beginSignIn(original), true);+ assert.equal(guard.beginSignIn(original), false);+ assert.equal(guard.beginRun(), null);+ const retry = guard.retry(original);+ assert.ok(retry);+ assert.equal(retry.retried, true);+ assert.equal(guard.retry(original), null);+ assert.equal(guard.beginRun(), null);+ guard.finishRun(retry, true);+ assert.equal(guard.beginSignIn(retry), false);+ assert.equal(guard.retry(retry), null);+});++test("ordinary errors and successful analyses never become recoverable", () => {+ const guard = new AnalysisRecovery();+ const run = guard.beginRun();+ assert.ok(run);+ guard.finishRun(run, false);+ assert.equal(guard.beginSignIn(run), false);+ assert.equal(guard.retry(run), null);+});++test("cancel discards the pending authentication continuation", () => {+ const guard = new AnalysisRecovery();+ const run = interrupted(guard);+ assert.equal(guard.beginSignIn(run), true);+ guard.endSignIn(run);+ assert.equal(guard.retry(run), null);+ assert.equal(guard.beginSignIn(run), false);+ assert.ok(guard.beginRun());+});++test("an unsuccessful sign-in can be attempted again without spending the analysis retry", () => {+ const guard = new AnalysisRecovery();+ const original = interrupted(guard);+ guard.beginSignIn(original);+ guard.endSignIn(original, false);+ assert.equal(guard.retry(original), null);+ assert.equal(guard.beginSignIn(original), true);+ const retry = guard.retry(original);+ assert.ok(retry);+ guard.finishRun(retry, true);+ assert.equal(guard.beginSignIn(retry), false);+});++test("a competing manual run supersedes the previous error and stale completion", () => {+ const guard = new AnalysisRecovery();+ const original = interrupted(guard);+ const manual = guard.beginRun();+ assert.ok(manual);+ assert.equal(guard.beginRun(), null);+ assert.equal(guard.beginSignIn(original), false);+ guard.finishRun(original, true);+ assert.equal(guard.accepts(manual), true);+ guard.finishRun(manual, true);+ assert.equal(guard.beginSignIn(manual), true);+ assert.equal(guard.retry(original), null);+ assert.ok(guard.retry(manual));+});++test("canceling analysis ignores its result and cannot release its lock prematurely", () => {+ const guard = new AnalysisRecovery();+ const run = guard.beginRun();+ assert.ok(run);+ guard.cancelRun();+ assert.equal(guard.accepts(run), false);+ assert.equal(guard.isCurrent(run), true);+ assert.equal(guard.beginRun(), null);+ guard.finishRun(run, true);+ assert.equal(guard.beginSignIn(run), false);+ assert.ok(guard.beginRun());+});++test("unmount and session switch invalidate old runs and late authentication", () => {+ const guard = new AnalysisRecovery();+ const original = interrupted(guard);+ guard.beginSignIn(original);+ guard.invalidate();+ assert.equal(guard.retry(original), null);+ const current = guard.beginRun();+ assert.ok(current);+ guard.finishRun(original, true);+ guard.endSignIn(original);+ assert.equal(guard.accepts(current), true);+ guard.invalidate();+ assert.equal(guard.accepts(current), false);+ assert.equal(guard.isCurrent(current), false);+});++test("late sign-in cleanup cannot interrupt the automatic retry", () => {+ const guard = new AnalysisRecovery();+ const original = interrupted(guard);+ guard.beginSignIn(original);+ const retry = guard.retry(original);+ assert.ok(retry);+ guard.endSignIn(original);+ assert.equal(guard.accepts(retry), true);+ guard.finishRun(retry, false);+ const next = guard.beginRun();+ assert.ok(next);+ assert.equal(next.retried, false);+});++test("the continuation waits for verified authentication rather than browser launch", async () => {+ let finish!: (result: CopilotSignInResult) => void;+ const result = new Promise<CopilotSignInResult>((resolve) => { finish = resolve; });+ let calls = 0;+ const completion = completeSignIn(result, () => true, () => { calls++; });+ await Promise.resolve();+ assert.equal(calls, 0);+ finish({ ok: true, status: "authenticated" });+ assert.deepEqual(await completion, { ok: true, status: "authenticated" });+ assert.equal(calls, 1);+});++test("canceled, failed, timed-out and stale sign-ins do not call the continuation", async () => {+ let calls = 0;+ const callback = () => { calls++; };+ for (const status of ["canceled", "failed", "timed-out"] as const) {+ await completeSignIn(Promise.resolve({ ok: false, status }), () => true, callback);+ }+ let live = true;+ let finish!: (result: CopilotSignInResult) => void;+ const result = new Promise<CopilotSignInResult>((resolve) => { finish = resolve; });+ const completion = completeSignIn(result, () => live, callback);+ live = false;+ finish({ ok: true, status: "authenticated" });+ assert.equal(await completion, null);+ assert.equal(calls, 0);+});++test("IPC rejections and thrown or rejected callbacks reach the banner's error handler", async () => {+ await assert.rejects(+ completeSignIn(Promise.reject(new Error("IPC unavailable")), () => true),+ /IPC unavailable/,+ );+ for (const callback of [+ () => { throw new Error("retry failed"); },+ async () => { throw new Error("retry failed"); },+ ]) {+ await assert.rejects(+ completeSignIn(Promise.resolve({ ok: true, status: "authenticated" }), () => true, callback),+ /retry failed/,+ );+ }+});++test("panels without a continuation only report authentication", async () => {+ const result = { ok: true, status: "authenticated" } as const;+ assert.equal(await completeSignIn(Promise.resolve(result), () => true), result);+});++test("a continuation that leaves the panel suppresses its stale success UI", async () => {+ let live = true;+ const completion = completeSignIn(+ Promise.resolve({ ok: true, status: "authenticated" }),+ () => live,+ () => { live = false; },+ );+ assert.equal(await completion, null);+});diff --git a/src/analysis-recovery.ts b/src/analysis-recovery.tsnew file mode 100644index 0000000..ae0930c--- /dev/null+++ b/src/analysis-recovery.ts@@ -0,0 +1,74 @@+import type { CopilotSignInResult } from "../common/ipc";++export async function completeSignIn(+ result: Promise<CopilotSignInResult>,+ isCurrent: () => boolean,+ onAuthenticated?: () => void | Promise<void>,+): Promise<CopilotSignInResult | null> {+ const settled = await result;+ if (!isCurrent()) return null;+ if (settled.ok && settled.status === "authenticated") await onAuthenticated?.();+ return isCurrent() ? settled : null;+}++export interface AnalysisRun {+ readonly retried: boolean;+ canceled: boolean;+}++/** Synchronous identity guards: React state alone cannot exclude same-tick clicks. */+export class AnalysisRecovery {+ private current: AnalysisRun | null = null;+ private eligible: AnalysisRun | null = null;+ private signingIn: AnalysisRun | null = null;++ beginRun(): AnalysisRun | null {+ if (this.current || this.signingIn) return null;+ this.eligible = null;+ return (this.current = { retried: false, canceled: false });+ }++ isCurrent(run: AnalysisRun): boolean {+ return this.current === run;+ }++ accepts(run: AnalysisRun): boolean {+ return this.isCurrent(run) && !run.canceled;+ }++ finishRun(run: AnalysisRun, signedOut: boolean): void {+ if (!this.isCurrent(run)) return;+ this.current = null;+ this.eligible = signedOut && !run.retried && !run.canceled ? run : null;+ }++ beginSignIn(run: AnalysisRun): boolean {+ if (this.current || this.signingIn || this.eligible !== run) return false;+ this.signingIn = run;+ return true;+ }++ retry(run: AnalysisRun): AnalysisRun | null {+ if (this.current || this.signingIn !== run || this.eligible !== run) return null;+ this.signingIn = null;+ this.eligible = null;+ return (this.current = { retried: true, canceled: false });+ }++ endSignIn(run: AnalysisRun, invalidate = true): void {+ if (this.signingIn !== run) return;+ this.signingIn = null;+ if (invalidate) this.eligible = null;+ }++ cancelRun(): void {+ if (this.current) this.current.canceled = true;+ this.eligible = null;+ this.signingIn = null;+ }++ invalidate(): void {+ this.cancelRun();+ this.current = null;+ }+}