Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 截屏首帧不再被鼠标读取和过短等待拖垮 (#6112)
Dash491c7c69e023
diff --git a/apps/desktop/native/remote-desktop/macos-capture.m b/apps/desktop/native/remote-desktop/macos-capture.mindex 615949bdf1..944293f2d8 100644--- a/apps/desktop/native/remote-desktop/macos-capture.m+++ b/apps/desktop/native/remote-desktop/macos-capture.m@@ -14,6 +14,7 @@#import <time.h>static _Atomic(time_t) lastRequest;+static atomic_bool awaitingFrame;// Compatibility capture for an already logged-in macOS session. These public// legacy symbols are unavailable at compile time in SDK 15+, and may eventually@@ -181,15 +182,28 @@ int main(int argc, const char *argv[]) {__block NSData *latest = nil;__block BOOL requested = NO;atomic_store(&lastRequest, time(NULL));+ // The first system cursor read can block on WindowServer for many seconds.+ // Frames never wait for it: each reply carries the latest completed read+ // (null until one finishes) and starts the next read on the main queue.+ __block NSDictionary *cursor = nil;+ __block BOOL cursorReading = NO;+ void (^refreshCursor)(void) = ^{+ if (!separateCursor || cursorReading) return;+ cursorReading = YES;+ dispatch_async(dispatch_get_main_queue(), ^{+ NSDictionary *value = readCursor(onlyWindow ? windowBounds(onlyWindow) : CGDisplayBounds(display));+ dispatch_async(queue, ^{+ cursor = value;+ cursorReading = NO;+ });+ });+ };void (^reply)(void) = ^{if (!requested || !latest) return;requested = NO;NSData *data;if (overlay) {- __block NSDictionary *cursor = nil;- if (separateCursor) dispatch_sync(dispatch_get_main_queue(), ^{- cursor = readCursor(onlyWindow ? windowBounds(onlyWindow) : CGDisplayBounds(display));- });+ refreshCursor();NSDictionary *frame = @{@"jpeg": [latest base64EncodedStringWithOptions:0], @"cursor": cursor ?: [NSNull null]};NSMutableData *line = [[NSJSONSerialization dataWithJSONObject:frame options:0 error:NULL] mutableCopy];[line appendBytes:"\n" length:1];@@ -205,6 +219,7 @@ int main(int argc, const char *argv[]) {if (count <= 0) _exit(0);bytes += count; remaining -= count;}+ atomic_store(&awaitingFrame, false);};FrameHandler receiveFrame = ^(int32_t status, uint64_t timestamp, IOSurfaceRef surface, const void *update) {@autoreleasepool {@@ -306,14 +321,18 @@ int main(int argc, const char *argv[]) {(__bridge CFDictionaryRef)@{(__bridge NSString *)*intervalKey: @(1.0/fps), (__bridge NSString *)*cursorKey: separateCursor ? @NO : @YES}, queue, receiveFrame);if (!stream || start(stream) != kCGErrorSuccess) return 5;}+ if (overlay) dispatch_async(queue, refreshCursor);signal(SIGPIPE, SIG_IGN);// stdin is a private parent pipe: one byte asks for one latest frame. EOF// and a stalled parent both terminate capture without retaining any pixels.+ // A parent still waiting for its first frame gets a longer bound; it+ // normally gives up and kills this helper first.dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{char byte;while (read(STDIN_FILENO, &byte, 1) == 1) {if (byte != 'f') _exit(2);atomic_store(&lastRequest, time(NULL));+ atomic_store(&awaitingFrame, true);dispatch_async(queue, ^{ requested = YES; reply(); });}_exit(0);@@ -321,7 +340,9 @@ int main(int argc, const char *argv[]) {dispatch_source_t watchdog = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));dispatch_source_set_timer(watchdog, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0);dispatch_source_set_event_handler(watchdog, ^{- if (time(NULL) - atomic_load(&lastRequest) > 5) _exit(0);+ // A pending frame extends the idle limit beyond the parent's cold-start+ // wait, but never indefinitely: a parent that stopped reading is stalled.+ if (time(NULL) - atomic_load(&lastRequest) > (atomic_load(&awaitingFrame) ? 15 : 5)) _exit(0);});dispatch_resume(watchdog);dispatch_main();diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxNativeCapture.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxNativeCapture.test.tsindex 48bdc7ac33..11b8dea65f 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxNativeCapture.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxNativeCapture.test.ts@@ -1,5 +1,6 @@import { EventEmitter } from 'node:events';import { PassThrough } from 'node:stream';+import { REMOTE_DESKTOP_OFFER_BUDGET } from '@cindy/device-link';import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({ spawn: vi.fn(), binary: vi.fn() }));vi.mock('node:child_process', () => ({ spawn: h.spawn, execFile: vi.fn() }));@@ -78,7 +79,10 @@ it('times out a stalled child and rejects unsupported display requests', async (expect(h.binary).not.toHaveBeenCalled();vi.useFakeTimers();const pending = owner.frame('wayland-portal');+ // A starting helper keeps the cold-start budget instead of the steady-state bound.await vi.advanceTimersByTimeAsync(3000);+ expect(child.kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_OFFER_BUDGET.captureReadyMs - 3000);await expect(pending).resolves.toBeNull();expect(child.kill).toHaveBeenCalledOnce();});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/macNativeCapture.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/macNativeCapture.test.tsindex ac19595191..2db2adcfce 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/macNativeCapture.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/macNativeCapture.test.ts@@ -1,5 +1,6 @@import { EventEmitter } from 'node:events';import { PassThrough } from 'node:stream';+import { REMOTE_DESKTOP_OFFER_BUDGET } from '@cindy/device-link';import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({ spawn: vi.fn() }));vi.mock('node:child_process', () => ({ spawn: h.spawn, execFile: vi.fn() }));@@ -19,6 +20,8 @@ beforeEach(() => {afterEach(() => {owners.splice(0).forEach((o) => o.stop());vi.unstubAllGlobals();+ // A failed fake-timer case must not leave later cases waiting on frozen time.+ vi.useRealTimers();});function setup() {const child = Object.assign(new EventEmitter(), {@@ -61,6 +64,24 @@ it('accepts frames up to the tier budget and stops capture beyond it', async ()await expect(rejected).resolves.toBeNull();});+it('waits out a slow helper start but bounds later frames to the steady-state wait', async () => {+ vi.useFakeTimers();+ const { child, owner } = setup();+ const settings = { fps: 30, quality: 'auto', audio: false } as const;+ const frame = { jpeg: 'abcd', cursor: null };+ const first = owner.frame('1', true, settings);+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_OFFER_BUDGET.captureReadyMs - 1000);+ expect(child.kill).not.toHaveBeenCalled();+ child.stdout.write(JSON.stringify(frame) + '\n');+ await expect(first).resolves.toEqual(frame);++ const next = owner.frame('1', true, settings);+ await vi.advanceTimersByTimeAsync(3000);+ await expect(next).resolves.toBeNull();+ expect(child.kill).toHaveBeenCalledOnce();+ expect(h.spawn).toHaveBeenCalledOnce();+});+it('captures only the 代输入 window, never the display, and returns to the display after', async () => {const { owner } = setup();owner.setExcludedWindows([7, 8]);diff --git a/apps/desktop/src/main/remote-desktop/nativeCapture.ts b/apps/desktop/src/main/remote-desktop/nativeCapture.tsindex 78e3a4ab5b..8c2aeadf6d 100644--- a/apps/desktop/src/main/remote-desktop/nativeCapture.ts+++ b/apps/desktop/src/main/remote-desktop/nativeCapture.ts@@ -1,5 +1,6 @@import {isRemoteDesktopCursor,+ REMOTE_DESKTOP_OFFER_BUDGET,type RemoteDesktopCursorFrame,type RemoteDesktopVideoSettings,} from '@cindy/device-link';@@ -10,6 +11,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import { desktopVideoFramerate, desktopVideoProfile } from '../../shared/remoteDesktopQuality';+import { createLogger } from '../logger';import { openWindowsDesktopConnection, type WindowsDesktopConnection } from './windowsHost';import { decodeWindowsCursorFrame } from './windowsCursorFrame';@@ -17,8 +19,11 @@ import { resolveLinuxCaptureBinary } from './linuxCapture';import { WAYLAND_DISPLAY_ID } from './waylandCapture';import { linuxMonitor } from './linuxDesktop';+const log = createLogger('remote-desktop:native-capture');const exec = promisify(execFile);const name = 'cindy-macos-desktop-capture';+// A running helper answers within this; a fresh one may still be starting capture.+const FRAME_MS = 3000;let building: Promise<string> | null = null;async function binary(): Promise<string> {if (process.platform === 'linux') return resolveLinuxCaptureBinary();@@ -90,7 +95,10 @@ async function binary(): Promise<string> {* stream as the live view. Its own pixels only, whatever covers it; never the* display. Null when it cannot be taken. Nothing is written to disk.*/-export async function photographMacWindow(displayId: string, windowId: number): Promise<Buffer | null> {+export async function photographMacWindow(+ displayId: string,+ windowId: number,+): Promise<Buffer | null> {if (process.platform !== 'darwin' || !/^[0-9]{1,10}$/.test(displayId)) return null;if (!Number.isSafeInteger(windowId) || windowId <= 0 || windowId > 0xffff_ffff) return null;const executable = await binary();@@ -122,7 +130,10 @@ export async function photographMacWindow(displayId: string, windowId: number):if (end < 0) return;try {const frame = JSON.parse(text.slice(0, end)) as { jpeg?: unknown };- const jpeg = typeof frame.jpeg === 'string' && /^[A-Za-z0-9+/]+={0,2}$/.test(frame.jpeg) ? frame.jpeg : '';+ const jpeg =+ typeof frame.jpeg === 'string' && /^[A-Za-z0-9+/]+={0,2}$/.test(frame.jpeg)+ ? frame.jpeg+ : '';finish(jpeg ? Buffer.from(jpeg, 'base64') : null);} catch {finish(null);@@ -148,7 +159,8 @@ export class NativeDesktopCapture {private onlyWindow = '';/** 代输入 live view (macOS): capture just this window; null returns to the whole display. */setWindow(id: number | null): void {- const next = id && Number.isSafeInteger(id) && id > 0 && id <= 0xffff_ffff ? `window:${id}` : '';+ const next =+ id && Number.isSafeInteger(id) && id > 0 && id <= 0xffff_ffff ? `window:${id}` : '';if (next === this.onlyWindow) return;this.stop();this.onlyWindow = next;@@ -239,6 +251,7 @@ export class NativeDesktopCapture {this.busy = true;const generation = this.generation;try {+ const cold = !this.child;if (!this.child) {const output = linux && display !== WAYLAND_DISPLAY_ID ? await linuxMonitor(display) : null;const executable = await binary();@@ -276,6 +289,7 @@ export class NativeDesktopCapture {});child.on('exit', (code) => {if (this.child !== child) return;+ log.warn(`Native capture helper exited code=${code}`);this.cancel?.(new Error(code === 3 ? 'DESKTOP_SCREEN_PERMISSION_REQUIRED' : 'DESKTOP_VIDEO_UNAVAILABLE',@@ -331,7 +345,14 @@ export class NativeDesktopCapture {}finish(generation === this.generation ? jpeg : null);};- const timer = setTimeout(() => this.stop(), 3000);+ // Starting capture and the first cursor read can take seconds on a busy+ // or high-resolution Mac; only later frames use the steady-state bound.+ const waitMs = cold ? REMOTE_DESKTOP_OFFER_BUDGET.captureReadyMs : FRAME_MS;+ const timer = setTimeout(() => {+ if (generation === this.generation)+ log.warn(`Native capture produced no frame within ${waitMs}ms cold=${cold}`);+ this.stop();+ }, waitMs);this.cancel = (error) => finish(null, error);child.stdout.on('data', receive);child.stdin.write('f');