Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(computer): serialize agent input and keep macOS drag in background (#4744)
Dash18a3e3d03b1b
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.tsindex 016b88d734..fa53e0902e 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts@@ -325,6 +325,7 @@ function mockWorkspaceRootExists(workspaceRoot: string): void {describe('computer mcp integration', () => {let revisionSpy: ReturnType<typeof vi.spyOn>;+ let agentRevisionSpy: 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.@@ -332,6 +333,10 @@ describe('computer mcp integration', () => {const initialRevision = readRevision();revisionSpy = vi.spyOn(inputOwnership, 'desktopInputRevision').mockImplementation(() => readRevision() - initialRevision);+ const readAgentRevision = inputOwnership.agentDesktopInputRevision;+ const initialAgentRevision = readAgentRevision();+ agentRevisionSpy = vi.spyOn(inputOwnership, 'agentDesktopInputRevision')+ .mockImplementation(() => readAgentRevision() - initialAgentRevision);setPlatform(originalPlatform);await cleanupAllComputerDriverSessions();resetComputerDriverPermissionProbeCacheForTests();@@ -363,6 +368,7 @@ describe('computer mcp integration', () => {afterEach(() => {revisionSpy.mockRestore();+ agentRevisionSpy.mockRestore();for (const key of driverResolutionEnvKeys) {const value = originalDriverResolutionEnv.get(key);if (value === undefined) {@@ -1270,6 +1276,8 @@ describe('computer mcp integration', () => {y: 20,}, { sessionId: 'session-style-recreated' });await cleanupComputerDriverSession('session-style-recreated');+ mcpCallToolMock.mockResolvedValueOnce({ structuredContent: { ok: true, clicked: true } });+ await callComputerDriverTool('get_window_state', { pid: 123, window_id: 7 }, { sessionId: 'session-style-recreated' });await callComputerDriverTool('click', {pid: 123,window_id: 7,@@ -1284,6 +1292,7 @@ describe('computer mcp integration', () => {'end_session','set_agent_cursor_motion','set_agent_cursor_style',+ 'get_window_state','click',]);expect(mcpConnectMock).toHaveBeenCalledTimes(2);@@ -1383,7 +1392,7 @@ describe('computer mcp integration', () => {});it.each([- ['darwin', undefined, 'foreground'],+ ['darwin', undefined, 'background'],['darwin', 'background', 'background'],['darwin', 'foreground', 'foreground'],['win32', undefined, undefined],@@ -1466,8 +1475,18 @@ describe('computer mcp integration', () => {expect(mcpCallToolMock).toHaveBeenCalledTimes(1);});- it('does not escalate or repeat an explicitly refused background drag', async () => {+ it.each([undefined, 'background'] as const)('does not escalate or repeat a refused background drag (%s)', async (mode) => {setPlatform('darwin');+ mcpListToolsMock.mockResolvedValue({+ tools: [{+ name: 'drag',+ inputSchema: {+ type: 'object',+ properties: { delivery_mode: {} },+ additionalProperties: true,+ },+ }],+ });mcpCallToolMock.mockImplementation(async ({ name }) =>name === 'drag'? {@@ -1487,7 +1506,7 @@ describe('computer mcp integration', () => {from_y: 1,to_x: 5,to_y: 5,- delivery_mode: 'background',+ ...(mode ? { delivery_mode: mode } : {}),},{ sessionId: 'explicit-background' },),@@ -1598,6 +1617,125 @@ describe('computer mcp integration', () => {expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);});+ it.each([false, true])('invalidates other tasks after Agent input, including session recreation=%s', async (recreate) => {+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true } });+ const target = { pid: 123, window_id: 7 };+ const a = { sessionId: 'agent-a' }, b = { sessionId: 'agent-b' };+ await callComputerDriverTool('get_window_state', target, a);+ await callComputerDriverTool('get_window_state', target, b);+ await callComputerDriverTool('click', { ...target, x: 1, y: 1 }, b);+ if (recreate) await cleanupComputerDriverSession(a.sessionId);+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, a))+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });+ await callComputerDriverTool('get_window_state', target, a);+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, a)).resolves.toBeDefined();+ // Own input does not invalidate a task's next primitive.+ await expect(callComputerDriverTool('type_text', { ...target, text: 'hello' }, a)).resolves.toBeDefined();+ });++ it.each(['read-first', 'input-first'] as const)('does not authorize observations overlapping Agent input: %s', async (order) => {+ const target = { pid: 123, window_id: 7 };+ const read = createDeferred<unknown>();+ const input = createDeferred<unknown>();+ mcpCallToolMock.mockImplementation(({ name }) => name === 'get_window_state' ? read.promise+ : name === 'click' ? input.promise : { structuredContent: { ok: true } });+ const observe = () => callComputerDriverTool('get_window_state', target, { sessionId: 'reader' });+ const act = () => callComputerDriverTool('click', { ...target, x: 1, y: 1 }, { sessionId: 'writer' });+ const first = order === 'read-first' ? observe() : act();+ await waitForCondition(() => mcpCallToolMock.mock.calls.some(([call]) => call.name === (order === 'read-first' ? 'get_window_state' : 'click')));+ const second = order === 'read-first' ? act() : observe();+ await waitForCondition(() => mcpCallToolMock.mock.calls.some(([call]) => call.name === 'click')+ && mcpCallToolMock.mock.calls.some(([call]) => call.name === 'get_window_state'));+ input.resolve({ structuredContent: { ok: true } });+ read.resolve({ structuredContent: { ok: true } });+ await Promise.all([first, second]);+ await expect(callComputerDriverTool('click', { ...target, x: 1, y: 1 }, { sessionId: 'reader' }))+ .rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });+ });++ it('keeps text chunks together while another Agent waits', async () => {+ const firstChunk = createDeferred<unknown>();+ const events: string[] = [];+ mcpCallToolMock.mockImplementation(({ name }) => {+ if (name === 'type_text' || name === 'launch_app') events.push(name);+ if (name === 'type_text' && events.length === 1) return firstChunk.promise;+ return { structuredContent: { ok: true, effect: 'confirmed' } };+ });+ const typing = callComputerDriverTool('type_text', { pid: 123, window_id: 7, text: 'a'.repeat(850) }, { sessionId: 'typing' });+ await waitForCondition(() => events.length === 1);+ const launch = callComputerDriverTool('launch_app', { name: 'Calculator' }, { sessionId: 'launch' });+ await waitForCondition(() => transportCtorMock.mock.calls.length === 2);+ expect(events).toEqual(['type_text']);+ firstChunk.resolve({ structuredContent: { ok: true, effect: 'confirmed' } });+ await Promise.all([typing, launch]);+ expect(events).toEqual(['type_text', 'type_text', 'type_text', 'launch_app']);+ });++ it('holds ownership through failed-input teardown before admitting the next Agent', async () => {+ const input = createDeferred<unknown>();+ const teardown = createDeferred<unknown>();+ const events: string[] = [];+ mcpCallToolMock.mockImplementation(({ name }) => {+ events.push(name);+ if (name === 'type_text') return input.promise;+ if (name === 'end_session') return teardown.promise;+ return { structuredContent: { ok: true } };+ });+ const active = callComputerDriverTool('type_text', { pid: 123, text: 'hello' }, { sessionId: 'failing' });+ const rejected = expect(active).rejects.toMatchObject({ code: 'ACTION_OUTCOME_UNKNOWN' });+ await waitForCondition(() => events.includes('type_text'));+ const next = callComputerDriverTool('launch_app', { name: 'Calculator' }, { sessionId: 'next' });+ input.reject(new Error('transport closed'));+ await waitForCondition(() => events.includes('end_session'));+ expect(events).not.toContain('launch_app');+ teardown.resolve({ structuredContent: { ok: true } });+ await Promise.all([rejected, next]);+ expect(events.filter((name) => ['type_text', 'end_session', 'launch_app'].includes(name)))+ .toEqual(['type_text', 'end_session', 'launch_app']);+ });++ it('preserves the completed prefix and uncertain chunk after a typing transport failure', async () => {+ let chunks = 0;+ mcpCallToolMock.mockImplementation(({ name }) => {+ if (name === 'type_text' && ++chunks === 2) throw new Error('transport closed');+ return { structuredContent: { ok: true, effect: 'confirmed' } };+ });+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'a'.repeat(850) }, { sessionId: 'partial' }))+ .rejects.toMatchObject({ code: 'ACTION_OUTCOME_UNKNOWN', outcomeUnknown: true,+ inputProgress: { completed_chars: 400, attempted_chars: 400, remaining_chars: 50 } });+ expect(chunks).toBe(2);+ });++ it('refuses an action prepared before another task changed the desktop', async () => {+ const startup = createDeferred<void>();+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: true } });+ const target = { pid: 123, window_id: 7 };+ mcpConnectMock.mockReturnValueOnce(startup.promise);+ const oldAction = callComputerDriverTool('click', { ...target, x: 1, y: 1 }, { sessionId: 'slow-start' });+ const rejected = expect(oldAction).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });+ await callComputerDriverTool('launch_app', { name: 'Calculator' }, { sessionId: 'other' });+ startup.resolve();+ await rejected;+ expect(mcpCallToolMock.mock.calls.some(([call]) => call.name === 'click')).toBe(false);+ });++ it('cancels a queued same-session call without closing the active driver', async () => {+ const pending = createDeferred<unknown>();+ const controller = new AbortController();+ mcpCallToolMock.mockImplementation(({ name }) => name === 'type_text' ? pending.promise : { structuredContent: { ok: true } });+ const active = callComputerDriverTool('type_text', { pid: 123, text: 'hello' }, { sessionId: 'shared' });+ await waitForCondition(() => mcpCallToolMock.mock.calls.some(([call]) => call.name === 'type_text'));+ const queued = callComputerDriverTool('launch_app', { name: 'Calculator' }, { sessionId: 'shared', signal: controller.signal });+ const rejected = expect(queued).rejects.toMatchObject({ code: 'REQUEST_CANCELLED', outcomeUnknown: false });+ await new Promise((resolve) => setTimeout(resolve, 0));+ controller.abort();+ await rejected;+ expect(mcpCloseMock).not.toHaveBeenCalled();+ expect(mcpCallToolMock.mock.calls.some(([call]) => call.name === 'launch_app' || call.name === 'end_session')).toBe(false);+ pending.resolve({ structuredContent: { ok: true } });+ await active;+ });+it('yields to remote input between text chunks and requires a fresh target before resuming', async () => {vi.useFakeTimers();const human = new HumanDesktopInput();@@ -1610,7 +1748,8 @@ describe('computer mcp integration', () => {return { structuredContent: { ok: true, effect: 'confirmed' } };});await expect(callComputerDriverTool('type_text', { ...target, text: 'a'.repeat(850) }, context))- .rejects.toThrow('Agent yielded');+ .rejects.toMatchObject({ code: 'DESKTOP_INPUT_YIELDED', outcomeUnknown: true,+ inputProgress: { completed_chars: 400, attempted_chars: 0, remaining_chars: 450 } });expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);await batch!.ready;batch!.complete();@@ -1909,7 +2048,8 @@ describe('computer mcp integration', () => {await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 10, y: 20 }, {sessionId: 'setup-cancel', signal: controller.signal,})).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' });- expect(mcpCallToolMock.mock.calls.map(([call]) => call.name)).toEqual(['set_agent_cursor_motion', 'end_session']);+ expect(mcpCallToolMock.mock.calls.map(([call]) => call.name)).toEqual(['set_agent_cursor_motion']);+ expect(mcpCloseMock).not.toHaveBeenCalled();});it('negotiates paginated tools once per connection and fails unsupported actions locally', async () => {diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.tsindex 2d3dea9a24..432486768c 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 { desktopInputRevision, hasRemoteDesktopInput, isHumanDesktopInputActive, withAgentDesktopInput } from '../remote-desktop/inputOwnership';+import { agentDesktopInputRevision, desktopInputRevision, hasRemoteDesktopInput, isAgentDesktopInputActive, isHumanDesktopInputActive, withAgentDesktopInput } from '../remote-desktop/inputOwnership';import os from 'node:os';import { randomUUID } from 'node:crypto';import { spawn, type ChildProcess } from 'node:child_process';@@ -2229,8 +2229,9 @@ async function callCuaMcpTool(args.delivery_mode === undefined &&Object.hasOwn(entry.toolSchemas.get(name)?.properties ?? {}, 'delivery_mode')) {- // Older drivers may not accept delivery_mode at all; adapt only advertised capabilities.- args = { ...args, delivery_mode: 'foreground' };+ // Never implicitly take foreground input from the person using this Mac.+ // Older drivers may not accept delivery_mode; adapt only advertised capabilities.+ args = { ...args, delivery_mode: 'background' };}const driverArgs = adaptComputerDriverArgs(name, args, entry.toolSchemas);const result = await withTimeout(@@ -2280,23 +2281,26 @@ async function callCuaMcpToolWithTypeTextChunks(signal?: AbortSignal,assertActive: () => void = () => {},settleFailedInput: () => Promise<void> = async () => {},+ onDispatch: () => void = () => {},): 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;+ const dispatch = async (input: Record<string, unknown>) => {+ signal?.throwIfAborted();+ assertActive();+ onDispatch();+ try {+ return await callCuaMcpTool(entry, name, input, timeoutMs, signal);+ } catch (error) {+ // Cancellation/timeout is not proof that native input stopped. Keep+ // all competing input waiting through the existing driver-session teardown.+ if (getComputerTool(name)?.readOnly !== true+ && (signal?.aborted || shouldCleanupCuaMcpSessionAfterError(error))) {+ await settleFailedInput();}- });+ throw error;+ }+ };if (name !== 'type_text' || typeof args.text !== 'string') {return dispatch(args);}@@ -2315,9 +2319,24 @@ async function callCuaMcpToolWithTypeTextChunks(let processedChunks = 0;for (let index = 0; index < chunks.length; index += 1) {const chunk = chunks[index];- signal?.throwIfAborted();- assertActive();- lastResult = await dispatch({ ...args, text: chunk });+ let attempted = false;+ try {+ signal?.throwIfAborted();+ assertActive();+ attempted = true;+ lastResult = await dispatch({ ...args, text: chunk });+ } catch (error) {+ // A completed prefix must survive cancellation/yield/transport errors.+ // Never encourage replay of the whole string or guess the in-flight chunk.+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {+ outcomeUnknown: attempted || inserted > 0,+ inputProgress: {+ completed_chars: inserted,+ attempted_chars: attempted ? Array.from(chunk).length : 0,+ remaining_chars: Array.from(chunks.slice(index + (attempted ? 1 : 0)).join('')).length,+ },+ });+ }const resultObject = objectValue(lastResult);processedChunks += 1;const outcome = computerResultOutcome(name, lastResult);@@ -3420,9 +3439,9 @@ 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 | symbol> }>();+// Human input and other tasks invalidate observed targets after ownership ends.+// Own sequential primitives retain their observations; overlapping reads do not.+const inputObservations = new Map<string, { windows: Map<string, number | symbol>; requiresObservation: boolean }>();export async function callComputerDriverTool(name: ComputerMcpToolName,@@ -3433,16 +3452,18 @@ export async function callComputerDriverTool(const revision = desktopInputRevision();let observations = sessionId ? inputObservations.get(sessionId) : undefined;if (sessionId && !observations) {- observations = { windows: new Map() };+ observations = { windows: new Map(), requiresObservation: agentDesktopInputRevision() > 0 };inputObservations.set(sessionId, observations);}const window = `${args.pid}:${args.window_id}`;if (getComputerTool(name)?.readOnly === true) {- const startedIdle = !isHumanDesktopInputActive();+ const agentRevision = agentDesktopInputRevision();+ const startedIdle = !isHumanDesktopInputActive() && !isAgentDesktopInputActive();const explicitObservation = name === 'get_window_state' && context?.observationPurpose !== 'recovery';const observation = Symbol('pending observation');const app = `${args.pid}:undefined`;if (explicitObservation) {+ if (observations) observations.requiresObservation = true;// Revoke old permission and prevent an older concurrent read from// restoring it after this read fails or is cancelled.observations?.windows.set(window, observation);@@ -3451,7 +3472,8 @@ export async function callComputerDriverTool(const result = await callComputerDriverToolImpl(name, args, context);if (explicitObservation && startedIdle && !context?.signal?.aborted&& !isUnavailableWindowObservation(result, args) && computerResultOutcome(name, result).ok- && revision === desktopInputRevision() && !isHumanDesktopInputActive()) {+ && revision === desktopInputRevision() && !isHumanDesktopInputActive()+ && agentRevision === agentDesktopInputRevision() && !isAgentDesktopInputActive()) {if (observations?.windows.get(window) === observation) 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.@@ -3460,7 +3482,7 @@ export async function callComputerDriverTool(return result;}// Preparation can be slow and does not inject input. Reserve ownership only- // around each driver primitive, and recheck this observation before dispatch.+ // around the logical input, and recheck this observation after queue admission.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');@@ -3468,12 +3490,12 @@ export async function callComputerDriverTool(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');}+ if (args.pid !== undefined && observations && (revision > 0 || observations.requiresObservation)+ && observations.windows.get(window) !== revision) {+ throw new ComputerDriverError('Desktop input or a newer observation invalidated this target. Get fresh state for this window before acting again.', 'STALE_SNAPSHOT');+ }};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);}@@ -3514,10 +3536,20 @@ async function callComputerDriverToolImpl(const entry = await getCuaMcpSession(sessionId, signal);const driverArgs = applyDriverSessionArgs(name, normalizedArgs, entry.driverSessionId, entry.toolSchemas);const timeoutMs = getCuaMcpToolTimeoutMs(name);+ let inputDispatched = false;try {await initializeDefaultCursorStyle(name, driverArgs, entry, entry.driverSessionId, sessionCloseVersion, signal, assertActive);- const result = await callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs, signal, assertActive,- () => cleanupCuaMcpSessionAfterError(sessionId, entry));+ const invoke = () => callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs, signal, assertActive,+ () => cleanupCuaMcpSessionAfterError(sessionId, entry), () => { inputDispatched = true; });+ const result = getComputerTool(name)?.readOnly === true ? await invoke()+ : await withAgentDesktopInput(() => {+ for (const [otherSessionId, observation] of inputObservations) {+ if (otherSessionId === sessionId) continue;+ observation.requiresObservation = true;+ observation.windows.clear();+ }+ return invoke();+ }, { signal, assertCurrent: assertActive });return name === 'list_windows' ? enrichAndFilterListWindowsResult(result, rawArgs) : result;} catch (err) {logger.warn('cua-driver MCP tool call failed', {@@ -3527,14 +3559,19 @@ async function callComputerDriverToolImpl(error: err instanceof Error ? err.message : String(err),});if (signal?.aborted) {- await cleanupCuaMcpSessionAfterError(sessionId, entry).catch(() => undefined);- throw new ComputerDriverError('Computer Use cancelled. An action already dispatched may have taken effect; observe before acting again.', 'REQUEST_CANCELLED', getComputerTool(name)?.readOnly !== true);+ if (inputDispatched) await cleanupCuaMcpSessionAfterError(sessionId, entry).catch(() => undefined);+ throw Object.assign(new ComputerDriverError(+ inputDispatched ? 'Computer Use cancelled. An action already dispatched may have taken effect; observe before acting again.'+ : 'Computer Use cancelled before dispatch; no input was sent.',+ 'REQUEST_CANCELLED', inputDispatched && getComputerTool(name)?.readOnly !== true),+ { inputProgress: (err as { inputProgress?: unknown })?.inputProgress });}if (shouldCleanupCuaMcpSessionAfterError(err)) {const cleanup = cleanupCuaMcpSessionAfterError(sessionId, entry);if (getComputerTool(name)?.readOnly !== true) {await cleanup.catch(() => undefined);- throw new ComputerDriverError('Driver connection failed during an action. Its outcome is unknown; the action was not replayed. Take fresh state before continuing.', 'ACTION_OUTCOME_UNKNOWN', true);+ throw Object.assign(new ComputerDriverError('Driver connection failed during an action. Its outcome is unknown; the action was not replayed. Take fresh state before continuing.', 'ACTION_OUTCOME_UNKNOWN', true),+ { inputProgress: (err as { inputProgress?: unknown })?.inputProgress });}if (shouldUseCliFallbackAfterError(name, err)) {try {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.tsindex 7e264686d4..9ba7c98d1e 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputOwnership.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { HumanDesktopInput, HUMAN_INPUT_QUIET_MS, withAgentDesktopInput } from '../inputOwnership';+import { AGENT_INPUT_WAIT_MS, HumanDesktopInput, HUMAN_INPUT_QUIET_MS, withAgentDesktopInput } from '../inputOwnership';const humans: HumanDesktopInput[] = [];const human = () => {@@ -104,12 +104,64 @@ describe('remote input yields only during actual interaction', () => {});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');+ let finish!: () => void;+ const events: string[] = [];+ const first = withAgentDesktopInput(async () => {+ await new Promise<void>((resolve) => { finish = resolve; });+ throw new Error('failed');+ });+ const rejected = expect(first).rejects.toThrow('failed');+ const second = withAgentDesktopInput(async () => { events.push('second'); });+ const third = withAgentDesktopInput(async () => { events.push('third'); });+ expect(events).toEqual([]);+ finish();+ await Promise.all([rejected, second, third]);+ expect(events).toEqual(['second', 'third']);await expect(agent()).resolves.toBe('done');});++ it.each(['cancel', 'timeout'] as const)('removes a waiter on %s without releasing active input', async (mode) => {+ vi.useFakeTimers();+ let finish!: () => void;+ const active = withAgentDesktopInput(() => new Promise<void>((resolve) => { finish = resolve; }));+ const controller = new AbortController();+ const dispatch = vi.fn();+ const waiting = withAgentDesktopInput(dispatch, { signal: controller.signal });+ const rejected = expect(waiting).rejects.toMatchObject({ code: mode === 'cancel' ? 'REQUEST_CANCELLED' : 'DESKTOP_INPUT_BUSY' });+ if (mode === 'cancel') controller.abort();+ else await vi.advanceTimersByTimeAsync(AGENT_INPUT_WAIT_MS);+ await rejected;+ const next = vi.fn();+ const tail = withAgentDesktopInput(next);+ expect(next).not.toHaveBeenCalled();+ finish();+ await Promise.all([active, tail]);+ expect(dispatch).not.toHaveBeenCalled();+ expect(next).toHaveBeenCalledOnce();+ });++ it('revalidates queued work and drains past a refused waiter', async () => {+ let finish!: () => void;+ const active = withAgentDesktopInput(() => new Promise<void>((resolve) => { finish = resolve; }));+ const dispatch = vi.fn();+ const stale = withAgentDesktopInput(dispatch, { assertCurrent: () => { throw new Error('stale'); } });+ const rejected = expect(stale).rejects.toThrow('stale');+ const tail = agent();+ finish();+ await Promise.all([active, rejected, tail]);+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('gives human input priority over already-queued Agent work', async () => {+ let finish!: () => void;+ const active = withAgentDesktopInput(() => new Promise<void>((resolve) => { finish = resolve; }));+ const dispatch = vi.fn();+ const waiting = withAgentDesktopInput(dispatch);+ const rejected = expect(waiting).rejects.toMatchObject({ code: 'DESKTOP_INPUT_BUSY' });+ const batch = human().begin([{ kind: 'text', text: 'human' }]);+ finish();+ await Promise.all([active, rejected, batch.ready]);+ batch.complete();+ expect(dispatch).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/remote-desktop/inputOwnership.ts b/apps/desktop/src/main/remote-desktop/inputOwnership.tsindex 354012f6c2..3532a43016 100644--- a/apps/desktop/src/main/remote-desktop/inputOwnership.ts+++ b/apps/desktop/src/main/remote-desktop/inputOwnership.ts@@ -3,9 +3,14 @@ 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>>();+const waiters: Array<() => void> = [];let revision = 0;+let agentRevision = 0;export const HUMAN_INPUT_QUIET_MS = 300;+export const AGENT_INPUT_WAIT_MS = 5_000;export const desktopInputRevision = (): number => revision;+export const agentDesktopInputRevision = (): number => agentRevision;+export const isAgentDesktopInputActive = (): boolean => actions.size > 0;export const hasRemoteDesktopInput = (): boolean => humans.size > 0;export const isHumanDesktopInputActive = (): boolean => [...humans].some((human) => human.busy);@@ -63,26 +68,65 @@ export class HumanDesktopInput {}}-export async function withAgentDesktopInput<T>(+function inputError(code: string, message: string): Error & { code: string } {+ return Object.assign(new Error(message), { code });+}++/** FIFO admission for one logical input (including all of its text chunks). */+export function withAgentDesktopInput<T>(+ run: (assertCurrent: () => void) => Promise<T>,+ options: { signal?: AbortSignal; assertCurrent?: () => void } = {},+): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const remove = () => {+ if (timer) clearTimeout(timer);+ options.signal?.removeEventListener('abort', cancel);+ const index = waiters.indexOf(start);+ if (index >= 0) waiters.splice(index, 1);+ };+ const cancel = () => {+ remove();+ reject(inputError('REQUEST_CANCELLED', 'Computer Use cancelled while waiting; no input was dispatched.'));+ };+ const start = () => {+ remove();+ if (options.signal?.aborted) return cancel();+ void runOwnedInput(run, options.assertCurrent).then(resolve, reject);+ };+ if (options.signal?.aborted) return cancel();+ if (isHumanDesktopInputActive() || actions.size === 0) return start();+ waiters.push(start);+ options.signal?.addEventListener('abort', cancel, { once: true });+ timer = setTimeout(() => {+ remove();+ reject(inputError('DESKTOP_INPUT_BUSY', 'Another Agent input is still finishing. No input was dispatched; get fresh window state before retrying.'));+ }, AGENT_INPUT_WAIT_MS);+ });+}++async function runOwnedInput<T>(run: (assertCurrent: () => void) => Promise<T>,+ validate?: () => void,): Promise<T> {if (isHumanDesktopInputActive()) {- throw new Error(+ throw inputError('DESKTOP_INPUT_BUSY','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.');+ // Validate after waiting, atomically with ownership acquisition.+ validate?.();const startedAt = revision;let finish!: () => void;const done = new Promise<void>((resolve) => {finish = resolve;});actions.add(done);+ agentRevision++;try {return await run(() => {if (revision !== startedAt) {- throw new Error(+ throw inputError('DESKTOP_INPUT_YIELDED','Remote desktop input arrived. Agent yielded before further input; previous input may have completed. Get fresh window state before continuing.',);}@@ -90,5 +134,7 @@ export async function withAgentDesktopInput<T>(} finally {actions.delete(done);finish();+ // A refused waiter does not own input; keep draining until one does.+ while (actions.size === 0 && waiters.length > 0) waiters.shift()!();}}diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex 078258df20..d2b9741319 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -376,6 +376,19 @@ reads revoke prior permission, and older concurrent reads cannot restore it.Empty connectionheartbeats do not claim input ownership.+Agent inputs in the same Cindy process share FIFO admission with a cancellable+five-second wait (`DESKTOP_INPUT_BUSY` on expiry). A logical text input keeps its+place across chunks; human input still preempts at a chunk boundary. The host+rechecks cancellation, session lifetime and observation freshness after waiting,+before dispatch. Input from another task invalidates prior observations, including+pending reads; captures overlapping any Agent input cannot authorize later actions.+New or recreated task sessions must observe after prior Agent input as well.+Interrupted multi-chunk text reports completed, attempted and remaining character+counts without replaying the prefix. Timeout/cancellation during native input keeps+ownership until driver teardown settles. See+[`inputOwnership.ts`](../apps/desktop/src/main/remote-desktop/inputOwnership.ts)+and the [Computer Use regression tests](../apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts).+The native macOS/Windows helper acknowledges a batch only after posting all itsevents; the Windows service forwards that acknowledgement. Main retains ownershipthrough native shutdown when stopping held input. The guard coordinates only@@ -383,6 +396,15 @@ remote input and CUA calls in this Cindy process: physical keyboard/mouse input,other applications, and separate Cindy processes are outside it. Native eventposting is not proof that an application has finished handling those events.+On macOS, a drag without `delivery_mode` uses `background` when the driver+advertises that parameter. A background refusal is returned without an automatic+foreground retry. Explicit `foreground` remains available, but agents must+coordinate desktop use with the person before requesting it. Legacy drivers+without the parameter retain their native behavior. Background delivery itself+does not guarantee focus isolation: the driver may temporarily change application+or window focus. Cindy does not currently verify restoration of the original+focused window or text field, and does not force focus back after an action.+## Wayland capture lifetimeOn Hyprland with the system `/usr/bin/grim` executable, Cindy uses native screencopydiff --git a/packages/lizi-mcps/src/computer/recovery.test.ts b/packages/lizi-mcps/src/computer/recovery.test.tsindex 6c6273a406..4e761ebe01 100644--- a/packages/lizi-mcps/src/computer/recovery.test.ts+++ b/packages/lizi-mcps/src/computer/recovery.test.ts@@ -33,6 +33,22 @@ async function harness(dispatch: ComputerMcpDeps["callTool"]) {}describe("bounded Computer Use recovery", () => {+ it("preserves interrupted typing progress without replaying input", async () => {+ const inputProgress = { completed_chars: 400, attempted_chars: 0, remaining_chars: 450 };+ const dispatch = vi.fn(async (name: string) => {+ if (name === "type_text") throw Object.assign(new Error("Agent yielded"), {+ code: "DESKTOP_INPUT_YIELDED", outcomeUnknown: true, inputProgress,+ });+ return { ok: true };+ });+ const call = await harness(dispatch);+ expect(await call("type_text", { pid: 1, window_id: 2, text: "hello" })).toMatchObject({+ ok: false, errorCode: "DESKTOP_INPUT_YIELDED",+ data: { outcome_unknown: true, input_progress: inputProgress },+ });+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual(["type_text", "get_window_state"]);+ });+it("observes unknown input exactly once, preserving uncertainty and session provenance", async () => {const raw = { effect: "unverifiable", remaining_chars: 450 };const dispatch = vi.fn(async (name: string) =>diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.tsindex 637c7fa286..15b11cc806 100644--- a/packages/lizi-mcps/src/computer/server.ts+++ b/packages/lizi-mcps/src/computer/server.ts@@ -792,6 +792,9 @@ export function createComputerMcpServer(: {}),data: {message: err instanceof Error ? err.message : String(err),+ ...((err as { inputProgress?: unknown })?.inputProgress+ ? { input_progress: (err as { inputProgress: unknown }).inputProgress }+ : {}),...((err as { outcomeUnknown?: boolean })?.outcomeUnknown? { outcome_unknown: true, next_step: "fresh_state" }: {}),diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.tsindex 508f116ac3..c770f226f7 100644--- a/packages/lizi-mcps/src/computer/tools.ts+++ b/packages/lizi-mcps/src/computer/tools.ts@@ -228,7 +228,7 @@ const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [{name: "drag",description:- "Drag from one window-local coordinate to another. Use after get_window_state or zoom. On macOS, omitted delivery_mode defaults to foreground and may bring the target forward; explicit background is never escalated or retried.",+ 'Drag from one window-local coordinate to another. Use after get_window_state or zoom. On macOS drivers supporting delivery_mode, omitted mode defaults to background; unsupported background drag returns an error without automatic foreground escalation or retry. Explicit foreground delivery may interrupt the user\'s keyboard and mouse input; coordinate desktop use with the user before requesting it. Background delivery is not a guarantee of focus isolation.',inputShape: {pid: z.number().int().positive(),window_id: z.number().int().nonnegative().optional(),