Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-desktop): 仅在实际输入期间让 Agent 退让 (#4539)

Dash29cba1e8de76
diff --git a/apps/desktop/native/remote-desktop/macos-input.swift b/apps/desktop/native/remote-desktop/macos-input.swift
index 9cfb75a3f0..035c02c2e4 100644
--- a/apps/desktop/native/remote-desktop/macos-input.swift
+++ b/apps/desktop/native/remote-desktop/macos-input.swift
@@ -241,6 +241,7 @@ while let line = readLine() {
lock.lock(); lastSeen = Date()
for event in events { apply(event) }
lock.unlock()
+ print("ok"); fflush(stdout)
}
lock.lock(); releaseAll(); lock.unlock()
#endif
diff --git a/apps/desktop/native/remote-desktop/windows-host/src/service.rs b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
index 9d9f88dedd..06742be738 100644
--- a/apps/desktop/native/remote-desktop/windows-host/src/service.rs
+++ b/apps/desktop/native/remote-desktop/windows-host/src/service.rs
@@ -633,24 +633,20 @@ pub fn worker(name: &str) -> Result<()> {
return denied();
}
pipe.write(b"ready\n")?;
- // Observe input failure without blocking normal per-batch replies.
- let failed = std::sync::Arc::new(AtomicBool::new(false));
- let output = failed.clone();
- std::thread::spawn(move || {
- let mut line = String::new();
- let _ = reader.read_line(&mut line);
- output.store(true, Ordering::SeqCst);
- });
loop {
let line = pipe.line(32768)?;
- if failed.load(Ordering::SeqCst) {
- return denied();
- }
let events: Vec<serde_json::Value> = serde_json::from_slice(&line)?;
if events.len() > 64 {
return denied();
}
child.0.stdin.as_mut().ok_or_else(error)?.write_all(&line)?;
+ // A pipe write is not input completion. Do not let Agent input overlap
+ // a remote text batch still being applied by the worker.
+ let mut acknowledgement = String::new();
+ reader.read_line(&mut acknowledgement)?;
+ if acknowledgement != "ok\n" {
+ return denied();
+ }
pipe.write(b"ok\n")?;
}
}
diff --git a/apps/desktop/native/remote-desktop/windows-input/src/main.rs b/apps/desktop/native/remote-desktop/windows-input/src/main.rs
index 0946aec7d4..4bdf28bb19 100644
--- a/apps/desktop/native/remote-desktop/windows-input/src/main.rs
+++ b/apps/desktop/native/remote-desktop/windows-input/src/main.rs
@@ -304,6 +304,8 @@ fn main() {
if FAILED.load(std::sync::atomic::Ordering::SeqCst) {
break;
}
+ println!("ok");
+ io::stdout().flush().ok();
}
release(&mut keys, &mut buttons);
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
index 7bf4b9bff5..ee9940ffe4 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -4,6 +4,8 @@ import { PassThrough } from 'node:stream';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { COMPUTER_TOOLS } from '@cindy/mcps/computer';
+import { HumanDesktopInput, HUMAN_INPUT_QUIET_MS } from '../../remote-desktop/inputOwnership';
+import * as inputOwnership from '../../remote-desktop/inputOwnership';
const {
existsSyncMock,
@@ -319,7 +321,14 @@ function mockWorkspaceRootExists(workspaceRoot: string): void {
}
describe('computer mcp integration', () => {
+ let revisionSpy: ReturnType<typeof vi.spyOn>;
beforeEach(async () => {
+ // Each test starts with a fresh process input history; cleanup of a driver
+ // session deliberately does not reset production remote-input revisions.
+ const readRevision = inputOwnership.desktopInputRevision;
+ const initialRevision = readRevision();
+ revisionSpy = vi.spyOn(inputOwnership, 'desktopInputRevision')
+ .mockImplementation(() => readRevision() - initialRevision);
setPlatform(originalPlatform);
await cleanupAllComputerDriverSessions();
resetComputerDriverPermissionProbeCacheForTests();
@@ -343,6 +352,7 @@ describe('computer mcp integration', () => {
});
afterEach(() => {
+ revisionSpy.mockRestore();
for (const key of driverResolutionEnvKeys) {
const value = originalDriverResolutionEnv.get(key);
if (value === undefined) {
@@ -1399,6 +1409,164 @@ describe('computer mcp integration', () => {
expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);
});
+ it('yields to remote input between text chunks and requires a fresh target before resuming', async () => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ let batch: ReturnType<HumanDesktopInput['begin']> | undefined;
+ const context = { sessionId: 'remote-yield' };
+ const target = { pid: 123, window_id: 7 };
+ try {
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'type_text' && !batch) batch = human.begin([{ kind: 'text', text: 'human' }]);
+ return { structuredContent: { ok: true, effect: 'confirmed' } };
+ });
+ await expect(callComputerDriverTool('type_text', { ...target, text: 'a'.repeat(850) }, context))
+ .rejects.toThrow('Agent yielded');
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);
+ await batch!.ready;
+ batch!.complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await callComputerDriverTool('get_window_state', target, context);
+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, context)).resolves.toBeDefined();
+ } finally {
+ human.release();
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(['pending', 'quiet', 'settled-before-return', 'input-during-read'] as const)(
+ 'does not count an observation overlapping remote input (%s) as a fresh target', async (phase) => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'remote-observation' };
+ const target = { pid: 123, window_id: 7 };
+ try {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true } });
+ let batch: ReturnType<HumanDesktopInput['begin']> | undefined;
+ if (phase !== 'input-during-read') batch = human.begin([{ kind: 'text', text: 'human' }]);
+ if (phase === 'quiet') batch!.complete();
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'get_window_state') {
+ if (phase === 'input-during-read' && !batch) batch = human.begin([{ kind: 'text', text: 'human' }]);
+ if (phase === 'settled-before-return' || phase === 'input-during-read' || phase === 'quiet') {
+ batch!.complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ }
+ }
+ return { structuredContent: { ok: true } };
+ });
+ await callComputerDriverTool('get_window_state', target, context);
+ batch!.complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await callComputerDriverTool('get_window_state', { ...target, window_id: 8 }, context);
+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await callComputerDriverTool('get_window_state', target, context);
+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, context)).resolves.toBeDefined();
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
+ it.each([false, true])('requires successful re-observation after remote input, including session cleanup=%s', async (cleanup) => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'fresh-observation' };
+ const target = { pid: 123, window_id: 7 };
+ try {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true } });
+ if (cleanup) await callComputerDriverTool('get_window_state', target, context);
+ human.begin([{ kind: 'text', text: 'human' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ if (cleanup) await cleanupComputerDriverSession(context.sessionId);
+ await expect(callComputerDriverTool('click', target, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ const failedObservations = [
+ { args: {}, result: { ok: false, error: 'unavailable' } },
+ { args: { capture_mode: 'vision' }, result: { screenshot_frame_valid: false, elements: [{}] } },
+ { args: { capture_mode: 'som' }, result: { screenshot_error: 'capture failed', tree_markdown: 'AX' } },
+ { args: { include_screenshot: true }, result: { screenshot_error: 'capture failed' } },
+ { args: { screenshot_out_file: '/tmp/test.png' }, result: { screenshot_frame_valid: false } },
+ { args: { capture_mode: 'ax' }, result: { degraded: true, elements: [], tree_markdown: '' } },
+ { args: { include_screenshot: false }, result: { degraded: true } },
+ { args: {}, result: { screenshot_error: 'capture failed', degraded: true } },
+ ];
+ for (const observation of failedObservations) {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: observation.result });
+ await callComputerDriverTool('get_window_state', { ...target, ...observation.args }, context);
+ await expect(callComputerDriverTool('click', target, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ }
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true } });
+ await callComputerDriverTool('get_window_state', target, context);
+ for (const name of ['type_text', 'press_key', 'hotkey', 'click'] as const) {
+ await expect(callComputerDriverTool(name, { pid: 123, text: 'hello', key: 'a', keys: ['CTRL', 'a'] }, context))
+ .resolves.toBeDefined();
+ }
+ await expect(callComputerDriverTool('click', { pid: 124 }, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await expect(callComputerDriverTool('click', { ...target, window_id: 8 }, context))
+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await expect(callComputerDriverTool('click', target, context)).resolves.toBeDefined();
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
+ it('bounds delayed typing chunks while a remote input connection is open', async () => {
+ const human = new HumanDesktopInput();
+ try {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true, effect: 'confirmed' } });
+ await callComputerDriverTool('type_text', { pid: 123, window_id: 7, text: 'abc', delay_ms: 200 }, { sessionId: 'remote-slow-text' });
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')
+ .map(([call]) => call.arguments.text)).toEqual(['a', 'b', 'c']);
+ } finally { human.release(); }
+ });
+
+ it('lets remote input proceed during driver startup and refuses the now-stale Agent action', async () => {
+ const human = new HumanDesktopInput();
+ let finish!: () => void;
+ mcpConnectMock.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const action = callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, { sessionId: 'remote-startup' });
+ const rejected = expect(action).rejects.toThrow('Agent yielded');
+ try {
+ await vi.waitFor(() => expect(mcpConnectMock).toHaveBeenCalled());
+ const batch = human.begin([{ kind: 'text', text: 'human' }]);
+ await batch.ready;
+ batch.complete();
+ finish();
+ await rejected;
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'click')).toHaveLength(0);
+ } finally { finish?.(); human.release(); }
+ });
+
+ it('keeps remote input waiting through driver teardown after an interrupted primitive', async () => {
+ const human = new HumanDesktopInput();
+ let batch: ReturnType<HumanDesktopInput['begin']> | undefined;
+ let finish!: () => void;
+ let delivered = false;
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'type_text') {
+ batch = human.begin([{ kind: 'text', text: 'human' }]);
+ void batch.ready.then(() => { delivered = true; });
+ throw new Error('session ended; tool call ignored');
+ }
+ if (name === 'end_session') return new Promise((resolve) => {
+ finish = () => resolve({ structuredContent: { ok: true } });
+ });
+ return { structuredContent: { ok: true } };
+ });
+ const action = callComputerDriverTool('type_text', { pid: 123, window_id: 7, text: 'hello' }, { sessionId: 'remote-teardown' });
+ const rejected = expect(action).rejects.toMatchObject({ code: 'ACTION_OUTCOME_UNKNOWN' });
+ try {
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ expect(delivered).toBe(false);
+ finish(); await rejected; await batch!.ready;
+ expect(delivered).toBe(true);
+ batch!.complete();
+ } finally { finish?.(); human.release(); }
+ });
+
it.each(['connect', 'tools/list'] as const)('cancels the caller during %s without interrupting shared startup', async (phase) => {
mcpCallToolMock.mockResolvedValue({ structuredContent: { width: 1920, height: 1080 } });
let finish!: () => void;
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 4810d3eb81..ad5727be2d 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -1,5 +1,5 @@
import path from 'node:path';
-import { withAgentDesktopInput } from '../remote-desktop/inputOwnership';
+import { desktopInputRevision, hasRemoteDesktopInput, isHumanDesktopInputActive, withAgentDesktopInput } from '../remote-desktop/inputOwnership';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { spawn, type ChildProcess } from 'node:child_process';
@@ -23,7 +23,7 @@ import { createLogger } from '../logger.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { resolveDesktopOutboundProxy } from '../maker-host/outbound-proxy-resolver.js';
import { adaptComputerDriverArgs, type ComputerDriverToolSchema } from './computer-contract.js';
-import { computerResultOutcome, getComputerTool } from '@cindy/mcps/computer';
+import { computerResultOutcome, getComputerTool, isUnavailableWindowObservation } from '@cindy/mcps/computer';
const logger = createLogger('mcp/cindy_computer');
const DRIVER_COMMAND = 'cua-driver';
@@ -1974,12 +1974,12 @@ function applyDriverSessionArgs(
return result;
}
-function splitTypeTextChunks(text: string): string[] {
+function splitTypeTextChunks(text: string, chunkChars = TYPE_TEXT_CHUNK_CHARS): string[] {
const chars = Array.from(text);
- if (chars.length <= TYPE_TEXT_CHUNK_CHARS) return [text];
+ if (chars.length <= chunkChars) return [text];
const chunks: string[] = [];
- for (let index = 0; index < chars.length; index += TYPE_TEXT_CHUNK_CHARS) {
- chunks.push(chars.slice(index, index + TYPE_TEXT_CHUNK_CHARS).join(''));
+ for (let index = 0; index < chars.length; index += chunkChars) {
+ chunks.push(chars.slice(index, index + chunkChars).join(''));
}
return chunks;
}
@@ -2236,16 +2236,35 @@ async function callCuaMcpToolWithTypeTextChunks(
timeoutMs: number,
signal?: AbortSignal,
assertActive: () => void = () => {},
+ settleFailedInput: () => Promise<void> = async () => {},
): Promise<unknown> {
signal?.throwIfAborted();
assertActive();
+ const dispatch = (input: Record<string, unknown>) => getComputerTool(name)?.readOnly === true
+ ? callCuaMcpTool(entry, name, input, timeoutMs, signal)
+ : withAgentDesktopInput(async () => {
+ try {
+ return await callCuaMcpTool(entry, name, input, timeoutMs, signal);
+ } catch (error) {
+ // Cancellation/timeout is not proof that native input stopped. Keep
+ // remote input waiting through the existing driver-session teardown.
+ if (signal?.aborted || shouldCleanupCuaMcpSessionAfterError(error)) {
+ await settleFailedInput();
+ }
+ throw error;
+ }
+ });
if (name !== 'type_text' || typeof args.text !== 'string') {
- return callCuaMcpTool(entry, name, args, timeoutMs, signal);
+ return dispatch(args);
}
- const chunks = splitTypeTextChunks(args.text);
+ // Slow per-character typing must also offer frequent handoff boundaries.
+ const chunkChars = hasRemoteDesktopInput() && typeof args.delay_ms === 'number' && args.delay_ms > 0
+ ? Math.max(1, Math.min(TYPE_TEXT_CHUNK_CHARS, Math.floor(300 / args.delay_ms)))
+ : TYPE_TEXT_CHUNK_CHARS;
+ const chunks = splitTypeTextChunks(args.text, chunkChars);
if (chunks.length === 1) {
- return callCuaMcpTool(entry, name, args, timeoutMs, signal);
+ return dispatch(args);
}
let lastResult: unknown = null;
@@ -2255,7 +2274,7 @@ async function callCuaMcpToolWithTypeTextChunks(
const chunk = chunks[index];
signal?.throwIfAborted();
assertActive();
- lastResult = await callCuaMcpTool(entry, name, { ...args, text: chunk }, timeoutMs, signal);
+ lastResult = await dispatch({ ...args, text: chunk });
const resultObject = objectValue(lastResult);
processedChunks += 1;
const outcome = computerResultOutcome(name, lastResult);
@@ -3358,20 +3377,59 @@ export async function grantComputerDriverPermissions(
};
}
+// Remote input invalidates previously observed targets even after its short
+// ownership window ends. Never resume typing into a stale focus implicitly.
+const inputObservations = new Map<string, { windows: Map<string, number> }>();
+
export async function callComputerDriverTool(
name: ComputerMcpToolName,
args: Record<string, unknown>,
context?: ComputerMcpCallContext,
): Promise<unknown> {
- return getComputerTool(name)?.readOnly === true
- ? callComputerDriverToolImpl(name, args, context)
- : withAgentDesktopInput(() => callComputerDriverToolImpl(name, args, context));
+ const sessionId = readSessionIdFromContext(context);
+ const revision = desktopInputRevision();
+ let observations = sessionId ? inputObservations.get(sessionId) : undefined;
+ if (sessionId && !observations) {
+ observations = { windows: new Map() };
+ inputObservations.set(sessionId, observations);
+ }
+ const window = `${args.pid}:${args.window_id}`;
+ if (getComputerTool(name)?.readOnly === true) {
+ const startedIdle = !isHumanDesktopInputActive();
+ const result = await callComputerDriverToolImpl(name, args, context);
+ if (name === 'get_window_state' && startedIdle && computerResultOutcome(name, result).ok
+ && !isUnavailableWindowObservation(result, args)
+ && revision === desktopInputRevision() && !isHumanDesktopInputActive()) {
+ observations?.windows.set(window, revision);
+ // App-scoped actions may omit window_id; a successful observation of
+ // that app also refreshes its focus, without refreshing other windows.
+ observations?.windows.set(`${args.pid}:undefined`, revision);
+ }
+ return result;
+ }
+ // Preparation can be slow and does not inject input. Reserve ownership only
+ // around each driver primitive, and recheck this observation before dispatch.
+ const assertCurrent = () => {
+ if (desktopInputRevision() !== revision) {
+ throw new ComputerDriverError('Remote desktop input arrived. Agent yielded before further input; previous input may have completed. Get fresh window state before continuing.', 'DESKTOP_INPUT_YIELDED');
+ }
+ if (isHumanDesktopInputActive()) {
+ throw new ComputerDriverError('Remote desktop input is active. Yield briefly, then get fresh window state before retrying; the remote connection can stay open.', 'DESKTOP_INPUT_BUSY');
+ }
+ };
+ assertCurrent();
+ if (args.pid !== undefined && observations && revision > 0
+ && observations.windows.get(window) !== revision) {
+ throw new ComputerDriverError('Remote desktop input changed the desktop. Get fresh state for this window before acting again.', 'STALE_SNAPSHOT');
+ }
+ return callComputerDriverToolImpl(name, args, context, assertCurrent);
}
async function callComputerDriverToolImpl(
name: ComputerMcpToolName,
args: Record<string, unknown>,
context?: ComputerMcpCallContext,
+ assertInputCurrent: () => void = () => {},
): Promise<unknown> {
const signal = context?.signal;
signal?.throwIfAborted();
@@ -3382,6 +3440,7 @@ async function callComputerDriverToolImpl(
}
const sessionCloseVersion = getCuaMcpSessionCloseVersion(sessionId);
const assertActive = () => {
+ assertInputCurrent();
signal?.throwIfAborted();
assertComputerDriverToolDispatchAvailable();
if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
@@ -3405,7 +3464,8 @@ async function callComputerDriverToolImpl(
const timeoutMs = getCuaMcpToolTimeoutMs(name);
try {
await initializeDefaultCursorStyle(name, driverArgs, entry, entry.driverSessionId, sessionCloseVersion, signal, assertActive);
- const result = await callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs, signal, assertActive);
+ const result = await callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs, signal, assertActive,
+ () => cleanupCuaMcpSessionAfterError(sessionId, entry));
return name === 'list_windows' ? enrichAndFilterListWindowsResult(result, rawArgs) : result;
} catch (err) {
logger.warn('cua-driver MCP tool call failed', {
@@ -3495,6 +3555,7 @@ async function cleanupComputerDriverSessionEntry(sessionId: string, entry: CuaMc
}
export function cleanupComputerDriverSession(sessionId: string): Promise<void> {
+ inputObservations.delete(sessionId);
cuaMcpSessionCursorCapabilities.delete(sessionId);
markCuaMcpSessionClosed(sessionId);
const entry = cuaMcpSessions.get(sessionId);
@@ -3535,6 +3596,7 @@ async function cleanupActiveComputerDriverSessions(): Promise<void> {
}
export async function cleanupAllComputerDriverSessions(): Promise<void> {
+ inputObservations.clear();
stopPermissionGrantFlow('cleanup');
clearProcessSnapshotCache();
await cleanupActiveComputerDriverSessions();
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
index 5a95b57478..6b0249a497 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
import { RemoteDesktopController, type DesktopControllerDeps } from '../controller';
-import { acquireHumanDesktopInput, withAgentDesktopInput } from '../inputOwnership';
import { enumerateDesktopSources } from '../captureSource';
import type { RemoteDesktopIceReply, RemoteDesktopLease } from '@cindy/device-link';
@@ -654,17 +653,3 @@ describe('remote desktop authority and lifecycle', () => {
expect(h.controller.hasLease(lease.lease)).toBe(true);
});
});
-describe('human / Agent input ownership', () => {
- it('excludes simultaneous input in both directions and releases on error', async () => {
- const release = acquireHumanDesktopInput();
- await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('person');
- release();
- await expect(
- withAgentDesktopInput(async () => {
- expect(() => acquireHumanDesktopInput()).toThrow('BUSY');
- throw new Error('action');
- }),
- ).rejects.toThrow('action');
- acquireHumanDesktopInput()();
- });
-});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts
index ff6448af91..f9b20bd391 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts
@@ -1,12 +1,29 @@
import { EventEmitter } from 'node:events';
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { DesktopInputHost } from '../inputHost';
-import { withAgentDesktopInput } from '../inputOwnership';
+import { HUMAN_INPUT_QUIET_MS, withAgentDesktopInput } from '../inputOwnership';
+import { openWindowsDesktopConnection } from '../windowsHost';
+
+const platform = process.platform;
+afterEach(() => {
+ vi.useRealTimers();
+ Object.defineProperty(process, 'platform', { value: platform });
+});
+const flush = async () => {
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+};
vi.mock('electron', () => ({
app: {},
- screen: { getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0, width: 100, height: 100 } }] },
+ screen: {
+ getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0, width: 100, height: 100 } }],
+ dipToScreenPoint: (point: unknown) => point,
+ },
+}));
+vi.mock('../windowsHost', () => ({
+ openWindowsDesktopConnection: vi.fn(),
+ readWindowsDesktopSupport: async () => 'ready',
}));
function childProcess() {
const child = Object.assign(new EventEmitter(), {
@@ -34,6 +51,160 @@ function childProcess() {
};
}
describe('native input lifecycle', () => {
+ it('retains Windows ownership until queued text and native release are acknowledged', async () => {
+ vi.useFakeTimers();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ const replies: ((value: string) => void)[] = [];
+ const connection = {
+ request: vi.fn(() => new Promise<string>((resolve) => replies.push(resolve))),
+ close: vi.fn(),
+ };
+ vi.mocked(openWindowsDesktopConnection).mockResolvedValueOnce(connection);
+ const host = new DesktopInputHost(vi.fn());
+ await host.start('1');
+ host.input([{ kind: 'text', text: 'hello' }]);
+ await flush();
+ host.stop();
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ replies.shift()!('ok\n');
+ await flush();
+ expect(connection.request).toHaveBeenLastCalledWith('[{"kind":"release"}]');
+ vi.advanceTimersByTime(2000);
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ replies.shift()!('ok\n');
+ await flush();
+ expect(connection.close).toHaveBeenCalled();
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ });
+
+ it('retains Windows ownership through the service shutdown deadline when release fails', async () => {
+ vi.useFakeTimers();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ const connection = { request: vi.fn().mockRejectedValue(new Error('closed')), close: vi.fn() };
+ vi.mocked(openWindowsDesktopConnection).mockResolvedValueOnce(connection);
+ const host = new DesktopInputHost(vi.fn());
+ await host.start('1');
+ host.stop();
+ await flush();
+ expect(connection.close).toHaveBeenCalled();
+ vi.advanceTimersByTime(6499);
+ await flush();
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ vi.advanceTimersByTime(1);
+ await flush();
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ });
+ it('waits for native completion of text and key-up instead of unlocking on stdin write', async () => {
+ vi.useFakeTimers();
+ const c = childProcess();
+ let host: DesktopInputHost;
+ const failure = vi.fn(() => host.stop());
+ host = new DesktopInputHost(failure, {
+ platform: 'darwin',
+ resolveBinary: async () => '/test/helper',
+ spawn: () => {
+ void Promise.resolve().then(() => c.child.stdout.emit('data', Buffer.from('ready\n')));
+ return c.typed;
+ },
+ });
+ try {
+ await host.start('1');
+ host.input([{ kind: 'key', code: 'ShiftLeft', down: true }]);
+ await flush();
+ c.child.stdout.emit('data', Buffer.from('ok\n'));
+ await flush();
+ vi.advanceTimersByTime(301);
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ host.input([
+ { kind: 'key', code: 'ShiftLeft', down: false },
+ { kind: 'text', text: 'hello' },
+ ]);
+ await flush();
+ vi.advanceTimersByTime(301);
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ c.child.stdout.emit('data', Buffer.from('o'));
+ c.child.stdout.emit('data', Buffer.from('k\n'));
+ await flush();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ expect(failure).not.toHaveBeenCalled();
+ } finally {
+ host.stop();
+ c.exit();
+ await flush();
+ }
+ });
+
+ it('keeps heartbeats alive while an Agent primitive finishes, and never replays queued input after stop', async () => {
+ vi.useFakeTimers();
+ const c = childProcess();
+ const host = new DesktopInputHost(vi.fn(), {
+ platform: 'darwin',
+ resolveBinary: async () => '/test/helper',
+ spawn: () => {
+ void Promise.resolve().then(() => c.child.stdout.emit('data', Buffer.from('ready\n')));
+ return c.typed;
+ },
+ });
+ let finish!: () => void;
+ try {
+ await host.start('1');
+ const action = withAgentDesktopInput(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ host.input([{ kind: 'text', text: 'must not replay' }]);
+ vi.advanceTimersByTime(2000);
+ await flush();
+ expect(c.child.stdin.write).toHaveBeenCalledOnce();
+ expect(c.child.stdin.write.mock.calls[0][0]).toBe('[]\n');
+ c.child.stdout.emit('data', Buffer.from('ok\n'));
+ await flush();
+ host.stop();
+ c.exit();
+ finish();
+ await action;
+ await flush();
+ expect(c.child.stdin.write).toHaveBeenCalledOnce();
+ } finally {
+ finish?.();
+ host.stop();
+ c.exit();
+ await flush();
+ }
+ });
+
+ it('stops a stalled native batch without unlocking until native exit', async () => {
+ vi.useFakeTimers();
+ const c = childProcess();
+ let host: DesktopInputHost;
+ const failure = vi.fn(() => host.stop());
+ host = new DesktopInputHost(failure, {
+ platform: 'darwin',
+ resolveBinary: async () => '/test/helper',
+ spawn: () => {
+ void Promise.resolve().then(() => c.child.stdout.emit('data', Buffer.from('ready\n')));
+ return c.typed;
+ },
+ });
+ try {
+ await host.start('1');
+ host.input([{ kind: 'button', button: 0, down: true, x: 0, y: 0 }]);
+ await flush();
+ vi.advanceTimersByTime(10_000);
+ await flush();
+ expect(failure).toHaveBeenCalled();
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
+ c.exit();
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ } finally {
+ host.stop();
+ c.exit();
+ await flush();
+ }
+ });
it('keeps Agent input excluded until the old helper has actually exited', async () => {
const c = childProcess();
const host = new DesktopInputHost(vi.fn(), {
@@ -45,8 +216,10 @@ describe('native input lifecycle', () => {
},
});
await host.start('1');
+ await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
+ host.input([{ kind: 'button', button: 0, down: true, x: 0.2, y: 0.2 }]);
host.stop();
- await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('person');
+ await expect(withAgentDesktopInput(async () => {})).rejects.toThrow('input is active');
expect(c.child.stdin.end).toHaveBeenCalledWith('[{"kind":"release"}]\n');
c.exit();
await expect(withAgentDesktopInput(async () => {})).resolves.toBeUndefined();
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts
new file mode 100644
index 0000000000..7e264686d4
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HumanDesktopInput, HUMAN_INPUT_QUIET_MS, withAgentDesktopInput } from '../inputOwnership';
+
+const humans: HumanDesktopInput[] = [];
+const human = () => {
+ const input = new HumanDesktopInput();
+ humans.push(input);
+ return input;
+};
+const agent = () => withAgentDesktopInput(async () => 'done');
+afterEach(() => {
+ humans.splice(0).forEach((input) => input.release());
+ vi.useRealTimers();
+});
+
+describe('remote input yields only during actual interaction', () => {
+ it('retains ownership during shutdown even if a rejected key-up batch settles first', async () => {
+ vi.useFakeTimers();
+ const input = human();
+ input.begin([{ kind: 'key', code: 'ShiftLeft', down: true }]).complete();
+ const up = input.begin([{ kind: 'key', code: 'ShiftLeft', down: false }]);
+ input.holdUntilExit();
+ up.complete();
+ vi.advanceTimersByTime(60_000);
+ await expect(agent()).rejects.toThrow('input is active');
+ input.release();
+ await expect(agent()).resolves.toBe('done');
+ });
+ it('allows Agent input with an idle remote connection', async () => {
+ human();
+ await expect(agent()).resolves.toBe('done');
+ });
+
+ it.each(['button', 'key'] as const)(
+ 'holds a %s gesture past the quiet interval until native key-up completes',
+ async (kind) => {
+ vi.useFakeTimers();
+ const input = human();
+ const event =
+ kind === 'button'
+ ? { kind, button: 0 as const, down: true, x: 0, y: 0 }
+ : { kind, code: 'ShiftLeft', down: true };
+ input.begin([event]).complete();
+ vi.advanceTimersByTime(60_000);
+ await expect(agent()).rejects.toThrow('input is active');
+ const up = input.begin([{ ...event, down: false }]);
+ vi.advanceTimersByTime(60_000);
+ await expect(agent()).rejects.toThrow('input is active');
+ up.complete();
+ await expect(agent()).rejects.toThrow('input is active');
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(agent()).resolves.toBe('done');
+ },
+ );
+
+ it('keeps a long text batch protected until native acknowledgement, then releases automatically', async () => {
+ vi.useFakeTimers();
+ const batch = human().begin([{ kind: 'text', text: 'test' }]);
+ vi.advanceTimersByTime(60_000);
+ await expect(agent()).rejects.toThrow('input is active');
+ batch.complete();
+ batch.complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(agent()).resolves.toBe('done');
+ });
+
+ it('reserves human priority and yields between Agent primitives without changing focus during a primitive', async () => {
+ const input = human();
+ let finish!: () => void;
+ const primitive = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const action = withAgentDesktopInput(async (assertCurrent) => {
+ await primitive;
+ assertCurrent();
+ throw new Error('must not dispatch the next text chunk');
+ });
+ const rejected = expect(action).rejects.toThrow('Agent yielded');
+ const batch = input.begin([{ kind: 'text', text: 'human' }]);
+ const native = vi.fn();
+ void batch.ready.then(native);
+ await Promise.resolve();
+ expect(native).not.toHaveBeenCalled();
+ await expect(agent()).rejects.toThrow('input is active');
+ finish();
+ await rejected;
+ await batch.ready;
+ expect(native).toHaveBeenCalledOnce();
+ batch.complete();
+ });
+
+ it('clears held keys on release and keeps generations independent', async () => {
+ vi.useFakeTimers();
+ const old = human();
+ old.begin([{ kind: 'key', code: 'ControlLeft', down: true }]).complete();
+ const current = human();
+ current.begin([{ kind: 'button', button: 0, down: true, x: 0, y: 0 }]).complete();
+ old.release();
+ vi.advanceTimersByTime(60_000);
+ await expect(agent()).rejects.toThrow('input is active');
+ current.begin([{ kind: 'release' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ await expect(agent()).resolves.toBe('done');
+ });
+
+ it('releases Agent ownership after errors and excludes overlapping Agent actions', async () => {
+ await expect(
+ withAgentDesktopInput(async () => {
+ await expect(agent()).rejects.toThrow('another Agent');
+ throw new Error('failed');
+ }),
+ ).rejects.toThrow('failed');
+ await expect(agent()).resolves.toBe('done');
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.ts
index 2f9281673d..9bc3f067ea 100644
--- a/apps/desktop/src/main/remote-desktop/inputHost.ts
+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts
@@ -9,7 +9,7 @@ import type {
DesktopPermissionStatus,
RemoteDesktopDisplayMode,
} from '@cindy/device-link';
-import { acquireHumanDesktopInput } from './inputOwnership';
+import { HumanDesktopInput } from './inputOwnership';
import {
openWindowsDesktopConnection,
readWindowsDesktopSupport,
@@ -187,7 +187,8 @@ export class DesktopInputHost {
private queuedBytes = 0;
private writing = Promise.resolve();
private child: ChildProcessWithoutNullStreams | null = null;
- private releaseOwnership: (() => void) | null = null;
+ private activity: HumanDesktopInput | null = null;
+ private acknowledge: ((error?: Error) => void) | null = null;
private displayId = '';
private generation = 0;
private heartbeat: ReturnType<typeof setInterval> | null = null;
@@ -210,8 +211,7 @@ export class DesktopInputHost {
const generation = this.generation;
await this.stopping;
if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
- const release = acquireHumanDesktopInput();
- this.releaseOwnership = release;
+ this.activity = new HumanDesktopInput();
try {
if (
platform === 'win32' &&
@@ -261,8 +261,20 @@ export class DesktopInputHost {
child.once('exit', () => finish(new Error('DESKTOP_INPUT_UNAVAILABLE')));
});
if (generation !== this.generation) throw new Error('DESKTOP_LEASE_EXPIRED');
+ let output = '';
child.stdout.on('data', (data: Buffer) => {
- if (data.toString().includes('error') && this.child === child) this.onFailure();
+ if (this.child !== child) return;
+ output += data.toString();
+ while (output.includes('\n')) {
+ const end = output.indexOf('\n');
+ const line = output.slice(0, end).trim();
+ output = output.slice(end + 1);
+ if (line === 'ok') this.acknowledge?.();
+ else {
+ this.acknowledge?.(new Error('DESKTOP_INPUT_UNAVAILABLE'));
+ this.onFailure();
+ }
+ }
});
this.heartbeat = setInterval(() => this.write([]), 2000);
} catch (error) {
@@ -273,6 +285,8 @@ export class DesktopInputHost {
input(events: DesktopInput[]): void {
const display = screen.getAllDisplays().find((item) => String(item.id) === this.displayId);
if (!display || (!this.child && !this.windows)) throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ if (events.length === 0) return;
+ const batch = this.activity!.begin(events);
this.write(
events.map((event) => {
if (event.kind !== 'move' && event.kind !== 'button') return event;
@@ -283,43 +297,55 @@ export class DesktopInputHost {
const native = process.platform === 'win32' ? screen.dipToScreenPoint(point) : point;
return { ...event, ...native };
}),
+ batch,
);
}
- private write(events: unknown[]): void {
+ private write(events: unknown[], batch?: { ready: Promise<void>; complete: () => void }): void {
const child = this.child;
const line = `${JSON.stringify(events)}\n`;
const connection = this.windows;
- if (connection) {
- const bytes = Buffer.byteLength(line);
- if (this.queuedBytes + bytes > 32_768) {
- this.onFailure();
- return;
- }
- this.queuedBytes += bytes;
- const generation = this.generation;
- this.writing = this.writing
- .then(async () => {
- if (this.windows !== connection) return;
- if ((await connection.request(line.slice(0, -1))) !== 'ok\n')
- throw new Error('DESKTOP_INPUT_UNAVAILABLE');
- })
- .catch(() => {
- if (this.windows === connection) this.onFailure();
- })
- .finally(() => {
- if (generation === this.generation) this.queuedBytes -= bytes;
- });
- return;
- }
- if (
- !child ||
- child.stdin.destroyed ||
- child.stdin.writableLength + Buffer.byteLength(line) > 32_768
- ) {
+ const bytes = Buffer.byteLength(line);
+ if (this.queuedBytes + bytes > 32_768 || (!connection && (!child || child.stdin.destroyed))) {
this.onFailure();
return;
}
- child.stdin.write(line);
+ this.queuedBytes += bytes;
+ const generation = this.generation;
+ const send = async () => {
+ if (generation !== this.generation) return;
+ this.writing = this.writing.then(async () => {
+ if (generation !== this.generation) return;
+ if (connection) {
+ if ((await connection.request(line.slice(0, -1))) !== 'ok\n')
+ throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ } else {
+ // stdin.write completion only proves bytes were queued. Hold ownership
+ // until the helper has finished posting the entire native batch.
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => finish(new Error('DESKTOP_INPUT_TIMEOUT')), 10_000);
+ const finish = (error?: Error) => {
+ clearTimeout(timer);
+ if (this.acknowledge === finish) this.acknowledge = null;
+ error ? reject(error) : resolve();
+ };
+ this.acknowledge = finish;
+ child!.stdin.write(line, (error) => {
+ if (error) finish(error);
+ });
+ });
+ }
+ });
+ await this.writing;
+ };
+ // Waiting for an Agent primitive must not hold up empty native heartbeats.
+ void (batch ? batch.ready.then(send) : send())
+ .catch(() => {
+ if (generation === this.generation) this.onFailure();
+ })
+ .finally(() => {
+ batch?.complete();
+ if (generation === this.generation) this.queuedBytes -= bytes;
+ });
}
async release(): Promise<void> {
this.stop();
@@ -327,8 +353,9 @@ export class DesktopInputHost {
}
stop(): void {
this.generation++;
+ this.acknowledge?.(new Error('DESKTOP_LEASE_EXPIRED'));
const windows = this.windows;
- windows?.close();
+ const writing = this.writing;
this.windows = null;
this.queuedBytes = 0;
this.writing = Promise.resolve();
@@ -336,8 +363,10 @@ export class DesktopInputHost {
this.heartbeat = null;
const child = this.child;
this.child = null;
- const release = this.releaseOwnership;
- this.releaseOwnership = null;
+ const activity = this.activity;
+ activity?.holdUntilExit();
+ const release = () => activity?.release();
+ this.activity = null;
if (child) {
this.stopping = new Promise<void>((resolve) => {
const finish = () => {
@@ -355,13 +384,21 @@ export class DesktopInputHost {
timer.unref();
child.once('exit', () => clearTimeout(timer));
} else if (windows) {
- // The service closes its worker gracefully before the job-kill deadline.
- this.stopping = new Promise<void>((resolve) =>
- setTimeout(() => {
- release?.();
- resolve();
- }, 1500),
- );
+ this.stopping = (async () => {
+ try {
+ await writing;
+ if ((await windows.request('[{"kind":"release"}]')) !== 'ok\n')
+ throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ } catch {
+ windows.close();
+ // Failed completion: allow the service's 5 s pipe deadline plus
+ // 1.2 s worker job-kill deadline before relinquishing ownership.
+ await new Promise<void>((resolve) => setTimeout(resolve, 6500));
+ } finally {
+ windows.close();
+ release();
+ }
+ })();
} else release?.();
}
}
diff --git a/apps/desktop/src/main/remote-desktop/inputOwnership.ts b/apps/desktop/src/main/remote-desktop/inputOwnership.ts
index dc3250d670..354012f6c2 100644
--- a/apps/desktop/src/main/remote-desktop/inputOwnership.ts
+++ b/apps/desktop/src/main/remote-desktop/inputOwnership.ts
@@ -1,24 +1,94 @@
-// Process-local arbitration: a human and an Agent cannot inject simultaneously.
-let human = false;
-let actions = 0;
-export function acquireHumanDesktopInput(): () => void {
- if (human || actions > 0) throw new Error('DESKTOP_INPUT_BUSY');
- human = true;
- let released = false;
- return () => {
- if (!released) {
- released = true;
- human = false;
+import type { DesktopInput } from '@cindy/device-link';
+
+// Coordinate actual input, not the lifetime of a remote desktop connection.
+const humans = new Set<HumanDesktopInput>();
+const actions = new Set<Promise<void>>();
+let revision = 0;
+export const HUMAN_INPUT_QUIET_MS = 300;
+export const desktopInputRevision = (): number => revision;
+export const hasRemoteDesktopInput = (): boolean => humans.size > 0;
+export const isHumanDesktopInputActive = (): boolean => [...humans].some((human) => human.busy);
+
+/** Tracks queued native input and held gestures for one input-helper generation. */
+export class HumanDesktopInput {
+ private held = new Set<string>();
+ private pending = 0;
+ private quietUntil = 0;
+ private released = false;
+ private stopping = false;
+
+ constructor() {
+ humans.add(this);
+ }
+
+ get busy(): boolean {
+ return this.stopping || this.pending > 0 || this.held.size > 0 || Date.now() < this.quietUntil;
+ }
+
+ begin(events: DesktopInput[]): { ready: Promise<void>; complete: () => void } {
+ if (this.released) throw new Error('DESKTOP_LEASE_EXPIRED');
+ revision++;
+ this.pending++;
+ for (const event of events) {
+ if (event.kind === 'release') this.held.clear();
+ if (event.kind === 'key' || event.kind === 'button') {
+ const id = event.kind === 'key' ? `key:${event.code}` : `button:${event.button}`;
+ if (event.down) this.held.add(id);
+ else this.held.delete(id);
+ }
}
- };
+ // Reserve human priority immediately. Let an already-dispatched primitive
+ // finish before moving focus; the Agent yields before its next text chunk.
+ const ready = Promise.all([...actions]).then(() => undefined);
+ let completed = false;
+ return {
+ ready,
+ complete: () => {
+ if (completed) return;
+ completed = true;
+ this.pending--;
+ this.quietUntil = Date.now() + HUMAN_INPUT_QUIET_MS;
+ },
+ };
+ }
+
+ holdUntilExit(): void {
+ this.stopping = true;
+ }
+
+ // Called only after native release/exit, never merely when key-up is queued.
+ release(): void {
+ this.released = true;
+ humans.delete(this);
+ }
}
-export async function withAgentDesktopInput<T>(run: () => Promise<T>): Promise<T> {
- if (human)
- throw new Error('Desktop input is in use by a person. Retry after they release control.');
- actions++;
+
+export async function withAgentDesktopInput<T>(
+ run: (assertCurrent: () => void) => Promise<T>,
+): Promise<T> {
+ if (isHumanDesktopInputActive()) {
+ throw new Error(
+ 'Remote desktop input is active. Yield briefly, then get fresh window state before retrying; the remote connection can stay open.',
+ );
+ }
+ if (actions.size > 0)
+ throw new Error('DESKTOP_INPUT_BUSY: another Agent input action is finishing.');
+ const startedAt = revision;
+ let finish!: () => void;
+ const done = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ actions.add(done);
try {
- return await run();
+ return await run(() => {
+ if (revision !== startedAt) {
+ throw new Error(
+ 'Remote desktop input arrived. Agent yielded before further input; previous input may have completed. Get fresh window state before continuing.',
+ );
+ }
+ });
} finally {
- actions--;
+ actions.delete(done);
+ finish();
}
}
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 2e8ee5e4c1..afe1cbf2f4 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -332,8 +332,24 @@ one extra dialog as proof of local human consent.
The native helper holds actual down/up state and releases it on EOF/stop, with a
watchdog for an unresponsive parent. Input batches and queues are bounded; a
backpressure failure stops control rather than silently dropping key-up events.
-CUA Agent actions and human input share a process-local ownership guard. Other
-applications and separate Cindy processes are outside that guard.
+CUA Agent actions yield to actual remote input, rather than to an open control
+connection. Queued native batches, held mouse buttons/keys, and a 300 ms quiet
+interval after native completion exclude new Agent actions. An already-dispatched
+Agent primitive finishes before remote input is delivered; further Agent text
+chunks yield. Agent actions are never automatically replayed. After remote input,
+the Agent must successfully observe the target window again with input idle at
+both the start and end of the read and no input revision change during the read
+before acting on it, including the first action of a new or cleaned-up driver
+session. Actions without a window ID accept an observation of the same process;
+an explicit window ID still requires that exact window. Empty connection
+heartbeats do not claim input ownership.
+
+The native macOS/Windows helper acknowledges a batch only after posting all its
+events; the Windows service forwards that acknowledgement. Main retains ownership
+through native shutdown when stopping held input. The guard coordinates only
+remote input and CUA calls in this Cindy process: physical keyboard/mouse input,
+other applications, and separate Cindy processes are outside it. Native event
+posting is not proof that an application has finished handling those events.
## Platform and verification limits
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 7d7ebddf17..083974bfc2 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -1026,7 +1026,7 @@ export function createComputerMcpServer(
}
/** Only explicit driver failure signals override legacy/partial observation success. */
-function isUnavailableWindowObservation(
+export function isUnavailableWindowObservation(
data: unknown,
args: Record<string, unknown>,
): boolean {