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
Harden describer: apply code-review fixes
adilei24859e8fc78c
diff --git a/electron/describer/describer.ts b/electron/describer/describer.tsindex 4267379..627a79d 100644--- a/electron/describer/describer.ts+++ b/electron/describer/describer.ts@@ -14,7 +14,7 @@ import type { AnalyzeProgress } from "../../common/ipc";import type { SessionMeta } from "../../common/types";import { FrameExtractor } from "../frames/extractor";import { createLogger } from "../logger";-import { sessionsRoot } from "../recorder/session-store";+import { sessionsRoot, sessionDir, isValidSessionId } from "../recorder/session-store";import { DESCRIBER_INSTRUCTIONS } from "./instructions";import { createDescriberTools } from "./tools";@@ -23,6 +23,9 @@ const log = createLogger("Describer");/** How long a single agent turn may run before we give up (multi-tool loop). */const TURN_TIMEOUT_MS = 180_000;+/** Cap on simultaneously-held live agent sessions; oldest idle ones are evicted. */+const MAX_LIVE_SESSIONS = 4;+const KICKOFF_PROMPT ="Reconstruct what the user did in this recording. Start with get_timeline, then read events " +"where anything is unclear, and look at frames only where the events are ambiguous. When " +@@ -61,6 +64,7 @@ function readJson<T>(file: string): T | null {/** Load a persisted analysis from a session dir (validated), or null. */export function loadPersistedAnalysis(sessionId: string): Analysis | null {+ if (!isValidSessionId(sessionId)) return null;const file = path.join(sessionsRoot(), sessionId, "analysis.json");const raw = readJson<unknown>(file);if (!raw) return null;@@ -107,11 +111,9 @@ export class Describer {this.emit(sessionId, "start", "Re-analyzing with your feedback…");const live = this.live.get(sessionId) ?? (await this.createLive(sessionId));const prior = loadPersistedAnalysis(sessionId);- live.feedbackLog = [- ...live.feedbackLog,- { revision: live.revision + 1, at: Date.now(), overall: fb.overall, steps: fb.steps },- ];- return await this.runTurn(live, renderFeedbackPrompt(fb, prior));+ // The feedback round is recorded in runTurn only after it produces a+ // revision, so a failed turn never leaves a phantom log entry.+ return await this.runTurn(live, renderFeedbackPrompt(fb, prior), fb);} finally {this.active.delete(sessionId);}@@ -119,11 +121,11 @@ export class Describer {/** Accept an analysis as correct. Persists `approved` so a Skill can be built from it. */async approve(sessionId: string): Promise<Analysis> {+ if (this.active.has(sessionId)) throw new Error("Wait for the current analysis to finish before saving.");const prior = loadPersistedAnalysis(sessionId);if (!prior) throw new Error("There is no analysis to approve yet.");const approved: Analysis = { ...prior, approved: true, approvedAt: Date.now() };- const dir = path.join(sessionsRoot(), sessionId);- this.persist(dir, approved, this.live.get(sessionId)?.copilot.sessionId);+ this.persist(sessionDir(sessionId), approved);return approved;}@@ -133,13 +135,13 @@ export class Describer {* intent is ignored (a session always keeps a goal); the title may be cleared.*/async edit(sessionId: string, patch: { title?: string; intent?: string }): Promise<Analysis> {+ if (this.active.has(sessionId)) throw new Error("Wait for the current analysis to finish before editing.");const prior = loadPersistedAnalysis(sessionId);if (!prior) throw new Error("There is no analysis to edit yet.");const next: Analysis = { ...prior };if (patch.title !== undefined) next.title = patch.title.trim();if (patch.intent !== undefined && patch.intent.trim()) next.intent = patch.intent.trim();- const dir = path.join(sessionsRoot(), sessionId);- this.persist(dir, next, this.live.get(sessionId)?.copilot.sessionId);+ this.persist(sessionDir(sessionId), next);return next;}@@ -149,6 +151,19 @@ export class Describer {if (live) await live.copilot.abort().catch(() => undefined);}+ /**+ * Disconnect live sessions that aren't currently running — called when the+ * library window closes, so idle agent conversations don't linger. The active+ * (in-flight) session, if any, is left alone.+ */+ async evictIdle(): Promise<void> {+ for (const [id, live] of this.live) {+ if (this.active.has(id)) continue;+ this.live.delete(id);+ await live.copilot.disconnect().catch(() => undefined);+ }+ }+/** Tear down the client + all live sessions (called on app quit). */async dispose(): Promise<void> {for (const [id] of this.live) await this.disposeLive(id);@@ -206,15 +221,15 @@ export class Describer {}private async createLive(sessionId: string): Promise<LiveSession> {- const sessionDir = path.join(sessionsRoot(), sessionId);- const meta = readJson<SessionMeta>(path.join(sessionDir, "session.json"));+ const dir = sessionDir(sessionId);+ const meta = readJson<SessionMeta>(path.join(dir, "session.json"));if (!meta) throw new Error(`Session ${sessionId} not found or has no session.json.`);- const extractor = buildExtractor(sessionDir);+ const extractor = buildExtractor(dir);const holder: LiveSession["holder"] = { submission: undefined };const tools = createDescriberTools({- sessionDir,+ sessionDir: dir,startedAt: meta.startedAt,extractor,onProgress: (m) => this.emit(sessionId, "working", m),@@ -228,34 +243,44 @@ export class Describer {systemMessage: { mode: "append" as const, content: DESCRIBER_INSTRUCTIONS },tools,onPermissionRequest: approveAll,- workingDirectory: sessionDir,+ workingDirectory: dir,enableHostGitOperations: false,infiniteSessions: { enabled: false },...(this.model ? { model: this.model } : {}),};- // Restrict to our custom tools where supported; fall back if the runtime- // rejects an allowlist of custom names.- let copilot: CopilotSession;- try {- copilot = await client.createSession({ ...config, availableTools: tools.map((t) => t.name) });- } catch (err) {- log.warn("createSession with tool allowlist failed; retrying without it:", msg(err));- copilot = await client.createSession(config);- }+ // Always constrain the agent to our sandboxed custom tools. If the runtime+ // cannot honor the allowlist we fail the analysis rather than silently+ // creating an unsandboxed session — which, combined with approveAll, would+ // auto-run the SDK's full default toolset in the user's environment.+ const copilot = await client.createSession({+ ...config,+ availableTools: tools.map((t) => t.name),+ });const prior = loadPersistedAnalysis(sessionId);const live: LiveSession = {sessionId,- sessionDir,+ sessionDir: dir,copilot,revision: prior?.revision ?? 0,feedbackLog: prior?.feedbackLog ?? [],holder,};this.live.set(sessionId, live);+ this.evictOverflow(sessionId);return live;}+ /** Keep at most MAX_LIVE_SESSIONS live; disconnect the oldest idle ones. */+ private evictOverflow(keep: string): void {+ for (const [id, live] of this.live) {+ if (this.live.size <= MAX_LIVE_SESSIONS) break;+ if (id === keep || this.active.has(id)) continue;+ this.live.delete(id);+ void live.copilot.disconnect().catch(() => undefined);+ }+ }+private async disposeLive(sessionId: string): Promise<void> {const live = this.live.get(sessionId);if (!live) return;@@ -263,12 +288,18 @@ export class Describer {await live.copilot.disconnect().catch(() => undefined);}- private async runTurn(live: LiveSession, prompt: string): Promise<Analysis> {+ private async runTurn(+ live: LiveSession,+ prompt: string,+ pendingFeedback?: AnalysisFeedback,+ ): Promise<Analysis> {live.holder.submission = undefined;this.emit(live.sessionId, "working", "Thinking…");try {await live.copilot.sendAndWait(prompt, TURN_TIMEOUT_MS);} catch (err) {+ // Don't leave the agent running past our timeout/abort — reclaim the turn.+ await live.copilot.abort().catch(() => undefined);throw new Error(`Analysis run failed: ${msg(err)}`);}if (!live.holder.submission) {@@ -279,23 +310,30 @@ export class Describer {if (!submission) throw new Error("The agent finished without submitting an analysis.");live.revision += 1;+ // Record the feedback round only now that it actually produced a revision, so+ // a failed turn above never leaves a phantom entry with a duplicated revision.+ if (pendingFeedback) {+ live.feedbackLog = [+ ...live.feedbackLog,+ {+ revision: live.revision,+ at: Date.now(),+ overall: pendingFeedback.overall,+ steps: pendingFeedback.steps,+ },+ ];+ }this.emit(live.sessionId, "drafting", "Finalizing analysis…");const analysis = toAnalysis(live.sessionId, live.revision, submission, [...live.feedbackLog]);- this.persist(live.sessionDir, analysis, live.copilot.sessionId);+ this.persist(live.sessionDir, analysis);this.emit(live.sessionId, "done", `Analysis ready (revision ${analysis.revision}).`);return analysis;}- private persist(sessionDir: string, analysis: Analysis, copilotSessionId?: string): void {+ private persist(sessionDir: string, analysis: Analysis): void {try {writeFileSync(path.join(sessionDir, "analysis.json"), JSON.stringify(analysis, null, 2));writeFileSync(path.join(sessionDir, "analysis.md"), renderAnalysisMarkdown(analysis));- if (copilotSessionId) {- writeFileSync(- path.join(sessionDir, "describer.json"),- JSON.stringify({ copilotSessionId }, null, 2),- );- }} catch (err) {log.warn("failed to persist analysis:", msg(err));}diff --git a/electron/describer/tools.ts b/electron/describer/tools.tsindex d7399a1..72bff96 100644--- a/electron/describer/tools.ts+++ b/electron/describer/tools.ts@@ -28,6 +28,8 @@ export interface ToolContext {const MAX_IMAGES_PER_CALL = 6;const MAX_STR = 2000;+/** Cap rows returned by get_events so an un-windowed call can't dump the whole log. */+const MAX_EVENTS = 500;const truncate = (v: unknown): unknown =>typeof v === "string" && v.length > MAX_STR ? v.slice(0, MAX_STR) + "…[truncated]" : v;@@ -121,7 +123,7 @@ export function createDescriberTools(ctx: ToolContext): Tool[] {} catch (err) {return `Could not read events: ${err instanceof Error ? err.message : String(err)}`;}- const rows = events+ const all = events.filter((e) => (wanted ? wanted.has(e.type) : MEANINGFUL_EVENT_TYPES.has(e.type))).map((e) => ({ e, atMs: rel(e.epoch) })).filter(({ atMs }) => atMs >= from && atMs <= to)@@ -130,7 +132,22 @@ export function createDescriberTools(ctx: ToolContext): Tool[] {for (const [k, v] of Object.entries(e.payload)) payload[k] = truncate(v);return { seq: e.seq, atMs, type: e.type, source: e.source, ...payload };});- return JSON.stringify({ count: rows.length, events: rows }, null, 2);+ // Bound the payload so a long, un-windowed session can't return thousands+ // of rows in one tool result. When truncated, tell the agent how to narrow.+ const rows = all.slice(0, MAX_EVENTS);+ const truncated = all.length > rows.length;+ return JSON.stringify(+ {+ count: rows.length,+ total: all.length,+ ...(truncated+ ? { truncated: true, note: `Showing the first ${MAX_EVENTS} of ${all.length} events. Narrow with fromMs/toMs or filter by types.` }+ : {}),+ events: rows,+ },+ null,+ 2,+ );},};diff --git a/electron/ipc.ts b/electron/ipc.tsindex af75f29..fe5faae 100644--- a/electron/ipc.ts+++ b/electron/ipc.ts@@ -8,6 +8,7 @@ import { Describer, loadPersistedAnalysis } from "./describer/describer";import { runDoctor } from "./doctor";import { createLogger } from "./logger";import type { RecorderController } from "./recorder/controller";+import { isValidSessionId } from "./recorder/session-store";import { listSessions } from "./sessions";import type { SettingsStore } from "./settings";@@ -48,6 +49,7 @@ export function registerIpc(ipcMain.handle(IPC.analyze, async (_event, sessionId?: string): Promise<AnalyzeResult> => {const id = resolveSessionId(sessionId);if (!id) return { ok: false, error: "No completed session to analyze yet." };+ if (!isValidSessionId(id)) return { ok: false, error: "Unknown session." };try {const analysis = await describer.analyze(id);return { ok: true, analysis };@@ -61,7 +63,7 @@ export function registerIpc(ipcMain.handle(IPC.analyzeFeedback,async (_event, input: AnalysisFeedbackInput): Promise<AnalyzeResult> => {- if (!input?.sessionId) return { ok: false, error: "Missing sessionId." };+ if (!isValidSessionId(input?.sessionId)) return { ok: false, error: "Unknown session." };try {const analysis = await describer.feedback(input.sessionId, {overall: input.overall,@@ -77,11 +79,11 @@ export function registerIpc();ipcMain.handle(IPC.getAnalysis, (_event, sessionId: string) =>- sessionId ? loadPersistedAnalysis(sessionId) : null,+ isValidSessionId(sessionId) ? loadPersistedAnalysis(sessionId) : null,);ipcMain.handle(IPC.approveAnalysis, async (_event, sessionId: string): Promise<AnalyzeResult> => {- if (!sessionId) return { ok: false, error: "Missing sessionId." };+ if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };try {const analysis = await describer.approve(sessionId);return { ok: true, analysis };@@ -93,7 +95,7 @@ export function registerIpc(});ipcMain.handle(IPC.updateAnalysis, async (_event, input: AnalysisEditInput): Promise<AnalyzeResult> => {- if (!input?.sessionId) return { ok: false, error: "Missing sessionId." };+ if (!isValidSessionId(input?.sessionId)) return { ok: false, error: "Unknown session." };try {const analysis = await describer.edit(input.sessionId, {title: input.title,@@ -108,7 +110,7 @@ export function registerIpc(});ipcMain.handle(IPC.cancelAnalysis, async (_event, sessionId: string) => {- if (sessionId) await describer.cancel(sessionId);+ if (isValidSessionId(sessionId)) await describer.cancel(sessionId);return { ok: true };});diff --git a/electron/main.ts b/electron/main.tsindex b829de4..e04181f 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -52,6 +52,8 @@ function openLibrary(): void {recorderWindow.setBounds(recorderHome);}recorderHome = null;+ // Drop idle agent conversations now that the library is gone.+ void describer.evictIdle();});}diff --git a/electron/recorder/session-store.ts b/electron/recorder/session-store.tsindex d6464ad..8c2a288 100644--- a/electron/recorder/session-store.ts+++ b/electron/recorder/session-store.ts@@ -12,6 +12,31 @@ export function sessionsRoot(): string {return path.join(app.getPath("userData"), "sessions");}+/**+ * True when `id` is safe to use as a single path segment under {@link sessionsRoot}.+ *+ * This is a traversal guard, not a format check: renderer- or caller-supplied ids+ * must be a single segment with no path separators and no `..`, so `path.join`+ * can never escape the sessions root. It intentionally accepts any reasonable slug+ * (our own `YYYYMMDD-HHMMSS-<hex>` ids, but also eval/test/imported ids) rather+ * than coupling to {@link makeSessionId}'s exact shape.+ */+export function isValidSessionId(id: unknown): id is string {+ return (+ typeof id === "string" &&+ id.length > 0 &&+ id.length <= 128 &&+ !id.includes("..") &&+ /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)+ );+}++/** Absolute directory for a session id. Throws on an unsafe id (no traversal). */+export function sessionDir(id: string): string {+ if (!isValidSessionId(id)) throw new Error(`Invalid session id: ${String(id)}`);+ return path.join(sessionsRoot(), id);+}+/*** Owns the on-disk artifacts for a single recording session:* <sessionsRoot>/<id>/session.json session metadatadiff --git a/electron/sessions.ts b/electron/sessions.tsindex 6866295..fcad138 100644--- a/electron/sessions.ts+++ b/electron/sessions.ts@@ -1,64 +1,89 @@-import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { access, readdir, readFile, stat } from "node:fs/promises";import path from "node:path";+import { AnalysisSchema, type Analysis } from "../common/analysis";import type { SessionSummary } from "../common/ipc";import type { SessionMeta } from "../common/types";-import { loadPersistedAnalysis } from "./describer/describer";-import { createLogger } from "./logger";-import { sessionsRoot } from "./recorder/session-store";+import { isValidSessionId, sessionsRoot } from "./recorder/session-store";-const log = createLogger("Sessions");+/** True when `file` exists (non-throwing `fs.access`). */+async function exists(file: string): Promise<boolean> {+ try {+ await access(file);+ return true;+ } catch {+ return false;+ }+}-/** Enumerate saved recordings for the sessions library, newest first. */-export function listSessions(): SessionSummary[] {- const root = sessionsRoot();- if (!existsSync(root)) return [];+/** Load and validate a session's persisted analysis without blocking the main thread. */+async function loadAnalysis(dir: string): Promise<Analysis | null> {+ try {+ const raw = JSON.parse(await readFile(path.join(dir, "analysis.json"), "utf8"));+ const parsed = AnalysisSchema.safeParse(raw);+ return parsed.success ? parsed.data : null;+ } catch {+ return null;+ }+}- const out: SessionSummary[] = [];- let names: string[];+/** Build the library summary for a single session dir, or null if it isn't one. */+async function summarize(root: string, name: string): Promise<SessionSummary | null> {+ const dir = path.join(root, name);try {- names = readdirSync(root);- } catch (err) {- log.warn("failed to read sessions dir:", err instanceof Error ? err.message : err);- return [];+ if (!(await stat(dir)).isDirectory()) return null;+ } catch {+ return null;}- for (const name of names) {- const dir = path.join(root, name);- try {- if (!statSync(dir).isDirectory()) continue;- } catch {- continue;- }- let meta: SessionMeta | null = null;- try {- meta = JSON.parse(readFileSync(path.join(dir, "session.json"), "utf8")) as SessionMeta;- } catch {- continue; // not a valid session dir- }- if (!meta?.id) continue;+ let meta: SessionMeta | null = null;+ try {+ meta = JSON.parse(await readFile(path.join(dir, "session.json"), "utf8")) as SessionMeta;+ } catch {+ return null; // not a valid session dir+ }+ if (!meta?.id) return null;++ const [analysis, processed, hasVideo] = await Promise.all([+ loadAnalysis(dir),+ exists(path.join(dir, "bundle.json")),+ exists(path.join(dir, "video.json")),+ ]);++ return {+ id: meta.id,+ startedAt: meta.startedAt ?? null,+ stoppedAt: meta.stoppedAt ?? null,+ durationMs: meta.startedAt && meta.stoppedAt ? meta.stoppedAt - meta.startedAt : null,+ processed,+ hasVideo,+ analysis: analysis+ ? {+ revision: analysis.revision,+ title: analysis.title ?? "",+ intent: analysis.intent,+ intentConfidence: analysis.intentConfidence,+ stepCount: analysis.steps.length,+ approved: analysis.approved ?? false,+ }+ : null,+ };+}- const analysis = loadPersistedAnalysis(name);- out.push({- id: meta.id,- startedAt: meta.startedAt ?? null,- stoppedAt: meta.stoppedAt ?? null,- durationMs: meta.startedAt && meta.stoppedAt ? meta.stoppedAt - meta.startedAt : null,- processed: existsSync(path.join(dir, "bundle.json")),- hasVideo: existsSync(path.join(dir, "video.json")),- analysis: analysis- ? {- revision: analysis.revision,- title: analysis.title ?? "",- intent: analysis.intent,- intentConfidence: analysis.intentConfidence,- stepCount: analysis.steps.length,- approved: analysis.approved ?? false,- }- : null,- });+/** Enumerate saved recordings for the sessions library, newest first. */+export async function listSessions(): Promise<SessionSummary[]> {+ const root = sessionsRoot();+ let names: string[];+ try {+ names = await readdir(root);+ } catch {+ return []; // no sessions dir yet}+ const summaries = await Promise.all(+ names.filter((name) => isValidSessionId(name)).map((name) => summarize(root, name)),+ );+ const out = summaries.filter((s): s is SessionSummary => s !== null);out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));return out;}diff --git a/electron/window.ts b/electron/window.tsindex 31fe36a..0178a50 100644--- a/electron/window.ts+++ b/electron/window.ts@@ -87,7 +87,7 @@ export function createLibraryWindow(recorder: BrowserWindow): BrowserWindow {const layout = computeDock(recorder);const win = new BrowserWindow({...layout.library,- minWidth: 560,+ minWidth: LIBRARY.floorWidth,minHeight: 480,show: false,title: "Skill Recorder — Sessions",diff --git a/src/App.css b/src/App.cssindex 9258ee5..62e580b 100644--- a/src/App.css+++ b/src/App.css@@ -121,6 +121,18 @@ button:focus-visible,color: var(--muted);}+.status-text {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.status-cancel {+ margin-left: auto;+ flex: none;+}+.spinner {width: 13px;height: 13px;diff --git a/src/Library.tsx b/src/Library.tsxindex f70ef2a..c994231 100644--- a/src/Library.tsx+++ b/src/Library.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import type { Analysis } from "../common/analysis";import type { AnalyzeProgress, SessionSummary } from "../common/ipc";@@ -131,6 +131,9 @@ function AnalysisWorkspace({const [editing, setEditing] = useState(false);const [draftTitle, setDraftTitle] = useState("");const [draftIntent, setDraftIntent] = useState("");+ // 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(() => {let live = true;@@ -152,16 +155,24 @@ function AnalysisWorkspace({}, [sessionId]);const run = useCallback(async () => {+ canceled.current = false;setAnalyzing(true);setError(null);setStatusLine("Starting…");const res = await window.skillRecorder.analyze(sessionId);if (res.ok && res.analysis) setAnalysis(res.analysis);- else setError(res.error ?? "Analysis failed");+ else if (!canceled.current) setError(res.error ?? "Analysis failed");setAnalyzing(false);void onChanged();}, [sessionId, onChanged]);+ const cancel = useCallback(async () => {+ canceled.current = true;+ setStatusLine("Stopping…");+ await window.skillRecorder.cancelAnalysis(sessionId);+ setAnalyzing(false);+ }, [sessionId]);+const hasFeedback =overall.trim().length > 0 || Object.values(notes).some((n) => n.trim().length > 0);@@ -170,6 +181,7 @@ function AnalysisWorkspace({.filter(([, note]) => note.trim()).map(([stepId, note]) => ({ stepId, note: note.trim() }));if (!overall.trim() && steps.length === 0) return;+ canceled.current = false;setAnalyzing(true);setError(null);setStatusLine("Re-analyzing with your feedback…");@@ -183,7 +195,7 @@ function AnalysisWorkspace({setOverall("");setOverallOpen(false);setNotes({});- } else {+ } else if (!canceled.current) {setError(res.error ?? "Re-analysis failed");}setAnalyzing(false);@@ -257,7 +269,10 @@ function AnalysisWorkspace({{analyzing && (<div className="status-line"><span className="spinner" />- {statusLine || "Working…"}+ <span className="status-text">{statusLine || "Working…"}</span>+ <button className="linky status-cancel" onClick={cancel}>+ Cancel+ </button></div>)}