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(desktop): 修复 Work Louder HID 重启风暴 (#3660)

Dash1fe13abca319
diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts
index 6a7a43b1da..b2532189f5 100644
--- a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts
+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts
@@ -14,6 +14,8 @@ import type {
} from '../../shared/workLouderCodex.js';
import type { WorkLouderCodexLightingSink } from './WorkLouderCodexLightingController.js';
+const MAX_CONSECUTIVE_CRASHES = 5;
+
export interface WorkLouderCodexChildLike {
postMessage(message: unknown): void;
on(event: 'message', listener: (message: unknown) => void): void;
@@ -89,6 +91,8 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
private wantsHidInput = false;
private deviceEnabled = true;
private wantsPresence = false;
+ /** Permission failures are user-actionable; stop automatic recovery until an explicit retry or toggle. */
+ private permissionBlocked = false;
/** True while the current host is stopping so re-enable cannot talk to it. */
private hostStopping = false;
@@ -123,6 +127,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
setDeviceEnabled(enabled: boolean): void {
if (this.deviceEnabled === enabled) return;
this.deviceEnabled = enabled;
+ this.permissionBlocked = false;
if (enabled) {
this.updateHidListeningIntent();
if (this.latestFrame) this.update(this.latestFrame);
@@ -152,13 +157,15 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
}
setPresenceHandler(
- handler: ((
- present: boolean,
- identity?: {
- deviceType: 'codex-micro' | 'creator-micro-2';
- isUsbConnection: boolean;
- },
- ) => void) | null,
+ handler:
+ | ((
+ present: boolean,
+ identity?: {
+ deviceType: 'codex-micro' | 'creator-micro-2';
+ isUsbConnection: boolean;
+ },
+ ) => void)
+ | null,
): void {
this.presenceHandler = handler;
}
@@ -220,6 +227,11 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
private ensureChild(): WorkLouderCodexChildLike | null {
if (this.hostStopping) return null;
+ // A scheduled recycle owns recovery; work/presence callers must not
+ // recreate the host early and bypass its exponential backoff.
+ if (this.restartTimer) return null;
+ if (this.permissionBlocked) return null;
+ if (this.isCrashBudgetExhausted()) return null;
if (!this.deviceEnabled && !this.wantsPresence) return null;
if (this.child) return this.child;
const sdk = this.deps.resolveSdk();
@@ -286,12 +298,15 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
* no such keyboard.
*/
probe(): void {
- if (this.disposed) return;
+ if (this.disposed || this.permissionBlocked) return;
if (!this.deviceEnabled) {
this.discoverPresence();
return;
}
- if (!this.child) return;
+ // A background probe is observational only. If the host is gone, either
+ // the restart backoff or the crash budget owns recovery; do not recreate
+ // it indirectly through requestHidListening/update.
+ if (!this.child || this.restartTimer) return;
try {
const request: WorkLouderCodexHostRequest = { kind: 'probe' };
this.child.postMessage(request);
@@ -302,6 +317,24 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
}
}
+ /**
+ * Clear a permission breaker only for an explicit recovery signal.
+ *
+ * Background connection polling must stay observational: repeatedly
+ * recreating a host while macOS still denies HID access is the restart storm
+ * this client is designed to prevent. The settings toggle and system unlock
+ * paths call this method when a permission change may have happened.
+ */
+ retryPermission(): void {
+ if (this.disposed || !this.permissionBlocked) return;
+ this.permissionBlocked = false;
+ if (this.restartTimer) {
+ clearTimeout(this.restartTimer);
+ this.restartTimer = null;
+ }
+ this.restartHost();
+ }
+
private requestHidListening(): void {
if (this.disposed || !this.wantsHidInput) return;
const child = this.ensureChild();
@@ -372,11 +405,25 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
}
if (message.kind !== 'state') return;
this.clearConnectWatchdog();
+ if (this.permissionBlocked && message.status === 'connected') return;
this.updateConnectionReason(message.reason ?? null);
- if (message.status === this.lastStatus) return;
+ const permissionRequired =
+ message.status === 'error' && message.reason === 'permission-required';
+ if (permissionRequired) this.permissionBlocked = true;
const previousStatus = this.lastStatus;
- this.lastStatus = message.status;
- this.updateConnectionStatus(message.status);
+ const statusChanged = message.status !== this.lastStatus;
+ if (statusChanged) {
+ this.lastStatus = message.status;
+ this.updateConnectionStatus(message.status);
+ }
+ // Permission errors own teardown even when a previous connection error
+ // already published the same coarse `error` status. The breaker must not
+ // leave a permission-blocked child alive and unable to honor retry.
+ if (permissionRequired) {
+ this.stopHostAfterPermission(child);
+ return;
+ }
+ if (!statusChanged) return;
if (message.status === 'connected') {
this.armStableConnection();
this.deps.log.info('Codex Micro lighting connected');
@@ -393,6 +440,25 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
if (previousStatus === 'connected') this.recycleStaleHost(child);
}
+ private stopHostAfterPermission(child: WorkLouderCodexChildLike): void {
+ if (this.disposed || this.child !== child) return;
+ this.clearConnectWatchdog();
+ this.clearStableConnection();
+ if (this.restartTimer) {
+ clearTimeout(this.restartTimer);
+ this.restartTimer = null;
+ }
+ this.deps.log.warn(
+ 'Codex Micro lighting paused because HID permission is required; retry after permission changes',
+ );
+ try {
+ child.kill();
+ } catch {
+ // Permission failure owns the stop; the host may already have exited.
+ }
+ this.handleExit(child, 0);
+ }
+
private recycleStaleHost(child: WorkLouderCodexChildLike): void {
if (this.disposed || this.recyclingChild || this.child !== child) return;
this.recyclingChild = true;
@@ -426,8 +492,13 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
if (this.wantsPresence) this.scheduleRestart();
return;
}
+ if (this.permissionBlocked) {
+ this.updateConnectionReason('permission-required');
+ this.updateConnectionStatus('error');
+ return;
+ }
if (recycled) {
- this.restartHost();
+ this.scheduleRestart();
return;
}
this.deps.log.warn('Codex Micro lighting host exited', { code });
@@ -445,9 +516,9 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
}
private scheduleRestart(): void {
- if (this.restartTimer || !this.shouldRestartHost()) return;
+ if (this.restartTimer || this.permissionBlocked || !this.shouldRestartHost()) return;
this.consecutiveCrashes += 1;
- if (this.consecutiveCrashes > 5) {
+ if (this.isCrashBudgetExhausted()) {
this.deps.log.error('Codex Micro lighting host repeatedly crashed; disabled until restart');
return;
}
@@ -465,6 +536,10 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
this.restartTimer.unref?.();
}
+ private isCrashBudgetExhausted(): boolean {
+ return this.consecutiveCrashes > MAX_CONSECUTIVE_CRASHES;
+ }
+
private shouldRestartHost(): boolean {
if (this.disposed) return false;
if (!this.deviceEnabled) return this.wantsPresence;
@@ -581,6 +656,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {
}
this.lastStatus = null;
this.consecutiveCrashes = 0;
+ this.permissionBlocked = false;
this.updateConnectionReason(null);
this.updateConnectionStatus('disabled');
}
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts
index 34d7ee0569..44e6d45d38 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts
@@ -222,6 +222,7 @@ describe('WorkLouderCodexHostClient', () => {
expect(fork).toHaveBeenCalledTimes(1);
child.emit('exit', 1);
+ client.probe();
expect(fork).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(500);
@@ -351,7 +352,6 @@ describe('WorkLouderCodexHostClient', () => {
'connecting',
'connected',
'not-detected',
- 'connecting',
]);
expect(child.kill).toHaveBeenCalledOnce();
});
@@ -521,7 +521,136 @@ describe('WorkLouderCodexHostClient', () => {
}
});
- it('recycles the host immediately after a live session drops', () => {
+ it('does not let probes or lighting updates bypass an exhausted crash budget', async () => {
+ vi.useFakeTimers();
+ try {
+ const children = Array.from({ length: 7 }, () => new FakeChild());
+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);
+ const client = new WorkLouderCodexHostClient({
+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),
+ fork,
+ log: logger(),
+ });
+ const frame = createWorkLouderCodexLightingFrame([
+ {
+ sessionId: 'session-1',
+ phase: 'running',
+ compactDetail: '',
+ attention: false,
+ },
+ ]);
+ client.setAgentKeyPressHandler(vi.fn());
+
+ for (let index = 0; index < 6; index += 1) {
+ children[index].emit('exit', 1);
+ await vi.advanceTimersByTimeAsync(Math.min(10_000, 500 * 2 ** index));
+ }
+
+ const forksAfterBudget = fork.mock.calls.length;
+ client.probe();
+ client.probe();
+ client.update(frame);
+
+ expect(fork).toHaveBeenCalledTimes(forksAfterBudget);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('backs off a host recycle after a live session drops', async () => {
+ vi.useFakeTimers();
+ try {
+ const children = [new FakeChild(), new FakeChild()];
+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);
+ const client = new WorkLouderCodexHostClient({
+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),
+ fork,
+ log: logger(),
+ });
+ client.setAgentKeyPressHandler(vi.fn());
+ children[0].emit('message', { kind: 'state', status: 'connected' });
+ children[0].emit('message', { kind: 'state', status: 'not-detected' });
+
+ expect(children[0].kill).toHaveBeenCalledOnce();
+ expect(fork).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(fork).toHaveBeenCalledTimes(2);
+ expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'listen' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not let background probes bypass host recycle backoff', async () => {
+ vi.useFakeTimers();
+ try {
+ const children = [new FakeChild(), new FakeChild()];
+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);
+ const client = new WorkLouderCodexHostClient({
+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),
+ fork,
+ log: logger(),
+ });
+ client.setAgentKeyPressHandler(vi.fn());
+ children[0].emit('message', { kind: 'state', status: 'connected' });
+ children[0].emit('message', { kind: 'state', status: 'not-detected' });
+
+ expect(fork).toHaveBeenCalledTimes(1);
+ client.probe();
+ client.probe();
+ client.update(
+ createWorkLouderCodexLightingFrame([
+ {
+ sessionId: 'session-1',
+ phase: 'running',
+ compactDetail: '',
+ attention: false,
+ },
+ ]),
+ );
+ expect(fork).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(fork).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not restart after a permission-required failure during background probes', async () => {
+ vi.useFakeTimers();
+ try {
+ const children = [new FakeChild(), new FakeChild()];
+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);
+ const client = new WorkLouderCodexHostClient({
+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),
+ fork,
+ log: logger(),
+ });
+ client.setAgentKeyPressHandler(vi.fn());
+ children[0].emit('message', { kind: 'state', status: 'connected' });
+ children[0].emit('message', {
+ kind: 'state',
+ status: 'error',
+ reason: 'permission-required',
+ });
+
+ expect(children[0].kill).toHaveBeenCalledOnce();
+ expect(fork).toHaveBeenCalledTimes(1);
+ client.probe();
+ client.probe();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(fork).toHaveBeenCalledTimes(1);
+
+ client.retryPermission();
+ expect(fork).toHaveBeenCalledTimes(2);
+ expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'listen' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stops a host when permission-required follows another error status', () => {
const children = [new FakeChild(), new FakeChild()];
const fork = vi.fn(() => children[fork.mock.calls.length - 1]);
const client = new WorkLouderCodexHostClient({
@@ -530,13 +659,39 @@ describe('WorkLouderCodexHostClient', () => {
log: logger(),
});
client.setAgentKeyPressHandler(vi.fn());
- children[0].emit('message', { kind: 'state', status: 'connected' });
- children[0].emit('message', { kind: 'state', status: 'not-detected' });
+ children[0].emit('message', {
+ kind: 'state',
+ status: 'error',
+ reason: 'connection-failed',
+ });
+ children[0].emit('message', {
+ kind: 'state',
+ status: 'error',
+ reason: 'permission-required',
+ });
expect(children[0].kill).toHaveBeenCalledOnce();
+ expect(fork).toHaveBeenCalledTimes(1);
+
+ client.retryPermission();
+
expect(fork).toHaveBeenCalledTimes(2);
expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'listen' });
});
+
+ it('does not discover presence when unlock arrives without a permission breaker', () => {
+ const fork = vi.fn(() => new FakeChild());
+ const client = new WorkLouderCodexHostClient({
+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),
+ fork,
+ log: logger(),
+ });
+
+ client.setDeviceEnabled(false);
+ client.retryPermission();
+
+ expect(fork).not.toHaveBeenCalled();
+ });
});
describe('Work Louder SDK resolution', () => {
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostProcess.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostProcess.test.ts
new file mode 100644
index 0000000000..6a5c9475d9
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostProcess.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ classifyConnectionError,
+ isOptionalDeviceStatusError,
+ postDeviceStatus,
+} from '../workLouderCodexHostProcess.js';
+
+const originalPlatform = process.platform;
+
+function setPlatform(platform: NodeJS.Platform): void {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+}
+
+afterEach(() => {
+ setPlatform(originalPlatform);
+});
+
+describe('Work Louder connection error classification', () => {
+ it('keeps macOS authorization failures on the permission circuit breaker path', () => {
+ setPlatform('darwin');
+
+ expect(classifyConnectionError('HID access denied by Input Monitoring')).toBe(
+ 'permission-required',
+ );
+ expect(classifyConnectionError('operation not allowed')).toBe('permission-required');
+ });
+
+ it('keeps Windows access denied on the bounded connection retry path', () => {
+ setPlatform('win32');
+
+ expect(classifyConnectionError('HID access denied')).toBe('connection-failed');
+ expect(classifyConnectionError('permission denied while opening HID handle')).toBe(
+ 'connection-failed',
+ );
+ });
+
+ it('does not treat permission-looking errors as permanent outside macOS', () => {
+ setPlatform('linux');
+
+ expect(classifyConnectionError('not permitted')).toBe('connection-failed');
+ });
+});
+
+describe('Work Louder device status', () => {
+ it('recognizes explicit unsupported status RPC errors as optional telemetry', () => {
+ expect(isOptionalDeviceStatusError(new Error('status RPC unsupported'))).toBe(true);
+ expect(isOptionalDeviceStatusError({ code: 'ERR_METHOD_NOT_FOUND' })).toBe(true);
+ });
+
+ it('keeps rejected hardware status probes fatal so unplugged handles are recycled', () => {
+ expect(isOptionalDeviceStatusError(new Error('device disconnected'))).toBe(false);
+ expect(isOptionalDeviceStatusError(new Error('HID request failed'))).toBe(false);
+ });
+
+ it('keeps the HID connection usable when optional status telemetry fails', async () => {
+ const getDeviceStatus = vi.fn().mockRejectedValue(new Error('status RPC unsupported'));
+
+ await expect(
+ postDeviceStatus(
+ {
+ sendLightingConfig: vi.fn(),
+ sendThreadsLighting: vi.fn(),
+ getDeviceStatus,
+ },
+ 'codex-micro',
+ true,
+ ),
+ ).resolves.toBeUndefined();
+ expect(getDeviceStatus).toHaveBeenCalledOnce();
+ });
+
+ it('rejects a status probe that fails without an unsupported-RPC signal', async () => {
+ const getDeviceStatus = vi.fn().mockRejectedValue(new Error('device disconnected'));
+
+ await expect(
+ postDeviceStatus(
+ {
+ sendLightingConfig: vi.fn(),
+ sendThreadsLighting: vi.fn(),
+ getDeviceStatus,
+ },
+ 'codex-micro',
+ true,
+ ),
+ ).rejects.toThrow('device disconnected');
+ });
+});
diff --git a/apps/desktop/src/main/worklouder-codex/index.ts b/apps/desktop/src/main/worklouder-codex/index.ts
index a007ef38b0..44128167d9 100644
--- a/apps/desktop/src/main/worklouder-codex/index.ts
+++ b/apps/desktop/src/main/worklouder-codex/index.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
-import { BrowserWindow, ipcMain, shell, utilityProcess } from 'electron';
+import { app, BrowserWindow, ipcMain, powerMonitor, shell, utilityProcess } from 'electron';
import { createLogger } from '../logger.js';
import { getDeepLinkMainWindow, openMainWindowSession, sendMainWindowMessage } from '../deepLink.js';
@@ -172,6 +172,7 @@ const layoutPreviewLease = createLayoutPreviewLease((active) => {
let settingsIpcRegistered = false;
let inputDeviceRegistered = false;
+let permissionSettingsRetryPending = false;
/** Register this board as one input-device adapter, not as the host keyboard layer. */
export function registerWorkLouderCodexInputDevice(): void {
@@ -206,6 +207,17 @@ export function registerWorkLouderCodexSettingsIpc(): void {
if (settingsIpcRegistered) return;
settingsIpcRegistered = true;
+ // macOS can report the same HID denial while the screen is locked. The
+ // client keeps that failure circuit-broken until unlock, then makes one
+ // bounded recovery attempt instead of relying on the settings poller to
+ // recreate the host every two seconds.
+ powerMonitor.on('unlock-screen', () => hostClient.retryPermission());
+ app.on('browser-window-focus', () => {
+ if (!permissionSettingsRetryPending) return;
+ permissionSettingsRetryPending = false;
+ hostClient.retryPermission();
+ });
+
workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());
workLouderCodexLightingController.start();
const handlers = createWorkLouderCodexSettingsIpc({
@@ -216,9 +228,15 @@ export function registerWorkLouderCodexSettingsIpc(): void {
applySettings: (settings) => workLouderCodexLightingController.applySettings(settings),
openInputMonitoringSettings: async () => {
if (process.platform !== 'darwin') return;
- await shell.openExternal(
- 'x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent',
- );
+ permissionSettingsRetryPending = true;
+ try {
+ await shell.openExternal(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent',
+ );
+ } catch (error) {
+ permissionSettingsRetryPending = false;
+ throw error;
+ }
},
probeDevice: () => hostClient.probe(),
publishTasks: (tasks) => {
diff --git a/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts
index 04c6747cc0..463aa67927 100644
--- a/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts
+++ b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts
@@ -65,6 +65,8 @@ interface WorkLouderLogger {
const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;
const requireFromHost = createRequire(__filename);
const RETRY_MS = 3_000;
+const SDK_LOG_WINDOW_MS = 60_000;
+const SDK_LOG_BURST = 3;
let sdk: WorkLouderSdk | null = null;
let sdkEntry: string | null = null;
@@ -84,6 +86,9 @@ let stopping = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
let lastLoggedError: string | null = null;
let lastActivityPostedAt = 0;
+let lastTransportError: string | null = null;
+let permissionBlocked = false;
+const sdkLogBuckets = new Map<string, { startedAt: number; emitted: number; suppressed: number }>();
/** The native SDK often logs a dead USB/BT handle instead of throwing. */
let transportFaulted = false;
/** Which device the current `api` handle belongs to, so probes can refresh it. */
@@ -95,6 +100,10 @@ if (parentPort) {
const request = event.data as WorkLouderCodexHostRequest;
if (request?.kind === 'init') {
sdkEntry = request.sdkEntry;
+ permissionBlocked = false;
+ transportFaulted = false;
+ lastTransportError = null;
+ lastLoggedError = null;
} else if (request?.kind === 'listen') {
hidListeningRequested = true;
requestListen();
@@ -102,6 +111,10 @@ if (parentPort) {
latestFrame = request.frame;
requestApply();
} else if (request?.kind === 'probe') {
+ // A probe is an explicit recovery request (for example after the user
+ // grants Input Monitoring or unlocks macOS), so it is allowed to clear
+ // the permission circuit breaker once.
+ permissionBlocked = false;
requestProbe();
} else if (request?.kind === 'discover') {
requestDiscover();
@@ -122,10 +135,12 @@ function hostLog(level: 'debug' | 'info' | 'warn' | 'error', message: string): v
const sdkLogger: WorkLouderLogger = {
debug: () => undefined,
info: () => undefined,
- warn: (...args) => hostLog('warn', `Work Louder SDK reported a warning${formatSdkLog(args)}`),
+ warn: (...args) => logSdkMessage('warn', 'Work Louder SDK reported a warning', args),
error: (...args) => {
transportFaulted = true;
- hostLog('error', `Work Louder SDK reported an error${formatSdkLog(args)}`);
+ const detail = formatSdkLog(args);
+ lastTransportError = `Work Louder SDK reported an error${detail}`;
+ logSdkMessage('error', 'Work Louder SDK reported an error', args);
if (api && !stopping && !probePending && !applying) requestProbe();
},
};
@@ -147,19 +162,19 @@ function loadSdk(): WorkLouderSdk {
}
function requestApply(): void {
- if (stopping) return;
+ if (stopping || permissionBlocked) return;
applyPending = true;
kickQueue();
}
function requestListen(): void {
- if (stopping) return;
+ if (stopping || permissionBlocked) return;
listenPending = true;
kickQueue();
}
function requestProbe(): void {
- if (stopping) return;
+ if (stopping || permissionBlocked) return;
probePending = true;
kickQueue();
}
@@ -226,7 +241,11 @@ async function applyFrame(frame: WorkLouderCodexLightingFrame): Promise<void> {
});
const threadsOk = await deviceApi.sendThreadsLighting(frame.threads);
if (!lightingOk || !threadsOk || transportFaulted) {
- throw new Error(transportFaulted ? 'lighting transport faulted' : 'lighting RPC returned false');
+ throw new Error(
+ transportFaulted
+ ? (lastTransportError ?? 'lighting transport faulted')
+ : 'lighting RPC returned false',
+ );
}
clearRetry();
lastLoggedError = null;
@@ -238,8 +257,7 @@ async function applyFrame(frame: WorkLouderCodexLightingFrame): Promise<void> {
hostLog('error', `lighting apply failed: ${message}`);
}
await disconnect();
- post({ kind: 'state', status: 'error', reason: classifyConnectionError(message) });
- scheduleRetry();
+ reportConnectionError(message);
}
}
@@ -256,14 +274,16 @@ async function applyFrame(frame: WorkLouderCodexLightingFrame): Promise<void> {
* showing connection state, so an idle app is not waking the device on a timer.
*/
async function probeConnection(): Promise<void> {
- if (stopping) return;
+ if (stopping || permissionBlocked) return;
if (api) {
const faulted = transportFaulted;
+ let probeError: string | null = null;
+ let optionalStatusFailure = false;
if (typeof api.getDeviceStatus === 'function' && !faulted) {
try {
- // Call it directly rather than through postDeviceStatus, which swallows
- // failures — swallowing here would make every probe "succeed" and defeat
- // the whole point. Same round trip also keeps battery and firmware fresh.
+ // Call it directly so a successful round trip keeps battery and firmware
+ // values fresh while still letting an explicit transport fault trigger
+ // reconnect handling below.
const status = await api.getDeviceStatus();
if (!transportFaulted) {
const device = connectedDevice;
@@ -272,9 +292,34 @@ async function probeConnection(): Promise<void> {
return;
}
} catch (error) {
- hostLog('debug', `probe found the device gone: ${safeErrorMessage(error)}`);
+ probeError = safeErrorMessage(error);
+ optionalStatusFailure = isOptionalDeviceStatusError(error);
+ hostLog(
+ 'debug',
+ optionalStatusFailure
+ ? `probe status unavailable: ${probeError}`
+ : `probe found the device gone: ${probeError}`,
+ );
}
}
+ const transportError = transportFaulted ? lastTransportError : null;
+ if (transportError) {
+ await disconnect();
+ reportConnectionError(transportError);
+ return;
+ }
+ if (probeError && optionalStatusFailure) {
+ // Status is optional telemetry. Keep the healthy HID transport when a
+ // firmware/RPC implementation explicitly reports that this query is not
+ // supported; a rejected hardware request must still invalidate the handle.
+ post({ kind: 'state', status: 'connected' });
+ return;
+ }
+ if (probeError) {
+ await disconnect();
+ reportConnectionError(probeError);
+ return;
+ }
hostLog('debug', 'probe dropped a stale Work Louder transport');
await disconnect();
}
@@ -290,9 +335,10 @@ async function probeConnection(): Promise<void> {
post({ kind: 'state', status: 'connected' });
if (hidListeningRequested) requestListen();
if (latestFrame && !isWorkLouderCodexLightingFrameOff(latestFrame)) requestApply();
- } catch {
- post({ kind: 'state', status: 'not-detected' });
- scheduleRetry();
+ } catch (error) {
+ const message = safeErrorMessage(error);
+ await disconnect();
+ reportConnectionError(message);
}
}
@@ -312,6 +358,10 @@ function discoverPresence(): void {
} catch (error) {
hostLog('debug', `presence discovery failed: ${safeErrorMessage(error)}`);
post({ kind: 'presence', present: false });
+ } finally {
+ // Presence discovery does not own a HID transport. Do not let an SDK
+ // discovery diagnostic poison the next real connection attempt.
+ clearTransportFault();
}
}
@@ -355,8 +405,7 @@ async function listenForAgentKeys(): Promise<void> {
hostLog('error', `HID listening failed: ${message}`);
}
await disconnect();
- post({ kind: 'state', status: 'error', reason: classifyConnectionError(message) });
- scheduleRetry();
+ reportConnectionError(message);
}
}
@@ -370,6 +419,42 @@ function formatSdkLog(args: unknown[]): string {
return detail ? `: ${detail}` : '';
}
+function logSdkMessage(level: 'warn' | 'error', prefix: string, args: unknown[]): void {
+ const detail = formatSdkLog(args);
+ const message = `${prefix}${detail}`;
+ const signature = normalizeSdkLogSignature(message);
+ const now = Date.now();
+ const previous = sdkLogBuckets.get(signature);
+ if (!previous || now - previous.startedAt >= SDK_LOG_WINDOW_MS) {
+ if (previous?.suppressed) {
+ hostLog(
+ level,
+ `${prefix} (suppressed ${previous.suppressed} repeated messages in the previous minute): ${signature}`,
+ );
+ }
+ if (!previous && sdkLogBuckets.size >= 128) {
+ const oldest = sdkLogBuckets.keys().next().value;
+ if (typeof oldest === 'string') sdkLogBuckets.delete(oldest);
+ }
+ sdkLogBuckets.set(signature, { startedAt: now, emitted: 1, suppressed: 0 });
+ hostLog(level, message);
+ return;
+ }
+ if (previous.emitted < SDK_LOG_BURST) {
+ previous.emitted += 1;
+ hostLog(level, message);
+ } else {
+ previous.suppressed += 1;
+ }
+}
+
+function normalizeSdkLogSignature(message: string): string {
+ return message
+ .replace(/0x[0-9a-f]+/gi, '<hex>')
+ .replace(/\b\d+\b/g, '<n>')
+ .slice(0, 240);
+}
+
function safeErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return message
@@ -381,11 +466,33 @@ function safeErrorMessage(error: unknown): string {
async function ensureConnected(): Promise<WorkLouderApi | null> {
if (api && transportFaulted) await disconnect();
if (api) return api;
+ // Discovery runs with the same SDK logger as the HID transport, but it is
+ // independent of any connection. Start each new connection with a clean
+ // transport-fault state.
+ clearTransportFault();
const candidate = findCandidates()[0];
+ clearTransportFault();
if (!candidate) return null;
const loaded = loadSdk();
const nextComm = new loaded.WLDeviceCommImpl(sdkLogger);
- if (!(await nextComm.connect(candidate.device))) return null;
+ let connected = false;
+ try {
+ connected = await nextComm.connect(candidate.device);
+ } catch (error) {
+ const message = transportFaulted ? (lastTransportError ?? safeErrorMessage(error)) : null;
+ try {
+ await nextComm.disconnect();
+ } catch {
+ // Connection setup failed; teardown is best effort.
+ }
+ throw new Error(message ?? safeErrorMessage(error));
+ }
+ if (!connected) {
+ if (transportFaulted) {
+ throw new Error(lastTransportError ?? 'Work Louder transport faulted');
+ }
+ return null;
+ }
comm = nextComm;
const nextApi = new loaded.RPCApiOAI(nextComm, sdkLogger);
if (typeof nextApi.onHidReceived === 'function') {
@@ -411,7 +518,20 @@ async function ensureConnected(): Promise<WorkLouderApi | null> {
deviceType: candidate.deviceType,
isUsb: candidate.device.isUsbConnection === true,
};
- await postDeviceStatus(nextApi, candidate.deviceType, candidate.device.isUsbConnection === true);
+ try {
+ await postDeviceStatus(
+ nextApi,
+ candidate.deviceType,
+ candidate.device.isUsbConnection === true,
+ );
+ if (transportFaulted) {
+ throw new Error(lastTransportError ?? 'Work Louder transport faulted');
+ }
+ } catch (error) {
+ const message = transportFaulted ? (lastTransportError ?? safeErrorMessage(error)) : null;
+ await disconnect();
+ throw new Error(message ?? safeErrorMessage(error));
+ }
return nextApi;
}
@@ -422,7 +542,35 @@ function postActivity(): void {
post({ kind: 'activity' });
}
-async function postDeviceStatus(
+/**
+ * The SDK exposes status as an optional RPC on some firmware versions. Keep
+ * that compatibility failure non-fatal, but treat every other rejection as a
+ * failed hardware round trip so unplugged handles are recycled promptly.
+ */
+export function isOptionalDeviceStatusError(error: unknown): boolean {
+ const record =
+ typeof error === 'object' && error !== null ? (error as Record<string, unknown>) : null;
+ const code = typeof record?.code === 'string' ? record.code : '';
+ if (
+ /not[_ -]?supported|unsupported|not[_ -]?implemented|method[_ -]?not[_ -]?found|enosys/i.test(
+ code,
+ )
+ ) {
+ return true;
+ }
+
+ const message = safeErrorMessage(error);
+ return (
+ /(?:getDeviceStatus|device status|status rpc|status request).*(?:not supported|unsupported|not implemented|unknown method|method not found)/i.test(
+ message,
+ ) ||
+ /(?:not supported|unsupported|not implemented|unknown method|method not found).*(?:getDeviceStatus|device status|status rpc|status request)/i.test(
+ message,
+ )
+ );
+}
+
+export async function postDeviceStatus(
deviceApi: WorkLouderApi,
deviceType: 'codex-micro' | 'creator-micro-2',
isUsbConnection: boolean,
@@ -433,6 +581,10 @@ async function postDeviceStatus(
status = await deviceApi.getDeviceStatus();
} catch (error) {
hostLog('warn', `device status unavailable: ${safeErrorMessage(error)}`);
+ // Device status is optional telemetry only when the SDK explicitly says
+ // this RPC is unsupported. A rejected hardware request still means the
+ // transport may be dead and must not be reported as connected.
+ if (transportFaulted || !isOptionalDeviceStatusError(error)) throw error;
}
}
postDeviceState(deviceType, isUsbConnection, status);
@@ -461,18 +613,35 @@ function postDeviceState(
});
}
-function classifyConnectionError(message: string): 'connection-failed' | 'permission-required' {
- return /permission|not permitted|access denied|input monitoring|operation not allowed/i.test(
- message,
- )
+export function classifyConnectionError(
+ message: string,
+): 'connection-failed' | 'permission-required' {
+ const looksLikePermissionError =
+ /permission|not permitted|access denied|input monitoring|operation not allowed/i.test(message);
+ // Input Monitoring is a macOS authorization boundary. On Windows, the HID
+ // backend also reports transient handle contention as "access denied"; that
+ // must stay on the bounded connection retry path instead of tripping the
+ // permanent permission circuit breaker.
+ return process.platform === 'darwin' && looksLikePermissionError
? 'permission-required'
: 'connection-failed';
}
+function reportConnectionError(message: string): void {
+ const reason = classifyConnectionError(message);
+ if (reason === 'permission-required') {
+ permissionBlocked = true;
+ clearRetry();
+ }
+ post({ kind: 'state', status: 'error', reason });
+ if (reason !== 'permission-required') scheduleRetry();
+}
+
function scheduleRetry(): void {
if (
retryTimer ||
stopping ||
+ permissionBlocked ||
(!latestFrame && !hidListeningRequested) ||
(latestFrame && isWorkLouderCodexLightingFrameOff(latestFrame) && !hidListeningRequested)
) {
@@ -494,7 +663,7 @@ function clearRetry(): void {
}
async function disconnect(): Promise<void> {
- transportFaulted = false;
+ clearTransportFault();
connectedDevice = null;
const unsubscribe = unsubscribeHid;
unsubscribeHid = null;
@@ -525,6 +694,11 @@ async function disconnect(): Promise<void> {
}
}
+function clearTransportFault(): void {
+ transportFaulted = false;
+ lastTransportError = null;
+}
+
async function stop(): Promise<void> {
if (stopping) return;
stopping = true;