Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 按需启停手柄辅助进程 (#4748)
Dashd74abeee5a0f
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.tsindex 2022551727..812e3ce02d 100644--- a/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts@@ -9,6 +9,21 @@ function enabledSettings() {}describe('XboxGamepadController', () => {+ it('clears stale helper errors before the next enablement', () => {+ const controller = new XboxGamepadController({+ isCindyFrontmost: () => true,+ dispatch: vi.fn(),+ });+ controller.applySettings('xbox', enabledSettings());+ controller.handleHostMessage({ kind: 'host-error', message: 'helper failed' });+ controller.applySettings('xbox', createXboxGamepadDefaultSettings());+ controller.resetHostState();+ expect(controller.getState().devicePresent).toBeNull();+ expect(controller.getState().connectionStatus).toBe('disabled');+ controller.applySettings('xbox', enabledSettings());+ expect(controller.getState().connectionStatus).toBe('connecting');+ });+it.each(['lt', 'rt'] as const)('keeps Windows %s voice held across pressure dips until release',(trigger) => {diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.tsindex 7239837d3a..453c595dd8 100644--- a/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts@@ -44,6 +44,64 @@ async function flush(): Promise<void> {}describe('XboxGamepadHost', () => {+ it('does not start an idle helper for a probe', async () => {+ const spawnHelper = vi.fn(() => fakeChild());+ const host = createXboxGamepadHost(vi.fn(), {+ resolveHelperPath: async () => '/helper',+ spawnHelper,+ });+ host.probe();+ await flush();+ expect(spawnHelper).not.toHaveBeenCalled();+ });++ it('ignores old output and exit events after a quick stop and restart', async () => {+ vi.useFakeTimers();+ try {+ const first = fakeChild();+ const second = fakeChild();+ const onMessage = vi.fn();+ const spawnHelper = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);+ const host = createXboxGamepadHost(onMessage, {+ resolveHelperPath: async () => '/helper',+ spawnHelper,+ });+ host.start();+ await flush();+ (first.stdout as PassThrough).write('{"kind":');+ host.stop();+ host.start();+ await flush();+ (first.stdout as PassThrough).write('"presence","present":true}\n');+ first.emit('error', new Error('late error'));+ first.emit('exit', 0, null);+ expect(onMessage).not.toHaveBeenCalled();+ (second.stdout as PassThrough).write('{"kind":"presence","present":false}\n');+ expect(onMessage).toHaveBeenCalledExactlyOnceWith({ kind: 'presence', present: false });+ await vi.advanceTimersByTimeAsync(2_000);+ expect(spawnHelper).toHaveBeenCalledTimes(2);+ host.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it('ignores a path resolution failure after disabling the helper', async () => {+ let rejectResolve!: (error: Error) => void;+ const onMessage = vi.fn();+ const host = createXboxGamepadHost(onMessage, {+ resolveHelperPath: () =>+ new Promise((_, reject) => {+ rejectResolve = reject;+ }),+ });+ host.start();+ host.stop();+ rejectResolve(new Error('compile failed'));+ await flush();+ expect(onMessage).not.toHaveBeenCalled();+ });+it('resolves a packaged Windows helper rather than rejecting the platform', async () => {vi.stubGlobal('process', { ...process, resourcesPath: path.resolve('resources') });try {diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/index.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/index.test.tsnew file mode 100644index 0000000000..28011220ba--- /dev/null+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/index.test.ts@@ -0,0 +1,155 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ createXboxGamepadDefaultSettings,+ GAMEPAD_FAMILIES,+ XBOX_GAMEPAD_GET_STATE_CHANNEL,+ XBOX_GAMEPAD_SET_SETTINGS_CHANNEL,+ XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL,+ type GamepadFamily,+ type XboxGamepadSettings,+} from '../../../shared/xboxGamepad.js';+import type { InputDeviceHost } from '../../input-devices/registry.js';+import type { XboxGamepadHostMessage } from '../protocol.js';++const mocks = vi.hoisted(() => ({+ host: { start: vi.fn(), stop: vi.fn(), probe: vi.fn(), setSwitch2UsbWanted: vi.fn() },+ handlers: new Map<string, (...args: any[]) => any>(),+ devices: [] as InputDeviceHost[],+ settings: {} as Record<GamepadFamily, XboxGamepadSettings>,+ onMessage: null as ((message: XboxGamepadHostMessage) => void) | null,+}));+vi.mock('electron', () => ({+ app: { on: vi.fn() },+ BrowserWindow: { getAllWindows: () => [], getFocusedWindow: () => null },+ ipcMain: {+ handle: (channel: string, handler: (...args: any[]) => any) =>+ mocks.handlers.set(channel, handler),+ },+ shell: { openExternal: vi.fn() },+}));+vi.mock('../../logger.js', () => ({ createLogger: () => ({ debug: vi.fn(), warn: vi.fn() }) }));+vi.mock('../../deepLink.js', () => ({ getDeepLinkMainWindow: () => null }));+vi.mock('../../secondary-windows.js', () => ({ isSecondaryAppWindow: () => false }));+vi.mock('../../windowFocusClassifier.js', () => ({ isAppContentWindow: () => false }));+vi.mock('../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: vi.fn(),+ isTrustedAppRendererWindow: () => true,+}));+vi.mock('../../input-devices/registry.js', () => ({+ registerInputDevice: (device: InputDeviceHost) => mocks.devices.push(device),+}));+vi.mock('../host.js', () => ({+ createXboxGamepadHost: (callback: (message: XboxGamepadHostMessage) => void) => {+ mocks.onMessage = callback;+ return mocks.host;+ },+}));+vi.mock('../settingsStore.js', () => ({+ readXboxGamepadSettings: (family: GamepadFamily) => mocks.settings[family],+ writeXboxGamepadSettingsPatch: (family: GamepadFamily, patch: Partial<XboxGamepadSettings>) =>+ (mocks.settings[family] = { ...mocks.settings[family], ...patch }),+ resetXboxGamepadSettings: (family: GamepadFamily) => mocks.settings[family],+}));++function invoke(channel: string, ...args: unknown[]) {+ return mocks.handlers.get(channel)!({}, ...args);+}+async function register() {+ const api = await import('../index.js');+ api.registerXboxGamepadInputDevice();+ api.registerXboxGamepadSettingsIpc();+}++describe('gamepad helper demand', () => {+ beforeEach(() => {+ vi.resetModules();+ vi.clearAllMocks();+ vi.stubGlobal('process', { ...process, platform: 'win32' });+ mocks.handlers.clear();+ mocks.devices.length = 0;+ for (const family of GAMEPAD_FAMILIES)+ mocks.settings[family] = createXboxGamepadDefaultSettings();+ });+ afterEach(() => vi.unstubAllGlobals());++ it('does not start a helper when all accessories are disabled', async () => {+ await register();+ expect(mocks.host.start).not.toHaveBeenCalled();+ });++ it.each(GAMEPAD_FAMILIES)('starts for saved %s enablement', async (family) => {+ mocks.settings[family].deviceEnabled = true;+ await register();+ expect(mocks.host.start).toHaveBeenCalledTimes(1);+ });++ it('keeps the shared helper until the last enabled family is disabled', async () => {+ await register();+ invoke(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, 'xbox', { deviceEnabled: true });+ invoke(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, 'playstation', { deviceEnabled: true });+ invoke(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, 'xbox', { deviceEnabled: false });+ expect(mocks.host.start).toHaveBeenCalledTimes(1);+ expect(mocks.host.stop).not.toHaveBeenCalled();+ mocks.onMessage?.({+ kind: 'presence',+ family: 'playstation',+ present: true,+ name: 'DualSense',+ });+ invoke(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, 'playstation', { deviceEnabled: false });+ expect(mocks.host.stop).toHaveBeenCalledTimes(1);+ expect(invoke(XBOX_GAMEPAD_GET_STATE_CHANNEL).playstation).toMatchObject({+ devicePresent: null,+ deviceName: null,+ connectionStatus: 'disabled',+ });+ });++ it.each(['close', 'destroyed', 'render-process-gone'])(+ 'releases disabled preview on %s',+ async (ending) => {+ await register();+ const sender = Object.assign(new EventEmitter(), { id: 1 });+ const preview = mocks.handlers.get(XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL)!;+ preview({ sender }, { active: true, family: 'nintendo' });+ expect(mocks.host.start).toHaveBeenCalledTimes(1);+ expect(mocks.host.setSwitch2UsbWanted).toHaveBeenLastCalledWith(true);+ if (ending === 'close') preview({ sender }, false);+ else sender.emit(ending);+ expect(mocks.host.stop).toHaveBeenCalledTimes(1);+ expect(mocks.host.setSwitch2UsbWanted).toHaveBeenLastCalledWith(false);+ },+ );++ it('keeps an enabled helper after preview closes', async () => {+ mocks.settings.generic.deviceEnabled = true;+ await register();+ const sender = Object.assign(new EventEmitter(), { id: 1 });+ const preview = mocks.handlers.get(XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL)!;+ preview({ sender }, { active: true, family: 'generic' });+ preview({ sender }, false);+ expect(mocks.host.start).toHaveBeenCalledTimes(1);+ expect(mocks.host.stop).not.toHaveBeenCalled();+ });++ it('stops and resumes with task slots without changing saved settings', async () => {+ mocks.settings.nintendo.deviceEnabled = true;+ await register();+ for (const device of mocks.devices) device.suspendTaskSlots();+ expect(mocks.host.stop).toHaveBeenCalledTimes(1);+ expect(mocks.settings.nintendo.deviceEnabled).toBe(true);+ for (const device of mocks.devices) await device.resumeTaskSlots();+ expect(mocks.host.start).toHaveBeenCalledTimes(2);+ });++ it('does not restart during shutdown when the preview owner is destroyed', async () => {+ mocks.settings.xbox.deviceEnabled = true;+ await register();+ const sender = Object.assign(new EventEmitter(), { id: 1 });+ mocks.handlers.get(XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL)!({ sender }, true);+ for (const device of mocks.devices) await device.dispose();+ sender.emit('destroyed');+ expect(mocks.host.start).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/xbox-gamepad/controller.ts b/apps/desktop/src/main/xbox-gamepad/controller.tsindex 231bf61d40..71b5a0bd1b 100644--- a/apps/desktop/src/main/xbox-gamepad/controller.ts+++ b/apps/desktop/src/main/xbox-gamepad/controller.ts@@ -131,7 +131,9 @@ export class XboxGamepadController {const slot = this.slots[family];slot.devicePresent = message.present;slot.deviceName = message.present ? (message.name ?? slot.deviceName) : null;- slot.device = message.present ? deviceFromPresence(message, family) : emptyGamepadDevice(family);+ slot.device = message.present+ ? deviceFromPresence(message, family)+ : emptyGamepadDevice(family);this.syncConnectionStatus(slot);if (!message.present) {this.releaseHolds(slot);@@ -156,6 +158,20 @@ export class XboxGamepadController {this.emitActions(slot, actions);}+ resetHostState(): void {+ this.hostError = null;+ for (const family of GAMEPAD_FAMILIES) {+ const slot = this.slots[family];+ slot.devicePresent = null;+ slot.deviceName = null;+ slot.device = emptyGamepadDevice(family);+ this.syncConnectionStatus(slot);+ this.releaseHolds(slot);+ this.emitPreview(emptyGamepadPreview(family));+ }+ this.emit();+ }+markUnavailable(): void {for (const family of GAMEPAD_FAMILIES) {const slot = this.slots[family];diff --git a/apps/desktop/src/main/xbox-gamepad/host.ts b/apps/desktop/src/main/xbox-gamepad/host.tsindex 415914cde6..8847343993 100644--- a/apps/desktop/src/main/xbox-gamepad/host.ts+++ b/apps/desktop/src/main/xbox-gamepad/host.ts@@ -41,7 +41,6 @@ export function createXboxGamepadHost(let starting = false;let wanted = false;let switch2UsbWanted = false;- let buffer = '';let consecutiveFailures = 0;let crashAccounted = false;let restartTimer: ReturnType<typeof setTimeout> | null = null;@@ -106,6 +105,7 @@ export function createXboxGamepadHost(writeHelper(switch2UsbWanted ? 'switch2-usb on\n' : 'switch2-usb off\n');const attach = (next: ChildProcessWithoutNullStreams): void => {+ let buffer = '';child = next;starting = false;crashAccounted = false;@@ -116,6 +116,7 @@ export function createXboxGamepadHost(stableTimer.unref?.();next.stdout.setEncoding('utf8');next.stdout.on('data', (chunk: string) => {+ if (child !== next) return;buffer += chunk;const lines = buffer.split('\n');buffer = lines.pop() ?? '';@@ -130,14 +131,16 @@ export function createXboxGamepadHost(log.debug('xbox gamepad helper stdin error', { error: error.message });});next.on('error', (error: Error) => {- if (child === next) child = null;+ if (child !== next) return;+ child = null;starting = false;if (!wanted) return;reportHostFailure(error.message);noteChildGone();});next.on('exit', (code, signal) => {- if (child === next) child = null;+ if (child !== next) return;+ child = null;if (!wanted) return;reportHostFailure(`Xbox gamepad helper exited unexpectedly (${code ?? signal ?? 'unknown'})`);noteChildGone();@@ -163,6 +166,7 @@ export function createXboxGamepadHost(attach(next);} catch (error) {starting = false;+ if (!wanted) return;const message = error instanceof Error ? error.message : String(error);// Not `presence: false` — a helper that won't build is an error state, not// "no controller plugged in", and the settings page must say so.diff --git a/apps/desktop/src/main/xbox-gamepad/index.ts b/apps/desktop/src/main/xbox-gamepad/index.tsindex 536b2c26f8..2361efd1fa 100644--- a/apps/desktop/src/main/xbox-gamepad/index.ts+++ b/apps/desktop/src/main/xbox-gamepad/index.ts@@ -105,20 +105,39 @@ const host = createXboxGamepadHost((message) => {});let previewFamily: GamepadFamily | null = null;let taskSlotsSuspended = false;+let hostWanted = false;+let disposed = false;const layoutPreviewLease = createLayoutPreviewLease((active) => {if (!active) previewFamily = null;controller.setLayoutPreviewActive(active, active ? previewFamily : null);- syncSwitch2Usb();+ syncHost();});-function syncSwitch2Usb(): void {+function syncHost(): void {+ if (disposed) return;+ if (process.platform !== 'darwin' && process.platform !== 'win32') {+ controller.markUnavailable();+ return;+ }+ const accessories = controller.getAccessories();+ const wanted =+ previewFamily !== null ||+ (!taskSlotsSuspended &&+ GAMEPAD_FAMILIES.some((family) => accessories[family].settings.deviceEnabled));host.setSwitch2UsbWanted(computeSwitch2UsbWanted({taskSlotsSuspended,- nintendoDeviceEnabled: controller.getAccessories().nintendo.settings.deviceEnabled,+ nintendoDeviceEnabled: accessories.nintendo.settings.deviceEnabled,previewFamily,}),);+ if (wanted === hostWanted) return;+ hostWanted = wanted;+ if (wanted) host.start();+ else {+ host.stop();+ controller.resetHostState();+ }}let inputDeviceRegistered = false;@@ -138,7 +157,7 @@ export function registerXboxGamepadInputDevice(): void {resumeTaskSlots: async () => {taskSlotsSuspended = false;controller.applySettings(family, readXboxGamepadSettings(family));- syncSwitch2Usb();+ syncHost();},suspendTaskSlots: () => {taskSlotsSuspended = true;@@ -146,9 +165,11 @@ export function registerXboxGamepadInputDevice(): void {...readXboxGamepadSettings(family),deviceEnabled: false,});- syncSwitch2Usb();+ syncHost();},dispose: async () => {+ disposed = true;+ hostWanted = false;host.stop();},});@@ -162,8 +183,7 @@ export function registerXboxGamepadSettingsIpc(): void {controller.applySettings(family, readXboxGamepadSettings(family));}if (process.platform === 'darwin' || process.platform === 'win32') {- host.start();- syncSwitch2Usb();+ syncHost();} else {controller.markUnavailable();}@@ -176,7 +196,7 @@ export function registerXboxGamepadSettingsIpc(): void {resetSettings: resetXboxGamepadSettings,applySettings: (family, settings) => {controller.applySettings(family, settings);- syncSwitch2Usb();+ syncHost();},probeDevice: () => host.probe(),setLayoutPreviewActive: (active, family, event) => {@@ -186,7 +206,7 @@ export function registerXboxGamepadSettingsIpc(): void {previewFamily = family;layoutPreviewLease.setActive(true, owner);controller.setLayoutPreviewActive(true, family);- syncSwitch2Usb();+ syncHost();return;}layoutPreviewLease.setActive(false, owner);