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
Add optional SKILL.md review and prepare 0.7.0
Giorgio Ughini9ddfe22ec78b
diff --git a/README.md b/README.mdindex 87ca1e8..6d18797 100644--- a/README.md+++ b/README.md@@ -40,6 +40,13 @@ form can teach the agent to submit *all* of them.4. ✨ **Create.** From an approved analysis, generate a reusable **Skill** and/or ascheduled **Automation**.+For skills, **Review SKILL.md** optionally shows the complete, read-only file text+(including frontmatter) before installation or export. Preparing a preview writes+no skill files. Close and reopen it without regenerating; Add/Export from either+surface uses that exact preview. Editing the plan discards the preview. You can+still choose Add/Export directly without reviewing or adding a confirmation step.+Review provides visibility into the generated instructions, not a security guarantee.+## Get startedSkill Recorder is published as a **source release**: one command downloads a pinned Node.jsdiff --git a/common/ipc.ts b/common/ipc.tsindex fac3499..50070a7 100644--- a/common/ipc.ts+++ b/common/ipc.ts@@ -206,9 +206,23 @@ export interface SkillPlanResult {*/export type SkillPlacement = TargetPlacement;+/** Exact rendered file held in the main process until placement or discard. */+export interface SkillPreview {+ id: string;+ markdown: string;+}++export interface SkillPreviewResult {+ ok: boolean;+ preview?: SkillPreview;+ error?: string;+}+/** Result of finalizing + placing a skill. */export interface SkillCreateResult {ok: boolean;+ /** The reviewed candidate was discarded or no longer matches the plan. */+ previewExpired?: boolean;skill?: BuiltSkill;/** Absolute path of the placed SKILL.md. */path?: string;@@ -475,6 +489,8 @@ export const IPC = {deleteSession: "sessions:delete",exportDebugBundle: "sessions:export-debug",buildSkill: "skill:build",+ prepareSkill: "skill:prepare",+ discardSkillPreview: "skill:discard-preview",createSkill: "skill:create",getSkill: "skill:get",cancelSkill: "skill:cancel",@@ -602,7 +618,14 @@ export interface SkillRecorderApi {* skills folder (Scout); `"export"` prompts for a folder and downloads it there (the* only option for Cowork). Defaults to `"install"`.*/- createSkill(sessionId: string, plan: SkillPlan, placement?: SkillPlacement): Promise<SkillCreateResult>;+ prepareSkill(sessionId: string, plan: SkillPlan): Promise<SkillPreviewResult>;+ discardSkillPreview(sessionId: string, previewId?: string): Promise<{ ok: boolean; error?: string }>;+ createSkill(+ sessionId: string,+ plan: SkillPlan,+ placement?: SkillPlacement,+ previewId?: string,+ ): Promise<SkillCreateResult>;/** Load a previously built skill for a session, if any. */getSkill(sessionId: string): Promise<BuiltSkill | null>;/** Abort an in-flight build. */diff --git a/electron/ipc.ts b/electron/ipc.tsindex 85b694f..c659c7b 100644--- a/electron/ipc.ts+++ b/electron/ipc.ts@@ -26,6 +26,7 @@ import type {SkillCreateResult,SkillPlacement,SkillPlanResult,+ SkillPreviewResult,} from "../common/ipc";import { IPC } from "../common/ipc";import type { AutomationPlan } from "../common/automation";@@ -52,7 +53,7 @@ import {import type { SensitiveModelManager } from "./sensitive/model-manager";import { buildRedactor, loadSensitiveReport, saveSensitiveReport, scanSession } from "./sensitive/scanner";import { deleteSession, listSessions } from "./sessions";-import { loadPersistedSkill, SkillBuilder, type SkillTarget } from "./skillbuilder/builder";+import { loadPersistedSkill, SkillBuilder, SkillPreviewExpiredError, type SkillTarget } from "./skillbuilder/builder";const log = createLogger("IPC");@@ -428,6 +429,29 @@ export function registerIpc(}});+ ipcMain.handle(+ IPC.prepareSkill,+ async (_event, sessionId: string, plan: SkillPlan): Promise<SkillPreviewResult> => {+ if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };+ try {+ return { ok: true, preview: await builder.prepare(sessionId, plan) };+ } catch (err) {+ const error = err instanceof Error ? err.message : String(err);+ log.warn("prepare skill failed:", error);+ return { ok: false, error };+ }+ },+ );++ ipcMain.handle(IPC.discardSkillPreview, (_event, sessionId: string, previewId?: string) => {+ if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };+ if (previewId !== undefined && typeof previewId !== "string") {+ return { ok: false, error: "Invalid skill preview." };+ }+ builder.discardPreview(sessionId, previewId);+ return { ok: true };+ });+ipcMain.handle(IPC.createSkill,async (@@ -435,11 +459,18 @@ export function registerIpc(sessionId: string,plan?: SkillPlan,placement: SkillPlacement = "install",+ previewId?: string,): Promise<SkillCreateResult> => {if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };+ if (placement !== "install" && placement !== "export") {+ return { ok: false, error: "Unknown skill placement." };+ }+ if (previewId !== undefined && typeof previewId !== "string") {+ return { ok: false, error: "Invalid skill preview." };+ }try {- let target: SkillTarget = { kind: "install" };- if (placement === "export") {+ const placed = await builder.create(sessionId, plan, async (): Promise<SkillTarget | null> => {+ if (placement === "install") return { kind: "install" };// Export == download: let the user pick a destination folder; we drop a// ready-to-use <name>/SKILL.md inside it. A dismissed dialog is a cancel, not an error.const win = BrowserWindow.fromWebContents(event.sender) ?? undefined;@@ -451,15 +482,16 @@ export function registerIpc(const result = win? await dialog.showOpenDialog(win, opts): await dialog.showOpenDialog(opts);- if (result.canceled || result.filePaths.length === 0) return { ok: false, canceled: true };- target = { kind: "export", dir: result.filePaths[0] };- }- const { skill, path: file } = await builder.create(sessionId, plan, target);+ if (result.canceled || result.filePaths.length === 0) return null;+ return { kind: "export", dir: result.filePaths[0] };+ }, previewId);+ if (!placed) return { ok: false, canceled: true };+ const { skill, path: file } = placed;return { ok: true, skill, path: file, placement };} catch (err) {const error = err instanceof Error ? err.message : String(err);log.warn("create skill failed:", error);- return { ok: false, error };+ return { ok: false, error, previewExpired: err instanceof SkillPreviewExpiredError };}},);diff --git a/electron/preload.cjs b/electron/preload.cjsindex dc4c798..b7dce6f 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -43,6 +43,8 @@ const IPC = {deleteSession: "sessions:delete",exportDebugBundle: "sessions:export-debug",buildSkill: "skill:build",+ prepareSkill: "skill:prepare",+ discardSkillPreview: "skill:discard-preview",createSkill: "skill:create",getSkill: "skill:get",cancelSkill: "skill:cancel",@@ -180,7 +182,10 @@ contextBridge.exposeInMainWorld("skillRecorder", {deleteSession: (sessionId) => ipcRenderer.invoke(IPC.deleteSession, sessionId),exportDebugBundle: (sessionId) => ipcRenderer.invoke(IPC.exportDebugBundle, sessionId),buildSkill: (input) => ipcRenderer.invoke(IPC.buildSkill, input),- createSkill: (sessionId, plan, placement) => ipcRenderer.invoke(IPC.createSkill, sessionId, plan, placement),+ prepareSkill: (sessionId, plan) => ipcRenderer.invoke(IPC.prepareSkill, sessionId, plan),+ discardSkillPreview: (sessionId, previewId) => ipcRenderer.invoke(IPC.discardSkillPreview, sessionId, previewId),+ createSkill: (sessionId, plan, placement, previewId) =>+ ipcRenderer.invoke(IPC.createSkill, sessionId, plan, placement, previewId),getSkill: (sessionId) => ipcRenderer.invoke(IPC.getSkill, sessionId),cancelSkill: (sessionId) => ipcRenderer.invoke(IPC.cancelSkill, sessionId),revealSkill: (sessionId) => ipcRenderer.invoke(IPC.revealSkill, sessionId),diff --git a/electron/skillbuilder/builder.ts b/electron/skillbuilder/builder.tsindex 116e121..744b7bb 100644--- a/electron/skillbuilder/builder.ts+++ b/electron/skillbuilder/builder.ts@@ -1,4 +1,5 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { randomUUID } from "node:crypto";import os from "node:os";import path from "node:path";@@ -17,7 +18,7 @@ import {type SkillSubmission,} from "../../common/skill";import { unresolvedTokens } from "../../common/values";-import type { SkillBuildInput, SkillBuildProgress } from "../../common/ipc";+import type { SkillBuildInput, SkillBuildProgress, SkillPreview } from "../../common/ipc";import { requireCatalogue } from "../architectures/catalogue-registry";import { AgentBuilder, type BaseLive } from "../builders/agent-builder";import { createReadTools } from "../builders/read-tools";@@ -30,6 +31,7 @@ import { createSkillBuilderTools } from "./tools";const log = createLogger("SkillBuilder");const TURN_TIMEOUT_MS = 180_000;+const MAX_PREVIEWS = 4;const KICKOFF_PROMPT ="Read get_analysis (and get_timeline where the tool mapping needs evidence), then call " +@@ -65,6 +67,23 @@ function isInside(root: string, dir: string): boolean {* - **export** — into a user-picked folder (a "download"), as `<dir>/<name>/SKILL.md`.*/export type SkillTarget = { kind: "install" } | { kind: "export"; dir: string };+type SkillTargetPicker = () => Promise<SkillTarget | null>;++interface PreparedSkill extends SkillPreview {+ skill: BuiltSkill;+ planKey: string;+}++interface BuildOperation {+ canceled: boolean;+}++export class SkillPreviewExpiredError extends Error {+ constructor() {+ super("This skill preview is no longer current. Review the skill again before placing it.");+ this.name = "SkillPreviewExpiredError";+ }+}interface LiveBuild extends BaseLive {sessionDir: string;@@ -101,6 +120,9 @@ export function loadPersistedSkill(sessionId: string): BuiltSkill | null {* callback and writes the final SKILL.md into the target agent's skills folder.*/export class SkillBuilder extends AgentBuilder<LiveBuild> {+ private readonly previews = new Map<string, PreparedSkill>();+ private readonly operations = new Map<string, BuildOperation>();+constructor(private readonly emitProgress: (p: SkillBuildProgress) => void) {super("SkillBuilder");}@@ -113,7 +135,8 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {const analysis = loadPersistedAnalysis(sessionId);if (!analysis) throw new Error("There is no analysis for this recording yet.");- this.active.add(sessionId);+ const operation = this.begin(sessionId);+ this.discardPreview(sessionId);try {const refining = Boolean(feedback && feedback.trim());this.emit(sessionId, "start", refining ? "Refining the plan…" : "Planning the skill…");@@ -123,82 +146,173 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {live = await this.createLive(sessionId, architecture);}const prompt = refining ? renderRefinePrompt(feedback!.trim(), live.lastPlan) : KICKOFF_PROMPT;- return await this.runProposeTurn(live, prompt);+ this.requireActive(operation);+ return await this.runProposeTurn(live, prompt, operation);+ } finally {+ this.finish(sessionId);+ }+ }++ /** Prepare the exact file for optional review, without writing or placing it. */+ async prepare(sessionId: string, editedPlan: SkillPlan): Promise<SkillPreview> {+ const plan = SkillPlanSchema.parse(editedPlan);+ const operation = this.begin(sessionId);+ try {+ let prepared = this.previews.get(sessionId);+ if (!prepared || prepared.planKey !== JSON.stringify(plan)) {+ this.discardPreview(sessionId);+ prepared = await this.generate(sessionId, plan, operation);+ this.requireActive(operation);+ this.previews.set(sessionId, prepared);+ while (this.previews.size > MAX_PREVIEWS) {+ const oldest = this.previews.keys().next().value;+ if (oldest === undefined) break;+ this.previews.delete(oldest);+ }+ }+ this.emit(sessionId, "done", "Skill ready for review. Nothing has been installed.");+ return { id: prepared.id, markdown: prepared.markdown };} finally {- this.active.delete(sessionId);+ this.finish(sessionId);}}- /** Finalize the user-edited plan into a SKILL.md and place it. The edited plan is- * authoritative: its name/description/values/steps are used verbatim and only the- * markdown body is written by the agent (which references each fixed value by its- * `{{id}}` token; `renderSkillMarkdown` substitutes the literals). `target` picks the- * destination — installed into the agent's live skills folder, or exported (downloaded)- * to a user-picked dir. */+ discardPreview(sessionId: string, previewId?: string): void {+ if (previewId === undefined || this.previews.get(sessionId)?.id === previewId) {+ this.previews.delete(sessionId);+ }+ }++ override async cancel(sessionId: string): Promise<void> {+ const operation = this.operations.get(sessionId);+ if (operation) operation.canceled = true;+ await super.cancel(sessionId);+ }++ override async forget(sessionId: string): Promise<void> {+ this.discardPreview(sessionId);+ await this.cancel(sessionId);+ await super.forget(sessionId);+ }++ override async dispose(): Promise<void> {+ for (const operation of this.operations.values()) operation.canceled = true;+ this.previews.clear();+ await super.dispose();+ }++ /** Place a reviewed candidate, or generate and place in one step for direct callers.+ * The picker runs under the operation guard, before any direct-path generation. */async create(sessionId: string,editedPlan?: SkillPlan,- target: SkillTarget = { kind: "install" },- ): Promise<{ skill: BuiltSkill; path: string }> {- if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");- let held = this.live.get(sessionId);- // Prefer the user's edited plan from the review tiles; fall back to the last- // proposed plan for older callers that don't pass one.- const plan = editedPlan ? SkillPlanSchema.parse(editedPlan) : held?.lastPlan ?? null;+ target: SkillTarget | SkillTargetPicker = { kind: "install" },+ previewId?: string,+ ): Promise<{ skill: BuiltSkill; path: string } | null> {+ const plan = editedPlan+ ? SkillPlanSchema.parse(editedPlan)+ : this.live.get(sessionId)?.lastPlan ?? null;if (!plan) throw new Error("There is no plan to build from yet.");- requireTargetPlacement(plan.architecture, "skill", target.kind);- // The pool may have evicted the live conversation while the user edited the plan;- // recreate one so export always works.- if (!held) held = await this.createLive(sessionId, plan.architecture);- const live = held;- live.lastPlan = plan;-- this.active.add(sessionId);+ const operation = this.begin(sessionId);try {- this.emit(sessionId, "drafting", "Writing the skill…");- live.holder.submission = undefined;- try {- await live.copilot.sendAndWait(`${CREATE_PROMPT}\n\n${renderPlanForPrompt(plan)}`, TURN_TIMEOUT_MS);- } catch (err) {- await live.copilot.abort().catch(() => undefined);- throw new Error(`Skill build failed: ${msg(err)}`);+ let prepared = previewId === undefined ? undefined : this.requirePreview(sessionId, plan, previewId);+ const destination = typeof target === "function" ? await target() : target;+ this.requireActive(operation);+ if (!destination) return null;+ requireTargetPlacement(plan.architecture, "skill", destination.kind);+ if (previewId !== undefined) {+ // The folder picker can outlive a discarded or replaced preview.+ prepared = this.requirePreview(sessionId, plan, previewId);+ } else {+ this.discardPreview(sessionId);+ prepared = await this.generate(sessionId, plan, operation);}- const submission = live.holder.submission as SkillSubmission | undefined;- if (!submission) throw new Error("The agent finished without submitting a skill.");- // Lint the authored body: the agent is given each value as `{{id}} — name` (never the- // literal), so it can only reference tokens. Any token that doesn't match a declared- // value would ship un-substituted, so surface it (the render leaves unknown tokens as-is).- const unknownTokens = unresolvedTokens(submission.body, plan.values);- if (unknownTokens.length) {- log.warn(`skill body references unknown value tokens: ${unknownTokens.map((t) => `{{${t}}}`).join(", ")}`);- }- // The frontmatter comes from the edited plan (authoritative); only the body is- // the agent's generated prose. allowed-tools may be tightened by the agent to the- // final steps, but never emptied below what the plan declared.- const finalSubmission: SkillSubmission = {- name: plan.name,- description: plan.description,- allowedTools: submission.allowedTools.length ? submission.allowedTools : plan.allowedTools,- body: submission.body,- };- const built = toBuiltSkill(sessionId, plan.architecture, finalSubmission, plan);+ this.requireActive(operation);+ if (!prepared) throw new Error("There is no prepared skill to place.");const exportPath =- target.kind === "export" ? this.exportSkillTo(built, target.dir) : this.exportSkill(built);- const finalSkill: BuiltSkill = { ...built, exportedPath: exportPath, exportedAt: Date.now() };- this.persist(live.sessionDir, finalSkill);+ destination.kind === "export"+ ? this.exportSkillTo(prepared.skill, destination.dir, prepared.markdown)+ : this.exportSkill(prepared.skill, prepared.markdown);+ const finalSkill: BuiltSkill = { ...prepared.skill, exportedPath: exportPath, exportedAt: Date.now() };+ this.persist(sessionDir(sessionId), finalSkill);+ this.discardPreview(sessionId);this.emit(sessionId,"done",- target.kind === "export" ? `Skill exported to ${exportPath}` : `Skill added: ${exportPath}`,+ destination.kind === "export" ? `Skill exported to ${exportPath}` : `Skill added: ${exportPath}`,);return { skill: finalSkill, path: exportPath };} finally {- this.active.delete(sessionId);+ this.finish(sessionId);}}// --- internals -----------------------------------------------------------+ private begin(sessionId: string): BuildOperation {+ if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");+ const operation: BuildOperation = { canceled: false };+ this.active.add(sessionId);+ this.operations.set(sessionId, operation);+ return operation;+ }++ private finish(sessionId: string): void {+ this.operations.delete(sessionId);+ this.active.delete(sessionId);+ }++ private requireActive(operation: BuildOperation): void {+ if (operation.canceled) throw new Error("Skill build canceled.");+ }++ private requirePreview(sessionId: string, plan: SkillPlan, id: string): PreparedSkill {+ const prepared = this.previews.get(sessionId);+ if (!prepared || prepared.id !== id || prepared.planKey !== JSON.stringify(plan)) {+ throw new SkillPreviewExpiredError();+ }+ return prepared;+ }++ private async generate(+ sessionId: string,+ plan: SkillPlan,+ operation: BuildOperation,+ ): Promise<PreparedSkill> {+ let live = this.live.get(sessionId);+ if (live && live.architecture !== plan.architecture) {+ await this.disposeLive(sessionId);+ live = undefined;+ }+ this.requireActive(operation);+ if (!live) live = await this.createLive(sessionId, plan.architecture);+ this.requireActive(operation);+ live.lastPlan = plan;+ this.emit(sessionId, "drafting", "Writing the skill…");+ live.holder.submission = undefined;+ try {+ await live.copilot.sendAndWait(`${CREATE_PROMPT}\n\n${renderPlanForPrompt(plan)}`, TURN_TIMEOUT_MS);+ } catch (err) {+ await live.copilot.abort().catch(() => undefined);+ throw new Error(`Skill build failed: ${msg(err)}`);+ }+ this.requireActive(operation);+ const submission = live.holder.submission as SkillSubmission | undefined;+ if (!submission) throw new Error("The agent finished without submitting a skill.");+ const unknownTokens = unresolvedTokens(submission.body, plan.values);+ if (unknownTokens.length) {+ log.warn(`skill body references unknown value tokens: ${unknownTokens.map((t) => `{{${t}}}`).join(", ")}`);+ }+ const finalSubmission: SkillSubmission = {+ name: plan.name,+ description: plan.description,+ allowedTools: submission.allowedTools.length ? submission.allowedTools : plan.allowedTools,+ body: submission.body,+ };+ const skill = toBuiltSkill(sessionId, plan.architecture, finalSubmission, plan);+ return { id: randomUUID(), skill, planKey: JSON.stringify(plan), markdown: renderSkillMarkdown(skill) };+ }+private emit(sessionId: string, phase: SkillBuildProgress["phase"], message: string): void {this.emitProgress({ sessionId, phase, message });}@@ -254,7 +368,11 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {return live;}- private async runProposeTurn(live: LiveBuild, prompt: string): Promise<SkillPlan> {+ private async runProposeTurn(+ live: LiveBuild,+ prompt: string,+ operation: BuildOperation,+ ): Promise<SkillPlan> {live.holder.plan = undefined;this.emit(live.sessionId, "working", "Thinking…");try {@@ -263,6 +381,7 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {await live.copilot.abort().catch(() => undefined);throw new Error(`Planning failed: ${msg(err)}`);}+ this.requireActive(operation);const plan = live.holder.plan;if (!plan) throw new Error("The agent finished without proposing a plan.");live.lastPlan = plan;@@ -271,7 +390,7 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {}/** Write the SKILL.md into the target agent's live skills folder; returns its path. */- private exportSkill(skill: BuiltSkill): string {+ private exportSkill(skill: BuiltSkill, markdown: string): string {const root = skillsRoot();const name = slugifySkillName(skill.name);const prior = loadPersistedSkill(skill.sessionId);@@ -288,13 +407,13 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {}mkdirSync(dir, { recursive: true });const file = path.join(dir, "SKILL.md");- writeFileSync(file, renderSkillMarkdown(skill));+ writeFileSync(file, markdown);return file;}/** Export (download) the SKILL.md into a user-picked folder as `<baseDir>/<name>/SKILL.md`;* returns its path. Always picks a fresh, non-colliding subfolder within `baseDir`. */- private exportSkillTo(skill: BuiltSkill, baseDir: string): string {+ private exportSkillTo(skill: BuiltSkill, baseDir: string, markdown: string): string {const name = slugifySkillName(skill.name);let dir = path.join(baseDir, name);if (existsSync(dir)) {@@ -304,7 +423,7 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {}mkdirSync(dir, { recursive: true });const file = path.join(dir, "SKILL.md");- writeFileSync(file, renderSkillMarkdown(skill));+ writeFileSync(file, markdown);return file;}diff --git a/electron/skillbuilder/preview.test.ts b/electron/skillbuilder/preview.test.tsnew file mode 100644index 0000000..88e0c83--- /dev/null+++ b/electron/skillbuilder/preview.test.ts@@ -0,0 +1,328 @@+import assert from "node:assert/strict";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import test, { type TestContext } from "node:test";++import { CopilotClient, CopilotSession, type SessionConfig } from "@github/copilot-sdk";++import { AnalysisSchema } from "../../common/analysis";+import type { SkillBuildProgress } from "../../common/ipc";+import { renderSkillMarkdown, SkillPlanSchema, type SkillPlan } from "../../common/skill";+import { loadPersistedSkill, SkillBuilder } from "./builder";++const sessionId = "preview-test";+const plan = SkillPlanSchema.parse({+ architecture: "scout",+ name: "reviewed-skill",+ title: "Reviewed skill",+ description: "A skill to review.",+ allowedTools: ["Bash(gh *)"],+ values: [{ id: "repo", name: "Repository", value: "example/repository" }],+ steps: [{ kind: "calculation", title: "List issues", text: "List issues for {{repo}}.", tools: ["bash"] }],+});++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => { resolve = done; });+ return { promise, resolve };+}++function fixture(+ t: TestContext,+ options: { beforeTurn?: () => Promise<void>; beforeSession?: () => Promise<void> } = {},+) {+ const root = mkdtempSync(path.join(os.tmpdir(), "skill-preview-"));+ const sessions = path.join(root, "sessions");+ const skills = path.join(root, "skills");+ const priorSessions = process.env.SKILL_RECORDER_SESSIONS_DIR;+ const priorSkills = process.env.SKILL_RECORDER_SKILLS_DIR;+ process.env.SKILL_RECORDER_SESSIONS_DIR = sessions;+ process.env.SKILL_RECORDER_SKILLS_DIR = skills;+ const progress: SkillBuildProgress[] = [];+ const counts = { turns: 0, sessions: 0, aborts: 0 };+ const client = new CopilotClient();+ t.mock.method(client, "createSession", async (config: SessionConfig) => {+ counts.sessions++;+ await options.beforeSession?.();+ const session = new CopilotSession();+ t.mock.method(session, "abort", async () => { counts.aborts++; });+ t.mock.method(session, "disconnect", async () => undefined);+ t.mock.method(session, "sendAndWait", async (input: string | { prompt: string }) => {+ counts.turns++;+ await options.beforeTurn?.();+ const prompt = typeof input === "string" ? input : input.prompt;+ const toolName = prompt.includes("Call submit_skill") ? "submit_skill" : "propose_plan";+ const tool = config.tools?.find((candidate) => candidate.name === toolName);+ assert.ok(tool);+ assert.ok(tool.handler);+ const payload = toolName === "submit_skill"+ ? { name: "model-name", description: "Model description", allowedTools: ["Bash(gh issue *)"], body: "# Instructions\n\nList issues for {{repo}}.\n\n<script>text only</script>" }+ : plan;+ await tool.handler(payload, { sessionId, toolCallId: "test", toolName, arguments: payload });+ return undefined;+ });+ return session;+ });+ class TestBuilder extends SkillBuilder {+ protected override async ensureClient(): Promise<CopilotClient> {+ return client;+ }+ }+ const builder = new TestBuilder((event) => progress.push(event));+ function seed(id: string) {+ const dir = path.join(sessions, id);+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, "analysis.json"), JSON.stringify(AnalysisSchema.parse({+ version: 1, sessionId: id, revision: 1, createdAt: 1,+ intent: "List issues", intentConfidence: "high", intentRationale: "Used gh", steps: [],+ })));+ }+ seed(sessionId);+ t.after(async () => {+ await builder.dispose();+ if (priorSessions === undefined) delete process.env.SKILL_RECORDER_SESSIONS_DIR;+ else process.env.SKILL_RECORDER_SESSIONS_DIR = priorSessions;+ if (priorSkills === undefined) delete process.env.SKILL_RECORDER_SKILLS_DIR;+ else process.env.SKILL_RECORDER_SKILLS_DIR = priorSkills;+ rmSync(root, { recursive: true, force: true });+ });+ return { builder, root, sessions, skills, counts, progress, seed };+}++test("preview renders the entire final file without installing or marking the session complete", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ assert.match(preview.markdown, /^---\nname: reviewed-skill\n/);+ assert.match(preview.markdown, /allowed-tools:\n - Bash\(gh issue \*\)/);+ assert.match(preview.markdown, /List issues for example\/repository/);+ assert.match(preview.markdown, /<script>text only<\/script>/);+ assert.equal(preview.markdown.includes("{{repo}}"), false);+ assert.equal(existsSync(f.skills), false);+ assert.equal(loadPersistedSkill(sessionId), null);+ assert.match(f.progress.at(-1)?.message ?? "", /Nothing has been installed/);+ assert.deepEqual(await f.builder.prepare(sessionId, plan), preview);+ assert.equal(f.counts.turns, 1);+});++test("reviewed install writes identical bytes once, even after model-session eviction", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ await f.builder.evictIdle();+ const result = await f.builder.create(sessionId, plan, { kind: "install" }, preview.id);+ assert.ok(result);+ assert.equal(readFileSync(result.path, "utf8"), preview.markdown);+ assert.equal(renderSkillMarkdown(result.skill), preview.markdown);+ assert.equal(loadPersistedSkill(sessionId)?.exportedPath, result.path);+ assert.equal(f.counts.turns, 1);+ assert.equal(f.counts.sessions, 1);+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, preview.id), /no longer current/);+});++test("direct placement still generates and installs with no preview step", async (t) => {+ const f = fixture(t);+ const result = await f.builder.create(sessionId, plan);+ assert.ok(result);+ assert.equal(f.counts.turns, 1);+ assert.equal(readFileSync(result.path, "utf8"), renderSkillMarkdown(result.skill));+});++test("direct export picker cancellation does not generate or write anything", async (t) => {+ const f = fixture(t);+ assert.equal(await f.builder.create(sessionId, plan, async () => null), null);+ assert.equal(f.counts.turns, 0);+ assert.equal(f.counts.sessions, 0);+ assert.equal(existsSync(f.skills), false);+ assert.equal(loadPersistedSkill(sessionId), null);+});++test("export-only skills can be reviewed and exported without allowing installation", async (t) => {+ const f = fixture(t);+ const exportPlan: SkillPlan = { ...plan, architecture: "cowork" };+ const preview = await f.builder.prepare(sessionId, exportPlan);+ await assert.rejects(f.builder.create(sessionId, exportPlan, { kind: "install" }, preview.id), /does not support/);+ assert.equal(await f.builder.create(sessionId, exportPlan, async () => null, preview.id), null);+ const result = await f.builder.create(sessionId, exportPlan, { kind: "export", dir: path.join(f.root, "export") }, preview.id);+ assert.ok(result);+ assert.equal(readFileSync(result.path, "utf8"), preview.markdown);+ assert.equal(f.counts.turns, 1);+ assert.equal(existsSync(f.skills), false);+});++test("every edited plan field invalidates reviewed placement without silently regenerating", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ const changes: Partial<SkillPlan>[] = [+ { name: "changed" }, { title: "Changed" }, { description: "Changed" },+ { summary: "Changed" }, { generalization: "Changed" }, { architecture: "cowork" },+ { allowedTools: ["Read"] }, { values: [{ id: "repo", name: "Repository", value: "changed/repo" }] },+ { steps: [] },+ ];+ for (const change of changes) {+ await assert.rejects(+ f.builder.create(sessionId, { ...plan, ...change }, { kind: "export", dir: f.root }, preview.id),+ /no longer current/,+ );+ }+ assert.equal(f.counts.turns, 1);+ assert.equal(existsSync(f.skills), false);+});++test("changed plans produce a new candidate and old discard requests cannot clear it", async (t) => {+ const f = fixture(t);+ const old = await f.builder.prepare(sessionId, plan);+ const changed = { ...plan, description: "Updated description" };+ const next = await f.builder.prepare(sessionId, changed);+ assert.notEqual(next.id, old.id);+ f.builder.discardPreview(sessionId, old.id);+ assert.deepEqual(await f.builder.prepare(sessionId, changed), next);+ assert.equal(f.counts.turns, 2);+ await assert.rejects(f.builder.create(sessionId, changed, { kind: "install" }, old.id), /no longer current/);+ assert.ok(await f.builder.create(sessionId, changed, { kind: "install" }, next.id));+});++test("candidate IDs cannot cross sessions, and explicit discard prevents later placement", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ f.seed("another-session");+ await assert.rejects(f.builder.create("another-session", plan, { kind: "install" }, preview.id), /no longer current/);+ f.builder.discardPreview(sessionId, preview.id);+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, preview.id), /no longer current/);+ assert.equal(f.counts.turns, 1);+});++test("write failure keeps the reviewed candidate available for retry", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ const blocked = path.join(f.root, "not-a-directory");+ writeFileSync(blocked, "file");+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "export", dir: blocked }, preview.id));+ assert.deepEqual(await f.builder.prepare(sessionId, plan), preview);+ const result = await f.builder.create(sessionId, plan, { kind: "install" }, preview.id);+ assert.ok(result);+ assert.equal(readFileSync(result.path, "utf8"), preview.markdown);+ assert.equal(f.counts.turns, 1);+});++test("cancel during generation rejects late model output and permits a clean retry", async (t) => {+ const entered = deferred();+ const release = deferred();+ const f = fixture(t, { beforeTurn: async () => { entered.resolve(); await release.promise; } });+ const work = f.builder.prepare(sessionId, plan);+ const rejected = assert.rejects(work, /canceled/);+ await entered.promise;+ await assert.rejects(f.builder.prepare(sessionId, plan), /Wait for the current step/);+ await assert.rejects(f.builder.create(sessionId, plan), /Wait for the current step/);+ await f.builder.cancel(sessionId);+ release.resolve();+ await rejected;+ assert.equal(existsSync(f.skills), false);+ assert.equal(loadPersistedSkill(sessionId), null);+ await f.builder.prepare(sessionId, plan);+ assert.equal(f.counts.turns, 2);+});++test("cancel while connecting prevents any subsequent model turn", async (t) => {+ const entered = deferred();+ const release = deferred();+ const f = fixture(t, { beforeSession: async () => { entered.resolve(); await release.promise; } });+ const work = f.builder.prepare(sessionId, plan);+ const rejected = assert.rejects(work, /canceled/);+ await entered.promise;+ await f.builder.cancel(sessionId);+ release.resolve();+ await rejected;+ assert.equal(f.counts.turns, 0);+ assert.equal(existsSync(f.skills), false);+});++test("canceling direct creation never places late model output", async (t) => {+ const entered = deferred();+ const release = deferred();+ const f = fixture(t, { beforeTurn: async () => { entered.resolve(); await release.promise; } });+ const work = f.builder.create(sessionId, plan);+ const rejected = assert.rejects(work, /canceled/);+ await entered.promise;+ await f.builder.cancel(sessionId);+ release.resolve();+ await rejected;+ assert.equal(existsSync(f.skills), false);+ assert.equal(loadPersistedSkill(sessionId), null);+});++test("generation errors remain explicit and release the operation for retry", async (t) => {+ let fail = true;+ const f = fixture(t, { beforeTurn: async () => {+ if (fail) throw new Error("Model transport unavailable");+ } });+ await assert.rejects(f.builder.prepare(sessionId, plan), /Skill build failed: Model transport unavailable/);+ assert.equal(existsSync(f.skills), false);+ assert.equal(loadPersistedSkill(sessionId), null);+ assert.equal(f.counts.aborts, 1);+ fail = false;+ assert.ok(await f.builder.prepare(sessionId, plan));+ assert.equal(f.counts.turns, 2);+});++test("cancel or discard while the folder picker is open cannot install a reviewed candidate", async (t) => {+ const f = fixture(t);+ const preview = await f.builder.prepare(sessionId, plan);+ const entered = deferred();+ const release = deferred();+ const work = f.builder.create(sessionId, plan, async () => {+ entered.resolve();+ await release.promise;+ return { kind: "install" };+ }, preview.id);+ const rejected = assert.rejects(work, /canceled/);+ await entered.promise;+ await f.builder.cancel(sessionId);+ release.resolve();+ await rejected;+ assert.equal(existsSync(f.skills), false);+ await assert.rejects(f.builder.create(sessionId, plan, async () => {+ f.builder.discardPreview(sessionId);+ return { kind: "install" };+ }, preview.id), /no longer current/);+});++test("fresh planning, forgetting a recording, and shutdown discard candidates", async (t) => {+ const f = fixture(t);+ let preview = await f.builder.prepare(sessionId, plan);+ await f.builder.build({ sessionId, architecture: plan.architecture });+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, preview.id), /no longer current/);+ preview = await f.builder.prepare(sessionId, plan);+ await f.builder.forget(sessionId);+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, preview.id), /no longer current/);+ preview = await f.builder.prepare(sessionId, plan);+ await f.builder.dispose();+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, preview.id), /no longer current/);+});++test("preview cache is bounded and expired candidates fail rather than regenerate", async (t) => {+ const f = fixture(t);+ const first = await f.builder.prepare(sessionId, plan);+ for (let n = 0; n < 4; n++) {+ const id = `another-${n}`;+ f.seed(id);+ await f.builder.prepare(id, plan);+ }+ await assert.rejects(f.builder.create(sessionId, plan, { kind: "install" }, first.id), /no longer current/);+ assert.equal(f.counts.turns, 5);+});++test("reviewed placement preserves collision handling and reinstall behavior", async (t) => {+ const f = fixture(t);+ const unrelated = path.join(f.skills, plan.name);+ mkdirSync(unrelated, { recursive: true });+ writeFileSync(path.join(unrelated, "SKILL.md"), "Unrelated skill");+ const preview = await f.builder.prepare(sessionId, plan);+ const first = await f.builder.create(sessionId, plan, { kind: "install" }, preview.id);+ assert.ok(first);+ assert.equal(path.basename(path.dirname(first.path)), `${plan.name}-2`);+ const next = await f.builder.prepare(sessionId, plan);+ const second = await f.builder.create(sessionId, plan, { kind: "install" }, next.id);+ assert.ok(second);+ assert.equal(second.path, first.path);+ assert.equal(readFileSync(path.join(unrelated, "SKILL.md"), "utf8"), "Unrelated skill");+});diff --git a/package-lock.json b/package-lock.jsonindex 947424d..077241c 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "skill-recorder",- "version": "0.6.1",+ "version": "0.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "skill-recorder",- "version": "0.6.1",+ "version": "0.7.0","license": "MIT","dependencies": {"@github/copilot": "1.0.78",diff --git a/package.json b/package.jsonindex f45d7a4..dd1ac9a 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "skill-recorder",- "version": "0.6.1",+ "version": "0.7.0","description": "Records a user's on-screen work session and derives a structured description for building AI-agent skills.","author": "Skill Recorder contributors","repository": "github:microsoft/skill-recorder",@@ -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/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 scripts/install-windows-dependencies.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 electron/skillbuilder/preview.test.ts src/skill-placement.test.ts src/skill-review-state.test.ts scripts/compliance.test.mjs scripts/install-windows-dependencies.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/App.css b/src/App.cssindex 0225851..53ebd5d 100644--- a/src/App.css+++ b/src/App.css@@ -2764,6 +2764,46 @@ button:focus-visible,Reuses ws / ws-head / ws-foot / status-line / record-cta. The two signaturemoments are the input-source badges and the action → native-tool rows, sothose carry the only colour; everything else stays quiet sand + neutral. */+.skill-builder .ws-foot-actions {+ flex-wrap: wrap;+ justify-content: flex-end;+}++.skill-review-sheet {+ max-width: 920px;+}++.skill-review-sheet .sheet-head {+ justify-content: space-between;+}++.skill-review-source {+ min-height: 120px;+ max-height: 55vh;+ margin: 0;+ padding: 14px;+ overflow: auto;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ user-select: text;+ font-family: var(--mono);+ font-size: 12px;+ line-height: 1.6;+ color: var(--text);+ background: var(--deck);+ border: 1px solid var(--line);+ border-radius: 9px;+}++.skill-review-source code {+ user-select: text;+}++.skill-review-actions {+ flex-wrap: wrap;+ flex-shrink: 0;+}+.sb-arch {display: flex;flex-direction: column;diff --git a/src/Library.tsx b/src/Library.tsxindex 9dd4e00..11693f1 100644--- a/src/Library.tsx+++ b/src/Library.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";import type { Analysis, AnalysisStep } from "../common/analysis";import type {@@ -10,6 +10,7 @@ import type {SessionSummary,SkillBuildProgress,SkillPlacement,+ SkillPreview,} from "../common/ipc";import { isCopilotSignedOutError } from "../common/ipc";import type {@@ -39,6 +40,8 @@ import {} from "./plan-edit";import { formatBytes, formatDur, formatWhen, shortLabel } from "./format";import { skillPlacementModel, skillTargetFor } from "./skill-placement";+import { SkillReviewModal } from "./SkillReviewModal";+import { initialSkillReviewState, SkillOperationGuard, skillReviewBusy, skillReviewReducer } from "./skill-review-state";import { SensitiveReview } from "./SensitiveReview";import { AnalysisRecovery, completeSignIn, type AnalysisRun } from "./analysis-recovery";@@ -1148,35 +1151,78 @@ function SkillBuilderView({);// If this recording is already a skill, hold on a spinner until we've loaded it,// so we never flash the planning state before jumping to the skill.- const [phase, setPhase] = useState<BuildPhase>(hasSkill ? "loading" : "ready");+ const [{ phase, preview, reviewOpen, statusLine, error }, dispatch] = useReducer(+ skillReviewReducer, hasSkill, initialSkillReviewState,+ );const [architecture, setArchitecture] = useState<SkillArchitecture>(initialArch);const [plan, setPlan] = useState<SkillPlan | null>(null);- const [statusLine, setStatusLine] = useState("");- const [error, setError] = useState<string | null>(null);const [exportedPath, setExportedPath] = useState("");const [builtName, setBuiltName] = useState("");- const canceled = useRef(false);- const inFlight = useRef(false);+ const operations = useRef(new SkillOperationGuard());+ const flowVersion = useRef(0);+ const stopping = useRef(false);+ const mounted = useRef(false);+ const previewRef = useRef<SkillPreview | null>(null);+ const workspaceRef = useRef<HTMLElement>(null);+ const reviewButtonRef = useRef<HTMLButtonElement>(null);+ const doneRef = useRef<HTMLDivElement>(null);const [placement, setPlacement] = useState<SkillPlacement>(() => defaultPlacementFor(initialArch));const placementModel = useMemo(() => skillPlacementModel(skillTargetFor(architecture)), [architecture]);+ const discardPreview = useCallback(async (id: string, reportError = false) => {+ const version = flowVersion.current;+ try {+ const result = await window.skillRecorder.discardSkillPreview(sessionId, id);+ if (!result.ok) throw new Error(result.error ?? "Could not discard the preview");+ } catch (cause) {+ const message = cause instanceof Error ? cause.message : String(cause);+ if (reportError && mounted.current && flowVersion.current === version) {+ dispatch({ type: "error", error: message });+ }+ else console.warn("Could not discard skill preview", cause);+ }+ }, [sessionId]);++ const invalidatePreview = useCallback(() => {+ flowVersion.current++;+ const previous = previewRef.current;+ previewRef.current = null;+ dispatch({ type: "invalidate" });+ if (previous) void discardPreview(previous.id, true);+ }, [discardPreview]);+const updatePlan = useCallback((part: Partial<SkillPlan>) => {+ invalidatePreview();setPlan((prev) => (prev ? { ...prev, ...part } : prev));- }, []);+ }, [invalidatePreview]);// Leaving the builder (session switch or Close) discards an in-progress plan —// we don't save drafts — so stop any run that's still going in the background.useEffect(() => {+ mounted.current = true;+ const guard = operations.current;return () => {- if (inFlight.current) void window.skillRecorder.cancelSkill(sessionId);+ mounted.current = false;+ flowVersion.current++;+ if (guard.invalidate()) {+ void window.skillRecorder.cancelSkill(sessionId).then((result) => {+ if (!result.ok) throw new Error("Could not cancel skill work");+ }).catch((cause: unknown) => {+ console.warn("Could not cancel skill work on departure", cause);+ });+ }+ const previous = previewRef.current;+ previewRef.current = null;+ if (previous) void discardPreview(previous.id);};- }, [sessionId]);+ }, [sessionId, discardPreview]);// Reopen straight to the exported state if this recording already has a skill.useEffect(() => {let live = true;+ const version = flowVersion.current;void window.skillRecorder.getSkill(sessionId).then((s: BuiltSkill | null) => {- if (!live) return;+ if (!live || flowVersion.current !== version) return;if (s?.exportedPath) {setBuiltName(s.name);setExportedPath(s.exportedPath);@@ -1185,11 +1231,16 @@ function SkillBuilderView({// current default placement from the manifest.setPlacement(defaultPlacementFor(s.architecture));if (s.plan) setPlan(s.plan);- setPhase("done");+ dispatch({ type: "done" });} else if (hasSkill) {// We expected a skill but couldn't load it; fall back to the ready screen.- setPhase("ready");+ dispatch({ type: "settle", phase: "ready" });}+ }).catch((cause: unknown) => {+ if (live && flowVersion.current === version) dispatch({+ type: "settle", phase: "ready",+ error: cause instanceof Error ? cause.message : "Could not open the skill",+ });});return () => {live = false;@@ -1198,65 +1249,143 @@ function SkillBuilderView({useEffect(() => {return window.skillRecorder.onSkillProgress((p: SkillBuildProgress) => {- if (p.sessionId === sessionId) setStatusLine(p.message);+ if (p.sessionId === sessionId && mounted.current && operations.current.busy && !stopping.current) {+ dispatch({ type: "progress", message: p.message });+ }});}, [sessionId]);const runPlan = useCallback(async () => {- canceled.current = false;- inFlight.current = true;- setError(null);- setStatusLine("Planning the skill…");- setPhase("planning");- const res = await window.skillRecorder.buildSkill({ sessionId, architecture });- inFlight.current = false;- if (res.ok && res.plan) {- setPlan(res.plan);- setPhase("plan");- } else if (!canceled.current) {- setError(res.error ?? "Planning failed");- setPhase("ready");+ const operation = operations.current.begin();+ if (!operation) return;+ invalidatePreview();+ flowVersion.current++;+ dispatch({ type: "start", phase: "planning", message: "Planning the skill…" });+ try {+ const res = await window.skillRecorder.buildSkill({ sessionId, architecture });+ if (!mounted.current || !operations.current.isCurrent(operation)) return;+ if (res.ok && res.plan) {+ setPlan(res.plan);+ dispatch({ type: "settle", phase: "plan" });+ } else {+ dispatch({ type: "settle", phase: "ready", error: res.error ?? "Planning failed" });+ }+ } catch (cause) {+ if (mounted.current && operations.current.isCurrent(operation)) {+ dispatch({ type: "settle", phase: "ready", error: cause instanceof Error ? cause.message : "Planning failed" });+ }+ } finally {+ operations.current.finish(operation);}- }, [sessionId, architecture]);+ }, [sessionId, architecture, invalidatePreview]);++ const review = useCallback(async () => {+ if (!plan) return;+ dispatch({ type: "visibility", open: true });+ if (previewRef.current) return;+ const operation = operations.current.begin();+ if (!operation) return;+ flowVersion.current++;+ dispatch({ type: "start", phase: "preparing", message: "Preparing SKILL.md preview…" });+ try {+ const res = await window.skillRecorder.prepareSkill(sessionId, plan);+ if (!mounted.current || !operations.current.isCurrent(operation)) {+ if (res.preview) void discardPreview(res.preview.id);+ return;+ }+ if (res.ok && res.preview) {+ previewRef.current = res.preview;+ dispatch({ type: "preview", preview: res.preview });+ } else {+ dispatch({ type: "settle", phase: "plan", error: res.error ?? "Could not prepare the preview" });+ }+ } catch (cause) {+ if (mounted.current && operations.current.isCurrent(operation)) {+ dispatch({ type: "settle", phase: "plan", error: cause instanceof Error ? cause.message : "Could not prepare the preview" });+ }+ } finally {+ operations.current.finish(operation);+ }+ }, [sessionId, plan, discardPreview]);const place = useCallback(async (which: SkillPlacement) => {if (!plan) return;- canceled.current = false;- inFlight.current = true;- setError(null);- setStatusLine(which === "export" ? "Exporting the skill…" : "Writing the skill…");- setPhase("creating");- const res = await window.skillRecorder.createSkill(sessionId, plan, which);- inFlight.current = false;- if (res.ok && res.skill) {- setBuiltName(res.skill.name);- setExportedPath(res.path ?? res.skill.exportedPath ?? "");- setPlacement(res.placement ?? which);- setPhase("done");- } else if (res.canceled) {- // User dismissed the export folder picker — quietly return to the plan.- setPhase("plan");- } else if (!canceled.current) {- setError(res.error ?? "Could not create the skill");- setPhase("plan");+ const operation = operations.current.begin();+ if (!operation) return;+ flowVersion.current++;+ dispatch({ type: "start", phase: "creating", message: which === "export" ? "Exporting the skill…" : "Writing the skill…" });+ try {+ const res = await window.skillRecorder.createSkill(sessionId, plan, which, previewRef.current?.id);+ if (!mounted.current) return;+ if (res.ok && res.skill) {+ if (!operations.current.commit(operation)) return;+ setBuiltName(res.skill.name);+ setExportedPath(res.path ?? res.skill.exportedPath ?? "");+ setPlacement(res.placement ?? which);+ previewRef.current = null;+ dispatch({ type: "done" });+ } else {+ if (!operations.current.isCurrent(operation)) return;+ // Folder-picker cancellation and placement failures both retain the candidate.+ // An expired candidate must be reviewed again explicitly, never silently regenerated.+ if (res.previewExpired) previewRef.current = null;+ dispatch({+ type: "settle",+ phase: "plan",+ previewExpired: res.previewExpired,+ error: res.canceled ? undefined : res.error ?? "Could not create the skill",+ });+ }+ } catch (cause) {+ if (mounted.current && operations.current.isCurrent(operation)) {+ dispatch({ type: "settle", phase: "plan", error: cause instanceof Error ? cause.message : "Could not create the skill" });+ }+ } finally {+ operations.current.finish(operation);}},[sessionId, plan],);const cancelRun = useCallback(async () => {- canceled.current = true;- inFlight.current = false;- setStatusLine("Stopping…");- await window.skillRecorder.cancelSkill(sessionId);- setPhase(plan ? "plan" : "ready");+ if (stopping.current || !operations.current.busy) return;+ const cancellation = operations.current.beginCancellation();+ if (!cancellation) return;+ stopping.current = true;+ flowVersion.current++;+ const { operation, originalSettled } = cancellation;+ dispatch({ type: "start", phase: "stopping", message: "Stopping…" });+ let error: string | undefined;+ try {+ const res = await window.skillRecorder.cancelSkill(sessionId);+ if (!res.ok) throw new Error("Could not cancel skill work");+ } catch (cause) {+ error = cause instanceof Error ? cause.message : "Could not cancel skill work";+ }+ // Acknowledging cancellation only marks the backend operation. Its original+ // request may still own a model turn or an open native folder picker.+ try {+ await originalSettled;+ if (mounted.current && operations.current.isCurrent(operation)) {+ dispatch({ type: "settle", phase: plan ? "plan" : "ready", error });+ }+ } finally {+ operations.current.finish(operation);+ stopping.current = false;+ }}, [sessionId, plan]);- const busy = phase === "planning" || phase === "creating";+ const restoreReviewFocus = useCallback(() => {+ if (mounted.current) (doneRef.current ?? reviewButtonRef.current ?? workspaceRef.current)?.focus();+ }, []);+ useEffect(() => {+ if (phase === "done") doneRef.current?.focus();+ }, [phase]);+ const busy = skillReviewBusy(phase);return (- <section className="ws">+ <section className="ws skill-builder" ref={workspaceRef} tabIndex={-1}><div className="ws-head"><div className="ws-titles"><span className="eyebrow">{phase === "done" ? "Skill" : "Create skill"}</span>@@ -1292,12 +1421,17 @@ function SkillBuilderView({)}{busy && (- <div className="status-line">+ <div className="status-line" role="status"><span className="spinner" /><span className="status-text">{statusLine || "Working…"}</span>- <button className="linky status-cancel" onClick={cancelRun}>+ <button className="linky status-cancel" onClick={cancelRun} disabled={phase === "stopping"}>Cancel</button>+ {(phase === "preparing" || preview) && (+ <button className="ghost" ref={reviewButtonRef} onClick={() => dispatch({ type: "visibility", open: true })}>+ Review SKILL.md+ </button>+ )}</div>)}@@ -1340,7 +1474,7 @@ function SkillBuilderView({)}{phase === "done" && (- <div className="sb-done">+ <div className="sb-done" ref={doneRef} tabIndex={-1}><div className="sb-check" aria-hidden>✓</div>@@ -1362,6 +1496,9 @@ function SkillBuilderView({<div className="ws-foot"><span className="foot-status" /><div className="ws-foot-actions">+ <button className="ghost" ref={reviewButtonRef} onClick={() => void review()}>+ Review SKILL.md+ </button>{placementModel.actions.map((action) => (<buttonkey={action.placement}@@ -1388,6 +1525,21 @@ function SkillBuilderView({</div></div>)}+ {reviewOpen && (+ <SkillReviewModal+ preview={preview}+ busy={busy}+ stopping={phase === "stopping"}+ statusLine={statusLine}+ error={error}+ placementModel={placementModel}+ onPlace={(which) => void place(which)}+ onPrepare={() => void review()}+ onCancel={() => void cancelRun()}+ onClose={() => dispatch({ type: "visibility", open: false })}+ restoreFocus={restoreReviewFocus}+ />+ )}</section>);}diff --git a/src/SkillReviewModal.tsx b/src/SkillReviewModal.tsxnew file mode 100644index 0000000..da8759b--- /dev/null+++ b/src/SkillReviewModal.tsx@@ -0,0 +1,140 @@+import { useEffect, useId, useRef } from "react";+import { createPortal } from "react-dom";++import type { SkillPlacement, SkillPreview } from "../common/ipc";+import type { SkillPlacementModel } from "./skill-placement";++export function SkillReviewModal({+ preview,+ busy,+ stopping,+ statusLine,+ error,+ placementModel,+ onPlace,+ onPrepare,+ onCancel,+ onClose,+ restoreFocus,+}: {+ preview: SkillPreview | null;+ busy: boolean;+ stopping: boolean;+ statusLine: string;+ error: string | null;+ placementModel: SkillPlacementModel;+ onPlace: (placement: SkillPlacement) => void;+ onPrepare: () => void;+ onCancel: () => void;+ onClose: () => void;+ restoreFocus: () => void;+}) {+ const dialog = useRef<HTMLDivElement>(null);+ const titleId = useId();+ const descriptionId = useId();+ const closeRef = useRef(onClose);+ closeRef.current = onClose;++ useEffect(() => {+ const node = dialog.current!;+ const backdrop = node.parentElement!;+ const background = [...document.body.children]+ .filter((element): element is HTMLElement => element instanceof HTMLElement && element !== backdrop)+ .map((element) => ({ element, inert: element.inert }));+ for (const { element } of background) element.inert = true;+ const previousOverflow = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ node.focus();++ const keepFocus = (event: FocusEvent) => {+ if (!node.contains(event.target as Node)) node.focus();+ };+ const keydown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ closeRef.current();+ } else if (event.key === "Tab") {+ const focusable = [...node.querySelectorAll<HTMLElement>(+ 'button:not(:disabled), [href], input:not(:disabled), textarea:not(:disabled), [tabindex="0"]',+ )].filter((element) => element.getClientRects().length > 0);+ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ if (!first) {+ event.preventDefault();+ node.focus();+ } else if (event.shiftKey && (document.activeElement === first || document.activeElement === node)) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && (document.activeElement === last || document.activeElement === node)) {+ event.preventDefault();+ first.focus();+ }+ }+ };+ document.addEventListener("keydown", keydown, true);+ document.addEventListener("focusin", keepFocus);+ return () => {+ document.removeEventListener("keydown", keydown, true);+ document.removeEventListener("focusin", keepFocus);+ for (const { element, inert } of background) element.inert = inert;+ document.body.style.overflow = previousOverflow;+ queueMicrotask(restoreFocus);+ };+ }, [restoreFocus]);++ return createPortal(+ <div className="sheet-backdrop" onClick={(event) => {+ if (event.target === event.currentTarget) onClose();+ }}>+ <div+ ref={dialog}+ className="sheet skill-review-sheet"+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ aria-describedby={descriptionId}+ tabIndex={-1}+ >+ <div className="sheet-head">+ <h2 id={titleId}>Review SKILL.md</h2>+ <button className="ghost" onClick={onClose}>Close</button>+ </div>+ <p className="sheet-lead" id={descriptionId}>+ Read-only file preview, including frontmatter. Nothing is installed or exported until you choose an action below.+ Closing this window keeps the preview; editing the plan discards it.+ </p>+ {error && <p className="sheet-caution" role="alert">{error}</p>}+ {busy && (+ <div className="status-line" role="status">+ <span className="spinner" aria-hidden="true" />+ <span className="status-text">{statusLine || "Working…"}</span>+ <button className="linky status-cancel" onClick={onCancel} disabled={stopping}>Cancel</button>+ </div>+ )}+ {preview && (+ <pre className="skill-review-source" tabIndex={0} aria-label="SKILL.md source">+ <code>{preview.markdown}</code>+ </pre>+ )}+ {!preview && !busy && (+ <button className="ghost" onClick={onPrepare}>Prepare preview</button>+ )}+ <div className="sheet-actions skill-review-actions">+ {placementModel.actions.map((action) => (+ <button+ key={action.placement}+ className={action.primary ? "record-cta" : "ghost"}+ disabled={busy || !preview}+ onClick={() => onPlace(action.placement)}+ title={action.title}+ >+ {action.label}+ </button>+ ))}+ </div>+ </div>+ </div>,+ document.body,+ );+}diff --git a/src/skill-review-state.test.ts b/src/skill-review-state.test.tsnew file mode 100644index 0000000..aba1c0b--- /dev/null+++ b/src/skill-review-state.test.ts@@ -0,0 +1,202 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ initialSkillReviewState,+ SkillOperationGuard,+ skillReviewBusy,+ skillReviewReducer as reduce,+} from "./skill-review-state";++const preview = { id: "candidate-1", markdown: "---\nname: example\n---\n<script>not rendered</script>\n" };+const reviewed = () => reduce(+ reduce(initialSkillReviewState(false), { type: "visibility", open: true }),+ { type: "preview", preview },+);++test("direct placement skips review and finishes on the shared done surface", () => {+ const creating = reduce(initialSkillReviewState(false), { type: "start", phase: "creating", message: "Writing…" });+ assert.equal(creating.reviewOpen, false);+ assert.equal(creating.preview, null);+ const done = reduce(creating, { type: "done" });+ assert.equal(done.phase, "done");+ assert.equal(done.reviewOpen, false);+ assert.equal(skillReviewBusy(done.phase), false);+});++test("close and reopen retain the exact candidate and do not change operation status", () => {+ const closed = reduce(reviewed(), { type: "visibility", open: false });+ assert.equal(closed.preview, preview);+ assert.equal(closed.phase, "plan");+ const opened = reduce(closed, { type: "visibility", open: true });+ assert.equal(opened.preview, preview);+ assert.equal(opened.preview?.markdown, preview.markdown);+ const preparing = reduce(opened, { type: "start", phase: "preparing", message: "Preparing…" });+ const hidden = reduce(preparing, { type: "visibility", open: false });+ assert.equal(hidden.phase, "preparing");+ assert.equal(skillReviewBusy(hidden.phase), true);+ assert.equal(reduce(hidden, { type: "preview", preview }).reviewOpen, false);+});++test("export cancellation preserves the open review and candidate without an error", () => {+ const creating = reduce(reviewed(), { type: "start", phase: "creating", message: "Exporting…" });+ const canceled = reduce(creating, { type: "settle", phase: "plan" });+ assert.equal(canceled.preview, preview);+ assert.equal(canceled.reviewOpen, true);+ assert.equal(canceled.error, null);+ assert.equal(canceled.phase, "plan");+});++test("placement failure retains the candidate and shared error for retry from either surface", () => {+ for (const open of [true, false]) {+ const ready = reduce(reviewed(), { type: "visibility", open });+ const failed = reduce(ready, { type: "settle", phase: "plan", error: "Write failed" });+ assert.equal(failed.preview, preview);+ assert.equal(failed.error, "Write failed");+ assert.equal(failed.reviewOpen, open);+ const retrying = reduce(failed, { type: "start", phase: "creating", message: "Writing…" });+ assert.equal(retrying.error, null);+ const done = reduce(retrying, { type: "done" });+ assert.equal(done.phase, "done");+ assert.equal(done.reviewOpen, false);+ assert.equal(done.preview, null);+ }+});++test("plan invalidation drops the candidate without blocking edits", () => {+ const invalidated = reduce(reviewed(), { type: "invalidate" });+ assert.equal(invalidated.preview, null);+ assert.equal(invalidated.phase, "plan");+ assert.equal(skillReviewBusy(invalidated.phase), false);+});++test("expired placement clears the local candidate while retaining the error and explicit review retry", () => {+ for (const open of [true, false]) {+ const ready = reduce(reviewed(), { type: "visibility", open });+ const creating = reduce(ready, { type: "start", phase: "creating", message: "Writing…" });+ const expired = reduce(creating, {+ type: "settle", phase: "plan", previewExpired: true, error: "Preview expired. Review again.",+ });+ assert.equal(expired.preview, null);+ assert.equal(expired.reviewOpen, open);+ assert.equal(expired.error, "Preview expired. Review again.");+ assert.equal(expired.phase, "plan");+ assert.equal(skillReviewBusy(expired.phase), false);+ const reopened = reduce(reduce(expired, { type: "visibility", open: false }), { type: "visibility", open: true });+ assert.equal(reopened.preview, null);+ assert.equal(reopened.error, expired.error);+ const retry = reduce(reopened, { type: "start", phase: "preparing", message: "Preparing…" });+ assert.equal(retry.phase, "preparing");+ assert.equal(retry.error, null);+ }+});++test("generation failure and cancellation return to the plan without accepting a preview", () => {+ const preparing = reduce(initialSkillReviewState(false), { type: "start", phase: "preparing", message: "Preparing…" });+ const failed = reduce(preparing, { type: "settle", phase: "plan", error: "IPC failed" });+ assert.equal(failed.phase, "plan");+ assert.equal(failed.preview, null);+ assert.equal(failed.error, "IPC failed");+ const stopping = reduce(preparing, { type: "start", phase: "stopping", message: "Stopping…" });+ assert.equal(skillReviewBusy(stopping.phase), true);+ assert.equal(reduce(stopping, { type: "settle", phase: "plan" }).error, null);+});++test("synchronous operation guard rejects double clicks and releases only the matching operation", () => {+ const guard = new SkillOperationGuard();+ const first = guard.begin()!;+ assert.equal(guard.begin(), null);+ assert.equal(guard.isCurrent(first), true);+ guard.finish(Symbol());+ assert.equal(guard.busy, true);+ guard.finish(first);+ assert.equal(guard.busy, false);+ assert.ok(guard.begin());+});++test("cancellation or departure makes late results stale without unlocking newer work", () => {+ const guard = new SkillOperationGuard();+ const old = guard.begin()!;+ assert.equal(guard.invalidate(), true);+ const next = guard.begin()!;+ assert.equal(guard.isCurrent(old), false);+ guard.finish(old);+ assert.equal(guard.isCurrent(next), true);+ assert.equal(guard.begin(), null);+ guard.invalidate();+ assert.equal(guard.isCurrent(next), false);+ assert.equal(guard.invalidate(), false);+});++test("cancellation acknowledgement cannot release the lock before the original request settles", async () => {+ const guard = new SkillOperationGuard();+ const original = guard.begin()!;+ const { originalSettled, operation: cancellation } = guard.beginCancellation()!;+ let stopped = false;+ const stop = (async () => {+ await Promise.resolve(); // cancelSkill acknowledged, but generation/picker is still pending.+ await originalSettled;+ stopped = true;+ guard.finish(cancellation);+ })();+ await Promise.resolve();+ await Promise.resolve();+ assert.equal(stopped, false);+ assert.equal(guard.busy, true);+ assert.equal(guard.begin(), null);+ assert.equal(guard.isCurrent(original), false);+ guard.finish(original);+ await stop;+ assert.equal(stopped, true);+ assert.equal(guard.busy, false);+ assert.ok(guard.begin());+});++test("committed placement wins a cancellation race and keeps the shared done screen", async () => {+ const guard = new SkillOperationGuard();+ const placement = guard.begin()!;+ let state = reduce(reviewed(), { type: "start", phase: "creating", message: "Writing…" });+ const cancellation = guard.beginCancellation()!;+ state = reduce(state, { type: "start", phase: "stopping", message: "Stopping…" });+ assert.equal(guard.isCurrent(placement), false);+ // createSkill reports success after the synchronous write beat cancellation.+ assert.equal(guard.commit(placement), true);+ state = reduce(state, { type: "done" });+ guard.finish(placement);+ await cancellation.originalSettled;+ // The cancellation continuation must not put the completed UI back on its plan.+ if (guard.isCurrent(cancellation.operation)) {+ state = reduce(state, { type: "settle", phase: "plan" });+ }+ guard.finish(cancellation.operation);+ assert.equal(state.phase, "done");+ assert.equal(state.preview, null);+ assert.equal(state.reviewOpen, false);+ assert.equal(guard.busy, false);+});++test("departed or superseded placements cannot report a committed success", () => {+ const guard = new SkillOperationGuard();+ const old = guard.begin()!;+ guard.beginCancellation();+ guard.invalidate();+ const next = guard.begin()!;+ assert.equal(guard.commit(old), false);+ assert.equal(guard.isCurrent(next), true);+ guard.finish(old);+ assert.equal(guard.isCurrent(next), true);+});++test("departed operation completion does not unlock a fresh builder instance", async () => {+ const previousView = new SkillOperationGuard();+ const departed = previousView.begin()!;+ const settled = previousView.whenSettled();+ previousView.invalidate();+ const freshView = new SkillOperationGuard();+ const current = freshView.begin()!;+ previousView.finish(departed);+ await settled;+ assert.equal(previousView.isCurrent(departed), false);+ assert.equal(freshView.isCurrent(current), true);+ assert.equal(freshView.begin(), null);+});diff --git a/src/skill-review-state.ts b/src/skill-review-state.tsnew file mode 100644index 0000000..63de041--- /dev/null+++ b/src/skill-review-state.ts@@ -0,0 +1,119 @@+import type { SkillPreview } from "../common/ipc";++export type SkillPhase = "loading" | "ready" | "planning" | "plan" | "preparing" | "creating" | "stopping" | "done";++export interface SkillReviewState {+ phase: SkillPhase;+ preview: SkillPreview | null;+ reviewOpen: boolean;+ statusLine: string;+ error: string | null;+}++export type SkillReviewAction =+ | { type: "start"; phase: "planning" | "preparing" | "creating" | "stopping"; message: string }+ | { type: "settle"; phase: "ready" | "plan"; error?: string; previewExpired?: boolean }+ | { type: "preview"; preview: SkillPreview }+ | { type: "visibility"; open: boolean }+ | { type: "invalidate" }+ | { type: "progress"; message: string }+ | { type: "error"; error: string }+ | { type: "done" };++export function initialSkillReviewState(hasSkill: boolean): SkillReviewState {+ return { phase: hasSkill ? "loading" : "ready", preview: null, reviewOpen: false, statusLine: "", error: null };+}++export function skillReviewBusy(phase: SkillPhase): boolean {+ return phase === "planning" || phase === "preparing" || phase === "creating" || phase === "stopping";+}++export function skillReviewReducer(state: SkillReviewState, action: SkillReviewAction): SkillReviewState {+ switch (action.type) {+ case "start":+ return { ...state, phase: action.phase, statusLine: action.message, error: null };+ case "settle":+ return {+ ...state,+ phase: action.phase,+ preview: action.previewExpired ? null : state.preview,+ statusLine: "",+ error: action.error ?? null,+ };+ case "preview":+ return { ...state, phase: "plan", preview: action.preview, statusLine: "", error: null };+ case "visibility":+ return { ...state, reviewOpen: action.open };+ case "invalidate":+ return { ...state, preview: null };+ case "progress":+ return { ...state, statusLine: action.message };+ case "error":+ return { ...state, error: action.error };+ case "done":+ return { ...state, phase: "done", preview: null, reviewOpen: false, statusLine: "", error: null };+ }+}++// React state updates are deferred; acquire this guard before the first await.+export class SkillOperationGuard {+ private active: symbol | null = null;+ private canceledSource: symbol | null = null;+ private pending = new Map<symbol, { promise: Promise<void>; resolve: () => void }>();++ begin(): symbol | null {+ if (this.active) return null;+ this.active = Symbol();+ let resolve!: () => void;+ const promise = new Promise<void>((done) => { resolve = done; });+ this.pending.set(this.active, { promise, resolve });+ return this.active;+ }++ isCurrent(operation: symbol): boolean {+ return this.active === operation;+ }++ beginCancellation(): { operation: symbol; originalSettled: Promise<void> } | null {+ if (!this.active || this.canceledSource) return null;+ const original = this.active;+ const originalSettled = this.whenSettled();+ this.active = null;+ const operation = this.begin()!;+ this.canceledSource = original;+ return { operation, originalSettled };+ }++ // Cancellation cannot undo a synchronous file write that already committed.+ // Departure invalidates both identities, so it still rejects late successes.+ commit(operation: symbol): boolean {+ if (!this.isCurrent(operation) && this.canceledSource !== operation) return false;+ this.active = null;+ this.canceledSource = null;+ return true;+ }++ finish(operation: symbol): void {+ this.pending.get(operation)?.resolve();+ this.pending.delete(operation);+ if (this.isCurrent(operation)) {+ this.active = null;+ this.canceledSource = null;+ }+ }++ whenSettled(): Promise<void> {+ return (this.active && this.pending.get(this.active)?.promise) || Promise.resolve();+ }++ invalidate(): boolean {+ const wasActive = this.active !== null;+ this.active = null;+ this.canceledSource = null;+ return wasActive;+ }++ get busy(): boolean {+ return this.active !== null;+ }+}