From c9bcf9997b4974959d80babb67e5597866da92e9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:13:25 -0500 Subject: [PATCH 01/25] feat(mcp): agents list and run the window's commands, start long tools as jobs, and the window hears of their changes (0.12.0) The owner's rule is that Claude Code and the other agents can do everything a person can do in FormREC. The engine had 124 MCP tools but nothing reached the window: no list or run of its command registry, no way to start a long tool without waiting on it, and the window showed an agent's change only after the person navigated. - src/window/bridge.ts: the window keeps GET /api/window/stream open; the engine sends it list, describe and run calls and the window answers on POST /api/window/result. The window that took focus last answers. The same stream carries `changed` notices. Commands whose risk is destructive, external or privacy ask the person in the dock's consent dialog every time, whoever the agent is; a blocked policy refuses them. - formrec_window_commands (read only) and formrec_window_command_run: in the app through the bridge, from `formrec mcp` (stdio or --http) through the running app's /api/window/commands and /api/window/run with the run token. - formrec_job_start, formrec_job_status, formrec_job_cancel: any other tool in the background with a job id to poll; its arguments are checked with its own schema, its result is what it would have answered, and it may run only what the server offers (scope and core filters hold). - buildServer announces every successful mutating tool's recording ids to the window, so changes show at once; the relay's bridge gets none of this (no window caller), and read-only tokens stay read-only. --- src/app.ts | 6 ++ src/mcp/http.ts | 4 +- src/mcp/jobs.ts | 134 ++++++++++++++++++++++++ src/mcp/server.ts | 58 ++++++++++- src/mcp/tools.ts | 2 + src/window/bridge.ts | 237 +++++++++++++++++++++++++++++++++++++++++++ src/window/tools.ts | 42 ++++++++ 7 files changed, 478 insertions(+), 5 deletions(-) create mode 100644 src/mcp/jobs.ts create mode 100644 src/window/bridge.ts create mode 100644 src/window/tools.ts diff --git a/src/app.ts b/src/app.ts index a8dea77..88ba51b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -17,6 +17,7 @@ import { mcpToken } from './mcp/token.js' import { playerLinkGate } from './server/player-link.js' import { version } from './version.js' import { createDock } from './dock/index.js' +import { localCaller, WindowBridge, windowRoutes } from './window/bridge.js' export interface AppOptions { dataDir: string @@ -80,6 +81,9 @@ export function createApp(opts: AppOptions): App { return port === undefined ? [] : [`http://127.0.0.1:${port}`, `http://localhost:${port}`] } const dock = createDock({ dataDir: opts.dataDir, port: ctx.port, codebase: opts.codebase }) + // The agent bridge to the open window (window/bridge.ts): its command registry, and live notices of agents' changes. + const bridge = new WindowBridge() + const windowCaller = localCaller(bridge, dock.consent, opts.dataDir) const mcp = createMcpHttp({ build: () => buildServer( @@ -88,6 +92,7 @@ export function createApp(opts: AppOptions): App { // No run token: buildServer gives each recording's link its own player key (mcp/player-links.ts). playerBase: async () => `${origin()[0] ?? 'http://127.0.0.1:8770'}/`, allowedRoots: opts.codebase ? [opts.codebase.root] : undefined, + window: windowCaller, }, version(), {}, @@ -106,6 +111,7 @@ export function createApp(opts: AppOptions): App { studioRoutes({ sessions, room, devices, guests, codebase: opts.codebase, engine: opts.engine }), ...FEATURES.flatMap((f) => (f.routes ? [f.routes(ctx)] : [])), dock.routes, + windowRoutes(bridge, dock.consent, opts.dataDir), ], mediaFile: featureFile, gates: [playerLinkGate(library), extensionGate(ctx), mailGate()], diff --git a/src/mcp/http.ts b/src/mcp/http.ts index 47e5f80..87c8fe7 100644 --- a/src/mcp/http.ts +++ b/src/mcp/http.ts @@ -23,6 +23,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js' import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js' import { remoteGate } from './consent.js' +import { remoteCaller } from '../window/bridge.js' import { hostAllowed } from '../server/http.js' import { tokenMatches } from '../server/token.js' import { buildServer } from './server.js' @@ -238,7 +239,8 @@ export async function serveMcpHttp(o: McpHttpServerOptions): Promise buildServer(o.deps, o.version, {}, remoteGate(o.dataDir)), + // Window commands reach the running app's window over its loopback API (window/bridge.ts remoteCaller). + build: () => buildServer({ ...o.deps, window: o.deps.window ?? remoteCaller(o.dataDir) }, o.version, {}, remoteGate(o.dataDir)), tokens: async () => [await mcpToken(o.dataDir), ...(o.extraTokens ?? [])], allowedOrigins: () => [], allowedHosts: () => [wildcard ? '*' : host], diff --git a/src/mcp/jobs.ts b/src/mcp/jobs.ts new file mode 100644 index 0000000..849e3b2 --- /dev/null +++ b/src/mcp/jobs.ts @@ -0,0 +1,134 @@ +/** + * Long operations as jobs: formrec_job_start runs any other FormREC tool in the background and answers at once with a + * job id; formrec_job_status polls it (state, the tool's progress notifications, and its result once done); + * formrec_job_cancel stops it (the tool's cancellation signal, as an MCP cancel would). Recording a walkthrough, + * exporting, transcribing, making clips, rendering a voice-over or checking freshness can take minutes; a client with + * a short request timeout uses these instead of waiting on the tool itself. + * + * The started tool runs exactly as it would if called directly (same arguments, checked with its own schema, same + * answer shape and player links); the consent gate asks once, for formrec_job_start, naming the tool in its summary. + * Jobs live in this process's memory: an hour after they end they are dropped, and at most MAX_JOBS are kept. + */ +import { randomUUID } from 'node:crypto' +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { z } from 'zod' +import { failure, READ_ONLY, reply, UPDATES, WRITES, type ToolReply } from './reply.js' + +export const JOB_TOOLS = ['formrec_job_start', 'formrec_job_status', 'formrec_job_cancel'] as const +const MAX_JOBS = 100 +const KEEP_MS = 60 * 60 * 1000 + +/** What a job needs from the tool it runs: its own argument check and its handler (with the server's link fixing). */ +export interface JobTarget { + check(args: unknown): { ok: true; value: unknown } | { ok: false; error: string } + run(args: unknown, extra: Record): Promise +} + +interface Job { + id: string + tool: string + state: 'running' | 'done' | 'failed' | 'cancelled' + startedAt: string + endedAt?: string + progress?: { progress: number; total?: number; message?: string } + reply?: ToolReply + abort: AbortController + ended?: number +} + +// One table per process, so a job started on one MCP session can be polled from another. +const jobs = new Map() + +function prune(): void { + const now = Date.now() + for (const [id, j] of jobs) if (j.ended !== undefined && now - j.ended > KEEP_MS) jobs.delete(id) + if (jobs.size < MAX_JOBS) return + for (const [id, j] of [...jobs].filter(([, j]) => j.ended !== undefined).sort((a, b) => a[1].ended! - b[1].ended!)) { + if (jobs.size < MAX_JOBS) break + jobs.delete(id) + } +} + +/** The compact view of a job: the result as the tool gave it (structured when it has one, else its text). */ +function view(j: Job, withResult: boolean): Record { + const out: Record = { jobId: j.id, tool: j.tool, state: j.state, startedAt: j.startedAt } + if (j.endedAt) out['endedAt'] = j.endedAt + if (j.progress) out['progress'] = j.progress + if (withResult && j.reply) { + if (j.reply.isError) out['error'] = j.reply.content.map((c) => c.text).join('\n') + else out['result'] = j.reply.structuredContent ?? j.reply.content.map((c) => c.text).join('\n') + } + return out +} + +export function registerJobTools(server: McpServer, find: (tool: string) => JobTarget | string): void { + server.registerTool( + 'formrec_job_start', + { + title: 'Start a tool as a background job', + description: + 'Run any other FormREC tool (for example formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover, formrec_walkthrough_rerecord) in the background and answer at once with a jobId. Poll formrec_job_status every few seconds until state is done, failed or cancelled; the result is then exactly what the tool would have answered. Use it for anything that can take more than a few seconds.', + inputSchema: { + tool: z.string().min(1).max(80).describe('the tool to run, for example formrec_record'), + args: z.record(z.string(), z.unknown()).optional().describe('that tool\'s arguments'), + }, + annotations: WRITES, + }, + async (input, extra) => { + if (input.tool.startsWith('formrec_job_')) return failure(new Error('a job cannot start another job tool')) + const target = find(input.tool) + if (typeof target === 'string') return failure(new Error(target)) + const checked = target.check(input.args ?? {}) + if (!checked.ok) return failure(new Error(`${input.tool}: ${checked.error}`)) + prune() + if ([...jobs.values()].filter((j) => j.state === 'running').length >= 16) return failure(new Error('16 jobs are running already; wait for one to end')) + const job: Job = { id: `job-${randomUUID().slice(0, 12)}`, tool: input.tool, state: 'running', startedAt: new Date().toISOString(), abort: new AbortController() } + jobs.set(job.id, job) + const inner: Record = { + signal: job.abort.signal, + requestId: job.id, + authInfo: (extra as { authInfo?: unknown }).authInfo, + _meta: { progressToken: job.id }, + sendNotification: async (n: { method?: string; params?: { progress?: number; total?: number; message?: string } }) => { + if (n.method === 'notifications/progress' && n.params) job.progress = { progress: n.params.progress ?? 0, total: n.params.total, message: n.params.message } + }, + sendRequest: async () => { throw new Error('a background job cannot ask the client') }, + } + void target.run(checked.value, inner).then( + (r) => { job.reply = r; job.state = job.abort.signal.aborted ? 'cancelled' : r.isError ? 'failed' : 'done' }, + (e: unknown) => { job.reply = failure(e); job.state = job.abort.signal.aborted ? 'cancelled' : 'failed' }, + ).finally(() => { job.ended = Date.now(); job.endedAt = new Date(job.ended).toISOString() }) + return reply(() => ({ jobId: job.id, tool: job.tool, state: job.state, poll: 'formrec_job_status' })) + }, + ) + server.registerTool( + 'formrec_job_status', + { + title: 'Poll a background job', + description: 'A job\'s state (running, done, failed, cancelled), its latest progress, and once it ended the tool\'s result or error. Without jobId: every job of this server, newest first, without results.', + inputSchema: { jobId: z.string().max(60).optional().describe('the id formrec_job_start answered') }, + annotations: READ_ONLY, + }, + (input) => reply(() => { + if (!input.jobId) return { jobs: [...jobs.values()].reverse().map((j) => view(j, false)) } + const j = jobs.get(input.jobId) + if (!j) throw new Error(`no job ${input.jobId} (jobs are kept for an hour after they end)`) + return view(j, true) + }), + ) + server.registerTool( + 'formrec_job_cancel', + { + title: 'Cancel a background job', + description: 'Stop a running job, as cancelling the tool call would (formrec_record saves nothing when cancelled). A job that already ended is left as it is.', + inputSchema: { jobId: z.string().max(60).describe('the job to stop') }, + annotations: UPDATES, + }, + (input) => reply(() => { + const j = jobs.get(input.jobId) + if (!j) throw new Error(`no job ${input.jobId}`) + if (j.state === 'running') j.abort.abort() + return view(j, false) + }), + ) +} diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 9aa48e0..3cebcfa 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -21,6 +21,9 @@ import { DESTRUCTIVE, OPEN_WORLD, READ_ONLY, UPDATES, reply, type ToolReply } fr import { keyReply } from './player-links.js' import { DeleteOutput, DemosOutput, FormcutOutput, GetOutput, ListOutput, RecordOutput, RenameOutput, ValidateOutput } from './schemas.js' import { FEATURES } from '../features/index.js' +import { registerJobTools, JOB_TOOLS, type JobTarget } from './jobs.js' +import { registerWindowTools, WINDOW_TOOLS } from '../window/tools.js' +import { remoteCaller } from '../window/bridge.js' const walkInput = { walkthrough: z.record(z.string(), z.unknown()).optional().describe('the walkthrough object (see formrec_guide)'), @@ -40,8 +43,23 @@ export const CORE_TOOLS = [ 'formrec_delete', 'formrec_open_in_formcut', 'formrec_demos', + // Only where the server has a window caller (the app, `formrec mcp`): the window's commands and background jobs. + ...WINDOW_TOOLS, + ...JOB_TOOLS, ] as const +/** The ids a tool's arguments or answer name: the recordings a window should show again after an agent changed them. */ +function changedIds(args: unknown, out: ToolReply): string[] { + const ids: string[] = [] + const take = (v: unknown): void => { if (typeof v === 'string') ids.push(v); else if (Array.isArray(v)) for (const x of v) if (typeof x === 'string') ids.push(x) } + const a = (args && typeof args === 'object' ? args : {}) as Record + for (const k of ['id', 'ids', 'recordingId', 'recordingIds']) take(a[k]) + const s = out.structuredContent ?? {} + take(s['id']) + take((s['recording'] as { id?: unknown } | undefined)?.id) + return ids +} + /** * Which tools a server offers. Stdio, HTTP inside the app and `formrec mcp --http` offer all of them (no `ToolSet`); * the relay passes the subset a remote agent may use. Names not listed are not registered at all. @@ -72,19 +90,38 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {} const registered = new Map() const register = server.registerTool.bind(server) const base = (): Promise => resolvePlayerBase(deps.playerBase) + // What a background job runs (jobs.ts): the tool's own handler, after the consent formrec_job_start already passed. + const runners = new Map() server.registerTool = ((name: string, ...rest: unknown[]) => { // Every answer's player links get their form in one place (player-links.ts): no run token, a player key per recording. const handler = rest[rest.length - 1] as (...args: unknown[]) => unknown - const config = rest[0] as { title?: string; annotations?: { readOnlyHint?: boolean } } | undefined - const asks = consent !== undefined && config?.annotations?.readOnlyHint !== true + const config = rest[0] as { title?: string; inputSchema?: Record | z.ZodType; annotations?: { readOnlyHint?: boolean } } | undefined + const reads = config?.annotations?.readOnlyHint === true + const asks = consent !== undefined && !reads + const finish = async (args: unknown, out: ToolReply): Promise => { + const keyedOut = await keyReply(out, base, deps.library.dataDir) + // An agent's change shows in the open window at once (window/bridge.ts `changed`). + if (!reads && !keyedOut.isError && deps.window && !name.startsWith('formrec_window_') && !name.startsWith('formrec_job_')) deps.window.changed(changedIds(args, keyedOut), name) + return keyedOut + } const keyed = async (...args: unknown[]): Promise => { if (asks) { const extra = args[args.length - 1] as { authInfo?: { token?: string } } | undefined const why = await consent({ agent: server.server.getClientVersion()?.name ?? '', tool: name, title: config?.title, args: args.length > 1 ? args[0] : undefined, token: extra?.authInfo?.token }) if (why) return { content: [{ type: 'text', text: why }], isError: true } } - return keyReply((await handler(...args)) as ToolReply, base, deps.library.dataDir) + return finish(args.length > 1 ? args[0] : undefined, (await handler(...args)) as ToolReply) } + const shape = config?.inputSchema + const schema = shape === undefined ? undefined : shape instanceof z.ZodType ? shape : z.object(shape) + runners.set(name, { + check: (args) => { + if (!schema) return { ok: true, value: undefined } + const parsed = schema.safeParse(args) + return parsed.success ? { ok: true, value: parsed.data } : { ok: false, error: parsed.error.issues.map((i) => `${i.path.join('.') || 'args'}: ${i.message}`).join('; ') } + }, + run: async (args, extra) => finish(args, (await (schema ? handler(args, extra) : handler(extra))) as ToolReply), + }) const tool = (register as (n: string, ...r: unknown[]) => RegisteredTool)(name, ...rest.slice(0, -1), keyed) registered.set(name, tool) return tool @@ -224,6 +261,17 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {} }, () => reply(() => demosTool(deps), { structured: true }), ) + if (deps.window) { + registerWindowTools(server, deps.window, () => server.server.getClientVersion()?.name ?? '') + // A job may run only what this server offers: not a tool removed below, nor one its scope disabled. + registerJobTools(server, (tool) => { + const r = registered.get(tool) + const runner = runners.get(tool) + if (!r || !runner) return `no tool ${tool} on this server` + if (!r.enabled) return `${tool} is not offered on this server` + return runner + }) + } if (tools.core) { for (const [name, tool] of [...registered]) { if (tools.core.includes(name)) continue @@ -246,5 +294,7 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {} } export async function serveMcp(deps: ToolDeps, version: string): Promise { - await buildServer(deps, version, {}, remoteGate(deps.library.dataDir)).connect(new StdioServerTransport()) + // Window commands reach the running app's window over its loopback API (window/bridge.ts remoteCaller). + const withWindow: ToolDeps = { ...deps, window: deps.window ?? remoteCaller(deps.library.dataDir) } + await buildServer(withWindow, version, {}, remoteGate(deps.library.dataDir)).connect(new StdioServerTransport()) } diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index 0286c02..96f9983 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -30,6 +30,8 @@ export interface ToolDeps { demosDir?: string /** Open a recording in FormCut (tests); default: find FormCut's engine and call it over JSON-RPC. */ formcut?: (rec: Recording) => Promise<{ projectId: string; clips: number }> + /** The open window's commands (window/bridge.ts). Given: formrec_window_* and formrec_job_* are offered, and changes are announced. */ + window?: import('../window/bridge.js').WindowCaller } export type PlayerBase = string | (() => Promise) diff --git a/src/window/bridge.ts b/src/window/bridge.ts new file mode 100644 index 0000000..ed65a92 --- /dev/null +++ b/src/window/bridge.ts @@ -0,0 +1,237 @@ +/** + * The agent bridge to the open window: the app's whole command registry (web/src/features/registry.ts `commands`, + * every menu item, sidebar page, recording action, player control and client preference) offered to agents, as + * FormDeck's list_commands and run_command and FormCite's window_commands do. + * + * The window keeps `GET /api/window/stream` open (server-sent events read with fetch, as the consent stream is, since + * an EventSource cannot send the token). The engine sends it calls ({ type: 'call', callId, op, ... }) and the window + * answers each with `POST /api/window/result`. The window that last took focus answers; the others are spares. The + * same stream carries `changed` notices, sent after an agent's tool changed something, so the window shows the change + * at once (web/src/agent-bridge.ts). + * + * Routes (behind the run's token, like every /api route): + * GET /api/window/stream the window's end of the bridge + * POST /api/window/result { callId, ok, value?, error? } + * POST /api/window/focus { windowId } + * GET /api/window/commands?query=&id= the catalogue, or one command described (for `formrec mcp` over stdio) + * POST /api/window/run { id, args?, agent? } with the approval below (for `formrec mcp` over stdio) + * POST /api/window/changed { ids, tool } a change made by another process (`formrec mcp` over stdio) + * + * Approval: a command whose risk is destructive, external or privacy (deleting, publishing outside this computer, the + * camera, microphone or screen) asks the person in the window every time an agent runs it, through the dock's consent + * dialog, whoever the agent is. Outside agents are also asked once for the tool itself by the MCP consent gate. + */ +import { randomUUID } from 'node:crypto' +import http from 'node:http' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { readJsonBody } from '../server/files.js' +import { readConsent, type ConsentBroker } from '../mcp/consent.js' +import { liveServers } from '../store/server-file.js' +import { loadToken } from '../server/token.js' + +export const CALL_MS = 15_000 +const RISKY = new Set(['destructive', 'external', 'privacy']) + +export type WindowEvent = + | { type: 'hello'; windowId: string } + | { type: 'call'; callId: string; op: 'list' | 'describe' | 'run'; id?: string; args?: Record; query?: string } + | { type: 'changed'; ids: string[]; tool: string } + +/** What `describe` answers for one command (the window builds it, web/src/agent-bridge.ts). */ +export interface CommandInfo { + id: string + label: string + risk: string + unavailable?: string + params?: Record +} + +/** What the MCP tools call: in the app the bridge itself, from `formrec mcp` the running app over HTTP. */ +export interface WindowCaller { + commands(input: { query?: string; id?: string; limit?: number }): Promise + run(input: { id: string; args?: Record; agent: string }): Promise + /** An agent changed these recordings (or the library, when ids is empty); open windows show it. Never throws. */ + changed(ids: string[], tool: string): void +} + +export class NoWindow extends Error { + constructor() { + super('No FormREC window is open, so window commands cannot run. Ask the person to open FormREC (formrec, or the desktop app), or use the engine tools, which work without a window.') + } +} + +interface Win { send(event: WindowEvent): void; focusedAt: number } + +export class WindowBridge { + private readonly windows = new Map() + private readonly pending = new Map() + + open(): number { + return this.windows.size + } + + /** The window's end: an event stream that lives as long as the request. */ + stream(req: IncomingMessage, res: ServerResponse): void { + const windowId = randomUUID() + res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }) + const send = (event: WindowEvent): void => { if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`) } + this.windows.set(windowId, { send, focusedAt: Date.now() }) + send({ type: 'hello', windowId }) + const beat = setInterval(() => { if (!res.writableEnded) res.write(': keep\n\n') }, 25_000) + beat.unref() + req.on('close', () => { clearInterval(beat); this.windows.delete(windowId) }) + } + + focus(windowId: string): boolean { + const w = this.windows.get(windowId) + if (w) w.focusedAt = Date.now() + return w !== undefined + } + + result(body: { callId?: unknown; ok?: unknown; value?: unknown; error?: unknown }): boolean { + const p = typeof body.callId === 'string' ? this.pending.get(body.callId) : undefined + if (!p) return false + this.pending.delete(body.callId as string) + clearTimeout(p.timer) + if (body.ok === true) p.resolve(body.value) + else p.reject(new Error(typeof body.error === 'string' && body.error ? body.error.slice(0, 2000) : 'the window refused the command')) + return true + } + + /** Ask the window that took focus last. */ + call(op: 'list' | 'describe' | 'run', payload: { id?: string; args?: Record; query?: string }, ms = CALL_MS): Promise { + const front = [...this.windows.values()].sort((a, b) => b.focusedAt - a.focusedAt)[0] + if (!front) return Promise.reject(new NoWindow()) + const callId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(callId) + reject(new Error(`The FormREC window did not answer within ${Math.round(ms / 1000)} seconds. It may be busy or hidden; if the command was started it may still finish there.`)) + }, ms) + timer.unref() + this.pending.set(callId, { resolve, reject, timer }) + front.send({ type: 'call', callId, op, ...payload }) + }) + } + + changed(ids: string[], tool: string): void { + const clean = [...new Set(ids.filter((i) => typeof i === 'string' && /^[a-z0-9][a-z0-9-]{0,80}$/.test(i)))].slice(0, 50) + for (const w of this.windows.values()) w.send({ type: 'changed', ids: clean, tool }) + } +} + +/** Runs a command in the window, asking the person first when its risk calls for it. */ +export async function runWithApproval(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string, input: { id: string; args?: Record; agent: string }): Promise { + const info = (await bridge.call('describe', { id: input.id, args: input.args ?? {} })) as CommandInfo + if (info.unavailable) throw new Error(`${input.id} cannot run now: ${info.unavailable}`) + if (RISKY.has(info.risk)) { + if ((await readConsent(dataDir)).policy === 'blocked') throw new Error(`Outside agents are blocked in FormREC (Preferences, Agents), so ${input.id} did not run.`) + if (!consent) throw new Error(`${input.id} needs the person's approval and this server cannot ask; run it from the FormREC app's MCP.`) + const name = info.label.length <= 60 ? info.label : input.id + const verdict = await consent.ask({ agent: input.agent, tool: 'formrec_window_command_run', title: `Run ${name} (${info.risk})`, args: { command: input.id, ...(input.args ?? {}) } }) + if (verdict !== 'allow') { + const why = verdict === 'deny' ? 'The person declined it' : verdict === 'timeout' ? 'The person did not answer in time' : 'No FormREC window could ask the person' + throw new Error(`${why}, so ${input.id} (${info.risk}) did not run. Do not retry without asking them.`) + } + } + const value = await bridge.call('run', { id: input.id, args: input.args ?? {} }) + return { ok: true, id: input.id, risk: info.risk, ...(value === undefined || value === null ? {} : { value }) } +} + +export function localCaller(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string): WindowCaller { + return { + commands: (input) => bridge.call(input.id ? 'describe' : 'list', input.id ? { id: input.id } : { query: input.query, args: { limit: input.limit ?? 200 } }), + run: (input) => runWithApproval(bridge, consent, dataDir, input), + changed: (ids, tool) => bridge.changed(ids, tool), + } +} + +function request(port: number, token: string, method: string, path: string, payload?: unknown): Promise { + const body = payload === undefined ? '' : JSON.stringify(payload) + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, path, method, headers: { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}) } }, (res) => { + const chunks: Buffer[] = [] + res.on('data', (c: Buffer) => chunks.push(c)) + res.on('end', () => { + let value: unknown + try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { value = undefined } + if ((res.statusCode ?? 500) >= 400) reject(new Error(typeof (value as { error?: unknown })?.error === 'string' ? (value as { error: string }).error : `the FormREC app answered ${res.statusCode}`)) + else resolve(value) + }) + res.on('error', reject) + }) + req.setTimeout(200_000, () => req.destroy(new Error('the FormREC app did not answer'))) + req.on('error', reject) + req.end(body) + }) +} + +/** For `formrec mcp` (stdio or --http on its own port): the running app's bridge, found through its server file. */ +export function remoteCaller(dataDir: string): WindowCaller { + const target = async (): Promise<{ port: number; token: string }> => { + const token = await loadToken(dataDir).catch(() => '') + const server = token ? (await liveServers(dataDir, token).catch(() => []))[0] : undefined + if (!server) throw new NoWindow() + return { port: server.port, token } + } + return { + async commands(input) { + const t = await target() + const q = new URLSearchParams() + if (input.query) q.set('query', input.query) + if (input.id) q.set('id', input.id) + if (input.limit) q.set('limit', String(input.limit)) + return request(t.port, t.token, 'GET', `/api/window/commands?${q}`) + }, + async run(input) { + const t = await target() + return request(t.port, t.token, 'POST', '/api/window/run', input) + }, + changed(ids, tool) { + void target().then((t) => request(t.port, t.token, 'POST', '/api/window/changed', { ids, tool }), () => undefined).catch(() => undefined) + }, + } +} + +function sendJson(res: ServerResponse, status: number, body: unknown): void { + res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }).end(JSON.stringify(body)) +} + +const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : {}) + +/** The /api/window routes. */ +export function windowRoutes(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string) { + return async (req: IncomingMessage, res: ServerResponse, parts: string[], url: URL): Promise => { + if (parts[1] !== 'window' || parts.length !== 3) return false + const what = parts[2] + const method = req.method ?? 'GET' + try { + if (what === 'stream' && method === 'GET') { bridge.stream(req, res); return true } + if (what === 'result' && method === 'POST') { sendJson(res, bridge.result(obj(await readJsonBody(req, 1024 * 1024))) ? 200 : 404, {}); return true } + if (what === 'focus' && method === 'POST') { const b = obj(await readJsonBody(req, 4096)); sendJson(res, 200, { ok: bridge.focus(String(b['windowId'] ?? '')) }); return true } + if (what === 'commands' && method === 'GET') { + const id = url.searchParams.get('id') ?? undefined + const limit = Number(url.searchParams.get('limit') ?? 200) + sendJson(res, 200, await localCaller(bridge, consent, dataDir).commands({ id, query: url.searchParams.get('query') ?? undefined, limit })) + return true + } + if (what === 'run' && method === 'POST') { + const b = obj(await readJsonBody(req, 256 * 1024)) + if (typeof b['id'] !== 'string' || !b['id']) { sendJson(res, 400, { error: 'id is required' }); return true } + const agent = typeof b['agent'] === 'string' ? b['agent'] : '' + sendJson(res, 200, await runWithApproval(bridge, consent, dataDir, { id: b['id'], args: obj(b['args']), agent })) + return true + } + if (what === 'changed' && method === 'POST') { + const b = obj(await readJsonBody(req, 64 * 1024)) + bridge.changed(Array.isArray(b['ids']) ? (b['ids'] as unknown[]).filter((i): i is string => typeof i === 'string') : [], typeof b['tool'] === 'string' ? b['tool'].slice(0, 80) : '') + sendJson(res, 200, {}) + return true + } + } catch (error) { + sendJson(res, error instanceof NoWindow ? 409 : 400, { error: (error as Error).message }) + return true + } + return false + } +} diff --git a/src/window/tools.ts b/src/window/tools.ts new file mode 100644 index 0000000..d3326f2 --- /dev/null +++ b/src/window/tools.ts @@ -0,0 +1,42 @@ +/** + * formrec_window_commands and formrec_window_command_run: the open window's command registry for agents (bridge.ts). + * Registered by buildServer when it is given a WindowCaller; the relay's bridge is not (no window there). + */ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { z } from 'zod' +import { READ_ONLY, reply, UPDATES } from '../mcp/reply.js' +import type { WindowCaller } from './bridge.js' + +export const WINDOW_TOOLS = ['formrec_window_commands', 'formrec_window_command_run'] as const + +export function registerWindowTools(server: McpServer, caller: WindowCaller, agent: () => string): void { + server.registerTool( + 'formrec_window_commands', + { + title: 'List or describe the window\'s commands', + description: + 'Every action a person can take in the open FormREC window, as commands: pages (nav.go), menus (file.*, view.*, help.*), the studio (studio.*: start, pause, stop, camera...), drawing (annotate.*), the player (player.play, player.seek, player.panel), recording actions from the library card and player menus (recording.action), Preferences (settings.open, prefs.get, prefs.set) and each feature\'s commands. Without id: a compact list (id, label, args as `name?: type`, risk), filtered by query words. With id: that command\'s full arguments (types, allowed values, ranges) and whether it can run now. window says which page is open. Use the engine tools for data (they work without a window); use these to make the window do what the person would click.', + inputSchema: { + query: z.string().max(200).optional().describe('words that must all appear in the id or label, for example "studio" or "theme"'), + id: z.string().max(120).optional().describe('describe this one command'), + limit: z.number().int().min(1).max(500).optional().describe('at most this many (default 200)'), + }, + annotations: READ_ONLY, + }, + (input) => reply(() => caller.commands(input)), + ) + server.registerTool( + 'formrec_window_command_run', + { + title: 'Run a window command', + description: + 'Run one command in the open FormREC window by id with its args (see formrec_window_commands), exactly as if the person chose it: the window shows the result at once. Commands that delete, publish outside this computer, or turn on the camera, microphone or screen ask the person in the window every time and fail if they decline. Returns { ok, id, risk, value? } with what the command reports (for example prefs.get\'s values, or the page it opened). Fails when no window is open or the command cannot run now (no studio open, no recording open), saying why.', + inputSchema: { + id: z.string().min(1).max(120).describe('the command id, for example nav.go, studio.start or recording.action'), + args: z.record(z.string(), z.unknown()).optional().describe('the command\'s arguments, for example { "page": "library" }'), + }, + annotations: UPDATES, + }, + (input) => reply(() => caller.run({ id: input.id, args: input.args, agent: agent() })), + ) +} From 064290b0ce923623c1bea9215d9ce5a2233296bd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:13:35 -0500 Subject: [PATCH 02/25] feat(web): every page, menu row, recording action, player control and preference is a typed command the agent bridge runs, and agents' changes show at once (0.12.0) The command registry had about 60 commands with no arguments, and much of what a person clicks was not in it: the sidebar's pages, the menu rows that only had an act, the library card and player More menus, the player's transport and panels, Preferences and the client's own settings. - registry.ts: a Command may declare typed params (string, number, boolean, enums fixed or computed at run time, ranges), a risk (read, change, destructive, external, privacy) and why it cannot run now; run takes the arguments and may return a small JSON value. - agent-commands.ts: nav.go (31 pages, including a recording, a demo, the tour, the editors), window.state, recording.action (each recordingActions entry, with its own risk), player.play, player.pause, player.seek (keeps playing or paused unless told), player.panel, settings.open, prefs.get, prefs.set (theme, default mode, countdown, limit, check-in, hidden controls, quality, dock, menus in the window), studio.configure (layout, target, quality), and every File, View and Help row that was not a command. The commands other modules register get a risk: studio.start, camera, screenshot and the desktop controls are privacy, cancel and rewind are destructive, so the person is asked before any of them. - agent-bridge.ts: the window's end of /api/window/stream; it lists commands compactly (args as `name?: type`), describes one in full, checks arguments before running, and answers with the command's value cut at 16 KB. - app.ts: on an agent's change the counts follow and the library, Home, Shared, Notifications, Insights or the open player is drawn again (the player keeps its moment and its paused state); a burst is drawn once; the studio and the editors are never redrawn under the person. Checked live with a window in Chromium and an outside agent over /mcp and over stdio: every sidebar page, the tour, player seek and panels, theme and Preferences, File > New Audio Recording, studio layout, a declined studio.start, an import, rename and comment shown at once, a trash that asked first, and an export job polled to done. --- web/src/agent-bridge.ts | 134 ++++++++++++++ web/src/agent-commands.ts | 337 +++++++++++++++++++++++++++++++++++ web/src/app.ts | 39 ++++ web/src/features/registry.ts | 30 +++- 4 files changed, 538 insertions(+), 2 deletions(-) create mode 100644 web/src/agent-bridge.ts create mode 100644 web/src/agent-commands.ts diff --git a/web/src/agent-bridge.ts b/web/src/agent-bridge.ts new file mode 100644 index 0000000..a0ebad5 --- /dev/null +++ b/web/src/agent-bridge.ts @@ -0,0 +1,134 @@ +/** + * The window's end of the agent bridge (src/window/bridge.ts): it keeps /api/window/stream open, answers the engine's + * calls (list the commands, describe one, run one) from the command registry (./features/registry.ts, filled by every + * feature and by ./agent-commands.ts), and turns the engine's `changed` notices into a 'formrec:agent-change' event + * that app.ts answers by showing the change. Arguments are checked here against each command's params before it runs. + * The person's approval for risky commands is asked by the engine first (the dock's consent dialog). + */ +import { authHeaders } from './api.js' +import { commands, type Command, type CommandParam } from './features/registry.js' +import { riskOf } from './agent-commands.js' + +type Call = { type: 'call'; callId: string; op: 'list' | 'describe' | 'run'; id?: string; args?: Record; query?: string } +type Event = { type: 'hello'; windowId: string } | Call | { type: 'changed'; ids: string[]; tool: string } + +/** Agents' changes, for app.ts: the recordings named (empty: the library as a whole) and the tool that changed them. */ +export const AGENT_CHANGE = 'formrec:agent-change' + +const MAX_VALUE = 16_000 +let windowId = '' + +const values = (p: CommandParam): readonly string[] | undefined => (typeof p.enum === 'function' ? p.enum() : p.enum) + +/** `name?: type` with the allowed values when there are few, as FormDeck's list_commands shows them. */ +function brief(params: Command['params']): string { + return Object.entries(params ?? {}).map(([k, p]) => { + const e = values(p) + const type = e && e.length <= 8 ? e.join('|') : e ? `${p.type} (${e.length} values, describe)` : p.type + const range = p.min !== undefined || p.max !== undefined ? ` ${p.min ?? ''}..${p.max ?? ''}` : '' + return `${k}${p.optional ? '?' : ''}: ${type}${range}` + }).join(', ') +} + +function describe(c: Command, args: Record = {}): Record { + const params = Object.fromEntries(Object.entries(c.params ?? {}).map(([k, p]) => [k, { ...p, enum: values(p) }])) + const unavailable = c.unavailable?.() + return { id: c.id, label: c.label, risk: riskOf(c, args), ...(c.shortcut ? { shortcut: c.shortcut } : {}), ...(unavailable ? { unavailable } : {}), ...(c.params ? { params } : {}) } +} + +/** The problems with these arguments, or '' when they are right. */ +export function checkArgs(c: Command, args: Record): string { + const params = c.params ?? {} + const problems: string[] = [] + for (const k of Object.keys(args)) if (!(k in params)) problems.push(`${k} is not an argument of ${c.id}${Object.keys(params).length ? ` (it takes ${Object.keys(params).join(', ')})` : ' (it takes none)'}`) + for (const [k, p] of Object.entries(params)) { + const v = args[k] + if (v === undefined || v === null) { if (!p.optional) problems.push(`${k} is required`); continue } + if (typeof v !== p.type) { problems.push(`${k} must be a ${p.type}`); continue } + if (p.type === 'number' && (!Number.isFinite(v) || (p.min !== undefined && (v as number) < p.min) || (p.max !== undefined && (v as number) > p.max))) problems.push(`${k} must be a number from ${p.min ?? '-'} to ${p.max ?? '-'}`) + const e = values(p) + if (e && !e.includes(v as string)) problems.push(`${k} must be one of ${e.join(', ')}`) + } + return problems.join('; ') +} + +function compact(value: unknown): unknown { + if (value === undefined) return undefined + let text: string + try { text = JSON.stringify(value) } catch { return undefined } + if (text === undefined) return undefined + return text.length <= MAX_VALUE ? JSON.parse(text) : { truncated: true, text: text.slice(0, MAX_VALUE) } +} + +async function answer(call: Call): Promise { + if (call.op === 'list') { + const words = (call.query ?? '').toLowerCase().split(/\s+/).filter(Boolean) + const limit = Math.max(1, Math.min(500, Number(call.args?.['limit'] ?? 200) || 200)) + const all = commands.all().filter((c) => words.every((w) => `${c.id} ${c.label}`.toLowerCase().includes(w))) + const state = commands.all().find((c) => c.id === 'window.state') + return { + window: state ? await state.run() : { page: location.hash.slice(1) || '/' }, + count: all.length, + commands: all.slice(0, limit).map((c) => { + const args = brief(c.params) + return { id: c.id, label: c.label, risk: riskOf(c, {}), ...(args ? { args } : {}) } + }), + ...(all.length > limit ? { more: all.length - limit } : {}), + } + } + const c = commands.all().find((x) => x.id === call.id) + if (!c) throw new Error(`no command ${call.id ?? ''} in this window; formrec_window_commands lists them`) + const args = call.args ?? {} + if (call.op === 'describe') return describe(c, args) + const why = c.unavailable?.() + if (why) throw new Error(`${c.id} cannot run now: ${why}`) + const wrong = checkArgs(c, args) + if (wrong) throw new Error(wrong) + return compact(await c.run(args)) +} + +async function post(path: string, body: unknown): Promise { + await fetch(path, { method: 'POST', headers: { ...authHeaders(), 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).catch(() => undefined) +} + +function take(event: Event): void { + if (event.type === 'hello') { windowId = event.windowId; if (document.hasFocus()) void post('/api/window/focus', { windowId }); return } + if (event.type === 'changed') { window.dispatchEvent(new CustomEvent(AGENT_CHANGE, { detail: { ids: event.ids, tool: event.tool } })); return } + void answer(event).then( + (value) => post('/api/window/result', { callId: event.callId, ok: true, value }), + (error: unknown) => post('/api/window/result', { callId: event.callId, ok: false, error: error instanceof Error ? error.message : String(error) }), + ) +} + +/** Opens the bridge and keeps it open (it reconnects after the engine restarts). */ +export function startAgentBridge(): void { + window.addEventListener('focus', () => { if (windowId) void post('/api/window/focus', { windowId }) }) + void (async () => { + for (;;) { + try { + const r = await fetch('/api/window/stream', { headers: authHeaders() }) + if (r.ok && r.body) { + const reader = r.body.pipeThrough(new TextDecoderStream()).getReader() + let held = '' + for (;;) { + const { value, done } = await reader.read() + if (done) break + held += value + let cut = held.indexOf('\n\n') + while (cut >= 0) { + const block = held.slice(0, cut) + held = held.slice(cut + 2) + const data = block.split('\n').filter((l) => l.startsWith('data: ')).map((l) => l.slice(6)).join('\n') + if (data) { try { take(JSON.parse(data) as Event) } catch { /* a malformed event is skipped */ } } + cut = held.indexOf('\n\n') + } + } + } + } catch { + // The engine is restarting or the workspace switched; try again shortly. + } + windowId = '' + await new Promise((r) => setTimeout(r, 3000)) + } + })() +} diff --git a/web/src/agent-commands.ts b/web/src/agent-commands.ts new file mode 100644 index 0000000..1e8785b --- /dev/null +++ b/web/src/agent-commands.ts @@ -0,0 +1,337 @@ +/** + * Every action a person can take in the window, as a command in the one registry (./features/registry.ts), so agents + * reach all of it through the bridge (./agent-bridge.ts, formrec_window_commands and formrec_window_command_run): + * - nav.go: every page of the sidebar, Home, the Library tabs, the studio's modes and layouts, a recording, a demo + * (the tour), the editor, annotate, clips and the interactive demo; + * - recording.action: every action of a library card's menu and the player's More menu (recordingActions); + * - player.*: play, pause, seek and the side panels of the open player; + * - settings.open, prefs.get and prefs.set: Preferences and the client's own settings (theme, default mode, the + * studio's countdown, limit, check-in, hidden controls and quality, the dock, menus in the window); + * - studio.configure: the studio's layout, capture target and quality; + * - window.state: which page is open; + * - each menu bar row that is not a command yet (File, View, Help), under its menu id. + * It also gives the commands other modules registered without a risk the risk the bridge asks the person about. + * Nothing here draws anything; it loads after the features (app.ts) so every registry is filled. + */ +import { api } from './api.js' +import { DEMOS } from './demos.js' +import { MENUS } from './menus.js' +import { isCommand, isSub, type MenuItem } from './menu.js' +import { openSettings } from './settings.js' +import { setTheme, themeMode, type ThemeMode } from './theme.js' +import { defaultMode, setDefaultMode, type StudioMode } from './prefs.js' +import { loadSettings, saveSettings, TWO_HOURS } from './studio-settings.js' +import { canChooseMenus, menusInWindow, setMenusInWindow, showDock } from './preferences.js' +import { commands, playerLayers, recordingActions, settingsSections, type Command, type CommandRisk, type PlayerContext } from './features/registry.js' + +const ID = /^[a-z0-9][a-z0-9-]{0,80}$/ + +/** The risk of the commands other modules registered (the bridge asks the person before destructive, external and privacy ones). */ +const RISKS: Record = { + 'app.home': 'read', 'app.preferences': 'read', 'view.dock': 'read', 'view.menus-in-window': 'change', + 'studio.open': 'read', 'studio.start': 'privacy', 'studio.start-stop': 'privacy', 'studio.restart': 'privacy', 'studio.camera': 'privacy', + 'studio.screenshot': 'privacy', 'studio.resume': 'privacy', 'studio.toggle-pause': 'privacy', 'studio.cancel': 'destructive', + 'studio.stop': 'change', 'studio.pause': 'change', 'studio.rewind': 'destructive', 'studio.notes': 'change', + 'agents.rotate-player-links': 'destructive', 'documents-clear-recent': 'destructive', 'documents-reveal': 'read', + 'engage.insights': 'read', 'engage.notifications': 'read', 'engage.history': 'read', 'share.shared': 'read', 'ai.ask': 'read', + 'meetings.open': 'read', 'integrations.meetings': 'read', 'library-trash': 'read', 'library-history': 'read', +} + +/** Recording actions that remove, publish or send. */ +const ACTION_RISKS: Record = { + 'library-trash': 'destructive', share: 'external', 'ai-apply-jira': 'external', 'documents-reveal': 'read', +} + +export function riskOf(c: Command, args: Record): CommandRisk { + if (typeof c.risk === 'function') return c.risk(args) + return c.risk ?? RISKS[c.id] ?? (c.id.startsWith('desktop.') ? 'privacy' : 'change') +} + +// ---------- pages ---------- + +/** Every page, with the address it opens; `id` pages need a recording (or demo) id. */ +const PAGES: Record = { + home: { hash: '#/' }, + library: { hash: '#/library' }, + 'library-videos': { hash: '#/library/videos' }, + 'library-history': { hash: '#/library/history' }, + 'library-archive': { hash: '#/library/archive' }, + 'library-trash': { hash: '#/library/trash' }, + 'library-team': { hash: '#/library/team' }, + studio: { hash: '#/record' }, + screen: { hash: '#/record?mode=screen' }, + camera: { hash: '#/record?mode=camera' }, + audio: { hash: '#/record?mode=audio' }, + 'studio-screen-only': { hash: '#/record/screen-only' }, + 'studio-meeting': { hash: '#/record/meeting' }, + 'studio-presentation': { hash: '#/record/presentation' }, + 'studio-canvas': { hash: '#/record/canvas' }, + effects: { hash: '#/effects' }, + shared: { hash: '#/shared' }, + notifications: { hash: '#/notifications' }, + insights: { hash: '#/insights' }, + 'recently-watched': { hash: '#/history' }, + meetings: { hash: '#/meetings' }, + ask: { hash: '#/ask' }, + tour: { hash: '#/demo/self-tour' }, + demo: { hash: '#/demo/', id: 'demo' }, + recording: { hash: '#/f/', id: 'recording' }, + edit: { hash: '#/edit/', id: 'recording' }, + annotate: { hash: '#/annotate/', id: 'recording' }, + clips: { hash: '#/clips/', id: 'recording' }, + interactive: { hash: '#/interactive/', id: 'recording' }, + 'team-recording': { hash: '#/team/', id: 'recording' }, + playlist: { hash: '#/playlist/', id: 'playlist' }, +} + +const str = (v: unknown): string => (typeof v === 'string' ? v : '') + +/** Waits for the route to draw (the router replaces #view's children), at most two seconds. */ +function drawn(): Promise { + const view = document.getElementById('view') + if (!view) return Promise.resolve() + return new Promise((resolve) => { + const done = (): void => { observer.disconnect(); clearTimeout(timer); resolve() } + const observer = new MutationObserver(done) + observer.observe(view, { childList: true }) + const timer = setTimeout(done, 2000) + }) +} + +async function go(hash: string): Promise<{ page: string }> { + if (location.hash === hash || (hash === '#/' && location.hash === '')) return { page: hash.slice(1) || '/' } + const wait = drawn() + location.hash = hash + await wait + return { page: location.hash.slice(1) || '/' } +} + +commands.add({ + id: 'nav.go', + label: 'Go to a page (Home, Library, Studio, Shared, Notifications, Insights, Meetings, Ask, a recording, a demo...)', + risk: 'read', + params: { + page: { type: 'string', enum: Object.keys(PAGES), description: 'the page; recording, edit, annotate, clips, interactive and team-recording need id, demo needs id, playlist needs id' }, + id: { type: 'string', optional: true, description: 'the recording id (formrec_list), demo id (formrec_demos) or playlist id' }, + }, + run: (args = {}) => { + const page = PAGES[str(args['page'])] + if (!page) throw new Error('unknown page') + if (!page.id) return go(page.hash) + const id = str(args['id']) + if (!ID.test(id)) throw new Error(`page ${str(args['page'])} needs id`) + if (page.id === 'demo' && !DEMOS.some((d) => d.id === id)) throw new Error(`no demo ${id}; the demos are ${DEMOS.map((d) => d.id).join(', ')}`) + return go(`${page.hash}${encodeURIComponent(id)}`) + }, +}) + +commands.add({ + id: 'window.state', + label: 'Which page the window shows', + risk: 'read', + run: () => ({ + page: location.hash.slice(1) || '/', + title: document.querySelector('[data-title]')?.textContent ?? '', + recording: /^#\/(?:f|edit|annotate|clips|interactive|team)\/([a-z0-9-]+)/.exec(location.hash)?.[1] ?? null, + player: player ? { atMs: Math.round(player.now()), playing: playing(player) } : null, + dock: document.documentElement.getAttribute('data-ft-dock') === 'open', + settingsOpen: !!document.querySelector('dialog[open]'), + }), +}) + +// ---------- recording actions (library card menus, the player's More menu) ---------- + +commands.add({ + id: 'recording.action', + label: 'Run a recording action of the library card and player menus (Share, Edit, Duplicate, Rename, Export, Move to Trash...)', + params: { + id: { type: 'string', description: 'the recording id' }, + action: { type: 'string', enum: () => recordingActions.all().map((a) => a.id), description: 'the action, as the menus list it' }, + }, + risk: (args) => ACTION_RISKS[str(args['action'])] ?? 'change', + run: async (args = {}) => { + const id = str(args['id']) + if (!ID.test(id)) throw new Error('id is not a recording id') + const action = recordingActions.all().find((a) => a.id === str(args['action'])) + if (!action) throw new Error('unknown action') + const rec = await api.get(id).catch(() => { throw new Error(`no recording ${id}`) }) + if (action.when && !action.when(rec)) throw new Error(`${action.id} does not apply to this recording`) + await action.run(rec) + return { action: action.id, recording: id, page: location.hash.slice(1) || '/' } + }, +}) + +// ---------- the open player ---------- + +let player: PlayerContext | null = null +let resumeAt: { id: string; ms: number; playing: boolean } | null = null + +const playing = (ctx: PlayerContext): boolean => (ctx.video ? !ctx.video.paused : ctx.media().some((m) => !m.paused)) + +/** Seek, then keep playing or paused as asked (the timeline's seek always plays, as a chapter click does). */ +function seekTo(ctx: PlayerContext, ms: number, play: boolean): void { + ctx.seek(ms) + if (!play) ctx.pause() +} + +/** Kept across an agent's change that redraws the player (app.ts): the new player starts where the old one was, playing or not. */ +export function holdPlayerTime(): void { + if (player && !player.demo) resumeAt = { id: player.rec.id, ms: player.now(), playing: playing(player) } +} + +playerLayers.add({ + id: 'agent-player', + order: 9999, + demo: true, + place: 'stage', + render: (ctx) => { + player = ctx + if (resumeAt && resumeAt.id === ctx.rec.id) { const { ms, playing: was } = resumeAt; resumeAt = null; queueMicrotask(() => seekTo(ctx, ms, was)) } + ctx.signal.addEventListener('abort', () => { if (player === ctx) player = null }) + return null + }, +}) + +const needPlayer = (): string | undefined => (player ? undefined : 'no recording or demo is open in the player (nav.go page recording)') +const open = (): PlayerContext => { if (!player) throw new Error('no player is open'); return player } + +commands.add({ id: 'player.play', label: 'Player: play', risk: 'read', unavailable: needPlayer, run: () => { open().play(); return { atMs: Math.round(open().now()) } } }) +commands.add({ id: 'player.pause', label: 'Player: pause', risk: 'read', unavailable: needPlayer, run: () => { open().pause(); return { atMs: Math.round(open().now()) } } }) +commands.add({ + id: 'player.seek', + label: 'Player: go to a moment', + risk: 'read', + unavailable: needPlayer, + params: { + ms: { type: 'number', min: 0, description: 'milliseconds from the start' }, + play: { type: 'boolean', optional: true, description: 'play from there (default: keep playing or paused as now)' }, + }, + run: (args = {}) => { + const ctx = open() + seekTo(ctx, Number(args['ms']), typeof args['play'] === 'boolean' ? args['play'] : playing(ctx)) + return { atMs: Math.round(ctx.now()), playing: playing(ctx) } + }, +}) +commands.add({ + id: 'player.panel', + label: 'Player: show a side panel (Chapters, Transcript, Comments, Tasks, Buttons, Insights, Zoom, Voice-over, Keys...)', + risk: 'read', + unavailable: needPlayer, + params: { panel: { type: 'string', enum: () => [...document.querySelectorAll('[data-player-tab]')].map((b) => b.dataset['playerTab'] ?? ''), description: 'the panel id' } }, + run: (args = {}) => { + const tab = [...document.querySelectorAll('[data-player-tab]')].find((b) => b.dataset['playerTab'] === str(args['panel'])) + if (!tab) throw new Error('no such panel in this player') + tab.click() + return { panel: str(args['panel']) } + }, +}) + +// ---------- Preferences ---------- + +const BUILT_IN = ['appearance', 'recording', 'guests', 'library', 'agents', 'about'] + +commands.add({ + id: 'settings.open', + label: 'Open Preferences at a section', + risk: 'read', + params: { section: { type: 'string', optional: true, enum: () => [...BUILT_IN, ...settingsSections.all().map((s) => s.id)], description: 'the section (default appearance)' } }, + run: (args = {}) => { openSettings(str(args['section']) || 'appearance'); return { section: str(args['section']) || 'appearance' } }, +}) + +const THEMES = ['system', 'dark', 'light'] as const +const MODES = ['screen', 'camera', 'audio'] as const +const QUALITIES = ['720p', '1080p', '1440p', '2160p'] as const + +function prefs(): Record { + const s = loadSettings() + return { + theme: themeMode(), defaultMode: defaultMode(), countdownS: s.countdownS, limitMin: s.limitMin, checkIn: s.checkInMs > 0, + hideControls: s.hideControls, quality: s.quality, dock: document.documentElement.getAttribute('data-ft-dock') === 'open', + ...(canChooseMenus() ? { menusInWindow: menusInWindow() } : {}), + } +} + +commands.add({ id: 'prefs.get', label: 'Read the window\'s own settings (theme, default mode, studio countdown and limits, dock)', risk: 'read', run: () => prefs() }) +commands.add({ + id: 'prefs.set', + label: 'Change the window\'s own settings; give only what changes', + params: { + theme: { type: 'string', optional: true, enum: THEMES }, + defaultMode: { type: 'string', optional: true, enum: MODES, description: 'what New recording opens' }, + countdownS: { type: 'number', optional: true, min: 0, max: 10, description: 'seconds counted before a take' }, + limitMin: { type: 'number', optional: true, min: 0, max: 1440, description: 'stop a take after this many minutes, 0 for none' }, + checkIn: { type: 'boolean', optional: true, description: 'pause every two hours and ask' }, + hideControls: { type: 'boolean', optional: true, description: 'hide the record bar while recording' }, + quality: { type: 'string', optional: true, enum: QUALITIES }, + dock: { type: 'boolean', optional: true, description: 'show the agent dock' }, + menusInWindow: { type: 'boolean', optional: true, description: 'macOS app only: menus in the window instead of the menu bar' }, + }, + run: (args = {}) => { + if (args['theme'] !== undefined) setTheme(str(args['theme']) as ThemeMode) + if (args['defaultMode'] !== undefined) setDefaultMode(str(args['defaultMode']) as StudioMode) + const studio: Parameters[0] = {} + if (args['countdownS'] !== undefined) studio.countdownS = Number(args['countdownS']) + if (args['limitMin'] !== undefined) studio.limitMin = Number(args['limitMin']) + if (args['checkIn'] !== undefined) studio.checkInMs = args['checkIn'] === true ? TWO_HOURS : 0 + if (args['hideControls'] !== undefined) studio.hideControls = args['hideControls'] === true + if (args['quality'] !== undefined) studio.quality = str(args['quality']) as (typeof QUALITIES)[number] + if (Object.keys(studio).length) saveSettings(studio) + if (args['dock'] !== undefined) showDock(args['dock'] === true) + if (args['menusInWindow'] !== undefined && canChooseMenus()) setMenusInWindow(args['menusInWindow'] === true) + return prefs() + }, +}) + +// ---------- the studio's choices ---------- + +commands.add({ + id: 'studio.configure', + label: 'Studio: choose the layout, what to capture and the quality (before a take)', + unavailable: () => (document.querySelector('[data-studio-mode]') ? undefined : 'the studio is not open (nav.go page studio)'), + params: { + layout: { type: 'string', optional: true, enum: ['screen', 'screen-only', 'camera', 'audio', 'meeting', 'presentation', 'canvas'], description: 'screen is screen and camera' }, + target: { type: 'string', optional: true, enum: ['monitor', 'window', 'browser', 'current-tab', 'region'] }, + quality: { type: 'string', optional: true, enum: QUALITIES }, + }, + run: (args = {}) => { + const done: Record = {} + if (args['layout'] !== undefined) { + const b = document.querySelector(`[data-studio-mode] [data-mode="${str(args['layout'])}"]`) + if (!b || b.disabled) throw new Error('that layout cannot be chosen now (a take may be running)') + b.click() + done['layout'] = str(args['layout']) + } + for (const [key, attr] of [['target', 'data-studio-target'], ['quality', 'data-studio-quality']] as const) { + if (args[key] === undefined) continue + const s = document.querySelector(`select[${attr}]`) + const want = str(args[key]) + const option = s ? [...s.options].find((o) => o.value === want) : undefined + if (!s || !option || option.disabled || s.disabled) throw new Error(`${key} ${want} cannot be chosen now`) + s.value = want + s.dispatchEvent(new Event('change', { bubbles: true })) + done[key] = want + } + return done + }, +}) + +// ---------- the menu bar's own rows ---------- + +function rows(items: readonly MenuItem[]): MenuItem[] { + return items.flatMap((i) => (isSub(i) ? rows(i.items) : [i])) +} + +for (const menu of MENUS) { + const items = typeof menu.items === 'function' ? menu.items() : menu.items + for (const item of rows(items)) { + if (!isCommand(item) || !item.act || commands.all().some((c) => c.id === item.id)) continue + const act = item.act + commands.add({ + id: item.id, + label: `${menu.label}: ${item.label.replace(/\.\.\.$/, '')}`, + risk: item.id === 'view.reload' || item.id.startsWith('view.theme-') ? 'change' : 'read', + unavailable: () => (item.when && !item.when() ? 'not in this window' : item.enabled && !item.enabled() ? 'not available on this page' : undefined), + run: () => { act(); return { page: location.hash.slice(1) || '/' } }, + }) + } +} diff --git a/web/src/app.ts b/web/src/app.ts index e784824..95605ca 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -14,6 +14,9 @@ import { wireTheme } from './theme.js' // Every feature registers its slots before the first view is drawn. import './features/index.js' import { commands, viewRoutes } from './features/registry.js' +// After the features: every page, menu row, recording action and preference as a command agents can run. +import { holdPlayerTime } from './agent-commands.js' +import { AGENT_CHANGE, startAgentBridge } from './agent-bridge.js' /** 'mod+shift+l' and the like: mod is Cmd on a Mac and Ctrl elsewhere. */ export function shortcutMatches(shortcut: string, e: KeyboardEvent): boolean { @@ -109,3 +112,39 @@ countRecordings() window.addEventListener('hashchange', countRecordings) window.addEventListener('hashchange', () => void route()) void route() + +/** + * An agent changed something (agent-bridge.ts): the counts follow, and the view is drawn again when it shows what + * changed (the library, Home, Shared, or the open recording, whose player keeps its place, playing or paused). The + * studio and the editors (edit, annotate, clips, interactive), which can hold the person's unsaved work, are never + * redrawn under them. + */ +const LISTS = /^\/(?:$|library|shared|notifications|insights|history|playlist\/)/ +let changedIds = new Set() +let changedTools = new Set() +let changeTimer: ReturnType | undefined +const showChange = (): void => { + const ids = changedIds + const tools = changedTools + changedIds = new Set() + changedTools = new Set() + changeTimer = undefined + countRecordings() + const hash = location.hash.replace(/^#/, '') || '/' + const open = /^\/(?:f|edit|annotate|clips|interactive|team)\/([a-z0-9-]+)/.exec(hash)?.[1] + if (open && ids.has(open) && /^\/(?:f|team)\//.test(hash)) { + if (tools.has('formrec_delete')) { location.hash = '#/library'; return } + holdPlayerTime() + void route() + return + } + if (!open && LISTS.test(hash)) void route() +} +// A burst of changes (an agent tagging ten recordings) is drawn once. +window.addEventListener(AGENT_CHANGE, (e) => { + const { ids, tool } = (e as CustomEvent<{ ids: string[]; tool: string }>).detail + for (const id of ids) changedIds.add(id) + changedTools.add(tool) + changeTimer ??= setTimeout(showChange, 150) +}) +if (token() && document.getElementById('view')) startAgentBridge() diff --git a/web/src/features/registry.ts b/web/src/features/registry.ts index 6aaed49..80d944c 100644 --- a/web/src/features/registry.ts +++ b/web/src/features/registry.ts @@ -154,13 +154,39 @@ export interface StudioPlugin { /** Extra data saved with the take, written by the feature's own API after 'saved'. */ } -/** A command anyone can run: menus, keyboard shortcuts, the desktop app's native menu (by id). */ +/** One argument a command takes (agents read these through formrec_window_commands, ../agent-bridge.ts). */ +export interface CommandParam { + type: 'string' | 'number' | 'boolean' + /** The values allowed, when they are a fixed set (a function when the set is known only at run time). */ + enum?: readonly string[] | (() => readonly string[]) + optional?: boolean + min?: number + max?: number + description?: string +} + +/** + * What a command does beyond the window, for the agent bridge's approval: 'read' changes nothing, 'change' (the + * default) changes this window or library, 'destructive' removes something, 'external' sends or publishes outside this + * computer, 'privacy' turns on the camera, the microphone or the screen. The last three ask the person every time an + * agent runs them. + */ +export type CommandRisk = 'read' | 'change' | 'destructive' | 'external' | 'privacy' + +/** A command anyone can run: menus, keyboard shortcuts, the desktop app's native menu (by id), agents (by id, with args). */ export interface Command { id: string label: string /** For example 'mod+shift+l' (mod is Cmd on a Mac, Ctrl elsewhere). Shown in menus; bound while no input has focus. */ shortcut?: string - run(): void | Promise + /** The arguments it takes, checked before run; menus and shortcuts run it with none. */ + params?: Readonly> + /** Default 'change'. A function when it depends on the arguments (a recording action's risk is the action's). */ + risk?: CommandRisk | ((args: Record) => CommandRisk) + /** Why it cannot run now (no studio open, no recording open), or undefined when it can. */ + unavailable?(): string | undefined + /** May return a small JSON value for the agent that ran it. */ + run(args?: Record): unknown } function registry() { From ab7dd55cbb46bcd38eb4ce08141057aa4cd8b9c9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:14:37 -0500 Subject: [PATCH 03/25] fix(dock): find agent programs on the login-shell PATH and known install folders (0.12.0) The desktop app started from the Finder or the Dock inherits launchd's PATH (/usr/bin:/bin:/usr/sbin:/sbin). The dock engine found claude, codex, cursor-agent and agy with a bare scan of that PATH, so a Claude Code installed by npm, Homebrew, nvm or the native installer showed as "not installed" in the Ask tab while FormDeck and FormVis found it. src/dock/lookup.ts ports the family's agent_lookup.py 1.1.0 (FormDeck, FormVis): the engine's PATH, then the known install folders (npm prefix from NPM_CONFIG_PREFIX or ~/.npmrc, ~/.npm-global, ~/.local/bin, nvm, fnm, asdf, mise, volta, bun, pnpm, ~/.claude/local, Homebrew, and on Windows %APPDATA%\npm, %LOCALAPPDATA%\npm and the like), then the person's own shell PATH ($SHELL -l -i, falling back to -l, 5 s each, in its own session, killed with its group at the deadline; the registry Path on Windows), asked once at engine start and kept. An empty answer is asked again in the background after a minute. The status route reports path and how it was found, or where it looked. Claude Code and the other agent tabs start with a PATH of the program's own folder, the shell PATH, the known folders and the engine's PATH, so an npm "#!/usr/bin/env node" script finds node; --version runs the same way. Opening a tab for a missing program asks the shell again first. --- src/dock/index.ts | 22 +-- src/dock/lookup.ts | 328 +++++++++++++++++++++++++++++++++++++++++++ src/dock/programs.ts | 77 +++++++--- 3 files changed, 402 insertions(+), 25 deletions(-) create mode 100644 src/dock/lookup.ts diff --git a/src/dock/index.ts b/src/dock/index.ts index e582fe2..32e31a4 100644 --- a/src/dock/index.ts +++ b/src/dock/index.ts @@ -6,7 +6,7 @@ import { z } from 'zod' import { readJsonBody } from '../server/files.js' import { CONSENT_CHOICES, ConsentBroker, OUTSIDE_POLICIES, type ConsentEvent } from '../mcp/consent.js' import { ptyMissing } from './pty.js' -import { AGENT_TABS, childEnv, claudeConfig, locate, programLaunch, programStatus, PROGRAMS, removeFile, removeTabEntry, shellLaunch, tabToken, writeTabEntry, type AgentTab } from './programs.js' +import { AGENT_TABS, agentEnv, childEnv, claudeConfig, locate, programLaunch, programStatus, PROGRAMS, removeFile, removeTabEntry, shellLaunch, tabToken, warmLookup, writeTabEntry, type AgentTab } from './programs.js' import { originAllowed, TerminalSockets, Tickets } from './socket.js' import { NoPty, Terminals, TooMany, type Session } from './terminals.js' @@ -74,6 +74,7 @@ export function createDock(o: DockServerOptions): DockServer { const mcpUrl = (): string => `http://127.0.0.1:${o.port() ?? 8770}/mcp` const consent = new ConsentBroker(o.dataDir) const streams = new Set() + warmLookup() const consentStream = async (req: IncomingMessage, res: ServerResponse): Promise => { res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }) @@ -137,24 +138,27 @@ export function createDock(o: DockServerOptions): DockServer { const openShell = (cols?: number, rows?: number, title?: string): Session => open(() => terminals.open('shell', title || `Terminal ${terminals.shells() + 1}`, home(), shellLaunch(), childEnv(), cols ?? 100, rows ?? 30)) - const openClaude = (b: z.infer): Session => { - const file = locate('claude') + const openClaude = async (b: z.infer): Promise => { + const file = await locate('claude') if (!file) throw new Refusal(409, 'not-installed', 'Claude Code is not installed. Install it with npm install -g @anthropic-ai/claude-code, then sign in once by running claude in a terminal.') + const env = await agentEnv(file, { FORMREC_MCP_URL: mcpUrl() }) let config = '' return withToken((token) => open(() => { config = claudeConfig(path.join(tabsDir(), 'claude'), tabToken().slice(0, 12), mcpUrl(), token) const args = ['--mcp-config', config, ...(b.resume ? ['--resume', b.resume] : []), ...(b.prompt ? [b.prompt] : [])] - return terminals.open('claude', 'Claude Code', home(), programLaunch(file, args), childEnv({ FORMREC_MCP_URL: mcpUrl() }), b.cols ?? 100, b.rows ?? 30) + return terminals.open('claude', 'Claude Code', home(), programLaunch(file, args, env), env, b.cols ?? 100, b.rows ?? 30) }), () => { if (config) removeFile(config) }) } - const openAgent = (kind: AgentTab, cols?: number, rows?: number): Session => { - const file = locate(kind) + const openAgent = async (kind: AgentTab, cols?: number, rows?: number): Promise => { + const file = await locate(kind) if (!file) throw new Refusal(409, 'not-installed', `${PROGRAMS[kind].title} is not installed.${PROGRAMS[kind].install ? ` Install it with ${PROGRAMS[kind].install}.` : ''}`) const own = kind === 'antigravity' ? path.join(tabsDir(), kind) : undefined + const base = await agentEnv(file, { FORMREC_MCP_URL: mcpUrl() }) return withToken((token) => open(() => { if (own) writeTabEntry(own, mcpUrl(), token) - return terminals.open(kind, PROGRAMS[kind].title, own ?? home(), programLaunch(file, []), childEnv({ FORMREC_MCP_URL: mcpUrl(), FORMREC_INAPP_TOKEN: token }), cols ?? 100, rows ?? 30) + const env = { ...base, FORMREC_INAPP_TOKEN: token } + return terminals.open(kind, PROGRAMS[kind].title, own ?? home(), programLaunch(file, [], env), env, cols ?? 100, rows ?? 30) }), (token) => { if (own) removeTabEntry(own, token) }) } @@ -184,10 +188,10 @@ export function createDock(o: DockServerOptions): DockServer { return true } if (parts.length === 3 && a === 'ticket' && method === 'POST') { sendJson(res, 200, { ticket: tickets.issue() }); return true } - if (parts.length === 3 && a === 'claude' && method === 'POST') { sendJson(res, 200, openClaude(await body(req, ClaudeBody)).describe()); return true } + if (parts.length === 3 && a === 'claude' && method === 'POST') { sendJson(res, 200, (await openClaude(await body(req, ClaudeBody))).describe()); return true } if (parts.length === 3 && a === 'agent' && method === 'POST') { const o2 = await body(req, AgentBody) - sendJson(res, 200, openAgent(o2.kind, o2.cols, o2.rows).describe()) + sendJson(res, 200, (await openAgent(o2.kind, o2.cols, o2.rows)).describe()) return true } if (!a) return false diff --git a/src/dock/lookup.ts b/src/dock/lookup.ts new file mode 100644 index 0000000..4b59665 --- /dev/null +++ b/src/dock/lookup.ts @@ -0,0 +1,328 @@ +/** + * Where an agent program (Claude Code, Codex, Cursor's agent, Antigravity) is, the Form family's way: the engine's PATH, + * then the known install folders, then the person's own shell PATH, asked once and kept. A port of the family's + * `agent_lookup.py` 1.1.0 (FormDeck and FormVis, `backend/app/services/agent_lookup.py`) to the engine's TypeScript. + * + * The reason: an app started from the Finder, the Dock, the Start menu or a desktop launcher gets the system's short + * PATH (launchd's /usr/bin:/bin:/usr/sbin:/sbin on macOS), not the one a terminal has, so a bare PATH search reports + * programs installed by Homebrew, npm, a version manager or into the home folder as missing. The same PATH is what a + * program needs when it starts: an npm-installed `claude` is a `#!/usr/bin/env node` script, so `agentPath` puts the + * program's own folder, the shell's PATH and the known folders in front of the engine's own. + */ +import { execFile, spawn } from 'node:child_process' +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { which } from '../agents/clients.js' + +export const LOOKUP_VERSION = '1.1.0' +const MARK = '__FORM_AGENT_LOOKUP__' +/** How long the person's shell may take to say its PATH (a slow .zshrc is common; the answer is kept). */ +export const SHELL_MS = 5000 +/** An empty answer is asked again after this long, so a fix to the person's shell files is picked up. */ +const RETRY_MS = 60_000 + +export type How = 'path' | 'folder' | 'shell' +export const HOW: Record = { path: "the engine's PATH", folder: 'a known install folder', shell: "your shell's PATH" } + +export interface Spec { + names: readonly string[] + /** Folders under the home folder on macOS and Linux; a * stands for version folders, newest first. */ + home?: readonly string[] + /** Folders on Windows as local:, roaming: or home: and a path. */ + windows?: readonly string[] + /** Files inside an application bundle in /Applications or ~/Applications (macOS). */ + macFiles?: readonly string[] +} + +export interface Found { file?: string; how?: How; looked: string[] } + +export interface LookupOptions { + env?: NodeJS.ProcessEnv + platform?: NodeJS.Platform + home?: string +} + +let shellAnswer: { path: string[]; note: string; at: number } | undefined +let shellAsking: Promise<{ path: string[]; note: string }> | undefined + +/** Forget the shell's answer (tests, and a refresh that must ask again). */ +export function forgetShell(): void { + shellAnswer = undefined + shellAsking = undefined +} + +function isDir(p: string): boolean { + try { + return statSync(p).isDirectory() + } catch { + return false + } +} + +function versionKey(name: string): number[] { + const n = name.match(/\d+/g)?.map(Number) ?? [] + return n.length ? n : [0] +} + +function newestFirst(a: string, b: string): number { + const x = versionKey(a) + const y = versionKey(b) + for (let i = 0; i < Math.max(x.length, y.length); i++) { + const d = (y[i] ?? 0) - (x[i] ?? 0) + if (d) return d + } + return 0 +} + +/** The version folders under base, newest first, each with tail joined. */ +function versions(base: string, tail = ''): string[] { + let names: string[] + try { + names = readdirSync(base).filter((n) => isDir(path.join(base, n))) + } catch { + return [] + } + return names.sort(newestFirst).map((n) => (tail ? path.join(base, n, tail) : path.join(base, n))) +} + +/** npm's global prefix from ~/.npmrc (`prefix=`), which a person sets instead of the variable. */ +function npmrcPrefix(home: string): string | undefined { + try { + const line = readFileSync(path.join(home, '.npmrc'), 'utf8').split(/\r?\n/).find((l) => /^\s*prefix\s*=/.test(l)) + const value = line?.split('=').slice(1).join('=').trim().replace(/^["']|["']$/g, '') + return value ? value.replace(/^~(?=$|[\\/])/, home) : undefined + } catch { + return undefined + } +} + +export function systemFolders(platform: NodeJS.Platform): string[] { + if (platform === 'win32') return [] + if (platform === 'darwin') return ['/opt/homebrew/bin', '/usr/local/bin', '/opt/local/bin'] + return ['/usr/local/bin', '/usr/bin', '/snap/bin', '/home/linuxbrew/.linuxbrew/bin'] +} + +/** The known install folders for a program on this system, in the family's order, whether or not they exist. */ +export function folders(spec: Spec, o: LookupOptions = {}): string[] { + const env = o.env ?? process.env + const platform = o.platform ?? process.platform + const home = o.home ?? os.homedir() + const win = platform === 'win32' + const p = win ? path.win32 : path.posix + const out: string[] = [] + const prefix = env.NPM_CONFIG_PREFIX || env.npm_config_prefix || npmrcPrefix(home) + if (prefix) out.push(win ? prefix : p.join(prefix, 'bin')) + for (const [key, tail] of [['PNPM_HOME', ''], ['VOLTA_HOME', 'bin'], ['BUN_INSTALL', 'bin'], ['NVM_SYMLINK', '']] as const) { + const value = env[key] + if (value) out.push(tail ? p.join(value, tail) : value) + } + if (win) { + const roots: Record = { home, roaming: env.APPDATA || p.join(home, 'AppData', 'Roaming'), local: env.LOCALAPPDATA || p.join(home, 'AppData', 'Local') } + out.push(p.join(home, '.local', 'bin'), p.join(roots.roaming!, 'npm'), p.join(roots.local!, 'npm'), p.join(roots.local!, 'pnpm'), p.join(roots.local!, 'Volta', 'bin'), + p.join(home, '.bun', 'bin'), p.join(home, '.volta', 'bin')) + for (const place of spec.windows ?? []) { + const [root, ...rest] = place.split(':') + out.push(p.join(roots[root!] ?? home, ...rest.join(':').split('/'))) + } + return [...new Set(out)] + } + out.push(p.join(home, '.local', 'bin'), p.join(home, '.npm-global', 'bin'), p.join(home, '.bun', 'bin'), p.join(home, '.volta', 'bin'), p.join(home, '.local', 'share', 'pnpm')) + if (platform === 'darwin') out.push(p.join(home, 'Library', 'pnpm')) + out.push(...versions(p.join(home, '.nvm', 'versions', 'node'), 'bin')) + out.push(...versions(p.join(home, '.local', 'share', 'fnm', 'node-versions'), 'installation/bin')) + out.push(...versions(p.join(home, 'Library', 'Application Support', 'fnm', 'node-versions'), 'installation/bin')) + out.push(...versions(p.join(home, '.asdf', 'installs', 'nodejs'), 'bin')) + out.push(...versions(p.join(home, '.local', 'share', 'mise', 'installs', 'node'), 'bin')) + out.push(p.join(home, '.asdf', 'shims'), p.join(home, '.local', 'share', 'mise', 'shims')) + for (const place of spec.home ?? []) { + const [base, tail] = place.split('*') + if (tail !== undefined) out.push(...versions(p.join(home, base!), tail.replace(/^\//, ''))) + else out.push(p.join(home, place)) + } + out.push(...systemFolders(platform)) + return [...new Set(out)] +} + +/** The shell the person logs in with: $SHELL, else zsh on macOS, else bash or sh. */ +export function loginShell(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string { + if (env.SHELL) return env.SHELL + if (platform === 'darwin' && existsSync('/bin/zsh')) return '/bin/zsh' + return which('bash', env, platform) ?? '/bin/sh' +} + +/** + * Ask a shell for its PATH: started in its own session with no terminal (so an interactive start cannot stop on the + * terminal), stdin closed, killed with its whole group at the deadline. The PATH is read between two markers, so + * whatever the shell's start files print around it is ignored. + */ +export function askShell(shell: string, flags: string[], env: NodeJS.ProcessEnv, ms: number): Promise { + const script = path.basename(shell) === 'fish' ? `printf '%s%s%s' ${MARK} (string join : $PATH) ${MARK}` : `printf "%s%s%s" ${MARK} "$PATH" ${MARK}` + return new Promise((resolve) => { + let out = '' + let done = false + const finish = (value: string[] | null): void => { + if (done) return + done = true + clearTimeout(timer) + resolve(value) + } + let child: ReturnType + try { + child = spawn(shell, [...flags, '-c', script], { env, stdio: ['ignore', 'pipe', 'ignore'], detached: true, windowsHide: true }) + } catch { + resolve(null) + return + } + const timer = setTimeout(() => { + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL') + } catch { + child.kill('SIGKILL') + } + finish(null) + }, ms) + timer.unref() + child.stdout?.setEncoding('utf8') + child.stdout?.on('data', (chunk: string) => { if (out.length < 1_000_000) out += chunk }) + child.on('error', () => finish(null)) + child.on('close', () => { + const hit = new RegExp(`${MARK}([\\s\\S]*?)${MARK}`).exec(out) + const parts = hit ? hit[1]!.split(':').filter(Boolean) : [] + finish(parts.length ? parts : null) + }) + child.unref() + }) +} + +function expandWin(text: string, env: NodeJS.ProcessEnv): string { + return text.replace(/%([^%]+)%/g, (whole, name: string) => { + const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase()) + return key ? env[key] ?? whole : whole + }) +} + +/** The user and system Path values in the registry (Windows), as a newly opened terminal would have them. */ +function registryPath(env: NodeJS.ProcessEnv, ms: number): Promise { + const keys = ['HKCU\\Environment', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment'] + return Promise.all(keys.map((key) => new Promise((resolve) => { + try { + execFile('reg', ['query', key, '/v', 'Path'], { timeout: ms, windowsHide: true, encoding: 'utf8' }, (error, stdout) => { + const line = String(stdout ?? '').split(/\r?\n/).find((l) => /^\s*Path\s+REG_/i.test(l)) + const value = line?.replace(/^\s*Path\s+REG_\w+\s+/i, '') ?? '' + resolve(error && !value ? [] : expandWin(value, env).split(';').map((s) => s.trim()).filter(Boolean)) + }) + } catch { + resolve([]) + } + }))).then((both) => [...new Set(both.flat())]) +} + +/** + * The person's own PATH: on macOS and Linux what their login, interactive shell ends up with (login only when the + * interactive start gives nothing), on Windows the Path values in the registry. Asked once and kept; an empty answer is + * asked again after a minute (in the background: the kept answer is returned meanwhile, so a shell that hangs costs + * its wait once, not on every question), or at once with fresh. Callers at the same time share one question. + */ +export function shellPath(o: LookupOptions & { fresh?: boolean; ms?: number } = {}): Promise<{ path: string[]; note: string }> { + const env = o.env ?? process.env + const platform = o.platform ?? process.platform + const ms = o.ms ?? SHELL_MS + if (shellAnswer && !o.fresh) { + const kept = { path: [...shellAnswer.path], note: shellAnswer.note } + if (!shellAnswer.path.length && Date.now() - shellAnswer.at >= RETRY_MS && !shellAsking) void shellPath({ ...o, fresh: true }) + return Promise.resolve(kept) + } + if (shellAsking) return shellAsking + const asking = (async (): Promise<{ path: string[]; note: string }> => { + if (platform === 'win32') { + const found = await registryPath(env, ms) + return { path: found, note: found.length ? 'the Path values in the registry' : 'the Path values in the registry (none could be read)' } + } + const shell = loginShell(env, platform) + const name = path.basename(shell) + const seconds = `${ms / 1000} s` + const first = await askShell(shell, ['-l', '-i'], env, ms) + if (first) return { path: first, note: `your shell (${name}, login and interactive)` } + const second = await askShell(shell, ['-l'], env, ms) + if (second) return { path: second, note: `your shell (${name}, login only: the interactive start gave no PATH within ${seconds})` } + return { path: [], note: `your shell (${name} gave no PATH within ${seconds})` } + })() + shellAsking = asking + void asking.then((answer) => { + if (shellAsking === asking) { + shellAnswer = { ...answer, at: Date.now() } + shellAsking = undefined + } + }) + return asking +} + +function short(p: string, home: string): string { + return home && home !== path.sep && (p === home || p.startsWith(home + path.sep)) ? `~${p.slice(home.length)}` : p +} + +function onPath(names: readonly string[], dirs: string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined { + if (!dirs.length) return undefined + const delimiter = platform === 'win32' ? ';' : ':' + for (const name of names) { + const hit = which(name, { ...env, PATH: dirs.join(delimiter), Path: undefined }, platform) + if (hit) return hit + } + return undefined +} + +function appFile(spec: Spec, home: string, platform: NodeJS.Platform): string | undefined { + if (platform !== 'darwin') return undefined + for (const apps of ['/Applications', path.join(home, 'Applications')]) { + for (const inside of spec.macFiles ?? []) { + const file = path.join(apps, ...inside.split('/')) + try { + if (statSync(file).isFile()) return file + } catch { + // not here + } + } + } + return undefined +} + +/** + * Where the program is, in the family's order: the engine's PATH, the known install folders, then the person's shell + * PATH. `looked` records where it was not, so a not-found message can say so. + */ +export async function find(spec: Spec, o: LookupOptions & { fresh?: boolean } = {}): Promise { + const env = o.env ?? process.env + const platform = o.platform ?? process.platform + const home = o.home ?? os.homedir() + const looked: string[] = [] + const enginePath = env.PATH ?? env.Path ?? '' + const delimiter = platform === 'win32' ? ';' : ':' + const fromPath = onPath(spec.names, enginePath.split(delimiter).filter(Boolean), env, platform) + if (fromPath) return { file: fromPath, how: 'path', looked } + looked.push(`PATH (${enginePath || 'empty'})`) + const known = folders(spec, { env, platform, home }) + const fromFolder = onPath(spec.names, known, env, platform) ?? appFile(spec, home, platform) + if (fromFolder) return { file: fromFolder, how: 'folder', looked } + looked.push(known.map((f) => short(f, home)).join(', ')) + const shell = await shellPath({ env, platform, fresh: o.fresh }) + const fromShell = onPath(spec.names, shell.path, env, platform) + if (fromShell) return { file: fromShell, how: 'shell', looked } + looked.push(shell.note) + return { looked } +} + +/** + * The PATH an agent program starts with (and its `--version` check): its own folder first (so a node script finds the + * node beside it), the person's shell PATH, the known folders that exist for every program, then the engine's PATH. + */ +export async function agentPath(file: string | undefined, specs: readonly Spec[], o: LookupOptions = {}): Promise { + const env = o.env ?? process.env + const platform = o.platform ?? process.platform + const delimiter = platform === 'win32' ? ';' : ':' + const shell = await shellPath({ env, platform }) + const known = specs.flatMap((spec) => folders(spec, { env, platform, home: o.home })).filter(isDir) + const own = file ? [(platform === 'win32' ? path.win32 : path.posix).dirname(file)] : [] + const parts = [...own, ...shell.path, ...known, ...(env.PATH ?? env.Path ?? '').split(delimiter)] + return [...new Set(parts.filter(Boolean))].join(delimiter) +} diff --git a/src/dock/programs.ts b/src/dock/programs.ts index 69142cb..be0dc5c 100644 --- a/src/dock/programs.ts +++ b/src/dock/programs.ts @@ -4,37 +4,81 @@ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } import path from 'node:path' import { which } from '../agents/clients.js' import { launchArgv } from '../agents/win-launch.js' +import { agentPath, find, shellPath, type Found, type How, type Spec } from './lookup.js' import type { Launch } from './terminals.js' export const PROGRAMS = { - claude: { bin: 'claude', title: 'Claude Code', install: 'npm install -g @anthropic-ai/claude-code' }, - codex: { bin: 'codex', title: 'Codex', install: 'npm install -g @openai/codex' }, - cursor: { bin: 'cursor-agent', title: 'Cursor', install: 'curl https://cursor.com/install -fsS | bash' }, - antigravity: { bin: 'agy', title: 'Antigravity', install: '' }, -} as const + claude: { bin: 'claude', title: 'Claude Code', install: 'npm install -g @anthropic-ai/claude-code', + lookup: { names: ['claude'], home: ['.claude/local', '.claude/bin'], windows: ['home:.claude/local', 'home:.claude/bin', 'local:Programs/claude', 'roaming:Programs/claude'] } }, + codex: { bin: 'codex', title: 'Codex', install: 'npm install -g @openai/codex', + lookup: { names: ['codex'], windows: ['local:Programs/OpenAI/Codex/bin'], macFiles: ['Codex.app/Contents/Resources/codex', 'Codex.app/Contents/Resources/bin/codex'] } }, + cursor: { bin: 'cursor-agent', title: 'Cursor', install: 'curl https://cursor.com/install -fsS | bash', + lookup: { names: ['cursor-agent'], home: ['.local/share/cursor-agent/versions/*'], windows: ['local:cursor-agent'] } }, + antigravity: { bin: 'agy', title: 'Antigravity', install: '', lookup: { names: ['agy'] } }, +} as const satisfies Record export type ProgramKind = keyof typeof PROGRAMS export const AGENT_TABS = ['codex', 'cursor', 'antigravity'] as const export type AgentTab = (typeof AGENT_TABS)[number] +const SPECS: Spec[] = Object.values(PROGRAMS).map((p) => p.lookup) -export interface ProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null; title: string; said?: string; finding: 'runs' | 'missing' } +export interface ProgramStatus { + installed: boolean; version: string | null; install: string; signedIn: boolean | null; title: string; said?: string; finding: 'runs' | 'missing' + path?: string; how?: How; looked?: string[] +} export const TAB_ENTRY = 'formrec_tab' const VERSION_MS = 4000 const VERSION_KEEP_MS = 10 * 60 * 1000 const versions = new Map }>() -export function locate(kind: ProgramKind, env: NodeJS.ProcessEnv = process.env): string | undefined { - return which(PROGRAMS[kind].bin, env) +/** + * A missing program has the person's shell asked again (an install may have changed its PATH), at most this often and + * in the background, so the status route never waits on a slow shell twice; the next check (the window regaining + * focus, the dock's menu) sees the new answer. The folders themselves are looked in afresh on every check. + */ +const FRESH_MS = 30_000 +let freshAt = 0 + +/** Ask the person's shell for its PATH now, at the engine's start, so the dock's first question does not wait on it. */ +export function warmLookup(): void { + freshAt = Date.now() + void shellPath().catch(() => undefined) +} + +/** Where the program is (the engine's PATH, the known install folders, the person's shell PATH), and where it looked. */ +export async function locateFound(kind: ProgramKind): Promise { + const found = await find(PROGRAMS[kind].lookup) + if (!found.file && Date.now() - freshAt >= FRESH_MS) { + freshAt = Date.now() + void shellPath({ fresh: true }).catch(() => undefined) + } + return found +} + +/** The program's file. Asked to start one, so worth a wait: when it is missing the shell is asked again first. */ +export async function locate(kind: ProgramKind): Promise { + const found = await find(PROGRAMS[kind].lookup) + if (found.file) return found.file + freshAt = Date.now() + return (await find(PROGRAMS[kind].lookup, { fresh: true })).file +} + +/** The environment of an agent program: childEnv with the PATH it needs to start (see lookup.ts `agentPath`). */ +export async function agentEnv(file: string, extra: Record = {}): Promise> { + const env = childEnv(extra) + const PATH = await agentPath(file, SPECS) + if (process.platform === 'win32') for (const k of Object.keys(env)) if (k.toUpperCase() === 'PATH') delete env[k] + return { ...env, PATH } } -function versionOf(file: string): Promise { +function versionOf(file: string, env: Record): Promise { const known = versions.get(file) if (known && Date.now() - known.at < VERSION_KEEP_MS) return known.value const value = new Promise((resolve) => { try { - const launch = launchArgv(file, ['--version'], { platform: process.platform, env: process.env, which: (b) => which(b) }) - execFile(launch.command, launch.args, { timeout: VERSION_MS, windowsHide: true, windowsVerbatimArguments: launch.verbatim, encoding: 'utf8' }, (error, stdout) => { + const launch = launchArgv(file, ['--version'], { platform: process.platform, env, which: (b) => which(b, env) }) + execFile(launch.command, launch.args, { env, timeout: VERSION_MS, windowsHide: true, windowsVerbatimArguments: launch.verbatim, encoding: 'utf8' }, (error, stdout) => { const line = String(stdout ?? '').trim().split('\n')[0] ?? '' const found = /\d+\.\d+(?:\.\d+)?(?:[-+.][0-9A-Za-z.-]+)?/.exec(line)?.[0] resolve(error && !found ? null : found ?? (line || null)) @@ -49,14 +93,15 @@ function versionOf(file: string): Promise { export async function programStatus(kind: ProgramKind): Promise { const p = PROGRAMS[kind] - const file = locate(kind) + const found = await locateFound(kind) + const file = found.file if (!file) { const said = kind === 'antigravity' ? 'Antigravity was not found on this computer. Install it from antigravity.google, then open a new tab here.' : `${p.title} was not found on this computer. Install it with the command below, then sign in once in a terminal.` - return { installed: false, version: null, install: p.install, signedIn: null, title: p.title, said, finding: 'missing' } + return { installed: false, version: null, install: p.install, signedIn: null, title: p.title, said, finding: 'missing', looked: found.looked } } - return { installed: true, version: await versionOf(file), install: '', signedIn: null, title: p.title, finding: 'runs' } + return { installed: true, version: await versionOf(file, await agentEnv(file)), install: '', signedIn: null, title: p.title, finding: 'runs', path: file, how: found.how } } export function childEnv(extra: Record = {}): Record { @@ -73,8 +118,8 @@ export function shellLaunch(): Launch { return { command: process.env.SHELL || which('bash') || '/bin/sh', args: ['-l'] } } -export function programLaunch(file: string, args: string[]): Launch { - const launch = launchArgv(file, args, { platform: process.platform, env: process.env, which: (b) => which(b) }) +export function programLaunch(file: string, args: string[], env: Record = process.env as Record): Launch { + const launch = launchArgv(file, args, { platform: process.platform, env, which: (b) => which(b, env) }) return { command: launch.command, args: launch.verbatim ? launch.args.join(' ') : launch.args } } From 969080e12ad9b9c767cb759e249d317f651437d7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:14:37 -0500 Subject: [PATCH 04/25] fix(dock): recheck the agent programs when the window regains focus (0.12.0) Someone who installs Claude Code while FormREC is open is no longer stuck on the "not installed" note: on window focus the dock refreshes its program list (as FormDeck's dock does), and a Claude Code install note left from before is dismissed once the engine reports it installed. The shared dock module is unchanged; this is FormREC's adapter. --- web/src/dock-adapter.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/web/src/dock-adapter.ts b/web/src/dock-adapter.ts index 0f9ca81..6705b6d 100644 --- a/web/src/dock-adapter.ts +++ b/web/src/dock-adapter.ts @@ -240,10 +240,22 @@ export function formrecDock(): DockAdapter { let mounted: Dock | null = null export function mountDock(host: HTMLElement): { toggle(): void; open(): void; close(): void } { - const dock = mounted ?? new Dock(formrecDock()) if (!mounted) { + const adapter = formrecDock() + const dock = new Dock(adapter) mounted = dock dock.mount(host, host.querySelector(':scope > .statusbar')) + // A program installed while the window was away shows up when it comes back (FormDeck's dock does the same), and + // a "not installed" note left from before is taken down once the engine finds Claude Code. + window.addEventListener('focus', () => { + dock.refresh() + const cmd = host.querySelector('.ft-dock-note:not([hidden]) .ft-dock-note-cmd:not([hidden])') + if (!cmd?.textContent) return + void adapter.agentStatus().then((st) => { + if (st?.claude?.installed && cmd.textContent && !cmd.closest('[hidden]')) host.querySelector('[data-dock-part="note.dismiss"]')?.click() + }) + }) } + const dock = mounted return { toggle: () => dock.toggle(), open: () => dock.toggle(true), close: () => dock.toggle(false) } } From 1fb2b88c9db12ad797180121bfaf9c9f12e2f5a1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:16:01 -0500 Subject: [PATCH 05/25] docs(agents): the guide, the harness skill, AGENTS.md, CLAUDE.md and the API reference say agents can do everything in the window (0.12.0) - formrec_guide (src/mcp/guide.ts): what the window commands are, that destructive, external and privacy commands ask the person every time, that engine changes show in the window, and the job tools for long work. The old line that studio takes are not made over MCP is gone. - formrec-harness SKILL.md: a section on the window (pages, menus, studio, player, recording menus, Preferences, with the command ids), the job loop, a routing row, and the studio rule now says an agent starts a take only when asked and the window asks before any device turns on. The description is left as it is: it is at 1004 of 1024 characters. - AGENTS.md and CLAUDE.md name the bridge, its files, and that a new UI action is a registered command so agents can run it. - docs/api.md regenerated with its own generator (src/features/integrations/api-doc.ts) from the /api/window route lines in src/window/bridge.ts's header, whose notes now read on their own. --- .claude/skills/formrec-harness/SKILL.md | 18 +++++++++++++++++- AGENTS.md | 2 ++ CLAUDE.md | 2 +- docs/api.md | 11 +++++++++++ src/mcp/guide.ts | 22 +++++++++++++++++++--- src/window/bridge.ts | 12 ++++++------ 6 files changed, 56 insertions(+), 11 deletions(-) diff --git a/.claude/skills/formrec-harness/SKILL.md b/.claude/skills/formrec-harness/SKILL.md index 355382f..38517c7 100644 --- a/.claude/skills/formrec-harness/SKILL.md +++ b/.claude/skills/formrec-harness/SKILL.md @@ -40,6 +40,21 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - `formrec_open_in_formcut` hands the recording to FormCut, the Form family video editor, when the person wants a full timeline edit (FormCut must be running). - `formrec_delete` removes a recording and its folder for good: only when the person asked, and with `confirm` repeating the id. +## The window: everything a person can do + +When a FormREC window is open, its whole command registry is yours: `formrec_window_commands` lists every command (id, label, `args` as `name?: type`, risk; `query` filters, `id` describes one in full with allowed values and whether it can run now), and `formrec_window_command_run` runs one with `args`, exactly as if the person chose it, and the window shows it at once. + +- Pages: `nav.go` with `page` (home, library and its tabs, studio, screen, camera, audio, the studio layouts, shared, notifications, insights, recently-watched, meetings, ask, tour, demo, recording, edit, annotate, clips, interactive, playlist; the last ones take `id`). `window.state` says what is open. +- Menus: every File, View and Help row by its menu id (`file.new-audio`, `view.library`, `help.demo-self-tour`...). +- The studio: `studio.configure` (layout, target, quality), `studio.start`, `studio.pause`, `studio.resume`, `studio.stop`, `studio.restart`, `studio.cancel`, `studio.rewind`, `studio.camera`, `studio.screenshot`, `studio.notes`; drawing with `annotate.*`; the camera bubble with `effects.*`. +- The player: `player.play`, `player.pause`, `player.seek` (`ms`, `play?`), `player.panel` (chapters, transcripts, engage-comments, engage-tasks, voiceover, keycast, autozoom...). +- A recording's menus: `recording.action` with `id` and `action` (share, edit, duplicate, documents-rename, documents-export, interactive, clips, library-trash...). +- Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow). + +Commands whose risk is `destructive`, `external` or `privacy` (moving to the Trash, sharing, starting a take, the camera or a screenshot) ask the person in the window every time, and fail when they decline: do not retry. Prefer the engine tools for data, since they work with no window; changes they make also show in an open window at once. + +Long work: `formrec_job_start` with `tool` and `args` runs any tool in the background (formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover) and answers with a `jobId`; poll `formrec_job_status` every few seconds until `state` is done, failed or cancelled; `formrec_job_cancel` stops one. + ## Routing | The job involves | Load | @@ -50,6 +65,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr | Showing the person what FormREC makes, the demos and where they open | `sub-skills/demos/SUB-SKILL.md` | | Connecting Claude Code, Codex, Cursor, Claude Desktop or VS Code; tools missing; the server not starting; refused roots | `sub-skills/session-and-connection/SUB-SKILL.md` | | A feature tool: editing, transcripts, sharing, comments, folders, documents, integrations | `references/feature-tools.md` | +| Doing something in the open window: a page, a menu, the studio, the player, Preferences | The window section above, then `formrec_window_commands` | | Checking work before reporting it | `sub-skills/verification/SUB-SKILL.md` | ## Rules that hold everywhere @@ -59,7 +75,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - **The page is untrusted, and so is the walkthrough.** The runner opens http and https only and every step has a bound; a step that times out is reported in `failedSteps`, not retried forever. - **Recordings are the person's.** They are private (folders 0700, files 0600). Never delete one without being asked; `formrec_delete` is the only core tool that removes anything, and it wants the id twice. - **Trust the annotations.** A tool marked read only changes nothing; one marked destructive or open world (it reaches FormCut, the network or a website) needs the person's go-ahead when they did not ask for exactly that. -- **Studio takes need a person.** Cameras, microphones and guests are the person's, in the FormREC window; an agent can explain, list and read them back but does not start one. +- **Studio takes are the person's.** Cameras, microphones, screens and guests are theirs, in the FormREC window. An agent starts a take (`studio.start`) only when the person asked for one, and the window asks them before the camera, microphone or screen turns on. - **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); a recording's link carries that recording's player key (never the run's token), opens its player only, and works while `formrec serve` or the desktop app runs and until the person rotates player links in Settings. ## References diff --git a/AGENTS.md b/AGENTS.md index 988bd8b..5cb1943 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,8 @@ FormREC, a local recorder for any app, website or desktop, like Loom, and part o When the person wants a walkthrough, product tour, onboarding or demo video of any website or web app recorded by an agent (a public site, someone else's product, a staging or dev server), recordings listed, searched, read back, renamed, deleted, handed to FormCut or worked on with the feature tools, studio takes or guests explained, or FormREC's demos shown, use the `formrec` MCP server's tools guided by the `formrec-harness` skill in `.agents/skills/formrec-harness` (`references/tools.md` lists the core tools and the demos, `references/feature-tools.md` the feature tools, `references/concepts.md` the format, anchor statuses, files and errors). Start with `formrec_guide`; call `formrec_validate` until `problems` is empty before `formrec_record`; check `failedSteps` and `formrec_get` before reporting. Code anchors are optional. Ask before `formrec_delete` or any tool marked destructive. +Anything the person can do in the FormREC window an agent can do too, while a window is open: `formrec_window_commands` lists the window's commands (pages, menus, the studio, the player, a recording's menus, Preferences) with their arguments and risk, and `formrec_window_command_run` runs one; deleting, publishing and the camera, microphone or screen ask the person in the window every time. Long tools run as jobs: `formrec_job_start`, then `formrec_job_status`. + The MCP server is configured here in `.codex/config.toml` (Codex), `.cursor/mcp.json` and `.cursor/rules/formrec.mdc` (Cursor) and `.mcp.json` (Claude Code); all run `node dist/src/cli.js mcp --codebase `, so build first (`npm ci && npm run build`). The checkout is also a Claude Code plugin (`.claude-plugin/`). `formrec agents install` (from this checkout, `npm run agents -- install`) sets Claude Code, Codex and Cursor up for the user account (name `desktop` for Claude Desktop and `vscode` for VS Code, `--codebase DIR` to fix the root, `--dry-run` to see what it writes), registering the installed app's `formrec-desktop mcp` when there is one; `formrec agents status` shows what is set up, and Settings, Agents in the app does the same with one click. Without MCP, `node dist/src/cli.js validate|record|list|url` has the same surface. ## Changing FormREC's code diff --git a/CLAUDE.md b/CLAUDE.md index 51a34be..f62841f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,7 +25,7 @@ The app is FormREC (window title, brand, docs headings). The CLI and package `fo - `src-tauri/` the desktop app: a Tauri 2 window around `formrec serve --desktop` (`src/cli.ts`) run by a bundled Node 22 (`formrec-node`); `reveal.rs` keeps the window hidden until the page calls `app_ready`, `menu.rs` is the native menu (hash routes). `setup/stage_desktop` stages `dist`, the production dependencies and the pinned Node runtime; `setup/build_release --target ` is what FormCompiler runs (signing, notarization, the stapling retry, the seal check). FormCompiler's entry is `apps/formrec.json` in nodemode-dev/formcompiler; the version source is `src-tauri/tauri.conf.json`. - Runs that need a real desktop or toolchain, each with a vitest test that skips with a clear message when the tool is missing: `setup/linux_desktop_run.mjs` (the built Linux app on Xvfb; `tests/desktop-linux-run.test.ts`), `setup/extension_capture_run.mjs` (the extension's real tab capture in headed Chromium; `tests/extension-capture-e2e.test.ts`), `apps/android` with its Gradle wrapper (`tests/phone-android-e2e.test.ts`, ANDROID_HOME or /opt/android-sdk), `apps/ios/Package.swift` with Swift on Linux (`tests/phone-ios-e2e.test.ts`, /opt/swift), the X11 native display feed on Xvfb (`tests/desktop-x11-*.test.ts`), and Tesseract for redaction and scene titles. - Features: `src/features//` and `web/src/features/.ts` (with `web/src/-*.ts` and `web/styles/.css`), one per Loom-class capability: studio, effects, annotate, edit, transcripts, ai, share, engage, library, documents, workspace, integrations, mail, extension, desktop, agents, runner, phone, tunnel, relay, meetings, analytics, wtdiff, teamsync, zoom, and since 0.8.0 the ones beyond Loom (`docs/beyond-loom.md`): interactive (click-through demos at `/i/`, one import-free player in `web/src/interactive-view.ts` for the app, the share page and the zip), live, objects (the MCP object tools), autozoom, keycast (`shared/keycast-math.ts`), redact (`src/runner/redact.ts` in the page) and clips; scene chapters are ai's `scenes.ts`, the X11 native display feed is desktop's `native-feed.ts` (`src/features/sso/` is a module share and the relay use; `web/src/features/roles.ts` and `sso.ts` are client sections over the workspace's and the relay's routes). Since 0.9.0: variants (`src/variants/`: `substitute.ts` the `{{variables}}` on a copy, `values.ts` the JSON or CSV value sets, `run.ts` one recording per set, `tools.ts` the handler behind `formrec variants`, the MCP tool and the panel; `src/features/variants/` the routes; `web/src/variants-panel.ts`); in live, `keyforward.ts` and `rtmp-rewrite.ts` (FFmpeg publishes to a one-use loopback forwarder that holds the real stream key, so the key is in no argument list or environment), `hls.ts`, `link.ts`, `link-http.ts` and `link-page.ts` (the live link at `/l/`, served by `handleShareRequest` on the LAN and tunnel, not the relay; `web/src/live-view.ts` and `live-hls.ts`) and `slate.ts` with `feedclock.ts` (the paused take's slate on one growing clock); in documents, `guide.ts`, `guide-publish.ts` and `guide-run.ts` (picture guides from the interactive demo's pictures; the tool is `formrec_picture_guide`); in interactive, `insights.ts` and `translate.ts` and the click-based planning in `build.ts`. The contract is `src/features/types.ts` (routes under `/api//`, per-recording files, sidecars and feature folders through `src/features/store.ts`, MCP tools, start and stop, library events) and `web/src/features/registry.ts` (player panels, actions, layers and control-bar buttons, recording actions, Settings sections, routes, studio plugins, commands). The player's control bar is `web/src/player-controls.ts` (FormREC's own, under the picture, never the browser's controls; keys in `player-keys.ts`; styles in `web/styles/player-bar.css`), and the share page runs the same module from share's fixed file list. Walkthrough chapters keep `action`, `actionMs` and the target's `box`, which demos, zoom, keystrokes and redaction read. Integrations publish pages to form.md (`src/features/integrations/formmd.ts`, the Form family's workspace, in Notion's place, with the video in the page through `formmd-video.ts`; `tests/apps-formmd-real.test.ts` runs a real form-md binary from FORMMD_BIN or FORMMD_SRC and skips without one) and Confluence. Shared things have one owner: edit exports, the workspace owns policy, branding, people and the activity log, engage owns plays and comments, documents owns deep links and packages, the library owns import and the Trash (zoom imports through `importVideoFile`), the workspace owns every per-video setting and its default (`video-settings.ts`), edit makes the share renditions, share's `origin.ts` builds every share link, share's `listener.ts` `handleShareRequest` is the one share handler (LAN, tunnel and relay), mail sends everything, `src/apps/context.ts` is the one AppContext. `docs/parity/.md` maps each Loom row to its code and test; `docs/LOOM_PARITY.md` is the whole table. -- Agents: `src/mcp/` (core tools with titles, annotations and output schemas; `reply.ts` is the reply shape feature tools share; `demos.ts` is `formrec_demos`), `src/agents/` (`formrec agents install|status|sync [--check]`: the launcher, per-client text and state, install writers for Claude Code, Codex, Cursor, Claude Desktop and VS Code with backups, the reference generator and the skill and plugin gates; `scripts/agents.mjs` runs its build), `src/features/agents` (`/api/agents` behind Settings, Agents), the skills `formrec-harness` and `formrec-skillset` in `.claude/skills/` (mirrored in `.agents/skills/`, each with `EVALS.json`), the checkout's `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and `.cursor/rules/`, and the Claude Code plugin in `.claude-plugin/`. `npm run agents:check` runs in CI via `.github/workflows/agents.yml`. Change a tool, then `npm run agents:sync`. +- Agents: `src/mcp/` (core tools with titles, annotations and output schemas; `reply.ts` is the reply shape feature tools share; `demos.ts` is `formrec_demos`; `jobs.ts` runs any tool as a background job), `src/window/` (the agent bridge to the open window: `bridge.ts` the `/api/window/*` routes, the event stream the window keeps open, the approval of destructive, external and privacy commands and the change notices; `tools.ts` `formrec_window_commands` and `formrec_window_command_run`), `web/src/agent-bridge.ts` and `web/src/agent-commands.ts` (the window's end, and every page, menu row, recording action, player control and preference as a command with typed `params` and a `risk`: a new UI action is a command in `web/src/features/registry.ts` so agents can run it too), `src/agents/` (`formrec agents install|status|sync [--check]`: the launcher, per-client text and state, install writers for Claude Code, Codex, Cursor, Claude Desktop and VS Code with backups, the reference generator and the skill and plugin gates; `scripts/agents.mjs` runs its build), `src/features/agents` (`/api/agents` behind Settings, Agents), the skills `formrec-harness` and `formrec-skillset` in `.claude/skills/` (mirrored in `.agents/skills/`, each with `EVALS.json`), the checkout's `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and `.cursor/rules/`, and the Claude Code plugin in `.claude-plugin/`. `npm run agents:check` runs in CI via `.github/workflows/agents.yml`. Change a tool, then `npm run agents:sync`. ## Checks diff --git a/docs/api.md b/docs/api.md index 0e5b583..a6a284e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -860,6 +860,17 @@ From `src/server/player-link.ts`: | GET | `/api/player/:id?key=` | the recording (what the player draws) | | GET | `/api/player/:id/:file?key=` | its video, tracks, captions and chapters (the core media names, server/http.ts MEDIA) | +From `src/window/bridge.ts`: + +| method | path | what it does | +|---|---|---| +| GET | `/api/window/stream` | the window's end: events hello, call (list, describe, run) and changed | +| POST | `/api/window/result` | { callId, ok, value?, error? } the window's answer to a call | +| POST | `/api/window/focus` | { windowId } this window answers the next calls | +| GET | `/api/window/commands?query=&id=` | the window's commands (id, label, args, risk), or one described in full | +| POST | `/api/window/run` | { id, args?, agent? } runs one; destructive, external and privacy ones ask the person first | +| POST | `/api/window/changed` | { ids, tool } an agent in another process (`formrec mcp`) changed these recordings | + ## The guest listener HTTPS on the local network, on only while guests are turned on in the studio. A guest pairs with a six-digit code diff --git a/src/mcp/guide.ts b/src/mcp/guide.ts index 6a5878c..e8b27a0 100644 --- a/src/mcp/guide.ts +++ b/src/mcp/guide.ts @@ -67,8 +67,24 @@ The full format follows (the same text formrec_walkthrough_format returns): ${WALKTHROUGH_FORMAT} -Studio takes and guests are made by a person in the FormREC window (Record), not over MCP: any -screen, window or app, camera and microphone is its own track, guests on the same network join with a six-digit -code and record themselves. formrec_list and formrec_get return those recordings too (source "person", with a track per source). +Studio takes and guests are made in the FormREC window (Record): any screen, window or app, +camera and microphone is its own track, guests on the same network join with a six-digit code and +record themselves. formrec_list and formrec_get return those recordings too (source "person", with +a track per source). + +Everything a person can do in the window, you can do too, when a FormREC window is open: +formrec_window_commands lists its commands (pages with nav.go, the menus, the studio's +studio.start, studio.stop and the rest, drawing tools, player.seek and player.panel, the library +card and player menus with recording.action, Preferences with settings.open, prefs.get and +prefs.set), compactly, with each one's args and risk; pass id to see one in full. Run one with +formrec_window_command_run; the window shows the result at once. A command whose risk is +destructive, external or privacy (deleting, publishing, the camera, microphone or screen) asks the +person in the window every time. Prefer the engine tools for data (they work without a window) and +the window commands to show the person something or do what only the window does (studio takes). +Changes you make with the engine tools also show in the open window at once. + +Long work: formrec_job_start runs any tool (formrec_record, formrec_export, formrec_transcribe, +formrec_make_clips...) in the background and answers with a jobId; poll formrec_job_status until +its state is done, failed or cancelled, or stop it with formrec_job_cancel. ${demosGuide()}` diff --git a/src/window/bridge.ts b/src/window/bridge.ts index ed65a92..e7ed7e8 100644 --- a/src/window/bridge.ts +++ b/src/window/bridge.ts @@ -10,12 +10,12 @@ * at once (web/src/agent-bridge.ts). * * Routes (behind the run's token, like every /api route): - * GET /api/window/stream the window's end of the bridge - * POST /api/window/result { callId, ok, value?, error? } - * POST /api/window/focus { windowId } - * GET /api/window/commands?query=&id= the catalogue, or one command described (for `formrec mcp` over stdio) - * POST /api/window/run { id, args?, agent? } with the approval below (for `formrec mcp` over stdio) - * POST /api/window/changed { ids, tool } a change made by another process (`formrec mcp` over stdio) + * GET /api/window/stream the window's end: events hello, call (list, describe, run) and changed + * POST /api/window/result { callId, ok, value?, error? } the window's answer to a call + * POST /api/window/focus { windowId } this window answers the next calls + * GET /api/window/commands?query=&id= the window's commands (id, label, args, risk), or one described in full + * POST /api/window/run { id, args?, agent? } runs one; destructive, external and privacy ones ask the person first + * POST /api/window/changed { ids, tool } an agent in another process (`formrec mcp`) changed these recordings * * Approval: a command whose risk is destructive, external or privacy (deleting, publishing outside this computer, the * camera, microphone or screen) asks the person in the window every time an agent runs it, through the dock's consent From 2e195c4cb7b9361a8ad84a59f04e9c7684170ba7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:24:52 -0500 Subject: [PATCH 06/25] feat(web): every control of every Preferences section is reachable by agents, never the agent's own consent (0.12.0) prefs.set covered the window's own settings, but most Preferences sections are forms (Trash and imports, guests, branding, email, redaction, voice and the rest), and several have no engine tool. Two generic commands make all of them reachable without a command per field: - settings.controls { section }: each control of that section page that has a data attribute, named as the attribute (`studio-setting=check-in`, `library-setting=trashDays`, `library-setting-save`), with its kind, row label and current value (passwords say only whether one is set). - settings.set { section, control, value?, checked? }: sets a field or a select (a value the select lacks is refused), ticks a checkbox, or presses a button, then fires input and change as a person's edit does. Fields, pressed-or-not choices, tabs and Save buttons are changes; any other button may remove or send something, so it is destructive and the person is asked every time, as is any control that cannot be found when the risk is judged. Outside agents (the consent policy and the remembered agents) is the person's own choice: it is neither listed nor set, and is refused before any question is asked. Checked live: the studio section's five controls listed; hide controls ticked and countdown 10 stored; countdown 7 refused; Trash after 45 days typed and saved, and the engine's library settings then read 45; the outside agents choice absent from the list and refused. --- web/src/agent-commands.ts | 91 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/web/src/agent-commands.ts b/web/src/agent-commands.ts index 1e8785b..15a3bb8 100644 --- a/web/src/agent-commands.ts +++ b/web/src/agent-commands.ts @@ -238,6 +238,97 @@ commands.add({ run: (args = {}) => { openSettings(str(args['section']) || 'appearance'); return { section: str(args['section']) || 'appearance' } }, }) +/** + * Any control of a Preferences page, by its data attribute: `name` or `name=value` without the `data-` prefix, as + * settings.controls lists them (for example `studio-setting=check-in` or `theme-set=dark`). The agent's own consent + * (Outside agents) is the person's to choose and is never offered. A button that is not a pressed-or-not choice may + * remove or send something, so pressing one asks the person. + */ +const NEVER = /^(outside-|consent)/ +const CONTROLS = 'input, select, textarea, button' + +function settingsPage(section: string): HTMLElement { + const page = [...document.querySelectorAll('[data-settings-page]')].find((p) => p.dataset['settingsPage'] === section) + if (!page) throw new Error(`no Preferences section ${section}`) + return page +} + +function keyOf(el: Element): string | undefined { + const attr = [...el.attributes].find((a) => a.name.startsWith('data-')) + if (!attr) return undefined + const name = attr.name.slice(5) + return attr.value ? `${name}=${attr.value}` : name +} + +function control(section: string, key: string): HTMLElement { + if (NEVER.test(key)) throw new Error('Outside agents is the person\'s own choice; ask them to change it in Preferences, Agents') + const all = [...settingsPage(section).querySelectorAll(CONTROLS)].filter((el) => keyOf(el) === key) + if (all.length !== 1) throw new Error(all.length ? `${key} names ${all.length} controls in ${section}` : `no control ${key} in ${section}; settings.controls lists them`) + return all[0]! +} + +/** Fields, pressed-or-not choices, tabs and Save buttons change settings; any other button may remove or send. */ +const isChoice = (el: HTMLElement): boolean => + el.tagName !== 'BUTTON' || el.hasAttribute('aria-pressed') || el.getAttribute('role') === 'tab' || /(^|-)save(-|=|$)/.test(keyOf(el)?.split('=')[0] ?? '') + +const sectionIds = (): string[] => [...document.querySelectorAll('[data-settings-page]')].map((p) => p.dataset['settingsPage'] ?? '') + +commands.add({ + id: 'settings.controls', + label: 'Preferences: the controls of a section, with their current values', + risk: 'read', + params: { section: { type: 'string', enum: sectionIds, description: 'the section' } }, + run: (args = {}) => { + const controls = [...settingsPage(str(args['section'])).querySelectorAll(CONTROLS)].flatMap((el) => { + const key = keyOf(el) + if (!key || NEVER.test(key)) return [] + const row = el.closest('.settings-row')?.querySelector('.settings-label strong')?.textContent ?? el.getAttribute('aria-label') ?? (el.tagName === 'BUTTON' ? el.textContent : '') ?? '' + const input = el as HTMLInputElement + const kind = el.tagName === 'INPUT' ? input.type : el.tagName.toLowerCase() + const value = kind === 'checkbox' || kind === 'radio' ? { checked: input.checked } + : kind === 'password' ? { set: input.value !== '' } + : el.tagName === 'BUTTON' ? (el.hasAttribute('aria-pressed') ? { pressed: el.getAttribute('aria-pressed') === 'true' } : {}) + : { value: String(input.value).slice(0, 200) } + return [{ control: key, kind, label: row.trim().slice(0, 80), ...value, ...((el as HTMLButtonElement).disabled ? { disabled: true } : {}) }] + }) + return { section: str(args['section']), controls } + }, +}) + +commands.add({ + id: 'settings.set', + label: 'Preferences: set or press one control of a section (settings.controls lists them)', + params: { + section: { type: 'string', enum: sectionIds, description: 'the section' }, + control: { type: 'string', description: 'the control, as settings.controls names it' }, + value: { type: 'string', optional: true, description: 'for a text, number or select control' }, + checked: { type: 'boolean', optional: true, description: 'for a checkbox' }, + }, + risk: (args) => { + // Refused before anyone is asked (the bridge describes a command, with its risk, before it asks). + if (NEVER.test(str(args['control']))) throw new Error('Outside agents is the person\'s own choice; ask them to change it in Preferences, Agents') + try { return isChoice(control(str(args['section']), str(args['control']))) ? 'change' : 'destructive' } catch { return 'destructive' } + }, + run: (args = {}) => { + openSettings(str(args['section'])) + const el = control(str(args['section']), str(args['control'])) + if ((el as HTMLButtonElement).disabled) throw new Error(`${str(args['control'])} is turned off now`) + const input = el as HTMLInputElement + if (el.tagName === 'BUTTON') el.click() + else if (input.type === 'checkbox' || input.type === 'radio') { + if (typeof args['checked'] !== 'boolean') throw new Error('give checked for a checkbox') + if (input.checked !== args['checked']) input.click() + } else { + if (typeof args['value'] !== 'string') throw new Error('give value for this control') + input.value = args['value'] + if (input.value !== args['value']) throw new Error(`${str(args['value'])} is not a value this control takes`) + el.dispatchEvent(new Event('input', { bubbles: true })) + el.dispatchEvent(new Event('change', { bubbles: true })) + } + return { section: str(args['section']), control: str(args['control']) } + }, +}) + const THEMES = ['system', 'dark', 'light'] as const const MODES = ['screen', 'camera', 'audio'] as const const QUALITIES = ['720p', '1080p', '1440p', '2160p'] as const From d94c593cf911c46af187285f1731d966a46a7660 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:25:03 -0500 Subject: [PATCH 07/25] docs(agents): the guide and the harness skill name settings.controls and settings.set (0.12.0) The commit before made every Preferences control reachable through two generic commands; formrec_guide and the formrec-harness skill now say so, that a Save is a change while other buttons ask the person, and that Outside agents is never offered. --- .claude/skills/formrec-harness/SKILL.md | 2 +- src/mcp/guide.ts | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.claude/skills/formrec-harness/SKILL.md b/.claude/skills/formrec-harness/SKILL.md index 38517c7..7a836d3 100644 --- a/.claude/skills/formrec-harness/SKILL.md +++ b/.claude/skills/formrec-harness/SKILL.md @@ -49,7 +49,7 @@ When a FormREC window is open, its whole command registry is yours: `formrec_win - The studio: `studio.configure` (layout, target, quality), `studio.start`, `studio.pause`, `studio.resume`, `studio.stop`, `studio.restart`, `studio.cancel`, `studio.rewind`, `studio.camera`, `studio.screenshot`, `studio.notes`; drawing with `annotate.*`; the camera bubble with `effects.*`. - The player: `player.play`, `player.pause`, `player.seek` (`ms`, `play?`), `player.panel` (chapters, transcripts, engage-comments, engage-tasks, voiceover, keycast, autozoom...). - A recording's menus: `recording.action` with `id` and `action` (share, edit, duplicate, documents-rename, documents-export, interactive, clips, library-trash...). -- Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow). +- Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow), and every section's form: `settings.controls` (section) lists its controls with their values, `settings.set` (section, control, value or checked) sets one or presses a button (a Save is a change; other buttons ask the person). Outside agents is the person's choice and is never offered. Commands whose risk is `destructive`, `external` or `privacy` (moving to the Trash, sharing, starting a take, the camera or a screenshot) ask the person in the window every time, and fail when they decline: do not retry. Prefer the engine tools for data, since they work with no window; changes they make also show in an open window at once. diff --git a/src/mcp/guide.ts b/src/mcp/guide.ts index e8b27a0..8be8e45 100644 --- a/src/mcp/guide.ts +++ b/src/mcp/guide.ts @@ -75,8 +75,9 @@ a track per source). Everything a person can do in the window, you can do too, when a FormREC window is open: formrec_window_commands lists its commands (pages with nav.go, the menus, the studio's studio.start, studio.stop and the rest, drawing tools, player.seek and player.panel, the library -card and player menus with recording.action, Preferences with settings.open, prefs.get and -prefs.set), compactly, with each one's args and risk; pass id to see one in full. Run one with +card and player menus with recording.action, Preferences with settings.open, prefs.get, prefs.set, +and any control of any section with settings.controls and settings.set), compactly, with each +one's args and risk; pass id to see one in full. Run one with formrec_window_command_run; the window shows the result at once. A command whose risk is destructive, external or privacy (deleting, publishing, the camera, microphone or screen) asks the person in the window every time. Prefer the engine tools for data (they work without a window) and From a2682923688e30c0b53ac3a2b537a57863a5add4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:27:09 -0500 Subject: [PATCH 08/25] feat(web): any control of the open page is reachable by agents, and every studio control asks first (0.12.0) After the named commands and the Preferences pair, what a person could still do and an agent could not were the controls of the pages themselves: the studio's inspector panels (devices, live, guests, script, sound), the library's search and filters, the editors' fields. view.controls and view.set reach them the way settings.controls and settings.set reach Preferences, through one set of helpers now shared by both: - view.controls { query? }: every control of the open page that has a data attribute, named by it, with kind, label and value (a select lists its options; a password says only whether it is set; a file picker has no value), at most 150, filtered by words. - view.set { control, value?, checked? }: sets, ticks or presses one. A file picker is refused (it needs the person; the import tools exist). In the studio every view.set is privacy, since any control there may choose or turn on a camera, microphone or screen, so the person is asked each time. Elsewhere fields, choices and Save are changes, and other buttons, or a control that cannot be found when the risk is judged, are destructive and ask. Outside agents stays out of reach here too. Checked live: 163 studio controls listed; studio quality 720p asked (privacy), allowed once, set; the library search typed with no question; settings.controls unchanged after the refactor. --- web/src/agent-commands.ts | 118 +++++++++++++++++++++++++++----------- 1 file changed, 86 insertions(+), 32 deletions(-) diff --git a/web/src/agent-commands.ts b/web/src/agent-commands.ts index 15a3bb8..8d9cc08 100644 --- a/web/src/agent-commands.ts +++ b/web/src/agent-commands.ts @@ -260,13 +260,52 @@ function keyOf(el: Element): string | undefined { return attr.value ? `${name}=${attr.value}` : name } -function control(section: string, key: string): HTMLElement { +/** The one control under root that key names (settings.controls and view.controls list them). */ +function controlIn(root: HTMLElement, where: string, key: string, lister: string): HTMLElement { if (NEVER.test(key)) throw new Error('Outside agents is the person\'s own choice; ask them to change it in Preferences, Agents') - const all = [...settingsPage(section).querySelectorAll(CONTROLS)].filter((el) => keyOf(el) === key) - if (all.length !== 1) throw new Error(all.length ? `${key} names ${all.length} controls in ${section}` : `no control ${key} in ${section}; settings.controls lists them`) + const all = [...root.querySelectorAll(CONTROLS)].filter((el) => keyOf(el) === key) + if (all.length !== 1) throw new Error(all.length ? `${key} names ${all.length} controls in ${where}` : `no control ${key} in ${where}; ${lister} lists them`) return all[0]! } +const control = (section: string, key: string): HTMLElement => controlIn(settingsPage(section), section, key, 'settings.controls') + +/** Every control under root that has a data attribute: its key, kind, label and current value (never a password). */ +function listControls(root: HTMLElement): Record[] { + return [...root.querySelectorAll(CONTROLS)].flatMap((el) => { + const key = keyOf(el) + if (!key || NEVER.test(key)) return [] + const row = el.closest('.settings-row')?.querySelector('.settings-label strong')?.textContent ?? el.getAttribute('aria-label') ?? el.getAttribute('title') ?? (el.tagName === 'BUTTON' ? el.textContent : '') ?? '' + const input = el as HTMLInputElement + const kind = el.tagName === 'INPUT' ? input.type : el.tagName.toLowerCase() + const value = kind === 'checkbox' || kind === 'radio' ? { checked: input.checked } + : kind === 'password' ? { set: input.value !== '' } + : kind === 'file' ? {} + : el.tagName === 'BUTTON' ? (el.hasAttribute('aria-pressed') ? { pressed: el.getAttribute('aria-pressed') === 'true' } : {}) + : el.tagName === 'SELECT' ? { value: input.value, options: [...(el as HTMLSelectElement).options].filter((o) => !o.disabled).map((o) => o.value).slice(0, 40) } + : { value: String(input.value).slice(0, 200) } + return [{ control: key, kind, label: row.trim().replace(/\s+/g, ' ').slice(0, 80), ...value, ...((el as HTMLButtonElement).disabled ? { disabled: true } : {}) }] + }) +} + +/** Sets a field or select, ticks a checkbox or presses a button, as a person's edit does. */ +function setControl(el: HTMLElement, key: string, args: Record): void { + if ((el as HTMLButtonElement).disabled) throw new Error(`${key} is turned off now`) + const input = el as HTMLInputElement + if (el.tagName === 'BUTTON') el.click() + else if (input.type === 'file') throw new Error('a file picker needs the person; use formrec_import or formrec_library_import') + else if (input.type === 'checkbox' || input.type === 'radio') { + if (typeof args['checked'] !== 'boolean') throw new Error('give checked for a checkbox') + if (input.checked !== args['checked']) input.click() + } else { + if (typeof args['value'] !== 'string') throw new Error('give value for this control') + input.value = args['value'] + if (input.value !== args['value']) throw new Error(`${args['value']} is not a value this control takes`) + el.dispatchEvent(new Event('input', { bubbles: true })) + el.dispatchEvent(new Event('change', { bubbles: true })) + } +} + /** Fields, pressed-or-not choices, tabs and Save buttons change settings; any other button may remove or send. */ const isChoice = (el: HTMLElement): boolean => el.tagName !== 'BUTTON' || el.hasAttribute('aria-pressed') || el.getAttribute('role') === 'tab' || /(^|-)save(-|=|$)/.test(keyOf(el)?.split('=')[0] ?? '') @@ -278,21 +317,7 @@ commands.add({ label: 'Preferences: the controls of a section, with their current values', risk: 'read', params: { section: { type: 'string', enum: sectionIds, description: 'the section' } }, - run: (args = {}) => { - const controls = [...settingsPage(str(args['section'])).querySelectorAll(CONTROLS)].flatMap((el) => { - const key = keyOf(el) - if (!key || NEVER.test(key)) return [] - const row = el.closest('.settings-row')?.querySelector('.settings-label strong')?.textContent ?? el.getAttribute('aria-label') ?? (el.tagName === 'BUTTON' ? el.textContent : '') ?? '' - const input = el as HTMLInputElement - const kind = el.tagName === 'INPUT' ? input.type : el.tagName.toLowerCase() - const value = kind === 'checkbox' || kind === 'radio' ? { checked: input.checked } - : kind === 'password' ? { set: input.value !== '' } - : el.tagName === 'BUTTON' ? (el.hasAttribute('aria-pressed') ? { pressed: el.getAttribute('aria-pressed') === 'true' } : {}) - : { value: String(input.value).slice(0, 200) } - return [{ control: key, kind, label: row.trim().slice(0, 80), ...value, ...((el as HTMLButtonElement).disabled ? { disabled: true } : {}) }] - }) - return { section: str(args['section']), controls } - }, + run: (args = {}) => ({ section: str(args['section']), controls: listControls(settingsPage(str(args['section']))) }), }) commands.add({ @@ -311,24 +336,53 @@ commands.add({ }, run: (args = {}) => { openSettings(str(args['section'])) - const el = control(str(args['section']), str(args['control'])) - if ((el as HTMLButtonElement).disabled) throw new Error(`${str(args['control'])} is turned off now`) - const input = el as HTMLInputElement - if (el.tagName === 'BUTTON') el.click() - else if (input.type === 'checkbox' || input.type === 'radio') { - if (typeof args['checked'] !== 'boolean') throw new Error('give checked for a checkbox') - if (input.checked !== args['checked']) input.click() - } else { - if (typeof args['value'] !== 'string') throw new Error('give value for this control') - input.value = args['value'] - if (input.value !== args['value']) throw new Error(`${str(args['value'])} is not a value this control takes`) - el.dispatchEvent(new Event('input', { bubbles: true })) - el.dispatchEvent(new Event('change', { bubbles: true })) - } + setControl(control(str(args['section']), str(args['control'])), str(args['control']), args) return { section: str(args['section']), control: str(args['control']) } }, }) +// ---------- any control of the open page (studio panels, devices, live, library filters, editors) ---------- + +const viewRoot = (): HTMLElement => { + const view = document.getElementById('view') + if (!view) throw new Error('no page is open') + return view +} +const inStudio = (): boolean => /^#\/record/.test(location.hash) + +commands.add({ + id: 'view.controls', + label: 'The open page\'s controls (studio panels and devices, live, library filters, the editors...), with their values', + risk: 'read', + params: { query: { type: 'string', optional: true, description: 'words that must all be in the control or its label' } }, + run: (args = {}) => { + const words = str(args['query']).toLowerCase().split(/\s+/).filter(Boolean) + const all = listControls(viewRoot()).filter((c) => words.every((w) => `${String(c['control'])} ${String(c['label'])}`.toLowerCase().includes(w))) + return { page: location.hash.slice(1) || '/', count: all.length, controls: all.slice(0, 150), ...(all.length > 150 ? { more: all.length - 150 } : {}) } + }, +}) + +commands.add({ + id: 'view.set', + label: 'Set or press one control of the open page (view.controls lists them); prefer a named command when there is one', + params: { + control: { type: 'string', description: 'the control, as view.controls names it' }, + value: { type: 'string', optional: true, description: 'for a text, number or select control' }, + checked: { type: 'boolean', optional: true, description: 'for a checkbox' }, + }, + // In the studio any control may choose or turn on a camera, microphone or screen; elsewhere a button that is not a + // choice or a Save may remove or send something. Both ask the person. + risk: (args) => { + if (NEVER.test(str(args['control']))) throw new Error('Outside agents is the person\'s own choice; ask them to change it in Preferences, Agents') + if (inStudio()) return 'privacy' + try { return isChoice(controlIn(viewRoot(), 'this page', str(args['control']), 'view.controls')) ? 'change' : 'destructive' } catch { return 'destructive' } + }, + run: (args = {}) => { + setControl(controlIn(viewRoot(), 'this page', str(args['control']), 'view.controls'), str(args['control']), args) + return { page: location.hash.slice(1) || '/', control: str(args['control']) } + }, +}) + const THEMES = ['system', 'dark', 'light'] as const const MODES = ['screen', 'camera', 'audio'] as const const QUALITIES = ['720p', '1080p', '1440p', '2160p'] as const From 8f44ef7d6fcdcdb310f9c84ef414083c55a86816 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:27:18 -0500 Subject: [PATCH 09/25] docs(agents): the guide and the harness skill name view.controls and view.set (0.12.0) formrec_guide and the formrec-harness skill say that any other control of the open page (the studio's devices and panels, library filters, editors) is reached with view.controls and view.set, that a named command comes first, and that every view.set in the studio asks the person. --- .claude/skills/formrec-harness/SKILL.md | 1 + src/mcp/guide.ts | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.claude/skills/formrec-harness/SKILL.md b/.claude/skills/formrec-harness/SKILL.md index 7a836d3..4262403 100644 --- a/.claude/skills/formrec-harness/SKILL.md +++ b/.claude/skills/formrec-harness/SKILL.md @@ -50,6 +50,7 @@ When a FormREC window is open, its whole command registry is yours: `formrec_win - The player: `player.play`, `player.pause`, `player.seek` (`ms`, `play?`), `player.panel` (chapters, transcripts, engage-comments, engage-tasks, voiceover, keycast, autozoom...). - A recording's menus: `recording.action` with `id` and `action` (share, edit, duplicate, documents-rename, documents-export, interactive, clips, library-trash...). - Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow), and every section's form: `settings.controls` (section) lists its controls with their values, `settings.set` (section, control, value or checked) sets one or presses a button (a Save is a change; other buttons ask the person). Outside agents is the person's choice and is never offered. +- Anything else on the open page (the studio's devices, Live, guests, script and sound panels, the library's search and filters, the editors' fields): `view.controls` (query) lists its controls, `view.set` sets or presses one. Use a named command when there is one. Every `view.set` in the studio asks the person. Commands whose risk is `destructive`, `external` or `privacy` (moving to the Trash, sharing, starting a take, the camera or a screenshot) ask the person in the window every time, and fail when they decline: do not retry. Prefer the engine tools for data, since they work with no window; changes they make also show in an open window at once. diff --git a/src/mcp/guide.ts b/src/mcp/guide.ts index 8be8e45..395f26f 100644 --- a/src/mcp/guide.ts +++ b/src/mcp/guide.ts @@ -76,8 +76,9 @@ Everything a person can do in the window, you can do too, when a FormREC window formrec_window_commands lists its commands (pages with nav.go, the menus, the studio's studio.start, studio.stop and the rest, drawing tools, player.seek and player.panel, the library card and player menus with recording.action, Preferences with settings.open, prefs.get, prefs.set, -and any control of any section with settings.controls and settings.set), compactly, with each -one's args and risk; pass id to see one in full. Run one with +and any control of any section with settings.controls and settings.set; any other control of the +open page, such as the studio's devices and Live panel, with view.controls and view.set), +compactly, with each one's args and risk; pass id to see one in full. Run one with formrec_window_command_run; the window shows the result at once. A command whose risk is destructive, external or privacy (deleting, publishing, the camera, microphone or screen) asks the person in the window every time. Prefer the engine tools for data (they work without a window) and From 293998c58bd8fcc5acbb8fb3016218737d3a938f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:30:02 -0500 Subject: [PATCH 10/25] fix(agents): Settings, Agents finds and runs claude the way the dock does (0.12.0) Settings, Agents (GET /api/agents and Connect, POST /api/agents/install) found claude and codex with a bare which() over the engine's PATH, so in the desktop app started from the Finder or the Dock it said "the claude command is not installed here" while the dock, after fd10486, found it. The feature now looks claude and codex up with the dock's lookup (src/dock/lookup.ts: the engine's PATH, the known install folders, the login shell's PATH) and passes the result to clientStatus as find and to installClient, installHttpClient and installRelayClient as claudeBin. A status read never waits on the shell; a Connect for Claude Code asks the shell again first when claude is missing. claudeReplace runs `claude mcp remove/add` with the new optional Env.toolEnv when one is given: this process's environment with the PATH an agent program needs (programs.ts toolEnv), so an npm-installed claude (#!/usr/bin/env node) finds node. Without toolEnv, as in `formrec agents` from a terminal, nothing changes. --- src/agents/clients.ts | 14 +++++++++--- src/dock/programs.ts | 7 ++++++ src/features/agents/index.ts | 41 +++++++++++++++++++++++++++--------- 3 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/agents/clients.ts b/src/agents/clients.ts index 3adc788..d5e0a63 100644 --- a/src/agents/clients.ts +++ b/src/agents/clients.ts @@ -46,6 +46,12 @@ export interface Env { env: NodeJS.ProcessEnv /** File existence (tests pass their own). */ exists?: (file: string) => boolean + /** + * The environment the claude command runs with, when it is not this process's (the app's Settings, Agents passes one + * whose PATH holds the login shell's and the known install folders, src/dock/lookup.ts, so an npm-installed claude + * finds node when the app was started from the Finder or the Dock). Default: this process's environment. + */ + toolEnv?: NodeJS.ProcessEnv } /** @@ -185,10 +191,12 @@ export function which(bin: string, env: NodeJS.ProcessEnv = process.env, platfor * Connect runs this inside the server, which must never hang on a stuck claude command. Returns why the add failed. */ export function claudeReplace(bin: string, name: string, addArgs: string[], e: Env): string | undefined { - const le: LaunchEnv = { platform: e.platform, env: e.env, exists: e.exists, which: (b) => which(b, e.env, e.platform) } + const runEnv = e.toolEnv ?? e.env + const le: LaunchEnv = { platform: e.platform, env: runEnv, exists: e.exists, which: (b) => which(b, runEnv, e.platform) } + const own = e.toolEnv ? { env: e.toolEnv } : {} try { - runTool(bin, ['mcp', 'remove', name, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }, le) - const add = runTool(bin, ['mcp', 'add', ...addArgs], { encoding: 'utf8', timeout: 15_000 }, le) + runTool(bin, ['mcp', 'remove', name, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000, ...own }, le) + const add = runTool(bin, ['mcp', 'add', ...addArgs], { encoding: 'utf8', timeout: 15_000, ...own }, le) return add.status === 0 ? undefined : (add.stderr || add.stdout || add.error?.message || '').trim() } catch (err) { if (err instanceof LaunchRefused) return err.message diff --git a/src/dock/programs.ts b/src/dock/programs.ts index be0dc5c..9a0fcdd 100644 --- a/src/dock/programs.ts +++ b/src/dock/programs.ts @@ -72,6 +72,13 @@ export async function agentEnv(file: string, extra: Record = {}) return { ...env, PATH } } +/** base with the PATH an agent program needs to start (see lookup.ts `agentPath`); for Settings, Agents' claude runs. */ +export async function toolEnv(file: string | undefined, base: NodeJS.ProcessEnv = process.env): Promise { + const env: NodeJS.ProcessEnv = { ...base } + if (process.platform === 'win32') for (const k of Object.keys(env)) if (k.toUpperCase() === 'PATH') delete env[k] + return { ...env, PATH: await agentPath(file, SPECS, { env: base }) } +} + function versionOf(file: string, env: Record): Promise { const known = versions.get(file) if (known && Date.now() - known.at < VERSION_KEEP_MS) return known.value diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index e25a336..d313843 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -19,7 +19,8 @@ import { z } from 'zod' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' import type { Feature, FeatureContext } from '../types.js' -import { CLIENT_IDS, clientStatus, currentEnv, findRoot, HTTP_CLIENT_IDS, installClient, installHttpClient, isHttpClient, serverEntry, type HttpEndpoint } from '../../agents/clients.js' +import { CLIENT_IDS, clientStatus, currentEnv, findRoot, HTTP_CLIENT_IDS, installClient, installHttpClient, isHttpClient, serverEntry, which, type Env, type HttpEndpoint } from '../../agents/clients.js' +import { locate, locateFound, toolEnv } from '../../dock/programs.js' import { installRelayClient, relaySnippet, relayState } from '../../agents/relay-clients.js' import { mcpToken, rotateMcpToken } from '../../mcp/token.js' import { rotatePlayerLinks } from '../../server/player-link.js' @@ -70,10 +71,30 @@ async function listTools(ctx: FeatureContext): Promise { } } -function state(ep: HttpEndpoint) { +interface Located { e: Env; find: (bin: string) => string | undefined; claudeBin: string | null } + +/** + * This account, with claude and codex found the way the dock finds them (src/dock/lookup.ts: the engine's PATH, the + * known install folders, the login shell's PATH), not by the engine's PATH alone: the desktop app started from the + * Finder or the Dock has launchd's short PATH. The claude command then runs with that PATH (Env.toolEnv). wait: a + * Connect press, which may wait for the shell to be asked again when claude is missing; a status read does not. + */ +async function located(wait: boolean): Promise { const e = currentEnv() + const look = (kind: 'claude' | 'codex'): Promise => (wait ? locate(kind) : locateFound(kind).then((f) => f.file)) + const [claude, codex] = await Promise.all([look('claude'), look('codex')]) + const files: Record = { claude, codex } + return { + e: { ...e, toolEnv: await toolEnv(claude) }, + find: (bin) => (bin in files ? files[bin] : which(bin)), + claudeBin: claude ?? null, + } +} + +async function state(ep: HttpEndpoint, at?: Located) { + const { e, find } = at ?? (await located(false)) const entry = serverEntry({ root: findRoot(), e }) - return { entry, clients: clientStatus(entry, e, undefined, ep) } + return { entry, clients: clientStatus(entry, e, find, ep) } } export const feature: Feature = { @@ -84,14 +105,14 @@ export const feature: Feature = { if (parts.length === 2 && method === 'GET') { toolNames ??= listTools(ctx).catch(() => []) const http = await endpoint(ctx) - const { entry, clients } = state(http) + const { entry, clients } = await state(http) sendJson(res, 200, { server: entry, clients, tools: await toolNames, http, relay: await relayInfo(ctx) }) return true } if (parts.length === 4 && parts[2] === 'mcp-token' && parts[3] === 'rotate' && method === 'POST') { await rotateMcpToken(ctx.dataDir) const http = await endpoint(ctx) - sendJson(res, 200, { http, clients: state(http).clients }) + sendJson(res, 200, { http, clients: (await state(http)).clients }) return true } if (parts.length === 4 && parts[2] === 'player-links' && parts[3] === 'rotate' && method === 'POST') { @@ -105,7 +126,7 @@ export const feature: Feature = { sendJson(res, 400, { error: `send { "client": ${CLIENT_IDS.map((c) => `"${c}"`).join(' | ')} }` }) return true } - const e = currentEnv() + const { e, find, claudeBin } = await located(parsed.data.client === 'claude') const entry = serverEntry({ root: findRoot(), e }) const http = await endpoint(ctx) try { @@ -115,8 +136,8 @@ export const feature: Feature = { if (!relay.connected || !relay.url) sendJson(res, 409, { error: 'not connected to a relay; connect one in Settings, Relay' }) else if (!isHttpClient(id)) sendJson(res, 400, { error: `${id} cannot connect to a relay` }) else { - const said = installRelayClient(id, { url: relay.url, e }) - sendJson(res, 200, { said, clients: clientStatus(entry, e, undefined, http), relay: await relayInfo(ctx) }) + const said = installRelayClient(id, { url: relay.url, e, claudeBin }) + sendJson(res, 200, { said, clients: clientStatus(entry, e, find, http), relay: await relayInfo(ctx) }) } return true } @@ -124,8 +145,8 @@ export const feature: Feature = { sendJson(res, 400, { error: `${id} cannot connect over HTTP` }) return true } - const said = parsed.data.transport === 'http' && isHttpClient(id) ? installHttpClient(id, { ep: http, e }) : installClient(id, { root: findRoot(), entry, e }) - sendJson(res, 200, { said, clients: clientStatus(entry, e, undefined, http) }) + const said = parsed.data.transport === 'http' && isHttpClient(id) ? installHttpClient(id, { ep: http, e, claudeBin }) : installClient(id, { root: findRoot(), entry, e, claudeBin }) + sendJson(res, 200, { said, clients: clientStatus(entry, e, find, http) }) } catch (error) { sendJson(res, 500, { error: (error as Error).message }) } From 6d2879feb53e1e41edfda0b1fec39fbf16b6667a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:31:53 -0500 Subject: [PATCH 11/25] fix(mcp): the window and job tools are not core tools, and the HTTP test's stdio is built as formrec mcp builds it (0.12.0) The window tools and the job tools exist only where the server has a window caller (the app's /mcp, `formrec mcp`, `formrec mcp --http`), so listing them in CORE_TOOLS broke the promise that a server starts with every core tool: mcp.test, mcp-tools.test and mcp-http-server.test failed on a server built with no window. They now have their own WINDOW_AND_JOB_TOOLS, registered right after the core tools; CORE_TOOLS is the nine it was. agents:sync therefore writes them into feature-tools.md beside the feature tools. mcp-http-server.test's stdioToolNames built a bare server as its model of stdio; serveMcp now adds the remote window caller, so the helper builds the same way and the test still checks that --http and stdio offer exactly the same tools in the same order. The assertions are unchanged. The 14 agent and MCP test files pass under the build lock (106 tests). --- src/mcp/server.ts | 9 ++++++--- tests/mcp-http-server.test.ts | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 3cebcfa..760079a 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -43,11 +43,14 @@ export const CORE_TOOLS = [ 'formrec_delete', 'formrec_open_in_formcut', 'formrec_demos', - // Only where the server has a window caller (the app, `formrec mcp`): the window's commands and background jobs. - ...WINDOW_TOOLS, - ...JOB_TOOLS, ] as const +/** + * Registered right after the core tools, but only where the server has a window caller (the app's /mcp, + * `formrec mcp` and `formrec mcp --http`): the window's commands and background jobs. Not on the relay's bridge. + */ +export const WINDOW_AND_JOB_TOOLS = [...WINDOW_TOOLS, ...JOB_TOOLS] as const + /** The ids a tool's arguments or answer name: the recordings a window should show again after an agent changed them. */ function changedIds(args: unknown, out: ToolReply): string[] { const ids: string[] = [] diff --git a/tests/mcp-http-server.test.ts b/tests/mcp-http-server.test.ts index c664036..727f34c 100644 --- a/tests/mcp-http-server.test.ts +++ b/tests/mcp-http-server.test.ts @@ -16,6 +16,7 @@ import { buildServer, CORE_TOOLS } from '../src/mcp/server.js' import { createMcpHttp, serveMcpHttp, type McpHttpServer } from '../src/mcp/http.js' import { mcpToken, rotateMcpToken, mcpTokenFile } from '../src/mcp/token.js' import { writeConsent } from '../src/mcp/consent.js' +import { remoteCaller } from '../src/window/bridge.js' import { Library } from '../src/store/library.js' import type { Recording } from '../src/model/recording.js' import { tempDir } from './helpers.js' @@ -30,7 +31,8 @@ type Text = { content: { type: string; text: string }[]; isError?: boolean } async function stdioToolNames(library: Library): Promise { const [a, b] = InMemoryTransport.createLinkedPair() - await buildServer({ library }, '0.5.0').connect(a) + // As serveMcp builds it: stdio reaches the running app's window (window/bridge.ts remoteCaller). + await buildServer({ library, window: remoteCaller(library.dataDir) }, '0.5.0').connect(a) const client = new Client({ name: 'stdio-side', version: '1' }) await client.connect(b) const names = (await client.listTools()).tools.map((t) => t.name) From d0d4a2e33a96e560eaf4c71a15291e26ded4d48f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:32:05 -0500 Subject: [PATCH 12/25] docs(agents): agents:sync lists the window and job tools and mirrors the harness skill (0.12.0) Regenerated by `npm run agents:sync` under the build lock from the live server (129 tools): feature-tools.md now has formrec_window_commands, formrec_window_command_run, formrec_job_start, formrec_job_status and formrec_job_cancel (120 tools there, from 115), and .agents/skills mirrors the harness SKILL.md's window section. tools.md changed only by the two new demos' rows, which belong to the demos work and are left to it. --- .agents/skills/formrec-harness/SKILL.md | 19 +++++++++++- .../references/feature-tools.md | 31 ++++++++++++++++++- .../references/feature-tools.md | 31 ++++++++++++++++++- 3 files changed, 78 insertions(+), 3 deletions(-) diff --git a/.agents/skills/formrec-harness/SKILL.md b/.agents/skills/formrec-harness/SKILL.md index 355382f..4262403 100644 --- a/.agents/skills/formrec-harness/SKILL.md +++ b/.agents/skills/formrec-harness/SKILL.md @@ -40,6 +40,22 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - `formrec_open_in_formcut` hands the recording to FormCut, the Form family video editor, when the person wants a full timeline edit (FormCut must be running). - `formrec_delete` removes a recording and its folder for good: only when the person asked, and with `confirm` repeating the id. +## The window: everything a person can do + +When a FormREC window is open, its whole command registry is yours: `formrec_window_commands` lists every command (id, label, `args` as `name?: type`, risk; `query` filters, `id` describes one in full with allowed values and whether it can run now), and `formrec_window_command_run` runs one with `args`, exactly as if the person chose it, and the window shows it at once. + +- Pages: `nav.go` with `page` (home, library and its tabs, studio, screen, camera, audio, the studio layouts, shared, notifications, insights, recently-watched, meetings, ask, tour, demo, recording, edit, annotate, clips, interactive, playlist; the last ones take `id`). `window.state` says what is open. +- Menus: every File, View and Help row by its menu id (`file.new-audio`, `view.library`, `help.demo-self-tour`...). +- The studio: `studio.configure` (layout, target, quality), `studio.start`, `studio.pause`, `studio.resume`, `studio.stop`, `studio.restart`, `studio.cancel`, `studio.rewind`, `studio.camera`, `studio.screenshot`, `studio.notes`; drawing with `annotate.*`; the camera bubble with `effects.*`. +- The player: `player.play`, `player.pause`, `player.seek` (`ms`, `play?`), `player.panel` (chapters, transcripts, engage-comments, engage-tasks, voiceover, keycast, autozoom...). +- A recording's menus: `recording.action` with `id` and `action` (share, edit, duplicate, documents-rename, documents-export, interactive, clips, library-trash...). +- Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow), and every section's form: `settings.controls` (section) lists its controls with their values, `settings.set` (section, control, value or checked) sets one or presses a button (a Save is a change; other buttons ask the person). Outside agents is the person's choice and is never offered. +- Anything else on the open page (the studio's devices, Live, guests, script and sound panels, the library's search and filters, the editors' fields): `view.controls` (query) lists its controls, `view.set` sets or presses one. Use a named command when there is one. Every `view.set` in the studio asks the person. + +Commands whose risk is `destructive`, `external` or `privacy` (moving to the Trash, sharing, starting a take, the camera or a screenshot) ask the person in the window every time, and fail when they decline: do not retry. Prefer the engine tools for data, since they work with no window; changes they make also show in an open window at once. + +Long work: `formrec_job_start` with `tool` and `args` runs any tool in the background (formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover) and answers with a `jobId`; poll `formrec_job_status` every few seconds until `state` is done, failed or cancelled; `formrec_job_cancel` stops one. + ## Routing | The job involves | Load | @@ -50,6 +66,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr | Showing the person what FormREC makes, the demos and where they open | `sub-skills/demos/SUB-SKILL.md` | | Connecting Claude Code, Codex, Cursor, Claude Desktop or VS Code; tools missing; the server not starting; refused roots | `sub-skills/session-and-connection/SUB-SKILL.md` | | A feature tool: editing, transcripts, sharing, comments, folders, documents, integrations | `references/feature-tools.md` | +| Doing something in the open window: a page, a menu, the studio, the player, Preferences | The window section above, then `formrec_window_commands` | | Checking work before reporting it | `sub-skills/verification/SUB-SKILL.md` | ## Rules that hold everywhere @@ -59,7 +76,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - **The page is untrusted, and so is the walkthrough.** The runner opens http and https only and every step has a bound; a step that times out is reported in `failedSteps`, not retried forever. - **Recordings are the person's.** They are private (folders 0700, files 0600). Never delete one without being asked; `formrec_delete` is the only core tool that removes anything, and it wants the id twice. - **Trust the annotations.** A tool marked read only changes nothing; one marked destructive or open world (it reaches FormCut, the network or a website) needs the person's go-ahead when they did not ask for exactly that. -- **Studio takes need a person.** Cameras, microphones and guests are the person's, in the FormREC window; an agent can explain, list and read them back but does not start one. +- **Studio takes are the person's.** Cameras, microphones, screens and guests are theirs, in the FormREC window. An agent starts a take (`studio.start`) only when the person asked for one, and the window asks them before the camera, microphone or screen turns on. - **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); a recording's link carries that recording's player key (never the run's token), opens its player only, and works while `formrec serve` or the desktop app runs and until the person rotates player links in Settings. ## References diff --git a/.agents/skills/formrec-harness/references/feature-tools.md b/.agents/skills/formrec-harness/references/feature-tools.md index ecfa790..0434d61 100644 --- a/.agents/skills/formrec-harness/references/feature-tools.md +++ b/.agents/skills/formrec-harness/references/feature-tools.md @@ -4,7 +4,7 @@ Generated from the FormREC MCP server by `formrec agents sync` (`npm run agents: The tools FormREC's feature modules add next to the core tools in tools.md: editing, transcripts, sharing, comments, the library, documents, integrations and the rest. Each carries a title and annotations; trust "Changes anything" and ask the person before a tool that removes or reaches outside FormREC. They take a recording id from `formrec_list` or `formrec_record` unless they say otherwise. -115 tools. +120 tools. ## Tools @@ -56,6 +56,9 @@ The tools FormREC's feature modules add next to the core tools in tools.md: edit | `formrec_integrations` | List integrations | no | Which services are connected (Slack, Teams, Jira, Linear, GitHub, GitLab, form.md, Confluence, calendar), their non-secret settings and last test, the outgoing webhooks, the twelve integration apps (Slack, Google, Salesforce, HubSpot, Zendesk, Intercom, GitHub, GitLab, Jira, Linear, form.md, Figma): for each its install folder and INSTALL.md, whether it is configured, which fields are set, the public address it uses (relay or tunnel) and whether that address answers, and the recorder SDK apps (id, mode, allowed origins, key ids, guest limits, and the relay script address). Secrets are never shown. Read this before posting or creating issues. | | `formrec_interactive_demo` | Build or read an interactive demo | yes | Make a click-through demo from a recording that has steps (a walkthrough): one picture per step, a hotspot over the element the step pointed at, the step's words as the callout, Back and Next, and an end card with the recording's call to action when it has one. Builds it when there is none (or when build is true; the owner's edits are kept), otherwise reads it. A person's recording with chapters gets its recorded clicks as hotspots, and one with only clicks gets a step per click. Returns the steps (id, title, text, hidden, hotspot in the picture's pixels), the viewers' insights (views, where they stop, hotspot against Next, call to action, completion; shown steps only), the languages it can be translated into and the demo links on the share servers (/i/[shareId], and ?embed=1 for an embed), which exist once the recording is shared. Needs FFmpeg. | | `formrec_interactive_export` | Export an interactive demo as a zip | yes | Write the recording's demo as a zip with demo.html and its pictures. The page works offline, from a file or any static host. Hidden steps are left out. Build the demo first with formrec_interactive_demo. | +| `formrec_job_cancel` | Cancel a background job | yes | Stop a running job, as cancelling the tool call would (formrec_record saves nothing when cancelled). A job that already ended is left as it is. | +| `formrec_job_start` | Start a tool as a background job | yes | Run any other FormREC tool (for example formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover, formrec_walkthrough_rerecord) in the background and answer at once with a jobId. Poll formrec_job_status every few seconds until state is done, failed or cancelled; the result is then exactly what the tool would have answered. Use it for anything that can take more than a few seconds. | +| `formrec_job_status` | Poll a background job | no | A job's state (running, done, failed, cancelled), its latest progress, and once it ended the tool's result or error. Without jobId: every job of this server, newest first, without results. | | `formrec_keycast` | Keystrokes on screen | yes | Show or change the keys drawn over a recording: whether they are on, where (bottom-left, bottom-center, bottom-right, top-left, top-center, top-right), the size (1 to 5), how long each shows (400 to 6000 ms), and whether share pages show them (share). A walkthrough records its presses (Ctrl+K, Enter, Tab x3) and counts of typed characters (never the characters, nothing for a secret); a tab recorded with the browser extension with keystrokes on brings shortcuts and named keys. The reply has counts and the choices, not the keys themselves. Give only the recording to read. | | `formrec_library_archive` | Archive or unarchive recordings | yes | Archived recordings leave the library's Videos tab for its Archive tab; unarchive returns them where they were. Nothing is deleted. | | `formrec_library_export` | Export recordings to a folder | yes | Copy recordings (all of them when ids is omitted) with every file and a formrec-library.json manifest of their tags, folders and spaces into a new `formrec-export-