From 5c4645f0a0a6b45b6c525e0b9c122795b332222e Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 09:51:58 +0900 Subject: [PATCH 01/96] feat(cua): define self-window driver and surface contracts --- src/preload/index.ts | 13 ++++++++++ src/shared/cua.ts | 62 ++++++++++++++++++++++++++++++++++++++++++++ src/shared/ipc.ts | 4 +++ 3 files changed, 79 insertions(+) create mode 100644 src/shared/cua.ts diff --git a/src/preload/index.ts b/src/preload/index.ts index cc85ada3..568363a3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,4 +1,5 @@ import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'; +import type { CuaState, CuaStopResult, CuaSurfaceSnapshot } from '../shared/cua'; import type { AgentChatApprovalInput, @@ -64,6 +65,10 @@ type AssetPlaybackUrl = { }; export interface VideoToolApi { + cuaGetState(): Promise>; + cuaStop(): Promise>; + cuaReportSurfaceSnapshot(snapshot: CuaSurfaceSnapshot): Promise>; + onCuaStateChanged(listener: (state: CuaState) => void): () => void; shortsStart(input: ShortsStartInput): Promise>; shortsGet(input: ShortsJobInput): Promise>; shortsList(input: ShortsListInput): Promise>; @@ -153,6 +158,14 @@ function parseUpdaterSnapshot(payload: unknown): UpdaterSnapshot | null { } const videoTool: VideoToolApi = { + cuaGetState: () => ipcRenderer.invoke(IPC_CHANNELS.cuaGetState) as Promise>, + cuaStop: () => ipcRenderer.invoke(IPC_CHANNELS.cuaStop) as Promise>, + cuaReportSurfaceSnapshot: snapshot => ipcRenderer.invoke(IPC_CHANNELS.cuaReportSurfaceSnapshot, snapshot) as Promise>, + onCuaStateChanged: listener => { + const subscription = (_event: IpcRendererEvent, state: CuaState): void => listener(state); + ipcRenderer.on(IPC_CHANNELS.cuaStateChanged, subscription); + return () => ipcRenderer.removeListener(IPC_CHANNELS.cuaStateChanged, subscription); + }, shortsStart: input => ipcRenderer.invoke(IPC_CHANNELS.shortsStart, input) as Promise>, shortsGet: input => ipcRenderer.invoke(IPC_CHANNELS.shortsGet, input) as Promise>, shortsList: input => ipcRenderer.invoke(IPC_CHANNELS.shortsList, input) as Promise>, diff --git a/src/shared/cua.ts b/src/shared/cua.ts new file mode 100644 index 00000000..a319508e --- /dev/null +++ b/src/shared/cua.ts @@ -0,0 +1,62 @@ +/** Desktop self-window CUA v1. All positions are viewport CSS pixels. */ +export interface CuaPoint { readonly x: number; readonly y: number } +export interface CuaRect extends CuaPoint { readonly width: number; readonly height: number } +export interface CuaSurfaceSnapshot { + readonly layoutRevision: number; + readonly viewport: { readonly width: number; readonly height: number }; + readonly safeSurface: { readonly kind: 'timeline' | 'canvas' | 'shorts-review'; readonly rect: CuaRect; readonly interactive: boolean } | null; + readonly protectedRects: readonly { readonly id: string; readonly kind: 'stop-button' | 'approval-ui' | 'agent-panel' | 'settings' | 'chrome-menu' | 'modal'; readonly rect: CuaRect }[]; + readonly focusedInSafeSurface: boolean; + readonly focusedTestId: string | null; +} +export interface CuaFrame { + readonly sessionId: string; + readonly runId: string; + readonly windowId: number; + readonly frameId: string; + readonly layoutRevision: number; + readonly capturedAt: number; + readonly viewport: { readonly width: number; readonly height: number }; + readonly bitmap: { readonly width: number; readonly height: number }; + readonly deviceScaleFactor: number; + readonly zoomFactor: number; + readonly pngDataUrl: string; +} +export const CUA_KEYS = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Delete', 'Backspace', 'Space', 'z', 'y'] as const; +export type CuaKey = typeof CUA_KEYS[number]; +export type CuaAction = + | { readonly kind: 'click'; readonly point: CuaPoint } + | { readonly kind: 'drag'; readonly from: CuaPoint; readonly to: CuaPoint; readonly durationMs: number } + | { readonly kind: 'key'; readonly key: CuaKey; readonly modifiers: readonly ('shift' | 'control' | 'meta' | 'alt')[] }; +/** Main-only approval issuer binds a one-use permit to this exact request. */ +export interface CuaActionRequest { + readonly sessionId: string; + readonly runId: string; + readonly windowId: number; + readonly frameId: string; + readonly layoutRevision: number; + readonly action: CuaAction; +} +export type CuaPhase = 'idle' | 'ready' | 'acting' | 'stopping' | 'stopped' | 'cleanup-failed'; +export interface CuaState { + readonly sessionId: string | null; + readonly runId: string | null; + readonly windowId: number; + readonly phase: CuaPhase; + readonly cursor: CuaPoint | null; + readonly dragStart: CuaPoint | null; + readonly target: CuaPoint | null; + readonly label: string | null; + readonly error: string | null; + readonly cleanupComplete: boolean; + readonly releaseFailures: readonly string[]; +} +export interface CuaStopResult { readonly accepted: boolean } + +/** Pixel conversion uses the actual returned bitmap, never DPR alone. */ +export function cuaBitmapPointToViewport(frame: Pick, point: CuaPoint): CuaPoint { + if (![point.x, point.y, frame.bitmap.width, frame.bitmap.height, frame.viewport.width, frame.viewport.height].every(Number.isFinite) + || frame.bitmap.width <= 0 || frame.bitmap.height <= 0 || frame.viewport.width <= 0 || frame.viewport.height <= 0 + || point.x < 0 || point.y < 0 || point.x >= frame.bitmap.width || point.y >= frame.bitmap.height) throw new Error('CUA_OUT_OF_BOUNDS'); + return { x: point.x * frame.viewport.width / frame.bitmap.width, y: point.y * frame.viewport.height / frame.bitmap.height }; +} diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index a3c611ed..238775cf 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -1,4 +1,8 @@ export const IPC_CHANNELS = { + cuaGetState: 'cua:get-state', + cuaStop: 'cua:stop', + cuaReportSurfaceSnapshot: 'cua:report-surface-snapshot', + cuaStateChanged: 'cua:state-changed', shortsStart: 'shorts:start', shortsGet: 'shorts:get', shortsList: 'shorts:list', From a1369cbd8ed6bcecab764dd66fbfb5a5a4fecb71 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 09:53:44 +0900 Subject: [PATCH 02/96] feat(agent): define CUA approval presentation contract --- src/shared/agentChat.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/shared/agentChat.ts b/src/shared/agentChat.ts index 4e96ca98..ce57474b 100644 --- a/src/shared/agentChat.ts +++ b/src/shared/agentChat.ts @@ -14,8 +14,39 @@ export interface AgentToolCallProposal { readonly toolCallId: string; readonly toolName: string; readonly args: Record; + /** Display evidence only; never an execution permit or an approval authority. */ + readonly cuaApproval?: AgentCuaApprovalSummary | undefined; } +/** + * A projection of the exact observed action awaiting approval. Coordinates are + * displayed in the coordinate system named here; the driver owns conversion + * and validation. Changing this evidence requires a new proposal and approval. + */ +export interface AgentCuaApprovalSummary { + readonly actionKind: 'click' | 'key' | 'drag'; + readonly actionLabel: string; + readonly frameId: string; + readonly scopeRevision: string | number; + readonly coordinateSpace?: 'css' | 'bitmap' | undefined; + readonly coords?: { readonly x: number; readonly y: number } | undefined; + readonly dragTo?: { readonly x: number; readonly y: number } | undefined; +} + +/** Stable presentation codes; the main process remains the source of errors. */ +export type AgentCuaErrorCode = + | 'CUA_FRAME_STALE' + | 'CUA_FRAME_EXPIRED' + | 'CUA_SCOPE_CHANGED' + | 'CUA_APPROVAL_EXPIRED' + | 'CUA_APPROVAL_MISMATCH' + | 'CUA_ACTION_REPLAYED' + | 'CUA_BUDGET_EXCEEDED' + | 'CUA_CANCELLED' + | 'CUA_BUSY' + | 'CUA_TARGET_GONE' + | 'CUA_CLEANUP_FAILED'; + export type AgentChatStatus = 'idle' | 'thinking' | 'awaiting-approval' | 'error'; /** @@ -34,6 +65,7 @@ export interface AgentChatTurnState { readonly pendingApproval: AgentToolCallProposal | null; readonly status: AgentChatStatus; readonly error?: string | undefined; + readonly errorCode?: AgentCuaErrorCode | undefined; readonly contextUsage?: AgentChatContextUsage | undefined; } @@ -77,6 +109,11 @@ export interface AgentChatResetInput { readonly conversationId: string; } +/** Cancel the named conversation; main must settle input release before returning. */ +export interface AgentChatCancelInput { + readonly conversationId: string; +} + /** One persisted Edit Agent conversation, stored inside its project folder. */ export interface AgentChatStoredConversation { readonly id: string; From ee7a24f3ff91c31bee09c0477b60e1e9405cea18 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 09:57:34 +0900 Subject: [PATCH 03/96] feat(cua): report renderer execution block independently of layout --- src/shared/cua.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/shared/cua.ts b/src/shared/cua.ts index a319508e..55d7406b 100644 --- a/src/shared/cua.ts +++ b/src/shared/cua.ts @@ -2,6 +2,8 @@ export interface CuaPoint { readonly x: number; readonly y: number } export interface CuaRect extends CuaPoint { readonly width: number; readonly height: number } export interface CuaSurfaceSnapshot { + readonly executionBlocked: boolean; + readonly blockReason: string | null; readonly layoutRevision: number; readonly viewport: { readonly width: number; readonly height: number }; readonly safeSurface: { readonly kind: 'timeline' | 'canvas' | 'shorts-review'; readonly rect: CuaRect; readonly interactive: boolean } | null; From 63eac3a18071c672b3fc8b86c10d2e093deca1ef Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:01:07 +0900 Subject: [PATCH 04/96] feat(cua): add scoped input driver and release lifecycle --- scripts/probe-cua-input.cjs | 30 ++++++ src/main/cuaDriver.ts | 177 ++++++++++++++++++++++++++++++++++++ src/main/cuaIpc.ts | 24 +++++ tests/cuaDriver.test.ts | 97 ++++++++++++++++++++ 4 files changed, 328 insertions(+) create mode 100644 scripts/probe-cua-input.cjs create mode 100644 src/main/cuaDriver.ts create mode 100644 src/main/cuaIpc.ts create mode 100644 tests/cuaDriver.test.ts diff --git a/scripts/probe-cua-input.cjs b/scripts/probe-cua-input.cjs new file mode 100644 index 00000000..e87e9128 --- /dev/null +++ b/scripts/probe-cua-input.cjs @@ -0,0 +1,30 @@ +// Local Electron API experiment. No debugger, OS input, or external window control. +const { app, BrowserWindow } = require('electron'); +const fs = require('node:fs'); +const path = require('node:path'); +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +app.whenReady().then(async () => { + const win = new BrowserWindow({ width: 700, height: 400, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); + const before = []; let injecting = false; + win.webContents.on('before-input-event', (_, input) => before.push({ event: 'key', injecting, ...input })); + win.webContents.on('before-mouse-event', (_, input) => before.push({ event: 'mouse', injecting, ...input })); + await win.loadURL('data:text/html,' + encodeURIComponent(`
clip
lane
`)); + if (process.env.CUA_PROBE_POINTER === '1') await win.webContents.executeJavaScript(`document.getElementById('clip').draggable=false;document.getElementById('clip').onpointerdown=e=>{e.currentTarget.setPointerCapture(e.pointerId);};void 0;`); + win.focus(); + await delay(300); + const focused = { window: win.isFocused(), contents: win.webContents.isFocused() }; + const send = (type,x,y,down=false) => {injecting=true;try{win.webContents.sendInputEvent({type,x,y,button:'left',clickCount:1,modifiers:down?['leftbuttondown']:[]});}finally{injecting=false;}}; + send('mouseMove',40,30); send('mouseDown',40,30,true); + for(let y=35;y<=150;y+=5){send('mouseMove',40,y,true);await delay(16);} + send('mouseUp',40,150); + win.webContents.sendInputEvent({type:'keyDown',keyCode:'z',modifiers:['meta']}); + win.webContents.sendInputEvent({type:'keyUp',keyCode:'z',modifiers:['meta']}); + await delay(300); + const events = await win.webContents.executeJavaScript('window.events'); + const out = process.env.CUA_PROBE_DIR || '/tmp/openscene-cua-probe'; + fs.mkdirSync(out,{recursive:true}); + fs.writeFileSync(path.join(out,'input.json'),JSON.stringify({focused,before,events},null,2)); + fs.writeFileSync(path.join(out,'capture.png'),(await win.webContents.capturePage()).toPNG()); + console.log(JSON.stringify({out,focused,beforeTypes:before.map(e=>e.type),domTypes:events.map(e=>e.type)})); + win.destroy();app.exit(0); +}).catch(error=>{console.error(error);app.exit(1);}); diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts new file mode 100644 index 00000000..6fab8f6e --- /dev/null +++ b/src/main/cuaDriver.ts @@ -0,0 +1,177 @@ +import { randomUUID } from 'node:crypto'; +import { performance } from 'node:perf_hooks'; +import type { BrowserWindow, KeyboardInputEvent, MouseInputEvent } from 'electron'; +import { CUA_KEYS, type CuaActionRequest, type CuaFrame, type CuaPoint, type CuaRect, type CuaState, type CuaSurfaceSnapshot } from '../shared/cua'; + +export interface CuaDriverDependencies { + readonly consumePermit: (request: CuaActionRequest, permit: unknown) => void; + readonly onCancel?: (context: { sessionId: string | null; runId: string | null; reason: string }) => void; + readonly onState?: (state: CuaState) => void; +} +const inside = (p: CuaPoint, r: CuaRect): boolean => Number.isFinite(p.x) && Number.isFinite(p.y) && p.x >= r.x && p.y >= r.y && p.x < r.x + r.width && p.y < r.y + r.height; +function crosses(a: CuaPoint, b: CuaPoint, r: CuaRect): boolean { + let lo = 0, hi = 1; + for (const [origin, delta, min, max] of [[a.x, b.x - a.x, r.x, r.x + r.width], [a.y, b.y - a.y, r.y, r.y + r.height]]) { + if (origin === undefined || delta === undefined || min === undefined || max === undefined) return true; + if (delta === 0) { if (origin < min || origin > max) return false; continue; } + const t0 = (min - origin) / delta, t1 = (max - origin) / delta; + lo = Math.max(lo, Math.min(t0, t1)); hi = Math.min(hi, Math.max(t0, t1)); + if (lo > hi) return false; + } + return true; +} + +/** Holds only the explicitly supplied app window; never discovers OS windows. */ +export class CuaDriver { + private surface: CuaSurfaceSnapshot | null = null; + private frame: CuaFrame | null = null; + private frameTime = 0; + private executionBlocked = true; + private generation = 0; + private heldMouse: CuaPoint | null = null; + private heldKey: KeyboardInputEvent | null = null; + private cancellation: Promise | null = null; + private injecting = false; + private state: CuaState; + + constructor(private readonly window: BrowserWindow, private readonly dependencies: CuaDriverDependencies) { + this.state = { sessionId: null, runId: null, windowId: window.id, phase: 'idle', cursor: null, dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; + window.on('blur', () => { void this.cancel('blur'); }); + window.on('resize', () => { void this.cancel('resize'); }); + window.on('closed', () => { void this.cancel('closed'); }); + window.webContents.on('did-start-navigation', () => { void this.cancel('navigation'); }); + window.webContents.on('render-process-gone', () => { void this.cancel('renderer-gone'); }); + window.webContents.on('zoom-changed', () => { void this.cancel('zoom'); }); + window.webContents.on('blur', () => { void this.cancel('contents-blur'); }); + // Electron 43 macOS probe verifies these events fire synchronously inside + // sendInputEvent. This is a delivery guard, never a renderer isTrusted test. + window.webContents.on('before-input-event', () => { + if (!this.injecting && this.state.phase === 'acting') void this.cancel('user-input'); + }); + window.webContents.on('before-mouse-event', () => { + if (!this.injecting && this.state.phase === 'acting') void this.cancel('user-input'); + }); + } + getState(): CuaState { return structuredClone(this.state); } + setExecutionBlocked(blocked: boolean): void { this.executionBlocked = blocked; } + private publish(patch: Partial): void { this.state = { ...this.state, ...patch }; this.dependencies.onState?.(this.getState()); } + private live(): void { + if (this.window.isDestroyed() || this.window.webContents.isDestroyed()) throw new Error('CUA_TARGET_GONE'); + if (!this.window.isFocused() || !this.window.webContents.isFocused()) throw new Error('CUA_NOT_FOCUSED'); + } + reportSurface(snapshot: CuaSurfaceSnapshot): void { + // Runtime validation is mandatory: the bridge does not make renderer data trusted. + if (!snapshot || !Number.isSafeInteger(snapshot.layoutRevision) || snapshot.layoutRevision < 0 + || typeof snapshot.executionBlocked !== 'boolean' || typeof snapshot.focusedInSafeSurface !== 'boolean' + || !snapshot.viewport || ![snapshot.viewport.width, snapshot.viewport.height].every(n => Number.isFinite(n) && n > 0 && n < 32768) + || !Array.isArray(snapshot.protectedRects) || snapshot.protectedRects.length > 256) throw new Error('CUA_INVALID_SURFACE'); + const validRect = (r: CuaRect): boolean => !!r && [r.x, r.y, r.width, r.height].every(Number.isFinite) && r.width >= 0 && r.height >= 0; + if (snapshot.protectedRects.some(p => !p || !validRect(p.rect)) || (snapshot.safeSurface !== null && (!validRect(snapshot.safeSurface.rect) || typeof snapshot.safeSurface.interactive !== 'boolean'))) throw new Error('CUA_INVALID_SURFACE'); + if (this.surface && snapshot.layoutRevision < this.surface.layoutRevision) throw new Error('CUA_STALE_SURFACE'); + const changed = this.surface !== null && (snapshot.layoutRevision !== this.surface.layoutRevision + || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport) + || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) + || JSON.stringify(snapshot.protectedRects) !== JSON.stringify(this.surface.protectedRects)); + this.surface = structuredClone(snapshot); + if (changed) { this.frame = null; if (this.state.phase === 'acting') void this.cancel('surface-changed'); } + } + async observe(context: { sessionId: string; runId: string }): Promise { + this.live(); + if (this.state.phase === 'acting' || this.state.phase === 'stopping' || this.state.phase === 'cleanup-failed') throw new Error('CUA_BUSY'); + if (!context.sessionId || !context.runId || !this.surface?.safeSurface?.interactive) throw new Error('CUA_UNSAFE_SURFACE'); + const snapshot = structuredClone(this.surface); + const revision = this.generation; + const image = await this.window.webContents.capturePage(); + this.live(); + if (revision !== this.generation || !this.surface || snapshot.layoutRevision !== this.surface.layoutRevision + || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) + || JSON.stringify(snapshot.protectedRects) !== JSON.stringify(this.surface.protectedRects) + || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport)) throw new Error('CUA_STALE_FRAME'); + const bitmap = image.getSize(); + if (image.isEmpty() || bitmap.width <= 0 || bitmap.height <= 0) throw new Error('CUA_EMPTY_CAPTURE'); + const frame: CuaFrame = { ...context, windowId: this.window.id, frameId: randomUUID(), layoutRevision: snapshot.layoutRevision, capturedAt: Date.now(), viewport: snapshot.viewport, bitmap, deviceScaleFactor: bitmap.width / snapshot.viewport.width / this.window.webContents.getZoomFactor(), zoomFactor: this.window.webContents.getZoomFactor(), pngDataUrl: image.toDataURL() }; + this.frame = frame; this.frameTime = performance.now(); this.cancellation = null; + this.publish({ ...context, phase: 'ready', error: null, cleanupComplete: true, releaseFailures: [] }); + return frame; + } + private validate(request: CuaActionRequest): CuaPoint[] { + this.live(); + if (this.state.phase !== 'ready') throw new Error('CUA_BUSY'); + const f = this.frame, s = this.surface; + if (!f || !s || request.sessionId !== f.sessionId || request.runId !== f.runId || request.windowId !== this.window.id || request.frameId !== f.frameId || request.layoutRevision !== f.layoutRevision || s.layoutRevision !== f.layoutRevision || performance.now() - this.frameTime > 120000 || this.window.webContents.getZoomFactor() !== f.zoomFactor) throw new Error('CUA_STALE_FRAME'); + if (this.executionBlocked || s.executionBlocked || !s.safeSurface?.interactive) throw new Error('CUA_EXECUTION_BLOCKED'); + const action = request.action; + if (!action || !['click', 'drag', 'key'].includes(action.kind)) throw new Error('CUA_INVALID_ACTION'); + if (action.kind === 'key') { + if (!s.focusedInSafeSurface || !CUA_KEYS.includes(action.key) || !Array.isArray(action.modifiers) + || action.modifiers.length > 1 || action.modifiers.some(m => !['shift', 'control', 'meta', 'alt'].includes(m)) + || (action.modifiers.length > 0 && !(['z', 'y'].includes(action.key) && ['control', 'meta'].includes(action.modifiers[0]!)))) throw new Error('CUA_UNSAFE_KEY'); + return []; + } + if (action.kind === 'drag' && (!Number.isFinite(action.durationMs) || action.durationMs < 100 || action.durationMs > 3000)) throw new Error('CUA_INVALID_ACTION'); + if (action.kind === 'drag' && s.protectedRects.some(r => crosses(action.from, action.to, r.rect))) throw new Error('CUA_OUT_OF_BOUNDS_OR_PROTECTED'); + const points = action.kind === 'click' ? [action.point] : Array.from({ length: 61 }, (_, i) => ({ x: action.from.x + (action.to.x - action.from.x) * i / 60, y: action.from.y + (action.to.y - action.from.y) * i / 60 })); + for (const p of points) if (!p || !inside(p, { x: 0, y: 0, ...s.viewport }) || !inside(p, s.safeSurface.rect) || s.protectedRects.some(r => inside(p, r.rect))) throw new Error('CUA_OUT_OF_BOUNDS_OR_PROTECTED'); + return points; + } + private mouse(type: MouseInputEvent['type'], point: CuaPoint): void { + this.input({ type, x: Math.round(point.x), y: Math.round(point.y), button: 'left', clickCount: 1, modifiers: this.heldMouse ? ['leftbuttondown'] : [] }); + } + private input(event: MouseInputEvent | KeyboardInputEvent): void { + this.injecting = true; + try { this.window.webContents.sendInputEvent(event); } + finally { this.injecting = false; } + } + async execute(request: CuaActionRequest, permit: unknown, signal?: AbortSignal): Promise { + const points = this.validate(request); + if (signal?.aborted) throw new Error('CUA_CANCELLED'); + this.dependencies.consumePermit(request, permit); // No await between validation, one-use consume and first input. + const generation = this.generation; + const abort = (): void => { void this.cancel('aborted'); }; + signal?.addEventListener('abort', abort, { once: true }); + this.publish({ phase: 'acting', cleanupComplete: false, label: request.action.kind }); + try { + if (request.action.kind === 'key') { + this.heldKey = { type: 'keyDown', keyCode: request.action.key, modifiers: [...request.action.modifiers] }; + this.input(this.heldKey); + } else { + const first = points[0]!; + this.mouse('mouseMove', first); this.heldMouse = first; this.mouse('mouseDown', first); + this.publish({ cursor: first, dragStart: request.action.kind === 'drag' ? first : null, target: points.at(-1)! }); + if (request.action.kind === 'drag') for (const p of points.slice(1)) { + await new Promise(resolve => setTimeout(resolve, request.action.kind === 'drag' ? request.action.durationMs / 60 : 0)); + if (generation !== this.generation || signal?.aborted) throw new Error('CUA_CANCELLED'); + this.live(); + this.heldMouse = p; this.mouse('mouseMove', p); this.publish({ cursor: p }); + } + } + if (generation !== this.generation) throw new Error('CUA_CANCELLED'); + const failures = this.release(); + this.frame = null; + this.publish({ phase: failures.length ? 'cleanup-failed' : 'ready', cleanupComplete: !failures.length, releaseFailures: failures, error: failures.length ? 'CUA_RELEASE_FAILED' : null, dragStart: null }); + if (failures.length) throw new Error('CUA_RELEASE_FAILED'); + return this.getState(); + } catch (error) { await this.cancel(error instanceof Error ? error.message : 'error'); throw error; } + finally { signal?.removeEventListener('abort', abort); } + } + private release(): string[] { + const failures: string[] = []; + if (this.heldMouse) { try { this.mouse('mouseUp', this.heldMouse); this.heldMouse = null; } catch { failures.push('left'); } } + if (this.heldKey) { const key = this.heldKey; try { this.input({ ...key, type: 'keyUp' }); this.heldKey = null; } catch { failures.push(key.keyCode); } } + return failures; + } + cancel(reason = 'stopped'): Promise { + if (this.cancellation) return this.cancellation; + this.generation++; this.frame = null; this.executionBlocked = true; + // Assign the promise before callbacks so recursive cancellation is idempotent. + let settle!: (state: CuaState) => void; + this.cancellation = new Promise(resolve => { settle = resolve; }); + this.publish({ phase: 'stopping', error: reason, cleanupComplete: false }); + try { this.dependencies.onCancel?.({ sessionId: this.state.sessionId, runId: this.state.runId, reason }); } + catch { reason += ':authority-revoke-failed'; } + const failures = this.release(); + this.publish({ phase: failures.length ? 'cleanup-failed' : 'stopped', error: reason, cleanupComplete: failures.length === 0, releaseFailures: failures, dragStart: null }); + settle(this.getState()); + return this.cancellation; + } +} diff --git a/src/main/cuaIpc.ts b/src/main/cuaIpc.ts new file mode 100644 index 00000000..d72b9dbd --- /dev/null +++ b/src/main/cuaIpc.ts @@ -0,0 +1,24 @@ +import type { BrowserWindow, IpcMain, IpcMainInvokeEvent } from 'electron'; +import { IPC_CHANNELS } from '../shared/ipc'; +import type { CuaSurfaceSnapshot } from '../shared/cua'; +import { fail, ok } from './ipcResponses'; +import type { CuaDriver } from './cuaDriver'; + +/** Only the supplied app's own top frame may report safety or request Stop. */ +export function registerCuaIpc(ipc: IpcMain, getTarget: () => { window: BrowserWindow; driver: CuaDriver } | null): void { + const own = (event: IpcMainInvokeEvent): CuaDriver => { + const target = getTarget(); + if (!target || target.window.isDestroyed() || event.sender !== target.window.webContents + || event.senderFrame !== target.window.webContents.mainFrame) throw new Error('CUA_UNAUTHORIZED_SENDER'); + return target.driver; + }; + ipc.handle(IPC_CHANNELS.cuaGetState, event => { + try { return ok(own(event).getState()); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } + }); + ipc.handle(IPC_CHANNELS.cuaStop, event => { + try { void own(event).cancel('user-stop'); return ok({ accepted: true }); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } + }); + ipc.handle(IPC_CHANNELS.cuaReportSurfaceSnapshot, (event, snapshot: CuaSurfaceSnapshot) => { + try { own(event).reportSurface(snapshot); return ok({ accepted: true }); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } + }); +} diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts new file mode 100644 index 00000000..c19638e8 --- /dev/null +++ b/tests/cuaDriver.test.ts @@ -0,0 +1,97 @@ +import { EventEmitter } from 'node:events'; +import type { BrowserWindow, MouseInputEvent } from 'electron'; +import { describe, expect, it, vi } from 'vitest'; +import { CuaDriver } from '../src/main/cuaDriver'; +import { cuaBitmapPointToViewport, type CuaActionRequest, type CuaSurfaceSnapshot } from '../src/shared/cua'; + +function fixture() { + const contents = Object.assign(new EventEmitter(), { + isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: () => 1, + capturePage: vi.fn(async () => ({ getSize: () => ({ width: 800, height: 600 }), isEmpty: () => false, toDataURL: () => 'data:image/png;base64,test' })), + sendInputEvent: vi.fn((input: MouseInputEvent) => contents.emit(input.type.startsWith('mouse') ? 'before-mouse-event' : 'before-input-event', {}, input)) + }); + const window = Object.assign(new EventEmitter(), { id: 7, webContents: contents, isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true) }); + const consumePermit = vi.fn(); const onCancel = vi.fn(); + const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel }); + const surface: CuaSurfaceSnapshot = { executionBlocked: false, blockReason: null, layoutRevision: 1, viewport: { width: 800, height: 600 }, safeSurface: { kind: 'timeline', rect: { x: 0, y: 0, width: 800, height: 600 }, interactive: true }, protectedRects: [], focusedInSafeSurface: true, focusedTestId: null }; + driver.reportSurface(surface); driver.setExecutionBlocked(false); + const observe = async (): Promise => { + const frame = await driver.observe({ sessionId: 's', runId: 'r' }); + return { sessionId: 's', runId: 'r', windowId: 7, frameId: frame.frameId, layoutRevision: 1, action: { kind: 'click', point: { x: 20, y: 20 } } }; + }; + return { driver, window, contents, consumePermit, onCancel, surface, observe }; +} +describe('self-window CUA safety', () => { + it('uses actual bitmap ratio and rejects invalid pixels', () => { + const f = { bitmap: { width: 1600, height: 1200 }, viewport: { width: 800, height: 600 } }; + expect(cuaBitmapPointToViewport(f, { x: 200, y: 100 })).toEqual({ x: 100, y: 50 }); + expect(() => cuaBitmapPointToViewport(f, { x: 1600, y: 1 })).toThrow('OUT_OF_BOUNDS'); + }); + it('requires current window/frame and performs no input on rejected permit', async () => { + const f = fixture(), request = await f.observe(); + await expect(f.driver.execute({ ...request, windowId: 99 }, 'p')).rejects.toThrow('STALE'); + f.consumePermit.mockImplementation(() => { throw new Error('denied'); }); + await expect(f.driver.execute(request, 'p')).rejects.toThrow('denied'); + expect(f.contents.sendInputEvent).not.toHaveBeenCalled(); + }); + it('blocks missing/renderer/main safety and unsafe keyboard shortcuts', async () => { + const f = fixture(), r = await f.observe(); + f.driver.setExecutionBlocked(true); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('BLOCKED'); + f.driver.setExecutionBlocked(false); + await expect(f.driver.execute({ ...r, action: { kind: 'key', key: 'Tab' as never, modifiers: [] } }, 'p')).rejects.toThrow('UNSAFE_KEY'); + f.driver.reportSurface({ ...f.surface, focusedInSafeSurface: false }); + await expect(f.driver.execute({ ...r, action: { kind: 'key', key: 'z', modifiers: ['meta'] } }, 'p')).rejects.toThrow('UNSAFE_KEY'); + expect(f.consumePermit).not.toHaveBeenCalled(); + }); + it('invalidates on geometry and validates protected drag path before consume', async () => { + const f = fixture(); + f.driver.reportSurface({ ...f.surface, protectedRects: [{ id: 'approval', kind: 'approval-ui', rect: { x: 100, y: 0, width: 40, height: 600 } }] }); + const r = await f.observe(); + await expect(f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p')).rejects.toThrow('PROTECTED'); + f.driver.reportSurface({ ...f.surface, layoutRevision: 2 }); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('STALE'); + expect(f.consumePermit).not.toHaveBeenCalled(); + }); + it('releases a held drag on stop and sends no subsequent moves', async () => { + const f = fixture(), r = await f.observe(); + const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 3000 } }, 'p'); + const rejected = expect(execution).rejects.toThrow('CANCELLED'); + const cancelled = f.driver.cancel('user-stop'); + expect(f.driver.cancel()).toBe(cancelled); + expect((await cancelled).cleanupComplete).toBe(true); + const count = f.contents.sendInputEvent.mock.calls.length; + await rejected; + expect(f.contents.sendInputEvent).toHaveBeenCalledTimes(count); + expect(f.contents.sendInputEvent.mock.calls.at(-1)?.[0].type).toBe('mouseUp'); + expect(f.onCancel).toHaveBeenCalledTimes(1); + }); + it('cancels real input during drag but ignores synchronous injected events', async () => { + const f = fixture(), r = await f.observe(); + const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p'); + expect(f.driver.getState().phase).toBe('acting'); + f.contents.emit('before-input-event', {}, { type: 'keyDown', key: 'Escape' }); + await expect(execution).rejects.toThrow('CANCELLED'); + expect(f.driver.getState().cleanupComplete).toBe(true); + expect(f.onCancel).toHaveBeenCalledTimes(1); + }); + it('does not report clean stop if held input release throws', async () => { + const f = fixture(), r = await f.observe(); + const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p'); + f.contents.sendInputEvent.mockImplementation(() => { throw new Error('closed'); }); + const stopped = await f.driver.cancel('closed'); + expect(stopped.phase).toBe('cleanup-failed'); + expect(stopped.cleanupComplete).toBe(false); + expect(stopped.releaseFailures).toEqual(['left']); + await expect(execution).rejects.toThrow('CANCELLED'); + await expect(f.observe()).rejects.toThrow('BUSY'); + }); + it('invalidates frames on resize and refuses unfocused capture', async () => { + const f = fixture(), r = await f.observe(); + f.window.emit('resize'); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('BUSY'); + f.window.isFocused.mockReturnValue(false); + await expect(f.observe()).rejects.toThrow('NOT_FOCUSED'); + expect(f.consumePermit).not.toHaveBeenCalled(); + }); +}); From 8294d27650ea79fc20d369562bda6176201993f9 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:03:02 +0900 Subject: [PATCH 05/96] test(cua): cover sender safety and document native input probes --- docs/cua-driver-validation.md | 23 +++++++++++++++++++++++ src/main/cuaDriver.ts | 17 +++++++++++++---- tests/cuaIpc.test.ts | 22 ++++++++++++++++++++++ 3 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 docs/cua-driver-validation.md create mode 100644 tests/cuaIpc.test.ts diff --git a/docs/cua-driver-validation.md b/docs/cua-driver-validation.md new file mode 100644 index 00000000..b7835a1e --- /dev/null +++ b/docs/cua-driver-validation.md @@ -0,0 +1,23 @@ +# Self-window CUA validation + +Backend item31, issue #558. Work started from clean `fdce65209afe784e92774e8c7d1fdd0daaf88e6c`. + +The driver binds to the BrowserWindow supplied by the host. It neither discovers nor controls other windows, exposes a debug port, nor sends OS input. Renderer IPC exposes state, safety reporting and Stop; approval permit issuance and action execution remain main-only. + +## Actual Electron API probes + +Run `node_modules/.bin/electron scripts/probe-cua-input.cjs` for HTML5 drag and set `CUA_PROBE_POINTER=1` for Pointer Capture. `CUA_PROBE_DIR` selects the local evidence directory. The probe uses an isolated BrowserWindow and sends actual webContents input. It does not represent a completed editor scenario. + +On this macOS host with Electron 43, HTML5 draggable receives pointerdown, mousedown, dragstart and pointercancel; subsequent sendInputEvent movements and mouseUp do not complete dragover/drop/dragend. The process also did not quit cleanly while native drag was outstanding. Therefore the existing HTML5 drag path cannot be claimed as supported by this driver. + +The Pointer Capture variant receives pointerdown, every pointermove, pointerup and mouseup. Injected DOM events have `isTrusted: true`; that property cannot distinguish user input. All 27 injected mouse events reached before-mouse-event synchronously during sendInputEvent. This observation supports a synchronous delivery guard on this tested Electron/macOS version, rather than a claim of universal native input attribution. + +Both initial probes reported window/content focus false even after win.focus. Actual input partially delivered regardless, so the production driver explicitly refuses unfocused input instead of relying on delivery behavior. Driver code never automatically focuses the window. + +Raw initial evidence: `/tmp/openscene-cua-probe/input.json`, `/tmp/openscene-cua-probe/capture.png`, `/tmp/openscene-cua-pointer-probe/input.json`, `/tmp/openscene-cua-pointer-probe/capture.png`. These are local experimental artifacts, not the required full application evidence. + +## Remaining integration evidence + +The actual OpenScene scenario (MCP clip creation, CUA selection/move, MCP state inspection, UI Undo) and mid-drag stop/rollback evidence are pending the coordinated Frontend Pointer Events implementation and LLM main approval runtime. Stop must verify renderer rollback before claiming cancellation, since a plain mouseUp can commit a pointer drag. Fresh verification, exact final SHA, CI and independent review must accompany the completed integration. + +This capability is Electron desktop-specific. Mobile cannot capture/control a BrowserWindow; the shared DTO and pure coordinate conversion must still compile under the mobile TypeScript configuration. diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 6fab8f6e..271e530d 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -32,6 +32,7 @@ export class CuaDriver { private heldKey: KeyboardInputEvent | null = null; private cancellation: Promise | null = null; private injecting = false; + private cleanupFailureLatched = false; private state: CuaState; constructor(private readonly window: BrowserWindow, private readonly dependencies: CuaDriverDependencies) { @@ -54,7 +55,11 @@ export class CuaDriver { } getState(): CuaState { return structuredClone(this.state); } setExecutionBlocked(blocked: boolean): void { this.executionBlocked = blocked; } - private publish(patch: Partial): void { this.state = { ...this.state, ...patch }; this.dependencies.onState?.(this.getState()); } + private publish(patch: Partial): void { + this.state = { ...this.state, ...patch }; + // A disappearing renderer must never prevent held-input release. + try { this.dependencies.onState?.(this.getState()); } catch { /* transport is gone; state remains queryable */ } + } private live(): void { if (this.window.isDestroyed() || this.window.webContents.isDestroyed()) throw new Error('CUA_TARGET_GONE'); if (!this.window.isFocused() || !this.window.webContents.isFocused()) throw new Error('CUA_NOT_FOCUSED'); @@ -77,7 +82,7 @@ export class CuaDriver { } async observe(context: { sessionId: string; runId: string }): Promise { this.live(); - if (this.state.phase === 'acting' || this.state.phase === 'stopping' || this.state.phase === 'cleanup-failed') throw new Error('CUA_BUSY'); + if (this.state.phase === 'acting' || this.state.phase === 'stopping' || this.cleanupFailureLatched) throw new Error('CUA_BUSY'); if (!context.sessionId || !context.runId || !this.surface?.safeSurface?.interactive) throw new Error('CUA_UNSAFE_SURFACE'); const snapshot = structuredClone(this.surface); const revision = this.generation; @@ -147,6 +152,7 @@ export class CuaDriver { } if (generation !== this.generation) throw new Error('CUA_CANCELLED'); const failures = this.release(); + if (failures.length) this.cleanupFailureLatched = true; this.frame = null; this.publish({ phase: failures.length ? 'cleanup-failed' : 'ready', cleanupComplete: !failures.length, releaseFailures: failures, error: failures.length ? 'CUA_RELEASE_FAILED' : null, dragStart: null }); if (failures.length) throw new Error('CUA_RELEASE_FAILED'); @@ -167,10 +173,13 @@ export class CuaDriver { let settle!: (state: CuaState) => void; this.cancellation = new Promise(resolve => { settle = resolve; }); this.publish({ phase: 'stopping', error: reason, cleanupComplete: false }); + let revokeFailed = false; try { this.dependencies.onCancel?.({ sessionId: this.state.sessionId, runId: this.state.runId, reason }); } - catch { reason += ':authority-revoke-failed'; } + catch { reason += ':authority-revoke-failed'; revokeFailed = true; } const failures = this.release(); - this.publish({ phase: failures.length ? 'cleanup-failed' : 'stopped', error: reason, cleanupComplete: failures.length === 0, releaseFailures: failures, dragStart: null }); + if (revokeFailed) failures.push('authority-revoke'); + if (failures.length) this.cleanupFailureLatched = true; + this.publish({ phase: this.cleanupFailureLatched ? 'cleanup-failed' : 'stopped', error: reason, cleanupComplete: !this.cleanupFailureLatched, releaseFailures: failures.length ? failures : this.state.releaseFailures, dragStart: null }); settle(this.getState()); return this.cancellation; } diff --git a/tests/cuaIpc.test.ts b/tests/cuaIpc.test.ts new file mode 100644 index 00000000..888ef31a --- /dev/null +++ b/tests/cuaIpc.test.ts @@ -0,0 +1,22 @@ +import type { BrowserWindow, IpcMain, IpcMainInvokeEvent } from 'electron'; +import { expect, it, vi } from 'vitest'; +import { registerCuaIpc } from '../src/main/cuaIpc'; +import type { CuaDriver } from '../src/main/cuaDriver'; +import { IPC_CHANNELS } from '../src/shared/ipc'; + +it('rejects other windows and child frames before consulting driver control', async () => { + const handlers = new Map unknown>(); + const ipc = { handle: (name: string, handler: (event: IpcMainInvokeEvent, data?: unknown) => unknown) => handlers.set(name, handler) } as unknown as IpcMain; + const frame = {}, contents = { mainFrame: frame }; + const window = { isDestroyed: () => false, webContents: contents } as BrowserWindow; + const driver = { getState: vi.fn(), cancel: vi.fn(async () => undefined), reportSurface: vi.fn() }; + registerCuaIpc(ipc, () => ({ window, driver: driver as unknown as CuaDriver })); + for (const name of [IPC_CHANNELS.cuaStop, IPC_CHANNELS.cuaGetState, IPC_CHANNELS.cuaReportSurfaceSnapshot]) { + const handler = handlers.get(name)!; + expect(handler({ sender: contents, senderFrame: {} } as IpcMainInvokeEvent)).toMatchObject({ ok: false }); + expect(handler({ sender: {}, senderFrame: frame } as IpcMainInvokeEvent)).toMatchObject({ ok: false }); + } + expect(driver.cancel).not.toHaveBeenCalled(); expect(driver.reportSurface).not.toHaveBeenCalled(); + expect(handlers.get(IPC_CHANNELS.cuaStop)!({ sender: contents, senderFrame: frame } as IpcMainInvokeEvent)).toEqual({ ok: true, value: { accepted: true } }); + expect(driver.cancel).toHaveBeenCalledWith('user-stop'); +}); From cf11d74dfc8d1adfa1f08b5d9e7372db27c73785 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:03:35 +0900 Subject: [PATCH 06/96] feat(cua): define bounded drag rollback acknowledgement --- src/preload/index.ts | 4 +++- src/shared/cua.ts | 4 ++++ src/shared/ipc.ts | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/preload/index.ts b/src/preload/index.ts index 568363a3..a24b5efb 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,5 +1,5 @@ import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'; -import type { CuaState, CuaStopResult, CuaSurfaceSnapshot } from '../shared/cua'; +import type { CuaCancelAck, CuaState, CuaStopResult, CuaSurfaceSnapshot } from '../shared/cua'; import type { AgentChatApprovalInput, @@ -65,6 +65,7 @@ type AssetPlaybackUrl = { }; export interface VideoToolApi { + cuaAckCancel(ack: CuaCancelAck): Promise>; cuaGetState(): Promise>; cuaStop(): Promise>; cuaReportSurfaceSnapshot(snapshot: CuaSurfaceSnapshot): Promise>; @@ -158,6 +159,7 @@ function parseUpdaterSnapshot(payload: unknown): UpdaterSnapshot | null { } const videoTool: VideoToolApi = { + cuaAckCancel: ack => ipcRenderer.invoke(IPC_CHANNELS.cuaAckCancel, ack) as Promise>, cuaGetState: () => ipcRenderer.invoke(IPC_CHANNELS.cuaGetState) as Promise>, cuaStop: () => ipcRenderer.invoke(IPC_CHANNELS.cuaStop) as Promise>, cuaReportSurfaceSnapshot: snapshot => ipcRenderer.invoke(IPC_CHANNELS.cuaReportSurfaceSnapshot, snapshot) as Promise>, diff --git a/src/shared/cua.ts b/src/shared/cua.ts index 55d7406b..b1048ad5 100644 --- a/src/shared/cua.ts +++ b/src/shared/cua.ts @@ -41,6 +41,9 @@ export interface CuaActionRequest { } export type CuaPhase = 'idle' | 'ready' | 'acting' | 'stopping' | 'stopped' | 'cleanup-failed'; export interface CuaState { + /** Present only while a held drag awaits synchronous renderer rollback. */ + readonly cancelToken: string | null; + readonly targetGone: boolean; readonly sessionId: string | null; readonly runId: string | null; readonly windowId: number; @@ -54,6 +57,7 @@ export interface CuaState { readonly releaseFailures: readonly string[]; } export interface CuaStopResult { readonly accepted: boolean } +export interface CuaCancelAck { readonly runId: string; readonly cancelToken: string } /** Pixel conversion uses the actual returned bitmap, never DPR alone. */ export function cuaBitmapPointToViewport(frame: Pick, point: CuaPoint): CuaPoint { diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index 238775cf..fd128829 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -1,5 +1,6 @@ export const IPC_CHANNELS = { cuaGetState: 'cua:get-state', + cuaAckCancel: 'cua:ack-cancel', cuaStop: 'cua:stop', cuaReportSurfaceSnapshot: 'cua:report-surface-snapshot', cuaStateChanged: 'cua:state-changed', From 7291355d2fc8ec6f8f72de5ca67b2a4c06ee26ae Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:04:11 +0900 Subject: [PATCH 07/96] feat(agent): orchestrate one-use CUA approval and settled cancellation --- src/main/agentChatGraph.ts | 76 ++++++- src/main/agentChatIpcHandlers.ts | 21 +- src/main/agentChatSession.ts | 73 ++++++- src/main/agentChatTools.ts | 38 +++- src/main/cuaAgentOrchestration.ts | 295 ++++++++++++++++++++++++++++ tests/agentChatCuaLifecycle.test.ts | 102 ++++++++++ tests/cuaAgentOrchestration.test.ts | 93 +++++++++ tests/cuaAgentRunBinding.test.ts | 108 ++++++++++ 8 files changed, 789 insertions(+), 17 deletions(-) create mode 100644 src/main/cuaAgentOrchestration.ts create mode 100644 tests/agentChatCuaLifecycle.test.ts create mode 100644 tests/cuaAgentOrchestration.test.ts create mode 100644 tests/cuaAgentRunBinding.test.ts diff --git a/src/main/agentChatGraph.ts b/src/main/agentChatGraph.ts index 8a9ef0fe..db741230 100644 --- a/src/main/agentChatGraph.ts +++ b/src/main/agentChatGraph.ts @@ -10,6 +10,8 @@ import { type BaseMessage } from '@langchain/core/messages'; import type { DynamicStructuredTool } from '@langchain/core/tools'; +import type { CuaAgentOrchestrator } from './cuaAgentOrchestration'; +import { CUA_ACTION_TOOL_SCHEMA } from './agentChatTools'; import { Annotation, END, MemorySaver, START, StateGraph, interrupt } from '@langchain/langgraph'; import { FFMPEG_EDITING_WORKFLOW } from '../shared/ffmpegEditingWorkflow'; import { AGENT_SCOPE_POLICY } from '../shared/agentScope'; @@ -145,6 +147,23 @@ function buildWatchFramesMessage(toolName: string, payload: WatchFramesPayload): }); } +function cuaVisualEvidence(output: unknown): { summary: string; image: HumanMessage } | null { + let value = output; + if (typeof value === 'string') { + try { value = JSON.parse(value); } catch { return null; } + } + if (!value || typeof value !== 'object') return null; + const candidate = value as { success?: unknown; summary?: unknown; frame?: { pngDataUrl?: unknown; frameId?: unknown } }; + if (candidate.success !== true || typeof candidate.summary !== 'string' + || typeof candidate.frame?.pngDataUrl !== 'string' || !candidate.frame.pngDataUrl.startsWith('data:image/png;base64,')) return null; + const { pngDataUrl, ...metadata } = candidate.frame; + const summary = `${candidate.summary}\n${JSON.stringify(metadata)}`; + return { summary, image: new HumanMessage({ content: [ + { type: 'text', text: `[OpenScene self-window evidence] ${summary}` }, + { type: 'image_url', image_url: { url: pngDataUrl } } + ] }) }; +} + export interface AgentChatModelHandle { invoke(messages: BaseMessage[], options?: { signal?: AbortSignal }): Promise; } @@ -174,6 +193,10 @@ const AgentChatState = Annotation.Root({ toolDecisions: Annotation>({ reducer: (current, update) => ({ ...current, ...update }), default: () => ({}) + }), + executedPerCallIds: Annotation({ + reducer: (current, update) => [...new Set([...current, ...update])], + default: () => [] }) }); @@ -182,6 +205,9 @@ export interface BuildAgentChatGraphOptions { readonly mutatingToolNames: ReadonlySet; /** Charges the user's provider account; never auto-approved by "always". */ readonly spendToolNames?: ReadonlySet; + /** Exact-action approval; an "always" answer covers this call only. */ + readonly perCallApprovalToolNames?: ReadonlySet; + readonly cua?: CuaAgentOrchestrator; readonly createModel: AgentChatModelFactory; } @@ -206,32 +232,44 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { ? state.messages : [new SystemMessage(buildAgentSystemPrompt(getEditAssetContext(configurable.editAssetContext), getEditProjectContext(configurable.editProjectContext))), ...state.messages]; - const response = await model.invoke(messages); + const response = await model.invoke(messages, config.signal ? { signal: config.signal } : undefined); + if ((response.tool_calls?.length ?? 0) > 16) throw new Error('CUA_BUDGET_EXCEEDED: At most 16 tool calls per model step.'); return { messages: [response] }; }) - .addNode('checkApproval', async (state) => { + .addNode('checkApproval', async (state, config) => { const last = state.messages[state.messages.length - 1]; if (!last || !isAiLike(last) || !last.tool_calls || last.tool_calls.length === 0) { return {}; } const decisions: Record = {}; + if (options.cua && (last.tool_calls?.filter((call) => call.name === 'executeCuaAction').length ?? 0) > 1) { + throw new Error('CUA_BUDGET_EXCEEDED: Propose one observed CUA action at a time.'); + } for (const call of last.tool_calls) { - if (!call.id || !options.mutatingToolNames.has(call.name) || state.toolDecisions[call.id]) { + if (!call.id || (!options.mutatingToolNames.has(call.name) + && !options.perCallApprovalToolNames?.has(call.name)) || state.toolDecisions[call.id]) { continue; } // A spend tool re-asks even after "always": that answer was given about // one charge, and cannot stand in for consent to every later one. - const spends = options.spendToolNames?.has(call.name) ?? false; + const spends = (options.spendToolNames?.has(call.name) ?? false) + || (options.perCallApprovalToolNames?.has(call.name) ?? false); if (!spends && state.alwaysAllowedTools.includes(call.name)) { decisions[call.id] = 'approve'; continue; } - const proposal: AgentToolCallProposal = { + let proposal: AgentToolCallProposal = { toolCallId: call.id, toolName: call.name, args: (call.args ?? {}) as Record }; + if (options.cua && call.name === 'executeCuaAction') { + const conversationId = config.configurable?.thread_id; + if (typeof conversationId !== 'string') throw new Error('CUA_SCOPE_CHANGED'); + const request = CUA_ACTION_TOOL_SCHEMA.parse(call.args); + proposal = { ...proposal, cuaApproval: options.cua.prepareApproval(conversationId, call.id, request) }; + } decisions[call.id] = interrupt(proposal); } const alwaysAllowedTools = Object.entries(decisions) @@ -240,7 +278,8 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { .filter((name): name is string => name !== undefined) // Recording a spend tool here would make the next charge silent even // though this pass correctly stopped to ask about this one. - .filter((name) => !(options.spendToolNames?.has(name) ?? false)); + .filter((name) => !(options.spendToolNames?.has(name) ?? false) + && !(options.perCallApprovalToolNames?.has(name) ?? false)); return { toolDecisions: decisions, alwaysAllowedTools }; }) .addNode('executeTools', async (state, config) => { @@ -250,19 +289,29 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { } const results: BaseMessage[] = []; + const executedPerCallIds: string[] = []; const visualEvidence: HumanMessage[] = []; const modelId = config?.configurable?.modelId; const model = typeof modelId === 'string' ? getLlmModel(modelId) : undefined; for (const call of last.tool_calls) { if (!call.id) continue; + const perCall = options.perCallApprovalToolNames?.has(call.name) ?? false; + if (perCall && (state.executedPerCallIds.includes(call.id) || executedPerCallIds.includes(call.id))) { + results.push(new ToolMessage({ content: 'CUA_ACTION_REPLAYED: This action call has already settled. Observe again and propose a new action.', tool_call_id: call.id, name: call.name })); + continue; + } if (call.name === 'watchProjectVideo' && model !== undefined && model.vision !== true) { results.push(new ToolMessage({ content: 'This model cannot inspect video frames. Switch to a vision model or use speech inspection.', tool_call_id: call.id, name: call.name })); continue; } - const decision = options.mutatingToolNames.has(call.name) ? state.toolDecisions[call.id] : 'approve'; + const decision = (perCall || options.mutatingToolNames.has(call.name)) ? state.toolDecisions[call.id] : 'approve'; + if (perCall) executedPerCallIds.push(call.id); if (decision !== 'approve' && decision !== 'always') { + if (options.cua && call.name === 'executeCuaAction') { + options.cua.deny(String(config.configurable?.thread_id), call.id); + } // A denial with feedback reads as a correction, so the model can act // on the reason instead of only learning that it was refused. const feedback = state.toolFeedback[call.id]; @@ -280,7 +329,16 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { } try { - const output: unknown = await tool.invoke(call.args ?? {}); + config.signal?.throwIfAborted(); + const output: unknown = options.cua && call.name === 'executeCuaAction' + ? await options.cua.executeApproved(String(config.configurable?.thread_id), call.id, CUA_ACTION_TOOL_SCHEMA.parse(call.args)) + : await tool.invoke(call.args ?? {}, config); + const cuaEvidence = cuaVisualEvidence(output); + if (cuaEvidence) { + results.push(new ToolMessage({ content: cuaEvidence.summary, tool_call_id: call.id, name: call.name })); + visualEvidence.push(cuaEvidence.image); + continue; + } const framesPayload = parseWatchFramesPayload(output); if (framesPayload !== null) { results.push(new ToolMessage({ content: framesPayload.summary, tool_call_id: call.id, name: call.name })); @@ -294,7 +352,7 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { results.push(new ToolMessage({ content: `Tool "${call.name}" failed: ${detail}`, tool_call_id: call.id, name: call.name })); } } - return { messages: [...results, ...visualEvidence] }; + return { messages: [...results, ...visualEvidence], executedPerCallIds }; }) .addEdge(START, 'agent') .addConditionalEdges('agent', (state) => { diff --git a/src/main/agentChatIpcHandlers.ts b/src/main/agentChatIpcHandlers.ts index 4a66beeb..59809fd2 100644 --- a/src/main/agentChatIpcHandlers.ts +++ b/src/main/agentChatIpcHandlers.ts @@ -1,4 +1,4 @@ -import type { IpcMain } from 'electron'; +import type { IpcMain, IpcMainInvokeEvent } from 'electron'; import type { AgentChatHistoryGetInput, AgentChatTurnState } from '../shared/agentChat'; import { IPC_CHANNELS } from '../shared/ipc'; @@ -9,7 +9,11 @@ import type { AgentChatSessionManager } from './agentChatSession'; export function registerAgentChatIpcHandlers( ipcMain: IpcMain, sessions: AgentChatSessionManager, - history: AgentChatHistoryStore | null = null + history: AgentChatHistoryStore | null = null, + options: { + readonly cancelChannel?: string; + readonly isTrustedSender?: (event: IpcMainInvokeEvent) => boolean; + } = {} ): void { const recordTurn = async (turn: AgentChatTurnState): Promise => { if (history === null || turn.messages.length === 0) return; @@ -27,6 +31,7 @@ export function registerAgentChatIpcHandlers( }; ipcMain.handle(IPC_CHANNELS.agentChatSend, async (_event, request) => { + if (options.isTrustedSender && !options.isTrustedSender(_event)) return fail('INVALID_INPUT', 'Untrusted agent chat sender'); try { const turn = await sessions.sendMessage(request); await recordTurn(turn); @@ -37,6 +42,7 @@ export function registerAgentChatIpcHandlers( }); ipcMain.handle(IPC_CHANNELS.agentChatApprove, async (_event, request) => { + if (options.isTrustedSender && !options.isTrustedSender(_event)) return fail('INVALID_INPUT', 'Untrusted approval sender'); try { const turn = await sessions.respondToApproval(request); await recordTurn(turn); @@ -46,6 +52,17 @@ export function registerAgentChatIpcHandlers( } }); + if (options.cancelChannel) ipcMain.handle(options.cancelChannel, async (event, request) => { + if (!options.isTrustedSender?.(event)) return fail('INVALID_INPUT', 'Untrusted cancellation sender'); + if (!request || typeof request.conversationId !== 'string' || !request.conversationId.trim() + || request.conversationId.length > 256) return fail('INVALID_INPUT', 'Invalid cancellation conversation'); + try { + return ok(await sessions.cancelConversation({ conversationId: request.conversationId })); + } catch (error) { + return fail('UNKNOWN_ERROR', error instanceof Error ? error.message : 'Failed to settle agent cancellation'); + } + }); + ipcMain.handle(IPC_CHANNELS.agentChatCompact, async (_event, request) => { try { const turn = await sessions.compactConversation(request); diff --git a/src/main/agentChatSession.ts b/src/main/agentChatSession.ts index 218c6ddc..80166bec 100644 --- a/src/main/agentChatSession.ts +++ b/src/main/agentChatSession.ts @@ -5,6 +5,7 @@ import type { MemorySaver } from '@langchain/langgraph-checkpoint'; import type { BaseMessage } from '@langchain/core/messages'; import type { AgentChatApprovalInput, + AgentChatCancelInput, AgentChatDisplayMessage, AgentChatResetInput, AgentChatSendInput, @@ -16,6 +17,7 @@ import { getDomainModel } from '../shared/aiDomainModels'; import { buildContextUsage, type TurnTokenUsage } from '../shared/agentChatUsage'; import type { OpenAiAuthMode, ReasoningEffort } from '../shared/openAiAuth'; import { isAiLike, isHumanMessage, isSystemMessage, isToolMessage, type AgentChatGraphBundle } from './agentChatGraph'; +import { CuaApprovalError } from './cuaAgentOrchestration'; interface ConversationConfig { readonly modelId: string; @@ -31,14 +33,23 @@ export class AgentChatSessionManager { private readonly checkpointer: MemorySaver; private readonly createModel: AgentChatGraphBundle['createModel']; private readonly conversationConfigs = new Map(); + private readonly activeTurns = new Map }>(); + private readonly cancellations = new Map>(); + private readonly cleanupLocked = new Set(); - constructor(bundle: AgentChatGraphBundle) { + constructor(bundle: AgentChatGraphBundle, private readonly lifecycle: { + readonly cancelCua?: (conversationId: string) => Promise; + } = {}) { this.graph = bundle.graph; this.checkpointer = bundle.checkpointer; this.createModel = bundle.createModel; } async sendMessage(input: AgentChatSendInput): Promise { + return this.runExclusive(input.conversationId, () => this.sendMessageUnchecked(input)); + } + + private async sendMessageUnchecked(input: AgentChatSendInput): Promise { this.conversationConfigs.set(input.conversationId, { modelId: input.modelId, openAiAuthMode: input.openAiAuthMode, @@ -87,6 +98,10 @@ export class AgentChatSessionManager { } async respondToApproval(input: AgentChatApprovalInput): Promise { + return this.runExclusive(input.conversationId, () => this.respondToApprovalUnchecked(input)); + } + + private async respondToApprovalUnchecked(input: AgentChatApprovalInput): Promise { const config = this.runnableConfig(input.conversationId); try { @@ -121,6 +136,10 @@ export class AgentChatSessionManager { * summary replaces the old history, the recent tail stays verbatim. */ async compactConversation(input: AgentChatCompactInput): Promise { + return this.runExclusive(input.conversationId, () => this.compactConversationUnchecked(input)); + } + + private async compactConversationUnchecked(input: AgentChatCompactInput): Promise { const config = this.runnableConfig(input.conversationId); const stored = this.conversationConfigs.get(input.conversationId); if (stored === undefined) { @@ -173,14 +192,61 @@ export class AgentChatSessionManager { } async resetConversation(input: AgentChatResetInput): Promise { + const cancelled = await this.cancelConversation(input); + if (cancelled.errorCode === 'CUA_CLEANUP_FAILED') return cancelled; this.conversationConfigs.delete(input.conversationId); await this.checkpointer.deleteThread(input.conversationId); return { conversationId: input.conversationId, messages: [], pendingApproval: null, status: 'idle' }; } - private runnableConfig(conversationId: string): { configurable: Record } { + /** Driver callbacks use this synchronous method; it never re-enters cancel. */ + abortConversation(conversationId: string): void { + this.activeTurns.get(conversationId)?.controller.abort(); + } + + cancelConversation(input: AgentChatCancelInput): Promise { + const existing = this.cancellations.get(input.conversationId); + if (existing) return existing; + this.abortConversation(input.conversationId); + // Install the promise before invoking the driver, whose callback may abort + // this conversation synchronously. Never remove a running checkpoint. + const cancellation = Promise.resolve().then(async () => { + try { + await this.lifecycle.cancelCua?.(input.conversationId); + } catch (error) { + this.cleanupLocked.add(input.conversationId); + await this.activeTurns.get(input.conversationId)?.settled; + return { ...await this.errorState(input.conversationId, error), errorCode: 'CUA_CLEANUP_FAILED' as const }; + } + await this.activeTurns.get(input.conversationId)?.settled; + const previous = await this.errorState(input.conversationId, new Error('CUA_CANCELLED')); + await this.checkpointer.deleteThread(input.conversationId); + return { ...previous, status: 'idle' as const, error: undefined, errorCode: undefined }; + }).finally(() => { this.cancellations.delete(input.conversationId); }); + this.cancellations.set(input.conversationId, cancellation); + return cancellation; + } + + private async runExclusive(conversationId: string, run: () => Promise): Promise { + if (this.cleanupLocked.has(conversationId)) return { + ...await this.errorState(conversationId, new Error('CUA_CLEANUP_FAILED')), errorCode: 'CUA_CLEANUP_FAILED' + }; + if (this.activeTurns.has(conversationId) || this.cancellations.has(conversationId)) { + return { ...await this.errorState(conversationId, new Error('CUA_BUSY')), errorCode: 'CUA_BUSY' }; + } + const controller = new AbortController(); + let settle!: () => void; + const settled = new Promise((resolve) => { settle = resolve; }); + this.activeTurns.set(conversationId, { controller, settled }); + try { return await run(); } + finally { this.activeTurns.delete(conversationId); settle(); } + } + + private runnableConfig(conversationId: string): { configurable: Record; signal?: AbortSignal; recursionLimit: number } { const stored = this.conversationConfigs.get(conversationId); return { + recursionLimit: 48, + ...(this.activeTurns.get(conversationId) ? { signal: this.activeTurns.get(conversationId)!.controller.signal } : {}), configurable: { thread_id: conversationId, modelId: stored?.modelId, @@ -243,7 +309,8 @@ export class AgentChatSessionManager { messages: toDisplayMessages(messages), pendingApproval: null, status: 'error', - error: err instanceof Error ? err.message : 'Agent chat failed unexpectedly.' + error: err instanceof Error ? err.message : 'Agent chat failed unexpectedly.', + ...(err instanceof CuaApprovalError ? { errorCode: err.code } : {}) }; } } diff --git a/src/main/agentChatTools.ts b/src/main/agentChatTools.ts index bd483f56..675cab67 100644 --- a/src/main/agentChatTools.ts +++ b/src/main/agentChatTools.ts @@ -2,6 +2,10 @@ import type { DynamicStructuredTool } from '@langchain/core/tools'; import type { InstanceResolver } from '@theorvane/type-mcp'; import { createLangChainTools } from '@theorvane/type-mcp/langchain'; import { OpenVideoMcpServer } from './openVideoMcpServer'; +import { tool } from '@langchain/core/tools'; +import { z } from 'zod'; +import { CUA_KEYS } from '../shared/cua'; +import type { CuaAgentOrchestrator } from './cuaAgentOrchestration'; /** * The tools that read and change nothing. @@ -28,7 +32,8 @@ export const AGENT_CHAT_READ_ONLY_TOOL_NAMES: ReadonlySet = new Set([ 'watchProjectVideo', 'getEditingCapabilities', 'planAutoClipEdit', - 'getCanvasWorkflow' + 'getCanvasWorkflow', + 'observeEditorWindow' ]); /** @@ -41,9 +46,36 @@ export function agentChatMutatingToolNames(tools: readonly { readonly name: stri return new Set(tools.map((tool) => tool.name).filter((name) => !AGENT_CHAT_READ_ONLY_TOOL_NAMES.has(name))); } -export async function createAgentChatTools(instance: OpenVideoMcpServer): Promise { +export async function createAgentChatTools(instance: OpenVideoMcpServer, cua?: CuaAgentOrchestrator): Promise { const resolver: InstanceResolver = { resolve: () => instance }; - return createLangChainTools(OpenVideoMcpServer, { resolver }); + const tools = await createLangChainTools(OpenVideoMcpServer, { resolver }); + return cua ? [...tools, ...createCuaAgentChatTools(cua)] : tools; +} + +const point = z.object({ x: z.number().finite().nonnegative(), y: z.number().finite().nonnegative() }).strict(); +export const CUA_ACTION_TOOL_SCHEMA = z.object({ + sessionId: z.string().min(1), runId: z.string().min(1), windowId: z.number().int().nonnegative(), + frameId: z.string().min(1), layoutRevision: z.number().int().nonnegative(), + action: z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('click'), point }).strict(), + z.object({ kind: z.literal('drag'), from: point, to: point, durationMs: z.number().int().min(1).max(3000) }).strict(), + z.object({ kind: z.literal('key'), key: z.enum(CUA_KEYS), modifiers: z.array(z.enum(['shift', 'control', 'meta', 'alt'])).max(4) }).strict() + ]) +}).strict(); + +export const AGENT_CHAT_CUA_PER_CALL_TOOL_NAMES: ReadonlySet = new Set(['executeCuaAction']); + +export function createCuaAgentChatTools(cua: CuaAgentOrchestrator): DynamicStructuredTool[] { + return [ + tool(async (_args, config) => { + const conversationId = config?.configurable?.thread_id; + if (typeof conversationId !== 'string') throw new Error('CUA_SCOPE_CHANGED'); + return JSON.stringify(await cua.observe(conversationId)); + }, { name: 'observeEditorWindow', description: 'Observe only this OpenScene editor window. Returns a frame and CSS coordinate scope; use exactly those IDs for a proposed action. No OS-wide control.', schema: z.object({}).strict() }), + tool(async () => { throw new Error('CUA_APPROVAL_MISMATCH: Only the main graph approval dispatch can execute an action.'); }, { + name: 'executeCuaAction', description: 'Propose one click, bounded drag or allowed key in the observed OpenScene editor. Requires a fresh exact per-call human approval; always never authorizes later actions. After execution inspect the returned frame and requery the project timeline. No implicit recapture or coordinate conversion.', schema: CUA_ACTION_TOOL_SCHEMA + }) + ]; } /** diff --git a/src/main/cuaAgentOrchestration.ts b/src/main/cuaAgentOrchestration.ts new file mode 100644 index 00000000..4110145a --- /dev/null +++ b/src/main/cuaAgentOrchestration.ts @@ -0,0 +1,295 @@ +import { createHash, randomUUID } from 'node:crypto'; +import type { CuaActionRequest, CuaFrame, CuaState } from '../shared/cua'; +import type { AgentCuaApprovalSummary, AgentCuaErrorCode } from '../shared/agentChat'; + +export class CuaApprovalError extends Error { + constructor(readonly code: AgentCuaErrorCode) { super(code); } +} + +interface Proposal { + readonly conversationId: string; + readonly toolCallId: string; + readonly request: CuaActionRequest; + readonly digest: string; +} +interface Permit extends Proposal { readonly issuedAt: number } + +function digest(request: CuaActionRequest): string { + // Copy only the canonical contract fields. Caller property ordering and extra + // model-generated properties cannot change what was approved. + const action = request.action; + const canonicalAction = action.kind === 'click' + ? ['click', action.point.x, action.point.y] + : action.kind === 'drag' + ? ['drag', action.from.x, action.from.y, action.to.x, action.to.y, action.durationMs] + : ['key', action.key, [...action.modifiers].sort()]; + return createHash('sha256').update(JSON.stringify([ + request.sessionId, request.runId, request.windowId, request.frameId, + request.layoutRevision, canonicalAction + ])).digest('hex'); +} + +/** + * Main-only authority. Neither a tool argument nor renderer approval carries + * this object. Driver validation must finish before calling consume, with no + * await between consumption and input dispatch. TTL and budget are supplied by + * trusted wiring, not by the model; the driver independently checks frame age. + */ +export class CuaApprovalAuthority { + private pending: Proposal | null = null; + private readonly permits = new Map(); + private readonly seenCalls = new Set(); + private readonly revokedRuns = new Set(); + private readonly actionsByRun = new Map(); + private cleanupFailed = false; + + constructor(private readonly options: { + readonly permitTtlMs: number; + readonly maxActionsPerRun: number; + readonly now: () => number; + }) { + if (!Number.isFinite(options.permitTtlMs) || options.permitTtlMs <= 0 || options.permitTtlMs > 10_000 + || !Number.isSafeInteger(options.maxActionsPerRun) || options.maxActionsPerRun < 1 || options.maxActionsPerRun > 100) { + throw new Error('Invalid trusted CUA authority limits'); + } + } + + propose(conversationId: string, toolCallId: string, request: CuaActionRequest): void { + this.checkRun(request.runId); + if (this.pending !== null || this.permits.size > 0) throw new CuaApprovalError('CUA_BUSY'); + const callKey = JSON.stringify([conversationId, toolCallId]); + if (this.seenCalls.has(callKey)) throw new CuaApprovalError('CUA_ACTION_REPLAYED'); + if ((this.actionsByRun.get(request.runId) ?? 0) >= this.options.maxActionsPerRun) { + throw new CuaApprovalError('CUA_BUDGET_EXCEEDED'); + } + this.seenCalls.add(callKey); + // Approval evidence cannot be mutated while the human reads it. + const snapshot = structuredClone(request); + this.pending = { conversationId, toolCallId, request: snapshot, digest: digest(snapshot) }; + } + + issueApproved(conversationId: string, toolCallId: string, request: CuaActionRequest): unknown { + this.checkRun(request.runId); + const proposal = this.pending; + if (proposal === null || proposal.conversationId !== conversationId + || proposal.toolCallId !== toolCallId || proposal.digest !== digest(request)) { + throw new CuaApprovalError('CUA_APPROVAL_MISMATCH'); + } + const token = randomUUID(); + this.permits.set(token, { ...proposal, issuedAt: this.options.now() }); + this.pending = null; + return token; + } + + deny(conversationId: string, toolCallId: string): void { + if (this.pending?.conversationId !== conversationId || this.pending.toolCallId !== toolCallId) { + throw new CuaApprovalError('CUA_APPROVAL_MISMATCH'); + } + this.pending = null; + } + + getPendingApproval(): Readonly<{ + conversationId: string; toolCallId: string; sessionId: string; runId: string; + windowId: number; frameId: string; layoutRevision: number; + }> | null { + const pending = this.pending; + if (!pending) return null; + const { sessionId, runId, windowId, frameId, layoutRevision } = pending.request; + return Object.freeze({ conversationId: pending.conversationId, toolCallId: pending.toolCallId, + sessionId, runId, windowId, frameId, layoutRevision }); + } + + /** Synchronous, atomic and one-use, including attempts with wrong evidence. */ + consume(request: CuaActionRequest, token: unknown): void { + this.checkRun(request.runId); + if (this.pending !== null) throw new CuaApprovalError('CUA_BUSY'); + const permit = typeof token === 'string' ? this.permits.get(token) : undefined; + if (typeof token === 'string') this.permits.delete(token); + if (permit === undefined) throw new CuaApprovalError('CUA_ACTION_REPLAYED'); + if (permit.digest !== digest(request)) throw new CuaApprovalError('CUA_APPROVAL_MISMATCH'); + const elapsed = this.options.now() - permit.issuedAt; + if (elapsed < 0 || elapsed >= this.options.permitTtlMs) throw new CuaApprovalError('CUA_APPROVAL_EXPIRED'); + const count = this.actionsByRun.get(request.runId) ?? 0; + if (count >= this.options.maxActionsPerRun) throw new CuaApprovalError('CUA_BUDGET_EXCEEDED'); + this.actionsByRun.set(request.runId, count + 1); + } + + /** Called synchronously on every cancellation source before releasing input. */ + revokeRun(runId: string): void { + this.revokedRuns.add(runId); + if (this.pending?.request.runId === runId) this.pending = null; + for (const [token, permit] of this.permits) { + if (permit.request.runId === runId) this.permits.delete(token); + } + } + + /** A failed release requires explicit app/driver recovery, never a new run. */ + recordCleanupFailure(): void { + this.cleanupFailed = true; + this.pending = null; + this.permits.clear(); + } + + private checkRun(runId: string): void { + if (this.cleanupFailed) throw new CuaApprovalError('CUA_CLEANUP_FAILED'); + if (this.revokedRuns.has(runId)) throw new CuaApprovalError('CUA_CANCELLED'); + } +} + +/** Structural seam implemented by the independently owned self-window driver. */ +export interface CuaAgentDriver { + observe(scope: { sessionId: string; runId: string }): Promise; + execute(request: CuaActionRequest, permit: unknown, signal?: AbortSignal): Promise; + cancel(reason?: string): Promise; + getState(): CuaState; + setExecutionBlocked(blocked: boolean): void; +} + +interface BoundRun { + readonly conversationId: string; + readonly runId: string; + readonly controller: AbortController; + frame: CuaFrame | null; + observation: Promise | null; + pending: { readonly toolCallId: string; readonly request: CuaActionRequest } | null; +} + +/** Trusted main wiring owns this instance and the immutable run bindings. */ +export class CuaAgentOrchestrator { + private readonly sessionId = randomUUID(); + private readonly runs = new Map(); + private readonly byConversation = new Map(); + private readonly cancellations = new Map>(); + + constructor(readonly authority: CuaApprovalAuthority, private readonly options: { + readonly driver: CuaAgentDriver; + readonly onAbortConversation: (conversationId: string) => void; + }) {} + + async observe(conversationId: string): Promise<{ success: true; summary: string; frame: CuaFrame }> { + let run = this.byConversation.get(conversationId); + if (run?.controller.signal.aborted) throw new CuaApprovalError('CUA_CANCELLED'); + if (!run) { + if (this.byConversation.size > 0) throw new CuaApprovalError('CUA_BUSY'); + run = { conversationId, runId: randomUUID(), controller: new AbortController(), frame: null, observation: null, pending: null }; + this.byConversation.set(conversationId, run); + this.runs.set(run.runId, run); + } + if (run.pending) throw new CuaApprovalError('CUA_BUSY'); + if (run.observation) throw new CuaApprovalError('CUA_BUSY'); + run.observation = this.options.driver.observe({ sessionId: this.sessionId, runId: run.runId }); + let frame: CuaFrame; + try { frame = await run.observation; } + finally { run.observation = null; } + run.controller.signal.throwIfAborted(); + if (frame.sessionId !== this.sessionId || frame.runId !== run.runId) throw new CuaApprovalError('CUA_SCOPE_CHANGED'); + run.frame = structuredClone(frame); + return { success: true, summary: `Self-window observation frameId=${frame.frameId}, layoutRevision=${frame.layoutRevision}; CSS viewport ${frame.viewport.width}×${frame.viewport.height}.`, frame }; + } + + prepareApproval(conversationId: string, toolCallId: string, request: CuaActionRequest): AgentCuaApprovalSummary { + const run = this.requireRun(conversationId, request); + const frame = run.frame; + if (!frame || frame.frameId !== request.frameId || frame.layoutRevision !== request.layoutRevision) { + throw new CuaApprovalError('CUA_FRAME_STALE'); + } + this.options.driver.setExecutionBlocked(true); + if (run.pending) { + // LangGraph replays this node while resuming its interrupt. + if (run.pending.toolCallId !== toolCallId || digest(run.pending.request) !== digest(request)) { + throw new CuaApprovalError('CUA_APPROVAL_MISMATCH'); + } + } else { + this.authority.propose(conversationId, toolCallId, request); + run.pending = { toolCallId, request: structuredClone(request) }; + } + const action = request.action; + return { actionKind: action.kind, actionLabel: action.kind === 'key' ? `Press ${action.modifiers.join('+')}${action.modifiers.length ? '+' : ''}${action.key}` : action.kind === 'drag' ? `Drag for ${action.durationMs} ms` : 'Click', + frameId: request.frameId, scopeRevision: request.layoutRevision, coordinateSpace: 'css', + ...(action.kind === 'click' ? { coords: action.point } : action.kind === 'drag' ? { coords: action.from, dragTo: action.to } : {}) }; + } + + deny(conversationId: string, toolCallId: string): void { + this.options.driver.setExecutionBlocked(true); + this.authority.deny(conversationId, toolCallId); + const run = this.byConversation.get(conversationId); + if (run?.pending?.toolCallId === toolCallId) run.pending = null; + } + + async executeApproved(conversationId: string, toolCallId: string, request: CuaActionRequest): Promise { + const run = this.requireRun(conversationId, request); + try { + const permit = this.authority.issueApproved(conversationId, toolCallId, request); + run.pending = null; + this.options.driver.setExecutionBlocked(false); + const state = await this.options.driver.execute(request, permit, run.controller.signal); + if (!state.cleanupComplete || state.phase === 'cleanup-failed') { + this.authority.recordCleanupFailure(); + throw new CuaApprovalError('CUA_CLEANUP_FAILED'); + } + run.frame = null; + this.options.driver.setExecutionBlocked(true); + return { state, ...await this.observe(conversationId) }; + } catch (error) { + await this.cancelConversation(conversationId); + throw error; + } finally { + this.options.driver.setExecutionBlocked(true); + } + } + + /** Driver onCancel calls this; no driver methods and no recursive cancellation. */ + abortRun(runId: string): void { + const run = this.runs.get(runId); + if (!run) return; + this.authority.revokeRun(runId); + run.controller.abort(); + this.options.onAbortConversation(run.conversationId); + } + + /** Trusted driver onState only; a renderer state payload must never call this. */ + settleRun(state: CuaState): void { + if (state.sessionId !== this.sessionId || !state.runId) return; + const run = this.runs.get(state.runId); + if (!run) return; + if (state.phase === 'cleanup-failed') this.authority.recordCleanupFailure(); + if (state.phase !== 'stopped' && state.phase !== 'cleanup-failed') return; + this.abortRun(run.runId); + this.runs.delete(run.runId); + if (this.byConversation.get(run.conversationId) === run) this.byConversation.delete(run.conversationId); + } + + cancelConversation(conversationId: string): Promise { + const existing = this.cancellations.get(conversationId); + if (existing) return existing; + const run = this.byConversation.get(conversationId); + if (!run) return Promise.resolve(); + this.abortRun(run.runId); + const settlement = Promise.resolve().then(async () => { + await run.observation?.catch(() => undefined); + const state = this.options.driver.getState(); + // A stale cancellation never cancels another conversation or newer run. + if (state.runId !== run.runId || state.sessionId !== this.sessionId) return; + this.options.driver.setExecutionBlocked(true); + const stopped = await this.options.driver.cancel('agent_cancelled'); + if (!stopped.cleanupComplete || stopped.phase === 'cleanup-failed') { + this.authority.recordCleanupFailure(); + throw new CuaApprovalError('CUA_CLEANUP_FAILED'); + } + }).finally(() => { + this.runs.delete(run.runId); + if (this.byConversation.get(conversationId) === run) this.byConversation.delete(conversationId); + this.cancellations.delete(conversationId); + }); + this.cancellations.set(conversationId, settlement); + return settlement; + } + + private requireRun(conversationId: string, request: CuaActionRequest): BoundRun { + const run = this.byConversation.get(conversationId); + if (!run || run.runId !== request.runId || this.sessionId !== request.sessionId + || run.frame?.windowId !== request.windowId) throw new CuaApprovalError('CUA_SCOPE_CHANGED'); + run.controller.signal.throwIfAborted(); + return run; + } +} diff --git a/tests/agentChatCuaLifecycle.test.ts b/tests/agentChatCuaLifecycle.test.ts new file mode 100644 index 00000000..558ede35 --- /dev/null +++ b/tests/agentChatCuaLifecycle.test.ts @@ -0,0 +1,102 @@ +import { AIMessage } from '@langchain/core/messages'; +import { tool } from '@langchain/core/tools'; +import { z } from 'zod'; +import { describe, expect, it } from 'vitest'; +import { buildAgentChatGraph } from '../src/main/agentChatGraph'; +import { AgentChatSessionManager } from '../src/main/agentChatSession'; + +const call = (id: string) => new AIMessage({ content: '', tool_calls: [{ id, name: 'cuaAction', args: {} }] }); +function fixture(replies: AIMessage[], options: { cancelCua?: (id: string) => Promise } = {}) { + let inputs = 0; + let index = 0; + const bundle = buildAgentChatGraph({ + tools: [tool(async () => { inputs++; return 'done'; }, { name: 'cuaAction', description: 'test CUA', schema: z.object({}) })], + mutatingToolNames: new Set(), // Per-call policy must fail closed even if this list is wrong. + perCallApprovalToolNames: new Set(['cuaAction']), + createModel: () => ({ invoke: async () => replies[index++] ?? new AIMessage('Done') }) + }); + return { session: new AgentChatSessionManager(bundle, options), inputs: () => inputs }; +} +const send = { conversationId: 'conversation', text: 'move clip', modelId: 'qwen2.5-coder' }; + +describe('CUA graph approval and cancellation lifecycle', () => { + it('always authorizes only the exact CUA call and prompts again for the next', async () => { + const { session, inputs } = fixture([call('one'), call('two'), new AIMessage('Done')]); + await session.sendMessage(send); + const next = await session.respondToApproval({ conversationId: send.conversationId, toolCallId: 'one', decision: 'always' }); + expect(inputs()).toBe(1); + expect(next.pendingApproval?.toolCallId).toBe('two'); + await session.respondToApproval({ conversationId: send.conversationId, toolCallId: 'two', decision: 'deny' }); + expect(inputs()).toBe(1); + }); + + it('denial executes zero inputs and reused call IDs never execute', async () => { + const { session, inputs } = fixture([call('one'), call('one'), new AIMessage('Done')]); + await session.sendMessage(send); + const result = await session.respondToApproval({ conversationId: send.conversationId, toolCallId: 'one', decision: 'deny' }); + expect(inputs()).toBe(0); + expect(result.messages.some((message) => message.text.includes('CUA_ACTION_REPLAYED'))).toBe(true); + }); + + it('concurrent approvals execute once and the second request is busy', async () => { + const { session, inputs } = fixture([call('one'), new AIMessage('Done')]); + await session.sendMessage(send); + const approve = { conversationId: send.conversationId, toolCallId: 'one', decision: 'approve' as const }; + const results = await Promise.all([session.respondToApproval(approve), session.respondToApproval(approve)]); + expect(inputs()).toBe(1); + expect(results.some((result) => result.errorCode === 'CUA_BUSY')).toBe(true); + }); + + it('shares cancel settlement and does not accept approval before release completes', async () => { + let release!: () => void; + let cancels = 0; + const released = new Promise((resolve) => { release = resolve; }); + const { session, inputs } = fixture([call('one')], { cancelCua: async () => { cancels++; await released; } }); + await session.sendMessage(send); + const first = session.cancelConversation(send); + expect(session.cancelConversation(send)).toBe(first); + const blocked = await session.respondToApproval({ conversationId: send.conversationId, toolCallId: 'one', decision: 'approve' }); + expect(blocked.errorCode).toBe('CUA_BUSY'); + expect(inputs()).toBe(0); + release(); + await first; + expect(cancels).toBe(1); + const stale = await session.respondToApproval({ conversationId: send.conversationId, toolCallId: 'one', decision: 'approve' }); + expect(stale.error).toContain('no longer matches'); + expect(inputs()).toBe(0); + }); + + it('aborts a running model before waiting for actual input release', async () => { + let started!: () => void; + const ready = new Promise((resolve) => { started = resolve; }); + let aborted = false; + let release!: () => void; + const released = new Promise((resolve) => { release = resolve; }); + const bundle = buildAgentChatGraph({ tools: [], mutatingToolNames: new Set(), createModel: () => ({ + invoke: async (_messages, options) => new Promise((_resolve, reject) => { + options?.signal?.addEventListener('abort', () => { aborted = true; reject(new Error('aborted')); }, { once: true }); + started(); + }) + }) }); + const session = new AgentChatSessionManager(bundle, { cancelCua: async () => { expect(aborted).toBe(true); await released; } }); + const turn = session.sendMessage(send); + await ready; + const cancel = session.cancelConversation(send); + expect(aborted).toBe(true); + let settled = false; + void cancel.then(() => { settled = true; }); + await Promise.resolve(); + expect(settled).toBe(false); + release(); + await Promise.all([turn, cancel]); + expect(settled).toBe(true); + }); + + it('reports failed release and does not delete the pending checkpoint as success', async () => { + const { session } = fixture([call('one')], { cancelCua: async () => { throw new Error('release failed'); } }); + await session.sendMessage(send); + const result = await session.cancelConversation(send); + expect(result.errorCode).toBe('CUA_CLEANUP_FAILED'); + expect(result.status).toBe('error'); + }); +}); diff --git a/tests/cuaAgentOrchestration.test.ts b/tests/cuaAgentOrchestration.test.ts new file mode 100644 index 00000000..33d3c2bc --- /dev/null +++ b/tests/cuaAgentOrchestration.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; +import type { CuaActionRequest } from '../src/shared/cua'; +import { CuaApprovalAuthority } from '../src/main/cuaAgentOrchestration'; + +const request: CuaActionRequest = { + sessionId: 'session', runId: 'run', windowId: 1, frameId: 'frame', layoutRevision: 3, + action: { kind: 'drag', from: { x: 10, y: 20 }, to: { x: 50, y: 20 }, durationMs: 100 } +}; +function fixture(maxActionsPerRun = 2) { + let now = 0; + const authority = new CuaApprovalAuthority({ permitTtlMs: 100, maxActionsPerRun, now: () => now }); + const approve = (id = 'call', action = request) => { + authority.propose('conversation', id, action); + return authority.issueApproved('conversation', id, action); + }; + return { authority, approve, advance: (ms: number) => { now += ms; } }; +} + +describe('main CUA approval authority', () => { + it('denial dispatches nothing and cannot later be upgraded by replay', () => { + const { authority } = fixture(); + authority.propose('conversation', 'call', request); + authority.deny('conversation', 'call'); + expect(() => authority.issueApproved('conversation', 'call', request)).toThrow('CUA_APPROVAL_MISMATCH'); + expect(() => authority.propose('conversation', 'call', request)).toThrow('CUA_ACTION_REPLAYED'); + }); + + it('accepts exactly one consumption and rejects duplicate approval', () => { + const { authority, approve } = fixture(); + const token = approve(); + expect(() => authority.issueApproved('conversation', 'call', request)).toThrow('CUA_APPROVAL_MISMATCH'); + authority.consume(request, token); + expect(() => authority.consume(request, token)).toThrow('CUA_ACTION_REPLAYED'); + }); + + it.each(['sessionId', 'runId', 'windowId', 'frameId', 'layoutRevision'] as const)('binds %s to the original evidence', (field) => { + const { authority, approve } = fixture(); + const token = approve(); + const changed = { ...request, [field]: typeof request[field] === 'number' ? 99 : 'different' } as CuaActionRequest; + expect(() => authority.consume(changed, token)).toThrow('CUA_APPROVAL_MISMATCH'); + expect(() => authority.consume(request, token)).toThrow('CUA_ACTION_REPLAYED'); + }); + + it('snapshots action arguments before approval and rejects a changed drag', () => { + const { authority } = fixture(); + const mutable = structuredClone(request); + authority.propose('conversation', 'call', mutable); + if (mutable.action.kind === 'drag') Object.assign(mutable.action.to, { x: 999 }); + expect(() => authority.issueApproved('conversation', 'call', mutable)).toThrow('CUA_APPROVAL_MISMATCH'); + const token = authority.issueApproved('conversation', 'call', request); + expect(() => authority.consume(mutable, token)).toThrow('CUA_APPROVAL_MISMATCH'); + }); + + it('never resets the permit clock and rejects its exact expiry boundary', () => { + const { authority, approve, advance } = fixture(); + const token = approve(); + advance(100); + expect(() => authority.consume(request, token)).toThrow('CUA_APPROVAL_EXPIRED'); + expect(() => authority.consume(request, token)).toThrow('CUA_ACTION_REPLAYED'); + }); + + it('cancellation revokes pending and issued permits before input release', () => { + const { authority, approve } = fixture(); + const token = approve(); + authority.revokeRun('run'); + authority.revokeRun('run'); + expect(() => authority.consume(request, token)).toThrow('CUA_CANCELLED'); + expect(() => authority.propose('conversation', 'new', request)).toThrow('CUA_CANCELLED'); + }); + + it('blocks another proposal until the approved action has been consumed', () => { + const { authority, approve } = fixture(); + const token = approve(); + expect(() => authority.propose('other', 'call', request)).toThrow('CUA_BUSY'); + authority.consume(request, token); + authority.propose('other', 'call', request); + expect(() => authority.consume(request, token)).toThrow('CUA_BUSY'); + }); + + it('bounds consumed actions per run, across conversations and new call IDs', () => { + const { authority, approve } = fixture(1); + authority.consume(request, approve()); + expect(() => authority.propose('other', 'next', request)).toThrow('CUA_BUDGET_EXCEEDED'); + }); + + it('locks every new run when release cleanup failed', () => { + const { authority, approve } = fixture(); + const token = approve(); + authority.recordCleanupFailure(); + expect(() => authority.consume(request, token)).toThrow('CUA_CLEANUP_FAILED'); + expect(() => authority.propose('other', 'next', { ...request, runId: 'new-run' })).toThrow('CUA_CLEANUP_FAILED'); + }); +}); diff --git a/tests/cuaAgentRunBinding.test.ts b/tests/cuaAgentRunBinding.test.ts new file mode 100644 index 00000000..9665ebb2 --- /dev/null +++ b/tests/cuaAgentRunBinding.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest'; +import { CuaAgentOrchestrator, CuaApprovalAuthority, type CuaAgentDriver } from '../src/main/cuaAgentOrchestration'; +import type { CuaActionRequest, CuaFrame, CuaState } from '../src/shared/cua'; + +function fixture() { + let state: CuaState = { sessionId: null, runId: null, windowId: 7, phase: 'idle', cursor: null, + dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; + let frameNumber = 0; + let inputs = 0; + let cancellations = 0; + let blocked = true; + const aborted: string[] = []; + const authority = new CuaApprovalAuthority({ permitTtlMs: 100, maxActionsPerRun: 2, now: () => 0 }); + const driver: CuaAgentDriver = { + observe: async (scope) => { + state = { ...state, ...scope, phase: 'ready' }; + return { ...scope, windowId: 7, frameId: `frame-${++frameNumber}`, layoutRevision: 1, capturedAt: 0, + viewport: { width: 100, height: 100 }, bitmap: { width: 100, height: 100 }, deviceScaleFactor: 1, + zoomFactor: 1, pngDataUrl: 'data:image/png;base64,AAAA' }; + }, + execute: async (request, permit) => { + expect(blocked).toBe(false); + authority.consume(request, permit); + inputs++; + return state; + }, + getState: () => state, + cancel: async () => { cancellations++; state = { ...state, phase: 'stopped' }; return state; }, + setExecutionBlocked: (value) => { blocked = value; } + }; + const orchestrator = new CuaAgentOrchestrator(authority, { driver, onAbortConversation: (id) => { aborted.push(id); } }); + const requestFor = (frame: CuaFrame): CuaActionRequest => ({ sessionId: frame.sessionId, runId: frame.runId, + windowId: frame.windowId, frameId: frame.frameId, layoutRevision: frame.layoutRevision, action: { kind: 'click', point: { x: 10, y: 20 } } }); + return { authority, driver, orchestrator, aborted, requestFor, inputs: () => inputs, + cancellations: () => cancellations, blocked: () => blocked }; +} + +describe('CUA immutable run binding and dispatch', () => { + it('preserves the original frame through prompt replay and runs the approved action once', async () => { + const f = fixture(); + const observed = await f.orchestrator.observe('a'); + const request = f.requestFor(observed.frame); + const summary = f.orchestrator.prepareApproval('a', 'one', request); + expect(f.orchestrator.prepareApproval('a', 'one', request)).toEqual(summary); + expect(f.authority.getPendingApproval()?.runId).toBe(observed.frame.runId); + await f.orchestrator.executeApproved('a', 'one', request); + expect(f.inputs()).toBe(1); + expect(f.blocked()).toBe(true); + await expect(f.orchestrator.executeApproved('a', 'one', request)).rejects.toThrow(); + expect(f.inputs()).toBe(1); + }); + + it('refuses a newly observed frame to inherit an old approval', async () => { + const f = fixture(); + const first = await f.orchestrator.observe('a'); + const second = await f.orchestrator.observe('a'); + expect(second.frame.frameId).not.toBe(first.frame.frameId); + expect(() => f.orchestrator.prepareApproval('a', 'one', f.requestFor(first.frame))).toThrow('CUA_FRAME_STALE'); + expect(f.inputs()).toBe(0); + }); + + it('cannot cancel the active run through another conversation ID', async () => { + const f = fixture(); + await f.orchestrator.observe('a'); + await f.orchestrator.cancelConversation('b'); + expect(f.cancellations()).toBe(0); + expect(f.aborted).toEqual([]); + }); + + it('shares cancellation settlement, revokes first and removes the old run binding', async () => { + const f = fixture(); + const old = await f.orchestrator.observe('a'); + const request = f.requestFor(old.frame); + f.orchestrator.prepareApproval('a', 'one', request); + const cancelled = f.orchestrator.cancelConversation('a'); + expect(f.orchestrator.cancelConversation('a')).toBe(cancelled); + expect(f.authority.getPendingApproval()).toBeNull(); + expect(f.aborted).toEqual(['a']); + await cancelled; + const next = await f.orchestrator.observe('b'); + expect(next.frame.runId).not.toBe(old.frame.runId); + f.orchestrator.abortRun(old.frame.runId); + expect(f.aborted).toEqual(['a']); + f.orchestrator.prepareApproval('b', 'new', f.requestFor(next.frame)); + }); + + it('settles a trusted external stop without keeping a dead conversation binding', async () => { + const f = fixture(); + const old = await f.orchestrator.observe('a'); + f.orchestrator.abortRun(old.frame.runId); + f.orchestrator.settleRun({ ...f.driver.getState(), phase: 'stopped' }); + const next = await f.orchestrator.observe('b'); + expect(next.frame.runId).not.toBe(old.frame.runId); + f.orchestrator.abortRun(old.frame.runId); + expect(f.aborted.every((id) => id === 'a')).toBe(true); + }); + + it('denial leaves main execution blocked and provides no permit', async () => { + const f = fixture(); + const frame = (await f.orchestrator.observe('a')).frame; + const request = f.requestFor(frame); + f.orchestrator.prepareApproval('a', 'one', request); + f.orchestrator.deny('a', 'one'); + expect(f.blocked()).toBe(true); + await expect(f.orchestrator.executeApproved('a', 'one', request)).rejects.toThrow('CUA_APPROVAL_MISMATCH'); + expect(f.inputs()).toBe(0); + }); +}); From 8d7dd2ad15a92453c66b3737ada4da66822e9502 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:05:26 +0900 Subject: [PATCH 08/96] feat(cua): await bounded rollback before releasing drag input --- src/main/cuaDriver.ts | 63 +++++++++++++++++++++++++++++++++++------ src/main/cuaIpc.ts | 5 +++- tests/cuaDriver.test.ts | 8 +++++- 3 files changed, 65 insertions(+), 11 deletions(-) diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 271e530d..6bf5ea30 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto'; import { performance } from 'node:perf_hooks'; import type { BrowserWindow, KeyboardInputEvent, MouseInputEvent } from 'electron'; -import { CUA_KEYS, type CuaActionRequest, type CuaFrame, type CuaPoint, type CuaRect, type CuaState, type CuaSurfaceSnapshot } from '../shared/cua'; +import { CUA_KEYS, type CuaActionRequest, type CuaCancelAck, type CuaFrame, type CuaPoint, type CuaRect, type CuaState, type CuaSurfaceSnapshot } from '../shared/cua'; export interface CuaDriverDependencies { readonly consumePermit: (request: CuaActionRequest, permit: unknown) => void; @@ -33,10 +33,11 @@ export class CuaDriver { private cancellation: Promise | null = null; private injecting = false; private cleanupFailureLatched = false; + private cancelAck: { token: string; runId: string; resolve: () => void } | null = null; private state: CuaState; constructor(private readonly window: BrowserWindow, private readonly dependencies: CuaDriverDependencies) { - this.state = { sessionId: null, runId: null, windowId: window.id, phase: 'idle', cursor: null, dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; + this.state = { cancelToken: null, targetGone: false, sessionId: null, runId: null, windowId: window.id, phase: 'idle', cursor: null, dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; window.on('blur', () => { void this.cancel('blur'); }); window.on('resize', () => { void this.cancel('resize'); }); window.on('closed', () => { void this.cancel('closed'); }); @@ -54,6 +55,10 @@ export class CuaDriver { }); } getState(): CuaState { return structuredClone(this.state); } + acknowledgeCancel(ack: CuaCancelAck): boolean { + if (!ack || this.state.phase !== 'stopping' || !this.cancelAck || ack.runId !== this.cancelAck.runId || ack.cancelToken !== this.cancelAck.token) return false; + const pending = this.cancelAck; this.cancelAck = null; pending.resolve(); return true; + } setExecutionBlocked(blocked: boolean): void { this.executionBlocked = blocked; } private publish(patch: Partial): void { this.state = { ...this.state, ...patch }; @@ -127,8 +132,32 @@ export class CuaDriver { try { this.window.webContents.sendInputEvent(event); } finally { this.injecting = false; } } + private async verifyDom(request: CuaActionRequest, points: readonly CuaPoint[]): Promise { + const surface = this.surface; + if (!surface?.safeSurface) throw new Error('CUA_UNSAFE_SURFACE'); + // Fixed read-only program, never caller-supplied JS. Independently verifies + // renderer-reported geometry/focus against the bound app document. + const expected = JSON.stringify({ viewport: surface.viewport, safe: surface.safeSurface, points, key: request.action.kind === 'key' }); + const valid: unknown = await this.window.webContents.executeJavaScript(`(() => { + const expected = ${expected}; + const close = (a,b) => Math.abs(a-b) <= 0.5; + if (!close(innerWidth,expected.viewport.width) || !close(innerHeight,expected.viewport.height)) return false; + if (document.querySelector('[role="dialog"][aria-modal="true"],dialog[open],[role="menu"]')) return false; + const safe = [...document.querySelectorAll('[data-cua-safe-surface]')].find(e => e.getAttribute('data-cua-safe-surface') === expected.safe.kind && e.getBoundingClientRect().width > 0); + if (!safe || safe.closest('[inert],[hidden],[aria-hidden="true"]')) return false; + const r = safe.getBoundingClientRect(), want = expected.safe.rect; + if (!['x','y','width','height'].every(k => close(r[k],want[k]))) return false; + const forbidden = '[data-cua-protected],[role="dialog"],[role="menu"],.oc-editor-host__header'; + if (expected.key && (!document.activeElement || !safe.contains(document.activeElement) || document.activeElement.closest(forbidden))) return false; + return expected.points.every(p => { const e = document.elementFromPoint(p.x,p.y); return e && safe.contains(e) && !e.closest(forbidden); }); + })()`); + if (valid !== true) throw new Error('CUA_UNSAFE_DOCUMENT'); + } async execute(request: CuaActionRequest, permit: unknown, signal?: AbortSignal): Promise { - const points = this.validate(request); + let points = this.validate(request); + await this.verifyDom(request, points); + // DOM reading is asynchronous: repeat all mutable checks immediately before consume. + points = this.validate(request); if (signal?.aborted) throw new Error('CUA_CANCELLED'); this.dependencies.consumePermit(request, permit); // No await between validation, one-use consume and first input. const generation = this.generation; @@ -172,15 +201,31 @@ export class CuaDriver { // Assign the promise before callbacks so recursive cancellation is idempotent. let settle!: (state: CuaState) => void; this.cancellation = new Promise(resolve => { settle = resolve; }); - this.publish({ phase: 'stopping', error: reason, cleanupComplete: false }); + const needsAck = this.heldMouse !== null && this.state.dragStart !== null && this.state.runId !== null; + let ackReceived = false; + let resolveAck!: () => void; + const ackPromise = new Promise(resolve => { resolveAck = resolve; }); + const token = needsAck ? randomUUID() : null; + if (token && this.state.runId) this.cancelAck = { token, runId: this.state.runId, resolve: () => { ackReceived = true; resolveAck(); } }; let revokeFailed = false; try { this.dependencies.onCancel?.({ sessionId: this.state.sessionId, runId: this.state.runId, reason }); } catch { reason += ':authority-revoke-failed'; revokeFailed = true; } - const failures = this.release(); - if (revokeFailed) failures.push('authority-revoke'); - if (failures.length) this.cleanupFailureLatched = true; - this.publish({ phase: this.cleanupFailureLatched ? 'cleanup-failed' : 'stopped', error: reason, cleanupComplete: !this.cleanupFailureLatched, releaseFailures: failures.length ? failures : this.state.releaseFailures, dragStart: null }); - settle(this.getState()); + this.publish({ phase: 'stopping', error: reason, cleanupComplete: false, cancelToken: token }); + void (async () => { + if (needsAck) { + let timeout!: ReturnType; + await Promise.race([ackPromise, new Promise(resolve => { timeout = setTimeout(resolve, 200); })]); + clearTimeout(timeout); + } + this.cancelAck = null; + const failures = this.release(); // Always attempt physical release, even without rollback ack. + if (needsAck && !ackReceived) failures.push('renderer-rollback-unconfirmed'); + if (revokeFailed) failures.push('authority-revoke'); + if (failures.length) this.cleanupFailureLatched = true; + const targetGone = this.window.isDestroyed() || this.window.webContents.isDestroyed(); + this.publish({ phase: this.cleanupFailureLatched ? 'cleanup-failed' : 'stopped', targetGone, error: reason, cleanupComplete: !this.cleanupFailureLatched, releaseFailures: failures.length ? failures : this.state.releaseFailures, dragStart: null, cancelToken: null }); + settle(this.getState()); + })(); return this.cancellation; } } diff --git a/src/main/cuaIpc.ts b/src/main/cuaIpc.ts index d72b9dbd..1638b82a 100644 --- a/src/main/cuaIpc.ts +++ b/src/main/cuaIpc.ts @@ -1,6 +1,6 @@ import type { BrowserWindow, IpcMain, IpcMainInvokeEvent } from 'electron'; import { IPC_CHANNELS } from '../shared/ipc'; -import type { CuaSurfaceSnapshot } from '../shared/cua'; +import type { CuaCancelAck, CuaSurfaceSnapshot } from '../shared/cua'; import { fail, ok } from './ipcResponses'; import type { CuaDriver } from './cuaDriver'; @@ -15,6 +15,9 @@ export function registerCuaIpc(ipc: IpcMain, getTarget: () => { window: BrowserW ipc.handle(IPC_CHANNELS.cuaGetState, event => { try { return ok(own(event).getState()); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } }); + ipc.handle(IPC_CHANNELS.cuaAckCancel, (event, ack: CuaCancelAck) => { + try { return ok({ accepted: own(event).acknowledgeCancel(ack) }); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } + }); ipc.handle(IPC_CHANNELS.cuaStop, event => { try { void own(event).cancel('user-stop'); return ok({ accepted: true }); } catch (e) { return fail('UNKNOWN_ERROR', String(e)); } }); diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts index c19638e8..07f89cea 100644 --- a/tests/cuaDriver.test.ts +++ b/tests/cuaDriver.test.ts @@ -7,12 +7,15 @@ import { cuaBitmapPointToViewport, type CuaActionRequest, type CuaSurfaceSnapsho function fixture() { const contents = Object.assign(new EventEmitter(), { isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: () => 1, + executeJavaScript: vi.fn(async () => true), capturePage: vi.fn(async () => ({ getSize: () => ({ width: 800, height: 600 }), isEmpty: () => false, toDataURL: () => 'data:image/png;base64,test' })), sendInputEvent: vi.fn((input: MouseInputEvent) => contents.emit(input.type.startsWith('mouse') ? 'before-mouse-event' : 'before-input-event', {}, input)) }); const window = Object.assign(new EventEmitter(), { id: 7, webContents: contents, isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true) }); const consumePermit = vi.fn(); const onCancel = vi.fn(); - const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel }); + const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel, onState: state => { + if (state.phase === 'stopping' && state.cancelToken && state.runId) driver.acknowledgeCancel({ runId: state.runId, cancelToken: state.cancelToken }); + } }); const surface: CuaSurfaceSnapshot = { executionBlocked: false, blockReason: null, layoutRevision: 1, viewport: { width: 800, height: 600 }, safeSurface: { kind: 'timeline', rect: { x: 0, y: 0, width: 800, height: 600 }, interactive: true }, protectedRects: [], focusedInSafeSurface: true, focusedTestId: null }; driver.reportSurface(surface); driver.setExecutionBlocked(false); const observe = async (): Promise => { @@ -56,6 +59,7 @@ describe('self-window CUA safety', () => { it('releases a held drag on stop and sends no subsequent moves', async () => { const f = fixture(), r = await f.observe(); const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 3000 } }, 'p'); + await Promise.resolve(); await Promise.resolve(); const rejected = expect(execution).rejects.toThrow('CANCELLED'); const cancelled = f.driver.cancel('user-stop'); expect(f.driver.cancel()).toBe(cancelled); @@ -69,6 +73,7 @@ describe('self-window CUA safety', () => { it('cancels real input during drag but ignores synchronous injected events', async () => { const f = fixture(), r = await f.observe(); const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p'); + await Promise.resolve(); await Promise.resolve(); expect(f.driver.getState().phase).toBe('acting'); f.contents.emit('before-input-event', {}, { type: 'keyDown', key: 'Escape' }); await expect(execution).rejects.toThrow('CANCELLED'); @@ -78,6 +83,7 @@ describe('self-window CUA safety', () => { it('does not report clean stop if held input release throws', async () => { const f = fixture(), r = await f.observe(); const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p'); + await Promise.resolve(); await Promise.resolve(); f.contents.sendInputEvent.mockImplementation(() => { throw new Error('closed'); }); const stopped = await f.driver.cancel('closed'); expect(stopped.phase).toBe('cleanup-failed'); From 3b9cd4e741604424c3f9030ce8c2bf90de19bd7f Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:07:17 +0900 Subject: [PATCH 09/96] fix(agent): align cancellation state and test observed CUA approval --- src/main/agentChatTools.ts | 4 ++-- src/main/cuaAgentOrchestration.ts | 3 ++- tests/cuaAgentRunBinding.test.ts | 36 ++++++++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/main/agentChatTools.ts b/src/main/agentChatTools.ts index 675cab67..1d1f25a5 100644 --- a/src/main/agentChatTools.ts +++ b/src/main/agentChatTools.ts @@ -58,8 +58,8 @@ export const CUA_ACTION_TOOL_SCHEMA = z.object({ frameId: z.string().min(1), layoutRevision: z.number().int().nonnegative(), action: z.discriminatedUnion('kind', [ z.object({ kind: z.literal('click'), point }).strict(), - z.object({ kind: z.literal('drag'), from: point, to: point, durationMs: z.number().int().min(1).max(3000) }).strict(), - z.object({ kind: z.literal('key'), key: z.enum(CUA_KEYS), modifiers: z.array(z.enum(['shift', 'control', 'meta', 'alt'])).max(4) }).strict() + z.object({ kind: z.literal('drag'), from: point, to: point, durationMs: z.number().int().min(100).max(3000) }).strict(), + z.object({ kind: z.literal('key'), key: z.enum(CUA_KEYS), modifiers: z.array(z.enum(['shift', 'control', 'meta', 'alt'])).max(1) }).strict() ]) }).strict(); diff --git a/src/main/cuaAgentOrchestration.ts b/src/main/cuaAgentOrchestration.ts index 4110145a..bd28d91f 100644 --- a/src/main/cuaAgentOrchestration.ts +++ b/src/main/cuaAgentOrchestration.ts @@ -243,6 +243,7 @@ export class CuaAgentOrchestrator { const run = this.runs.get(runId); if (!run) return; this.authority.revokeRun(runId); + if (run.controller.signal.aborted) return; run.controller.abort(); this.options.onAbortConversation(run.conversationId); } @@ -252,7 +253,7 @@ export class CuaAgentOrchestrator { if (state.sessionId !== this.sessionId || !state.runId) return; const run = this.runs.get(state.runId); if (!run) return; - if (state.phase === 'cleanup-failed') this.authority.recordCleanupFailure(); + if (state.phase === 'cleanup-failed' || (state.phase === 'stopped' && !state.cleanupComplete)) this.authority.recordCleanupFailure(); if (state.phase !== 'stopped' && state.phase !== 'cleanup-failed') return; this.abortRun(run.runId); this.runs.delete(run.runId); diff --git a/tests/cuaAgentRunBinding.test.ts b/tests/cuaAgentRunBinding.test.ts index 9665ebb2..cee64f21 100644 --- a/tests/cuaAgentRunBinding.test.ts +++ b/tests/cuaAgentRunBinding.test.ts @@ -1,10 +1,14 @@ import { describe, expect, it } from 'vitest'; import { CuaAgentOrchestrator, CuaApprovalAuthority, type CuaAgentDriver } from '../src/main/cuaAgentOrchestration'; import type { CuaActionRequest, CuaFrame, CuaState } from '../src/shared/cua'; +import { AIMessage, type BaseMessage } from '@langchain/core/messages'; +import { buildAgentChatGraph, isToolMessage } from '../src/main/agentChatGraph'; +import { createCuaAgentChatTools, AGENT_CHAT_CUA_PER_CALL_TOOL_NAMES } from '../src/main/agentChatTools'; +import { AgentChatSessionManager } from '../src/main/agentChatSession'; function fixture() { let state: CuaState = { sessionId: null, runId: null, windowId: 7, phase: 'idle', cursor: null, - dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; + dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [], cancelToken: null, targetGone: false }; let frameNumber = 0; let inputs = 0; let cancellations = 0; @@ -36,6 +40,36 @@ function fixture() { } describe('CUA immutable run binding and dispatch', () => { + it('carries PNG evidence to a synthetic model, displays exact approval, then reobserves without transcript base64', async () => { + const f = fixture(); + let step = 0; + let seen: BaseMessage[] = []; + const bundle = buildAgentChatGraph({ tools: createCuaAgentChatTools(f.orchestrator), cua: f.orchestrator, + mutatingToolNames: new Set(['executeCuaAction']), perCallApprovalToolNames: AGENT_CHAT_CUA_PER_CALL_TOOL_NAMES, + createModel: () => ({ invoke: async (messages) => { + seen = messages; + if (step++ === 0) return new AIMessage({ content: '', tool_calls: [{ id: 'observe', name: 'observeEditorWindow', args: {} }] }); + if (step === 2) { + const observation = messages.find((message) => isToolMessage(message) && message.name === 'observeEditorWindow'); + const metadata = JSON.parse(String(observation!.content).split('\n').at(-1)!) as CuaFrame; + return new AIMessage({ content: '', tool_calls: [{ id: 'action', name: 'executeCuaAction', args: { ...f.requestFor(metadata) } }] }); + } + return new AIMessage('Action observed; inspect project timeline next.'); + } }) + }); + const session = new AgentChatSessionManager(bundle, { cancelCua: (id) => f.orchestrator.cancelConversation(id) }); + const pending = await session.sendMessage({ conversationId: 'a', text: 'click', modelId: 'qwen2.5-coder' }); + expect(pending.pendingApproval?.cuaApproval?.frameId).toBe('frame-1'); + expect(pending.pendingApproval?.cuaApproval?.coords).toEqual({ x: 10, y: 20 }); + expect(f.inputs()).toBe(0); + const done = await session.respondToApproval({ conversationId: 'a', toolCallId: 'action', decision: 'approve' }); + expect(done.status).toBe('idle'); + expect(f.inputs()).toBe(1); + expect(done.messages.some((message) => message.text.includes('base64'))).toBe(false); + expect(seen.some((message) => Array.isArray(message.content) && message.content.some((block) => block.type === 'image_url'))).toBe(true); + expect(done.messages.some((message) => message.text.includes('frame-2'))).toBe(true); + }); + it('preserves the original frame through prompt replay and runs the approved action once', async () => { const f = fixture(); const observed = await f.orchestrator.observe('a'); From 1444d84ea616e24b3414436bdd5f614973af6a6d Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:08:27 +0900 Subject: [PATCH 10/96] feat(cua): wire trusted approval runtime and verify document safety --- src/main/cuaDriver.ts | 38 ++++++++++++++++++++++++----- src/main/index.ts | 54 +++++++++++++++++++++++++++++++++++++---- src/preload/index.ts | 3 +++ src/shared/ipc.ts | 1 + tests/cuaDriver.test.ts | 4 ++- 5 files changed, 88 insertions(+), 12 deletions(-) diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 6bf5ea30..45d9bdbd 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -4,6 +4,8 @@ import type { BrowserWindow, KeyboardInputEvent, MouseInputEvent } from 'electro import { CUA_KEYS, type CuaActionRequest, type CuaCancelAck, type CuaFrame, type CuaPoint, type CuaRect, type CuaState, type CuaSurfaceSnapshot } from '../shared/cua'; export interface CuaDriverDependencies { + readonly getDeviceScaleFactor?: () => number; + readonly getPendingApproval?: () => Readonly<{ sessionId: string; runId: string; windowId: number; frameId: string; layoutRevision: number }> | null; readonly consumePermit: (request: CuaActionRequest, permit: unknown) => void; readonly onCancel?: (context: { sessionId: string | null; runId: string | null; reason: string }) => void; readonly onState?: (state: CuaState) => void; @@ -34,6 +36,7 @@ export class CuaDriver { private injecting = false; private cleanupFailureLatched = false; private cancelAck: { token: string; runId: string; resolve: () => void } | null = null; + private trustedApprovalPanel: CuaRect | null = null; private state: CuaState; constructor(private readonly window: BrowserWindow, private readonly dependencies: CuaDriverDependencies) { @@ -48,10 +51,18 @@ export class CuaDriver { // Electron 43 macOS probe verifies these events fire synchronously inside // sendInputEvent. This is a delivery guard, never a renderer isTrusted test. window.webContents.on('before-input-event', () => { - if (!this.injecting && this.state.phase === 'acting') void this.cancel('user-input'); + if (!this.injecting && ['acting', 'ready'].includes(this.state.phase)) void this.cancel('user-input'); }); - window.webContents.on('before-mouse-event', () => { - if (!this.injecting && this.state.phase === 'acting') void this.cancel('user-input'); + window.webContents.on('before-mouse-event', (_event, input) => { + if (this.injecting || !['acting', 'ready'].includes(this.state.phase)) return; + const pending = this.dependencies.getPendingApproval?.(); + const frame = this.frame; + // A validated fixed panel is only a cancellation exception. It neither + // clears main execution blocking nor issues approval authority. + if (this.state.phase === 'ready' && this.executionBlocked && pending && frame && this.trustedApprovalPanel + && pending.sessionId === frame.sessionId && pending.runId === frame.runId && pending.windowId === this.window.id + && pending.frameId === frame.frameId && pending.layoutRevision === frame.layoutRevision && inside(input, this.trustedApprovalPanel)) return; + void this.cancel('user-input'); }); } getState(): CuaState { return structuredClone(this.state); } @@ -91,15 +102,30 @@ export class CuaDriver { if (!context.sessionId || !context.runId || !this.surface?.safeSurface?.interactive) throw new Error('CUA_UNSAFE_SURFACE'); const snapshot = structuredClone(this.surface); const revision = this.generation; + const panel: unknown = await this.window.webContents.executeJavaScript(`(() => { + const panels = [...document.querySelectorAll('[data-cua-protected="agent-panel"]')].filter(e => e.getBoundingClientRect().width > 0); + if (panels.length !== 1) return null; + const r = panels[0].getBoundingClientRect(); + return {x:r.x,y:r.y,width:r.width,height:r.height}; + })()`); + const candidate = panel as CuaRect | null; + const reported = snapshot.protectedRects.find(p => p.kind === 'agent-panel'); + this.trustedApprovalPanel = candidate && reported && [candidate.x,candidate.y,candidate.width,candidate.height].every(Number.isFinite) + && candidate.width > 0 && candidate.width <= snapshot.viewport.width / 2 + && ['x','y','width','height'].every(k => Math.abs(candidate[k as keyof CuaRect] - reported.rect[k as keyof CuaRect]) <= 0.5) + && !crosses({x:candidate.x,y:candidate.y},{x:candidate.x+candidate.width,y:candidate.y+candidate.height},snapshot.safeSurface!.rect) + ? candidate : null; const image = await this.window.webContents.capturePage(); this.live(); if (revision !== this.generation || !this.surface || snapshot.layoutRevision !== this.surface.layoutRevision || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) || JSON.stringify(snapshot.protectedRects) !== JSON.stringify(this.surface.protectedRects) || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport)) throw new Error('CUA_STALE_FRAME'); - const bitmap = image.getSize(); - if (image.isEmpty() || bitmap.width <= 0 || bitmap.height <= 0) throw new Error('CUA_EMPTY_CAPTURE'); - const frame: CuaFrame = { ...context, windowId: this.window.id, frameId: randomUUID(), layoutRevision: snapshot.layoutRevision, capturedAt: Date.now(), viewport: snapshot.viewport, bitmap, deviceScaleFactor: bitmap.width / snapshot.viewport.width / this.window.webContents.getZoomFactor(), zoomFactor: this.window.webContents.getZoomFactor(), pngDataUrl: image.toDataURL() }; + const png = image.toPNG(); + if (image.isEmpty() || png.length < 24 || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw new Error('CUA_EMPTY_CAPTURE'); + const bitmap = { width: png.readUInt32BE(16), height: png.readUInt32BE(20) }; + if (bitmap.width <= 0 || bitmap.height <= 0) throw new Error('CUA_EMPTY_CAPTURE'); + const frame: CuaFrame = { ...context, windowId: this.window.id, frameId: randomUUID(), layoutRevision: snapshot.layoutRevision, capturedAt: Date.now(), viewport: snapshot.viewport, bitmap, deviceScaleFactor: this.dependencies.getDeviceScaleFactor?.() ?? 1, zoomFactor: this.window.webContents.getZoomFactor(), pngDataUrl: `data:image/png;base64,${png.toString('base64')}` }; this.frame = frame; this.frameTime = performance.now(); this.cancellation = null; this.publish({ ...context, phase: 'ready', error: null, cleanupComplete: true, releaseFailures: [] }); return frame; diff --git a/src/main/index.ts b/src/main/index.ts index fcfc64c5..e7f69875 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,5 +1,6 @@ -import { app, BrowserWindow, desktopCapturer, dialog, ipcMain, session, shell, systemPreferences } from 'electron'; +import { app, BrowserWindow, desktopCapturer, dialog, ipcMain, screen, session, shell, systemPreferences } from 'electron'; import { existsSync } from 'node:fs'; +import { performance } from 'node:perf_hooks'; import { join } from 'node:path'; import { IPC_CHANNELS } from '../shared/ipc'; @@ -35,7 +36,10 @@ import { AgentChatHistoryStore } from './agentChatHistoryStore'; import { registerAgentChatIpcHandlers } from './agentChatIpcHandlers'; import { createAgentChatModel } from './agentChatModel'; import { AgentChatSessionManager } from './agentChatSession'; -import { AGENT_CHAT_SPEND_TOOL_NAMES, agentChatMutatingToolNames, createAgentChatTools } from './agentChatTools'; +import { AGENT_CHAT_CUA_PER_CALL_TOOL_NAMES, AGENT_CHAT_SPEND_TOOL_NAMES, agentChatMutatingToolNames, createAgentChatTools } from './agentChatTools'; +import { CuaDriver } from './cuaDriver'; +import { registerCuaIpc } from './cuaIpc'; +import { CuaAgentOrchestrator, CuaApprovalAuthority, type CuaAgentDriver } from './cuaAgentOrchestration'; import { ChatGptCodexAdapter } from './chatGptCodexAdapter'; import { ChatGptOAuthService } from './chatGptOAuthService'; import { CredentialStore } from './credentialStore'; @@ -172,6 +176,24 @@ function getScreenPermissionStatus(): string { * still shows Electron; this is what a packaged build and the About panel use. */ const APP_NAME = 'OpenScene'; +let cuaTarget: { window: BrowserWindow; driver: CuaDriver } | null = null; +let activeAgentChatSessions: AgentChatSessionManager | null = null; +const cuaAuthority = new CuaApprovalAuthority({ permitTtlMs: 2000, maxActionsPerRun: 20, now: () => performance.now() }); +const requireCuaDriver = (): CuaDriver => { + if (!cuaTarget || cuaTarget.window.isDestroyed()) throw new Error('CUA_TARGET_GONE'); + return cuaTarget.driver; +}; +const cuaDriverAdapter: CuaAgentDriver = { + observe: context => requireCuaDriver().observe(context), + execute: (request, permit, signal) => requireCuaDriver().execute(request, permit, signal), + cancel: reason => requireCuaDriver().cancel(reason), + getState: () => requireCuaDriver().getState(), + setExecutionBlocked: blocked => requireCuaDriver().setExecutionBlocked(blocked) +}; +const cuaAgent = new CuaAgentOrchestrator(cuaAuthority, { + driver: cuaDriverAdapter, + onAbortConversation: id => activeAgentChatSessions?.abortConversation(id) +}); /** Window icon for platforms that take one; macOS uses the bundle icon. */ function appIconPath(): string | undefined { @@ -205,6 +227,19 @@ function createWindow(): void { allowRunningInsecureContent: false } }); + const cuaDriver = new CuaDriver(mainWindow, { + getDeviceScaleFactor: () => screen.getDisplayMatching(mainWindow.getBounds()).scaleFactor, + getPendingApproval: () => cuaAuthority.getPendingApproval(), + consumePermit: (request, permit) => cuaAuthority.consume(request, permit), + onCancel: ({ runId }) => { + if (runId) { cuaAuthority.revokeRun(runId); cuaAgent.abortRun(runId); } + }, + onState: state => { + cuaAgent.settleRun(state); + if (!mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) mainWindow.webContents.send(IPC_CHANNELS.cuaStateChanged, state); + } + }); + cuaTarget = { window: mainWindow, driver: cuaDriver }; mainWindow.once('ready-to-show', () => { mainWindow.show(); @@ -306,6 +341,7 @@ function installDisplayMediaHandler(): void { } async function installIpcHandlers(): Promise { + registerCuaIpc(ipcMain, () => cuaTarget); ipcMain.handle(IPC_CHANNELS.getTitleFontData, (_event, input: unknown) => readTitleFontData(input)); registerCaptureIpcHandlers({ ipcMain, @@ -388,17 +424,24 @@ async function installIpcHandlers(): Promise { return executeRegisteredEditorTool(mcpServerInstance, toolName, params); }); - const agentChatTools = await createAgentChatTools(mcpServerInstance); + const agentChatTools = await createAgentChatTools(mcpServerInstance, cuaAgent); const agentChatGraphBundle = buildAgentChatGraph({ tools: agentChatTools, // Derived from the tools that exist, so a tool added tomorrow asks for // approval by default rather than because someone remembered a list. mutatingToolNames: agentChatMutatingToolNames(agentChatTools), spendToolNames: AGENT_CHAT_SPEND_TOOL_NAMES, + perCallApprovalToolNames: AGENT_CHAT_CUA_PER_CALL_TOOL_NAMES, + cua: cuaAgent, createModel: createAgentChatModel(agentChatTools, credentialStore, chatGptOAuthService) }); - const agentChatSessions = new AgentChatSessionManager(agentChatGraphBundle); - registerAgentChatIpcHandlers(ipcMain, agentChatSessions, new AgentChatHistoryStore(projectStore)); + const agentChatSessions = new AgentChatSessionManager(agentChatGraphBundle, { cancelCua: id => cuaAgent.cancelConversation(id) }); + activeAgentChatSessions = agentChatSessions; + registerAgentChatIpcHandlers(ipcMain, agentChatSessions, new AgentChatHistoryStore(projectStore), { + cancelChannel: IPC_CHANNELS.agentChatCancel, + isTrustedSender: event => cuaTarget !== null && !cuaTarget.window.isDestroyed() + && event.sender === cuaTarget.window.webContents && event.senderFrame === cuaTarget.window.webContents.mainFrame + }); } app.setName(APP_NAME); @@ -455,6 +498,7 @@ let shortsShutdownComplete = false; app.on('before-quit', event => { if (shortsShutdownComplete) return; event.preventDefault(); + void cuaTarget?.driver.cancel('app-quit'); exportIpcService.cancelAll(); void shortsService.shutdown().finally(() => { shortsShutdownComplete = true; diff --git a/src/preload/index.ts b/src/preload/index.ts index a24b5efb..dae621f1 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -3,6 +3,7 @@ import type { CuaCancelAck, CuaState, CuaStopResult, CuaSurfaceSnapshot } from ' import type { AgentChatApprovalInput, + AgentChatCancelInput, AgentChatCompactInput, AgentChatHistoryEntry, AgentChatHistoryGetInput, @@ -132,6 +133,7 @@ export interface VideoToolApi { mcpGetTools(): Promise>; mcpExecuteTool(toolName: string, params: unknown): Promise>; agentChatSend(input: AgentChatSendInput): Promise>; + agentChatCancel(input: AgentChatCancelInput): Promise>; agentChatApprove(input: AgentChatApprovalInput): Promise>; agentChatReset(input: AgentChatResetInput): Promise>; agentChatCompact(input: AgentChatCompactInput): Promise>; @@ -261,6 +263,7 @@ const videoTool: VideoToolApi = { mcpExecuteTool: (toolName: string, params: unknown) => ipcRenderer.invoke(IPC_CHANNELS.mcpExecuteTool, toolName, params) as Promise>, agentChatSend: (input) => ipcRenderer.invoke(IPC_CHANNELS.agentChatSend, input) as Promise>, + agentChatCancel: input => ipcRenderer.invoke(IPC_CHANNELS.agentChatCancel, input) as Promise>, agentChatApprove: (input) => ipcRenderer.invoke(IPC_CHANNELS.agentChatApprove, input) as Promise>, agentChatReset: (input) => ipcRenderer.invoke(IPC_CHANNELS.agentChatReset, input) as Promise>, diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index fd128829..6eecb2bb 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -60,6 +60,7 @@ export const IPC_CHANNELS = { mcpGetTools: 'mcp:get-tools', mcpExecuteTool: 'mcp:execute-tool', agentChatSend: 'agent-chat:send', + agentChatCancel: 'agent-chat:cancel', agentChatApprove: 'agent-chat:approve', agentChatReset: 'agent-chat:reset', agentChatHistoryList: 'agent-chat:history-list', diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts index 07f89cea..90bd75af 100644 --- a/tests/cuaDriver.test.ts +++ b/tests/cuaDriver.test.ts @@ -8,7 +8,9 @@ function fixture() { const contents = Object.assign(new EventEmitter(), { isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: () => 1, executeJavaScript: vi.fn(async () => true), - capturePage: vi.fn(async () => ({ getSize: () => ({ width: 800, height: 600 }), isEmpty: () => false, toDataURL: () => 'data:image/png;base64,test' })), + capturePage: vi.fn(async () => ({ isEmpty: () => false, toPNG: () => { + const png = Buffer.alloc(24); Buffer.from('89504e470d0a1a0a', 'hex').copy(png); png.writeUInt32BE(800,16); png.writeUInt32BE(600,20); return png; + } })), sendInputEvent: vi.fn((input: MouseInputEvent) => contents.emit(input.type.startsWith('mouse') ? 'before-mouse-event' : 'before-input-event', {}, input)) }); const window = Object.assign(new EventEmitter(), { id: 7, webContents: contents, isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true) }); From 58a25f499cdc85233b66a170c133c7043ad55323 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:10:22 +0900 Subject: [PATCH 11/96] fix(agent): enforce CUA per-call policy and rollback settlement locks --- src/main/agentChatGraph.ts | 15 +++++++++----- src/main/agentChatIpcHandlers.ts | 3 +++ src/main/cuaAgentOrchestration.ts | 3 +++ tests/agentChatIpcHandlers.test.ts | 23 +++++++++++++++++++++ tests/cuaAgentRunBinding.test.ts | 33 ++++++++++++++++++++++++++++++ 5 files changed, 72 insertions(+), 5 deletions(-) diff --git a/src/main/agentChatGraph.ts b/src/main/agentChatGraph.ts index db741230..03b8c2eb 100644 --- a/src/main/agentChatGraph.ts +++ b/src/main/agentChatGraph.ts @@ -213,6 +213,10 @@ export interface BuildAgentChatGraphOptions { export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { const toolsByName = new Map(options.tools.map((tool) => [tool.name, tool])); + const perCallApprovalToolNames = new Set([ + ...options.perCallApprovalToolNames ?? [], + ...options.cua ? ['executeCuaAction'] : [] + ]); const builder = new StateGraph(AgentChatState) .addNode('agent', async (state, config) => { @@ -230,7 +234,8 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { const hasSystemPrompt = state.messages.length > 0 && isSystemMessage(state.messages[0]!); const messages = hasSystemPrompt ? state.messages - : [new SystemMessage(buildAgentSystemPrompt(getEditAssetContext(configurable.editAssetContext), getEditProjectContext(configurable.editProjectContext))), ...state.messages]; + : [new SystemMessage(buildAgentSystemPrompt(getEditAssetContext(configurable.editAssetContext), getEditProjectContext(configurable.editProjectContext)) + + (options.cua ? ' For self-window UI actions, first observeEditorWindow and use the exact returned session/run/window/frame/layout scope and CSS coordinates. Propose only one executeCuaAction at a time; each exact action needs a new approval. Never use UI actions to approve tools, change settings, or access other windows. After execution inspect the returned frame and getProjectTimeline to verify the saved result. If evidence is stale, cancelled or denied, stop or explicitly observe again and request a new approval; never silently rebind approved coordinates. Prefer registered editing tools when they express the requested edit.' : '')), ...state.messages]; const response = await model.invoke(messages, config.signal ? { signal: config.signal } : undefined); if ((response.tool_calls?.length ?? 0) > 16) throw new Error('CUA_BUDGET_EXCEEDED: At most 16 tool calls per model step.'); @@ -248,13 +253,13 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { } for (const call of last.tool_calls) { if (!call.id || (!options.mutatingToolNames.has(call.name) - && !options.perCallApprovalToolNames?.has(call.name)) || state.toolDecisions[call.id]) { + && !perCallApprovalToolNames.has(call.name)) || state.toolDecisions[call.id]) { continue; } // A spend tool re-asks even after "always": that answer was given about // one charge, and cannot stand in for consent to every later one. const spends = (options.spendToolNames?.has(call.name) ?? false) - || (options.perCallApprovalToolNames?.has(call.name) ?? false); + || perCallApprovalToolNames.has(call.name); if (!spends && state.alwaysAllowedTools.includes(call.name)) { decisions[call.id] = 'approve'; continue; @@ -279,7 +284,7 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { // Recording a spend tool here would make the next charge silent even // though this pass correctly stopped to ask about this one. .filter((name) => !(options.spendToolNames?.has(name) ?? false) - && !(options.perCallApprovalToolNames?.has(name) ?? false)); + && !perCallApprovalToolNames.has(name)); return { toolDecisions: decisions, alwaysAllowedTools }; }) .addNode('executeTools', async (state, config) => { @@ -295,7 +300,7 @@ export function buildAgentChatGraph(options: BuildAgentChatGraphOptions) { const model = typeof modelId === 'string' ? getLlmModel(modelId) : undefined; for (const call of last.tool_calls) { if (!call.id) continue; - const perCall = options.perCallApprovalToolNames?.has(call.name) ?? false; + const perCall = perCallApprovalToolNames.has(call.name); if (perCall && (state.executedPerCallIds.includes(call.id) || executedPerCallIds.includes(call.id))) { results.push(new ToolMessage({ content: 'CUA_ACTION_REPLAYED: This action call has already settled. Observe again and propose a new action.', tool_call_id: call.id, name: call.name })); continue; diff --git a/src/main/agentChatIpcHandlers.ts b/src/main/agentChatIpcHandlers.ts index 59809fd2..ab2919c8 100644 --- a/src/main/agentChatIpcHandlers.ts +++ b/src/main/agentChatIpcHandlers.ts @@ -64,6 +64,7 @@ export function registerAgentChatIpcHandlers( }); ipcMain.handle(IPC_CHANNELS.agentChatCompact, async (_event, request) => { + if (options.isTrustedSender && !options.isTrustedSender(_event)) return fail('INVALID_INPUT', 'Untrusted agent chat sender'); try { const turn = await sessions.compactConversation(request); await recordTurn(turn); @@ -74,6 +75,7 @@ export function registerAgentChatIpcHandlers( }); ipcMain.handle(IPC_CHANNELS.agentChatReset, async (_event, request) => { + if (options.isTrustedSender && !options.isTrustedSender(_event)) return fail('INVALID_INPUT', 'Untrusted agent chat sender'); try { return ok(await sessions.resetConversation(request)); } catch (err) { @@ -91,6 +93,7 @@ export function registerAgentChatIpcHandlers( }); ipcMain.handle(IPC_CHANNELS.agentChatHistoryDelete, async (_event, request) => { + if (options.isTrustedSender && !options.isTrustedSender(_event)) return fail('INVALID_INPUT', 'Untrusted agent chat sender'); if (history === null) return ok(false); const input = request as Partial | undefined; if (typeof input?.projectId !== 'string' || typeof input.conversationId !== 'string') { diff --git a/src/main/cuaAgentOrchestration.ts b/src/main/cuaAgentOrchestration.ts index bd28d91f..e485e3c5 100644 --- a/src/main/cuaAgentOrchestration.ts +++ b/src/main/cuaAgentOrchestration.ts @@ -130,6 +130,8 @@ export class CuaApprovalAuthority { this.permits.clear(); } + assertRunAllowed(runId: string): void { this.checkRun(runId); } + private checkRun(runId: string): void { if (this.cleanupFailed) throw new CuaApprovalError('CUA_CLEANUP_FAILED'); if (this.revokedRuns.has(runId)) throw new CuaApprovalError('CUA_CANCELLED'); @@ -176,6 +178,7 @@ export class CuaAgentOrchestrator { this.runs.set(run.runId, run); } if (run.pending) throw new CuaApprovalError('CUA_BUSY'); + this.authority.assertRunAllowed(run.runId); if (run.observation) throw new CuaApprovalError('CUA_BUSY'); run.observation = this.options.driver.observe({ sessionId: this.sessionId, runId: run.runId }); let frame: CuaFrame; diff --git a/tests/agentChatIpcHandlers.test.ts b/tests/agentChatIpcHandlers.test.ts index 4af55923..7464bcfb 100644 --- a/tests/agentChatIpcHandlers.test.ts +++ b/tests/agentChatIpcHandlers.test.ts @@ -20,6 +20,29 @@ function createFakeIpcMain(): { ipcMain: IpcMain; handlers: Map { + it('checks trusted ownership before cancel or approval and awaits cancellation settlement', async () => { + const { ipcMain, handlers } = createFakeIpcMain(); + let release!: () => void; + const released = new Promise((resolve) => { release = resolve; }); + const cancelConversation = vi.fn(async () => { await released; return RESET_STATE; }); + const respondToApproval = vi.fn(); + const sessions = { cancelConversation, respondToApproval } as unknown as AgentChatSessionManager; + const trusted = {}; + registerAgentChatIpcHandlers(ipcMain, sessions, null, { cancelChannel: 'test:cancel', isTrustedSender: (event) => event === trusted }); + const cancel = handlers.get('test:cancel')!; + expect(await cancel({}, { conversationId: 'c1' })).toMatchObject({ ok: false }); + expect(await cancel(trusted, { conversationId: '' })).toMatchObject({ ok: false }); + expect(await handlers.get(IPC_CHANNELS.agentChatApprove)!({}, {})).toMatchObject({ ok: false }); + expect(respondToApproval).not.toHaveBeenCalled(); + expect(cancelConversation).not.toHaveBeenCalled(); + let settled = false; + const result = Promise.resolve(cancel(trusted, { conversationId: 'c1' })).then((response) => { settled = true; return response; }); + await Promise.resolve(); + expect(settled).toBe(false); + release(); + expect(await result).toEqual({ ok: true, value: RESET_STATE }); + }); + it('resolves the resetConversation promise before wrapping it in ok() for the reset channel', async () => { const { ipcMain, handlers } = createFakeIpcMain(); const sessions = { diff --git a/tests/cuaAgentRunBinding.test.ts b/tests/cuaAgentRunBinding.test.ts index cee64f21..01e912f5 100644 --- a/tests/cuaAgentRunBinding.test.ts +++ b/tests/cuaAgentRunBinding.test.ts @@ -139,4 +139,37 @@ describe('CUA immutable run binding and dispatch', () => { await expect(f.orchestrator.executeApproved('a', 'one', request)).rejects.toThrow('CUA_APPROVAL_MISMATCH'); expect(f.inputs()).toBe(0); }); + + it('awaits the entire rollback/physical-release promise before cancellation completes', async () => { + const f = fixture(); + await f.orchestrator.observe('a'); + let release!: () => void; + let held = 1; + let settled = false; + const released = new Promise((resolve) => { release = resolve; }); + f.driver.cancel = async () => { + await released; + held = 0; + return { ...f.driver.getState(), phase: 'stopped', cleanupComplete: true }; + }; + const stop = f.orchestrator.cancelConversation('a'); + void stop.then(() => { settled = true; }); + expect(f.orchestrator.cancelConversation('a')).toBe(stop); + await Promise.resolve(); + expect(settled).toBe(false); + expect(held).toBe(1); + release(); + await stop; + expect(held).toBe(0); + expect(settled).toBe(true); + }); + + it('latches failed rollback even when physical held input is zero', async () => { + const f = fixture(); + await f.orchestrator.observe('a'); + f.driver.cancel = async () => ({ ...f.driver.getState(), phase: 'cleanup-failed', cleanupComplete: false, + releaseFailures: ['renderer-rollback-unconfirmed'] }); + await expect(f.orchestrator.cancelConversation('a')).rejects.toThrow('CUA_CLEANUP_FAILED'); + await expect(f.orchestrator.observe('b')).rejects.toThrow('CUA_CLEANUP_FAILED'); + }); }); From 7bde903bb97b1047910a430e37bdcba324698b67 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:11:12 +0900 Subject: [PATCH 12/96] fix(cua): scale CSS input by measured Electron zoom --- docs/cua-driver-validation.md | 2 ++ scripts/probe-cua-input.cjs | 4 +++- src/main/cuaDriver.ts | 33 +++++++++++++++++++++++--------- src/main/index.ts | 3 +-- tests/cuaDriver.test.ts | 36 ++++++++++++++++++++++++++++++++--- 5 files changed, 63 insertions(+), 15 deletions(-) diff --git a/docs/cua-driver-validation.md b/docs/cua-driver-validation.md index b7835a1e..8b8e9ee8 100644 --- a/docs/cua-driver-validation.md +++ b/docs/cua-driver-validation.md @@ -14,6 +14,8 @@ The Pointer Capture variant receives pointerdown, every pointermove, pointerup a Both initial probes reported window/content focus false even after win.focus. Actual input partially delivered regardless, so the production driver explicitly refuses unfocused input instead of relying on delivery behavior. Driver code never automatically focuses the window. +The zoom-2 probe records a CSS viewport of 350×184, PNG bitmap 700×368 and devicePixelRatio 2. Electron input (40,30) arrives at DOM CSS (20,15): input uses window DIP and must multiply CSS coordinates by zoomFactor. PNG dimensions and device display scale are measured separately; DPR alone cannot supply both conversions. `/tmp/openscene-cua-zoom-probe/input.json` and `capture.png` retain the evidence. + Raw initial evidence: `/tmp/openscene-cua-probe/input.json`, `/tmp/openscene-cua-probe/capture.png`, `/tmp/openscene-cua-pointer-probe/input.json`, `/tmp/openscene-cua-pointer-probe/capture.png`. These are local experimental artifacts, not the required full application evidence. ## Remaining integration evidence diff --git a/scripts/probe-cua-input.cjs b/scripts/probe-cua-input.cjs index e87e9128..8457259e 100644 --- a/scripts/probe-cua-input.cjs +++ b/scripts/probe-cua-input.cjs @@ -10,6 +10,7 @@ app.whenReady().then(async () => { win.webContents.on('before-mouse-event', (_, input) => before.push({ event: 'mouse', injecting, ...input })); await win.loadURL('data:text/html,' + encodeURIComponent(`
clip
lane
`)); if (process.env.CUA_PROBE_POINTER === '1') await win.webContents.executeJavaScript(`document.getElementById('clip').draggable=false;document.getElementById('clip').onpointerdown=e=>{e.currentTarget.setPointerCapture(e.pointerId);};void 0;`); + if (process.env.CUA_PROBE_ZOOM) win.webContents.setZoomFactor(Number(process.env.CUA_PROBE_ZOOM)); win.focus(); await delay(300); const focused = { window: win.isFocused(), contents: win.webContents.isFocused() }; @@ -23,7 +24,8 @@ app.whenReady().then(async () => { const events = await win.webContents.executeJavaScript('window.events'); const out = process.env.CUA_PROBE_DIR || '/tmp/openscene-cua-probe'; fs.mkdirSync(out,{recursive:true}); - fs.writeFileSync(path.join(out,'input.json'),JSON.stringify({focused,before,events},null,2)); + const viewport = await win.webContents.executeJavaScript('({width:innerWidth,height:innerHeight,dpr:devicePixelRatio})'); + fs.writeFileSync(path.join(out,'input.json'),JSON.stringify({focused,viewport,zoom:win.webContents.getZoomFactor(),before,events},null,2)); fs.writeFileSync(path.join(out,'capture.png'),(await win.webContents.capturePage()).toPNG()); console.log(JSON.stringify({out,focused,beforeTypes:before.map(e=>e.type),domTypes:events.map(e=>e.type)})); win.destroy();app.exit(0); diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 45d9bdbd..f776908a 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -31,6 +31,7 @@ export class CuaDriver { private executionBlocked = true; private generation = 0; private heldMouse: CuaPoint | null = null; + private heldZoom: number | null = null; private heldKey: KeyboardInputEvent | null = null; private cancellation: Promise | null = null; private injecting = false; @@ -43,6 +44,7 @@ export class CuaDriver { this.state = { cancelToken: null, targetGone: false, sessionId: null, runId: null, windowId: window.id, phase: 'idle', cursor: null, dragStart: null, target: null, label: null, error: null, cleanupComplete: true, releaseFailures: [] }; window.on('blur', () => { void this.cancel('blur'); }); window.on('resize', () => { void this.cancel('resize'); }); + window.on('move', () => { void this.cancel('window-moved'); }); window.on('closed', () => { void this.cancel('closed'); }); window.webContents.on('did-start-navigation', () => { void this.cancel('navigation'); }); window.webContents.on('render-process-gone', () => { void this.cancel('renderer-gone'); }); @@ -61,7 +63,8 @@ export class CuaDriver { // clears main execution blocking nor issues approval authority. if (this.state.phase === 'ready' && this.executionBlocked && pending && frame && this.trustedApprovalPanel && pending.sessionId === frame.sessionId && pending.runId === frame.runId && pending.windowId === this.window.id - && pending.frameId === frame.frameId && pending.layoutRevision === frame.layoutRevision && inside(input, this.trustedApprovalPanel)) return; + && pending.frameId === frame.frameId && pending.layoutRevision === frame.layoutRevision + && inside({ x: input.x / frame.zoomFactor, y: input.y / frame.zoomFactor }, this.trustedApprovalPanel)) return; void this.cancel('user-input'); }); } @@ -80,6 +83,12 @@ export class CuaDriver { if (this.window.isDestroyed() || this.window.webContents.isDestroyed()) throw new Error('CUA_TARGET_GONE'); if (!this.window.isFocused() || !this.window.webContents.isFocused()) throw new Error('CUA_NOT_FOCUSED'); } + private protectedGeometry(snapshot: CuaSurfaceSnapshot): string { + const panel = this.trustedApprovalPanel; + return JSON.stringify(snapshot.protectedRects.filter(p => !(panel && p.kind === 'approval-ui' + && p.rect.x >= panel.x && p.rect.y >= panel.y + && p.rect.x + p.rect.width <= panel.x + panel.width && p.rect.y + p.rect.height <= panel.y + panel.height))); + } reportSurface(snapshot: CuaSurfaceSnapshot): void { // Runtime validation is mandatory: the bridge does not make renderer data trusted. if (!snapshot || !Number.isSafeInteger(snapshot.layoutRevision) || snapshot.layoutRevision < 0 @@ -92,7 +101,7 @@ export class CuaDriver { const changed = this.surface !== null && (snapshot.layoutRevision !== this.surface.layoutRevision || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport) || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) - || JSON.stringify(snapshot.protectedRects) !== JSON.stringify(this.surface.protectedRects)); + || this.protectedGeometry(snapshot) !== this.protectedGeometry(this.surface)); this.surface = structuredClone(snapshot); if (changed) { this.frame = null; if (this.state.phase === 'acting') void this.cancel('surface-changed'); } } @@ -119,7 +128,7 @@ export class CuaDriver { this.live(); if (revision !== this.generation || !this.surface || snapshot.layoutRevision !== this.surface.layoutRevision || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) - || JSON.stringify(snapshot.protectedRects) !== JSON.stringify(this.surface.protectedRects) + || this.protectedGeometry(snapshot) !== this.protectedGeometry(this.surface) || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport)) throw new Error('CUA_STALE_FRAME'); const png = image.toPNG(); if (image.isEmpty() || png.length < 24 || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw new Error('CUA_EMPTY_CAPTURE'); @@ -134,7 +143,8 @@ export class CuaDriver { this.live(); if (this.state.phase !== 'ready') throw new Error('CUA_BUSY'); const f = this.frame, s = this.surface; - if (!f || !s || request.sessionId !== f.sessionId || request.runId !== f.runId || request.windowId !== this.window.id || request.frameId !== f.frameId || request.layoutRevision !== f.layoutRevision || s.layoutRevision !== f.layoutRevision || performance.now() - this.frameTime > 120000 || this.window.webContents.getZoomFactor() !== f.zoomFactor) throw new Error('CUA_STALE_FRAME'); + if (!f || !s || request.sessionId !== f.sessionId || request.runId !== f.runId || request.windowId !== this.window.id || request.frameId !== f.frameId || request.layoutRevision !== f.layoutRevision || s.layoutRevision !== f.layoutRevision || performance.now() - this.frameTime > 120000 || this.window.webContents.getZoomFactor() !== f.zoomFactor + || (this.dependencies.getDeviceScaleFactor?.() ?? 1) !== f.deviceScaleFactor) throw new Error('CUA_STALE_FRAME'); if (this.executionBlocked || s.executionBlocked || !s.safeSurface?.interactive) throw new Error('CUA_EXECUTION_BLOCKED'); const action = request.action; if (!action || !['click', 'drag', 'key'].includes(action.kind)) throw new Error('CUA_INVALID_ACTION'); @@ -146,12 +156,16 @@ export class CuaDriver { } if (action.kind === 'drag' && (!Number.isFinite(action.durationMs) || action.durationMs < 100 || action.durationMs > 3000)) throw new Error('CUA_INVALID_ACTION'); if (action.kind === 'drag' && s.protectedRects.some(r => crosses(action.from, action.to, r.rect))) throw new Error('CUA_OUT_OF_BOUNDS_OR_PROTECTED'); - const points = action.kind === 'click' ? [action.point] : Array.from({ length: 61 }, (_, i) => ({ x: action.from.x + (action.to.x - action.from.x) * i / 60, y: action.from.y + (action.to.y - action.from.y) * i / 60 })); + const rawPoints = action.kind === 'click' ? [action.point] : Array.from({ length: 61 }, (_, i) => ({ x: action.from.x + (action.to.x - action.from.x) * i / 60, y: action.from.y + (action.to.y - action.from.y) * i / 60 })); + // Validate the effective CSS point after Electron's integer DIP rounding. + const points = rawPoints.map(p => ({ x: Math.round(p.x * f.zoomFactor) / f.zoomFactor, y: Math.round(p.y * f.zoomFactor) / f.zoomFactor })); + if (action.kind === 'drag' && s.protectedRects.some(r => crosses(points[0]!, points.at(-1)!, r.rect))) throw new Error('CUA_OUT_OF_BOUNDS_OR_PROTECTED'); for (const p of points) if (!p || !inside(p, { x: 0, y: 0, ...s.viewport }) || !inside(p, s.safeSurface.rect) || s.protectedRects.some(r => inside(p, r.rect))) throw new Error('CUA_OUT_OF_BOUNDS_OR_PROTECTED'); return points; } private mouse(type: MouseInputEvent['type'], point: CuaPoint): void { - this.input({ type, x: Math.round(point.x), y: Math.round(point.y), button: 'left', clickCount: 1, modifiers: this.heldMouse ? ['leftbuttondown'] : [] }); + const zoom = this.heldZoom ?? this.window.webContents.getZoomFactor(); + this.input({ type, x: Math.round(point.x * zoom), y: Math.round(point.y * zoom), button: 'left', clickCount: 1, modifiers: this.heldMouse ? ['leftbuttondown'] : [] }); } private input(event: MouseInputEvent | KeyboardInputEvent): void { this.injecting = true; @@ -172,7 +186,7 @@ export class CuaDriver { const safe = [...document.querySelectorAll('[data-cua-safe-surface]')].find(e => e.getAttribute('data-cua-safe-surface') === expected.safe.kind && e.getBoundingClientRect().width > 0); if (!safe || safe.closest('[inert],[hidden],[aria-hidden="true"]')) return false; const r = safe.getBoundingClientRect(), want = expected.safe.rect; - if (!['x','y','width','height'].every(k => close(r[k],want[k]))) return false; + if (want.x < r.x-0.5 || want.y < r.y-0.5 || want.x+want.width > r.right+0.5 || want.y+want.height > r.bottom+0.5) return false; const forbidden = '[data-cua-protected],[role="dialog"],[role="menu"],.oc-editor-host__header'; if (expected.key && (!document.activeElement || !safe.contains(document.activeElement) || document.activeElement.closest(forbidden))) return false; return expected.points.every(p => { const e = document.elementFromPoint(p.x,p.y); return e && safe.contains(e) && !e.closest(forbidden); }); @@ -196,12 +210,13 @@ export class CuaDriver { this.input(this.heldKey); } else { const first = points[0]!; - this.mouse('mouseMove', first); this.heldMouse = first; this.mouse('mouseDown', first); + this.mouse('mouseMove', first); this.heldMouse = first; this.heldZoom = this.window.webContents.getZoomFactor(); this.mouse('mouseDown', first); this.publish({ cursor: first, dragStart: request.action.kind === 'drag' ? first : null, target: points.at(-1)! }); if (request.action.kind === 'drag') for (const p of points.slice(1)) { await new Promise(resolve => setTimeout(resolve, request.action.kind === 'drag' ? request.action.durationMs / 60 : 0)); if (generation !== this.generation || signal?.aborted) throw new Error('CUA_CANCELLED'); this.live(); + if (this.window.webContents.getZoomFactor() !== this.heldZoom) throw new Error('CUA_STALE_FRAME'); this.heldMouse = p; this.mouse('mouseMove', p); this.publish({ cursor: p }); } } @@ -217,7 +232,7 @@ export class CuaDriver { } private release(): string[] { const failures: string[] = []; - if (this.heldMouse) { try { this.mouse('mouseUp', this.heldMouse); this.heldMouse = null; } catch { failures.push('left'); } } + if (this.heldMouse) { try { this.mouse('mouseUp', this.heldMouse); this.heldMouse = null; this.heldZoom = null; } catch { failures.push('left'); } } if (this.heldKey) { const key = this.heldKey; try { this.input({ ...key, type: 'keyUp' }); this.heldKey = null; } catch { failures.push(key.keyCode); } } return failures; } diff --git a/src/main/index.ts b/src/main/index.ts index e7f69875..32be324c 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -498,9 +498,8 @@ let shortsShutdownComplete = false; app.on('before-quit', event => { if (shortsShutdownComplete) return; event.preventDefault(); - void cuaTarget?.driver.cancel('app-quit'); exportIpcService.cancelAll(); - void shortsService.shutdown().finally(() => { + void Promise.allSettled([cuaTarget?.driver.cancel('app-quit'), shortsService.shutdown()]).finally(() => { shortsShutdownComplete = true; app.quit(); }); diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts index 90bd75af..58f4ae6f 100644 --- a/tests/cuaDriver.test.ts +++ b/tests/cuaDriver.test.ts @@ -4,9 +4,9 @@ import { describe, expect, it, vi } from 'vitest'; import { CuaDriver } from '../src/main/cuaDriver'; import { cuaBitmapPointToViewport, type CuaActionRequest, type CuaSurfaceSnapshot } from '../src/shared/cua'; -function fixture() { +function fixture(autoAck = true) { const contents = Object.assign(new EventEmitter(), { - isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: () => 1, + isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: vi.fn(() => 1), executeJavaScript: vi.fn(async () => true), capturePage: vi.fn(async () => ({ isEmpty: () => false, toPNG: () => { const png = Buffer.alloc(24); Buffer.from('89504e470d0a1a0a', 'hex').copy(png); png.writeUInt32BE(800,16); png.writeUInt32BE(600,20); return png; @@ -16,7 +16,7 @@ function fixture() { const window = Object.assign(new EventEmitter(), { id: 7, webContents: contents, isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true) }); const consumePermit = vi.fn(); const onCancel = vi.fn(); const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel, onState: state => { - if (state.phase === 'stopping' && state.cancelToken && state.runId) driver.acknowledgeCancel({ runId: state.runId, cancelToken: state.cancelToken }); + if (autoAck && state.phase === 'stopping' && state.cancelToken && state.runId) driver.acknowledgeCancel({ runId: state.runId, cancelToken: state.cancelToken }); } }); const surface: CuaSurfaceSnapshot = { executionBlocked: false, blockReason: null, layoutRevision: 1, viewport: { width: 800, height: 600 }, safeSurface: { kind: 'timeline', rect: { x: 0, y: 0, width: 800, height: 600 }, interactive: true }, protectedRects: [], focusedInSafeSurface: true, focusedTestId: null }; driver.reportSurface(surface); driver.setExecutionBlocked(false); @@ -102,4 +102,34 @@ describe('self-window CUA safety', () => { await expect(f.observe()).rejects.toThrow('NOT_FOCUSED'); expect(f.consumePermit).not.toHaveBeenCalled(); }); + it('times out missing rollback acknowledgement, still releases and locks recovery', async () => { + const f = fixture(false), r = await f.observe(); + const execution = f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 3000 } }, 'p'); + await Promise.resolve(); await Promise.resolve(); + const rejected = expect(execution).rejects.toThrow('CANCELLED'); + const stop = f.driver.cancel('user-stop'); + const pending = f.driver.getState(); + expect(pending.phase).toBe('stopping'); + expect(f.driver.acknowledgeCancel({ runId: 'wrong', cancelToken: pending.cancelToken! })).toBe(false); + const stopped = await stop; + expect(stopped.cleanupComplete).toBe(false); + expect(stopped.releaseFailures).toContain('renderer-rollback-unconfirmed'); + expect(f.contents.sendInputEvent.mock.calls.at(-1)?.[0].type).toBe('mouseUp'); + expect(f.driver.acknowledgeCancel({ runId: 'r', cancelToken: pending.cancelToken! })).toBe(false); + await rejected; + await expect(f.observe()).rejects.toThrow('BUSY'); + }); + it('rejects independently unsafe DOM without consuming a permit', async () => { + const f = fixture(), r = await f.observe(); + f.contents.executeJavaScript.mockResolvedValue(false); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('UNSAFE_DOCUMENT'); + expect(f.consumePermit).not.toHaveBeenCalled(); + expect(f.contents.sendInputEvent).not.toHaveBeenCalled(); + }); + it('converts CSS points to Electron DIP input with zoom, independently of bitmap scale', async () => { + const f = fixture(); f.contents.getZoomFactor.mockReturnValue(2); + const r = await f.observe(); + await f.driver.execute(r, 'p'); + expect(f.contents.sendInputEvent.mock.calls[0]?.[0]).toMatchObject({ type: 'mouseMove', x: 40, y: 40 }); + }); }); From bbf88354b66379e01cac27cb3a715db9f10a9d08 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:13:06 +0900 Subject: [PATCH 13/96] fix(cua): refuse iframe and webview input targets --- src/main/cuaDriver.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index f776908a..55775dce 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -187,7 +187,7 @@ export class CuaDriver { if (!safe || safe.closest('[inert],[hidden],[aria-hidden="true"]')) return false; const r = safe.getBoundingClientRect(), want = expected.safe.rect; if (want.x < r.x-0.5 || want.y < r.y-0.5 || want.x+want.width > r.right+0.5 || want.y+want.height > r.bottom+0.5) return false; - const forbidden = '[data-cua-protected],[role="dialog"],[role="menu"],.oc-editor-host__header'; + const forbidden = 'iframe,webview,[data-cua-protected],[role="dialog"],[role="menu"],.oc-editor-host__header'; if (expected.key && (!document.activeElement || !safe.contains(document.activeElement) || document.activeElement.closest(forbidden))) return false; return expected.points.every(p => { const e = document.elementFromPoint(p.x,p.y); return e && safe.contains(e) && !e.closest(forbidden); }); })()`); From c03f32cc9fe83f002fe9eda55e1df3aa50ac3442 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:16:05 +0900 Subject: [PATCH 14/96] test(cua): verify pending panel exceptions and serialize capture --- src/main/cuaDriver.ts | 9 +++++++-- tests/cuaDriver.test.ts | 43 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 55775dce..82203e49 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -38,6 +38,7 @@ export class CuaDriver { private cleanupFailureLatched = false; private cancelAck: { token: string; runId: string; resolve: () => void } | null = null; private trustedApprovalPanel: CuaRect | null = null; + private observing = false; private state: CuaState; constructor(private readonly window: BrowserWindow, private readonly dependencies: CuaDriverDependencies) { @@ -107,8 +108,11 @@ export class CuaDriver { } async observe(context: { sessionId: string; runId: string }): Promise { this.live(); - if (this.state.phase === 'acting' || this.state.phase === 'stopping' || this.cleanupFailureLatched) throw new Error('CUA_BUSY'); + if (this.observing || this.state.phase === 'acting' || this.state.phase === 'stopping' || this.cleanupFailureLatched) throw new Error('CUA_BUSY'); if (!context.sessionId || !context.runId || !this.surface?.safeSurface?.interactive) throw new Error('CUA_UNSAFE_SURFACE'); + this.observing = true; + this.frame = null; + try { const snapshot = structuredClone(this.surface); const revision = this.generation; const panel: unknown = await this.window.webContents.executeJavaScript(`(() => { @@ -138,10 +142,11 @@ export class CuaDriver { this.frame = frame; this.frameTime = performance.now(); this.cancellation = null; this.publish({ ...context, phase: 'ready', error: null, cleanupComplete: true, releaseFailures: [] }); return frame; + } finally { this.observing = false; } } private validate(request: CuaActionRequest): CuaPoint[] { this.live(); - if (this.state.phase !== 'ready') throw new Error('CUA_BUSY'); + if (this.observing || this.state.phase !== 'ready') throw new Error('CUA_BUSY'); const f = this.frame, s = this.surface; if (!f || !s || request.sessionId !== f.sessionId || request.runId !== f.runId || request.windowId !== this.window.id || request.frameId !== f.frameId || request.layoutRevision !== f.layoutRevision || s.layoutRevision !== f.layoutRevision || performance.now() - this.frameTime > 120000 || this.window.webContents.getZoomFactor() !== f.zoomFactor || (this.dependencies.getDeviceScaleFactor?.() ?? 1) !== f.deviceScaleFactor) throw new Error('CUA_STALE_FRAME'); diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts index 58f4ae6f..f81bcdf6 100644 --- a/tests/cuaDriver.test.ts +++ b/tests/cuaDriver.test.ts @@ -1,13 +1,13 @@ import { EventEmitter } from 'node:events'; import type { BrowserWindow, MouseInputEvent } from 'electron'; import { describe, expect, it, vi } from 'vitest'; -import { CuaDriver } from '../src/main/cuaDriver'; +import { CuaDriver, type CuaDriverDependencies } from '../src/main/cuaDriver'; import { cuaBitmapPointToViewport, type CuaActionRequest, type CuaSurfaceSnapshot } from '../src/shared/cua'; function fixture(autoAck = true) { const contents = Object.assign(new EventEmitter(), { isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true), getZoomFactor: vi.fn(() => 1), - executeJavaScript: vi.fn(async () => true), + executeJavaScript: vi.fn<(script: string) => Promise>(async () => true), capturePage: vi.fn(async () => ({ isEmpty: () => false, toPNG: () => { const png = Buffer.alloc(24); Buffer.from('89504e470d0a1a0a', 'hex').copy(png); png.writeUInt32BE(800,16); png.writeUInt32BE(600,20); return png; } })), @@ -15,7 +15,8 @@ function fixture(autoAck = true) { }); const window = Object.assign(new EventEmitter(), { id: 7, webContents: contents, isDestroyed: vi.fn(() => false), isFocused: vi.fn(() => true) }); const consumePermit = vi.fn(); const onCancel = vi.fn(); - const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel, onState: state => { + const getPendingApproval = vi.fn>(() => null); + const driver = new CuaDriver(window as unknown as BrowserWindow, { consumePermit, onCancel, getPendingApproval, onState: state => { if (autoAck && state.phase === 'stopping' && state.cancelToken && state.runId) driver.acknowledgeCancel({ runId: state.runId, cancelToken: state.cancelToken }); } }); const surface: CuaSurfaceSnapshot = { executionBlocked: false, blockReason: null, layoutRevision: 1, viewport: { width: 800, height: 600 }, safeSurface: { kind: 'timeline', rect: { x: 0, y: 0, width: 800, height: 600 }, interactive: true }, protectedRects: [], focusedInSafeSurface: true, focusedTestId: null }; @@ -24,7 +25,7 @@ function fixture(autoAck = true) { const frame = await driver.observe({ sessionId: 's', runId: 'r' }); return { sessionId: 's', runId: 'r', windowId: 7, frameId: frame.frameId, layoutRevision: 1, action: { kind: 'click', point: { x: 20, y: 20 } } }; }; - return { driver, window, contents, consumePermit, onCancel, surface, observe }; + return { driver, window, contents, consumePermit, onCancel, getPendingApproval, surface, observe }; } describe('self-window CUA safety', () => { it('uses actual bitmap ratio and rejects invalid pixels', () => { @@ -132,4 +133,38 @@ describe('self-window CUA safety', () => { await f.driver.execute(r, 'p'); expect(f.contents.sendInputEvent.mock.calls[0]?.[0]).toMatchObject({ type: 'mouseMove', x: 40, y: 40 }); }); + it('allows only current-ledger pending panel pointer as a cancellation exception', async () => { + const f = fixture(), panel = { x: 600, y: 0, width: 200, height: 600 }; + f.contents.executeJavaScript.mockImplementation(async script => script.includes('const panels') ? panel : true); + const surface: CuaSurfaceSnapshot = { ...f.surface, safeSurface: { kind: 'timeline', rect: { x: 0, y: 0, width: 500, height: 600 }, interactive: true }, protectedRects: [{ id: 'panel', kind: 'agent-panel', rect: panel }] }; + f.driver.reportSurface(surface); + const request = await f.observe(); f.driver.setExecutionBlocked(true); + f.getPendingApproval.mockReturnValue(request); + f.driver.reportSurface({ ...surface, executionBlocked: true, protectedRects: [...surface.protectedRects, { id: 'approval', kind: 'approval-ui', rect: { x: 610, y: 20, width: 180, height: 100 } }] }); + f.contents.emit('before-mouse-event', {}, { type: 'mouseDown', x: 650, y: 40 }); + expect(f.driver.getState().phase).toBe('ready'); + expect(f.onCancel).not.toHaveBeenCalled(); + await expect(f.driver.execute(request, 'forged')).rejects.toThrow('BLOCKED'); + expect(f.consumePermit).not.toHaveBeenCalled(); + f.getPendingApproval.mockReturnValue({ ...request, runId: 'another-run' }); + f.contents.emit('before-mouse-event', {}, { type: 'mouseDown', x: 650, y: 40 }); + expect(f.onCancel).toHaveBeenCalledOnce(); + }); + it('rejects a fresh-looking snapshot when the document rejects its safety claims', async () => { + const f = fixture(), r = await f.observe(); + f.contents.executeJavaScript.mockResolvedValue({ safe: true }); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('UNSAFE_DOCUMENT'); + expect(f.contents.sendInputEvent).not.toHaveBeenCalled(); + }); + it('serializes capture and prevents an older frame being used during recapture', async () => { + const f = fixture(), r = await f.observe(); + let resolve!: (value: unknown) => void; + f.contents.executeJavaScript.mockImplementationOnce(() => new Promise(done => { resolve = done; })); + const capture = f.observe(); + await expect(f.observe()).rejects.toThrow('BUSY'); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('BUSY'); + resolve(null); await capture; + await expect(f.driver.execute(r, 'p')).rejects.toThrow('STALE'); + expect(f.consumePermit).not.toHaveBeenCalled(); + }); }); From 5e035f02d21e2028e52573e6ec56cef74a937b23 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:18:20 +0900 Subject: [PATCH 15/96] test(cua): record isolated initial-focus probe limitations --- docs/cua-driver-validation.md | 2 ++ scripts/probe-cua-input.cjs | 19 ++++++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/cua-driver-validation.md b/docs/cua-driver-validation.md index 8b8e9ee8..0ad99ecf 100644 --- a/docs/cua-driver-validation.md +++ b/docs/cua-driver-validation.md @@ -16,6 +16,8 @@ Both initial probes reported window/content focus false even after win.focus. Ac The zoom-2 probe records a CSS viewport of 350×184, PNG bitmap 700×368 and devicePixelRatio 2. Electron input (40,30) arrives at DOM CSS (20,15): input uses window DIP and must multiply CSS coordinates by zoomFactor. PNG dimensions and device display scale are measured separately; DPR alone cannot supply both conversions. `/tmp/openscene-cua-zoom-probe/input.json` and `capture.png` retain the evidence. +An explicitly authorized, initial-only test-entry selection (`CUA_PROBE_INITIAL_FOCUS=1`) called app.focus({ steal: true }), win.focus and webContents.focus with a separate temporary userData profile. On this host the resulting window ID 1, title `OpenScene CUA Input Probe`, still reported both focus flags false. `/tmp/openscene-cua-focused-isolated-probe/input.json` and `capture.png` retain this result, including all 29 injected mouse/key before-events observed synchronously inside sendInputEvent. No production focus guard was relaxed and the test never refocused mid-run. Orca's native provider reports `windows.focus: false`; its availability does not establish that this Electron window can become focused. + Raw initial evidence: `/tmp/openscene-cua-probe/input.json`, `/tmp/openscene-cua-probe/capture.png`, `/tmp/openscene-cua-pointer-probe/input.json`, `/tmp/openscene-cua-pointer-probe/capture.png`. These are local experimental artifacts, not the required full application evidence. ## Remaining integration evidence diff --git a/scripts/probe-cua-input.cjs b/scripts/probe-cua-input.cjs index 8457259e..87822c94 100644 --- a/scripts/probe-cua-input.cjs +++ b/scripts/probe-cua-input.cjs @@ -2,30 +2,39 @@ const { app, BrowserWindow } = require('electron'); const fs = require('node:fs'); const path = require('node:path'); +const os = require('node:os'); +const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'openscene-cua-input-profile-')); +app.setPath('userData', profile); const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); app.whenReady().then(async () => { - const win = new BrowserWindow({ width: 700, height: 400, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); + const win = new BrowserWindow({ title: 'OpenScene CUA Input Probe', width: 700, height: 400, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); const before = []; let injecting = false; win.webContents.on('before-input-event', (_, input) => before.push({ event: 'key', injecting, ...input })); win.webContents.on('before-mouse-event', (_, input) => before.push({ event: 'mouse', injecting, ...input })); await win.loadURL('data:text/html,' + encodeURIComponent(`
clip
lane
`)); if (process.env.CUA_PROBE_POINTER === '1') await win.webContents.executeJavaScript(`document.getElementById('clip').draggable=false;document.getElementById('clip').onpointerdown=e=>{e.currentTarget.setPointerCapture(e.pointerId);};void 0;`); if (process.env.CUA_PROBE_ZOOM) win.webContents.setZoomFactor(Number(process.env.CUA_PROBE_ZOOM)); - win.focus(); + if (process.env.CUA_PROBE_INITIAL_FOCUS === '1') { + // Explicit test-entry-only initial selection, never production refocusing. + app.focus({ steal: true }); win.focus(); win.webContents.focus(); + } await delay(300); const focused = { window: win.isFocused(), contents: win.webContents.isFocused() }; const send = (type,x,y,down=false) => {injecting=true;try{win.webContents.sendInputEvent({type,x,y,button:'left',clickCount:1,modifiers:down?['leftbuttondown']:[]});}finally{injecting=false;}}; send('mouseMove',40,30); send('mouseDown',40,30,true); for(let y=35;y<=150;y+=5){send('mouseMove',40,y,true);await delay(16);} send('mouseUp',40,150); - win.webContents.sendInputEvent({type:'keyDown',keyCode:'z',modifiers:['meta']}); - win.webContents.sendInputEvent({type:'keyUp',keyCode:'z',modifiers:['meta']}); + for (const type of ['keyDown', 'keyUp']) { + injecting=true; + try { win.webContents.sendInputEvent({type,keyCode:'z',modifiers:['meta']}); } + finally { injecting=false; } + } await delay(300); const events = await win.webContents.executeJavaScript('window.events'); const out = process.env.CUA_PROBE_DIR || '/tmp/openscene-cua-probe'; fs.mkdirSync(out,{recursive:true}); const viewport = await win.webContents.executeJavaScript('({width:innerWidth,height:innerHeight,dpr:devicePixelRatio})'); - fs.writeFileSync(path.join(out,'input.json'),JSON.stringify({focused,viewport,zoom:win.webContents.getZoomFactor(),before,events},null,2)); + fs.writeFileSync(path.join(out,'input.json'),JSON.stringify({profile,windowId:win.id,title:win.getTitle(),initialFocusRequested:process.env.CUA_PROBE_INITIAL_FOCUS==='1',focused,viewport,zoom:win.webContents.getZoomFactor(),before,events},null,2)); fs.writeFileSync(path.join(out,'capture.png'),(await win.webContents.capturePage()).toPNG()); console.log(JSON.stringify({out,focused,beforeTypes:before.map(e=>e.type),domTypes:events.map(e=>e.type)})); win.destroy();app.exit(0); From 2a7edd741993ab2f59cc15a137e546a1851fe3f2 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:19:40 +0900 Subject: [PATCH 16/96] fix(cua): revoke ready runs on invalid or changed safety reports --- src/main/cuaDriver.ts | 11 ++++++++--- tests/cuaDriver.test.ts | 17 ++++++++++++++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main/cuaDriver.ts b/src/main/cuaDriver.ts index 82203e49..a39565a9 100644 --- a/src/main/cuaDriver.ts +++ b/src/main/cuaDriver.ts @@ -90,21 +90,26 @@ export class CuaDriver { && p.rect.x >= panel.x && p.rect.y >= panel.y && p.rect.x + p.rect.width <= panel.x + panel.width && p.rect.y + p.rect.height <= panel.y + panel.height))); } + private invalidSurface(): never { + this.surface = null; this.frame = null; + if (['ready', 'acting'].includes(this.state.phase)) void this.cancel('invalid-surface'); + throw new Error('CUA_INVALID_SURFACE'); + } reportSurface(snapshot: CuaSurfaceSnapshot): void { // Runtime validation is mandatory: the bridge does not make renderer data trusted. if (!snapshot || !Number.isSafeInteger(snapshot.layoutRevision) || snapshot.layoutRevision < 0 || typeof snapshot.executionBlocked !== 'boolean' || typeof snapshot.focusedInSafeSurface !== 'boolean' || !snapshot.viewport || ![snapshot.viewport.width, snapshot.viewport.height].every(n => Number.isFinite(n) && n > 0 && n < 32768) - || !Array.isArray(snapshot.protectedRects) || snapshot.protectedRects.length > 256) throw new Error('CUA_INVALID_SURFACE'); + || !Array.isArray(snapshot.protectedRects) || snapshot.protectedRects.length > 256) this.invalidSurface(); const validRect = (r: CuaRect): boolean => !!r && [r.x, r.y, r.width, r.height].every(Number.isFinite) && r.width >= 0 && r.height >= 0; - if (snapshot.protectedRects.some(p => !p || !validRect(p.rect)) || (snapshot.safeSurface !== null && (!validRect(snapshot.safeSurface.rect) || typeof snapshot.safeSurface.interactive !== 'boolean'))) throw new Error('CUA_INVALID_SURFACE'); + if (snapshot.protectedRects.some(p => !p || !validRect(p.rect)) || (snapshot.safeSurface !== null && (!validRect(snapshot.safeSurface.rect) || typeof snapshot.safeSurface.interactive !== 'boolean'))) this.invalidSurface(); if (this.surface && snapshot.layoutRevision < this.surface.layoutRevision) throw new Error('CUA_STALE_SURFACE'); const changed = this.surface !== null && (snapshot.layoutRevision !== this.surface.layoutRevision || JSON.stringify(snapshot.viewport) !== JSON.stringify(this.surface.viewport) || JSON.stringify(snapshot.safeSurface) !== JSON.stringify(this.surface.safeSurface) || this.protectedGeometry(snapshot) !== this.protectedGeometry(this.surface)); this.surface = structuredClone(snapshot); - if (changed) { this.frame = null; if (this.state.phase === 'acting') void this.cancel('surface-changed'); } + if (changed) { this.frame = null; if (['ready', 'acting'].includes(this.state.phase)) void this.cancel('surface-changed'); } } async observe(context: { sessionId: string; runId: string }): Promise { this.live(); diff --git a/tests/cuaDriver.test.ts b/tests/cuaDriver.test.ts index f81bcdf6..eb77753b 100644 --- a/tests/cuaDriver.test.ts +++ b/tests/cuaDriver.test.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'node:events'; +import { performance } from 'node:perf_hooks'; import type { BrowserWindow, MouseInputEvent } from 'electron'; import { describe, expect, it, vi } from 'vitest'; import { CuaDriver, type CuaDriverDependencies } from '../src/main/cuaDriver'; @@ -56,7 +57,7 @@ describe('self-window CUA safety', () => { const r = await f.observe(); await expect(f.driver.execute({ ...r, action: { kind: 'drag', from: { x: 20, y: 20 }, to: { x: 200, y: 20 }, durationMs: 100 } }, 'p')).rejects.toThrow('PROTECTED'); f.driver.reportSurface({ ...f.surface, layoutRevision: 2 }); - await expect(f.driver.execute(r, 'p')).rejects.toThrow('STALE'); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('BUSY'); expect(f.consumePermit).not.toHaveBeenCalled(); }); it('releases a held drag on stop and sends no subsequent moves', async () => { @@ -167,4 +168,18 @@ describe('self-window CUA safety', () => { await expect(f.driver.execute(r, 'p')).rejects.toThrow('STALE'); expect(f.consumePermit).not.toHaveBeenCalled(); }); + it('expires a frame by monotonic absolute age without resetting or rebinding it', async () => { + const f = fixture(), r = await f.observe(); + vi.spyOn(performance, 'now').mockReturnValue(performance.now() + 120001); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('STALE_FRAME'); + expect(f.consumePermit).not.toHaveBeenCalled(); + expect(f.contents.sendInputEvent).not.toHaveBeenCalled(); + }); + it('fails closed on malformed safety reports and revokes the ready run immediately', async () => { + const f = fixture(), r = await f.observe(); + expect(() => f.driver.reportSurface({ ...f.surface, viewport: { width: NaN, height: 600 } })).toThrow('INVALID_SURFACE'); + expect(f.onCancel).toHaveBeenCalledOnce(); + await expect(f.driver.execute(r, 'p')).rejects.toThrow('BUSY'); + expect(f.contents.sendInputEvent).not.toHaveBeenCalled(); + }); }); From 03fc2b0d779052cd81a89ada240801a20c291553 Mon Sep 17 00:00:00 2001 From: sjungwon03 Date: Tue, 24 Nov 2026 10:14:28 +0900 Subject: [PATCH 17/96] feat(cua): implement virtual cursor overlay, surface snapshots, and pointer timeline drag --- src/renderer/src/AgentChatPanel.tsx | 16 +- src/renderer/src/App.tsx | 2 + src/renderer/src/AppShell.tsx | 26 +- src/renderer/src/ApplicationMenuBar.tsx | 2 +- src/renderer/src/FirstRunOnboarding.tsx | 11 +- src/renderer/src/ProjectSettingsDialog.tsx | 2 + src/renderer/src/ProviderConnectDialog.tsx | 2 + src/renderer/src/cua/CuaOverlay.tsx | 205 ++++++++ src/renderer/src/cua/cuaOverlay.css | 287 +++++++++++ src/renderer/src/cua/cuaSurfaceSnapshot.ts | 296 ++++++++++++ src/renderer/src/cua/useCuaOverlay.ts | 456 ++++++++++++++++++ src/renderer/src/editor/TimelineCanvas.tsx | 335 ++++++++++++- src/renderer/src/editor/TimelineEditor.tsx | 9 +- .../src/editor/timelinePointerDrag.ts | 141 ++++++ .../src/editor/useTimelineShortcuts.ts | 5 +- tests/cuaOverlay.test.ts | 165 +++++++ tests/cuaSurfaceSnapshot.test.ts | 236 +++++++++ tests/timelinePointerDrag.test.ts | 151 ++++++ tsconfig.node.json | 2 + 19 files changed, 2318 insertions(+), 31 deletions(-) create mode 100644 src/renderer/src/cua/CuaOverlay.tsx create mode 100644 src/renderer/src/cua/cuaOverlay.css create mode 100644 src/renderer/src/cua/cuaSurfaceSnapshot.ts create mode 100644 src/renderer/src/cua/useCuaOverlay.ts create mode 100644 src/renderer/src/editor/timelinePointerDrag.ts create mode 100644 tests/cuaOverlay.test.ts create mode 100644 tests/cuaSurfaceSnapshot.test.ts create mode 100644 tests/timelinePointerDrag.test.ts diff --git a/src/renderer/src/AgentChatPanel.tsx b/src/renderer/src/AgentChatPanel.tsx index 6a7fc672..75f93371 100644 --- a/src/renderer/src/AgentChatPanel.tsx +++ b/src/renderer/src/AgentChatPanel.tsx @@ -56,7 +56,14 @@ export function AgentChatPanel({ width, onCollapse }: AgentChatPanelProps): Reac const panelStyle: AgentChatPanelStyle = { '--agent-chat-panel-width': `${width}px` }; return ( -