Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): Codex Micro 启用开关与焦点窗动作 (#3034)
Dash005637c72591
diff --git a/apps/desktop/native/voice-input/macos-text-insertion-helper.swift b/apps/desktop/native/voice-input/macos-text-insertion-helper.swiftindex 7fefe1fd79..f092047ef1 100644--- a/apps/desktop/native/voice-input/macos-text-insertion-helper.swift+++ b/apps/desktop/native/voice-input/macos-text-insertion-helper.swift@@ -31,6 +31,8 @@ enum HelperError: Error, CustomStringConvertible {struct Options {var command = "capture-target"var text = ""+ var key = ""+ var scrollDeltaY = 0var targetPid: pid_t?var targetBundleId = ""var targetName = ""@@ -148,6 +150,14 @@ func parseOptions() throws -> Options {options.targetName = valuecase "--with-focused-frame":options.withFocusedFrame = true+ case "--key":+ guard let value = iterator.next() else { throw HelperError.missingValue(arg) }+ options.key = value+ case "--scroll-delta-y":+ guard let value = iterator.next(), let intValue = Int(value) else {+ throw HelperError.invalidArgument("Invalid --scroll-delta-y value")+ }+ options.scrollDeltaY = intValuedefault:throw HelperError.invalidArgument("Unknown argument: \(arg)")}@@ -413,6 +423,119 @@ func postCommandV() throws {keyUp.post(tap: .cghidEventTap)}+func virtualKey(for name: String) throws -> CGKeyCode {+ switch name {+ case "return", "enter":+ return 36+ case "up":+ return 126+ case "down":+ return 125+ default:+ throw HelperError.invalidArgument("Unknown key: \(name)")+ }+}++func requireAccessibilityTrusted() throws {+ guard AXIsProcessTrusted() else {+ throw HelperError.accessibilityNotTrusted+ }+}++func postHardwareKey(name: String) throws {+ try requireAccessibilityTrusted()+ let virtualKey = try virtualKey(for: name)+ guard let source = CGEventSource(stateID: .privateState),+ let keyDown = CGEvent(keyboardEventSource: source, virtualKey: virtualKey, keyDown: true),+ let keyUp = CGEvent(keyboardEventSource: source, virtualKey: virtualKey, keyDown: false) else {+ throw HelperError.commandFailed("Could not create \(name) keyboard event")+ }+ keyDown.post(tap: .cghidEventTap)+ waitWithRunLoop(for: 0.02)+ keyUp.post(tap: .cghidEventTap)+}++func postScroll(deltaY: Int) throws {+ guard deltaY != 0 else { return }+ let wheel1 = Int32(clamping: deltaY)+ guard let source = CGEventSource(stateID: .privateState),+ let event = CGEvent(+ scrollWheelEvent2Source: source,+ units: .pixel,+ wheelCount: 1,+ wheel1: wheel1,+ wheel2: 0,+ wheel3: 0+ ) else {+ throw HelperError.commandFailed("Could not create scroll event")+ }+ event.post(tap: .cghidEventTap)+}++func keyEventPayload(options: Options) throws -> [String: Any] {+ let name = options.key.isEmpty ? "return" : options.key+ try postHardwareKey(name: name)+ return [+ "ok": true,+ "status": "ok",+ "outcome": "verified_success",+ "method": "post-key",+ "key": name,+ ]+}++func scrollEventPayload(options: Options) throws -> [String: Any] {+ try requireAccessibilityTrusted()+ try postScroll(deltaY: options.scrollDeltaY)+ return [+ "ok": true,+ "status": "ok",+ "outcome": "verified_success",+ "method": "post-scroll",+ "scrollDeltaY": options.scrollDeltaY,+ ]+}++/// Stay alive and post wheel events until stdin says stop. The parent writes+/// signed pixels/second; we own the 16ms clock so a held stick keeps scrolling+/// even when the device stops sending move events.+func runHoldScroll() throws {+ try requireAccessibilityTrusted()+ let lock = NSLock()+ var velocity = 0+ var stopped = false+ DispatchQueue.global(qos: .userInteractive).async {+ while let line = readLine() {+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed == "stop" { break }+ if let next = Int(trimmed) {+ lock.lock()+ velocity = next+ lock.unlock()+ }+ }+ lock.lock()+ stopped = true+ lock.unlock()+ }+ var last = Date()+ while true {+ waitWithRunLoop(for: 0.016)+ lock.lock()+ let current = velocity+ let done = stopped+ lock.unlock()+ if done { break }+ let now = Date()+ let dt = min(0.1, now.timeIntervalSince(last))+ last = now+ let delta = Int((Double(current) * dt).rounded())+ if delta != 0 {+ try postScroll(deltaY: delta)+ }+ }+}+func waitWithRunLoop(for interval: TimeInterval) {let deadline = Date().addingTimeInterval(interval)while Date() < deadline {@@ -1436,6 +1559,18 @@ do {emit(captureTargetPayload(withFocusedFrame: options.withFocusedFrame))case "paste-verified":emit(pasteVerifiedPayload(options: options))+ case "post-key":+ emit(try keyEventPayload(options: options))+ case "post-scroll":+ emit(try scrollEventPayload(options: options))+ case "hold-scroll":+ try runHoldScroll()+ emit([+ "ok": true,+ "status": "ok",+ "outcome": "verified_success",+ "method": "hold-scroll",+ ])default:throw HelperError.invalidArgument("Unknown command: \(options.command)")}diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.tsindex d5c952ef3c..6d32886f6d 100644--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@ -265,6 +265,10 @@ export function setDeepLinkMainWindow(win: BrowserWindow | null): void {mainWindowRef = win;}+export function getDeepLinkMainWindow(): BrowserWindow | null {+ return mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;+}+/*** 处理一条入站 URL。会内部解析、根据 mainWindow 状态选择直接发送 or 缓存。* 即使解析失败也只 log 不抛,避免污染调用方(open-url / second-instance / argv)。diff --git a/apps/desktop/src/main/voice-input/__tests__/macHelperProcess.test.ts b/apps/desktop/src/main/voice-input/__tests__/macHelperProcess.test.tsnew file mode 100644index 0000000000..b9dd3e665e--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/macHelperProcess.test.ts@@ -0,0 +1,42 @@+import { EventEmitter } from 'node:events';+import { describe, expect, it, vi } from 'vitest';++import {+ assertHelperCommandSucceeded,+ waitForSpawnedProcess,+} from '../macHelperProcess.js';++describe('waitForSpawnedProcess', () => {+ it('rejects when spawn emits error before start', async () => {+ const child = new EventEmitter();+ const pending = waitForSpawnedProcess(child);+ child.emit('error', new Error('ENOENT'));+ await expect(pending).rejects.toThrow('ENOENT');+ });++ it('resolves after spawn and swallows later errors', async () => {+ const child = new EventEmitter();+ const lateError = vi.fn();+ const pending = waitForSpawnedProcess(child, lateError);+ child.emit('spawn');+ await expect(pending).resolves.toBe(child);++ child.emit('error', new Error('EPIPE'));+ expect(lateError).toHaveBeenCalledOnce();+ });+});++describe('assertHelperCommandSucceeded', () => {+ it('throws on an explicit helper failure payload', () => {+ expect(() =>+ assertHelperCommandSucceeded({+ ok: false,+ error: 'Accessibility permission is not granted',+ }),+ ).toThrow('Accessibility permission is not granted');+ });++ it('ignores successful helper payloads', () => {+ expect(() => assertHelperCommandSucceeded({ ok: true })).not.toThrow();+ });+});diff --git a/apps/desktop/src/main/voice-input/__tests__/nativeVoiceActivation.test.ts b/apps/desktop/src/main/voice-input/__tests__/nativeVoiceActivation.test.tsnew file mode 100644index 0000000000..061d255d7c--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/nativeVoiceActivation.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { resolveNativeVoiceActivation } from '../nativeVoiceActivation.js';++describe('resolveNativeVoiceActivation', () => {+ it('pairs start and end on the same source', () => {+ const started = resolveNativeVoiceActivation(null, 'start', 'hardware', false);+ expect(started).toEqual({ owner: 'hardware', deliver: true });++ const ended = resolveNativeVoiceActivation(started.owner, 'end', 'hardware', false);+ expect(ended).toEqual({ owner: null, deliver: true });+ });++ it('ignores a second source while the first is held', () => {+ const held = resolveNativeVoiceActivation(null, 'start', 'hardware', false);++ expect(resolveNativeVoiceActivation(held.owner, 'start', 'shortcut', false)).toEqual({+ owner: 'hardware',+ deliver: false,+ });+ expect(resolveNativeVoiceActivation(held.owner, 'end', 'shortcut', false)).toEqual({+ owner: 'hardware',+ deliver: false,+ });+ expect(resolveNativeVoiceActivation(held.owner, 'end', 'hardware', false)).toEqual({+ owner: null,+ deliver: true,+ });+ });++ it('does not let a blocked shortcut start drop a held hardware pairing', () => {+ const held = resolveNativeVoiceActivation(null, 'start', 'hardware', false);++ expect(resolveNativeVoiceActivation(held.owner, 'start', 'shortcut', true)).toEqual({+ owner: 'hardware',+ deliver: false,+ });+ });+});diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.tsindex 060e04b355..660a4f38db 100644--- a/apps/desktop/src/main/voice-input/global.ts+++ b/apps/desktop/src/main/voice-input/global.ts@@ -53,6 +53,14 @@ import {import { voiceInputOverlayPositionStore } from './overlayPositionStore.js';import { voiceInputDataStore } from './VoiceInputDataStore.js';import { installWindowHiddenBroadcast } from '../windowHiddenBroadcast.js';+import {+ resolveNativeVoiceActivation,+ type NativeVoiceActivationSource,+} from './nativeVoiceActivation.js';+import {+ assertHelperCommandSucceeded,+ waitForSpawnedProcess,+} from './macHelperProcess.js';const log = createLogger('voice-input-global');type GlobalVoiceInputShortcutPhase = 'start' | 'tap' | 'end';@@ -91,32 +99,29 @@ function hasActiveShortcutRecordingSession(): boolean {}/**- * 上一次 native 激活的 start 有没有真的投递到下游。- *- * listener 的 triggered / end 是它自己的内部时序,与这里的投递层抑制无关:被上面那条守卫挡掉的- * start,用户按住超过阈值再松手时照样会给出一条 end(endActiveTriggerIfNeeded 补发的那条同理)。- * 而 end 在下游就是「停止并提交」—— 一个正在跑的 inline 语音输入会话会被这条**没有配对 start**- * 的 end 直接提交掉,而用户只是按了一下本该被吞掉的键。+ * Which native source currently owns the overlay start/end pair.*- * 所以 end 的投递条件是「配对的 start 投递过没有」。这也覆盖了录制框已经关掉、end 才姗姗来迟的- * 情形 —— 那时录制守卫早就不生效了,只有配对关系还算数。+ * Hardware and the system shortcut share this overlay. The pairing is per+ * source so one side's start or end cannot submit or drop the other.*/-let nativeActivationStartDelivered = false;+let nativeActivationOwner: NativeVoiceActivationSource | null = null;-function handleNativeGlobalShortcutPhase(phase: GlobalVoiceInputShortcutPhase): void {- if (phase !== 'end' && hasActiveShortcutRecordingSession()) {- // 挡掉 start 就等于这次激活在下游不存在,它后面那条配对的 end 也必须一起挡掉。- if (phase === 'start') nativeActivationStartDelivered = false;- log.debug('ignoring native global shortcut activation while recording', { phase });- return;- }- if (phase === 'end' && !nativeActivationStartDelivered) {- log.debug('ignoring native global shortcut end without a delivered start');+function handleNativeGlobalShortcutPhase(+ phase: GlobalVoiceInputShortcutPhase,+ source: NativeVoiceActivationSource = 'shortcut',+): void {+ const next = resolveNativeVoiceActivation(+ nativeActivationOwner,+ phase,+ source,+ hasActiveShortcutRecordingSession(),+ );+ nativeActivationOwner = next.owner;+ if (!next.deliver) {+ log.debug('ignoring native voice activation', { phase, source });return;}- // tap 没有配对的 end;end 到这里就算消费掉了。两种都把配对状态清干净。- nativeActivationStartDelivered = phase === 'start';- log.debug('native global shortcut triggered', { phase });+ log.debug('native global shortcut triggered', { phase, source });if (phase === 'tap') {handleGlobalVoiceInputShortcutTap();} else if (phase === 'start') {@@ -163,6 +168,11 @@ export function releaseActiveGlobalVoiceInputShortcut(): void {windowsFunctionKeyShortcutListener.releaseActiveTrigger();}+/** Drive the existing global overlay from hardware, using the same phases as the system shortcut. */+export function triggerGlobalVoiceInputFromHardware(phase: GlobalVoiceInputShortcutPhase): void {+ handleNativeGlobalShortcutPhase(phase, 'hardware');+}+type VoiceInputGlobalResult =| { ok: true }| { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };@@ -3663,6 +3673,27 @@ async function runMacTextInsertionHelper(}}+export async function runMacTextInsertionHelperCommand(+ args: string[],+ options?: { input?: string; timeoutMs?: number },+): Promise<MacTextInsertionHelperResult> {+ const result = await runMacTextInsertionHelper(args, options);+ assertHelperCommandSucceeded(result);+ return result;+}++export async function spawnMacTextInsertionHelper(args: string[]) {+ const helperPath = await resolveMacTextInsertionHelperPath();+ return waitForSpawnedProcess(+ spawn(helperPath, args, { stdio: ['pipe', 'ignore', 'pipe'] }),+ (error) => {+ log.warn('macOS text insertion helper failed after spawn', {+ error: error instanceof Error ? error.message : String(error),+ });+ },+ );+}+/** 取 stdout 的最后一行 JSON 作为命令结果(前面的行是流式进度事件)。 */export function parseMacTextInsertionHelperResult(stdout: string): MacTextInsertionHelperResult {const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);diff --git a/apps/desktop/src/main/voice-input/macHelperProcess.ts b/apps/desktop/src/main/voice-input/macHelperProcess.tsnew file mode 100644index 0000000000..4f3ecebbda--- /dev/null+++ b/apps/desktop/src/main/voice-input/macHelperProcess.ts@@ -0,0 +1,35 @@+export type SpawnedHelperProcess = {+ once(event: 'error', listener: (error: Error) => void): unknown;+ once(event: 'spawn', listener: () => void): unknown;+ off(event: 'error', listener: (error: Error) => void): unknown;+ on(event: 'error', listener: (error: Error) => void): unknown;+};++export function waitForSpawnedProcess<T extends SpawnedHelperProcess>(+ child: T,+ onLateError?: (error: Error) => void,+): Promise<T> {+ return new Promise((resolve, reject) => {+ const onError = (error: Error): void => {+ reject(error);+ };+ child.once('error', onError);+ child.once('spawn', () => {+ child.off('error', onError);+ child.on('error', (error) => {+ onLateError?.(error);+ });+ resolve(child);+ });+ });+}++export function assertHelperCommandSucceeded(result: {+ ok?: boolean;+ error?: string | null;+ reason?: string;+}): void {+ if (result.ok === false) {+ throw new Error(result.error || result.reason || 'macOS helper command failed');+ }+}diff --git a/apps/desktop/src/main/voice-input/nativeVoiceActivation.ts b/apps/desktop/src/main/voice-input/nativeVoiceActivation.tsnew file mode 100644index 0000000000..bc12f5f85f--- /dev/null+++ b/apps/desktop/src/main/voice-input/nativeVoiceActivation.ts@@ -0,0 +1,35 @@+export type NativeVoiceActivationPhase = 'start' | 'tap' | 'end';+export type NativeVoiceActivationSource = 'shortcut' | 'hardware';++export interface NativeVoiceActivationDecision {+ owner: NativeVoiceActivationSource | null;+ deliver: boolean;+}++/**+ * One native dictation owner at a time.+ *+ * Hardware and the system shortcut share the same overlay. A second source+ * must not steal the held start or consume the owner's release.+ */+export function resolveNativeVoiceActivation(+ owner: NativeVoiceActivationSource | null,+ phase: NativeVoiceActivationPhase,+ source: NativeVoiceActivationSource,+ recording: boolean,+): NativeVoiceActivationDecision {+ if (phase !== 'end' && recording) {+ if (phase === 'start' && owner === source) {+ return { owner: null, deliver: false };+ }+ return { owner, deliver: false };+ }+ if (phase === 'end') {+ if (owner !== source) return { owner, deliver: false };+ return { owner: null, deliver: true };+ }+ if (owner && owner !== source) {+ return { owner, deliver: false };+ }+ return { owner: phase === 'start' ? source : null, deliver: true };+}diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.tsindex 1e88d792b9..6a7a43b1da 100644--- a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts@@ -65,6 +65,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {private disposePromise: Promise<void> | null = null;private finishDispose: (() => void) | null = null;private disposeTimer: ReturnType<typeof setTimeout> | null = null;+ private disconnectTimer: ReturnType<typeof setTimeout> | null = null;private agentKeyPressHandler: ((slot: number) => void) | null = null;private deviceActivityHandler: (() => void) | null = null;private hidInputHandler: ((event: WorkLouderCodexHidEvent) => void) | null = null;@@ -74,9 +75,22 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {null;private connectionStatusHandler: ((status: WorkLouderCodexConnectionStatus) => void) | null =null;+ private presenceHandler:+ | ((+ present: boolean,+ identity?: {+ deviceType: 'codex-micro' | 'creator-micro-2';+ isUsbConnection: boolean;+ },+ ) => void)+ | null = null;private connectionStatus: WorkLouderCodexConnectionStatus = 'connecting';private connectionReason: WorkLouderCodexConnectionReason = null;private wantsHidInput = false;+ private deviceEnabled = true;+ private wantsPresence = false;+ /** True while the current host is stopping so re-enable cannot talk to it. */+ private hostStopping = false;constructor(private readonly deps: WorkLouderCodexHostClientDeps) {}@@ -106,11 +120,23 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {handler?.(this.connectionReason);}+ setDeviceEnabled(enabled: boolean): void {+ if (this.deviceEnabled === enabled) return;+ this.deviceEnabled = enabled;+ if (enabled) {+ this.updateHidListeningIntent();+ if (this.latestFrame) this.update(this.latestFrame);+ return;+ }+ this.disconnectHost();+ }+private updateHidListeningIntent(): void {this.wantsHidInput =- this.agentKeyPressHandler !== null ||- this.hidInputHandler !== null ||- this.joystickInputHandler !== null;+ this.deviceEnabled &&+ (this.agentKeyPressHandler !== null ||+ this.hidInputHandler !== null ||+ this.joystickInputHandler !== null);if (this.wantsHidInput) this.requestHidListening();}@@ -125,9 +151,22 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {handler?.(this.connectionStatus);}+ setPresenceHandler(+ handler: ((+ present: boolean,+ identity?: {+ deviceType: 'codex-micro' | 'creator-micro-2';+ isUsbConnection: boolean;+ },+ ) => void) | null,+ ): void {+ this.presenceHandler = handler;+ }+update(frame: WorkLouderCodexLightingFrame): void {if (this.disposed) return;this.latestFrame = frame;+ if (!this.deviceEnabled) return;if (isWorkLouderCodexLightingFrameOff(frame) && this.restartTimer) {clearTimeout(this.restartTimer);this.restartTimer = null;@@ -180,11 +219,15 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {}private ensureChild(): WorkLouderCodexChildLike | null {+ if (this.hostStopping) return null;+ if (!this.deviceEnabled && !this.wantsPresence) return null;if (this.child) return this.child;const sdk = this.deps.resolveSdk();if (!sdk) {- this.updateConnectionReason('sdk-unavailable');- this.updateConnectionStatus('unavailable');+ if (this.deviceEnabled) {+ this.updateConnectionReason('sdk-unavailable');+ this.updateConnectionStatus('unavailable');+ }if (!this.unavailableLogged) {this.unavailableLogged = true;this.deps.log.info('Codex Micro lighting unavailable: official Work Louder SDK not found');@@ -194,7 +237,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {let child: WorkLouderCodexChildLike | null = null;try {this.updateConnectionReason(null);- this.updateConnectionStatus('connecting');+ if (this.deviceEnabled) this.updateConnectionStatus('connecting');const startedChild = this.deps.fork(sdk.entry);child = startedChild;this.child = startedChild;@@ -207,7 +250,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {});const initRequest: WorkLouderCodexHostRequest = { kind: 'init', sdkEntry: sdk.entry };startedChild.postMessage(initRequest);- this.startConnectWatchdog(startedChild);+ if (this.deviceEnabled) this.startConnectWatchdog(startedChild);this.deps.log.info('Codex Micro lighting host started', { sdkSource: sdk.source });return startedChild;} catch (error) {@@ -222,9 +265,11 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {this.deps.log.warn('failed to start Codex Micro lighting host', {error: error instanceof Error ? error.message : String(error),});- this.updateConnectionReason('connection-failed');- this.updateConnectionStatus('error');- this.scheduleRestart();+ if (this.deviceEnabled) {+ this.updateConnectionReason('connection-failed');+ this.updateConnectionStatus('error');+ this.scheduleRestart();+ }return null;}}@@ -241,7 +286,12 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {* no such keyboard.*/probe(): void {- if (this.disposed || !this.child) return;+ if (this.disposed) return;+ if (!this.deviceEnabled) {+ this.discoverPresence();+ return;+ }+ if (!this.child) return;try {const request: WorkLouderCodexHostRequest = { kind: 'probe' };this.child.postMessage(request);@@ -302,6 +352,20 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {this.deviceStateHandler?.(message.device);return;}+ if (message.kind === 'presence') {+ this.clearConnectWatchdog();+ this.armStableConnection();+ this.presenceHandler?.(+ message.present,+ message.present && message.deviceType+ ? {+ deviceType: message.deviceType,+ isUsbConnection: message.isUsbConnection === true,+ }+ : undefined,+ );+ return;+ }if (message.kind === 'activity') {this.deviceActivityHandler?.();return;@@ -350,11 +414,18 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {this.clearConnectWatchdog();this.clearStableConnection();this.child = null;+ this.hostStopping = false;this.lastStatus = null;if (this.disposed) {this.completeDispose(child);return;}+ if (!this.deviceEnabled) {+ this.updateConnectionReason(null);+ this.updateConnectionStatus('disabled');+ if (this.wantsPresence) this.scheduleRestart();+ return;+ }if (recycled) {this.restartHost();return;@@ -368,21 +439,13 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {}private restartHost(): void {- if (this.disposed) return;+ if (this.disposed || !this.deviceEnabled) return;if (this.wantsHidInput) this.requestHidListening();if (this.latestFrame) this.update(this.latestFrame);}private scheduleRestart(): void {- if (- this.restartTimer ||- (!this.latestFrame && !this.wantsHidInput) ||- (this.latestFrame &&- isWorkLouderCodexLightingFrameOff(this.latestFrame) &&- !this.wantsHidInput)- ) {- return;- }+ if (this.restartTimer || !this.shouldRestartHost()) return;this.consecutiveCrashes += 1;if (this.consecutiveCrashes > 5) {this.deps.log.error('Codex Micro lighting host repeatedly crashed; disabled until restart');@@ -391,14 +454,26 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {const delayMs = Math.min(10_000, 500 * 2 ** (this.consecutiveCrashes - 1));this.restartTimer = setTimeout(() => {this.restartTimer = null;- const frame = this.latestFrame;- if (this.disposed) return;+ if (this.disposed || !this.shouldRestartHost()) return;+ if (!this.deviceEnabled) {+ this.discoverPresence();+ return;+ }if (this.wantsHidInput) this.requestHidListening();- if (frame) this.update(frame);+ if (this.latestFrame) this.update(this.latestFrame);}, delayMs);this.restartTimer.unref?.();}+ private shouldRestartHost(): boolean {+ if (this.disposed) return false;+ if (!this.deviceEnabled) return this.wantsPresence;+ return (+ this.wantsHidInput ||+ Boolean(this.latestFrame && !isWorkLouderCodexLightingFrameOff(this.latestFrame))+ );+ }+private startConnectWatchdog(child: WorkLouderCodexChildLike): void {this.clearConnectWatchdog();this.connectWatchdogTimer = setTimeout(() => {@@ -424,7 +499,7 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {}private armStableConnection(): void {- this.clearStableConnection();+ if (this.stableConnectionTimer) return;this.stableConnectionTimer = setTimeout(() => {this.stableConnectionTimer = null;this.consecutiveCrashes = 0;@@ -445,17 +520,26 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {clearTimeout(this.disposeTimer);this.disposeTimer = null;}- if (this.child === child) {+ if (this.disconnectTimer) {+ clearTimeout(this.disconnectTimer);+ this.disconnectTimer = null;+ }+ const owned = this.child === child;+ if (owned) {try {child.kill();} catch {// The utility process may already have exited after acknowledging stop.}this.child = null;+ this.hostStopping = false;}const finish = this.finishDispose;this.finishDispose = null;finish?.();+ if (this.disposed || !owned || this.child) return;+ if (this.deviceEnabled) this.restartHost();+ else if (this.wantsPresence) this.discoverPresence();}private updateConnectionStatus(status: WorkLouderCodexConnectionStatus): void {@@ -469,4 +553,49 @@ export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {this.connectionReason = reason;this.connectionReasonHandler?.(reason);}++ private disconnectHost(): void {+ if (this.restartTimer) {+ clearTimeout(this.restartTimer);+ this.restartTimer = null;+ }+ this.clearConnectWatchdog();+ this.clearStableConnection();+ const child = this.child;+ if (child) {+ this.hostStopping = true;+ if (this.disconnectTimer) {+ clearTimeout(this.disconnectTimer);+ this.disconnectTimer = null;+ }+ this.disconnectTimer = setTimeout(+ () => this.completeDispose(child),+ this.deps.disposeTimeoutMs ?? 1_000,+ );+ this.disconnectTimer.unref?.();+ try {+ child.postMessage({ kind: 'stop' } satisfies WorkLouderCodexHostRequest);+ } catch {+ this.completeDispose(child);+ }+ }+ this.lastStatus = null;+ this.consecutiveCrashes = 0;+ this.updateConnectionReason(null);+ this.updateConnectionStatus('disabled');+ }++ private discoverPresence(): void {+ this.wantsPresence = true;+ const child = this.ensureChild();+ if (!child) return;+ try {+ const request: WorkLouderCodexHostRequest = { kind: 'discover' };+ child.postMessage(request);+ } catch (error) {+ this.deps.log.debug('failed to discover Work Louder presence', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }}diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.tsindex b74500f17c..8ed67f99c1 100644--- a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts@@ -25,6 +25,7 @@ import {createWorkLouderCodexOffFrame,createWorkLouderCodexLightingFrame,createWorkLouderCodexWindowRevealFrame,+ foldOrcaWorkerActivityOntoLeads,isWorkLouderCodexLightingFrameOff,type WorkLouderCodexHidEvent,type WorkLouderCodexJoystickEvent,@@ -68,16 +69,30 @@ export interface WorkLouderCodexLightingSink {setConnectionReasonHandler?(handler: ((reason: WorkLouderCodexConnectionReason) => void) | null,): void;+ setDeviceEnabled?(enabled: boolean): void;+ setPresenceHandler?(+ handler: ((+ present: boolean,+ identity?: {+ deviceType: 'codex-micro' | 'creator-micro-2';+ isUsbConnection: boolean;+ },+ ) => void) | null,+ ): void;dispose(): Promise<void>;}type TaskCatalogLoader = () => Promise<WorkLouderCodexTaskCatalog | readonly string[]>;+type WorkerSessionLoader = (+ leadSessionIds: readonly string[],+) => Promise<Readonly<Record<string, readonly string[]>>>;/** Keeps task LEDs, physical controls, and the settings projection on one state machine. */export class WorkLouderCodexLightingController {private lastFrameKey = '';private slotSessionIds: string[] = [];private latestActivity: readonly WorkLouderCodexSessionActivity[] = [];+ private workersByLead: Readonly<Record<string, readonly string[]>> = {};private taskCatalog: WorkLouderCodexTaskCatalog = { sidebar: [], lastSent: [], options: [] };private agentSlots: WorkLouderCodexAgentSlotState[] = emptyAgentSlots();private slotRefreshVersion = 0;@@ -87,8 +102,9 @@ export class WorkLouderCodexLightingController {private slotRefreshInFlightVersion: number | null = null;private slotRefreshQueued = false;private settings: WorkLouderCodexSettings = createWorkLouderCodexDefaultSettings();- private connectionStatus: WorkLouderCodexConnectionStatus = 'connecting';+ private connectionStatus: WorkLouderCodexConnectionStatus = 'disabled';private connectionReason: WorkLouderCodexConnectionReason = null;+ private devicePresent: boolean | null = null;private device: WorkLouderCodexDeviceState = {...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,inputMonitoringPermission: process.platform === 'darwin' ? 'unknown' : 'not-required',@@ -119,6 +135,7 @@ export class WorkLouderCodexLightingController {undefined,private readonly dispatchPreviewInput: (input: WorkLouderCodexPreviewInput) => void = () =>undefined,+ private readonly loadWorkerSessions: WorkerSessionLoader = async () => ({}),) {}start(): void {@@ -127,7 +144,11 @@ export class WorkLouderCodexLightingController {this.sink.setConnectionStatusHandler((status) => this.handleConnectionStatus(status));this.sink.setConnectionReasonHandler?.((reason) => this.handleConnectionReason(reason));this.sink.setDeviceStateHandler?.((device) => this.handleDeviceState(device));+ this.sink.setPresenceHandler?.((present, identity) =>+ this.handleDevicePresence(present, identity),+ );this.sink.setDeviceActivityHandler(() => this.handleDeviceActivity());+ this.sink.setDeviceEnabled?.(this.settings.deviceEnabled);if (this.sink.setHidInputHandler) {this.sink.setAgentKeyPressHandler(null);this.sink.setHidInputHandler((event) => this.handleHidInput(event));@@ -148,6 +169,7 @@ export class WorkLouderCodexLightingController {return {connectionStatus: this.connectionStatus,connectionReason: this.connectionReason,+ devicePresent: this.devicePresent,device: { ...this.device },settings: cloneWorkLouderCodexSettings(this.settings),agentSlots: this.agentSlots.map((slot) => ({@@ -166,15 +188,20 @@ export class WorkLouderCodexLightingController {}setLayoutPreviewActive(active: boolean): void {+ if (active && !this.layoutPreviewActive) this.releaseHeldHardwareGestures();this.layoutPreviewActive = active;if (!active) this.pendingAgentKeyTap = null;}applySettings(settings: WorkLouderCodexSettings): void {+ const turningOff = this.settings.deviceEnabled && !settings.deviceEnabled;this.settings = cloneWorkLouderCodexSettings(settings);this.pendingAgentKeyTap = null;this.lightingDimmed = false;this.clearWindowRevealTimer();+ if (turningOff) this.releaseHeldHardwareGestures();+ this.sink.setDeviceEnabled?.(settings.deviceEnabled);+ if (!settings.deviceEnabled) this.connectionStatus = 'disabled';this.publishAgentSlots();const frame = this.updateLightingFrame();this.resetAutoDimTimer(frame);@@ -215,6 +242,8 @@ export class WorkLouderCodexLightingController {const catalog = normalizeTaskCatalog(await this.loadTaskCatalog());if (!this.taskSlotsEnabled || refreshVersion !== this.slotRefreshVersion) return;this.taskCatalog = catalog;+ await this.refreshWorkerSessions(refreshVersion);+ if (!this.taskSlotsEnabled || refreshVersion !== this.slotRefreshVersion) return;this.publishAgentSlots();this.updateLightingFrame(true);this.emitState();@@ -253,6 +282,8 @@ export class WorkLouderCodexLightingController {}this.taskSlotsEnabled = true;this.inputActionsEnabled = true;+ await this.refreshWorkerSessions(refreshVersion);+ if (refreshVersion !== this.slotRefreshVersion) return;this.publishAgentSlots();this.updateLightingFrame(true);this.emitState();@@ -263,7 +294,7 @@ export class WorkLouderCodexLightingController {this.clearEncoderLongPressTimer();this.encoderPressed = false;this.encoderLongPressed = false;- this.stopJoystickScroll();+ this.releaseHeldHardwareGestures();this.slotRefreshVersion += 1;this.taskSlotsEnabled = false;this.inputActionsEnabled = false;@@ -271,10 +302,10 @@ export class WorkLouderCodexLightingController {this.taskCatalog = { sidebar: [], lastSent: [], options: [] };this.agentSlots = emptyAgentSlots();this.slotSessionIds = [];+ this.workersByLead = {};this.pendingAgentKeyTap = null;this.joystickNeedsCenter = this.joystickDirection !== null;this.joystickDirection = null;- this.releaseHeldVoice();this.clearAutoDimTimer();this.clearWindowRevealTimer();this.lightingDimmed = false;@@ -287,8 +318,7 @@ export class WorkLouderCodexLightingController {this.clearEncoderLongPressTimer();this.clearAutoDimTimer();this.clearWindowRevealTimer();- this.stopJoystickScroll();- this.releaseHeldVoice();+ this.releaseHeldHardwareGestures();this.slotRefreshVersion += 1;this.taskSlotsEnabled = false;this.inputActionsEnabled = false;@@ -298,6 +328,7 @@ export class WorkLouderCodexLightingController {this.sink.setHidInputHandler?.(null);this.sink.setJoystickInputHandler?.(null);this.sink.setDeviceStateHandler?.(null);+ this.sink.setPresenceHandler?.(null);this.sink.setConnectionReasonHandler?.(null);this.sink.setDeviceActivityHandler(null);this.sink.setConnectionStatusHandler(null);@@ -540,6 +571,11 @@ export class WorkLouderCodexLightingController {this.releaseHeldVoice();}+ private releaseHeldHardwareGestures(): void {+ this.stopJoystickScroll();+ this.releaseHeldVoice();+ }+private releaseHeldVoice(): void {if (!this.voicePressed) return;this.voicePressed = false;@@ -609,7 +645,7 @@ export class WorkLouderCodexLightingController {const recentRank = new Map(this.taskCatalog.options.map((task, index) => [task.id, index] as const),);- const prioritized = this.latestActivity+ const prioritized = this.lightingActivity().filter((activity) => optionById.has(activity.sessionId)).toSorted((left, right) => {const scoreDiff = activityPriority(right) - activityPriority(left);@@ -624,8 +660,19 @@ export class WorkLouderCodexLightingController {return [...prioritized, ...this.taskCatalog.sidebar.filter((task) => !included.has(task.id))];}+ private lightingActivity(): WorkLouderCodexSessionActivity[] {+ return foldOrcaWorkerActivityOntoLeads(this.latestActivity, this.workersByLead);+ }++ private async refreshWorkerSessions(refreshVersion: number): Promise<void> {+ const leadIds = catalogLeadSessionIds(this.taskCatalog);+ const workersByLead = await this.loadWorkerSessions(leadIds);+ if (refreshVersion !== this.slotRefreshVersion) return;+ this.workersByLead = workersByLead;+ }+private updateLightingFrame(wakeOnBaseFrameChange = false): WorkLouderCodexLightingFrame {- const baseFrame = createWorkLouderCodexLightingFrame(this.latestActivity, this.slotSessionIds);+ const baseFrame = createWorkLouderCodexLightingFrame(this.lightingActivity(), this.slotSessionIds);const baseFrameKey = JSON.stringify(baseFrame);const baseFrameChanged = baseFrameKey !== this.lastBaseFrameKey;this.lastBaseFrameKey = baseFrameKey;@@ -679,14 +726,22 @@ export class WorkLouderCodexLightingController {}private handleConnectionStatus(status: WorkLouderCodexConnectionStatus): void {+ if (!this.settings.deviceEnabled && status !== 'disabled') return;if (status === this.connectionStatus) return;this.connectionStatus = status;if (status === 'connected') {this.connectionReason = null;+ this.devicePresent = true;if (process.platform === 'darwin') {this.device = { ...this.device, inputMonitoringPermission: 'granted' };}- } else {+ } else if (status === 'not-detected') {+ this.devicePresent = false;+ this.device = {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ inputMonitoringPermission: this.device.inputMonitoringPermission,+ };+ } else if (status !== 'disabled') {// Keep the last permission answer; everything else is stale once the// board is gone and would sit next to "Not detected" as if it were live.this.device = {@@ -708,6 +763,30 @@ export class WorkLouderCodexLightingController {private handleDeviceState(device: WorkLouderCodexDeviceState): void {this.device = { ...device };+ if (device.deviceType) this.devicePresent = true;+ this.emitState();+ }++ private handleDevicePresence(+ present: boolean,+ identity?: {+ deviceType: 'codex-micro' | 'creator-micro-2';+ isUsbConnection: boolean;+ },+ ): void {+ this.devicePresent = present;+ if (!present) {+ this.device = {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ inputMonitoringPermission: this.device.inputMonitoringPermission,+ };+ } else if (identity) {+ this.device = {+ ...this.device,+ deviceType: identity.deviceType,+ isUsbConnection: identity.isUsbConnection,+ };+ }this.emitState();}@@ -796,6 +875,16 @@ function emptyAgentSlots(): WorkLouderCodexAgentSlotState[] {}));}+function catalogLeadSessionIds(catalog: WorkLouderCodexTaskCatalog): string[] {+ return [+ ...new Set(+ [...catalog.options, ...catalog.sidebar, ...catalog.lastSent]+ .map((task) => task.id)+ .filter(Boolean),+ ),+ ];+}+function normalizeTaskCatalog(value: WorkLouderCodexTaskCatalog | readonly string[],): WorkLouderCodexTaskCatalog {diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.tsindex 92da81b703..34d7ee0569 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts@@ -61,6 +61,84 @@ describe('WorkLouderCodexHostClient', () => {expect(child.postMessage).toHaveBeenCalledWith({ kind: 'apply', frame });});+ it('releases the HID host when this instance turns the keyboard off', async () => {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ const status = vi.fn();+ client.setConnectionStatusHandler(status);+ client.setAgentKeyPressHandler(vi.fn());++ client.setDeviceEnabled(false);++ expect(child.postMessage).toHaveBeenCalledWith({ kind: 'stop' });+ expect(child.kill).not.toHaveBeenCalled();+ expect(status).toHaveBeenCalledWith('disabled');+ expect(fork).toHaveBeenCalledTimes(1);++ child.emit('message', { kind: 'stopped' });+ expect(child.kill).toHaveBeenCalledOnce();++ client.probe();+ expect(fork).toHaveBeenCalledTimes(2);+ expect(child.postMessage).toHaveBeenCalledWith({ kind: 'discover' });++ client.setDeviceEnabled(true);+ expect(fork).toHaveBeenCalledTimes(2);+ });++ it('restarts a still-wanted host after disable finishes stopping', () => {+ const stopping = new FakeChild();+ const restarted = new FakeChild();+ const children = [stopping, restarted];+ const fork = vi.fn(() => children.shift()!);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ client.setAgentKeyPressHandler(vi.fn());+ expect(fork).toHaveBeenCalledTimes(1);++ client.setDeviceEnabled(false);+ stopping.postMessage.mockClear();+ client.setDeviceEnabled(true);++ expect(fork).toHaveBeenCalledTimes(1);+ expect(stopping.postMessage).not.toHaveBeenCalled();++ stopping.emit('message', { kind: 'stopped' });++ expect(fork).toHaveBeenCalledTimes(2);+ expect(restarted.postMessage).toHaveBeenCalledWith({ kind: 'init', sdkEntry: '/sdk' });+ expect(restarted.postMessage).toHaveBeenCalledWith({ kind: 'listen' });+ });++ it('kills a host that never acknowledges stop after disable', async () => {+ vi.useFakeTimers();+ try {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ disposeTimeoutMs: 50,+ });+ client.setAgentKeyPressHandler(vi.fn());+ client.setDeviceEnabled(false);++ expect(child.kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(50);+ expect(child.kill).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });+it('starts HID listening even when there is no lighting activity', () => {const child = new FakeChild();const fork = vi.fn(() => child);@@ -96,6 +174,108 @@ describe('WorkLouderCodexHostClient', () => {expect(child.postMessage).toHaveBeenLastCalledWith({ kind: 'probe' });});+ it('discovers presence without occupying HID when this instance is off', () => {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ const presence = vi.fn();+ const status = vi.fn();+ client.setPresenceHandler(presence);+ client.setConnectionStatusHandler(status);+ client.setDeviceEnabled(false);+ status.mockClear();+ client.probe();++ expect(fork).toHaveBeenCalledWith('/sdk');+ expect(child.postMessage).toHaveBeenCalledWith({ kind: 'discover' });+ expect(child.postMessage).not.toHaveBeenCalledWith({ kind: 'listen' });++ child.emit('message', {+ kind: 'presence',+ present: true,+ deviceType: 'codex-micro',+ isUsbConnection: true,+ });+ expect(presence).toHaveBeenCalledWith(true, {+ deviceType: 'codex-micro',+ isUsbConnection: true,+ });+ expect(status).not.toHaveBeenCalled();+ });++ it('backs off presence-only host crashes instead of forking in a loop', async () => {+ vi.useFakeTimers();+ try {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ client.setDeviceEnabled(false);+ client.probe();+ expect(fork).toHaveBeenCalledTimes(1);++ child.emit('exit', 1);+ expect(fork).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(500);+ expect(fork).toHaveBeenCalledTimes(2);++ for (let crash = 0; crash < 5; crash += 1) {+ child.emit('exit', 1);+ await vi.advanceTimersByTimeAsync(10_000);+ }+ const forksAfterBudget = fork.mock.calls.length;+ child.emit('exit', 1);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(fork).toHaveBeenCalledTimes(forksAfterBudget);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let repeated presence probes postpone the crash-budget reset', async () => {+ vi.useFakeTimers();+ try {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ stableConnectionMs: 30,+ });+ client.setDeviceEnabled(false);+ client.probe();++ for (let crash = 0; crash < 5; crash += 1) {+ child.emit('exit', 1);+ await vi.advanceTimersByTimeAsync(10_000);+ }+ expect(fork.mock.calls.length).toBeGreaterThan(1);++ child.emit('message', { kind: 'presence', present: true, deviceType: 'codex-micro' });+ await vi.advanceTimersByTimeAsync(10);+ child.emit('message', { kind: 'presence', present: true, deviceType: 'codex-micro' });+ await vi.advanceTimersByTimeAsync(10);+ child.emit('message', { kind: 'presence', present: true, deviceType: 'codex-micro' });+ await vi.advanceTimersByTimeAsync(30);++ const forksBefore = fork.mock.calls.length;+ child.emit('exit', 1);+ await vi.advanceTimersByTimeAsync(500);+ expect(fork).toHaveBeenCalledTimes(forksBefore + 1);+ } finally {+ vi.useRealTimers();+ }+ });+it('asks the host to turn lighting off before shutdown', async () => {const child = new FakeChild();const client = new WorkLouderCodexHostClient({diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.tsindex 645a4ac5f2..6da826a87d 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.ts@@ -36,6 +36,87 @@ describe('WorkLouderCodexLightingController', () => {expect(sink.update).toHaveBeenCalledTimes(1);});+ it('lights a lead task key from a running Orca worker', async () => {+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(+ sink,+ vi.fn(),+ async () => ['lead-1'],+ vi.fn(),+ vi.fn(),+ async () => ({ 'lead-1': ['worker-1'] }),+ );+ await controller.resumeTaskSlots();+ sink.update.mockClear();++ controller.updateSessionActivity([+ {+ sessionId: 'worker-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);++ const frame = sink.update.mock.lastCall?.[0];+ expect(isWorkLouderCodexLightingFrameOff(frame)).toBe(false);+ expect(frame?.threads[0]?.brightness).toBeGreaterThan(0);+ });++ it('promotes an unslotted lead when only its worker is running', async () => {+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const catalog = [+ 'idle-1',+ 'idle-2',+ 'idle-3',+ 'idle-4',+ 'idle-5',+ 'idle-6',+ 'lead-outside',+ ];+ const loadWorkerSessions = vi.fn(async (leadIds: readonly string[]) => {+ expect(leadIds).toContain('lead-outside');+ return { 'lead-outside': ['worker-1'] };+ });+ const controller = new WorkLouderCodexLightingController(+ sink,+ vi.fn(),+ async () => catalog,+ vi.fn(),+ vi.fn(),+ loadWorkerSessions,+ );+ controller.applySettings(settings({ agentSource: 'priority' }));+ await controller.resumeTaskSlots();++ controller.updateSessionActivity([+ {+ sessionId: 'worker-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);++ expect(controller.getState().agentSlots[0]?.action).toMatchObject({+ type: 'task',+ sessionId: 'lead-outside',+ });+ expect(sink.update.mock.lastCall?.[0]?.threads[0]?.brightness).toBeGreaterThan(0);+ });+it('activates the task assigned to the pressed Agent key', async () => {const keyHandlerRef: { current: ((slot: number) => void) | null } = { current: null };const sink = {@@ -76,7 +157,7 @@ describe('WorkLouderCodexLightingController', () => {]);keyHandlerRef.current?.(1);- expect(activateSession).toHaveBeenCalledWith('waiting-session', false);+ expect(activateSession).toHaveBeenCalledWith('waiting-session', true);});it('maps last-sent keys by the last user message, not sidebar order', async () => {@@ -113,7 +194,7 @@ describe('WorkLouderCodexLightingController', () => {hidRef.current?.({ key: 'AG00', act: 1 });- expect(activateSession).toHaveBeenCalledWith('newer', false);+ expect(activateSession).toHaveBeenCalledWith('newer', true);});it('uses the published assignment for the current press and refreshes only later presses', async () => {@@ -151,7 +232,7 @@ describe('WorkLouderCodexLightingController', () => {sink.update.mockClear();keyHandlerRef.current?.(0);- expect(activateSession).toHaveBeenCalledWith('first', false);+ expect(activateSession).toHaveBeenCalledWith('first', true);expect(loadSlotSessionIds).toHaveBeenCalledTimes(2);resolveRefresh?.(['second']);await vi.waitFor(() => expect(sink.update).toHaveBeenCalledTimes(1));@@ -678,6 +759,7 @@ describe('WorkLouderCodexLightingController', () => {dispose: vi.fn(async () => undefined),};const controller = new WorkLouderCodexLightingController(sink, vi.fn());+ controller.applySettings(settings({ deviceEnabled: true }));controller.start();sink.setDeviceStateHandler.mock.calls.at(-1)?.[0]?.({deviceType: 'codex-micro',@@ -696,6 +778,40 @@ describe('WorkLouderCodexLightingController', () => {expect(controller.getState().device.inputMonitoringPermission).toBe('granted');});+ it('keeps the instance disabled while still recording keyboard presence', () => {+ const presenceRef: {+ current: ((+ present: boolean,+ identity?: { deviceType: 'codex-micro' | 'creator-micro-2'; isUsbConnection: boolean },+ ) => void) | null;+ } = { current: null };+ const statusRef: { current: ((status: 'connecting' | 'disabled') => void) | null } = {+ current: null,+ };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn((handler: typeof statusRef.current) => {+ statusRef.current = handler;+ }),+ setPresenceHandler: vi.fn((handler: typeof presenceRef.current) => {+ presenceRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn());+ controller.start();++ statusRef.current?.('connecting');+ presenceRef.current?.(true, { deviceType: 'codex-micro', isUsbConnection: true });++ expect(controller.getState().connectionStatus).toBe('disabled');+ expect(controller.getState().devicePresent).toBe(true);+ expect(controller.getState().device.deviceType).toBe('codex-micro');+ expect(controller.getState().device.isUsbConnection).toBe(true);+ });+it('delegates shutdown so the host can turn the device off', async () => {const sink = {update: vi.fn(),@@ -790,6 +906,77 @@ describe('WorkLouderCodexLightingController', () => {expect(dispatch).not.toHaveBeenCalledWith({ type: 'voice', phase: 'release' });});+ it('releases held voice and scroll when this instance turns the keyboard off', async () => {+ const hidRef: { current: ((event: { key: string; act: number }) => void) | null } = {+ current: null,+ };+ const joystickRef: { current: ((event: { angle: number; distance: number }) => void) | null } = {+ current: null,+ };+ const dispatch = vi.fn();+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ setDeviceEnabled: vi.fn(),+ setHidInputHandler: vi.fn((handler: typeof hidRef.current) => {+ hidRef.current = handler;+ }),+ setJoystickInputHandler: vi.fn((handler: typeof joystickRef.current) => {+ joystickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), undefined, dispatch);+ controller.start();+ controller.applySettings(settings({ deviceEnabled: true }));+ await controller.resumeTaskSlots();+ hidRef.current?.({ key: 'ACT10', act: 1 });+ joystickRef.current?.({ angle: 0.25, distance: 1 });+ dispatch.mockClear();++ controller.applySettings(settings({ deviceEnabled: false }));++ expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'release' });+ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });+ expect(sink.setDeviceEnabled).toHaveBeenLastCalledWith(false);+ });++ it('releases held voice and scroll when the layout editor opens', async () => {+ const hidRef: { current: ((event: { key: string; act: number }) => void) | null } = {+ current: null,+ };+ const joystickRef: { current: ((event: { angle: number; distance: number }) => void) | null } = {+ current: null,+ };+ const dispatch = vi.fn();+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ setHidInputHandler: vi.fn((handler: typeof hidRef.current) => {+ hidRef.current = handler;+ }),+ setJoystickInputHandler: vi.fn((handler: typeof joystickRef.current) => {+ joystickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), undefined, dispatch);+ controller.start();+ await controller.resumeTaskSlots();+ hidRef.current?.({ key: 'ACT10', act: 1 });+ joystickRef.current?.({ angle: 0.25, distance: 1 });+ dispatch.mockClear();++ controller.setLayoutPreviewActive(true);++ expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'release' });+ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });+ });+it('does not fire a held stick action after the account resumes', async () => {const joystickRef: { current: ((event: { angle: number; distance: number }) => void) | null } = {current: null,diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/actionWindow.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/actionWindow.test.tsnew file mode 100644index 0000000000..3db3b6cb10--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/actionWindow.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from 'vitest';++import type { WorkLouderCodexRendererAction } from '../../../shared/workLouderCodex.js';+import {+ createWorkLouderCodexActiveWindowRouter,+ workLouderCodexActionWindowTarget,+} from '../actionWindow.js';++function fakeWindow(id: string, options?: { destroyed?: boolean; loading?: boolean }) {+ return {+ id,+ isDestroyed: () => options?.destroyed === true,+ webContents: {+ isDestroyed: () => options?.destroyed === true,+ isLoading: () => options?.loading === true,+ },+ };+}++describe('workLouderCodexActionWindowTarget', () => {+ it('keeps encoder task switching on the primary window', () => {+ expect(+ workLouderCodexActionWindowTarget({+ type: 'command',+ commandId: 'session.selectNext',+ }),+ ).toBe('task-switch');+ expect(+ workLouderCodexActionWindowTarget({+ type: 'command',+ commandId: 'session.selectPrevious',+ }),+ ).toBe('task-switch');+ });++ it('sends voice, send, and scroll to the system frontmost app when Cindy is not focused', () => {+ expect(workLouderCodexActionWindowTarget({ type: 'voice', phase: 'press' })).toBe(+ 'system-frontmost',+ );+ expect(+ workLouderCodexActionWindowTarget({ type: 'command', commandId: 'composer.submit' }),+ ).toBe('system-frontmost');+ expect(+ workLouderCodexActionWindowTarget({+ type: 'scroll',+ direction: 'up',+ intensity: 1,+ }),+ ).toBe('system-frontmost');+ });+});++describe('createWorkLouderCodexActiveWindowRouter', () => {+ it('routes send to the focused secondary window and task switching to main', () => {+ const main = fakeWindow('main');+ const secondary = fakeWindow('secondary');+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => secondary,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main' || win?.id === 'secondary',+ });++ expect(router.resolve({ type: 'command', commandId: 'composer.submit' })).toBe(secondary);+ expect(router.resolve({ type: 'command', commandId: 'session.selectNext' })).toBe(main);+ });++ it('does not steal send from a utility window back to the main Cindy window', () => {+ const main = fakeWindow('main');+ const utility = fakeWindow('utility');+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => utility,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main',+ });++ expect(router.resolve({ type: 'command', commandId: 'composer.submit' })).toBeNull();+ });++ it('leaves voice, send, and scroll on the system frontmost app when Cindy is not focused', () => {+ const main = fakeWindow('main');+ const utility = fakeWindow('utility');+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => utility,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main',+ });++ expect(router.resolve({ type: 'voice', phase: 'press' })).toBeNull();+ expect(router.resolve({ type: 'command', commandId: 'composer.submit' })).toBeNull();+ expect(+ router.resolve({ type: 'scroll', direction: 'down', intensity: 0.8 }),+ ).toBeNull();+ });++ it('keeps a voice release on the window that received the press', () => {+ const main = fakeWindow('main');+ const secondary = fakeWindow('secondary');+ let focused = secondary;+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => focused,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main' || win?.id === 'secondary',+ });++ expect(router.resolve({ type: 'voice', phase: 'press' })).toBe(secondary);+ focused = main;+ expect(router.resolve({ type: 'voice', phase: 'release' })).toBe(secondary);+ expect(router.resolve({ type: 'command', commandId: 'composer.submit' })).toBe(main);+ });++ it('keeps joystick scroll on the window that started the push', () => {+ const main = fakeWindow('main');+ const secondary = fakeWindow('secondary');+ let focused = secondary;+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => focused,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main' || win?.id === 'secondary',+ });+ const scroll: WorkLouderCodexRendererAction = {+ type: 'scroll',+ direction: 'down',+ intensity: 0.8,+ };++ expect(router.resolve(scroll)).toBe(secondary);+ focused = main;+ expect(router.resolve(scroll)).toBe(secondary);+ expect(router.resolve({ type: 'scroll-stop' })).toBe(secondary);+ expect(router.resolve({ type: 'command', commandId: 'composer.submit' })).toBe(main);+ });++ it('does not let a scroll-stop steal the in-flight voice window', () => {+ const main = fakeWindow('main');+ const secondary = fakeWindow('secondary');+ let focused = secondary;+ const router = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => focused,+ getMainWindow: () => main,+ isActionWindow: (win) => win?.id === 'main' || win?.id === 'secondary',+ });++ expect(router.resolve({ type: 'voice', phase: 'press' })).toBe(secondary);+ expect(+ router.resolve({ type: 'scroll', direction: 'down', intensity: 0.8 }),+ ).toBe(secondary);+ focused = main;+ expect(router.resolve({ type: 'scroll-stop' })).toBe(secondary);+ expect(router.resolve({ type: 'voice', phase: 'release' })).toBe(secondary);+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.tsindex 13627f89b4..2199636e9f 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts@@ -8,6 +8,7 @@ import {isWorkLouderCodexHostMessage,isWorkLouderCodexLightingFrameOff,parseWorkLouderCodexAgentKeyPress,+ foldOrcaWorkerActivityOntoLeads,projectWorkLouderCodexSlotActivity,type WorkLouderCodexSessionActivity,WorkLouderLightingEffect,@@ -77,6 +78,27 @@ describe('createWorkLouderCodexLightingFrame', () => {expect(frame.threads[0].brightness).toBe(0);expect(frame.threads[1].brightness).toBeGreaterThan(0);});++ it('lights the lead task key when only an Orca worker is running', () => {+ const folded = foldOrcaWorkerActivityOntoLeads(+ [activity('worker-1', 'running')],+ { 'lead-1': ['worker-1'] },+ );+ const frame = createWorkLouderCodexLightingFrame(folded, ['lead-1']);++ expect(folded).toEqual([activity('worker-1', 'running'), activity('lead-1', 'running')]);+ expect(frame.ambient.effect).toBe(WorkLouderLightingEffect.Snake);+ expect(frame.threads[0].brightness).toBeGreaterThan(0);+ });++ it('keeps a lead question ahead of a running worker', () => {+ const folded = foldOrcaWorkerActivityOntoLeads(+ [activity('lead-1', 'needs-interaction'), activity('worker-1', 'running')],+ { 'lead-1': ['worker-1'] },+ );++ expect(folded[0]).toEqual(activity('lead-1', 'needs-interaction'));+ });});describe('Work Louder Agent key protocol', () => {@@ -100,6 +122,25 @@ describe('Work Louder Agent key protocol', () => {expect(isWorkLouderCodexHostMessage({ kind: 'device-activity' })).toBe(false);expect(isWorkLouderCodexHostMessage(null)).toBe(false);});++ it('accepts presence discovery with optional identity', () => {+ expect(isWorkLouderCodexHostMessage({ kind: 'presence', present: false })).toBe(true);+ expect(+ isWorkLouderCodexHostMessage({+ kind: 'presence',+ present: true,+ deviceType: 'codex-micro',+ isUsbConnection: true,+ }),+ ).toBe(true);+ expect(+ isWorkLouderCodexHostMessage({+ kind: 'presence',+ present: true,+ deviceType: 'keyboard',+ }),+ ).toBe(false);+ });});describe('Work Louder lighting settings', () => {diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.tsindex 8d4f1662e2..6f65b3e625 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts@@ -33,6 +33,7 @@ function makeIpc(options?: {const getState = vi.fn((): WorkLouderCodexState => ({connectionStatus: 'connected',connectionReason: null,+ devicePresent: true,device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },settings: { ...settings },agentSlots: Array.from({ length: 6 }, (_, slot) => ({@@ -103,6 +104,7 @@ describe('Work Louder Codex settings IPC business body', () => {[{ lightingBrightness: -1 }, 'must be an integer'],[{ lightingBrightness: 101 }, 'must be an integer'],[{ lightingAutoDim: 'sometimes' }, 'lightingAutoDim is invalid'],+ [{ deviceEnabled: 1 }, 'must be a boolean'],[{ singleTapAgentKeys: 1 }, 'must be a boolean'],])('rejects invalid payload %j with INVALID_PARAMS', (value, messagePart) => {const { ipc, writeSettings, applySettings } = makeIpc();@@ -125,9 +127,10 @@ describe('Work Louder Codex settings IPC business body', () => {expect(writeSettings).toHaveBeenCalledWith(patch);expect(applySettings).toHaveBeenCalledWith({+ deviceEnabled: false,lightingBrightness: 40,lightingAutoDim: 'off',- agentSource: 'sidebar',+ agentSource: 'last-sent',customAgentKeys: [null, null, null, null, null, null],singleTapAgentKeys: false,layout: DEFAULT_SETTINGS.layout,@@ -199,6 +202,13 @@ describe('Work Louder Codex settings IPC business body', () => {expect(source).toContain('if (rendererTaskCatalogScope !== currentTaskCatalogScope())');expect(source).toContain('if (!scope) return;');expect(source).toContain('workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());');+ expect(source).toContain('workLouderCodexLightingController.start();');+ expect(source).toContain('const win = actionWindowRouter.resolve(action);');+ expect(source).toContain('if (systemFrontmostInput.handle(action)) return;');+ expect(source).toContain('return win === main || isSecondaryAppWindow(win);');+ expect(source.indexOf('applySettings(readWorkLouderCodexSettings())')).toBeLessThan(+ source.indexOf('workLouderCodexLightingController.start();'),+ );});it('still accepts a layout saved before voiceButtonMode was removed', () => {diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.tsindex 2b6e1479eb..8a32fd49a0 100644--- a/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.ts+++ b/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.ts@@ -34,6 +34,7 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({import {__testing,readWorkLouderCodexSettings,+ resetWorkLouderCodexSettings,writeWorkLouderCodexSettingsPatch,} from '../settingsStore.js';@@ -111,6 +112,35 @@ describe('Work Louder Codex settings store', () => {).toEqual({lightingBrightness: 60,lightingAutoDim: '1-minute',+ singleTapAgentKeys: false,+ });+ });++ it('keeps the keyboard enabled when restoring other defaults', () => {+ electronMock.userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'worklouder-settings-'));++ writeWorkLouderCodexSettingsPatch({+ deviceEnabled: true,+ lightingBrightness: 40,});+ const next = resetWorkLouderCodexSettings();++ expect(next).toEqual({+ ...createWorkLouderCodexDefaultSettings(),+ deviceEnabled: true,+ });+ expect(+ JSON.parse(+ fs.readFileSync(+ path.join(+ electronMock.userDataDir,+ 'owners',+ 'owner-a',+ 'worklouder-codex-settings.json',+ ),+ 'utf-8',+ ),+ ),+ ).toEqual({ deviceEnabled: true });});});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/systemFrontmostInput.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/systemFrontmostInput.test.tsnew file mode 100644index 0000000000..637af4ec35--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/systemFrontmostInput.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it, vi } from 'vitest';++import { joystickScrollSpeed } from '../../../shared/workLouderCodexScroll.js';+import {+ WINDOWS_WHEEL_DELTA,+ accumulateScrollNotches,+ createIntervalScrollPump,+ createMacHoldScrollPump,+ createWorkLouderCodexSystemFrontmostInput,+} from '../systemFrontmostInput.js';++describe('createWorkLouderCodexSystemFrontmostInput', () => {+ it('maps a held microphone to the global overlay start/end phases', () => {+ const triggerVoice = vi.fn();+ const input = createWorkLouderCodexSystemFrontmostInput({ triggerVoice });++ expect(input.handle({ type: 'voice', phase: 'press' })).toBe(true);+ expect(input.handle({ type: 'voice', phase: 'release' })).toBe(true);++ expect(triggerVoice).toHaveBeenNthCalledWith(1, 'start');+ expect(triggerVoice).toHaveBeenNthCalledWith(2, 'end');+ });++ it('sends Return for the send key', () => {+ const postKey = vi.fn(async () => undefined);+ const input = createWorkLouderCodexSystemFrontmostInput({+ runner: { postKey, postScroll: vi.fn(async () => undefined) },+ createScrollPump: () => ({ setSpeed: vi.fn(), stop: vi.fn() }),+ });++ expect(input.handle({ type: 'command', commandId: 'composer.submit' })).toBe(true);+ expect(postKey).toHaveBeenCalledWith('return');+ });++ it('keeps a held stick scrolling until scroll-stop', () => {+ const speeds: number[] = [];+ const stop = vi.fn();+ const input = createWorkLouderCodexSystemFrontmostInput({+ createScrollPump: () => ({+ setSpeed: (pxPerSecond) => {+ speeds.push(pxPerSecond);+ },+ stop,+ }),+ });++ expect(input.handle({ type: 'scroll', direction: 'down', intensity: 1 })).toBe(true);+ expect(input.handle({ type: 'scroll', direction: 'up', intensity: 1 })).toBe(true);+ expect(input.handle({ type: 'scroll-stop' })).toBe(true);++ expect(speeds[0]).toBeCloseTo(-joystickScrollSpeed(1));+ expect(speeds[1]).toBeCloseTo(joystickScrollSpeed(1));+ expect(stop).toHaveBeenCalledOnce();+ });++ it('discards a hold-scroll helper that finishes after stop', async () => {+ let resolveSpawn!: (child: {+ stdin: {+ write: ReturnType<typeof vi.fn>;+ end: ReturnType<typeof vi.fn>;+ on: ReturnType<typeof vi.fn>;+ destroyed: boolean;+ };+ kill: ReturnType<typeof vi.fn>;+ once: ReturnType<typeof vi.fn>;+ }) => void;+ const spawn = vi.fn(+ () =>+ new Promise<Parameters<typeof resolveSpawn>[0]>((resolve) => {+ resolveSpawn = resolve;+ }),+ );+ const fallback = { setSpeed: vi.fn(), stop: vi.fn() };+ const pump = createMacHoldScrollPump(fallback, spawn);++ pump.setSpeed(-800);+ pump.stop();+ const child = {+ stdin: { write: vi.fn(), end: vi.fn(), on: vi.fn(), destroyed: false },+ kill: vi.fn(),+ once: vi.fn(),+ };+ resolveSpawn(child);+ await Promise.resolve();++ expect(child.kill).toHaveBeenCalledOnce();+ expect(child.stdin.write).toHaveBeenCalledWith('stop\n', expect.any(Function));+ expect(child.stdin.on).toHaveBeenCalledWith('error', expect.any(Function));+ expect(fallback.stop).toHaveBeenCalled();+ });++ it('listens for hold-scroll stdin errors before writing speed', async () => {+ let resolveSpawn!: (child: {+ stdin: { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn>; on: ReturnType<typeof vi.fn>; destroyed: boolean };+ kill: ReturnType<typeof vi.fn>;+ once: ReturnType<typeof vi.fn>;+ }) => void;+ const spawn = vi.fn(+ () =>+ new Promise<Parameters<typeof resolveSpawn>[0]>((resolve) => {+ resolveSpawn = resolve;+ }),+ );+ const pump = createMacHoldScrollPump({ setSpeed: vi.fn(), stop: vi.fn() }, spawn);+ pump.setSpeed(-800);+ const child = {+ stdin: { write: vi.fn(), end: vi.fn(), on: vi.fn(), destroyed: false },+ kill: vi.fn(),+ once: vi.fn(),+ };+ resolveSpawn(child);+ await Promise.resolve();++ expect(child.stdin.on).toHaveBeenCalledWith('error', expect.any(Function));+ expect(child.stdin.write).toHaveBeenCalledWith('-800\n', expect.any(Function));+ });++ it('keeps sub-notch Windows wheel remainders across ticks', () => {+ let state = accumulateScrollNotches(0, 42);+ expect(state).toEqual({ remainder: 42, deltaY: 0 });+ state = accumulateScrollNotches(state.remainder, 42);+ expect(state).toEqual({ remainder: 84, deltaY: 0 });+ state = accumulateScrollNotches(state.remainder, 42);+ expect(state).toEqual({ remainder: 6, deltaY: WINDOWS_WHEEL_DELTA });+ });++ it('posts a Windows wheel notch only after leftover pixels accumulate', async () => {+ vi.useFakeTimers();+ try {+ const postScroll = vi.fn(async () => undefined);+ let now = 1_000;+ const pump = createIntervalScrollPump(+ { postKey: vi.fn(async () => undefined), postScroll },+ () => now,+ WINDOWS_WHEEL_DELTA,+ );++ pump.setSpeed(2600);+ await vi.advanceTimersByTimeAsync(0);+ expect(postScroll).not.toHaveBeenCalled();++ now += 16;+ await vi.advanceTimersByTimeAsync(16);+ now += 16;+ await vi.advanceTimersByTimeAsync(16);+ expect(postScroll).toHaveBeenCalledWith(WINDOWS_WHEEL_DELTA);++ pump.stop();+ postScroll.mockClear();+ pump.setSpeed(2600);+ await vi.advanceTimersByTimeAsync(0);+ expect(postScroll).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/actionWindow.ts b/apps/desktop/src/main/worklouder-codex/actionWindow.tsnew file mode 100644index 0000000000..275f97e684--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/actionWindow.ts@@ -0,0 +1,148 @@+import type { WorkLouderCodexRendererAction } from '../../shared/workLouderCodex.js';++export interface WorkLouderCodexActionWindowLike {+ isDestroyed(): boolean;+ webContents?: {+ isDestroyed(): boolean;+ isLoading(): boolean;+ };+}++export type WorkLouderCodexActionWindowTarget = 'task-switch' | 'active-window' | 'system-frontmost';++/**+ * Task switching stays on the primary Cindy window so the six task keys keep+ * one stable owner. Voice, send, and scroll follow the focused Cindy window+ * when Cindy is frontmost; otherwise they go to the system frontmost app.+ */+const TASK_SWITCH_COMMANDS = new Set(['session.selectPrevious', 'session.selectNext']);+const SYSTEM_FRONTMOST_COMMANDS = new Set(['composer.submit']);++export function workLouderCodexActionWindowTarget(+ action: WorkLouderCodexRendererAction,+): WorkLouderCodexActionWindowTarget {+ if (action.type === 'command' && TASK_SWITCH_COMMANDS.has(action.commandId)) {+ return 'task-switch';+ }+ if (+ action.type === 'voice' ||+ action.type === 'scroll' ||+ action.type === 'scroll-stop' ||+ (action.type === 'command' && SYSTEM_FRONTMOST_COMMANDS.has(action.commandId))+ ) {+ return 'system-frontmost';+ }+ return 'active-window';+}++export function isSendableWorkLouderCodexWindow(+ win: WorkLouderCodexActionWindowLike | null | undefined,+): win is WorkLouderCodexActionWindowLike {+ return Boolean(+ win &&+ !win.isDestroyed() &&+ win.webContents &&+ !win.webContents.isDestroyed() &&+ !win.webContents.isLoading(),+ );+}++type HeldGesture = 'voice' | 'scroll';++function heldGestureFor(action: WorkLouderCodexRendererAction): HeldGesture | null {+ if (action.type === 'voice') return 'voice';+ if (action.type === 'scroll' || action.type === 'scroll-stop') return 'scroll';+ return null;+}++function isHeldGestureStart(action: WorkLouderCodexRendererAction): boolean {+ return (action.type === 'voice' && action.phase === 'press') || action.type === 'scroll';+}++function isHeldGestureEnd(action: WorkLouderCodexRendererAction): boolean {+ return (action.type === 'voice' && action.phase === 'release') || action.type === 'scroll-stop';+}++/**+ * Sticky held gestures stay on the window that received the press. A focus+ * change mid-hold must not split press and release across two composers.+ * Voice and scroll keep independent slots so one finishing cannot steal the+ * other's target.+ */+export function createWorkLouderCodexActiveWindowRouter<+ TWindow extends WorkLouderCodexActionWindowLike,+>(deps: {+ getFocusedWindow: () => TWindow | null;+ getMainWindow: () => TWindow | null;+ isActionWindow: (win: TWindow | null | undefined) => boolean;+}) {+ const held = {+ voice: { window: null as TWindow | null, onSystemFrontmost: false },+ scroll: { window: null as TWindow | null, onSystemFrontmost: false },+ };++ function isUsableActionWindow(win: TWindow | null | undefined): win is TWindow {+ return isSendableWorkLouderCodexWindow(win) && deps.isActionWindow(win);+ }++ function resolveFocusedCindyWindow(): TWindow | null {+ const focused = deps.getFocusedWindow();+ return isUsableActionWindow(focused) ? focused : null;+ }++ function resolveActiveCindyWindow(): TWindow | null {+ return resolveFocusedCindyWindow() ?? (() => {+ const main = deps.getMainWindow();+ return isUsableActionWindow(main) ? main : null;+ })();+ }++ function resolveHeldOrFocusedCindyWindow(gesture: HeldGesture): TWindow | null {+ const slot = held[gesture];+ if (isUsableActionWindow(slot.window)) return slot.window;+ slot.window = null;+ return resolveFocusedCindyWindow();+ }++ return {+ resolve(action: WorkLouderCodexRendererAction): TWindow | null {+ const target = workLouderCodexActionWindowTarget(action);+ if (target === 'task-switch') {+ const main = deps.getMainWindow();+ return isSendableWorkLouderCodexWindow(main) ? main : null;+ }++ const stayOnCindy = target !== 'system-frontmost';+ const gesture = heldGestureFor(action);+ if (gesture && isHeldGestureStart(action)) {+ const slot = held[gesture];+ if (slot.onSystemFrontmost) return null;+ const win = stayOnCindy ? resolveActiveCindyWindow() : resolveHeldOrFocusedCindyWindow(gesture);+ if (win) {+ slot.window = win;+ slot.onSystemFrontmost = false;+ return win;+ }+ if (!stayOnCindy) {+ slot.onSystemFrontmost = true;+ slot.window = null;+ }+ return null;+ }+ if (gesture && isHeldGestureEnd(action)) {+ const slot = held[gesture];+ if (slot.onSystemFrontmost) {+ slot.onSystemFrontmost = false;+ slot.window = null;+ return null;+ }+ const win = resolveHeldOrFocusedCindyWindow(gesture);+ slot.window = null;+ slot.onSystemFrontmost = false;+ return win;+ }++ return stayOnCindy ? resolveActiveCindyWindow() : resolveFocusedCindyWindow();+ },+ };+}diff --git a/apps/desktop/src/main/worklouder-codex/index.ts b/apps/desktop/src/main/worklouder-codex/index.tsindex 47ee4e04ed..b119ea76df 100644--- a/apps/desktop/src/main/worklouder-codex/index.ts+++ b/apps/desktop/src/main/worklouder-codex/index.ts@@ -4,8 +4,9 @@ import path from 'node:path';import { BrowserWindow, ipcMain, shell, utilityProcess } from 'electron';import { createLogger } from '../logger.js';-import { openMainWindowSession, sendMainWindowMessage } from '../deepLink.js';+import { getDeepLinkMainWindow, openMainWindowSession, sendMainWindowMessage } from '../deepLink.js';import { registerInputDevice } from '../input-devices/registry.js';+import { isSecondaryAppWindow } from '../secondary-windows.js';import {WORKLOUDER_CODEX_ACTION_CHANNEL,WORKLOUDER_CODEX_DEVICE,@@ -32,6 +33,8 @@ import {} from './WorkLouderCodexHostClient.js';import { WorkLouderCodexLightingController } from './WorkLouderCodexLightingController.js';import { createWorkLouderCodexSettingsIpc } from './settingsIpc.js';+import { createWorkLouderCodexActiveWindowRouter } from './actionWindow.js';+import { createWorkLouderCodexSystemFrontmostInput } from './systemFrontmostInput.js';import {createWorkLouderCodexWindowRevealGate,noteWorkLouderCodexWindowVisibility,@@ -45,6 +48,7 @@ import {resetWorkLouderCodexSettings,writeWorkLouderCodexSettingsPatch,} from './settingsStore.js';+import { listWorkersByLeads } from '../localDb/orcaTeamStore.js';import {buildWorkLouderCodexTaskCatalog,listWorkLouderCodexTaskCatalog,@@ -149,6 +153,16 @@ export const workLouderCodexLightingController = new WorkLouderCodexLightingCont},dispatchRendererAction,dispatchPreviewInput,+ async (leadSessionIds) => {+ if (leadSessionIds.length === 0) return {};+ const grouped = await listWorkersByLeads(leadSessionIds);+ return Object.fromEntries(+ Object.entries(grouped).map(([leadId, workers]) => [+ leadId,+ workers.map((worker) => worker.sessionId),+ ]),+ );+ },);let settingsIpcRegistered = false;@@ -187,8 +201,8 @@ export function registerWorkLouderCodexSettingsIpc(): void {if (settingsIpcRegistered) return;settingsIpcRegistered = true;- workLouderCodexLightingController.start();workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());+ workLouderCodexLightingController.start();const handlers = createWorkLouderCodexSettingsIpc({assertTrustedSender: (event) => assertTrustedAppRendererEvent(event as never),getState: () => workLouderCodexLightingController.getState(),@@ -235,6 +249,23 @@ export function registerWorkLouderCodexSettingsIpc(): void {});}+const actionWindowRouter = createWorkLouderCodexActiveWindowRouter({+ getFocusedWindow: () => BrowserWindow.getFocusedWindow(),+ getMainWindow: getDeepLinkMainWindow,+ isActionWindow: (win) => {+ if (!win) return false;+ const main = getDeepLinkMainWindow();+ return win === main || isSecondaryAppWindow(win);+ },+});+const systemFrontmostInput = createWorkLouderCodexSystemFrontmostInput();++function sendWindowMessage(win: BrowserWindow, channel: string, payload: unknown): boolean {+ if (win.webContents.isDestroyed() || win.webContents.isLoading()) return false;+ win.webContents.send(channel, payload);+ return true;+}+function dispatchRendererAction(action: WorkLouderCodexRendererAction): void {if (action.type === 'external-url') {void shell.openExternal(action.url).catch((error: unknown) => {@@ -244,11 +275,12 @@ function dispatchRendererAction(action: WorkLouderCodexRendererAction): void {});return;}- if (!sendMainWindowMessage(WORKLOUDER_CODEX_ACTION_CHANNEL, action)) {- log.debug('Codex Micro action skipped because the main renderer is not ready', {- type: action.type,- });- }+ const win = actionWindowRouter.resolve(action);+ if (win && sendWindowMessage(win, WORKLOUDER_CODEX_ACTION_CHANNEL, action)) return;+ if (systemFrontmostInput.handle(action)) return;+ log.debug('Codex Micro action skipped because no ready Cindy window can receive it', {+ type: action.type,+ });}function dispatchPreviewInput(input: WorkLouderCodexPreviewInput): void {diff --git a/apps/desktop/src/main/worklouder-codex/protocol.ts b/apps/desktop/src/main/worklouder-codex/protocol.tsindex 0c82593283..f940c33d5d 100644--- a/apps/desktop/src/main/worklouder-codex/protocol.ts+++ b/apps/desktop/src/main/worklouder-codex/protocol.ts@@ -56,6 +56,7 @@ export type WorkLouderCodexHostRequest =// talk to the device — this is that something, driven by whoever is// currently showing connection state.| { kind: 'probe' }+ | { kind: 'discover' }| { kind: 'stop' };export type WorkLouderCodexHostMessage =@@ -67,6 +68,12 @@ export type WorkLouderCodexHostMessage =/** Legacy utility-host message retained for older host fakes and upgrades. */| { kind: 'agent-key'; slot: number }| { kind: 'device'; device: WorkLouderCodexDeviceState }+ | {+ kind: 'presence';+ present: boolean;+ deviceType?: 'codex-micro' | 'creator-micro-2';+ isUsbConnection?: boolean;+ }| { kind: 'hid'; event: WorkLouderCodexHidEvent }| { kind: 'joystick'; event: WorkLouderCodexJoystickEvent }| { kind: 'activity' }@@ -142,6 +149,53 @@ export function selectWorkLouderCodexSlotActivity(return activity.filter(isLightingVisibleActivity).slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT);}+/**+ * Copy worker lighting onto the lead task key.+ *+ * Agent keys and LEDs are assigned to the lead session. Orca workers are+ * separate sessions, so a team that is still working would otherwise look idle+ * as soon as the lead turn finished.+ */+export function foldOrcaWorkerActivityOntoLeads(+ activity: readonly WorkLouderCodexSessionActivity[],+ workersByLead: Readonly<Record<string, readonly string[]>>,+): WorkLouderCodexSessionActivity[] {+ const byId = new Map(activity.map((item) => [item.sessionId, item]));+ let changed = false;+ const next = [...activity];+ for (const [leadId, workerIds] of Object.entries(workersByLead)) {+ if (workerIds.length === 0) continue;+ let best = lightingActivityOrNull(byId.get(leadId));+ for (const workerId of workerIds) {+ const worker = lightingActivityOrNull(byId.get(workerId));+ if (!worker) continue;+ if (!best || lightingActivityRank(worker) > lightingActivityRank(best)) {+ best = { ...worker, sessionId: leadId };+ }+ }+ if (!best) continue;+ const existingIndex = next.findIndex((item) => item.sessionId === leadId);+ if (existingIndex === -1) {+ next.push(best);+ changed = true;+ } else if (lightingActivityRank(best) > lightingActivityRank(next[existingIndex]!)) {+ next[existingIndex] = best;+ changed = true;+ }+ }+ return changed ? next : activity as WorkLouderCodexSessionActivity[];+}++function lightingActivityOrNull(+ item: WorkLouderCodexSessionActivity | undefined,+): WorkLouderCodexSessionActivity | null {+ return item && isLightingVisibleActivity(item) ? item : null;+}++function lightingActivityRank(item: WorkLouderCodexSessionActivity): number {+ return (PHASE_PRIORITY[item.phase] ?? 0) + (item.attention ? 0.1 : 0);+}+/** Aligns activity LEDs with an explicit six-task key assignment when one is available. */export function projectWorkLouderCodexSlotActivity(activity: readonly WorkLouderCodexSessionActivity[],@@ -288,6 +342,18 @@ export function isWorkLouderCodexHostMessage(value: unknown): value is WorkLoude}if (message.kind === 'device')return isWorkLouderCodexDeviceState((message as { device?: unknown }).device);+ if (message.kind === 'presence') {+ const present = (message as { present?: unknown }).present;+ const deviceType = (message as { deviceType?: unknown }).deviceType;+ const isUsbConnection = (message as { isUsbConnection?: unknown }).isUsbConnection;+ return (+ typeof present === 'boolean' &&+ (deviceType === undefined ||+ deviceType === 'codex-micro' ||+ deviceType === 'creator-micro-2') &&+ (isUsbConnection === undefined || typeof isUsbConnection === 'boolean')+ );+ }if (message.kind === 'state') {const validStatus =message.status === 'connected' ||diff --git a/apps/desktop/src/main/worklouder-codex/settingsIpc.ts b/apps/desktop/src/main/worklouder-codex/settingsIpc.tsindex 72c028e87c..60cc7f2c7c 100644--- a/apps/desktop/src/main/worklouder-codex/settingsIpc.ts+++ b/apps/desktop/src/main/worklouder-codex/settingsIpc.ts@@ -22,6 +22,7 @@ import { WORKLOUDER_CODEX_TASK_OPTION_LIMIT } from './taskSlots.js';import { throwIpcError } from '../utils/ipcValidate.js';const SETTING_KEYS = [+ 'deviceEnabled','lightingBrightness','lightingAutoDim','agentSource',@@ -87,6 +88,12 @@ function parseSettingsPatch(value: unknown): WorkLouderCodexSettingsPatch {}patch.customAgentKeys = record.customAgentKeys.map((action) => parseAction(action, true));}+ if ('deviceEnabled' in record) {+ if (typeof record.deviceEnabled !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'deviceEnabled must be a boolean');+ }+ patch.deviceEnabled = record.deviceEnabled;+ }if ('singleTapAgentKeys' in record) {if (typeof record.singleTapAgentKeys !== 'boolean') {throwIpcError('INVALID_PARAMS', 'singleTapAgentKeys must be a boolean');diff --git a/apps/desktop/src/main/worklouder-codex/settingsStore.ts b/apps/desktop/src/main/worklouder-codex/settingsStore.tsindex b65298243b..6af2c46637 100644--- a/apps/desktop/src/main/worklouder-codex/settingsStore.ts+++ b/apps/desktop/src/main/worklouder-codex/settingsStore.ts@@ -130,6 +130,8 @@ function normalize(raw: unknown): WorkLouderCodexSettings {lightingAutoDim: isWorkLouderCodexAutoDim(value.lightingAutoDim)? value.lightingAutoDim: defaults.lightingAutoDim,+ deviceEnabled:+ typeof value.deviceEnabled === 'boolean' ? value.deviceEnabled : defaults.deviceEnabled,agentSource: normalizeWorkLouderCodexAgentSource(value.agentSource),customAgentKeys,singleTapAgentKeys:@@ -166,8 +168,12 @@ export function writeWorkLouderCodexSettingsPatch(}export function resetWorkLouderCodexSettings(): WorkLouderCodexSettings {+ const keepEnabled = store.read().deviceEnabled;const settings = store.reset();log.info('Work Louder Codex settings reset');+ // Restore-defaults resets layout and lighting, but never turns the keyboard off+ // after the user has already chosen to use it in this instance.+ if (keepEnabled) return writeWorkLouderCodexSettingsPatch({ deviceEnabled: true });return settings;}diff --git a/apps/desktop/src/main/worklouder-codex/systemFrontmostInput.ts b/apps/desktop/src/main/worklouder-codex/systemFrontmostInput.tsnew file mode 100644index 0000000000..15a0a2b527--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/systemFrontmostInput.ts@@ -0,0 +1,335 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++import type { ChildProcess } from 'node:child_process';++import { createLogger } from '../logger.js';+import {+ runMacTextInsertionHelperCommand,+ spawnMacTextInsertionHelper,+ triggerGlobalVoiceInputFromHardware,+} from '../voice-input/global.js';+import { joystickScrollSpeed } from '../../shared/workLouderCodexScroll.js';+import type { WorkLouderCodexRendererAction } from '../../shared/workLouderCodex.js';++const execFilePromise = promisify(execFile);+const log = createLogger('worklouder-codex-system-input');++export type SystemFrontmostInputRunner = {+ postKey(key: 'return'): Promise<void>;+ postScroll(deltaY: number): Promise<void>;+};++const DEFAULT_COMMAND_TIMEOUT_MS = 4_000;+const HOLD_SCROLL_TICK_MS = 16;+/** Windows wheel events are counted in 120-unit notches. */+export const WINDOWS_WHEEL_DELTA = 120;++export function accumulateScrollNotches(+ remainder: number,+ deltaY: number,+ notch = WINDOWS_WHEEL_DELTA,+): { remainder: number; deltaY: number } {+ if (notch <= 0) return { remainder: 0, deltaY };+ const total = remainder + deltaY;+ const notches = total < 0 ? Math.ceil(total / notch) : Math.floor(total / notch);+ const emitted = notches * notch;+ return { remainder: total - emitted, deltaY: emitted };+}++export type SystemFrontmostScrollPump = {+ setSpeed(pxPerSecond: number): void;+ stop(): void;+};++function defaultRunner(): SystemFrontmostInputRunner {+ return {+ async postKey(key) {+ if (process.platform === 'darwin') {+ await runMacTextInsertionHelperCommand(['--command', 'post-key', '--key', key]);+ return;+ }+ await postKeyFallback(key);+ },+ async postScroll(deltaY) {+ if (deltaY === 0) return;+ if (process.platform === 'darwin') {+ await runMacTextInsertionHelperCommand([+ '--command',+ 'post-scroll',+ '--scroll-delta-y',+ String(deltaY),+ ]);+ return;+ }+ await postScrollFallback(deltaY);+ },+ };+}++async function postKeyFallback(key: 'return'): Promise<void> {+ switch (process.platform) {+ case 'win32':+ await execFilePromise(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ 'Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")',+ ],+ { timeout: DEFAULT_COMMAND_TIMEOUT_MS, windowsHide: true },+ );+ return;+ case 'linux':+ await execFilePromise('xdotool', ['key', 'Return'], { timeout: DEFAULT_COMMAND_TIMEOUT_MS });+ return;+ default:+ throw new Error(`System frontmost ${key} is not supported on ${process.platform}.`);+ }+}++async function postScrollFallback(deltaY: number): Promise<void> {+ switch (process.platform) {+ case 'win32': {+ const clicks = Math.max(-20, Math.min(20, Math.round(deltaY / 120)));+ if (clicks === 0) return;+ await execFilePromise(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Cursor]::Position = [System.Windows.Forms.Cursor]::Position; $sig = '[DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, int dwData, UIntPtr dwExtraInfo);'; $t = Add-Type -MemberDefinition $sig -Name WlMouse -Namespace Win32 -PassThru; $t::mouse_event(0x0800, 0, 0, ${clicks * 120}, [UIntPtr]::Zero)`,+ ],+ { timeout: DEFAULT_COMMAND_TIMEOUT_MS, windowsHide: true },+ );+ return;+ }+ case 'linux':+ await execFilePromise(+ 'xdotool',+ ['click', '--repeat', String(Math.max(1, Math.abs(Math.round(deltaY / 40)))), deltaY > 0 ? '4' : '5'],+ { timeout: DEFAULT_COMMAND_TIMEOUT_MS },+ );+ return;+ default:+ throw new Error(`System frontmost scroll is not supported on ${process.platform}.`);+ }+}++export function createIntervalScrollPump(+ runner: SystemFrontmostInputRunner,+ now: () => number,+ wheelNotch = process.platform === 'win32' ? WINDOWS_WHEEL_DELTA : 0,+): SystemFrontmostScrollPump {+ let speed = 0;+ let lastAt = 0;+ let remainder = 0;+ let inFlight = false;+ let timer: ReturnType<typeof setInterval> | null = null;++ const tick = (): void => {+ if (speed === 0 || inFlight) return;+ const at = now();+ const elapsedMs = lastAt === 0 ? HOLD_SCROLL_TICK_MS : Math.max(1, at - lastAt);+ lastAt = at;+ let deltaY = Math.round((speed * Math.min(elapsedMs, 100)) / 1000);+ if (wheelNotch > 0) {+ const next = accumulateScrollNotches(remainder, deltaY, wheelNotch);+ remainder = next.remainder;+ deltaY = next.deltaY;+ }+ if (deltaY === 0) return;+ inFlight = true;+ void runner+ .postScroll(deltaY)+ .catch((error: unknown) => {+ log.warn('failed to scroll the frontmost app', {+ error: error instanceof Error ? error.message : String(error),+ });+ })+ .finally(() => {+ inFlight = false;+ });+ };++ return {+ setSpeed(pxPerSecond) {+ speed = pxPerSecond;+ if (pxPerSecond === 0) return;+ if (timer) return;+ lastAt = 0;+ tick();+ timer = setInterval(tick, HOLD_SCROLL_TICK_MS);+ timer.unref?.();+ },+ stop() {+ speed = 0;+ lastAt = 0;+ remainder = 0;+ if (!timer) return;+ clearInterval(timer);+ timer = null;+ },+ };+}++export type HoldScrollChild = Pick<ChildProcess, 'kill' | 'once'> & {+ stdin?: Pick<NonNullable<ChildProcess['stdin']>, 'write' | 'end' | 'destroyed' | 'on'> | null;+};++function ignoreHoldScrollStdinErrors(child: HoldScrollChild): void {+ child.stdin?.on('error', () => undefined);+}++function writeHoldScrollLine(child: HoldScrollChild, line: string): void {+ const stdin = child.stdin;+ if (!stdin || stdin.destroyed) return;+ try {+ stdin.write(line, () => undefined);+ } catch {+ // The helper may already have closed stdin.+ }+}++function discardHoldScrollChild(next: HoldScrollChild): void {+ ignoreHoldScrollStdinErrors(next);+ writeHoldScrollLine(next, 'stop\n');+ try {+ next.stdin?.end();+ } catch {+ // The helper may already have exited after the last wheel event.+ }+ next.kill();+}++export function createMacHoldScrollPump(+ fallback: SystemFrontmostScrollPump,+ spawn: () => Promise<HoldScrollChild> = () =>+ spawnMacTextInsertionHelper(['--command', 'hold-scroll']),+): SystemFrontmostScrollPump {+ let child: HoldScrollChild | null = null;+ let starting = false;+ let spawnGeneration = 0;+ let speed = 0;++ const writeSpeed = (): void => {+ if (!child) return;+ writeHoldScrollLine(child, `${Math.round(speed)}\n`);+ };++ const start = (): void => {+ if (starting || child) return;+ starting = true;+ const generation = ++spawnGeneration;+ void spawn()+ .then((next) => {+ if (generation !== spawnGeneration) {+ discardHoldScrollChild(next);+ return;+ }+ child = next;+ starting = false;+ ignoreHoldScrollStdinErrors(next);+ next.once('exit', () => {+ if (child === next) child = null;+ });+ writeSpeed();+ if (speed !== 0) fallback.stop();+ })+ .catch((error: unknown) => {+ if (generation !== spawnGeneration) return;+ starting = false;+ log.warn('failed to start frontmost scroll helper', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+ };++ return {+ setSpeed(pxPerSecond) {+ speed = pxPerSecond;+ if (child?.stdin && !child.stdin.destroyed) {+ writeSpeed();+ return;+ }+ fallback.setSpeed(pxPerSecond);+ if (pxPerSecond !== 0) start();+ },+ stop() {+ speed = 0;+ spawnGeneration += 1;+ starting = false;+ fallback.stop();+ if (child) {+ discardHoldScrollChild(child);+ child = null;+ }+ },+ };+}++function signedScrollSpeed(direction: 'up' | 'down', intensity: number): number {+ const speed = joystickScrollSpeed(intensity);+ return direction === 'up' ? speed : -speed;+}++export function createWorkLouderCodexSystemFrontmostInput(deps?: {+ runner?: SystemFrontmostInputRunner;+ triggerVoice?: (phase: 'start' | 'tap' | 'end') => void;+ now?: () => number;+ createScrollPump?: (runner: SystemFrontmostInputRunner) => SystemFrontmostScrollPump;+ spawnHoldScroll?: () => Promise<HoldScrollChild>;+}) {+ const runner = deps?.runner ?? defaultRunner();+ const triggerVoice = deps?.triggerVoice ?? triggerGlobalVoiceInputFromHardware;+ const now = deps?.now ?? Date.now;+ const fallbackPump = createIntervalScrollPump(runner, now);+ const scrollPump =+ deps?.createScrollPump?.(runner) ??+ (process.platform === 'darwin'+ ? createMacHoldScrollPump(fallbackPump, deps?.spawnHoldScroll)+ : fallbackPump);+ let scrolling = false;+ let voicePressed = false;++ return {+ handle(action: WorkLouderCodexRendererAction): boolean {+ if (action.type === 'voice') {+ if (action.phase === 'press') {+ if (!voicePressed) {+ voicePressed = true;+ triggerVoice('start');+ }+ return true;+ }+ if (voicePressed) {+ voicePressed = false;+ triggerVoice('end');+ }+ return true;+ }+ if (action.type === 'command' && action.commandId === 'composer.submit') {+ void runner.postKey('return').catch((error: unknown) => {+ log.warn('failed to send Return to the frontmost app', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return true;+ }+ if (action.type === 'scroll') {+ scrolling = true;+ scrollPump.setSpeed(signedScrollSpeed(action.direction, action.intensity));+ return true;+ }+ if (action.type === 'scroll-stop') {+ if (!scrolling) return true;+ scrolling = false;+ scrollPump.stop();+ return true;+ }+ return false;+ },+ };+}diff --git a/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.tsindex 6aa5e5254b..04c6747cc0 100644--- a/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts+++ b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts@@ -76,6 +76,7 @@ let latestFrame: WorkLouderCodexLightingFrame | null = null;let applyPending = false;let listenPending = false;let probePending = false;+let discoverPending = false;let hidListeningRequested = false;let applying = false;let applyTask: Promise<void> | null = null;@@ -102,6 +103,8 @@ if (parentPort) {requestApply();} else if (request?.kind === 'probe') {requestProbe();+ } else if (request?.kind === 'discover') {+ requestDiscover();} else if (request?.kind === 'stop') {void stop();}@@ -161,6 +164,12 @@ function requestProbe(): void {kickQueue();}+function requestDiscover(): void {+ if (stopping) return;+ discoverPending = true;+ kickQueue();+}+function kickQueue(): void {if (applying) return;const task = drainApplyQueue();@@ -174,8 +183,12 @@ function kickQueue(): void {async function drainApplyQueue(): Promise<void> {applying = true;try {- while ((applyPending || listenPending || probePending) && !stopping) {+ while ((applyPending || listenPending || probePending || discoverPending) && !stopping) {// Drop a stale handle before lighting or HID reuse it.+ if (discoverPending) {+ discoverPending = false;+ discoverPresence();+ }if (probePending) {probePending = false;await probeConnection();@@ -283,6 +296,47 @@ async function probeConnection(): Promise<void> {}}+function discoverPresence(): void {+ try {+ const candidate = findCandidates()[0];+ if (!candidate) {+ post({ kind: 'presence', present: false });+ return;+ }+ post({+ kind: 'presence',+ present: true,+ deviceType: candidate.deviceType,+ isUsbConnection: candidate.device.isUsbConnection === true,+ });+ } catch (error) {+ hostLog('debug', `presence discovery failed: ${safeErrorMessage(error)}`);+ post({ kind: 'presence', present: false });+ }+}++function findCandidates(): Array<{+ device: WorkLouderDevice;+ deviceType: 'codex-micro' | 'creator-micro-2';+}> {+ const loaded = loadSdk();+ const discovery = new loaded.WLDeviceDiscovery(sdkLogger);+ return [+ ...discovery.findWLDevices([loaded.DeviceType.CodexMicro]).map((device) => ({+ device,+ deviceType: 'codex-micro' as const,+ })),+ ...(loaded.DeviceType.CreatorMicroV2 === undefined+ ? []+ : discovery.findWLDevices([loaded.DeviceType.CreatorMicroV2]).map((device) => ({+ device,+ deviceType: 'creator-micro-2' as const,+ }))),+ ].toSorted(+ (left, right) => Number(right.device.isUsbConnection) - Number(left.device.isUsbConnection),+ );+}+async function listenForAgentKeys(): Promise<void> {try {const deviceApi = await ensureConnected();@@ -327,24 +381,9 @@ function safeErrorMessage(error: unknown): string {async function ensureConnected(): Promise<WorkLouderApi | null> {if (api && transportFaulted) await disconnect();if (api) return api;- const loaded = loadSdk();- const discovery = new loaded.WLDeviceDiscovery(sdkLogger);- const candidates = [- ...discovery.findWLDevices([loaded.DeviceType.CodexMicro]).map((device) => ({- device,- deviceType: 'codex-micro' as const,- })),- ...(loaded.DeviceType.CreatorMicroV2 === undefined- ? []- : discovery.findWLDevices([loaded.DeviceType.CreatorMicroV2]).map((device) => ({- device,- deviceType: 'creator-micro-2' as const,- }))),- ].toSorted(- (left, right) => Number(right.device.isUsbConnection) - Number(left.device.isUsbConnection),- );- const candidate = candidates[0];+ const candidate = findCandidates()[0];if (!candidate) return null;+ const loaded = loadSdk();const nextComm = new loaded.WLDeviceCommImpl(sdkLogger);if (!(await nextComm.connect(candidate.device))) return null;comm = nextComm;@@ -491,6 +530,7 @@ async function stop(): Promise<void> {stopping = true;listenPending = false;probePending = false;+ discoverPending = false;hidListeningRequested = false;clearRetry();try {diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsxindex 7943d2013b..50a064e777 100644--- a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx@@ -116,7 +116,8 @@ interface WorkLouderCodexEntryProps {export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodexEntryProps) {const { t } = useTranslation();- const status = state?.connectionStatus ?? 'connecting';+ const enabled = state?.settings.deviceEnabled ?? false;+ const status = enabled ? (state?.connectionStatus ?? 'connecting') : 'disabled';return (<buttontype="button"@@ -143,7 +144,12 @@ export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodex</span></span><span className="flex shrink-0 items-center gap-2">- <ConnectionStatus status={status} loading={loading} compact />+ <ConnectionStatus+ status={status}+ present={state?.devicePresent ?? null}+ loading={loading}+ compact+ /><ChevronRight size={16} className="text-[var(--text-tertiary)]" aria-hidden="true" /></span></button>@@ -151,7 +157,7 @@ export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodex}export function WorkLouderCodexEntryContainer({ onOpen }: { onOpen(): void }) {- const { state, loading } = useWorkLouderCodex();+ const { state, loading } = useWorkLouderCodex({ watchConnection: true });return <WorkLouderCodexEntry state={state} loading={loading} onOpen={onOpen} />;}@@ -166,8 +172,6 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {resetSettings,openInputMonitoringSettings,reload,- // This page shows a live connection status, so it is the one place that- // polls the device — the entry row above it does not.} = useWorkLouderCodex({ watchConnection: true });const { skills, bootstrapped, refresh: refreshSkills } = useSkillhub();const [brightnessDraft, setBrightnessDraft] = useState(100);@@ -190,8 +194,7 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {[skills],);const isDefault =- state !== null &&- JSON.stringify(state.settings) === JSON.stringify(WORKLOUDER_CODEX_DEFAULT_SETTINGS);+ state !== null && workLouderCodexSettingsMatchRestoreDefaults(state.settings);useEffect(() => {if (state) setBrightnessDraft(state.settings.lightingBrightness);@@ -400,14 +403,32 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {<div className="flex min-w-0 flex-1 flex-col gap-2"><div className="flex flex-wrap items-center justify-between gap-2"><p className="text-13 font-medium text-[var(--text-primary)]">- {t('settings.shortcuts.workLouderCodex.connection.label')}+ {t('settings.shortcuts.workLouderCodex.connection.toggle.label')}</p>- <ConnectionStatus status={state?.connectionStatus ?? 'connecting'} loading={loading} />+ <div className="flex items-center gap-2">+ <Switch+ checked={settings.deviceEnabled}+ disabled={!state || saving}+ onCheckedChange={(checked) => void setSettings({ deviceEnabled: checked })}+ aria-label={t('settings.shortcuts.workLouderCodex.connection.toggle.aria')}+ />+ <ConnectionStatus+ status={+ settings.deviceEnabled+ ? (state?.connectionStatus ?? 'connecting')+ : 'disabled'+ }+ present={state?.devicePresent ?? null}+ loading={loading}+ />+ </div></div><p className="text-12 leading-[1.45] text-[var(--text-secondary)]">- {connectionDescription(t, state)}+ {settings.deviceEnabled ? connectionDescription(t, state) : presenceDescription(t)}</p>- {state?.connectionStatus === 'connected' && state.device.deviceType && (+ {((settings.deviceEnabled && state?.connectionStatus === 'connected') ||+ state?.devicePresent === true) &&+ state?.device.deviceType && (<div className="flex flex-wrap gap-2 pt-1"><DeviceChip icon={<Keyboard size={12} />}>{state.device.deviceType === 'creator-micro-2' ? 'Creator Micro 2' : 'Codex Micro'}@@ -712,7 +733,7 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {</div>)}- {state?.device.inputMonitoringPermission !== 'not-required' && (+ {state?.device.inputMonitoringPermission === 'denied' && (<SettingsGroup title={t('settings.shortcuts.workLouderCodex.device.title')}><SettingsRowlabel={t('settings.shortcuts.workLouderCodex.device.inputMonitoring.label')}@@ -1086,17 +1107,27 @@ function DeviceChip({ icon, children }: { icon?: ReactNode; children: ReactNodefunction ConnectionStatus({status,+ present = null,loading,compact = false,}: {status: WorkLouderCodexConnectionStatus;+ present?: boolean | null;loading: boolean;compact?: boolean;}) {const { t } = useTranslation();- const effectiveStatus = loading ? 'connecting' : status;+ const effectiveStatus = loading && status !== 'disabled' ? 'connecting' : status;+ const label =+ effectiveStatus === 'disabled'+ ? present === true+ ? t('settings.shortcuts.workLouderCodex.connection.status.connected')+ : present === false+ ? t('settings.shortcuts.workLouderCodex.connection.status.not-detected')+ : t('settings.shortcuts.workLouderCodex.connection.status.disabled')+ : t(`settings.shortcuts.workLouderCodex.connection.status.${effectiveStatus}`);const dotClass =- effectiveStatus === 'connected'+ effectiveStatus === 'connected' || (effectiveStatus === 'disabled' && present === true)? 'bg-[var(--settings-badge-connected)]': effectiveStatus === 'error' || effectiveStatus === 'unavailable'? 'bg-[var(--error-fg)]'@@ -1111,7 +1142,7 @@ function ConnectionStatus({)}><span className={cn('size-1.5 rounded-full', dotClass)} aria-hidden="true" />- {t(`settings.shortcuts.workLouderCodex.connection.status.${effectiveStatus}`)}+ {label}</span>);}@@ -1180,6 +1211,19 @@ function connectionDescription(return t(`settings.shortcuts.workLouderCodex.connection.descriptions.${key}`);}+function presenceDescription(t: ReturnType<typeof useTranslation>['t']): string {+ return t('settings.shortcuts.workLouderCodex.connection.descriptions.disabled');+}++function workLouderCodexSettingsMatchRestoreDefaults(+ settings: WorkLouderCodexState['settings'],+): boolean {+ return (+ JSON.stringify({ ...settings, deviceEnabled: false }) ===+ JSON.stringify({ ...WORKLOUDER_CODEX_DEFAULT_SETTINGS, deviceEnabled: false })+ );+}+/*** Human-readable name for whatever a key is bound to, for the hover tooltip.* Returns null when the binding has no name worth showing on its own.diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsxindex e01e0b8a70..e9ff798456 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx@@ -37,7 +37,12 @@ vi.mock('@/hooks/useWorkLouderCodex', () => ({state: {connectionStatus: 'connected',connectionReason: null,- device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },+ devicePresent: true,+ device: {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ deviceType: 'codex-micro',+ isUsbConnection: true,+ },settings: {...createWorkLouderCodexDefaultSettings(),lightingBrightness: 70,@@ -124,6 +129,7 @@ describe('WorkLouderCodexSettings', () => {state={{connectionStatus: 'connected',connectionReason: null,+ devicePresent: true,device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },settings: createWorkLouderCodexDefaultSettings(),agentSlots: Array.from({ length: 6 }, (_, slot) => ({@@ -151,6 +157,37 @@ describe('WorkLouderCodexSettings', () => {).toBeTruthy();});+ it('shows connected on the shortcuts entry when the keyboard is present but this instance is off', () => {+ render(+ <WorkLouderCodexEntry+ state={{+ connectionStatus: 'connecting',+ connectionReason: null,+ devicePresent: true,+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },+ settings: createWorkLouderCodexDefaultSettings(),+ agentSlots: Array.from({ length: 6 }, (_, slot) => ({+ slot,+ sessionId: null,+ title: null,+ action: null,+ })),+ taskOptions: [],+ agentSlotCount: 6,+ }}+ loading={false}+ onOpen={vi.fn()}+ />,+ );++ expect(+ screen.getByText('settings.shortcuts.workLouderCodex.connection.status.connected'),+ ).toBeTruthy();+ expect(+ screen.queryByText('settings.shortcuts.workLouderCodex.connection.status.connecting'),+ ).toBeNull();+ });+it('shows the six task keys and writes the settings that remain on the panel', async () => {render(<WorkLouderCodexSettings onBack={vi.fn()} />);@@ -158,6 +195,11 @@ describe('WorkLouderCodexSettings', () => {// not individually clickable.expect(screen.getByRole('img', { name: /AG00/ })).toBeTruthy();expect(screen.getByRole('img', { name: /AG05/ })).toBeTruthy();+ expect(+ screen.queryByText('settings.shortcuts.workLouderCodex.device.inputMonitoring.label'),+ ).toBeNull();+ expect(screen.getByText('Codex Micro')).toBeTruthy();+ expect(screen.getByText('USB')).toBeTruthy();expect(screen.getByTestId('worklouder-codex-keyboard-layout').parentElement?.className).toContain('justify-center',);@@ -187,12 +229,19 @@ describe('WorkLouderCodexSettings', () => {);expect(mocks.setSettings).toHaveBeenCalledWith({ agentSource: 'last-sent' });+ fireEvent.click(+ screen.getByRole('switch', {+ name: 'settings.shortcuts.workLouderCodex.connection.toggle.aria',+ }),+ );+ expect(mocks.setSettings).toHaveBeenCalledWith({ deviceEnabled: true });+fireEvent.click(screen.getByRole('switch', {name: 'settings.shortcuts.workLouderCodex.agentKeys.singleTap.aria',}),);- expect(mocks.setSettings).toHaveBeenCalledWith({ singleTapAgentKeys: true });+ expect(mocks.setSettings).toHaveBeenCalledWith({ singleTapAgentKeys: false });});it('only lets a task key be set on its own under "custom"', async () => {diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsxindex b7ca6a374a..fe7c633285 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsx+++ b/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsx@@ -17,6 +17,7 @@ function state(return {connectionStatus,connectionReason: null,+ devicePresent: connectionStatus === 'connected' ? true : null,device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },settings: {...createWorkLouderCodexDefaultSettings(),diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 4e8682c9ac..ee8ced840f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3486,16 +3486,24 @@},"connection": {"label": "Connection",+ "toggle": {+ "label": "Enable",+ "aria": "Let this Cindy use Codex Micro"+ },"status": {"connecting": "Connecting","connected": "Connected","not-detected": "Not detected",+ "present": "Connected",+ "disabled": "Off","error": "Connection problem","unavailable": "SDK unavailable"},"descriptions": {"connecting": "Cindy is starting the Work Louder device service.","connected": "USB is connected. Cindy is listening for key presses and syncing task lighting.",+ "disabled": "When enabled, Cindy listens for key presses and shows task status with lighting.",+ "present": "When enabled, Cindy listens for key presses and shows task status with lighting.","not-detected": "Connect the keyboard with a data-capable USB cable. Close ChatGPT if it is using the device.","error": "Cindy could not communicate with the keyboard and is retrying automatically.","unavailable": "The official Work Louder SDK was not found. Keep a supported ChatGPT or Codex app installed, then restart Cindy.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 557d01249c..5823e31257 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3512,16 +3512,24 @@},"connection": {"label": "接続",+ "toggle": {+ "label": "有効",+ "aria": "この Cindy で Codex Micro を使う"+ },"status": {"connecting": "接続中","connected": "接続済み","not-detected": "検出されていません",+ "present": "接続済み",+ "disabled": "無効","error": "接続エラー","unavailable": "SDK を利用できません"},"descriptions": {"connecting": "Cindy が Work Louder デバイスサービスを起動しています。","connected": "USB 接続済みです。Cindy がキー入力を待ち受け、タスクのライトを同期しています。",+ "disabled": "有効にすると、Cindy がキー入力を待ち受け、ライトでタスクの状態を表示します。",+ "present": "有効にすると、Cindy がキー入力を待ち受け、ライトでタスクの状態を表示します。","not-detected": "データ通信対応の USB ケーブルで接続してください。ChatGPT がデバイスを使用している場合は終了してください。","error": "Cindy はキーボードと通信できませんでした。自動的に再試行しています。","unavailable": "公式 Work Louder SDK が見つかりません。Codex Micro 対応の ChatGPT または Codex アプリを残した状態で Cindy を再起動してください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6c8e3d64a3..a6caf9e57a 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3512,16 +3512,24 @@},"connection": {"label": "연결",+ "toggle": {+ "label": "사용",+ "aria": "이 Cindy에서 Codex Micro 사용"+ },"status": {"connecting": "연결 중","connected": "연결됨","not-detected": "감지되지 않음",+ "present": "연결됨",+ "disabled": "사용 안 함","error": "연결 문제","unavailable": "SDK 사용 불가"},"descriptions": {"connecting": "Cindy가 Work Louder 장치 서비스를 시작하고 있습니다.","connected": "USB가 연결되었습니다. Cindy가 키 입력을 수신하고 작업 조명을 동기화합니다.",+ "disabled": "켜면 Cindy가 키 입력을 수신하고 조명으로 작업 상태를 표시합니다.",+ "present": "켜면 Cindy가 키 입력을 수신하고 조명으로 작업 상태를 표시합니다.","not-detected": "데이터 전송을 지원하는 USB 케이블로 연결하세요. ChatGPT가 장치를 사용 중이면 종료하세요.","error": "Cindy가 키보드와 통신하지 못해 자동으로 다시 시도하고 있습니다.","unavailable": "공식 Work Louder SDK를 찾지 못했습니다. Codex Micro를 지원하는 ChatGPT 또는 Codex 앱을 유지한 뒤 Cindy를 다시 시작하세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8c4f6ed434..abf0a5f3c9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3485,16 +3485,24 @@},"connection": {"label": "连接",+ "toggle": {+ "label": "启用",+ "aria": "让这个 Cindy 占用 Codex Micro"+ },"status": {"connecting": "正在连接","connected": "已连接","not-detected": "未检测到",+ "present": "已连接",+ "disabled": "未启用","error": "连接异常","unavailable": "SDK 不可用"},"descriptions": {"connecting": "Cindy 正在启动 Work Louder 设备服务。","connected": "USB 已连接,Cindy 正在监听按键并同步任务灯效。",+ "disabled": "启用后,Cindy 会监听按键,并用灯光显示任务状态。",+ "present": "启用后,Cindy 会监听按键,并用灯光显示任务状态。","not-detected": "请用支持数据传输的 USB 线连接键盘;如果 ChatGPT 正在占用设备,请先关闭。","error": "Cindy 暂时无法与键盘通信,正在自动重试。","unavailable": "未找到官方 Work Louder SDK。请保留支持 Codex Micro 的 ChatGPT 或 Codex 应用,重启 Cindy 后再试。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 60dcc498fc..fcb29af464 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3512,16 +3512,24 @@},"connection": {"label": "連線",+ "toggle": {+ "label": "啟用",+ "aria": "讓這個 Cindy 占用 Codex Micro"+ },"status": {"connecting": "正在連線","connected": "已連線","not-detected": "未偵測到",+ "present": "已連線",+ "disabled": "未啟用","error": "連線異常","unavailable": "SDK 無法使用"},"descriptions": {"connecting": "Cindy 正在啟動 Work Louder 裝置服務。","connected": "USB 已連線,Cindy 正在監聽按鍵並同步任務燈效。",+ "disabled": "啟用後,Cindy 會監聽按鍵,並用燈光顯示任務狀態。",+ "present": "啟用後,Cindy 會監聽按鍵,並用燈光顯示任務狀態。","not-detected": "請用支援資料傳輸的 USB 線連接鍵盤;如果 ChatGPT 正在占用裝置,請先關閉。","error": "Cindy 暫時無法與鍵盤通訊,正在自動重試。","unavailable": "找不到官方 Work Louder SDK。請保留支援 Codex Micro 的 ChatGPT 或 Codex 應用程式,重新啟動 Cindy 後再試。",diff --git a/apps/desktop/src/shared/workLouderCodex.ts b/apps/desktop/src/shared/workLouderCodex.tsindex f34e7c6845..1e0fae2c77 100644--- a/apps/desktop/src/shared/workLouderCodex.ts+++ b/apps/desktop/src/shared/workLouderCodex.ts@@ -196,6 +196,8 @@ export interface WorkLouderCodexLayout {}export interface WorkLouderCodexSettings {+ /** When false, this Cindy instance does not occupy the HID device. */+ deviceEnabled: boolean;/** Overall lighting intensity, in percent. Zero keeps HID input active with LEDs off. */lightingBrightness: number;lightingAutoDim: WorkLouderCodexAutoDim;@@ -209,7 +211,12 @@ export interface WorkLouderCodexSettings {export type WorkLouderCodexSettingsPatch = Partial<WorkLouderCodexSettings>;export type WorkLouderCodexConnectionStatus =- 'connecting' | 'connected' | 'not-detected' | 'error' | 'unavailable';+ | 'connecting'+ | 'connected'+ | 'not-detected'+ | 'disabled'+ | 'error'+ | 'unavailable';export type WorkLouderCodexConnectionReason ='connection-timeout' | 'connection-failed' | 'permission-required' | 'sdk-unavailable' | null;@@ -239,6 +246,8 @@ export interface WorkLouderCodexAgentSlotState {export interface WorkLouderCodexState {connectionStatus: WorkLouderCodexConnectionStatus;connectionReason: WorkLouderCodexConnectionReason;+ /** USB/Bluetooth presence, independent of whether this Cindy occupies HID. */+ devicePresent: boolean | null;device: WorkLouderCodexDeviceState;settings: WorkLouderCodexSettings;agentSlots: WorkLouderCodexAgentSlotState[];@@ -307,11 +316,12 @@ export const WORKLOUDER_CODEX_DEFAULT_LAYOUT: WorkLouderCodexLayout = {};export const WORKLOUDER_CODEX_DEFAULT_SETTINGS: WorkLouderCodexSettings = {+ deviceEnabled: false,lightingBrightness: 100,lightingAutoDim: '3-minutes',- agentSource: 'sidebar',+ agentSource: 'last-sent',customAgentKeys: Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, () => null),- singleTapAgentKeys: false,+ singleTapAgentKeys: true,layout: WORKLOUDER_CODEX_DEFAULT_LAYOUT,};