Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 接入 Work Louder Codex Micro 键盘 (#2937)
Dash10528ab66575
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 1f98c3d36b..69244e6a28 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1533,6 +1533,13 @@ const config: ForgeConfig = {// utilityProcess(@parcel/watcher 的 native 崩溃隔离,见 watcher-host/)。target: 'preload',},+ {+ entry: 'src/main/worklouder-codex/workLouderCodexHostProcess.ts',+ config: 'vite.preload.config.ts',+ // 私有 Work Louder SDK + node-hid 只在独立 utilityProcess 内加载;+ // SDK 缺失或原生崩溃都不能影响 Electron main。+ target: 'preload',+ },{entry: 'src/main/workdir-probe-host/workdirProbeHostProcess.ts',config: 'vite.preload.config.ts',diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.tsindex 89f6f81933..f4ff429681 100644--- a/apps/desktop/src/main/__tests__/deepLink.test.ts+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts@@ -75,7 +75,9 @@ describe('internal main-window navigation', () => {isMinimized: () => true,show: vi.fn(),restore: vi.fn(),+ moveTop: vi.fn(),focus: vi.fn(),+ setAlwaysOnTop: vi.fn(),webContents: {isLoading: () => false,send,@@ -88,6 +90,13 @@ describe('internal main-window navigation', () => {expect(mainWindow.show).toHaveBeenCalledOnce();expect(mainWindow.restore).toHaveBeenCalledOnce();expect(mainWindow.focus).toHaveBeenCalledOnce();+ if (process.platform === 'win32') {+ expect(mainWindow.moveTop).toHaveBeenCalledOnce();+ expect(mainWindow.setAlwaysOnTop).not.toHaveBeenCalled();+ } else {+ expect(mainWindow.setAlwaysOnTop).toHaveBeenNthCalledWith(1, true);+ expect(mainWindow.setAlwaysOnTop).toHaveBeenNthCalledWith(2, false);+ }expect(send).toHaveBeenCalledWith('deep-link:navigate', {type: 'settings',tab: 'providers',diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex adf675652c..93471f3a99 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -165,6 +165,8 @@ export interface AgentIslandServiceDeps {nativeHost?: AgentIslandNativeRenderer;/** Main-process upgrade window used to classify remote daemon shutdowns. */isPlannedRemoteDaemonClose?: (sessionId: string) => boolean;+ /** Optional process-local consumer for task activity, such as hardware status lighting. */+ onSessionActivityChange?: (activity: readonly AgentIslandSessionActivity[]) => void;}interface AgentIslandNativeRenderer {@@ -596,6 +598,7 @@ export class AgentIslandService {} else {this.publishHidden(Date.now());}+ this.notifySessionActivityConsumer([]);}setAppFocused(focused: boolean): void {@@ -1407,6 +1410,7 @@ export class AgentIslandService {private emitSessionActivityToRenderer(): void {const payload = this.buildSessionActivityPayload();this.sessionActivityRelay.publish(payload);+ this.notifySessionActivityConsumer(payload);// 广播给所有 app content window(含「在新窗口打开」的副窗),不只主窗 —— 副窗也有侧栏、// 也订阅同一频道,只发主窗会让副窗卡片预览停在陈旧 summary(PR #246 review)。const windows = BrowserWindow.getAllWindows().filter(isAppContentWindow);@@ -1417,6 +1421,16 @@ export class AgentIslandService {}}+ private notifySessionActivityConsumer(activity: readonly AgentIslandSessionActivity[]): void {+ try {+ this.deps.onSessionActivityChange?.(activity);+ } catch (error) {+ log.warn('process-local session activity consumer failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+private publish(): void {const now = Date.now();if (!this.enabledSynced) {diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 18d82ff850..2b19f5e307 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -350,6 +350,17 @@ import { initAppBadgeService, clearAllSessionAttention } from './appBadgeServiceimport { initNotificationService } from './notificationService';import { initWecomGroupNotificationIpc } from './wecomGroupNotification';import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';+import {+ attachWorkLouderCodexWindowReveal,+} from './worklouder-codex/index.js';+import {+ disposeInputDevices,+ resumeInputDeviceTaskSlots,+ startInputDeviceRuntime,+ startInputDevices,+ suspendInputDeviceTaskSlots,+ updateInputDeviceSessionActivity,+} from './input-devices/index.js';import {isAppContentWindow,isFocusedAppContentWindow,@@ -1214,6 +1225,9 @@ async function teardownGhostProjectionBoundary(reason: string): Promise<void> {async function teardownAuthAccountBoundary(reason: string): Promise<void> {const blockingFailures: unknown[] = [];+ // Hardware must stop before the long async drain. Otherwise a held stick or+ // microphone keeps acting on the outgoing account while caches and IM stop.+ suspendInputDeviceTaskSlots();// The boundary is already marked pending by every caller. New actions now// fail closed; drain an action that crossed the boundary before closing its DB.try {@@ -3095,6 +3109,8 @@ const createWindow = () => {// 装饰动画闸门的兜底信号。主窗在 running turn 期间会关掉 backgroundThrottling,// 那之后 Renderer 的 visibilityState 就不再反映真实可见性,细节见模块头注释。installWindowHiddenBroadcast(mainWindow);+ // Keyboard hello when the window comes back from hide / minimize / Dock.+ attachWorkLouderCodexWindowReveal(mainWindow);// App badge: 用户把任意 Cindy 窗口点回前台(Dock 点击 / taskbar / alt-tab / 点窗口)即视为// 「已查看」,直接清空整个 dock 红点。badge 是 app 级状态,不该依赖当前停在哪个@@ -3285,6 +3301,9 @@ const registerIpcHandlers = () => {initAgentIslandService({getMainWindow: () => getWindow() ?? null,isPlannedRemoteDaemonClose: isCcMgrUpgradeInFlight,+ onSessionActivityChange: (activity) => {+ updateInputDeviceSessionActivity(activity);+ },})?.setAppFocused(hasFocusedAppWindow());// 定向 replay:快照只补发给刚完成 sessions 订阅的那一台控制端。若沿默认广播// 通道扇出,每次 subscribe 都会把 O(会话数) 的帧重复灌给其它所有控制端,@@ -6864,6 +6883,8 @@ app.on('ready', async () => {});registerIpcHandlers();+ startInputDeviceRuntime();+ startInputDevices();// 本机 FS 目录浏览(项目选择器「添加远程项目」逐级浏览;device-link 经隧道在被控端执行)。// 无 DB / 无登录依赖,随其它顶层 handler 一起注册即可。registerFsBrowseIpc();@@ -6945,6 +6966,15 @@ app.on('ready', async () => {userId,mode: dbClientTakeover.mode,});+ // Teardown already closed the keyboard. The renderer still enters the+ // main UI, so restore hardware even when the lifecycle client did not.+ try {+ await resumeInputDeviceTaskSlots();+ } catch (error) {+ dbClientLog.warn('Input device task slot refresh failed (non-fatal)', {+ error: error instanceof Error ? error.message : String(error),+ });+ }return;}if (dbClientTakeover.mode === 'unchanged') {@@ -6963,8 +6993,24 @@ app.on('ready', async () => {// held across a Ghost boundary), and starts consumers if the original// then() skipped them while boundaryPending.void ensureCurrentAccountProviderReadiness();+ // Logout suspends the keyboard. Relogin of the same owner still lands+ // here, so restore task slots even when the lifecycle client is reused.+ try {+ await resumeInputDeviceTaskSlots();+ } catch (error) {+ dbClientLog.warn('Input device task slot refresh failed (non-fatal)', {+ error: error instanceof Error ? error.message : String(error),+ });+ }return;}+ try {+ await resumeInputDeviceTaskSlots();+ } catch (error) {+ dbClientLog.warn('Input device task slot refresh failed (non-fatal)', {+ error: error instanceof Error ? error.message : String(error),+ });+ }// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。// 如果 worker takeover 失败并进入 inproc fallback,main _db 必须继续保留,// 否则 fallback 会拿到已关闭的连接。@@ -7515,6 +7561,7 @@ onQuit('rsb-window', () => rsbWindowController.dispose(), 'sync');onQuit('ghost-panel-windows', () => ghostPanelWindowsController.dispose(), 'sync');onQuit('app-badge-clear', () => clearAllSessionAttention(), 'sync');onQuit('session-drag-preview', () => disposeSessionDragPreview(), 'sync');+onQuit('input-devices', () => disposeInputDevices(), 'async');// 自带 adb 的常驻 server 守护进程随退出收掉(fire-and-forget detached spawn,// 不阻塞)。不收会一直锁安装目录里的 adb.exe,弄挂增量更新(os error 32)。onQuit('android-adb-kill-server', () => disposeAndroidAdb(), 'sync');diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.tsindex 8e778dc53f..6087100aa2 100644--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@ -288,9 +288,9 @@ export function handleIncomingShareFile(filePath: string, source: string): void}/**- * 把主窗口拉回前台 (show + restore + focus)。Windows 的外部协议唤起需要先- * 激活应用并提升目标窗口 z-order;macOS 额外使用 app.focus steal——- * 从浏览器等其它前台应用手里抢焦点,单靠 win.focus() 不可靠。+ * 把主窗口拉回前台。Windows 的外部协议唤起需要先激活应用并提升目标窗口+ * z-order;其它平台短暂置顶后 focus,macOS 再使用 app.focus steal 从其它+ * 前台应用手里抢回焦点。* 窗口不存在 / 已销毁时返回 false,调用方自行决定是否忽略。*/export function focusMainWindow(platform: NodeJS.Platform = process.platform): boolean {@@ -305,8 +305,15 @@ export function focusMainWindow(platform: NodeJS.Platform = process.platform): b// 不会把后台 Ghost workspace 请求扩大为强制抢前台。app.focus();win.moveTop();+ win.focus();+ return true;+ }+ win.setAlwaysOnTop(true);+ try {+ win.focus();+ } finally {+ if (!win.isDestroyed()) win.setAlwaysOnTop(false);}- win.focus();if (platform === 'darwin') app.focus({ steal: true });return true;}@@ -323,14 +330,30 @@ export function openMainWindowVoiceSettings(tab: 'voice-input' | 'providers'): v* 主进程内部发起的会话聚焦(workspace 槽 focus:true)。复用 deep link 的* 前台 + renderer dispatch 通道,行为与用户点 cindy://session/<id> 一致。*/-export function openMainWindowSession(sessionId: string): void {- dispatchDeepLink({ type: 'session', id: sessionId });+export function openMainWindowSession(sessionId: string, options?: { focus?: boolean }): void {+ dispatchDeepLink({ type: 'session', id: sessionId }, options?.focus !== false);+}++/** Sends a typed internal event to the primary renderer without broadcasting to utility windows. */+export function sendMainWindowMessage(channel: string, payload: unknown): boolean {+ const win = mainWindowRef;+ if (+ !win ||+ win.isDestroyed() ||+ !win.webContents ||+ win.webContents.isDestroyed() ||+ win.webContents.isLoading()+ ) {+ return false;+ }+ win.webContents.send(channel, payload);+ return true;}-function dispatchDeepLink(payload: DeepLinkPayload): void {+function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {// 纯前台意图:main 进程内消化。冷启动时窗口还没建,app 启动流程本身会前台,直接丢弃。if (payload.type === 'focus') {- focusMainWindow();+ if (shouldFocus) focusMainWindow();return;}const win = mainWindowRef;@@ -348,20 +371,15 @@ function dispatchDeepLink(payload: DeepLinkPayload): void {}pendingDeepLink = payload;log.debug('buffered pending deep link until renderer pull', payload);- if (win && !win.isDestroyed()) {- // 把窗口拉前台(用户点链接 / 右键的意图就是 focus app)- if (!win.isVisible()) win.show();- if (win.isMinimized()) win.restore();- win.focus();- }+ // Agent-key first tap may switch in the background. A buffered deep link+ // from that path must not steal the frontmost app.+ if (shouldFocus) focusMainWindow();return;}// 已运行场景:listener 必然挂着(MainLayout 已 mount),直接 send,不进 pending。// 同时把窗口拉前台 — open-url / second-instance 本身不会唤起,用户点链接的// 意图就是要看到 app。- if (!win.isVisible()) win.show();- if (win.isMinimized()) win.restore();- win.focus();+ if (shouldFocus) focusMainWindow();win.webContents.send('deep-link:navigate', payload);}@@ -420,14 +438,19 @@ function findAbsolutePathAfterFlag(argv: readonly string[], flag: string): strinif (typeof arg !== 'string') continue;if (arg === flag) {const next = argv[i + 1];- if (typeof next === 'string' && next.length > 0 && isAbsoluteFilesystemPath(next)) return next;+ if (typeof next === 'string' && next.length > 0 && isAbsoluteFilesystemPath(next))+ return next;// Electron's Windows second-instance argv can interleave Chromium switches// between our custom flag and Explorer's folder path. Recover by taking the// first absolute path after the flag instead of returning a Chromium flag.for (let j = i + 1; j < argv.length; j++) {const candidate = argv[j];- if (typeof candidate === 'string' && candidate.length > 0 && isAbsoluteFilesystemPath(candidate)) {+ if (+ typeof candidate === 'string' &&+ candidate.length > 0 &&+ isAbsoluteFilesystemPath(candidate)+ ) {return candidate;}}@@ -470,9 +493,7 @@ export function registerDeepLinkProtocol(): void {if (process.defaultApp) {// dev:用 Electron 解释器跑 main 入口if (process.argv.length >= 2) {- app.setAsDefaultProtocolClient(scheme, process.execPath, [- path.resolve(process.argv[1]),- ]);+ app.setAsDefaultProtocolClient(scheme, process.execPath, [path.resolve(process.argv[1])]);} else {app.setAsDefaultProtocolClient(scheme);}diff --git a/apps/desktop/src/main/input-devices/__tests__/registry.test.ts b/apps/desktop/src/main/input-devices/__tests__/registry.test.tsnew file mode 100644index 0000000000..c20276e010--- /dev/null+++ b/apps/desktop/src/main/input-devices/__tests__/registry.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ disposeInputDevices,+ listInputDevices,+ playInputDeviceWindowReveal,+ registerInputDevice,+ resumeInputDeviceTaskSlots,+ startInputDevices,+ suspendInputDeviceTaskSlots,+ updateInputDeviceSessionActivity,+ type InputDeviceHost,+} from '../registry.js';++function createHost(id: string, calls: string[]): InputDeviceHost {+ return {+ descriptor: {+ id,+ label: id,+ capabilities: [{ kind: 'commands' }],+ },+ start: () => {+ calls.push(`${id}:start`);+ },+ updateSessionActivity: () => {+ calls.push(`${id}:activity`);+ },+ playWindowReveal: () => {+ calls.push(`${id}:reveal`);+ },+ resumeTaskSlots: async () => {+ calls.push(`${id}:resume`);+ },+ suspendTaskSlots: () => {+ calls.push(`${id}:suspend`);+ },+ dispose: async () => {+ calls.push(`${id}:dispose`);+ },+ };+}++describe('input device registry', () => {+ afterEach(async () => {+ await disposeInputDevices();+ });++ it('fans host lifecycle out to every registered adapter', async () => {+ const calls: string[] = [];+ registerInputDevice(createHost('one', calls));+ registerInputDevice(createHost('two', calls));++ expect(listInputDevices().map((device) => device.id)).toEqual(['one', 'two']);++ startInputDevices();+ updateInputDeviceSessionActivity([]);+ playInputDeviceWindowReveal();+ await resumeInputDeviceTaskSlots();+ suspendInputDeviceTaskSlots();+ await disposeInputDevices();++ expect(calls).toEqual([+ 'one:start',+ 'two:start',+ 'one:activity',+ 'two:activity',+ 'one:reveal',+ 'two:reveal',+ 'one:resume',+ 'two:resume',+ 'one:suspend',+ 'two:suspend',+ 'one:dispose',+ 'two:dispose',+ ]);+ });+});diff --git a/apps/desktop/src/main/input-devices/index.ts b/apps/desktop/src/main/input-devices/index.tsnew file mode 100644index 0000000000..691e6baf9b--- /dev/null+++ b/apps/desktop/src/main/input-devices/index.ts@@ -0,0 +1,24 @@+import { registerWorkLouderCodexInputDevice } from '../worklouder-codex/index.js';++let started = false;++/** Register first-party adapters. Each adapter owns its HID, lights, and settings. */+export function registerBuiltInInputDevices(): void {+ registerWorkLouderCodexInputDevice();+}++export function startInputDeviceRuntime(): void {+ if (started) return;+ started = true;+ registerBuiltInInputDevices();+}++export {+ disposeInputDevices,+ listInputDevices,+ playInputDeviceWindowReveal,+ resumeInputDeviceTaskSlots,+ startInputDevices,+ suspendInputDeviceTaskSlots,+ updateInputDeviceSessionActivity,+} from './registry.js';diff --git a/apps/desktop/src/main/input-devices/registry.ts b/apps/desktop/src/main/input-devices/registry.tsnew file mode 100644index 0000000000..ee47d4054c--- /dev/null+++ b/apps/desktop/src/main/input-devices/registry.ts@@ -0,0 +1,50 @@+import type { AgentIslandSessionActivity } from '../../shared/agentIsland.js';+import type { InputDeviceDescriptor } from '../../shared/inputDevices.js';++export interface InputDeviceHost {+ readonly descriptor: InputDeviceDescriptor;+ start(): void;+ updateSessionActivity(activity: readonly AgentIslandSessionActivity[]): void;+ playWindowReveal?(): void;+ resumeTaskSlots(): Promise<void>;+ suspendTaskSlots(): void;+ dispose(): Promise<void>;+}++const hosts = new Map<string, InputDeviceHost>();++export function registerInputDevice(host: InputDeviceHost): void {+ hosts.set(host.descriptor.id, host);+}++export function listInputDevices(): InputDeviceDescriptor[] {+ return [...hosts.values()].map((host) => host.descriptor);+}++export function startInputDevices(): void {+ for (const host of hosts.values()) host.start();+}++export function updateInputDeviceSessionActivity(+ activity: readonly AgentIslandSessionActivity[],+): void {+ for (const host of hosts.values()) host.updateSessionActivity(activity);+}++export function playInputDeviceWindowReveal(): void {+ for (const host of hosts.values()) host.playWindowReveal?.();+}++export async function resumeInputDeviceTaskSlots(): Promise<void> {+ await Promise.all([...hosts.values()].map((host) => host.resumeTaskSlots()));+}++export function suspendInputDeviceTaskSlots(): void {+ for (const host of hosts.values()) host.suspendTaskSlots();+}++export async function disposeInputDevices(): Promise<void> {+ const registered = [...hosts.values()];+ hosts.clear();+ await Promise.all(registered.map((host) => host.dispose()));+}diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.tsindex 620dc28b65..a35d5bbaa7 100644--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts@@ -140,15 +140,24 @@ describe('account provider readiness wiring', () => {bootstrapSource.indexOf('ensureCurrentAccountProviderReadiness()', waitFn),).toBeGreaterThan(waitFn);+ const failed = bootstrapSource.indexOf("dbClientTakeover.mode === 'failed'");+ const failedResume = bootstrapSource.indexOf('await resumeInputDeviceTaskSlots();', failed);+ const failedReturn = bootstrapSource.indexOf('return;', failedResume);+ expect(failed).toBeGreaterThanOrEqual(0);+ expect(failedResume).toBeGreaterThan(failed);+ expect(failedReturn).toBeGreaterThan(failedResume);+const unchanged = bootstrapSource.indexOf("dbClientTakeover.mode === 'unchanged'");const unchangedEnsure = bootstrapSource.indexOf('ensureCurrentAccountProviderReadiness()',unchanged,);- const unchangedReturn = bootstrapSource.indexOf('return;', unchangedEnsure);+ const unchangedResume = bootstrapSource.indexOf('await resumeInputDeviceTaskSlots();', unchanged);+ const unchangedReturn = bootstrapSource.indexOf('return;', unchangedResume);expect(unchanged).toBeGreaterThanOrEqual(0);expect(unchangedEnsure).toBeGreaterThan(unchanged);- expect(unchangedReturn).toBeGreaterThan(unchangedEnsure);+ expect(unchangedResume).toBeGreaterThan(unchangedEnsure);+ expect(unchangedReturn).toBeGreaterThan(unchangedResume);expect(bootstrapSource).toContain('shouldKeepPendingReadinessStart');expect(bootstrapSource).toContain('shouldClearCatalogAfterJoiningPreviousScope');expect(bootstrapSource).toMatch(@@ -194,6 +203,7 @@ describe('account provider readiness wiring', () => {it('clears owner-scoped custom routes before replacing account runtimes', () => {const teardown = bootstrapSource.indexOf('async function teardownAuthAccountBoundary');+ const suspendHardware = bootstrapSource.indexOf('suspendInputDeviceTaskSlots();', teardown);const clearCustomProviders = bootstrapSource.indexOf('setCustomProviders([])', teardown);const makerShutdown = bootstrapSource.indexOf('await maker.shutdown()', teardown);const joinPrevious = bootstrapSource.indexOf(@@ -206,6 +216,8 @@ describe('account provider readiness wiring', () => {);expect(teardown).toBeGreaterThanOrEqual(0);+ expect(suspendHardware).toBeGreaterThan(teardown);+ expect(suspendHardware).toBeLessThan(clearCustomProviders);expect(clearCustomProviders).toBeGreaterThan(teardown);expect(makerShutdown).toBeGreaterThan(clearCustomProviders);expect(joinPrevious).toBeGreaterThan(makerShutdown);diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex 1cfe651453..194b6d1f5a 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -70,6 +70,9 @@ function parseCommand(raw: unknown): RsbWindowCommand {if (r.type === 'open-terminal') {return { type: 'open-terminal', sessionId: r.sessionId };}+ if (r.type === 'toggle-review-tab') {+ return { type: 'toggle-review-tab', sessionId: r.sessionId };+ }if (r.type === 'open-web-browser') {if (typeof r.url !== 'string' || r.url.length === 0) {throwIpcError('INVALID_PARAMS', 'command.url required');diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.tsindex 0f3690dbd7..a7ec3c4a77 100644--- a/apps/desktop/src/main/sidebarSettingsStore.ts+++ b/apps/desktop/src/main/sidebarSettingsStore.ts@@ -33,6 +33,7 @@ import {ownerScopedUserDataPath,} from './appSessionState.js';import { createLogger } from './logger.js';+import { resumeInputDeviceTaskSlots } from './input-devices/registry.js';import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';import {hasExclusiveSharedLegacyUserDataAccess,@@ -411,6 +412,7 @@ async function savePinnedOrder(rawRequest: unknown): Promise<string[]> {}if (changed) {broadcastPinnedOrderChanged(nextSettings.pinnedOrder, ownerStamp);+ refreshInputDeviceTaskSlotsAfterPinnedOrderChange();}return Array.from(nextSettings.pinnedOrder);}@@ -741,6 +743,14 @@ function claimLegacySidebarSettingsResult(): LegacySidebarClaimResult {return initializeScopedSidebarSettings(scopedPath, ownerKey, legacyPath);}+function refreshInputDeviceTaskSlotsAfterPinnedOrderChange(): void {+ void resumeInputDeviceTaskSlots().catch((error: unknown) => {+ log.warn('Input device task slot refresh failed after pinned-order change', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+}+export function registerSidebarSettingsIpc(): void {ipcMain.on('sidebar-settings:claim-renderer-legacy-owner-sync', (event) => {assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.tsnew file mode 100644index 0000000000..1e88d792b9--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexHostClient.ts@@ -0,0 +1,472 @@+import {+ isWorkLouderCodexHostMessage,+ isWorkLouderCodexLightingFrameOff,+ parseWorkLouderCodexAgentKeyPress,+ type WorkLouderCodexHidEvent,+ type WorkLouderCodexHostRequest,+ type WorkLouderCodexJoystickEvent,+ type WorkLouderCodexLightingFrame,+} from './protocol.js';+import type {+ WorkLouderCodexConnectionReason,+ WorkLouderCodexConnectionStatus,+ WorkLouderCodexDeviceState,+} from '../../shared/workLouderCodex.js';+import type { WorkLouderCodexLightingSink } from './WorkLouderCodexLightingController.js';++export interface WorkLouderCodexChildLike {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (message: unknown) => void): void;+ on(event: 'exit', listener: (code: number) => void): void;+ on(+ event: 'error',+ listener: (type: string | Error, location?: string, report?: string) => void,+ ): void;+ kill(): boolean;+}++export interface WorkLouderCodexLoggerLike {+ debug(...args: unknown[]): void;+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ error(...args: unknown[]): void;+}++export interface WorkLouderSdkLocation {+ entry: string;+ source: 'cindy-package' | 'openai-app';+}++export interface WorkLouderCodexHostClientDeps {+ resolveSdk(): WorkLouderSdkLocation | null;+ fork(sdkEntry: string): WorkLouderCodexChildLike;+ log: WorkLouderCodexLoggerLike;+ connectTimeoutMs?: number;+ disposeTimeoutMs?: number;+ /** How long a connection must stay up before the crash budget resets. */+ stableConnectionMs?: number;+}++/**+ * Lazy main-process proxy for the Work Louder utility process. The native HID+ * SDK is never loaded into Electron main and an idle Cindy never forks it.+ */+export class WorkLouderCodexHostClient implements WorkLouderCodexLightingSink {+ private child: WorkLouderCodexChildLike | null = null;+ private latestFrame: WorkLouderCodexLightingFrame | null = null;+ private restartTimer: ReturnType<typeof setTimeout> | null = null;+ private connectWatchdogTimer: ReturnType<typeof setTimeout> | null = null;+ private consecutiveCrashes = 0;+ private stableConnectionTimer: ReturnType<typeof setTimeout> | null = null;+ private lastStatus: 'connected' | 'not-detected' | 'error' | null = null;+ private recyclingChild = false;+ private disposed = false;+ private unavailableLogged = false;+ private disposePromise: Promise<void> | null = null;+ private finishDispose: (() => void) | null = null;+ private disposeTimer: ReturnType<typeof setTimeout> | null = null;+ private agentKeyPressHandler: ((slot: number) => void) | null = null;+ private deviceActivityHandler: (() => void) | null = null;+ private hidInputHandler: ((event: WorkLouderCodexHidEvent) => void) | null = null;+ private joystickInputHandler: ((event: WorkLouderCodexJoystickEvent) => void) | null = null;+ private deviceStateHandler: ((device: WorkLouderCodexDeviceState) => void) | null = null;+ private connectionReasonHandler: ((reason: WorkLouderCodexConnectionReason) => void) | null =+ null;+ private connectionStatusHandler: ((status: WorkLouderCodexConnectionStatus) => void) | null =+ null;+ private connectionStatus: WorkLouderCodexConnectionStatus = 'connecting';+ private connectionReason: WorkLouderCodexConnectionReason = null;+ private wantsHidInput = false;++ constructor(private readonly deps: WorkLouderCodexHostClientDeps) {}++ setAgentKeyPressHandler(handler: ((slot: number) => void) | null): void {+ this.agentKeyPressHandler = handler;+ this.updateHidListeningIntent();+ }++ setHidInputHandler(handler: ((event: WorkLouderCodexHidEvent) => void) | null): void {+ this.hidInputHandler = handler;+ this.updateHidListeningIntent();+ }++ setJoystickInputHandler(handler: ((event: WorkLouderCodexJoystickEvent) => void) | null): void {+ this.joystickInputHandler = handler;+ this.updateHidListeningIntent();+ }++ setDeviceStateHandler(handler: ((device: WorkLouderCodexDeviceState) => void) | null): void {+ this.deviceStateHandler = handler;+ }++ setConnectionReasonHandler(+ handler: ((reason: WorkLouderCodexConnectionReason) => void) | null,+ ): void {+ this.connectionReasonHandler = handler;+ handler?.(this.connectionReason);+ }++ private updateHidListeningIntent(): void {+ this.wantsHidInput =+ this.agentKeyPressHandler !== null ||+ this.hidInputHandler !== null ||+ this.joystickInputHandler !== null;+ if (this.wantsHidInput) this.requestHidListening();+ }++ setDeviceActivityHandler(handler: (() => void) | null): void {+ this.deviceActivityHandler = handler;+ }++ setConnectionStatusHandler(+ handler: ((status: WorkLouderCodexConnectionStatus) => void) | null,+ ): void {+ this.connectionStatusHandler = handler;+ handler?.(this.connectionStatus);+ }++ update(frame: WorkLouderCodexLightingFrame): void {+ if (this.disposed) return;+ this.latestFrame = frame;+ if (isWorkLouderCodexLightingFrameOff(frame) && this.restartTimer) {+ clearTimeout(this.restartTimer);+ this.restartTimer = null;+ }+ if (!this.child && isWorkLouderCodexLightingFrameOff(frame) && !this.wantsHidInput) return;+ const child = this.ensureChild();+ if (!child) return;+ const request: WorkLouderCodexHostRequest = { kind: 'apply', frame };+ try {+ child.postMessage(request);+ } catch (error) {+ this.deps.log.warn('failed to send lighting frame to host', {+ error: error instanceof Error ? error.message : String(error),+ });+ try {+ child.kill();+ } catch {+ // A failed message channel commonly means the child already exited.+ }+ this.handleExit(child, 1);+ }+ }++ dispose(): Promise<void> {+ if (this.disposePromise) return this.disposePromise;+ this.disposed = true;+ if (this.restartTimer) {+ clearTimeout(this.restartTimer);+ this.restartTimer = null;+ }+ this.clearConnectWatchdog();+ const child = this.child;+ if (!child) return Promise.resolve();++ this.disposePromise = new Promise<void>((resolve) => {+ this.finishDispose = resolve;+ this.disposeTimer = setTimeout(+ () => this.completeDispose(child),+ this.deps.disposeTimeoutMs ?? 1_000,+ );+ this.disposeTimer.unref?.();+ const request: WorkLouderCodexHostRequest = { kind: 'stop' };+ try {+ child.postMessage(request);+ } catch {+ this.completeDispose(child);+ }+ });+ return this.disposePromise;+ }++ private ensureChild(): WorkLouderCodexChildLike | null {+ if (this.child) return this.child;+ const sdk = this.deps.resolveSdk();+ if (!sdk) {+ 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');+ }+ return null;+ }+ let child: WorkLouderCodexChildLike | null = null;+ try {+ this.updateConnectionReason(null);+ this.updateConnectionStatus('connecting');+ const startedChild = this.deps.fork(sdk.entry);+ child = startedChild;+ this.child = startedChild;+ startedChild.on('message', (message) => this.handleMessage(startedChild, message));+ startedChild.on('exit', (code) => this.handleExit(startedChild, code));+ startedChild.on('error', (type) => {+ this.deps.log.warn('Codex Micro lighting host error', {+ type: type instanceof Error ? type.name : type,+ });+ });+ const initRequest: WorkLouderCodexHostRequest = { kind: 'init', sdkEntry: sdk.entry };+ startedChild.postMessage(initRequest);+ this.startConnectWatchdog(startedChild);+ this.deps.log.info('Codex Micro lighting host started', { sdkSource: sdk.source });+ return startedChild;+ } catch (error) {+ if (child) {+ try {+ child.kill();+ } catch {+ // Startup already failed; teardown is best effort.+ }+ if (this.child === child) this.child = null;+ }+ 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();+ return null;+ }+ }++ /**+ * Ask the host to re-check the device.+ *+ * Used while something is showing connection state: the SDK never reports a+ * disconnect, so an unplugged device otherwise keeps reading as connected+ * until the next lighting write.+ *+ * Reuses the running host only — probing must not spin one up on its own,+ * or merely opening settings would start the process on a machine that has+ * no such keyboard.+ */+ probe(): void {+ if (this.disposed || !this.child) return;+ try {+ const request: WorkLouderCodexHostRequest = { kind: 'probe' };+ this.child.postMessage(request);+ } catch (error) {+ this.deps.log.debug('failed to probe the Work Louder host', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ private requestHidListening(): void {+ if (this.disposed || !this.wantsHidInput) return;+ const child = this.ensureChild();+ if (!child) return;+ try {+ const request: WorkLouderCodexHostRequest = { kind: 'listen' };+ child.postMessage(request);+ } catch (error) {+ this.deps.log.warn('failed to start Work Louder HID listening', {+ error: error instanceof Error ? error.message : String(error),+ });+ try {+ child.kill();+ } catch {+ // A failed message channel commonly means the child already exited.+ }+ this.handleExit(child, 1);+ }+ }++ private handleMessage(child: WorkLouderCodexChildLike, message: unknown): void {+ if (this.child !== child || !isWorkLouderCodexHostMessage(message)) return;+ if (message.kind === 'stopped') {+ this.completeDispose(child);+ return;+ }+ if (message.kind === 'log') {+ this.deps.log[message.level](`[host] ${message.message}`);+ return;+ }+ if (message.kind === 'hid') {+ this.clearConnectWatchdog();+ this.hidInputHandler?.(message.event);+ const slot = parseWorkLouderCodexAgentKeyPress(message.event);+ if (slot !== null) {+ this.deps.log.debug('Codex Micro Agent key pressed', { slot });+ this.agentKeyPressHandler?.(slot);+ }+ return;+ }+ if (message.kind === 'joystick') {+ this.clearConnectWatchdog();+ this.joystickInputHandler?.(message.event);+ return;+ }+ if (message.kind === 'device') {+ this.clearConnectWatchdog();+ this.deviceStateHandler?.(message.device);+ return;+ }+ if (message.kind === 'activity') {+ this.deviceActivityHandler?.();+ return;+ }+ if (message.kind !== 'state') return;+ this.clearConnectWatchdog();+ this.updateConnectionReason(message.reason ?? null);+ if (message.status === this.lastStatus) return;+ const previousStatus = this.lastStatus;+ this.lastStatus = message.status;+ this.updateConnectionStatus(message.status);+ if (message.status === 'connected') {+ this.armStableConnection();+ this.deps.log.info('Codex Micro lighting connected');+ return;+ }+ if (message.status === 'not-detected') {+ this.deps.log.debug('Codex Micro lighting device not detected');+ } else {+ this.deps.log.warn('Codex Micro lighting host could not apply the current frame');+ }+ // Pairing / USB re-enumeration leaves the native SDK handle alive but+ // unusable. ChatGPT recovers by opening a fresh transport; we do the same+ // by recycling the utility process once the live session drops.+ if (previousStatus === 'connected') this.recycleStaleHost(child);+ }++ private recycleStaleHost(child: WorkLouderCodexChildLike): void {+ if (this.disposed || this.recyclingChild || this.child !== child) return;+ this.recyclingChild = true;+ this.clearConnectWatchdog();+ this.clearStableConnection();+ this.deps.log.info('Codex Micro lighting host recycled after the device dropped');+ try {+ child.kill();+ } catch {+ // Recycle owns recovery even if the native host already disappeared.+ }+ this.handleExit(child, 0);+ }++ private handleExit(child: WorkLouderCodexChildLike, code: number): void {+ if (this.child !== child) return;+ const recycled = this.recyclingChild;+ this.recyclingChild = false;+ this.clearConnectWatchdog();+ this.clearStableConnection();+ this.child = null;+ this.lastStatus = null;+ if (this.disposed) {+ this.completeDispose(child);+ return;+ }+ if (recycled) {+ this.restartHost();+ return;+ }+ this.deps.log.warn('Codex Micro lighting host exited', { code });+ if (this.connectionReason !== 'connection-timeout') {+ this.updateConnectionReason('connection-failed');+ }+ this.updateConnectionStatus('error');+ this.scheduleRestart();+ }++ private restartHost(): void {+ if (this.disposed) 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;+ }+ this.consecutiveCrashes += 1;+ if (this.consecutiveCrashes > 5) {+ this.deps.log.error('Codex Micro lighting host repeatedly crashed; disabled until restart');+ return;+ }+ 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.wantsHidInput) this.requestHidListening();+ if (frame) this.update(frame);+ }, delayMs);+ this.restartTimer.unref?.();+ }++ private startConnectWatchdog(child: WorkLouderCodexChildLike): void {+ this.clearConnectWatchdog();+ this.connectWatchdogTimer = setTimeout(() => {+ this.connectWatchdogTimer = null;+ if (this.child !== child || this.disposed) return;+ this.deps.log.warn('Codex Micro lighting host connection timed out');+ this.updateConnectionReason('connection-timeout');+ this.updateConnectionStatus('error');+ try {+ child.kill();+ } catch {+ // The watchdog owns recovery even if the native host already disappeared.+ }+ this.handleExit(child, 1);+ }, this.deps.connectTimeoutMs ?? 5_000);+ this.connectWatchdogTimer.unref?.();+ }++ private clearConnectWatchdog(): void {+ if (!this.connectWatchdogTimer) return;+ clearTimeout(this.connectWatchdogTimer);+ this.connectWatchdogTimer = null;+ }++ private armStableConnection(): void {+ this.clearStableConnection();+ this.stableConnectionTimer = setTimeout(() => {+ this.stableConnectionTimer = null;+ this.consecutiveCrashes = 0;+ }, this.deps.stableConnectionMs ?? 10_000);+ this.stableConnectionTimer.unref?.();+ }++ private clearStableConnection(): void {+ if (!this.stableConnectionTimer) return;+ clearTimeout(this.stableConnectionTimer);+ this.stableConnectionTimer = null;+ }++ private completeDispose(child: WorkLouderCodexChildLike): void {+ this.clearConnectWatchdog();+ this.clearStableConnection();+ if (this.disposeTimer) {+ clearTimeout(this.disposeTimer);+ this.disposeTimer = null;+ }+ if (this.child === child) {+ try {+ child.kill();+ } catch {+ // The utility process may already have exited after acknowledging stop.+ }+ this.child = null;+ }+ const finish = this.finishDispose;+ this.finishDispose = null;+ finish?.();+ }++ private updateConnectionStatus(status: WorkLouderCodexConnectionStatus): void {+ if (status === this.connectionStatus) return;+ this.connectionStatus = status;+ this.connectionStatusHandler?.(status);+ }++ private updateConnectionReason(reason: WorkLouderCodexConnectionReason): void {+ if (reason === this.connectionReason) return;+ this.connectionReason = reason;+ this.connectionReasonHandler?.(reason);+ }+}diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.tsnew file mode 100644index 0000000000..c50f9bb02a--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts@@ -0,0 +1,861 @@+import type { AgentIslandSessionActivity } from '../../shared/agentIsland.js';+import {+ WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ WORKLOUDER_CODEX_KEYCAP_ACTIONS,+ cloneWorkLouderCodexSettings,+ createWorkLouderCodexDefaultSettings,+ isWorkLouderCodexMicrophoneKeycap,+ workLouderCodexAutoDimMs,+ type WorkLouderCodexAction,+ type WorkLouderCodexAgentSlotState,+ type WorkLouderCodexAnalogDirection,+ type WorkLouderCodexCommandSlot,+ type WorkLouderCodexConnectionReason,+ type WorkLouderCodexConnectionStatus,+ type WorkLouderCodexDeviceState,+ type WorkLouderCodexPreviewInput,+ type WorkLouderCodexPreviewPart,+ type WorkLouderCodexRendererAction,+ type WorkLouderCodexSettings,+ type WorkLouderCodexState,+ type WorkLouderCodexTaskOption,+} from '../../shared/workLouderCodex.js';+import {+ applyWorkLouderCodexLightingBrightness,+ createWorkLouderCodexOffFrame,+ createWorkLouderCodexLightingFrame,+ createWorkLouderCodexWindowRevealFrame,+ isWorkLouderCodexLightingFrameOff,+ type WorkLouderCodexHidEvent,+ type WorkLouderCodexJoystickEvent,+ type WorkLouderCodexLightingFrame,+} from './protocol.js';+import type { WorkLouderCodexTaskCatalog } from './taskSlots.js';+import {+ WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE,+ normalizeJoystickIntensity,+} from '../../shared/workLouderCodexScroll.js';++const TASK_SLOT_REFRESH_DEBOUNCE_MS = 250;+const AGENT_KEY_DOUBLE_TAP_MS = 350;+const ENCODER_LONG_PRESS_MS = 500;+/** How long the window-reopen greeting stays on the board. */+const WINDOW_REVEAL_MS = 2_000;+/**+ * How long a held stick may go silent before we give up on it.+ *+ * Measured against the hardware: a stick held still reports nothing at all,+ * with gaps of two seconds and more between updates. Release has its own+ * signal (distance drops to zero), so this is only a backstop for the device+ * going away mid-push — unplugged, asleep, or a dropped packet. It has to sit+ * well above the silent gaps or it would read "held" as "let go".+ */+const JOYSTICK_RELEASE_TIMEOUT_MS = 10_000;+type Timer = ReturnType<typeof setTimeout>;++export interface WorkLouderCodexLightingSink {+ update(frame: WorkLouderCodexLightingFrame): void;+ /** Legacy Agent-only hook retained for old host fakes and compatibility tests. */+ setAgentKeyPressHandler(handler: ((slot: number) => void) | null): void;+ setDeviceActivityHandler(handler: (() => void) | null): void;+ setConnectionStatusHandler(+ handler: ((status: WorkLouderCodexConnectionStatus) => void) | null,+ ): void;+ setHidInputHandler?(handler: ((event: WorkLouderCodexHidEvent) => void) | null): void;+ setJoystickInputHandler?(handler: ((event: WorkLouderCodexJoystickEvent) => void) | null): void;+ setDeviceStateHandler?(handler: ((device: WorkLouderCodexDeviceState) => void) | null): void;+ setConnectionReasonHandler?(+ handler: ((reason: WorkLouderCodexConnectionReason) => void) | null,+ ): void;+ dispose(): Promise<void>;+}++type TaskCatalogLoader = () => Promise<WorkLouderCodexTaskCatalog | 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 AgentIslandSessionActivity[] = [];+ private taskCatalog: WorkLouderCodexTaskCatalog = { sidebar: [], lastSent: [], options: [] };+ private agentSlots: WorkLouderCodexAgentSlotState[] = emptyAgentSlots();+ private slotRefreshVersion = 0;+ private taskSlotsEnabled = false;+ private slotRefreshTimer: Timer | null = null;+ private slotRefreshInFlight: Promise<void> | null = null;+ private slotRefreshInFlightVersion: number | null = null;+ private slotRefreshQueued = false;+ private settings: WorkLouderCodexSettings = createWorkLouderCodexDefaultSettings();+ private connectionStatus: WorkLouderCodexConnectionStatus = 'connecting';+ private connectionReason: WorkLouderCodexConnectionReason = null;+ private device: WorkLouderCodexDeviceState = {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ inputMonitoringPermission: process.platform === 'darwin' ? 'unknown' : 'not-required',+ };+ private stateListeners = new Set<(state: WorkLouderCodexState) => void>();+ private autoDimTimer: Timer | null = null;+ private lightingDimmed = false;+ private windowRevealTimer: Timer | null = null;+ private lastBaseFrameKey = '';+ private pendingAgentKeyTap: { slot: number; at: number } | null = null;+ private encoderLongPressTimer: Timer | null = null;+ private encoderPressed = false;+ private encoderLongPressed = false;+ private joystickDirection: WorkLouderCodexAnalogDirection | null = null;+ private joystickReleaseTimer: ReturnType<typeof setTimeout> | null = null;+ private scrollActive = false;+ private started = false;+ private layoutPreviewActive = false;+ private inputActionsEnabled = false;+ private joystickNeedsCenter = false;+ private voicePressed = false;++ constructor(+ private readonly sink: WorkLouderCodexLightingSink,+ private readonly activateSession: (sessionId: string, focus?: boolean) => void,+ private readonly loadTaskCatalog: TaskCatalogLoader = async () => [],+ private readonly dispatchRendererAction: (action: WorkLouderCodexRendererAction) => void = () =>+ undefined,+ private readonly dispatchPreviewInput: (input: WorkLouderCodexPreviewInput) => void = () =>+ undefined,+ ) {}++ start(): void {+ if (this.started) return;+ this.started = true;+ this.sink.setConnectionStatusHandler((status) => this.handleConnectionStatus(status));+ this.sink.setConnectionReasonHandler?.((reason) => this.handleConnectionReason(reason));+ this.sink.setDeviceStateHandler?.((device) => this.handleDeviceState(device));+ this.sink.setDeviceActivityHandler(() => this.handleDeviceActivity());+ if (this.sink.setHidInputHandler) {+ this.sink.setAgentKeyPressHandler(null);+ this.sink.setHidInputHandler((event) => this.handleHidInput(event));+ this.sink.setJoystickInputHandler?.((event) => this.handleJoystickInput(event));+ } else {+ this.sink.setAgentKeyPressHandler((slot) => this.handleAgentKeyPress(slot));+ }+ }++ updateSessionActivity(activity: readonly AgentIslandSessionActivity[]): void {+ this.latestActivity = activity;+ if (this.settings.agentSource === 'priority') this.publishAgentSlots();+ this.updateLightingFrame(true);+ this.scheduleTaskSlotRefresh();+ }++ getState(): WorkLouderCodexState {+ return {+ connectionStatus: this.connectionStatus,+ connectionReason: this.connectionReason,+ device: { ...this.device },+ settings: cloneWorkLouderCodexSettings(this.settings),+ agentSlots: this.agentSlots.map((slot) => ({+ ...slot,+ action: cloneAction(slot.action),+ })),+ taskOptions: this.taskCatalog.options.map((task) => ({ ...task })),+ agentSlotCount: WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ };+ }++ subscribeState(listener: (state: WorkLouderCodexState) => void): () => void {+ this.stateListeners.add(listener);+ listener(this.getState());+ return () => this.stateListeners.delete(listener);+ }++ setLayoutPreviewActive(active: boolean): void {+ this.layoutPreviewActive = active;+ if (!active) this.pendingAgentKeyTap = null;+ }++ applySettings(settings: WorkLouderCodexSettings): void {+ this.settings = cloneWorkLouderCodexSettings(settings);+ this.pendingAgentKeyTap = null;+ this.lightingDimmed = false;+ this.clearWindowRevealTimer();+ this.publishAgentSlots();+ const frame = this.updateLightingFrame();+ this.resetAutoDimTimer(frame);+ this.emitState();+ }++ /**+ * Flash a greeting when Cindy's window comes back after being hidden.+ *+ * Status lighting is paused for the duration so a running task's snake+ * does not overwrite the hello mid-sweep. Device activity or a settings+ * change also ends it early.+ */+ playWindowReveal(): void {+ this.lightingDimmed = false;+ this.clearWindowRevealTimer();+ // Same greeting twice in a row would otherwise be dropped as a duplicate.+ this.lastFrameKey = '';+ this.windowRevealTimer = setTimeout(() => {+ this.windowRevealTimer = null;+ this.updateLightingFrame();+ }, WINDOW_REVEAL_MS);+ this.windowRevealTimer.unref?.();+ const frame = this.updateLightingFrame();+ this.resetAutoDimTimer(frame);+ }++ async refreshTaskSlots(): Promise<void> {+ if (!this.taskSlotsEnabled) return;+ if (this.slotRefreshInFlight) {+ this.slotRefreshQueued = true;+ return this.slotRefreshInFlight;+ }++ const refreshVersion = ++this.slotRefreshVersion;+ const refresh = (async () => {+ try {+ const catalog = normalizeTaskCatalog(await this.loadTaskCatalog());+ if (!this.taskSlotsEnabled || refreshVersion !== this.slotRefreshVersion) return;+ this.taskCatalog = catalog;+ this.publishAgentSlots();+ this.updateLightingFrame(true);+ this.emitState();+ } finally {+ if (this.slotRefreshInFlightVersion !== refreshVersion) return;+ this.slotRefreshInFlight = null;+ this.slotRefreshInFlightVersion = null;+ if (this.slotRefreshQueued) {+ this.slotRefreshQueued = false;+ this.scheduleTaskSlotRefresh(true);+ }+ }+ })();+ this.slotRefreshInFlight = refresh;+ this.slotRefreshInFlightVersion = refreshVersion;+ return refresh;+ }++ async resumeTaskSlots(): Promise<void> {+ this.start();+ this.clearSlotRefreshTimer();+ const refreshVersion = ++this.slotRefreshVersion;+ try {+ const catalog = normalizeTaskCatalog(await this.loadTaskCatalog());+ if (refreshVersion !== this.slotRefreshVersion) return;+ this.taskCatalog = catalog;+ } catch (error) {+ if (refreshVersion !== this.slotRefreshVersion) return;+ this.taskCatalog = { sidebar: [], lastSent: [], options: [] };+ this.taskSlotsEnabled = true;+ this.inputActionsEnabled = true;+ this.publishAgentSlots();+ this.updateLightingFrame(true);+ this.scheduleTaskSlotRefresh();+ throw error;+ }+ this.taskSlotsEnabled = true;+ this.inputActionsEnabled = true;+ this.publishAgentSlots();+ this.updateLightingFrame(true);+ this.emitState();+ }++ suspendTaskSlots(): void {+ this.clearSlotRefreshTimer();+ this.clearEncoderLongPressTimer();+ this.encoderPressed = false;+ this.encoderLongPressed = false;+ this.stopJoystickScroll();+ this.slotRefreshVersion += 1;+ this.taskSlotsEnabled = false;+ this.inputActionsEnabled = false;+ this.slotRefreshQueued = false;+ this.taskCatalog = { sidebar: [], lastSent: [], options: [] };+ this.agentSlots = emptyAgentSlots();+ this.slotSessionIds = [];+ this.pendingAgentKeyTap = null;+ this.joystickNeedsCenter = this.joystickDirection !== null;+ this.joystickDirection = null;+ this.releaseHeldVoice();+ this.clearAutoDimTimer();+ this.clearWindowRevealTimer();+ this.lightingDimmed = false;+ this.updateLightingFrame();+ this.emitState();+ }++ dispose(): Promise<void> {+ this.clearSlotRefreshTimer();+ this.clearEncoderLongPressTimer();+ this.clearAutoDimTimer();+ this.clearWindowRevealTimer();+ this.stopJoystickScroll();+ this.releaseHeldVoice();+ this.slotRefreshVersion += 1;+ this.taskSlotsEnabled = false;+ this.inputActionsEnabled = false;+ this.slotRefreshQueued = false;+ this.started = false;+ this.sink.setAgentKeyPressHandler(null);+ this.sink.setHidInputHandler?.(null);+ this.sink.setJoystickInputHandler?.(null);+ this.sink.setDeviceStateHandler?.(null);+ this.sink.setConnectionReasonHandler?.(null);+ this.sink.setDeviceActivityHandler(null);+ this.sink.setConnectionStatusHandler(null);+ this.stateListeners.clear();+ return this.sink.dispose();+ }++ private handleHidInput(event: WorkLouderCodexHidEvent): void {+ this.handleDeviceActivity();+ if (event.key.startsWith('ENC')) {+ this.emitEncoderPreview(event);+ } else {+ this.emitKeyPreview(+ previewPartForHidKey(event.key, this.settings.layout.separateMicrophoneKeys),+ event.act,+ );+ }+ if (this.layoutPreviewActive) return;+ if (!this.inputActionsEnabled) {+ this.releaseHeldVoiceFromEvent(event);+ return;+ }+ const agentMatch = /^AG0([0-5])$/.exec(event.key);+ if (agentMatch) {+ if (event.act === 1) this.handleAgentKeyPress(Number(agentMatch[1]));+ return;+ }+ if (event.key.startsWith('ENC')) {+ this.handleEncoderInput(event);+ return;+ }+ if (/^ACT(?:0[6-9]|1[0-2])$/.test(event.key)) this.handleCommandKeyInput(event);+ }++ private handleAgentKeyPress(slot: number): void {+ this.handleDeviceActivity();+ if (!this.taskSlotsEnabled || slot < 0 || slot >= WORKLOUDER_CODEX_AGENT_SLOT_COUNT) return;+ const action = this.agentSlots[slot]?.action;+ if (!action) {+ this.dispatchRendererAction({ type: 'command', commandId: 'newTask' });+ void this.refreshTaskSlots().catch(() => undefined);+ return;+ }+ if (action.type === 'task') {+ const now = Date.now();+ const previous = this.pendingAgentKeyTap;+ const isDoubleTap = previous?.slot === slot && now - previous.at <= AGENT_KEY_DOUBLE_TAP_MS;+ this.pendingAgentKeyTap = isDoubleTap ? null : { slot, at: now };+ this.activateSession(action.sessionId, this.settings.singleTapAgentKeys || isDoubleTap);+ } else {+ this.pendingAgentKeyTap = null;+ this.executeAction(action, true);+ }+ void this.refreshTaskSlots().catch(() => {+ // The current press always uses the published mapping; refresh affects later presses only.+ });+ }++ private handleCommandKeyInput(event: WorkLouderCodexHidEvent): void {+ const slot = this.commandSlotForKey(event.key);+ if (!slot) return;+ const assignment = this.settings.layout.slots[slot];+ if (isWorkLouderCodexMicrophoneKeycap(assignment.keycapId)) {+ if (event.act === 1 || event.act === 0) {+ this.voicePressed = event.act === 1;+ this.dispatchRendererAction({+ type: 'voice',+ phase: event.act === 1 ? 'press' : 'release',+ });+ }+ return;+ }+ if (event.act !== 1) return;+ const action =+ assignment.action ?? WORKLOUDER_CODEX_KEYCAP_ACTIONS[assignment.keycapId] ?? null;+ if (action) this.executeAction(action, true);+ }++ private commandSlotForKey(key: string): WorkLouderCodexCommandSlot | null {+ if (!this.settings.layout.separateMicrophoneKeys && (key === 'ACT10' || key === 'ACT11')) {+ return key === 'ACT10' ? 'ACT10_ACT11' : null;+ }+ return /^ACT(?:0[6-9]|1[0-2])$/.test(key) ? (key as WorkLouderCodexCommandSlot) : null;+ }++ private handleEncoderInput(event: WorkLouderCodexHidEvent): void {+ if (event.act === 2 && (event.key === 'ENC_CW' || event.key === 'ENC_CC')) {+ const clockwise = event.key === 'ENC_CW';+ switch (this.settings.layout.encoderMode) {+ case 'custom':+ this.executeNullableAction(+ this.settings.layout.encoder[clockwise ? 'right' : 'left'],+ true,+ );+ break;+ case 'reasoning':+ this.dispatchRendererAction({+ type: 'command',+ commandId: clockwise+ ? 'composer.decreaseReasoningEffort'+ : 'composer.increaseReasoningEffort',+ });+ break;+ case 'conversation-scroll':+ this.dispatchRendererAction({+ type: 'command',+ commandId: clockwise ? 'conversation.scrollUp' : 'conversation.scrollDown',+ });+ break;+ case 'session-switch':+ // The knob follows the list on screen: left walks up the sidebar,+ // right walks down. Note ENC_CW is the *up* direction on this+ // hardware — `conversation-scroll` above maps it to scrollUp for the+ // same reason. The firmware's naming is not a guide to which way the+ // user is actually turning.+ this.dispatchRendererAction({+ type: 'command',+ commandId: clockwise ? 'session.selectPrevious' : 'session.selectNext',+ });+ break;+ case 'composer-navigation':+ this.dispatchRendererAction({+ type: 'keyboard',+ key: clockwise ? 'ArrowUp' : 'ArrowDown',+ });+ break;+ }+ return;+ }+ if (event.act === 1 && !this.encoderPressed) {+ this.encoderPressed = true;+ this.encoderLongPressed = false;+ this.clearEncoderLongPressTimer();+ this.encoderLongPressTimer = setTimeout(() => {+ this.encoderLongPressTimer = null;+ if (!this.encoderPressed) return;+ this.encoderLongPressed = true;+ if (this.settings.layout.encoderMode === 'custom') {+ this.executeNullableAction(this.settings.layout.encoder.longPress, true);+ } else {+ this.dispatchRendererAction({ type: 'command', commandId: 'settings' });+ }+ }, ENCODER_LONG_PRESS_MS);+ this.encoderLongPressTimer.unref?.();+ return;+ }+ if (event.act !== 0 || !this.encoderPressed) return;+ this.encoderPressed = false;+ this.clearEncoderLongPressTimer();+ if (this.encoderLongPressed) {+ this.encoderLongPressed = false;+ return;+ }+ switch (this.settings.layout.encoderMode) {+ case 'custom':+ this.executeNullableAction(this.settings.layout.encoder.click, true);+ break;+ case 'conversation-scroll':+ this.dispatchRendererAction({ type: 'command', commandId: 'conversation.scrollBottom' });+ break;+ case 'session-switch':+ case 'composer-navigation':+ case 'reasoning':+ this.dispatchRendererAction({ type: 'keyboard', key: 'Enter' });+ break;+ }+ }++ private handleJoystickInput(event: WorkLouderCodexJoystickEvent): void {+ this.handleDeviceActivity();+ const direction = joystickDirection(event);+ this.emitStickPreview(event);+ if (this.joystickNeedsCenter && !direction) {+ this.joystickNeedsCenter = false;+ }+ if (this.layoutPreviewActive || !this.inputActionsEnabled) return;+ if (this.joystickNeedsCenter) return;++ // Scrolling follows the stick continuously — held means keep scrolling, and+ // pushing further means faster — so it cannot go through the one-shot path+ // below, which only fires as the stick crosses into a direction.+ const scrollDirection = direction ? this.scrollDirectionFor(direction) : null;+ if (scrollDirection) {+ this.joystickDirection = direction;+ this.armJoystickReleaseWatchdog();+ this.scrollActive = true;+ this.dispatchRendererAction({+ type: 'scroll',+ direction: scrollDirection,+ intensity: normalizeJoystickIntensity(event.distance),+ });+ return;+ }++ // Anything else (including the stick returning to centre) ends a scroll.+ this.stopJoystickScroll();++ if (direction === this.joystickDirection) return;+ this.joystickDirection = direction;+ if (!direction) return;+ this.executeNullableAction(this.settings.layout.analogStick[direction], true);+ }++ /**+ * The scroll direction this stick axis drives, or null if it is bound to+ * something else. Rebinding up/down to an ordinary command keeps the+ * one-shot behaviour — only actual scrolling wants to repeat.+ */+ private scrollDirectionFor(direction: WorkLouderCodexAnalogDirection): 'up' | 'down' | null {+ const action = this.settings.layout.analogStick[direction];+ if (action?.type !== 'command') return null;+ if (action.commandId === 'conversation.scrollUp') return 'up';+ if (action.commandId === 'conversation.scrollDown') return 'down';+ return null;+ }++ /**+ * Stop scrolling if the stick goes quiet.+ *+ * The SDK hook is `onJoystickMove`, so a stick held perfectly still may stop+ * reporting entirely — and a release event can be missed outright if the+ * device sleeps or is unplugged mid-push. Without this the page would scroll+ * forever.+ */+ private armJoystickReleaseWatchdog(): void {+ if (this.joystickReleaseTimer) clearTimeout(this.joystickReleaseTimer);+ this.joystickReleaseTimer = setTimeout(() => {+ this.joystickReleaseTimer = null;+ this.joystickDirection = null;+ this.stopJoystickScroll();+ }, JOYSTICK_RELEASE_TIMEOUT_MS);+ this.joystickReleaseTimer.unref?.();+ }++ private releaseHeldVoiceFromEvent(event: WorkLouderCodexHidEvent): void {+ if (event.act !== 0 || !/^ACT(?:0[6-9]|1[0-2])$/.test(event.key)) return;+ const slot = this.commandSlotForKey(event.key);+ if (!slot) return;+ if (!isWorkLouderCodexMicrophoneKeycap(this.settings.layout.slots[slot].keycapId)) return;+ this.releaseHeldVoice();+ }++ private releaseHeldVoice(): void {+ if (!this.voicePressed) return;+ this.voicePressed = false;+ this.dispatchRendererAction({ type: 'voice', phase: 'release' });+ }++ private stopJoystickScroll(): void {+ if (this.joystickReleaseTimer) {+ clearTimeout(this.joystickReleaseTimer);+ this.joystickReleaseTimer = null;+ }+ if (!this.scrollActive) return;+ this.scrollActive = false;+ this.dispatchRendererAction({ type: 'scroll-stop' });+ }++ private executeNullableAction(action: WorkLouderCodexAction | null, focusTask: boolean): void {+ if (action) this.executeAction(action, focusTask);+ }++ private executeAction(action: WorkLouderCodexAction, focusTask: boolean): void {+ if (action.type === 'task') {+ this.activateSession(action.sessionId, focusTask);+ } else if (action.type === 'keycap') {+ const resolved = WORKLOUDER_CODEX_KEYCAP_ACTIONS[action.keycapId];+ if (resolved) this.executeAction(resolved, focusTask);+ } else {+ this.dispatchRendererAction(action);+ }+ }++ private publishAgentSlots(): void {+ const actions = this.agentActionsForCurrentSource();+ const titleById = new Map(+ this.taskCatalog.options.map((task) => [task.id, task.title] as const),+ );+ this.agentSlots = Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, slot) => {+ const action = actions[slot] ?? null;+ const sessionId = action?.type === 'task' ? action.sessionId : null;+ return {+ slot,+ sessionId,+ title: sessionId ? (titleById.get(sessionId) ?? sessionId) : actionTitle(action),+ action: cloneAction(action),+ };+ });+ this.slotSessionIds = this.agentSlots.map((slot) => slot.sessionId ?? '');+ }++ private agentActionsForCurrentSource(): Array<WorkLouderCodexAction | null> {+ if (this.settings.agentSource === 'custom') {+ return this.settings.customAgentKeys.map(cloneAction);+ }+ const tasks =+ this.settings.agentSource === 'last-sent'+ ? this.taskCatalog.lastSent+ : this.settings.agentSource === 'priority'+ ? this.priorityTasks()+ : this.taskCatalog.sidebar;+ return tasks+ .slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT)+ .map((task) => ({ type: 'task', sessionId: task.id }));+ }++ private priorityTasks(): WorkLouderCodexTaskOption[] {+ const optionById = new Map(this.taskCatalog.options.map((task) => [task.id, task] as const));+ const recentRank = new Map(+ this.taskCatalog.options.map((task, index) => [task.id, index] as const),+ );+ const prioritized = this.latestActivity+ .filter((activity) => optionById.has(activity.sessionId))+ .toSorted((left, right) => {+ const scoreDiff = activityPriority(right) - activityPriority(left);+ return (+ scoreDiff ||+ (recentRank.get(left.sessionId) ?? 999) - (recentRank.get(right.sessionId) ?? 999)+ );+ })+ .map((activity) => optionById.get(activity.sessionId)!)+ .filter((task, index, rows) => rows.findIndex((row) => row.id === task.id) === index);+ const included = new Set(prioritized.map((task) => task.id));+ return [...prioritized, ...this.taskCatalog.sidebar.filter((task) => !included.has(task.id))];+ }++ private updateLightingFrame(wakeOnBaseFrameChange = false): WorkLouderCodexLightingFrame {+ const baseFrame = createWorkLouderCodexLightingFrame(this.latestActivity, this.slotSessionIds);+ const baseFrameKey = JSON.stringify(baseFrame);+ const baseFrameChanged = baseFrameKey !== this.lastBaseFrameKey;+ this.lastBaseFrameKey = baseFrameKey;+ if (wakeOnBaseFrameChange && baseFrameChanged) this.lightingDimmed = false;+ const brightnessAdjusted = applyWorkLouderCodexLightingBrightness(+ baseFrame,+ this.settings.lightingBrightness,+ );+ const overlay = this.windowRevealTimer+ ? applyWorkLouderCodexLightingBrightness(+ createWorkLouderCodexWindowRevealFrame(),+ this.settings.lightingBrightness,+ )+ : null;+ const frame = this.lightingDimmed+ ? createWorkLouderCodexOffFrame()+ : (overlay ?? brightnessAdjusted);+ const frameKey = JSON.stringify(frame);+ if (frameKey !== this.lastFrameKey) {+ this.lastFrameKey = frameKey;+ this.sink.update(frame);+ }+ if (wakeOnBaseFrameChange && baseFrameChanged) this.resetAutoDimTimer(brightnessAdjusted);+ return brightnessAdjusted;+ }++ private scheduleTaskSlotRefresh(immediate = false): void {+ if (!this.taskSlotsEnabled) return;+ if (immediate) this.clearSlotRefreshTimer();+ if (this.slotRefreshTimer) return;+ if (immediate) {+ void this.refreshTaskSlots().catch(() => undefined);+ return;+ }+ this.slotRefreshTimer = setTimeout(() => {+ this.slotRefreshTimer = null;+ void this.refreshTaskSlots().catch(() => undefined);+ }, TASK_SLOT_REFRESH_DEBOUNCE_MS);+ }++ private clearSlotRefreshTimer(): void {+ if (!this.slotRefreshTimer) return;+ clearTimeout(this.slotRefreshTimer);+ this.slotRefreshTimer = null;+ }++ private clearEncoderLongPressTimer(): void {+ if (!this.encoderLongPressTimer) return;+ clearTimeout(this.encoderLongPressTimer);+ this.encoderLongPressTimer = null;+ }++ private handleConnectionStatus(status: WorkLouderCodexConnectionStatus): void {+ if (status === this.connectionStatus) return;+ this.connectionStatus = status;+ if (status === 'connected') {+ this.connectionReason = null;+ if (process.platform === 'darwin') {+ this.device = { ...this.device, inputMonitoringPermission: 'granted' };+ }+ } else {+ // 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 = {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ inputMonitoringPermission: this.device.inputMonitoringPermission,+ };+ }+ this.emitState();+ }++ private handleConnectionReason(reason: WorkLouderCodexConnectionReason): void {+ if (reason === this.connectionReason) return;+ this.connectionReason = reason;+ if (reason === 'permission-required' && process.platform === 'darwin') {+ this.device = { ...this.device, inputMonitoringPermission: 'denied' };+ }+ this.emitState();+ }++ private handleDeviceState(device: WorkLouderCodexDeviceState): void {+ this.device = { ...device };+ this.emitState();+ }++ private handleDeviceActivity(): void {+ this.lightingDimmed = false;+ this.clearWindowRevealTimer();+ const frame = this.updateLightingFrame();+ this.resetAutoDimTimer(frame);+ }++ private resetAutoDimTimer(frame: WorkLouderCodexLightingFrame): void {+ this.clearAutoDimTimer();+ const delayMs = workLouderCodexAutoDimMs(this.settings.lightingAutoDim);+ if (delayMs === null || isWorkLouderCodexLightingFrameOff(frame)) return;+ this.autoDimTimer = setTimeout(() => {+ this.autoDimTimer = null;+ this.lightingDimmed = true;+ this.updateLightingFrame();+ }, delayMs);+ this.autoDimTimer.unref?.();+ }++ private clearAutoDimTimer(): void {+ if (!this.autoDimTimer) return;+ clearTimeout(this.autoDimTimer);+ this.autoDimTimer = null;+ }++ private clearWindowRevealTimer(): void {+ if (!this.windowRevealTimer) return;+ clearTimeout(this.windowRevealTimer);+ this.windowRevealTimer = null;+ }++ private emitState(): void {+ const state = this.getState();+ for (const listener of this.stateListeners) listener(state);+ }++ private emitKeyPreview(part: WorkLouderCodexPreviewPart | null, act: number): void {+ if (!part) return;+ if (act !== 0 && act !== 1) return;+ this.dispatchPreviewInput({ part, pressed: act === 1 });+ }++ private emitEncoderPreview(event: WorkLouderCodexHidEvent): void {+ if (event.act === 2 && (event.key === 'ENC_CW' || event.key === 'ENC_CC')) {+ this.dispatchPreviewInput({+ part: 'encoder',+ pressed: this.encoderPressed,+ turn: event.key === 'ENC_CW' ? 1 : -1,+ });+ return;+ }+ if (event.act !== 0 && event.act !== 1) return;+ this.dispatchPreviewInput({ part: 'encoder', pressed: event.act === 1 });+ }++ private emitStickPreview(event: WorkLouderCodexJoystickEvent): void {+ this.dispatchPreviewInput({+ part: 'analog',+ pressed: event.distance > 0,+ angle: event.angle,+ distance: event.distance,+ });+ }+}++function previewPartForHidKey(+ key: string,+ separateMicrophoneKeys: boolean,+): WorkLouderCodexPreviewPart | null {+ if (/^AG0[0-5]$/.test(key)) return key as WorkLouderCodexPreviewPart;+ if (key.startsWith('ENC')) return 'encoder';+ if (!separateMicrophoneKeys && (key === 'ACT10' || key === 'ACT11')) return 'ACT10_ACT11';+ if (/^ACT(?:0[6-9]|1[0-2])$/.test(key)) return key as WorkLouderCodexPreviewPart;+ return null;+}++function emptyAgentSlots(): WorkLouderCodexAgentSlotState[] {+ return Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, slot) => ({+ slot,+ sessionId: null,+ title: null,+ action: null,+ }));+}++function normalizeTaskCatalog(+ value: WorkLouderCodexTaskCatalog | readonly string[],+): WorkLouderCodexTaskCatalog {+ if (isTaskCatalog(value)) {+ return {+ sidebar: value.sidebar.map((task) => ({ ...task })),+ lastSent: value.lastSent.map((task) => ({ ...task })),+ options: value.options.map((task) => ({ ...task })),+ };+ }+ const options = value.map((id) => ({ id, title: id, pinned: false }));+ return {+ sidebar: options.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT),+ lastSent: options.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT),+ options,+ };+}++function isTaskCatalog(+ value: WorkLouderCodexTaskCatalog | readonly string[],+): value is WorkLouderCodexTaskCatalog {+ return !Array.isArray(value);+}++function cloneAction(action: WorkLouderCodexAction | null): WorkLouderCodexAction | null {+ return action ? { ...action } : null;+}++function actionTitle(action: WorkLouderCodexAction | null): string | null {+ if (!action) return null;+ switch (action.type) {+ case 'command':+ return action.commandId;+ case 'skill':+ return action.name;+ case 'keycap':+ return action.keycapId;+ case 'composer-text':+ return action.text;+ case 'external-url':+ return action.url;+ case 'task':+ return action.sessionId;+ }+}++function activityPriority(activity: AgentIslandSessionActivity): number {+ if (activity.phase === 'needs-interaction') return 5;+ if (activity.attention) return 4;+ if (activity.phase === 'error') return 3;+ if (activity.phase === 'running') return 2;+ return 1;+}++function joystickDirection(+ event: WorkLouderCodexJoystickEvent,+): WorkLouderCodexAnalogDirection | null {+ if (event.distance < WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE) return null;+ if (event.angle >= 0.625 && event.angle < 0.875) return 'up';+ if (event.angle >= 0.125 && event.angle < 0.375) return 'down';+ if (event.angle >= 0.375 && event.angle < 0.625) return 'left';+ return 'right';+}diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.tsnew file mode 100644index 0000000000..92da81b703--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexHostClient.test.ts@@ -0,0 +1,370 @@+import { EventEmitter } from 'node:events';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it, vi } from 'vitest';++import { WORKLOUDER_CODEX_EMPTY_DEVICE_STATE } from '../../../shared/workLouderCodex.js';+import {+ WorkLouderCodexHostClient,+ type WorkLouderCodexChildLike,+} from '../WorkLouderCodexHostClient.js';+import { createWorkLouderCodexLightingFrame } from '../protocol.js';++class FakeChild extends EventEmitter implements WorkLouderCodexChildLike {+ readonly postMessage = vi.fn();+ readonly kill = vi.fn(() => true);+}++function logger() {+ return {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ };+}++describe('WorkLouderCodexHostClient', () => {+ it('does not load the optional native SDK for an idle Cindy', () => {+ const resolveSdk = vi.fn(() => null);+ const client = new WorkLouderCodexHostClient({+ resolveSdk,+ fork: vi.fn(),+ log: logger(),+ });++ client.update(createWorkLouderCodexLightingFrame([]));++ expect(resolveSdk).not.toHaveBeenCalled();+ });++ it('forks the isolated host on first active task', () => {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ const frame = createWorkLouderCodexLightingFrame([+ {+ sessionId: 'session-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);++ client.update(frame);++ expect(fork).toHaveBeenCalledWith('/sdk');+ expect(child.postMessage).toHaveBeenCalledWith({ kind: 'apply', frame });+ });++ it('starts HID listening even when there is no lighting activity', () => {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });++ client.setAgentKeyPressHandler(vi.fn());++ expect(fork).toHaveBeenCalledWith('/sdk');+ expect(child.postMessage).toHaveBeenCalledWith({ kind: 'listen' });+ });++ it('probes a running host but never starts one just to probe', () => {+ const child = new FakeChild();+ const fork = vi.fn(() => child);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });++ // Nothing running yet: probing must not spin up the host, or merely opening+ // settings would start it on a machine with no such keyboard.+ client.probe();+ expect(fork).not.toHaveBeenCalled();++ client.setAgentKeyPressHandler(vi.fn());+ client.probe();++ expect(child.postMessage).toHaveBeenLastCalledWith({ kind: 'probe' });+ });++ it('asks the host to turn lighting off before shutdown', async () => {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ disposeTimeoutMs: 50,+ });+ client.update(+ createWorkLouderCodexLightingFrame([+ {+ sessionId: 'session-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]),+ );++ const disposing = client.dispose();+ child.emit('message', { kind: 'stopped' });+ await disposing;++ expect(child.postMessage).toHaveBeenLastCalledWith({ kind: 'stop' });+ expect(child.kill).toHaveBeenCalledOnce();+ });++ it('forwards a validated Agent key press from the isolated host', () => {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ });+ const onAgentKeyPress = vi.fn();+ client.setAgentKeyPressHandler(onAgentKeyPress);+ client.update(+ createWorkLouderCodexLightingFrame([+ {+ sessionId: 'session-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]),+ );++ child.emit('message', { kind: 'hid', event: { key: 'AG04', act: 1 } });++ expect(onAgentKeyPress).toHaveBeenCalledWith(4);+ });++ it('forwards device activity and connection status changes', () => {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ });+ const onActivity = vi.fn();+ const onStatus = vi.fn();+ client.setDeviceActivityHandler(onActivity);+ client.setConnectionStatusHandler(onStatus);+ client.setAgentKeyPressHandler(vi.fn());++ child.emit('message', { kind: 'activity' });+ child.emit('message', { kind: 'state', status: 'connected' });+ child.emit('message', { kind: 'state', status: 'connected' });+ child.emit('message', { kind: 'state', status: 'not-detected' });++ expect(onActivity).toHaveBeenCalledOnce();+ expect(onStatus.mock.calls.map(([status]) => status)).toEqual([+ 'connecting',+ 'connected',+ 'not-detected',+ 'connecting',+ ]);+ expect(child.kill).toHaveBeenCalledOnce();+ });++ it('forwards HID, joystick, device, and connection reasons from the host', () => {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ });+ const onHid = vi.fn();+ const onJoystick = vi.fn();+ const onDevice = vi.fn();+ const onReason = vi.fn();+ client.setHidInputHandler(onHid);+ client.setJoystickInputHandler(onJoystick);+ client.setDeviceStateHandler(onDevice);+ client.setConnectionReasonHandler(onReason);++ const device = {+ ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ deviceType: 'codex-micro' as const,+ isUsbConnection: true,+ };+ child.emit('message', { kind: 'hid', event: { key: 'ACT12', act: 1 } });+ child.emit('message', { kind: 'joystick', event: { angle: 0.25, distance: 1 } });+ child.emit('message', { kind: 'device', device });+ child.emit('message', {+ kind: 'state',+ status: 'error',+ reason: 'connection-timeout',+ });++ expect(onHid).toHaveBeenCalledWith({ key: 'ACT12', act: 1 });+ expect(onJoystick).toHaveBeenCalledWith({ angle: 0.25, distance: 1 });+ expect(onDevice).toHaveBeenCalledWith(device);+ expect(onReason).toHaveBeenLastCalledWith('connection-timeout');+ });++ it('reports unavailable when the official SDK cannot be resolved', () => {+ const resolveSdk = vi.fn(() => null);+ const fork = vi.fn();+ const client = new WorkLouderCodexHostClient({ resolveSdk, fork, log: logger() });+ const onStatus = vi.fn();+ client.setConnectionStatusHandler(onStatus);++ client.setAgentKeyPressHandler(vi.fn());++ expect(resolveSdk).toHaveBeenCalledOnce();+ expect(fork).not.toHaveBeenCalled();+ expect(onStatus).toHaveBeenLastCalledWith('unavailable');+ });++ it('restarts the isolated host after a native-process crash', async () => {+ vi.useFakeTimers();+ try {+ const children = [new FakeChild(), new FakeChild()];+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ const frame = createWorkLouderCodexLightingFrame([+ {+ sessionId: 'session-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);+ client.update(frame);++ children[0].emit('exit', 1);+ await vi.advanceTimersByTimeAsync(500);++ expect(fork).toHaveBeenCalledTimes(2);+ expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'apply', frame });+ } finally {+ vi.useRealTimers();+ }+ });++ it('kills and restarts a host whose native HID connection never settles', async () => {+ vi.useFakeTimers();+ try {+ const children = [new FakeChild(), new FakeChild()];+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);+ const onStatus = vi.fn();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ connectTimeoutMs: 100,+ });+ client.setConnectionStatusHandler(onStatus);+ client.setAgentKeyPressHandler(vi.fn());++ await vi.advanceTimersByTimeAsync(100);+ expect(children[0].kill).toHaveBeenCalledOnce();+ expect(onStatus).toHaveBeenLastCalledWith('error');++ await vi.advanceTimersByTimeAsync(500);+ expect(fork).toHaveBeenCalledTimes(2);+ expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'listen' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('cancels the connection watchdog after the first state message', async () => {+ vi.useFakeTimers();+ try {+ const child = new FakeChild();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork: () => child,+ log: logger(),+ connectTimeoutMs: 100,+ });+ client.setAgentKeyPressHandler(vi.fn());+ child.emit('message', { kind: 'state', status: 'connected' });++ await vi.advanceTimersByTimeAsync(1_000);++ expect(child.kill).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not reset the crash budget on a connection that dies immediately', async () => {+ vi.useFakeTimers();+ try {+ const children = Array.from({ length: 7 }, () => new FakeChild());+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);+ const log = logger();+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log,+ stableConnectionMs: 10_000,+ });+ const frame = createWorkLouderCodexLightingFrame([+ {+ sessionId: 'session-1',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);+ client.update(frame);++ for (let index = 0; index < 6; index += 1) {+ children[index].emit('message', { kind: 'state', status: 'connected' });+ children[index].emit('exit', 1);+ await vi.advanceTimersByTimeAsync(Math.min(10_000, 500 * 2 ** index));+ }++ expect(fork).toHaveBeenCalledTimes(6);+ expect(log.error).toHaveBeenCalledWith(+ 'Codex Micro lighting host repeatedly crashed; disabled until restart',+ );+ } finally {+ vi.useRealTimers();+ }+ });++ it('recycles the host immediately after a live session drops', () => {+ const children = [new FakeChild(), new FakeChild()];+ const fork = vi.fn(() => children[fork.mock.calls.length - 1]);+ const client = new WorkLouderCodexHostClient({+ resolveSdk: () => ({ entry: '/sdk', source: 'openai-app' }),+ fork,+ log: logger(),+ });+ client.setAgentKeyPressHandler(vi.fn());+ children[0].emit('message', { kind: 'state', status: 'connected' });+ children[0].emit('message', { kind: 'state', status: 'not-detected' });++ expect(children[0].kill).toHaveBeenCalledOnce();+ expect(fork).toHaveBeenCalledTimes(2);+ expect(children[1].postMessage).toHaveBeenCalledWith({ kind: 'listen' });+ });+});++describe('Work Louder SDK resolution', () => {+ it('looks for ChatGPT and Codex installs on Windows as well as macOS', () => {+ const source = readFileSync(resolve(__dirname, '..', 'index.ts'), 'utf8');+ expect(source).toContain("process.platform === 'win32'");+ expect(source).toContain('LOCALAPPDATA');+ expect(source).toContain("path.join(root, 'Programs', appName, packageTail)");+ expect(source).not.toContain("if (process.platform !== 'darwin') return null;");+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.tsnew file mode 100644index 0000000000..645a4ac5f2--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/WorkLouderCodexLightingController.test.ts@@ -0,0 +1,909 @@+import { describe, expect, it, vi } from 'vitest';++import {+ createWorkLouderCodexDefaultSettings,+ type WorkLouderCodexSettings,+} from '../../../shared/workLouderCodex.js';+import { WorkLouderCodexLightingController } from '../WorkLouderCodexLightingController.js';+import { isWorkLouderCodexLightingFrameOff, WorkLouderLightingEffect } from '../protocol.js';++function settings(patch: Partial<WorkLouderCodexSettings>): WorkLouderCodexSettings {+ return { ...createWorkLouderCodexDefaultSettings(), ...patch };+}++describe('WorkLouderCodexLightingController', () => {+ it('deduplicates activity updates that produce the same lighting frame', () => {+ 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());+ const snapshot = [+ {+ sessionId: 'session-1',+ phase: 'running' as const,+ compactDetail: 'first detail',+ attention: false,+ },+ ];++ controller.updateSessionActivity(snapshot);+ controller.updateSessionActivity([{ ...snapshot[0], compactDetail: 'new detail' }]);++ expect(sink.update).toHaveBeenCalledTimes(1);+ });++ it('activates the task assigned to the pressed Agent key', async () => {+ const keyHandlerRef: { current: ((slot: number) => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn((handler: ((slot: number) => void) | null) => {+ keyHandlerRef.current = handler;+ }),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const activateSession = vi.fn();+ const controller = new WorkLouderCodexLightingController(sink, activateSession, async () => [+ 'running-session',+ 'waiting-session',+ ]);+ await controller.resumeTaskSlots();++ controller.updateSessionActivity([+ {+ sessionId: 'running-session',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ {+ sessionId: 'acknowledged-session',+ phase: 'completed',+ compactDetail: '',+ attention: false,+ },+ {+ sessionId: 'waiting-session',+ phase: 'needs-interaction',+ compactDetail: '',+ attention: false,+ },+ ]);+ keyHandlerRef.current?.(1);++ expect(activateSession).toHaveBeenCalledWith('waiting-session', false);+ });++ it('maps last-sent keys by the last user message, not sidebar order', async () => {+ const hidRef: { current: ((event: { key: string; act: number }) => void) | null } = {+ current: null,+ };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ setHidInputHandler: vi.fn((handler: typeof hidRef.current) => {+ hidRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const activateSession = vi.fn();+ const controller = new WorkLouderCodexLightingController(sink, activateSession, async () => ({+ sidebar: [+ { id: 'older', title: 'Older send', pinned: false },+ { id: 'newer', title: 'Newer send', pinned: false },+ ],+ lastSent: [+ { id: 'newer', title: 'Newer send', pinned: false },+ { id: 'older', title: 'Older send', pinned: false },+ ],+ options: [+ { id: 'older', title: 'Older send', pinned: false },+ { id: 'newer', title: 'Newer send', pinned: false },+ ],+ }));+ controller.applySettings(settings({ agentSource: 'last-sent' }));+ await controller.resumeTaskSlots();++ hidRef.current?.({ key: 'AG00', act: 1 });++ expect(activateSession).toHaveBeenCalledWith('newer', false);+ });++ it('uses the published assignment for the current press and refreshes only later presses', async () => {+ let resolveRefresh: ((value: readonly string[]) => void) | undefined;+ const keyHandlerRef: { current: ((slot: number) => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn((handler: ((slot: number) => void) | null) => {+ keyHandlerRef.current = handler;+ }),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const activateSession = vi.fn();+ const loadSlotSessionIds = vi+ .fn<() => Promise<readonly string[]>>()+ .mockResolvedValueOnce(['first'])+ .mockImplementationOnce(() => new Promise((resolve) => (resolveRefresh = resolve)))+ .mockResolvedValue(['second']);+ const controller = new WorkLouderCodexLightingController(+ sink,+ activateSession,+ loadSlotSessionIds,+ );+ const running = (sessionId: string) => ({+ sessionId,+ phase: 'running' as const,+ compactDetail: '',+ attention: false,+ });++ controller.updateSessionActivity([running('first')]);+ await controller.resumeTaskSlots();+ sink.update.mockClear();+ keyHandlerRef.current?.(0);++ expect(activateSession).toHaveBeenCalledWith('first', false);+ expect(loadSlotSessionIds).toHaveBeenCalledTimes(2);+ resolveRefresh?.(['second']);+ await vi.waitFor(() => expect(sink.update).toHaveBeenCalledTimes(1));+ keyHandlerRef.current?.(0);+ expect(activateSession).toHaveBeenLastCalledWith('second', true);+ expect(loadSlotSessionIds).toHaveBeenCalledTimes(3);+ });++ it('ignores keys and stale refreshes while task slots are suspended', async () => {+ let resolveSlots: ((value: readonly string[]) => void) | undefined;+ const keyHandlerRef: { current: ((slot: number) => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn((handler: ((slot: number) => void) | null) => {+ keyHandlerRef.current = handler;+ }),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const activateSession = vi.fn();+ const controller = new WorkLouderCodexLightingController(+ sink,+ activateSession,+ () => new Promise((resolve) => (resolveSlots = resolve)),+ );++ const resume = controller.resumeTaskSlots();+ controller.suspendTaskSlots();+ sink.update.mockClear();+ keyHandlerRef.current?.(0);+ resolveSlots?.(['old-owner-task']);+ await resume;++ expect(sink.update).not.toHaveBeenCalled();+ expect(activateSession).not.toHaveBeenCalled();+ });++ it('scales every lighting zone with the configured overall brightness', 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 () => [+ 'running-session',+ ]);+ controller.applySettings(+ settings({+ lightingBrightness: 50,+ lightingAutoDim: 'off',+ singleTapAgentKeys: true,+ }),+ );+ await controller.resumeTaskSlots();+ sink.update.mockClear();++ controller.updateSessionActivity([+ {+ sessionId: 'running-session',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);++ expect(sink.update).toHaveBeenCalledOnce();+ const frame = sink.update.mock.calls[0]?.[0];+ expect(frame?.ambient.brightness).toBe(0.35);+ expect(frame?.keys.brightness).toBe(0.08);+ expect(frame?.threads[0]?.brightness).toBe(0.4);+ });++ it('auto-dims after inactivity and wakes on the next device event', async () => {+ vi.useFakeTimers();+ try {+ const activityHandlerRef: { current: (() => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn((handler: (() => void) | null) => {+ activityHandlerRef.current = handler;+ }),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), async () => [+ 'running-session',+ ]);+ controller.applySettings(+ settings({+ lightingBrightness: 100,+ lightingAutoDim: '30-seconds',+ singleTapAgentKeys: true,+ }),+ );+ await controller.resumeTaskSlots();+ controller.updateSessionActivity([+ {+ sessionId: 'running-session',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);++ await vi.advanceTimersByTimeAsync(30_000);+ expect(isWorkLouderCodexLightingFrameOff(sink.update.mock.lastCall?.[0])).toBe(true);++ activityHandlerRef.current?.();+ expect(isWorkLouderCodexLightingFrameOff(sink.update.mock.lastCall?.[0])).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('switches tasks in the background first and focuses Cindy on the second tap', async () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(1_000);+ const keyHandlerRef: { current: ((slot: number) => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn((handler: ((slot: number) => void) | null) => {+ keyHandlerRef.current = handler;+ }),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const activateSession = vi.fn();+ const controller = new WorkLouderCodexLightingController(sink, activateSession, async () => [+ 'first',+ 'second',+ ]);+ controller.applySettings(+ settings({+ lightingBrightness: 100,+ lightingAutoDim: 'off',+ singleTapAgentKeys: false,+ }),+ );+ await controller.resumeTaskSlots();++ keyHandlerRef.current?.(0);+ expect(activateSession).toHaveBeenLastCalledWith('first', false);+ vi.setSystemTime(1_350);+ keyHandlerRef.current?.(0);+ expect(activateSession).toHaveBeenLastCalledWith('first', true);++ vi.setSystemTime(2_000);+ keyHandlerRef.current?.(0);+ vi.setSystemTime(2_200);+ keyHandlerRef.current?.(1);+ expect(activateSession).toHaveBeenLastCalledWith('second', false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('turns the encoder through the task list in its default mode', async () => {+ const hidRef: { current: ((event: { key: string; act: 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;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), undefined, dispatch);+ controller.start();+ await controller.resumeTaskSlots();++ // The knob follows the sidebar list: turning right walks down it, turning+ // left walks up. ENC_CW is the clockwise/right direction, the same one+ // `custom` mode maps to `right`.+ hidRef.current?.({ key: 'ENC_CW', act: 2 });+ expect(dispatch).toHaveBeenLastCalledWith({+ type: 'command',+ commandId: 'session.selectPrevious',+ });++ hidRef.current?.({ key: 'ENC_CC', act: 2 });+ expect(dispatch).toHaveBeenLastCalledWith({+ type: 'command',+ commandId: 'session.selectNext',+ });+ });++ it('mirrors physical presses onto the settings preview without changing actions', async () => {+ const hidRef: { current: ((event: { key: string; act: number }) => void) | null } = {+ current: null,+ };+ const dispatch = vi.fn();+ const preview = 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;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(+ sink,+ vi.fn(),+ undefined,+ dispatch,+ preview,+ );+ controller.start();+ await controller.resumeTaskSlots();++ hidRef.current?.({ key: 'ACT06', act: 1 });+ hidRef.current?.({ key: 'ACT06', act: 0 });+ hidRef.current?.({ key: 'ENC_CW', act: 2 });+ hidRef.current?.({ key: 'ENC_CC', act: 2 });+ hidRef.current?.({ key: 'ENC', act: 1 });++ expect(preview).toHaveBeenCalledWith({ part: 'ACT06', pressed: true });+ expect(preview).toHaveBeenCalledWith({ part: 'ACT06', pressed: false });+ expect(preview).toHaveBeenCalledWith({ part: 'encoder', pressed: false, turn: 1 });+ expect(preview).toHaveBeenCalledWith({ part: 'encoder', pressed: false, turn: -1 });+ expect(preview).toHaveBeenCalledWith({ part: 'encoder', pressed: true });+ expect(dispatch).toHaveBeenCalled();+ });++ it('keeps physical presses on the preview while the layout editor is open', () => {+ const hidRef: { current: ((event: { key: string; act: number }) => void) | null } = {+ current: null,+ };+ const dispatch = vi.fn();+ const preview = vi.fn();+ const activateSession = 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;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(+ sink,+ activateSession,+ undefined,+ dispatch,+ preview,+ );+ controller.start();+ controller.setLayoutPreviewActive(true);++ hidRef.current?.({ key: 'AG00', act: 1 });+ hidRef.current?.({ key: 'ACT06', act: 1 });+ hidRef.current?.({ key: 'ENC_CW', act: 2 });++ expect(preview).toHaveBeenCalledWith({ part: 'AG00', pressed: true });+ expect(preview).toHaveBeenCalledWith({ part: 'ACT06', pressed: true });+ expect(preview).toHaveBeenCalledWith({ part: 'encoder', pressed: false, turn: 1 });+ expect(activateSession).not.toHaveBeenCalled();+ expect(dispatch).not.toHaveBeenCalled();+ });++ describe('joystick scrolling', () => {+ function makeStick(preview = vi.fn()) {+ const stickRef: { 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(),+ setJoystickInputHandler: vi.fn((handler: typeof stickRef.current) => {+ stickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(+ sink,+ vi.fn(),+ undefined,+ dispatch,+ preview,+ );+ controller.start();+ return { stickRef, dispatch, controller, preview };+ }++ async function makeReadyStick() {+ const stick = makeStick();+ await stick.controller.resumeTaskSlots();+ return stick;+ }++ // Angles come from joystickDirection(): up is 0.625–0.875.+ const up = (distance: number) => ({ angle: 0.75, distance });+ const centre = { angle: 0.75, distance: 0 };++ it('keeps scrolling while the stick is held, carrying how hard it is pushed', async () => {+ const { stickRef, dispatch } = await makeReadyStick();++ stickRef.current?.(up(0.75));+ stickRef.current?.(up(1));++ // Both events scroll — the old code only fired as the stick crossed into+ // a direction, so holding it did nothing after the first report.+ const scrolls = dispatch.mock.calls.filter((call) => call[0].type === 'scroll');+ expect(scrolls).toHaveLength(2);+ expect(scrolls[0][0].direction).toBe('up');+ // Pushed further reads as more pressure.+ expect(scrolls[1][0].intensity).toBeGreaterThan(scrolls[0][0].intensity);+ });++ it('scrolls for the whole push and stops on release, as the hardware reports it', async () => {+ vi.useFakeTimers();+ try {+ const { stickRef, dispatch } = await makeReadyStick();++ // A real push, taken from device logs: it ramps in, sits silent while+ // held, eases off, then lands on zero when let go. The 0.24 lead-in is+ // below the activation point, so it correctly does not scroll.+ stickRef.current?.(up(0.24));+ stickRef.current?.(up(1));+ vi.advanceTimersByTime(2_190);+ stickRef.current?.(up(0.79));+ stickRef.current?.({ angle: 0, distance: 0 });++ const kinds = dispatch.mock.calls.map((call) => call[0].type);+ // Nothing during the silence, and no early stop before the release.+ expect(kinds).toEqual(['scroll', 'scroll', 'scroll-stop']);+ } finally {+ vi.useRealTimers();+ }+ });++ it('stops when the stick returns to centre', async () => {+ const { stickRef, dispatch } = await makeReadyStick();++ stickRef.current?.(up(1));+ dispatch.mockClear();+ stickRef.current?.(centre);++ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });+ });++ it('keeps scrolling through the long silences a held stick produces', async () => {+ vi.useFakeTimers();+ try {+ const { stickRef, dispatch } = await makeReadyStick();++ stickRef.current?.(up(1));+ dispatch.mockClear();+ // Measured against the hardware: holding the stick still reports+ // nothing for seconds at a time. Treating that silence as a release is+ // exactly what made held-to-scroll stop after a moment.+ vi.advanceTimersByTime(3_000);++ expect(dispatch).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('gives up if the device disappears mid-push', async () => {+ vi.useFakeTimers();+ try {+ const { stickRef, dispatch } = await makeReadyStick();++ stickRef.current?.(up(1));+ dispatch.mockClear();+ // Release has its own signal, so this only covers the device going+ // away while pushed — unplugged, asleep, or a dropped packet. Without+ // it the page would scroll forever.+ vi.advanceTimersByTime(30_000);++ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves the sideways directions as one-shot actions', async () => {+ const { stickRef, dispatch } = await makeReadyStick();++ // Left is 0.375–0.625; it toggles a sidebar, which must not repeat.+ stickRef.current?.({ angle: 0.5, distance: 1 });+ stickRef.current?.({ angle: 0.5, distance: 1 });++ const commands = dispatch.mock.calls.filter((call) => call[0].type === 'command');+ expect(commands).toHaveLength(1);+ expect(commands[0][0].commandId).toBe('toggleSidebar');+ expect(dispatch.mock.calls.some((call) => call[0].type === 'scroll')).toBe(false);+ });++ it('mirrors the raw stick angle and distance onto the settings preview', () => {+ const { stickRef, dispatch, preview, controller } = makeStick();+ controller.setLayoutPreviewActive(true);++ stickRef.current?.({ angle: 0.75, distance: 0.8 });+ stickRef.current?.({ angle: 0.12, distance: 0.6 });+ stickRef.current?.({ angle: 0.75, distance: 0 });++ expect(preview).toHaveBeenNthCalledWith(1, {+ part: 'analog',+ pressed: true,+ angle: 0.75,+ distance: 0.8,+ });+ expect(preview).toHaveBeenNthCalledWith(2, {+ part: 'analog',+ pressed: true,+ angle: 0.12,+ distance: 0.6,+ });+ expect(preview).toHaveBeenNthCalledWith(3, {+ part: 'analog',+ pressed: false,+ angle: 0.75,+ distance: 0,+ });+ expect(dispatch).not.toHaveBeenCalled();+ });+ });++ it('flashes a greeting when the window comes back, then returns to status lighting', async () => {+ vi.useFakeTimers();+ try {+ 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 () => [+ 'running-session',+ ]);+ controller.applySettings(settings({ lightingBrightness: 100, lightingAutoDim: 'off' }));+ await controller.resumeTaskSlots();+ controller.updateSessionActivity([+ {+ sessionId: 'running-session',+ phase: 'running',+ compactDetail: '',+ attention: false,+ },+ ]);+ sink.update.mockClear();++ controller.playWindowReveal();+ expect(sink.update.mock.lastCall?.[0]?.ambient.effect).toBe(WorkLouderLightingEffect.Snake);++ // Status lighting must not punch through the greeting mid-sweep.+ controller.updateSessionActivity([+ {+ sessionId: 'running-session',+ phase: 'needs-interaction',+ compactDetail: '',+ attention: false,+ },+ ]);+ expect(sink.update.mock.lastCall?.[0]?.ambient.effect).toBe(WorkLouderLightingEffect.Snake);++ await vi.advanceTimersByTimeAsync(2_000);+ expect(sink.update.mock.lastCall?.[0]?.ambient.effect).toBe(WorkLouderLightingEffect.Breath);+ expect(sink.update.mock.calls[0]?.[0]?.ambient.color).toBe(0xd0060c);+ } finally {+ vi.useRealTimers();+ }+ });++ it('ends the greeting early when the user touches the keyboard', () => {+ vi.useFakeTimers();+ try {+ const activityHandlerRef: { current: (() => void) | null } = { current: null };+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn((handler: (() => void) | null) => {+ activityHandlerRef.current = handler;+ }),+ setConnectionStatusHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn());+ controller.start();+ controller.playWindowReveal();+ expect(sink.update.mock.lastCall?.[0]?.ambient.effect).toBe(WorkLouderLightingEffect.Snake);++ activityHandlerRef.current?.();+ expect(isWorkLouderCodexLightingFrameOff(sink.update.mock.lastCall?.[0])).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ it('clears the last device snapshot when the keyboard disappears', () => {+ const statusRef: { current: ((status: 'connected' | 'not-detected') => 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;+ }),+ setDeviceStateHandler: vi.fn(),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn());+ controller.start();+ sink.setDeviceStateHandler.mock.calls.at(-1)?.[0]?.({+ deviceType: 'codex-micro',+ isUsbConnection: true,+ firmwareVersion: '1.2.3',+ batteryPercentage: 80,+ isCharging: false,+ inputMonitoringPermission: 'granted',+ });+ expect(controller.getState().device.deviceType).toBe('codex-micro');++ statusRef.current?.('not-detected');+ expect(controller.getState().connectionStatus).toBe('not-detected');+ expect(controller.getState().device.deviceType).toBeNull();+ expect(controller.getState().device.batteryPercentage).toBeNull();+ expect(controller.getState().device.inputMonitoringPermission).toBe('granted');+ });++ it('delegates shutdown so the host can turn the device off', 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());++ await controller.dispose();++ expect(sink.setAgentKeyPressHandler).toHaveBeenLastCalledWith(null);+ expect(sink.setDeviceActivityHandler).toHaveBeenLastCalledWith(null);+ expect(sink.setConnectionStatusHandler).toHaveBeenLastCalledWith(null);+ expect(sink.dispose).toHaveBeenCalledOnce();+ });++ it('stops leftover stick scrolling and encoder presses when the account suspends', 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();+ joystickRef.current?.({ angle: 0.25, distance: 1 });+ hidRef.current?.({ key: 'ENC', act: 1 });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'scroll', direction: 'down' }),+ );+ dispatch.mockClear();++ controller.suspendTaskSlots();+ hidRef.current?.({ key: 'ENC', act: 0 });++ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });+ expect(dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'keyboard' }));++ dispatch.mockClear();+ joystickRef.current?.({ angle: 0.25, distance: 1 });+ hidRef.current?.({ key: 'ACT06', act: 1 });+ hidRef.current?.({ key: 'ENC_CW', act: 2 });++ expect(dispatch).not.toHaveBeenCalled();+ });++ it('releases a held microphone when the account suspends or the key is later released', async () => {+ const hidRef: { current: ((event: { key: string; act: 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;+ }),+ 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 });+ expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'press' });++ dispatch.mockClear();+ controller.suspendTaskSlots();+ expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'release' });++ dispatch.mockClear();+ hidRef.current?.({ key: 'ACT10', act: 0 });+ expect(dispatch).not.toHaveBeenCalledWith({ type: 'voice', phase: 'press' });+ expect(dispatch).not.toHaveBeenCalledWith({ type: 'voice', phase: 'release' });+ });++ 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,+ };+ const dispatch = vi.fn();+ const sink = {+ update: vi.fn(),+ setAgentKeyPressHandler: vi.fn(),+ setDeviceActivityHandler: vi.fn(),+ setConnectionStatusHandler: vi.fn(),+ setHidInputHandler: vi.fn(),+ setJoystickInputHandler: vi.fn((handler: typeof joystickRef.current) => {+ joystickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), async () => [], dispatch);+ controller.start();+ await controller.resumeTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'command', commandId: 'toggleSidebar' }),+ );++ dispatch.mockClear();+ controller.suspendTaskSlots();+ await controller.resumeTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ expect(dispatch).not.toHaveBeenCalled();++ joystickRef.current?.({ angle: 0.5, distance: 0 });+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'command', commandId: 'toggleSidebar' }),+ );+ });++ it('clears a held stick during suspend so the next push after resume works', async () => {+ 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(),+ setJoystickInputHandler: vi.fn((handler: typeof joystickRef.current) => {+ joystickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), async () => [], dispatch);+ controller.start();+ await controller.resumeTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ controller.suspendTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 0 });+ dispatch.mockClear();+ await controller.resumeTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'command', commandId: 'toggleSidebar' }),+ );+ });++ it('keeps the first push after resume when the stick was already centred', async () => {+ 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(),+ setJoystickInputHandler: vi.fn((handler: typeof joystickRef.current) => {+ joystickRef.current = handler;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), async () => [], dispatch);+ controller.start();+ await controller.resumeTaskSlots();+ controller.suspendTaskSlots();+ dispatch.mockClear();+ await controller.resumeTaskSlots();+ joystickRef.current?.({ angle: 0.5, distance: 1 });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'command', commandId: 'toggleSidebar' }),+ );+ });++ it('does not dispatch hardware actions until the account resumes', () => {+ const hidRef: { current: ((event: { key: string; act: 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;+ }),+ dispose: vi.fn(async () => undefined),+ };+ const controller = new WorkLouderCodexLightingController(sink, vi.fn(), undefined, dispatch);+ controller.start();+ hidRef.current?.({ key: 'ACT06', act: 1 });+ hidRef.current?.({ key: 'ENC_CW', act: 2 });+ expect(dispatch).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.tsnew file mode 100644index 0000000000..466d10e49d--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts@@ -0,0 +1,137 @@+import { describe, expect, it } from 'vitest';++import type { AgentIslandSessionActivity } from '../../../shared/agentIsland.js';+import {+ applyWorkLouderCodexLightingBrightness,+ createWorkLouderCodexOffFrame,+ createWorkLouderCodexLightingFrame,+ createWorkLouderCodexWindowRevealFrame,+ isWorkLouderCodexHostMessage,+ isWorkLouderCodexLightingFrameOff,+ parseWorkLouderCodexAgentKeyPress,+ projectWorkLouderCodexSlotActivity,+ WorkLouderLightingEffect,+} from '../protocol.js';++function activity(+ sessionId: string,+ phase: AgentIslandSessionActivity['phase'],+ attention = false,+): AgentIslandSessionActivity {+ return { sessionId, phase, compactDetail: '', attention };+}++describe('createWorkLouderCodexLightingFrame', () => {+ it('keeps an idle keyboard off', () => {+ const frame = createWorkLouderCodexLightingFrame([]);++ expect(isWorkLouderCodexLightingFrameOff(frame)).toBe(true);+ expect(frame.threads).toHaveLength(6);+ });++ it('uses animated blue lighting while Cindy is running', () => {+ const frame = createWorkLouderCodexLightingFrame([activity('one', 'running')]);++ expect(frame.ambient.effect).toBe(WorkLouderLightingEffect.Snake);+ expect(frame.ambient.color).toBe(0x4c6fff);+ expect(frame.threads[0]).toMatchObject({+ id: 0,+ effect: WorkLouderLightingEffect.Breath,+ brightness: 0.8,+ });+ });++ it('prioritizes a user decision over concurrent running and error activity', () => {+ const frame = createWorkLouderCodexLightingFrame([+ activity('running', 'running'),+ activity('error', 'error', true),+ activity('question', 'needs-interaction'),+ ]);++ expect(frame.ambient.color).toBe(0xffa000);+ });++ it('shows unread terminal states and clears acknowledged ones', () => {+ const unread = createWorkLouderCodexLightingFrame([activity('done', 'completed', true)]);+ const acknowledged = createWorkLouderCodexLightingFrame([activity('done', 'completed', false)]);++ expect(unread.ambient.color).toBe(0x35c759);+ expect(isWorkLouderCodexLightingFrameOff(acknowledged)).toBe(true);+ });++ it('always sends six thread slots so stale device LEDs are cleared', () => {+ const frame = createWorkLouderCodexLightingFrame(+ Array.from({ length: 8 }, (_, index) => activity(String(index), 'running')),+ );++ expect(frame.threads.map((thread) => thread.id)).toEqual([0, 1, 2, 3, 4, 5]);+ expect(frame.threads.every((thread) => thread.brightness > 0)).toBe(true);+ });++ it('keeps an activity LED on the same slot as its task key assignment', () => {+ const running = activity('running-task', 'running');+ const projected = projectWorkLouderCodexSlotActivity([running], ['idle-task', 'running-task']);+ const frame = createWorkLouderCodexLightingFrame([running], ['idle-task', 'running-task']);++ expect(projected).toEqual([undefined, running, undefined, undefined, undefined, undefined]);+ expect(frame.threads[0].brightness).toBe(0);+ expect(frame.threads[1].brightness).toBeGreaterThan(0);+ });+});++describe('Work Louder Agent key protocol', () => {+ it('maps only press events from the six Agent keys', () => {+ expect(parseWorkLouderCodexAgentKeyPress({ key: 'AG00', act: 1 })).toBe(0);+ expect(parseWorkLouderCodexAgentKeyPress({ key: 'AG05', act: 1, agent: 99 })).toBe(5);+ expect(parseWorkLouderCodexAgentKeyPress({ key: 'AG03', act: 0 })).toBeNull();+ expect(parseWorkLouderCodexAgentKeyPress({ key: 'ENC_CW', act: 2 })).toBeNull();+ expect(parseWorkLouderCodexAgentKeyPress({ key: 'AG06', act: 1 })).toBeNull();+ });++ it('accepts only in-range Agent key messages from the utility process', () => {+ expect(isWorkLouderCodexHostMessage({ kind: 'agent-key', slot: 0 })).toBe(true);+ expect(isWorkLouderCodexHostMessage({ kind: 'agent-key', slot: 5 })).toBe(true);+ expect(isWorkLouderCodexHostMessage({ kind: 'agent-key', slot: 6 })).toBe(false);+ expect(isWorkLouderCodexHostMessage({ kind: 'agent-key', slot: 1.5 })).toBe(false);+ });++ it('accepts the activity notification and rejects malformed variants', () => {+ expect(isWorkLouderCodexHostMessage({ kind: 'activity' })).toBe(true);+ expect(isWorkLouderCodexHostMessage({ kind: 'device-activity' })).toBe(false);+ expect(isWorkLouderCodexHostMessage(null)).toBe(false);+ });+});++describe('Work Louder lighting settings', () => {+ it('scales every zone without mutating the semantic frame', () => {+ const frame = createWorkLouderCodexLightingFrame([activity('one', 'running')]);+ const scaled = applyWorkLouderCodexLightingBrightness(frame, 50);++ expect(scaled.ambient.brightness).toBe(frame.ambient.brightness * 0.5);+ expect(scaled.keys.brightness).toBe(frame.keys.brightness * 0.5);+ expect(scaled.threads[0]?.brightness).toBe(frame.threads[0]?.brightness * 0.5);+ expect(frame.ambient.brightness).toBe(0.7);+ });++ it('creates a complete six-slot off frame', () => {+ const frame = createWorkLouderCodexOffFrame();++ expect(isWorkLouderCodexLightingFrameOff(frame)).toBe(true);+ expect(frame.threads.map((thread) => thread.id)).toEqual([0, 1, 2, 3, 4, 5]);+ });++ it('greets a reopened window with a snake-and-breath sweep across every zone', () => {+ const frame = createWorkLouderCodexWindowRevealFrame();++ expect(frame.ambient.effect).toBe(WorkLouderLightingEffect.Snake);+ expect(frame.ambient.color).toBe(0xd0060c);+ expect(frame.keys.effect).toBe(WorkLouderLightingEffect.Breath);+ expect(frame.keys.color).toBe(0xd0060c);+ expect(frame.threads).toHaveLength(6);+ expect(frame.threads.every((thread) => thread.color === 0xd0060c)).toBe(true);+ expect(frame.threads.every((thread) => thread.effect === WorkLouderLightingEffect.Breath)).toBe(+ true,+ );+ expect(isWorkLouderCodexLightingFrameOff(frame)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.tsnew file mode 100644index 0000000000..8d4f1662e2--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts@@ -0,0 +1,260 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it, vi } from 'vitest';++import type {+ WorkLouderCodexSettings,+ WorkLouderCodexState,+} from '../../../shared/workLouderCodex.js';+import {+ WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ createWorkLouderCodexDefaultSettings,+} from '../../../shared/workLouderCodex.js';+import { createWorkLouderCodexSettingsIpc } from '../settingsIpc.js';++const DEFAULT_SETTINGS: WorkLouderCodexSettings = createWorkLouderCodexDefaultSettings();++const EVENT = { senderFrame: 'fake' };++function makeIpc(options?: {+ assertTrustedSender?: (event: unknown) => void;+ writeThrows?: boolean;+}) {+ let settings = createWorkLouderCodexDefaultSettings();+ const assertTrustedSender = vi.fn(options?.assertTrustedSender ?? (() => undefined));+ const writeSettings = vi.fn((patch: Partial<WorkLouderCodexSettings>) => {+ if (options?.writeThrows) throw new Error('EACCES: /internal/private/path readonly');+ settings = { ...settings, ...patch };+ return { ...settings };+ });+ const applySettings = vi.fn((next: WorkLouderCodexSettings) => {+ settings = { ...next };+ });+ const getState = vi.fn((): WorkLouderCodexState => ({+ connectionStatus: 'connected',+ connectionReason: null,+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },+ settings: { ...settings },+ agentSlots: Array.from({ length: 6 }, (_, slot) => ({+ slot,+ sessionId: null,+ title: null,+ action: null,+ })),+ taskOptions: [],+ agentSlotCount: 6,+ }));+ const resetSettings = vi.fn(() => {+ settings = createWorkLouderCodexDefaultSettings();+ return { ...settings };+ });+ const openInputMonitoringSettings = vi.fn(async () => undefined);+ const probeDevice = vi.fn();+ const publishTasks = vi.fn();+ const setLayoutPreviewActive = vi.fn();+ const ipc = createWorkLouderCodexSettingsIpc({+ assertTrustedSender,+ getState,+ writeSettings,+ resetSettings,+ applySettings,+ openInputMonitoringSettings,+ probeDevice,+ publishTasks,+ setLayoutPreviewActive,+ });+ return {+ ipc,+ assertTrustedSender,+ getState,+ writeSettings,+ resetSettings,+ applySettings,+ openInputMonitoringSettings,+ probeDevice,+ publishTasks,+ setLayoutPreviewActive,+ };+}++describe('Work Louder Codex settings IPC business body', () => {+ it('rejects an untrusted sender before reading or writing device state', () => {+ const untrusted = () => {+ throw new Error('untrusted sender');+ };+ const { ipc, getState, writeSettings, applySettings } = makeIpc({+ assertTrustedSender: untrusted,+ });++ expect(() => ipc.get(EVENT)).toThrow('untrusted sender');+ expect(() => ipc.set(EVENT, { lightingBrightness: 50 })).toThrow('untrusted sender');+ expect(getState).not.toHaveBeenCalled();+ expect(writeSettings).not.toHaveBeenCalled();+ expect(applySettings).not.toHaveBeenCalled();+ });++ it.each([+ [null, 'settings patch required'],+ [[], 'settings patch required'],+ [{}, 'cannot be empty'],+ [{ unknown: true }, 'unknown Work Louder Codex setting'],+ [{ lightingBrightness: '50' }, 'must be an integer'],+ [{ lightingBrightness: 49.5 }, 'must be an integer'],+ [{ lightingBrightness: -1 }, 'must be an integer'],+ [{ lightingBrightness: 101 }, 'must be an integer'],+ [{ lightingAutoDim: 'sometimes' }, 'lightingAutoDim is invalid'],+ [{ singleTapAgentKeys: 1 }, 'must be a boolean'],+ ])('rejects invalid payload %j with INVALID_PARAMS', (value, messagePart) => {+ const { ipc, writeSettings, applySettings } = makeIpc();++ expect(() => ipc.set(EVENT, value)).toThrow('[INVALID_PARAMS]');+ expect(() => ipc.set(EVENT, value)).toThrow(messagePart);+ expect(writeSettings).not.toHaveBeenCalled();+ expect(applySettings).not.toHaveBeenCalled();+ });++ it('persists, applies, and returns a valid settings patch', () => {+ const { ipc, writeSettings, applySettings } = makeIpc();+ const patch = {+ lightingBrightness: 40,+ lightingAutoDim: 'off' as const,+ singleTapAgentKeys: false,+ };++ const state = ipc.set(EVENT, patch);++ expect(writeSettings).toHaveBeenCalledWith(patch);+ expect(applySettings).toHaveBeenCalledWith({+ lightingBrightness: 40,+ lightingAutoDim: 'off',+ agentSource: 'sidebar',+ customAgentKeys: [null, null, null, null, null, null],+ singleTapAgentKeys: false,+ layout: DEFAULT_SETTINGS.layout,+ });+ expect(state.settings).toMatchObject({+ lightingBrightness: 40,+ lightingAutoDim: 'off',+ singleTapAgentKeys: false,+ });+ });++ it('re-checks the device on probe and refuses untrusted callers', () => {+ const { ipc, probeDevice, assertTrustedSender } = makeIpc();++ const state = ipc.probe(EVENT);++ expect(probeDevice).toHaveBeenCalledOnce();+ expect(state.settings).toBeTruthy();++ assertTrustedSender.mockImplementationOnce(() => {+ throw new Error('untrusted');+ });+ expect(() => ipc.probe(EVENT)).toThrow('untrusted');+ // Rejected before reaching the device.+ expect(probeDevice).toHaveBeenCalledOnce();+ });++ it('takes the sidebar task list, including tasks on linked machines', () => {+ const { ipc, publishTasks } = makeIpc();++ ipc.publishTasks(EVENT, [+ { id: 'local-1', title: 'Local task', pinnedAt: null, userSendAt: 1_700 },+ // Main cannot see this one at all — it lives in the renderer's remote store.+ { id: 'remote-1', title: 'Remote task', pinnedAt: 1_700_000_000_000, userSendAt: null },+ ]);++ expect(publishTasks).toHaveBeenCalledWith([+ { id: 'local-1', title: 'Local task', pinnedAt: null, userSendAt: 1_700 },+ { id: 'remote-1', title: 'Remote task', pinnedAt: 1_700_000_000_000, userSendAt: null },+ ]);+ });++ it('rejects a malformed task list rather than projecting garbage onto the keys', () => {+ const { ipc, publishTasks } = makeIpc();++ expect(() => ipc.publishTasks(EVENT, 'nope')).toThrow();+ expect(() => ipc.publishTasks(EVENT, [{ id: '', title: 'x', pinnedAt: null }])).toThrow();+ expect(() => ipc.publishTasks(EVENT, [{ id: 'a', title: 5, pinnedAt: null }])).toThrow();+ expect(() =>+ ipc.publishTasks(EVENT, [{ id: 'a', title: 'x'.repeat(513), pinnedAt: null, userSendAt: null }]),+ ).toThrow('title is too long');+ expect(() =>+ ipc.publishTasks(+ EVENT,+ Array.from({ length: 101 }, (_, index) => ({+ id: `task-${index}`,+ title: 'x',+ pinnedAt: null,+ userSendAt: null,+ })),+ ),+ ).toThrow('too long');+ expect(publishTasks).not.toHaveBeenCalled();+ });++ it('drops a published catalog that belongs to another account generation', () => {+ const source = readFileSync(resolve(__dirname, '../index.ts'), 'utf8');+ expect(source).toContain('if (isAppSessionBoundaryPending()) return null;');+ expect(source).toContain('if (rendererTaskCatalogScope !== currentTaskCatalogScope())');+ expect(source).toContain('if (!scope) return;');+ expect(source).toContain('workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());');+ });++ it('still accepts a layout saved before voiceButtonMode was removed', () => {+ const { ipc } = makeIpc();++ // Older builds stored a microphone mode. The key now follows Cindy's own+ // microphone, but a settings object round-tripped from such a build must+ // not be rejected outright.+ const state = ipc.set(EVENT, {+ layout: { ...DEFAULT_SETTINGS.layout, voiceButtonMode: 'push-to-talk' },+ });++ expect(state.settings.layout).not.toHaveProperty('voiceButtonMode');+ expect(state.settings.layout.separateMicrophoneKeys).toBe(false);+ });++ it('resets all settings through the dedicated reset operation', () => {+ const { ipc, resetSettings, applySettings } = makeIpc();++ const state = ipc.reset(EVENT);++ expect(resetSettings).toHaveBeenCalledOnce();+ expect(applySettings).toHaveBeenCalledWith(DEFAULT_SETTINGS);+ expect(state.settings).toEqual(DEFAULT_SETTINGS);+ });++ it('toggles layout preview without writing settings', () => {+ const { ipc, setLayoutPreviewActive, writeSettings } = makeIpc();++ ipc.setLayoutPreviewActive(EVENT, true);+ ipc.setLayoutPreviewActive(EVENT, false);++ expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(1, true);+ expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(2, false);+ expect(writeSettings).not.toHaveBeenCalled();+ });++ it('opens macOS Input Monitoring settings only for trusted callers', async () => {+ const { ipc, openInputMonitoringSettings } = makeIpc();++ await ipc.openInputMonitoringSettings(EVENT);++ expect(openInputMonitoringSettings).toHaveBeenCalledOnce();+ });++ it('converts persistence failures to INTERNAL without leaking file paths', () => {+ const { ipc, applySettings } = makeIpc({ writeThrows: true });+ let caught: Error | null = null;+ try {+ ipc.set(EVENT, { lightingBrightness: 20 });+ } catch (error) {+ caught = error as Error;+ }++ expect(caught?.message).toContain('[INTERNAL]');+ expect(caught?.message).not.toContain('/internal/private/path');+ expect(applySettings).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.tsnew file mode 100644index 0000000000..2b6e1479eb--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/settingsStore.test.ts@@ -0,0 +1,116 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { createWorkLouderCodexDefaultSettings } from '../../../shared/workLouderCodex.js';++const electronMock = vi.hoisted(() => ({+ userDataDir: '',+}));++vi.mock('electron', () => ({+ app: {+ getPath: vi.fn(() => electronMock.userDataDir),+ },+}));++vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => 'cloud:owner-a:1',+ ownerScopedUserDataPath: (...parts: string[]) =>+ path.join(electronMock.userDataDir, 'owners', 'owner-a', ...parts),+}));++vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: {+ child: () => ({+ info: vi.fn(),+ warn: vi.fn(),+ }),+ },+}));++import {+ __testing,+ readWorkLouderCodexSettings,+ writeWorkLouderCodexSettingsPatch,+} from '../settingsStore.js';++describe('Work Louder Codex settings store', () => {+ afterEach(() => {+ if (electronMock.userDataDir) {+ fs.rmSync(electronMock.userDataDir, { recursive: true, force: true });+ electronMock.userDataDir = '';+ }+ });++ it('uses the shipped defaults for missing or invalid persisted values', () => {+ expect(__testing.normalize(undefined)).toEqual(createWorkLouderCodexDefaultSettings());+ expect(+ __testing.normalize({+ lightingBrightness: '50',+ lightingAutoDim: 'sometimes',+ singleTapAgentKeys: 1,+ }),+ ).toEqual(createWorkLouderCodexDefaultSettings());+ });++ it('rounds and clamps persisted brightness while preserving valid options', () => {+ expect(+ __testing.normalize({+ lightingBrightness: 49.6,+ lightingAutoDim: '30-seconds',+ singleTapAgentKeys: false,+ }),+ ).toEqual({+ ...createWorkLouderCodexDefaultSettings(),+ lightingBrightness: 50,+ lightingAutoDim: '30-seconds',+ singleTapAgentKeys: false,+ });+ expect(__testing.normalize({ lightingBrightness: -9 }).lightingBrightness).toBe(0);+ expect(__testing.normalize({ lightingBrightness: 999 }).lightingBrightness).toBe(100);+ expect(__testing.normalize({ lightingBrightness: Number.NaN }).lightingBrightness).toBe(100);+ });++ it('maps the old pinned and recent sources onto sidebar order', () => {+ expect(__testing.normalize({ agentSource: 'pinned' }).agentSource).toBe('sidebar');+ expect(__testing.normalize({ agentSource: 'recent' }).agentSource).toBe('sidebar');+ expect(__testing.normalize({ agentSource: 'last-sent' }).agentSource).toBe('last-sent');+ });++ it('persists a patch under the Electron userData directory', () => {+ electronMock.userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'worklouder-settings-'));++ const next = writeWorkLouderCodexSettingsPatch({+ lightingBrightness: 60,+ lightingAutoDim: '1-minute',+ singleTapAgentKeys: false,+ });++ expect(next).toEqual({+ ...createWorkLouderCodexDefaultSettings(),+ lightingBrightness: 60,+ lightingAutoDim: '1-minute',+ singleTapAgentKeys: false,+ });+ expect(readWorkLouderCodexSettings()).toEqual(next);+ expect(+ JSON.parse(+ fs.readFileSync(+ path.join(+ electronMock.userDataDir,+ 'owners',+ 'owner-a',+ 'worklouder-codex-settings.json',+ ),+ 'utf-8',+ ),+ ),+ ).toEqual({+ lightingBrightness: 60,+ lightingAutoDim: '1-minute',+ });+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/taskSlots.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/taskSlots.test.tsnew file mode 100644index 0000000000..3834bcc31d--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/taskSlots.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from 'vitest';++import {+ buildWorkLouderCodexTaskCatalog,+ selectWorkLouderCodexRecentTaskSlots,+} from '../taskSlots.js';++describe('selectWorkLouderCodexRecentTaskSlots', () => {+ it('keeps pure recency order and caps the projection at six tasks', () => {+ expect(+ selectWorkLouderCodexRecentTaskSlots([+ { id: 'recent-1' },+ { id: 'recent-2' },+ { id: 'recent-3' },+ { id: 'recent-4' },+ { id: 'recent-5' },+ { id: 'recent-6' },+ { id: 'older-pinned-task' },+ ]),+ ).toEqual(['recent-1', 'recent-2', 'recent-3', 'recent-4', 'recent-5', 'recent-6']);+ });+});++describe('buildWorkLouderCodexTaskCatalog', () => {+ it('projects whatever list it is handed, wherever the tasks live', () => {+ // Rows can come from the renderer, which is the only side that sees tasks+ // on a linked machine. The catalogue does not care which is which.+ const catalog = buildWorkLouderCodexTaskCatalog([+ { id: 'local-1', title: 'Local', pinnedAt: null, userSendAt: 2_000 },+ { id: 'remote-1', title: 'On another machine', pinnedAt: null, userSendAt: 1_000 },+ ]);++ expect(catalog.sidebar.map((task) => task.id)).toEqual(['local-1', 'remote-1']);+ expect(catalog.options).toHaveLength(2);+ });++ it('caps the keys at six while keeping the full option list', () => {+ const rows = Array.from({ length: 9 }, (_, index) => ({+ id: `task-${index}`,+ title: `Task ${index}`,+ pinnedAt: null,+ userSendAt: index,+ }));++ const catalog = buildWorkLouderCodexTaskCatalog(rows);++ expect(catalog.sidebar).toHaveLength(6);+ expect(catalog.options).toHaveLength(9);+ });++ it('orders last-sent tasks by the last user message, not sidebar order', () => {+ const catalog = buildWorkLouderCodexTaskCatalog([+ { id: 'older', title: 'Sent earlier', pinnedAt: 9_000, userSendAt: 1_000 },+ { id: 'never', title: 'Never sent', pinnedAt: null, userSendAt: null },+ { id: 'newer', title: 'Sent later', pinnedAt: null, userSendAt: 2_000 },+ ]);++ expect(catalog.lastSent.map((task) => task.id)).toEqual(['newer', 'older', 'never']);+ expect(catalog.sidebar.map((task) => task.id)).toEqual(['older', 'never', 'newer']);+ });++ it('keeps last-sent on the full catalog when only some rows are visible', () => {+ const catalog = buildWorkLouderCodexTaskCatalog([+ { id: 'hidden-new', title: 'Hidden but recent', pinnedAt: null, userSendAt: 3_000 },+ {+ id: 'visible-old',+ title: 'Visible older',+ pinnedAt: null,+ userSendAt: 1_000,+ sidebarOrder: 0,+ },+ ]);++ expect(catalog.sidebar.map((task) => task.id)).toEqual(['visible-old']);+ expect(catalog.lastSent.map((task) => task.id)).toEqual(['hidden-new', 'visible-old']);+ });++ it('keeps a published empty sidebar empty instead of falling back to every task', () => {+ const catalog = buildWorkLouderCodexTaskCatalog(+ [+ { id: 'hidden-a', title: 'Hidden A', pinnedAt: null, userSendAt: 2_000 },+ { id: 'hidden-b', title: 'Hidden B', pinnedAt: null, userSendAt: 1_000 },+ ],+ { publishedVisibleOrder: true },+ );++ expect(catalog.sidebar).toEqual([]);+ expect(catalog.lastSent.map((task) => task.id)).toEqual(['hidden-a', 'hidden-b']);+ });++ it('keeps archived visible rows off last-sent while still lighting the sidebar keys', () => {+ const catalog = buildWorkLouderCodexTaskCatalog(+ [+ {+ id: 'archived-visible',+ title: 'Archived',+ pinnedAt: null,+ userSendAt: 9_000,+ sidebarOrder: 0,+ catalogEligible: false,+ },+ { id: 'active-hidden', title: 'Active', pinnedAt: null, userSendAt: 1_000 },+ ],+ { publishedVisibleOrder: true },+ );++ expect(catalog.sidebar.map((task) => task.id)).toEqual(['archived-visible']);+ expect(catalog.lastSent.map((task) => task.id)).toEqual(['active-hidden']);+ expect(catalog.options.map((task) => task.id)).toEqual(['active-hidden']);+ });++ it('still fills last-sent from active rows when only six archived keys are reserved', () => {+ const archived = Array.from({ length: 6 }, (_, index) => ({+ id: `archived-${index}`,+ title: `Archived ${index}`,+ pinnedAt: null,+ userSendAt: 9_000 + index,+ sidebarOrder: index,+ catalogEligible: false as const,+ }));+ const active = Array.from({ length: 4 }, (_, index) => ({+ id: `active-${index}`,+ title: `Active ${index}`,+ pinnedAt: null,+ userSendAt: index,+ }));+ const catalog = buildWorkLouderCodexTaskCatalog([...archived, ...active], {+ publishedVisibleOrder: true,+ });++ expect(catalog.sidebar.map((task) => task.id)).toEqual(archived.map((row) => row.id));+ expect(catalog.lastSent.map((task) => task.id)).toEqual([...active].reverse().map((row) => row.id));+ expect(catalog.options.map((task) => task.id)).toEqual(active.map((row) => row.id));+ });++ it('keeps an untitled task addressable instead of dropping it', () => {+ const catalog = buildWorkLouderCodexTaskCatalog([+ { id: 'blank', title: null, pinnedAt: null, userSendAt: null },+ ]);++ expect(catalog.sidebar).toEqual([{ id: 'blank', title: null, pinned: false }]);+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/windowReveal.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/windowReveal.test.tsnew file mode 100644index 0000000000..12922b931b--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/__tests__/windowReveal.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import {+ createWorkLouderCodexWindowRevealGate,+ noteWorkLouderCodexWindowVisibility,+} from '../windowReveal.js';++describe('noteWorkLouderCodexWindowVisibility', () => {+ it('plays the first time the window appears', () => {+ const gate = createWorkLouderCodexWindowRevealGate();++ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(true);+ });++ it('plays only when the window comes back after being hidden', () => {+ const gate = createWorkLouderCodexWindowRevealGate();++ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(true);+ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(false);+ expect(noteWorkLouderCodexWindowVisibility(gate, false)).toBe(false);+ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(true);+ });++ it('does not play again while the window stays visible', () => {+ const gate = createWorkLouderCodexWindowRevealGate();++ noteWorkLouderCodexWindowVisibility(gate, true);+ noteWorkLouderCodexWindowVisibility(gate, false);+ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(true);+ expect(noteWorkLouderCodexWindowVisibility(gate, true)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/worklouder-codex/index.ts b/apps/desktop/src/main/worklouder-codex/index.tsnew file mode 100644index 0000000000..47ee4e04ed--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/index.ts@@ -0,0 +1,302 @@+import fs from 'node:fs';+import { createRequire } from 'node:module';+import path from 'node:path';+import { BrowserWindow, ipcMain, shell, utilityProcess } from 'electron';++import { createLogger } from '../logger.js';+import { openMainWindowSession, sendMainWindowMessage } from '../deepLink.js';+import { registerInputDevice } from '../input-devices/registry.js';+import {+ WORKLOUDER_CODEX_ACTION_CHANNEL,+ WORKLOUDER_CODEX_DEVICE,+ WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL,+ WORKLOUDER_CODEX_GET_STATE_CHANNEL,+ WORKLOUDER_CODEX_OPEN_INPUT_MONITORING_CHANNEL,+ WORKLOUDER_CODEX_PROBE_CHANNEL,+ WORKLOUDER_CODEX_PUBLISH_TASKS_CHANNEL,+ WORKLOUDER_CODEX_SET_LAYOUT_PREVIEW_CHANNEL,+ WORKLOUDER_CODEX_RESET_SETTINGS_CHANNEL,+ WORKLOUDER_CODEX_SET_SETTINGS_CHANNEL,+ WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL,+ type WorkLouderCodexPreviewInput,+ type WorkLouderCodexRendererAction,+ type WorkLouderCodexState,+} from '../../shared/workLouderCodex.js';+import {+ assertTrustedAppRendererEvent,+ isTrustedAppRendererWindow,+} from '../security/trustedAppRenderer.js';+import {+ WorkLouderCodexHostClient,+ type WorkLouderSdkLocation,+} from './WorkLouderCodexHostClient.js';+import { WorkLouderCodexLightingController } from './WorkLouderCodexLightingController.js';+import { createWorkLouderCodexSettingsIpc } from './settingsIpc.js';+import {+ createWorkLouderCodexWindowRevealGate,+ noteWorkLouderCodexWindowVisibility,+} from './windowReveal.js';+import {+ activeOwnerScopeKey,+ isAppSessionBoundaryPending,+} from '../appSessionState.js';+import {+ readWorkLouderCodexSettings,+ resetWorkLouderCodexSettings,+ writeWorkLouderCodexSettingsPatch,+} from './settingsStore.js';+import {+ buildWorkLouderCodexTaskCatalog,+ listWorkLouderCodexTaskCatalog,+ type WorkLouderCodexTaskCatalogInput,+} from './taskSlots.js';++const log = createLogger('worklouder-codex');+const requireFromMain = createRequire(__filename);++function resolveWorkLouderSdk(): WorkLouderSdkLocation | null {+ try {+ return {+ entry: requireFromMain.resolve('@worklouder/device-kit-oai'),+ source: 'cindy-package',+ };+ } catch {+ // The official SDK is optional until Work Louder grants Cindy registry access.+ }++ for (const packageDir of listBundledWorkLouderSdkDirs()) {+ if (fs.existsSync(path.join(packageDir, 'package.json'))) {+ return { entry: packageDir, source: 'openai-app' };+ }+ }+ return null;+}++function listBundledWorkLouderSdkDirs(): string[] {+ const packageTail = path.join(+ 'resources',+ 'app.asar',+ 'node_modules',+ '@worklouder',+ 'device-kit-oai',+ );+ if (process.platform === 'darwin') {+ return ['ChatGPT.app', 'Codex.app'].map((appName) =>+ path.join('/Applications', appName, 'Contents', packageTail),+ );+ }+ if (process.platform === 'win32') {+ const localAppData = process.env.LOCALAPPDATA;+ const programFiles = process.env.ProgramFiles;+ const roots = [localAppData, programFiles].filter((root): root is string => Boolean(root));+ return roots.flatMap((root) =>+ ['ChatGPT', 'Codex'].flatMap((appName) => [+ path.join(root, appName, packageTail),+ path.join(root, 'Programs', appName, packageTail),+ ]),+ );+ }+ return [];+}++function forkWorkLouderHost(_sdkEntry: string): ReturnType<typeof utilityProcess.fork> {+ return utilityProcess.fork(path.join(__dirname, 'workLouderCodexHostProcess.js'), [], {+ serviceName: 'cindy-worklouder-codex',+ });+}++const hostClient = new WorkLouderCodexHostClient({+ resolveSdk: resolveWorkLouderSdk,+ fork: forkWorkLouderHost,+ log,+});++/**+ * Tasks as the sidebar currently shows them, published by the renderer.+ *+ * The local table is not the whole picture: sessions on a linked machine live+ * only in the renderer's remote store, so a machine driving someone else's+ * sessions would show six empty agent keys. The renderer is also the only side+ * that knows which machine filter is applied, so what it sends is what the user+ * sees. Null until it reports — until then the local table is the best guess.+ */+let rendererTaskCatalog: WorkLouderCodexTaskCatalogInput[] | null = null;+let rendererTaskCatalogScope: string | null = null;++function currentTaskCatalogScope(): string | null {+ if (isAppSessionBoundaryPending()) return null;+ return activeOwnerScopeKey();+}++function currentRendererTaskCatalog(): WorkLouderCodexTaskCatalogInput[] | null {+ if (!rendererTaskCatalog) return null;+ if (rendererTaskCatalogScope !== currentTaskCatalogScope()) {+ rendererTaskCatalog = null;+ rendererTaskCatalogScope = null;+ return null;+ }+ return rendererTaskCatalog;+}++export const workLouderCodexLightingController = new WorkLouderCodexLightingController(+ hostClient,+ (sessionId, focus = true) => openMainWindowSession(sessionId, { focus }),+ async () => {+ const catalog = currentRendererTaskCatalog();+ return catalog+ ? buildWorkLouderCodexTaskCatalog(catalog, { publishedVisibleOrder: true })+ : listWorkLouderCodexTaskCatalog();+ },+ dispatchRendererAction,+ dispatchPreviewInput,+);++let settingsIpcRegistered = false;+let inputDeviceRegistered = false;++/** Register this board as one input-device adapter, not as the host keyboard layer. */+export function registerWorkLouderCodexInputDevice(): void {+ if (inputDeviceRegistered) return;+ inputDeviceRegistered = true;+ registerInputDevice({+ descriptor: WORKLOUDER_CODEX_DEVICE,+ start: () => {+ registerWorkLouderCodexSettingsIpc();+ },+ updateSessionActivity: (activity) => {+ workLouderCodexLightingController.updateSessionActivity(activity);+ },+ playWindowReveal: () => {+ workLouderCodexLightingController.playWindowReveal();+ },+ resumeTaskSlots: async () => {+ workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());+ await workLouderCodexLightingController.resumeTaskSlots();+ },+ suspendTaskSlots: () => {+ rendererTaskCatalog = null;+ rendererTaskCatalogScope = null;+ workLouderCodexLightingController.suspendTaskSlots();+ },+ dispose: () => workLouderCodexLightingController.dispose(),+ });+}++/** Registers the local-desktop-only device settings bridge after Electron is ready. */+export function registerWorkLouderCodexSettingsIpc(): void {+ if (settingsIpcRegistered) return;+ settingsIpcRegistered = true;++ workLouderCodexLightingController.start();+ workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());+ const handlers = createWorkLouderCodexSettingsIpc({+ assertTrustedSender: (event) => assertTrustedAppRendererEvent(event as never),+ getState: () => workLouderCodexLightingController.getState(),+ writeSettings: writeWorkLouderCodexSettingsPatch,+ resetSettings: resetWorkLouderCodexSettings,+ applySettings: (settings) => workLouderCodexLightingController.applySettings(settings),+ openInputMonitoringSettings: async () => {+ if (process.platform !== 'darwin') return;+ await shell.openExternal(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent',+ );+ },+ probeDevice: () => hostClient.probe(),+ publishTasks: (tasks) => {+ const scope = currentTaskCatalogScope();+ if (!scope) return;+ rendererTaskCatalog = tasks.map((task) => ({ ...task }));+ rendererTaskCatalogScope = scope;+ void workLouderCodexLightingController.refreshTaskSlots().catch(() => undefined);+ },+ setLayoutPreviewActive: (active) => {+ workLouderCodexLightingController.setLayoutPreviewActive(active);+ },+ });++ ipcMain.handle(WORKLOUDER_CODEX_GET_STATE_CHANNEL, (event) => handlers.get(event));+ ipcMain.handle(WORKLOUDER_CODEX_SET_SETTINGS_CHANNEL, (event, patch: unknown) =>+ handlers.set(event, patch),+ );+ ipcMain.handle(WORKLOUDER_CODEX_RESET_SETTINGS_CHANNEL, (event) => handlers.reset(event));+ ipcMain.handle(WORKLOUDER_CODEX_OPEN_INPUT_MONITORING_CHANNEL, (event) =>+ handlers.openInputMonitoringSettings(event),+ );+ ipcMain.handle(WORKLOUDER_CODEX_PROBE_CHANNEL, (event) => handlers.probe(event));+ ipcMain.handle(WORKLOUDER_CODEX_PUBLISH_TASKS_CHANNEL, (event, tasks: unknown) =>+ handlers.publishTasks(event, tasks),+ );+ ipcMain.handle(WORKLOUDER_CODEX_SET_LAYOUT_PREVIEW_CHANNEL, (event, active: unknown) =>+ handlers.setLayoutPreviewActive(event, active),+ );++ workLouderCodexLightingController.subscribeState((state) => {+ broadcastState(state);+ });+}++function dispatchRendererAction(action: WorkLouderCodexRendererAction): void {+ if (action.type === 'external-url') {+ void shell.openExternal(action.url).catch((error: unknown) => {+ log.warn('failed to open Codex Micro external action', {+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return;+ }+ if (!sendMainWindowMessage(WORKLOUDER_CODEX_ACTION_CHANNEL, action)) {+ log.debug('Codex Micro action skipped because the main renderer is not ready', {+ type: action.type,+ });+ }+}++function dispatchPreviewInput(input: WorkLouderCodexPreviewInput): void {+ if (!sendMainWindowMessage(WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL, input)) {+ log.debug('Codex Micro preview skipped because the main renderer is not ready', {+ part: input.part,+ });+ }+}++function broadcastState(state: WorkLouderCodexState): void {+ for (const window of BrowserWindow.getAllWindows()) {+ if (!isTrustedAppRendererWindow(window)) continue;+ window.webContents.send(WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL, state);+ }+}++const windowRevealGates = new WeakMap<+ BrowserWindow,+ ReturnType<typeof createWorkLouderCodexWindowRevealGate>+>();++/**+ * Flash the keyboard when this Cindy window becomes visible.+ *+ * Hide / minimize / Dock close all count. Focus while already visible+ * does not. Seed from the current visibility so a show that already+ * fired is not treated as still hidden.+ */+export function attachWorkLouderCodexWindowReveal(win: BrowserWindow): void {+ if (windowRevealGates.has(win)) return;+ const gate = createWorkLouderCodexWindowRevealGate();+ windowRevealGates.set(win, gate);++ const sync = (): void => {+ if (win.isDestroyed()) return;+ const visible = win.isVisible() && !win.isMinimized();+ if (noteWorkLouderCodexWindowVisibility(gate, visible)) {+ workLouderCodexLightingController.playWindowReveal();+ }+ };++ win.on('show', sync);+ win.on('restore', sync);+ win.on('hide', sync);+ win.on('minimize', sync);+ win.once('closed', () => {+ windowRevealGates.delete(win);+ });+ sync();+}diff --git a/apps/desktop/src/main/worklouder-codex/protocol.ts b/apps/desktop/src/main/worklouder-codex/protocol.tsnew file mode 100644index 0000000000..26af56bb73--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/protocol.ts@@ -0,0 +1,399 @@+import type { AgentIslandSessionActivity } from '../../shared/agentIsland.js';+import {+ WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ type WorkLouderCodexConnectionReason,+ type WorkLouderCodexDeviceState,+} from '../../shared/workLouderCodex.js';++export { WORKLOUDER_CODEX_AGENT_SLOT_COUNT } from '../../shared/workLouderCodex.js';++export const enum WorkLouderLightingEffect {+ Off = 0,+ Solid = 1,+ Snake = 2,+ Rainbow = 3,+ Breath = 4,+ Gradient = 5,+ ShallowBreath = 6,+}++export interface WorkLouderLightingSide {+ effect: WorkLouderLightingEffect;+ brightness: number;+ speed: number;+ magic: number;+ color: number;+}++export interface WorkLouderThreadLighting {+ id: number;+ color: number;+ brightness: number;+ effect: WorkLouderLightingEffect;+ speed: number;+ syncKeysLighting: boolean;+ syncAmbientLighting: boolean;+}++export interface WorkLouderCodexLightingFrame {+ ambient: WorkLouderLightingSide;+ keys: WorkLouderLightingSide;+ threads: WorkLouderThreadLighting[];+}++export type WorkLouderCodexHostRequest =+ | { kind: 'init'; sdkEntry: string }+ | { kind: 'listen' }+ | { kind: 'apply'; frame: WorkLouderCodexLightingFrame }+ // Ask the host to verify the device is still there. The SDK has no+ // disconnect event, so unplugging goes unnoticed until something tries to+ // talk to the device — this is that something, driven by whoever is+ // currently showing connection state.+ | { kind: 'probe' }+ | { kind: 'stop' };++export type WorkLouderCodexHostMessage =+ | {+ kind: 'state';+ status: 'connected' | 'not-detected' | 'error';+ reason?: Exclude<WorkLouderCodexConnectionReason, 'sdk-unavailable'>;+ }+ /** Legacy utility-host message retained for older host fakes and upgrades. */+ | { kind: 'agent-key'; slot: number }+ | { kind: 'device'; device: WorkLouderCodexDeviceState }+ | { kind: 'hid'; event: WorkLouderCodexHidEvent }+ | { kind: 'joystick'; event: WorkLouderCodexJoystickEvent }+ | { kind: 'activity' }+ | { kind: 'log'; level: 'debug' | 'info' | 'warn' | 'error'; message: string }+ | { kind: 'stopped' };++export interface WorkLouderCodexHidEvent {+ key: string;+ act: 0 | 1 | 2;+}++export interface WorkLouderCodexJoystickEvent {+ angle: number;+ distance: number;+}++const COLORS = {+ running: 0x4c6fff,+ 'needs-interaction': 0xffa000,+ completed: 0x35c759,+ error: 0xff453a,+ /**+ * Window-reopen red tuned for these LEDs.+ * UI brand red `#DF0C27` / `#A61629` wash pink on the board.+ */+ brand: 0xd0060c,+} as const;++const OFF_SIDE: WorkLouderLightingSide = {+ effect: WorkLouderLightingEffect.Off,+ brightness: 0,+ speed: 0,+ magic: 0,+ color: 0,+};++const PHASE_PRIORITY: Readonly<Record<AgentIslandSessionActivity['phase'], number>> = {+ 'needs-interaction': 4,+ error: 3,+ running: 2,+ completed: 1,+};++/**+ * Projects Cindy's process-wide task activity into the two Codex Micro lighting+ * zones plus its six per-thread indicators.+ */+export function createWorkLouderCodexLightingFrame(+ activity: readonly AgentIslandSessionActivity[],+ slotSessionIds?: readonly string[],+): WorkLouderCodexLightingFrame {+ const slots = projectWorkLouderCodexSlotActivity(activity, slotSessionIds);+ const aggregate = slots.reduce<AgentIslandSessionActivity['phase'] | null>((current, item) => {+ if (!item) return current;+ return current === null || PHASE_PRIORITY[item.phase] > PHASE_PRIORITY[current]+ ? item.phase+ : current;+ }, null);++ return {+ ambient: aggregate ? ambientForPhase(aggregate) : { ...OFF_SIDE },+ keys: aggregate ? keysForPhase(aggregate) : { ...OFF_SIDE },+ threads: Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, id) =>+ threadForActivity(id, slots[id]),+ ),+ };+}++/** The ordered task assignment shared by the six LEDs and their physical keys. */+export function selectWorkLouderCodexSlotActivity(+ activity: readonly AgentIslandSessionActivity[],+): AgentIslandSessionActivity[] {+ return activity.filter(isLightingVisibleActivity).slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT);+}++/** Aligns activity LEDs with an explicit six-task key assignment when one is available. */+export function projectWorkLouderCodexSlotActivity(+ activity: readonly AgentIslandSessionActivity[],+ slotSessionIds?: readonly string[],+): Array<AgentIslandSessionActivity | undefined> {+ if (slotSessionIds === undefined) return selectWorkLouderCodexSlotActivity(activity);+ const visibleBySessionId = new Map(+ activity.filter(isLightingVisibleActivity).map((item) => [item.sessionId, item] as const),+ );+ return Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, slot) => {+ const sessionId = slotSessionIds[slot];+ return sessionId ? visibleBySessionId.get(sessionId) : undefined;+ });+}++/** Accept only press events for the six official Agent keys (AG00 through AG05). */+export function parseWorkLouderCodexAgentKeyPress(value: unknown): number | null {+ const event = parseWorkLouderCodexHidEvent(value);+ if (!event || event.act !== 1) return null;+ const match = /^AG0([0-5])$/.exec(event.key);+ return match ? Number(match[1]) : null;+}++export function parseWorkLouderCodexHidEvent(value: unknown): WorkLouderCodexHidEvent | null {+ if (!value || typeof value !== 'object') return null;+ const event = value as { key?: unknown; act?: unknown };+ if (+ typeof event.key !== 'string' ||+ event.key.length > 32 ||+ (event.act !== 0 && event.act !== 1 && event.act !== 2)+ ) {+ return null;+ }+ if (+ !/^AG0[0-5]$/.test(event.key) &&+ !/^ACT(?:0[6-9]|1[0-2])$/.test(event.key) &&+ !/^ENC[A-Z0-9_]*$/.test(event.key)+ ) {+ return null;+ }+ return { key: event.key, act: event.act };+}++export function parseWorkLouderCodexJoystickEvent(+ value: unknown,+): WorkLouderCodexJoystickEvent | null {+ if (!value || typeof value !== 'object') return null;+ const event = value as { angle?: unknown; distance?: unknown };+ if (+ typeof event.angle !== 'number' ||+ !Number.isFinite(event.angle) ||+ event.angle < 0 ||+ event.angle > 1 ||+ typeof event.distance !== 'number' ||+ !Number.isFinite(event.distance) ||+ event.distance < 0 ||+ event.distance > 1+ ) {+ return null;+ }+ return { angle: event.angle, distance: event.distance };+}++export function isWorkLouderCodexLightingFrameOff(frame: WorkLouderCodexLightingFrame): boolean {+ return (+ frame.ambient.brightness === 0 &&+ frame.keys.brightness === 0 &&+ frame.threads.every((thread) => thread.brightness === 0)+ );+}++/** Applies the user-facing overall brightness without mutating the semantic frame. */+export function applyWorkLouderCodexLightingBrightness(+ frame: WorkLouderCodexLightingFrame,+ brightnessPercent: number,+): WorkLouderCodexLightingFrame {+ const factor = Math.max(0, Math.min(100, brightnessPercent)) / 100;+ return {+ ambient: { ...frame.ambient, brightness: frame.ambient.brightness * factor },+ keys: { ...frame.keys, brightness: frame.keys.brightness * factor },+ threads: frame.threads.map((thread) => ({+ ...thread,+ brightness: thread.brightness * factor,+ })),+ };+}++export function createWorkLouderCodexOffFrame(): WorkLouderCodexLightingFrame {+ return {+ ambient: { ...OFF_SIDE },+ keys: { ...OFF_SIDE },+ threads: Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, id) => ({+ id,+ color: 0,+ brightness: 0,+ effect: WorkLouderLightingEffect.Off,+ speed: 0,+ syncKeysLighting: false,+ syncAmbientLighting: false,+ })),+ };+}++/**+ * A short hello on the whole board — used when Cindy's window comes back+ * after being hidden or minimized. Snake and breath are the two animated+ * effects already proven on this hardware (running / waiting). Rainbow is+ * not: on an idle board it can look like the lights never came on.+ */+export function createWorkLouderCodexWindowRevealFrame(): WorkLouderCodexLightingFrame {+ return {+ ambient: side(WorkLouderLightingEffect.Snake, 0.78, 0.55, COLORS.brand),+ keys: side(WorkLouderLightingEffect.Breath, 0.34, 0.55, COLORS.brand),+ threads: Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, id) => ({+ id,+ color: COLORS.brand,+ brightness: 0.72,+ effect: WorkLouderLightingEffect.Breath,+ speed: 0.55,+ syncKeysLighting: false,+ syncAmbientLighting: false,+ })),+ };+}++export function isWorkLouderCodexHostMessage(value: unknown): value is WorkLouderCodexHostMessage {+ if (!value || typeof value !== 'object') return false;+ const message = value as { kind?: unknown; status?: unknown; level?: unknown; message?: unknown };+ if (message.kind === 'stopped') return true;+ if (message.kind === 'activity') return true;+ if (message.kind === 'agent-key') {+ const slot = (message as { slot?: unknown }).slot;+ return (+ typeof slot === 'number' &&+ Number.isInteger(slot) &&+ slot >= 0 &&+ slot < WORKLOUDER_CODEX_AGENT_SLOT_COUNT+ );+ }+ if (message.kind === 'hid')+ return parseWorkLouderCodexHidEvent((message as { event?: unknown }).event) !== null;+ if (message.kind === 'joystick') {+ return parseWorkLouderCodexJoystickEvent((message as { event?: unknown }).event) !== null;+ }+ if (message.kind === 'device')+ return isWorkLouderCodexDeviceState((message as { device?: unknown }).device);+ if (message.kind === 'state') {+ const validStatus =+ message.status === 'connected' ||+ message.status === 'not-detected' ||+ message.status === 'error';+ const reason = (message as { reason?: unknown }).reason;+ return (+ validStatus &&+ (reason === undefined ||+ reason === null ||+ reason === 'connection-timeout' ||+ reason === 'connection-failed' ||+ reason === 'permission-required')+ );+ }+ if (message.kind === 'log') {+ return (+ (message.level === 'debug' ||+ message.level === 'info' ||+ message.level === 'warn' ||+ message.level === 'error') &&+ typeof message.message === 'string'+ );+ }+ return false;+}++function isWorkLouderCodexDeviceState(value: unknown): value is WorkLouderCodexDeviceState {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const device = value as WorkLouderCodexDeviceState;+ return (+ (device.deviceType === null ||+ device.deviceType === 'codex-micro' ||+ device.deviceType === 'creator-micro-2') &&+ (device.isUsbConnection === null || typeof device.isUsbConnection === 'boolean') &&+ (device.firmwareVersion === null || typeof device.firmwareVersion === 'string') &&+ (device.batteryPercentage === null ||+ (typeof device.batteryPercentage === 'number' &&+ Number.isFinite(device.batteryPercentage) &&+ device.batteryPercentage >= 0 &&+ device.batteryPercentage <= 100)) &&+ (device.isCharging === null || typeof device.isCharging === 'boolean') &&+ (device.inputMonitoringPermission === 'granted' ||+ device.inputMonitoringPermission === 'denied' ||+ device.inputMonitoringPermission === 'unknown' ||+ device.inputMonitoringPermission === 'not-required')+ );+}++function isLightingVisibleActivity(activity: AgentIslandSessionActivity): boolean {+ return (+ activity.phase === 'running' ||+ activity.phase === 'needs-interaction' ||+ activity.attention === true+ );+}++function ambientForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouderLightingSide {+ switch (phase) {+ case 'running':+ return side(WorkLouderLightingEffect.Snake, 0.7, 0.4, COLORS.running);+ case 'needs-interaction':+ return side(WorkLouderLightingEffect.Breath, 0.95, 0.35, COLORS['needs-interaction']);+ case 'completed':+ return side(WorkLouderLightingEffect.Solid, 0.7, 0, COLORS.completed);+ case 'error':+ return side(WorkLouderLightingEffect.Breath, 1, 0.45, COLORS.error);+ }+}++function keysForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouderLightingSide {+ const effect =+ phase === 'error' ? WorkLouderLightingEffect.Breath : WorkLouderLightingEffect.Solid;+ const brightness = phase === 'needs-interaction' || phase === 'error' ? 0.28 : 0.16;+ return side(effect, brightness, phase === 'error' ? 0.45 : 0, COLORS[phase]);+}++function threadForActivity(+ id: number,+ activity: AgentIslandSessionActivity | undefined,+): WorkLouderThreadLighting {+ if (!activity) {+ return {+ id,+ color: 0,+ brightness: 0,+ effect: WorkLouderLightingEffect.Off,+ speed: 0,+ syncKeysLighting: false,+ syncAmbientLighting: false,+ };+ }+ const animated =+ activity.phase === 'running' ||+ activity.phase === 'needs-interaction' ||+ activity.phase === 'error';+ return {+ id,+ color: COLORS[activity.phase],+ brightness: 0.8,+ effect: animated ? WorkLouderLightingEffect.Breath : WorkLouderLightingEffect.Solid,+ speed: animated ? 0.35 : 0,+ syncKeysLighting: false,+ syncAmbientLighting: false,+ };+}++function side(+ effect: WorkLouderLightingEffect,+ brightness: number,+ speed: number,+ color: number,+): WorkLouderLightingSide {+ return { effect, brightness, speed, magic: 0, color };+}diff --git a/apps/desktop/src/main/worklouder-codex/settingsIpc.ts b/apps/desktop/src/main/worklouder-codex/settingsIpc.tsnew file mode 100644index 0000000000..72c028e87c--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/settingsIpc.ts@@ -0,0 +1,359 @@+/** Testable business logic behind the Work Louder Codex Micro settings IPC. */++import {+ WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS,+ WORKLOUDER_CODEX_COMMAND_SLOTS,+ WORKLOUDER_CODEX_ENCODER_ACTIONS,+ isWorkLouderCodexAgentSource,+ normalizeWorkLouderCodexAgentSource,+ isWorkLouderCodexAutoDim,+ isWorkLouderCodexCommandId,+ isWorkLouderCodexEncoderMode,+ isWorkLouderCodexKeycapId,+ type WorkLouderCodexAction,+ type WorkLouderCodexLayout,+ type WorkLouderCodexSettings,+ type WorkLouderCodexSettingsPatch,+ type WorkLouderCodexPublishedTask,+ type WorkLouderCodexState,+} from '../../shared/workLouderCodex.js';+import { WORKLOUDER_CODEX_TASK_OPTION_LIMIT } from './taskSlots.js';+import { throwIpcError } from '../utils/ipcValidate.js';++const SETTING_KEYS = [+ 'lightingBrightness',+ 'lightingAutoDim',+ 'agentSource',+ 'customAgentKeys',+ 'singleTapAgentKeys',+ 'layout',+] as const;++export interface WorkLouderCodexSettingsIpcDeps {+ assertTrustedSender(event: unknown): void;+ getState(): WorkLouderCodexState;+ writeSettings(patch: WorkLouderCodexSettingsPatch): WorkLouderCodexSettings;+ resetSettings(): WorkLouderCodexSettings;+ applySettings(settings: WorkLouderCodexSettings): void;+ openInputMonitoringSettings(): Promise<void>;+ probeDevice(): void;+ publishTasks(tasks: readonly WorkLouderCodexPublishedTask[]): void;+ setLayoutPreviewActive(active: boolean): void;+}++function parseSettingsPatch(value: unknown): WorkLouderCodexSettingsPatch {+ const record = requireRecord(value, 'Work Louder Codex settings patch required');+ rejectUnknownKeys(record, SETTING_KEYS, 'Work Louder Codex setting');+ if (Object.keys(record).length === 0) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex settings patch cannot be empty');+ }++ const patch: WorkLouderCodexSettingsPatch = {};+ if ('lightingBrightness' in record) {+ const brightness = record.lightingBrightness;+ if (+ typeof brightness !== 'number' ||+ !Number.isInteger(brightness) ||+ brightness < 0 ||+ brightness > 100+ ) {+ throwIpcError('INVALID_PARAMS', 'lightingBrightness must be an integer from 0 to 100');+ }+ patch.lightingBrightness = brightness;+ }+ if ('lightingAutoDim' in record) {+ if (!isWorkLouderCodexAutoDim(record.lightingAutoDim)) {+ throwIpcError('INVALID_PARAMS', 'lightingAutoDim is invalid');+ }+ patch.lightingAutoDim = record.lightingAutoDim;+ }+ if ('agentSource' in record) {+ if (+ record.agentSource !== 'recent' &&+ record.agentSource !== 'pinned' &&+ !isWorkLouderCodexAgentSource(record.agentSource)+ ) {+ throwIpcError('INVALID_PARAMS', 'agentSource is invalid');+ }+ patch.agentSource = normalizeWorkLouderCodexAgentSource(record.agentSource);+ }+ if ('customAgentKeys' in record) {+ if (+ !Array.isArray(record.customAgentKeys) ||+ record.customAgentKeys.length !== WORKLOUDER_CODEX_AGENT_SLOT_COUNT+ ) {+ throwIpcError('INVALID_PARAMS', 'customAgentKeys must contain six assignments');+ }+ patch.customAgentKeys = record.customAgentKeys.map((action) => parseAction(action, true));+ }+ if ('singleTapAgentKeys' in record) {+ if (typeof record.singleTapAgentKeys !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'singleTapAgentKeys must be a boolean');+ }+ patch.singleTapAgentKeys = record.singleTapAgentKeys;+ }+ if ('layout' in record) patch.layout = parseLayout(record.layout);+ return patch;+}++function parseLayout(value: unknown): WorkLouderCodexLayout {+ const record = requireRecord(value, 'layout must be an object');+ rejectUnknownKeys(+ record,+ [+ 'version',+ 'slots',+ 'analogStick',+ 'encoder',+ 'encoderMode',+ // `voiceButtonMode` was dropped: the microphone key follows Cindy's own+ // microphone and has no mode. Still accepted so a settings object saved+ // by an older build round-trips instead of being rejected outright.+ 'voiceButtonMode',+ 'separateMicrophoneKeys',+ ],+ 'layout field',+ );+ if (record.version !== 1) throwIpcError('INVALID_PARAMS', 'layout version must be 1');+ const slotsRecord = requireRecord(record.slots, 'layout slots must be an object');+ rejectUnknownKeys(slotsRecord, WORKLOUDER_CODEX_COMMAND_SLOTS, 'layout slot');+ const slots = Object.fromEntries(+ WORKLOUDER_CODEX_COMMAND_SLOTS.map((slot) => {+ const assignment = requireRecord(slotsRecord[slot], `${slot} assignment is required`);+ rejectUnknownKeys(assignment, ['keycapId', 'action'], `${slot} assignment field`);+ if (!isWorkLouderCodexKeycapId(assignment.keycapId)) {+ throwIpcError('INVALID_PARAMS', `${slot} keycapId is invalid`);+ }+ return [+ slot,+ { keycapId: assignment.keycapId, action: parseAction(assignment.action ?? null, true) },+ ];+ }),+ ) as WorkLouderCodexLayout['slots'];++ const analogRecord = requireRecord(record.analogStick, 'analogStick must be an object');+ rejectUnknownKeys(analogRecord, WORKLOUDER_CODEX_ANALOG_DIRECTIONS, 'analogStick direction');+ const analogStick = Object.fromEntries(+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS.map((direction) => [+ direction,+ parseAction(analogRecord[direction] ?? null, true),+ ]),+ ) as WorkLouderCodexLayout['analogStick'];++ const encoderRecord = requireRecord(record.encoder, 'encoder must be an object');+ rejectUnknownKeys(encoderRecord, WORKLOUDER_CODEX_ENCODER_ACTIONS, 'encoder action');+ const encoder = Object.fromEntries(+ WORKLOUDER_CODEX_ENCODER_ACTIONS.map((action) => [+ action,+ parseAction(encoderRecord[action] ?? null, true),+ ]),+ ) as WorkLouderCodexLayout['encoder'];++ if (!isWorkLouderCodexEncoderMode(record.encoderMode)) {+ throwIpcError('INVALID_PARAMS', 'encoderMode is invalid');+ }+ if (typeof record.separateMicrophoneKeys !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'separateMicrophoneKeys must be a boolean');+ }+ return {+ version: 1,+ slots,+ analogStick,+ encoder,+ encoderMode: record.encoderMode,+ separateMicrophoneKeys: record.separateMicrophoneKeys,+ };+}++function parseAction(value: unknown, nullable: true): WorkLouderCodexAction | null;+function parseAction(value: unknown, nullable: false): WorkLouderCodexAction;+function parseAction(value: unknown, nullable: boolean): WorkLouderCodexAction | null {+ if (value === null && nullable) return null;+ const record = requireRecord(value, 'device action must be an object');+ if (record.type === 'command') {+ rejectUnknownKeys(record, ['type', 'commandId'], 'command action field');+ if (!isWorkLouderCodexCommandId(record.commandId)) {+ throwIpcError('INVALID_PARAMS', 'command action is invalid');+ }+ return { type: 'command', commandId: record.commandId };+ }+ if (record.type === 'task') {+ rejectUnknownKeys(record, ['type', 'sessionId'], 'task action field');+ return { type: 'task', sessionId: requireBoundedString(record.sessionId, 512, 'sessionId') };+ }+ if (record.type === 'keycap') {+ rejectUnknownKeys(record, ['type', 'keycapId'], 'keycap action field');+ if (!isWorkLouderCodexKeycapId(record.keycapId)) {+ throwIpcError('INVALID_PARAMS', 'keycap action is invalid');+ }+ return { type: 'keycap', keycapId: record.keycapId };+ }+ if (record.type === 'skill') {+ rejectUnknownKeys(record, ['type', 'skillId', 'name'], 'skill action field');+ return {+ type: 'skill',+ skillId: requireBoundedString(record.skillId, 1_024, 'skillId'),+ name: requireBoundedString(record.name, 256, 'skill name'),+ };+ }+ if (record.type === 'composer-text') {+ rejectUnknownKeys(record, ['type', 'text'], 'composer text action field');+ return {+ type: 'composer-text',+ text: requireBoundedString(record.text, 2_000, 'composer text'),+ };+ }+ if (record.type === 'external-url') {+ rejectUnknownKeys(record, ['type', 'url'], 'external URL action field');+ const url = requireBoundedString(record.url, 2_048, 'external URL');+ try {+ const parsed = new URL(url);+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') throw new Error('scheme');+ } catch {+ throwIpcError('INVALID_PARAMS', 'external URL must use http or https');+ }+ return { type: 'external-url', url };+ }+ throwIpcError('INVALID_PARAMS', 'device action type is invalid');+}++export function createWorkLouderCodexSettingsIpc(deps: WorkLouderCodexSettingsIpcDeps) {+ return {+ get(event: unknown): WorkLouderCodexState {+ deps.assertTrustedSender(event);+ return deps.getState();+ },++ set(event: unknown, value: unknown): WorkLouderCodexState {+ deps.assertTrustedSender(event);+ const patch = parseSettingsPatch(value);+ let settings: WorkLouderCodexSettings;+ try {+ settings = deps.writeSettings(patch);+ } catch {+ throwIpcError('INTERNAL', 'Work Louder Codex settings write failed');+ }+ deps.applySettings(settings);+ return deps.getState();+ },++ reset(event: unknown): WorkLouderCodexState {+ deps.assertTrustedSender(event);+ let settings: WorkLouderCodexSettings;+ try {+ settings = deps.resetSettings();+ } catch {+ throwIpcError('INTERNAL', 'Work Louder Codex settings reset failed');+ }+ deps.applySettings(settings);+ return deps.getState();+ },++ async openInputMonitoringSettings(event: unknown): Promise<void> {+ deps.assertTrustedSender(event);+ await deps.openInputMonitoringSettings();+ },++ /**+ * Re-check whether the device is still attached, and return the state that+ * results. Fire-and-forget at the host layer, so the caller polls this to+ * notice an unplug rather than waiting for a push that never comes.+ */+ probe(event: unknown): WorkLouderCodexState {+ deps.assertTrustedSender(event);+ deps.probeDevice();+ return deps.getState();+ },++ /**+ * Take the sidebar's task list for the agent keys. The renderer is the only+ * side that sees tasks on linked machines, and the only side that knows+ * which machine filter is applied.+ */+ publishTasks(event: unknown, value: unknown): void {+ deps.assertTrustedSender(event);+ if (!Array.isArray(value)) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task list must be an array');+ }+ if (value.length > WORKLOUDER_CODEX_TASK_OPTION_LIMIT) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task list is too long');+ }+ const tasks: WorkLouderCodexPublishedTask[] = value.map((item) => {+ const row = requireRecord(item, 'Work Louder Codex task must be an object');+ if (typeof row.id !== 'string' || row.id.length === 0 || row.id.length > 256) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task id is invalid');+ }+ if (row.title !== null && typeof row.title !== 'string') {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task title is invalid');+ }+ if (typeof row.title === 'string' && row.title.length > 512) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task title is too long');+ }+ if (+ row.pinnedAt !== null &&+ (typeof row.pinnedAt !== 'number' || !Number.isFinite(row.pinnedAt))+ ) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task pinnedAt is invalid');+ }+ if (+ row.userSendAt !== null &&+ row.userSendAt !== undefined &&+ (typeof row.userSendAt !== 'number' || !Number.isFinite(row.userSendAt))+ ) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task userSendAt is invalid');+ }+ if (+ row.sidebarOrder !== undefined &&+ (typeof row.sidebarOrder !== 'number' ||+ !Number.isInteger(row.sidebarOrder) ||+ row.sidebarOrder < 0)+ ) {+ throwIpcError('INVALID_PARAMS', 'Work Louder Codex task sidebarOrder is invalid');+ }+ return {+ id: row.id,+ title: typeof row.title === 'string' ? row.title : null,+ pinnedAt: typeof row.pinnedAt === 'number' ? row.pinnedAt : null,+ userSendAt: typeof row.userSendAt === 'number' ? row.userSendAt : null,+ ...(typeof row.sidebarOrder === 'number' ? { sidebarOrder: row.sidebarOrder } : {}),+ ...(row.catalogEligible === false ? { catalogEligible: false } : {}),+ };+ });+ deps.publishTasks(tasks);+ },++ setLayoutPreviewActive(event: unknown, value: unknown): void {+ deps.assertTrustedSender(event);+ if (typeof value !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'layout preview flag must be a boolean');+ }+ deps.setLayoutPreviewActive(value);+ },+ };+}++function requireRecord(value: unknown, message: string): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throwIpcError('INVALID_PARAMS', message);+ }+ return value as Record<string, unknown>;+}++function rejectUnknownKeys(+ value: Record<string, unknown>,+ allowed: readonly string[],+ label: string,+): void {+ const unknown = Object.keys(value).find((key) => !allowed.includes(key));+ if (unknown) throwIpcError('INVALID_PARAMS', `unknown ${label}: ${unknown}`);+}++function requireBoundedString(value: unknown, max: number, label: string): string {+ if (typeof value !== 'string' || value.length === 0 || value.length > max) {+ throwIpcError('INVALID_PARAMS', `${label} is invalid`);+ }+ return value;+}++export const __testing = { parseSettingsPatch, parseLayout, parseAction };diff --git a/apps/desktop/src/main/worklouder-codex/settingsStore.ts b/apps/desktop/src/main/worklouder-codex/settingsStore.tsnew file mode 100644index 0000000000..b65298243b--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/settingsStore.ts@@ -0,0 +1,194 @@+/** Main-process persistence for Work Louder Codex Micro device preferences. */++import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';++import {+ WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS,+ WORKLOUDER_CODEX_COMMAND_SLOTS,+ WORKLOUDER_CODEX_DEFAULT_LAYOUT,+ createWorkLouderCodexDefaultSettings,+ normalizeWorkLouderCodexAgentSource,+ isWorkLouderCodexAutoDim,+ isWorkLouderCodexCommandId,+ isWorkLouderCodexEncoderMode,+ isWorkLouderCodexKeycapId,+ type WorkLouderCodexAction,+ type WorkLouderCodexKeyAssignment,+ type WorkLouderCodexLayout,+ type WorkLouderCodexSettings,+ type WorkLouderCodexSettingsPatch,+} from '../../shared/workLouderCodex.js';+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';++const log = desktopMakerLogger.child('worklouder-codex-settings-store');+const MAX_SETTINGS_BYTES = 64 * 1024;++function settingsFilePath(): string {+ return ownerScopedUserDataPath('worklouder-codex-settings.json');+}++function normalizeAction(raw: unknown): WorkLouderCodexAction | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const value = raw as Record<string, unknown>;+ if (value.type === 'command' && isWorkLouderCodexCommandId(value.commandId)) {+ return { type: 'command', commandId: value.commandId };+ }+ if (value.type === 'task' && isBoundedString(value.sessionId, 512)) {+ return { type: 'task', sessionId: value.sessionId };+ }+ if (value.type === 'keycap' && isWorkLouderCodexKeycapId(value.keycapId)) {+ return { type: 'keycap', keycapId: value.keycapId };+ }+ if (+ value.type === 'skill' &&+ isBoundedString(value.skillId, 1_024) &&+ isBoundedString(value.name, 256)+ ) {+ return { type: 'skill', skillId: value.skillId, name: value.name };+ }+ if (value.type === 'composer-text' && isBoundedString(value.text, 2_000)) {+ return { type: 'composer-text', text: value.text };+ }+ if (value.type === 'external-url' && isSafeExternalUrl(value.url)) {+ return { type: 'external-url', url: value.url };+ }+ return null;+}++function normalizeKeyAssignment(+ raw: unknown,+ fallback: WorkLouderCodexKeyAssignment,+): WorkLouderCodexKeyAssignment {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ...fallback };+ const value = raw as Record<string, unknown>;+ return {+ keycapId: isWorkLouderCodexKeycapId(value.keycapId) ? value.keycapId : fallback.keycapId,+ action: value.action === null ? null : normalizeAction(value.action),+ };+}++function normalizeLayout(raw: unknown): WorkLouderCodexLayout {+ const value =+ raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};+ const rawSlots = asRecord(value.slots);+ const rawAnalog = asRecord(value.analogStick);+ const rawEncoder = asRecord(value.encoder);+ const slots = Object.fromEntries(+ WORKLOUDER_CODEX_COMMAND_SLOTS.map((slot) => [+ slot,+ normalizeKeyAssignment(rawSlots[slot], WORKLOUDER_CODEX_DEFAULT_LAYOUT.slots[slot]),+ ]),+ ) as WorkLouderCodexLayout['slots'];+ const analogStick = Object.fromEntries(+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS.map((direction) => [+ direction,+ rawAnalog[direction] === null+ ? null+ : (normalizeAction(rawAnalog[direction]) ??+ WORKLOUDER_CODEX_DEFAULT_LAYOUT.analogStick[direction]),+ ]),+ ) as WorkLouderCodexLayout['analogStick'];+ const encoder = Object.fromEntries(+ (['left', 'right', 'click', 'longPress'] as const).map((action) => [+ action,+ rawEncoder[action] === null ? null : normalizeAction(rawEncoder[action]),+ ]),+ ) as WorkLouderCodexLayout['encoder'];+ return {+ version: 1,+ slots,+ analogStick,+ encoder,+ encoderMode: isWorkLouderCodexEncoderMode(value.encoderMode)+ ? value.encoderMode+ : WORKLOUDER_CODEX_DEFAULT_LAYOUT.encoderMode,+ separateMicrophoneKeys:+ typeof value.separateMicrophoneKeys === 'boolean'+ ? value.separateMicrophoneKeys+ : WORKLOUDER_CODEX_DEFAULT_LAYOUT.separateMicrophoneKeys,+ };+}++function normalize(raw: unknown): WorkLouderCodexSettings {+ const defaults = createWorkLouderCodexDefaultSettings();+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return defaults;+ const value = raw as Record<string, unknown>;+ const brightness = value.lightingBrightness;+ const rawCustomAgentKeys = Array.isArray(value.customAgentKeys) ? value.customAgentKeys : null;+ const customAgentKeys = rawCustomAgentKeys+ ? Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, (_, index) =>+ rawCustomAgentKeys[index] === null ? null : normalizeAction(rawCustomAgentKeys[index]),+ )+ : defaults.customAgentKeys;+ return {+ lightingBrightness:+ typeof brightness === 'number' && Number.isFinite(brightness)+ ? Math.max(0, Math.min(100, Math.round(brightness)))+ : defaults.lightingBrightness,+ lightingAutoDim: isWorkLouderCodexAutoDim(value.lightingAutoDim)+ ? value.lightingAutoDim+ : defaults.lightingAutoDim,+ agentSource: normalizeWorkLouderCodexAgentSource(value.agentSource),+ customAgentKeys,+ singleTapAgentKeys:+ typeof value.singleTapAgentKeys === 'boolean'+ ? value.singleTapAgentKeys+ : defaults.singleTapAgentKeys,+ layout: normalizeLayout(value.layout),+ };+}++const store = createOverrideSettingsFile<WorkLouderCodexSettings>({+ filePath: settingsFilePath,+ defaults: createWorkLouderCodexDefaultSettings(),+ normalize,+ log,+ label: 'worklouder-codex',+ scopeKey: activeOwnerScopeKey,+ maxBytes: MAX_SETTINGS_BYTES,+ preserveUnreadableFile: true,+ logLoadedValue: false,+ logReadErrorDetails: false,+});++export function readWorkLouderCodexSettings(): WorkLouderCodexSettings {+ return store.read();+}++export function writeWorkLouderCodexSettingsPatch(+ patch: WorkLouderCodexSettingsPatch,+): WorkLouderCodexSettings {+ store.writePatch(patch);+ log.info('Work Louder Codex settings written', { keys: Object.keys(patch) });+ return store.read();+}++export function resetWorkLouderCodexSettings(): WorkLouderCodexSettings {+ const settings = store.reset();+ log.info('Work Louder Codex settings reset');+ return settings;+}++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function isBoundedString(value: unknown, maxLength: number): value is string {+ return typeof value === 'string' && value.length > 0 && value.length <= maxLength;+}++function isSafeExternalUrl(value: unknown): value is string {+ if (!isBoundedString(value, 2_048)) return false;+ try {+ const parsed = new URL(value);+ return parsed.protocol === 'https:' || parsed.protocol === 'http:';+ } catch {+ return false;+ }+}++export const __testing = { normalize, normalizeAction, normalizeLayout };diff --git a/apps/desktop/src/main/worklouder-codex/taskSlots.ts b/apps/desktop/src/main/worklouder-codex/taskSlots.tsnew file mode 100644index 0000000000..7743552121--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/taskSlots.ts@@ -0,0 +1,142 @@+import { and, desc, eq, inArray, isNull, ne, or, sql } from 'drizzle-orm';++import type { DbClient } from '../localDb/client/DbClient.js';+import { getDbClient } from '../localDb/client/current.js';+import { sessions } from '../localDb/schema.js';+import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';+import {+ WORKLOUDER_CODEX_AGENT_SLOT_COUNT,+ type WorkLouderCodexTaskOption,+} from '../../shared/workLouderCodex.js';++export const WORKLOUDER_CODEX_TASK_OPTION_LIMIT = 100;+const TASK_OPTION_LIMIT = WORKLOUDER_CODEX_TASK_OPTION_LIMIT;++export interface WorkLouderCodexTaskSlotRow {+ id: string;+}++interface WorkLouderCodexTaskCatalogRow extends WorkLouderCodexTaskOption {+ pinnedAt: number | null;+ userSendAt: number | null;+}++export interface WorkLouderCodexTaskCatalog {+ sidebar: WorkLouderCodexTaskOption[];+ lastSent: WorkLouderCodexTaskOption[];+ options: WorkLouderCodexTaskOption[];+}++/** Keeps database recency order unchanged and caps the keyboard projection at six tasks. */+export function selectWorkLouderCodexRecentTaskSlots(+ rows: readonly WorkLouderCodexTaskSlotRow[],+): string[] {+ return rows.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT).map((row) => row.id);+}++/** Reads the active task catalog used by recent, pinned, priority, and custom modes. */+export async function listWorkLouderCodexTaskCatalog(+ db: DbClient['drizzle'] = getDbClient().drizzle,+): Promise<WorkLouderCodexTaskCatalog> {+ const visibleActiveTask = and(+ eq(sessions.status, 'active'),+ inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES),+ or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker')),+ );+ const rows = await db+ .select({+ id: sessions.id,+ title: sessions.title,+ pinnedAt: sessions.pinnedAt,+ userSendAt: sessions.userSendAt,+ })+ .from(sessions)+ .where(visibleActiveTask)+ .orderBy(desc(sql`COALESCE(${sessions.userSendAt}, ${sessions.updatedAt})`), desc(sessions.id))+ .limit(TASK_OPTION_LIMIT);++ return buildWorkLouderCodexTaskCatalog(+ rows.map((row) => ({+ id: row.id,+ title: row.title,+ pinnedAt: row.pinnedAt,+ userSendAt: row.userSendAt,+ })),+ );+}++/** One task as the keyboard needs to see it, already in display order. */+export interface WorkLouderCodexTaskCatalogInput {+ id: string;+ title: string | null;+ pinnedAt: number | null;+ userSendAt: number | null;+ sidebarOrder?: number;+ catalogEligible?: boolean;+}++/**+ * Shape an ordered task list into the catalog the keyboard projects from.+ *+ * Split out from the database query because the rows can also come from the+ * renderer: tasks on a linked machine live only in its store, so reading the+ * local table alone leaves the agent keys empty on a machine that is driving+ * someone else's sessions.+ */+export function buildWorkLouderCodexTaskCatalog(+ rows: readonly WorkLouderCodexTaskCatalogInput[],+ options: { publishedVisibleOrder?: boolean } = {},+): WorkLouderCodexTaskCatalog {+ const publishedRows: WorkLouderCodexTaskCatalogRow[] = rows.slice(0, TASK_OPTION_LIMIT).map((row) => ({+ id: row.id,+ // An untitled task still gets a key; the UI supplies its own placeholder.+ title: row.title,+ pinned: row.pinnedAt !== null,+ pinnedAt: row.pinnedAt,+ userSendAt: row.userSendAt,+ }));+ const catalogRows = publishedRows.filter((_, index) => rows[index]?.catalogEligible !== false);+ const byPublishedId = new Map(publishedRows.map((row) => [row.id, row] as const));+ const visibleOrder = rows+ .filter((row) => row.sidebarOrder !== undefined)+ .toSorted((left, right) => (left.sidebarOrder ?? 0) - (right.sidebarOrder ?? 0));+ // Local database rows have no sidebarOrder. A renderer publication does:+ // even an empty visible list must stay empty, otherwise a machine filter+ // or sidebar search would light keys for tasks the user cannot see.+ const publishedVisibleRows = visibleOrder.flatMap((item) => {+ const row = byPublishedId.get(item.id);+ return row ? [row] : [];+ });+ const sidebarSource =+ options.publishedVisibleOrder || visibleOrder.length > 0 ? publishedVisibleRows : catalogRows;+ const sidebar = sidebarSource.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT).map(toTaskOption);+ const lastSent = sortLastSentRows(catalogRows)+ .slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT)+ .map(toTaskOption);+ return {+ sidebar,+ lastSent,+ options: catalogRows.map(toTaskOption),+ };+}++/** Backward-compatible recent-slot reader used by older controller tests. */+export async function listWorkLouderCodexTaskSlots(+ db: DbClient['drizzle'] = getDbClient().drizzle,+): Promise<string[]> {+ const catalog = await listWorkLouderCodexTaskCatalog(db);+ return catalog.sidebar.map((task) => task.id);+}++function sortLastSentRows(rows: WorkLouderCodexTaskCatalogRow[]): WorkLouderCodexTaskCatalogRow[] {+ return rows.toSorted((left, right) => {+ const leftSent = left.userSendAt ?? 0;+ const rightSent = right.userSendAt ?? 0;+ if (rightSent !== leftSent) return rightSent - leftSent;+ return right.id.localeCompare(left.id);+ });+}++function toTaskOption(row: WorkLouderCodexTaskCatalogRow): WorkLouderCodexTaskOption {+ return { id: row.id, title: row.title, pinned: row.pinned };+}diff --git a/apps/desktop/src/main/worklouder-codex/windowReveal.ts b/apps/desktop/src/main/worklouder-codex/windowReveal.tsnew file mode 100644index 0000000000..feef5503e4--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/windowReveal.ts@@ -0,0 +1,28 @@+/**+ * Decides when a Cindy window becoming visible should flash the keyboard.+ *+ * Any transition from hidden/minimized to visible counts, including the+ * first appearance after create. Focus changes while the window stays on+ * screen do not.+ */+export interface WorkLouderCodexWindowRevealGate {+ wasHidden: boolean;+}++export function createWorkLouderCodexWindowRevealGate(): WorkLouderCodexWindowRevealGate {+ return { wasHidden: true };+}++/** True when the window just became visible after having been hidden. */+export function noteWorkLouderCodexWindowVisibility(+ gate: WorkLouderCodexWindowRevealGate,+ nowVisible: boolean,+): boolean {+ if (!nowVisible) {+ gate.wasHidden = true;+ return false;+ }+ const play = gate.wasHidden;+ gate.wasHidden = false;+ return play;+}diff --git a/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.tsnew file mode 100644index 0000000000..6aa5e5254b--- /dev/null+++ b/apps/desktop/src/main/worklouder-codex/workLouderCodexHostProcess.ts@@ -0,0 +1,511 @@+/**+ * Isolated utility-process host for the optional Work Louder Codex Micro SDK.+ * The package is loaded only from a path resolved by Electron main; Cindy does+ * not bundle or copy the proprietary SDK.+ */++import { createRequire } from 'node:module';++import {+ createWorkLouderCodexOffFrame,+ isWorkLouderCodexLightingFrameOff,+ parseWorkLouderCodexHidEvent,+ parseWorkLouderCodexJoystickEvent,+ type WorkLouderCodexHostMessage,+ type WorkLouderCodexHostRequest,+ type WorkLouderCodexLightingFrame,+} from './protocol.js';++interface ParentPortLike {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}++interface WorkLouderDevice {+ isUsbConnection?: boolean;+}++interface WorkLouderDeviceStatus {+ firmwareVersion?: string;+ batteryPercentage?: number;+ isCharging?: boolean;+}++interface WorkLouderComm {+ connect(device: WorkLouderDevice): Promise<boolean>;+ disconnect(): Promise<void>;+}++interface WorkLouderApi {+ sendLightingConfig(+ config: Pick<WorkLouderCodexLightingFrame, 'ambient' | 'keys'>,+ ): Promise<boolean>;+ sendThreadsLighting(threads: WorkLouderCodexLightingFrame['threads']): Promise<boolean>;+ onHidReceived?(listener: (event: unknown) => void): (() => void) | void;+ onJoystickMove?(listener: (event: unknown) => void): (() => void) | void;+ getDeviceStatus?(): Promise<WorkLouderDeviceStatus>;+}++interface WorkLouderSdk {+ DeviceType: { CodexMicro: unknown; CreatorMicroV2?: unknown };+ WLDeviceDiscovery: new (logger?: WorkLouderLogger) => {+ findWLDevices(filter?: unknown[]): WorkLouderDevice[];+ };+ WLDeviceCommImpl: new (logger?: WorkLouderLogger) => WorkLouderComm;+ RPCApiOAI: new (comm: WorkLouderComm, logger?: WorkLouderLogger) => WorkLouderApi;+}++interface WorkLouderLogger {+ debug(...args: unknown[]): void;+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ error(...args: unknown[]): void;+}++const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;+const requireFromHost = createRequire(__filename);+const RETRY_MS = 3_000;++let sdk: WorkLouderSdk | null = null;+let sdkEntry: string | null = null;+let comm: WorkLouderComm | null = null;+let api: WorkLouderApi | null = null;+let unsubscribeHid: (() => void) | null = null;+let unsubscribeJoystick: (() => void) | null = null;+let latestFrame: WorkLouderCodexLightingFrame | null = null;+let applyPending = false;+let listenPending = false;+let probePending = false;+let hidListeningRequested = false;+let applying = false;+let applyTask: Promise<void> | null = null;+let stopping = false;+let retryTimer: ReturnType<typeof setTimeout> | null = null;+let lastLoggedError: string | null = null;+let lastActivityPostedAt = 0;+/** The native SDK often logs a dead USB/BT handle instead of throwing. */+let transportFaulted = false;+/** Which device the current `api` handle belongs to, so probes can refresh it. */+let connectedDevice: { deviceType: 'codex-micro' | 'creator-micro-2'; isUsb: boolean } | null =+ null;++if (parentPort) {+ parentPort.on('message', (event) => {+ const request = event.data as WorkLouderCodexHostRequest;+ if (request?.kind === 'init') {+ sdkEntry = request.sdkEntry;+ } else if (request?.kind === 'listen') {+ hidListeningRequested = true;+ requestListen();+ } else if (request?.kind === 'apply') {+ latestFrame = request.frame;+ requestApply();+ } else if (request?.kind === 'probe') {+ requestProbe();+ } else if (request?.kind === 'stop') {+ void stop();+ }+ });+}++function post(message: WorkLouderCodexHostMessage): void {+ parentPort?.postMessage(message);+}++function hostLog(level: 'debug' | 'info' | 'warn' | 'error', message: string): void {+ post({ kind: 'log', level, message });+}++const sdkLogger: WorkLouderLogger = {+ debug: () => undefined,+ info: () => undefined,+ warn: (...args) => hostLog('warn', `Work Louder SDK reported a warning${formatSdkLog(args)}`),+ error: (...args) => {+ transportFaulted = true;+ hostLog('error', `Work Louder SDK reported an error${formatSdkLog(args)}`);+ if (api && !stopping && !probePending && !applying) requestProbe();+ },+};++function loadSdk(): WorkLouderSdk {+ if (sdk) return sdk;+ if (!sdkEntry) throw new Error('Work Louder SDK entry is missing');+ const loaded = requireFromHost(sdkEntry) as Partial<WorkLouderSdk>;+ if (+ !loaded.DeviceType ||+ typeof loaded.WLDeviceDiscovery !== 'function' ||+ typeof loaded.WLDeviceCommImpl !== 'function' ||+ typeof loaded.RPCApiOAI !== 'function'+ ) {+ throw new Error('Work Louder SDK exports are incompatible');+ }+ sdk = loaded as WorkLouderSdk;+ return sdk;+}++function requestApply(): void {+ if (stopping) return;+ applyPending = true;+ kickQueue();+}++function requestListen(): void {+ if (stopping) return;+ listenPending = true;+ kickQueue();+}++function requestProbe(): void {+ if (stopping) return;+ probePending = true;+ kickQueue();+}++function kickQueue(): void {+ if (applying) return;+ const task = drainApplyQueue();+ applyTask = task;+ const clearApplyTask = () => {+ if (applyTask === task) applyTask = null;+ };+ void task.then(clearApplyTask, clearApplyTask);+}++async function drainApplyQueue(): Promise<void> {+ applying = true;+ try {+ while ((applyPending || listenPending || probePending) && !stopping) {+ // Drop a stale handle before lighting or HID reuse it.+ if (probePending) {+ probePending = false;+ await probeConnection();+ }+ if (listenPending) {+ listenPending = false;+ await listenForAgentKeys();+ }+ if (applyPending) {+ applyPending = false;+ const frame = latestFrame;+ if (frame) await applyFrame(frame);+ }+ }+ } finally {+ applying = false;+ }+}++async function applyFrame(frame: WorkLouderCodexLightingFrame): Promise<void> {+ if (!api && isWorkLouderCodexLightingFrameOff(frame) && !hidListeningRequested) {+ clearRetry();+ return;+ }+ try {+ const deviceApi = await ensureConnected();+ if (!deviceApi) {+ post({ kind: 'state', status: 'not-detected' });+ scheduleRetry();+ return;+ }+ const lightingOk = await deviceApi.sendLightingConfig({+ ambient: frame.ambient,+ keys: frame.keys,+ });+ const threadsOk = await deviceApi.sendThreadsLighting(frame.threads);+ if (!lightingOk || !threadsOk || transportFaulted) {+ throw new Error(transportFaulted ? 'lighting transport faulted' : 'lighting RPC returned false');+ }+ clearRetry();+ lastLoggedError = null;+ post({ kind: 'state', status: 'connected' });+ } catch (error) {+ const message = safeErrorMessage(error);+ if (message !== lastLoggedError) {+ lastLoggedError = message;+ hostLog('error', `lighting apply failed: ${message}`);+ }+ await disconnect();+ post({ kind: 'state', status: 'error', reason: classifyConnectionError(message) });+ scheduleRetry();+ }+}++/**+ * Check the device is still physically there.+ *+ * Nothing in the SDK reports a disconnect, and a cached `api` handle keeps+ * looking valid after the cable is pulled — so the only way to find out is to+ * ask the device something and see whether it answers. `getDeviceStatus` is+ * that question: it is the cheapest round trip that reaches the hardware, and+ * its answer doubles as fresh battery and firmware values.+ *+ * Callers drive the cadence. This runs only while something is actually+ * showing connection state, so an idle app is not waking the device on a timer.+ */+async function probeConnection(): Promise<void> {+ if (stopping) return;+ if (api) {+ const faulted = transportFaulted;+ if (typeof api.getDeviceStatus === 'function' && !faulted) {+ try {+ // Call it directly rather than through postDeviceStatus, which swallows+ // failures — swallowing here would make every probe "succeed" and defeat+ // the whole point. Same round trip also keeps battery and firmware fresh.+ const status = await api.getDeviceStatus();+ if (!transportFaulted) {+ const device = connectedDevice;+ if (device) postDeviceState(device.deviceType, device.isUsb, status);+ post({ kind: 'state', status: 'connected' });+ return;+ }+ } catch (error) {+ hostLog('debug', `probe found the device gone: ${safeErrorMessage(error)}`);+ }+ }+ hostLog('debug', 'probe dropped a stale Work Louder transport');+ await disconnect();+ }++ try {+ const deviceApi = await ensureConnected();+ if (!deviceApi) {+ post({ kind: 'state', status: 'not-detected' });+ scheduleRetry();+ return;+ }+ lastLoggedError = null;+ post({ kind: 'state', status: 'connected' });+ if (hidListeningRequested) requestListen();+ if (latestFrame && !isWorkLouderCodexLightingFrameOff(latestFrame)) requestApply();+ } catch {+ post({ kind: 'state', status: 'not-detected' });+ scheduleRetry();+ }+}++async function listenForAgentKeys(): Promise<void> {+ try {+ const deviceApi = await ensureConnected();+ if (!deviceApi) {+ post({ kind: 'state', status: 'not-detected' });+ scheduleRetry();+ return;+ }+ clearRetry();+ lastLoggedError = null;+ post({ kind: 'state', status: 'connected' });+ } catch (error) {+ const message = safeErrorMessage(error);+ if (message !== lastLoggedError) {+ lastLoggedError = message;+ hostLog('error', `HID listening failed: ${message}`);+ }+ await disconnect();+ post({ kind: 'state', status: 'error', reason: classifyConnectionError(message) });+ scheduleRetry();+ }+}++function formatSdkLog(args: unknown[]): string {+ if (args.length === 0) return '';+ const detail = args+ .map((value) => safeErrorMessage(value))+ .filter((value) => value.length > 0)+ .join(' ')+ .trim();+ return detail ? `: ${detail}` : '';+}++function safeErrorMessage(error: unknown): string {+ const message = error instanceof Error ? error.message : String(error);+ return message+ .replace(/\/Users\/[^/]+/g, '/Users/<user>')+ .replace(/[A-Za-z]:\\Users\\[^\\]+/g, 'C:\\Users\\<user>')+ .slice(0, 400);+}++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];+ if (!candidate) return null;+ const nextComm = new loaded.WLDeviceCommImpl(sdkLogger);+ if (!(await nextComm.connect(candidate.device))) return null;+ comm = nextComm;+ const nextApi = new loaded.RPCApiOAI(nextComm, sdkLogger);+ if (typeof nextApi.onHidReceived === 'function') {+ const unsubscribe = nextApi.onHidReceived((event) => {+ postActivity();+ const parsed = parseWorkLouderCodexHidEvent(event);+ if (parsed) post({ kind: 'hid', event: parsed });+ });+ unsubscribeHid = typeof unsubscribe === 'function' ? unsubscribe : null;+ } else {+ hostLog('warn', 'Work Louder SDK does not expose HID key events');+ }+ if (typeof nextApi.onJoystickMove === 'function') {+ const unsubscribe = nextApi.onJoystickMove((event) => {+ postActivity();+ const parsed = parseWorkLouderCodexJoystickEvent(event);+ if (parsed) post({ kind: 'joystick', event: parsed });+ });+ unsubscribeJoystick = typeof unsubscribe === 'function' ? unsubscribe : null;+ }+ api = nextApi;+ connectedDevice = {+ deviceType: candidate.deviceType,+ isUsb: candidate.device.isUsbConnection === true,+ };+ await postDeviceStatus(nextApi, candidate.deviceType, candidate.device.isUsbConnection === true);+ return nextApi;+}++function postActivity(): void {+ const now = Date.now();+ if (now - lastActivityPostedAt < 250) return;+ lastActivityPostedAt = now;+ post({ kind: 'activity' });+}++async function postDeviceStatus(+ deviceApi: WorkLouderApi,+ deviceType: 'codex-micro' | 'creator-micro-2',+ isUsbConnection: boolean,+): Promise<void> {+ let status: WorkLouderDeviceStatus = {};+ if (typeof deviceApi.getDeviceStatus === 'function') {+ try {+ status = await deviceApi.getDeviceStatus();+ } catch (error) {+ hostLog('warn', `device status unavailable: ${safeErrorMessage(error)}`);+ }+ }+ postDeviceState(deviceType, isUsbConnection, status);+}++/** Publish a device snapshot, clamping whatever the SDK handed back. */+function postDeviceState(+ deviceType: 'codex-micro' | 'creator-micro-2',+ isUsbConnection: boolean,+ status: WorkLouderDeviceStatus,+): void {+ post({+ kind: 'device',+ device: {+ deviceType,+ isUsbConnection,+ firmwareVersion:+ typeof status.firmwareVersion === 'string' ? status.firmwareVersion.slice(0, 128) : null,+ batteryPercentage:+ typeof status.batteryPercentage === 'number' && Number.isFinite(status.batteryPercentage)+ ? Math.max(0, Math.min(100, status.batteryPercentage))+ : null,+ isCharging: typeof status.isCharging === 'boolean' ? status.isCharging : null,+ inputMonitoringPermission: process.platform === 'darwin' ? 'unknown' : 'not-required',+ },+ });+}++function classifyConnectionError(message: string): 'connection-failed' | 'permission-required' {+ return /permission|not permitted|access denied|input monitoring|operation not allowed/i.test(+ message,+ )+ ? 'permission-required'+ : 'connection-failed';+}++function scheduleRetry(): void {+ if (+ retryTimer ||+ stopping ||+ (!latestFrame && !hidListeningRequested) ||+ (latestFrame && isWorkLouderCodexLightingFrameOff(latestFrame) && !hidListeningRequested)+ ) {+ return;+ }+ retryTimer = setTimeout(() => {+ retryTimer = null;+ requestProbe();+ if (hidListeningRequested) requestListen();+ if (latestFrame && !isWorkLouderCodexLightingFrameOff(latestFrame)) requestApply();+ }, RETRY_MS);+ retryTimer.unref?.();+}++function clearRetry(): void {+ if (!retryTimer) return;+ clearTimeout(retryTimer);+ retryTimer = null;+}++async function disconnect(): Promise<void> {+ transportFaulted = false;+ connectedDevice = null;+ const unsubscribe = unsubscribeHid;+ unsubscribeHid = null;+ if (unsubscribe) {+ try {+ unsubscribe();+ } catch {+ // Subscription teardown is best effort before closing the HID transport.+ }+ }+ const unsubscribeStick = unsubscribeJoystick;+ unsubscribeJoystick = null;+ if (unsubscribeStick) {+ try {+ unsubscribeStick();+ } catch {+ // Subscription teardown is best effort before closing the HID transport.+ }+ }+ const current = comm;+ comm = null;+ api = null;+ if (!current) return;+ try {+ await current.disconnect();+ } catch {+ // Connection teardown is best effort after a failed HID RPC.+ }+}++async function stop(): Promise<void> {+ if (stopping) return;+ stopping = true;+ listenPending = false;+ probePending = false;+ hidListeningRequested = false;+ clearRetry();+ try {+ await applyTask;+ } catch (error) {+ hostLog('warn', `lighting apply stopped unexpectedly: ${safeErrorMessage(error)}`);+ }+ const currentApi = api;+ if (currentApi) {+ const off = createWorkLouderCodexOffFrame();+ await Promise.allSettled([+ currentApi.sendLightingConfig({ ambient: off.ambient, keys: off.keys }),+ currentApi.sendThreadsLighting(off.threads),+ ]);+ }+ await disconnect();+ post({ kind: 'stopped' });+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex a6424f7cc9..f18a6873f7 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -28,6 +28,23 @@ import {WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL,type WindowsCloseBehavior,} from '../shared/windowBehavior';+import {+ WORKLOUDER_CODEX_ACTION_CHANNEL,+ WORKLOUDER_CODEX_GET_STATE_CHANNEL,+ WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL,+ WORKLOUDER_CODEX_OPEN_INPUT_MONITORING_CHANNEL,+ WORKLOUDER_CODEX_PROBE_CHANNEL,+ WORKLOUDER_CODEX_PUBLISH_TASKS_CHANNEL,+ WORKLOUDER_CODEX_SET_LAYOUT_PREVIEW_CHANNEL,+ type WorkLouderCodexPublishedTask,+ WORKLOUDER_CODEX_RESET_SETTINGS_CHANNEL,+ WORKLOUDER_CODEX_SET_SETTINGS_CHANNEL,+ WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL,+ type WorkLouderCodexPreviewInput,+ type WorkLouderCodexRendererAction,+ type WorkLouderCodexSettingsPatch,+ type WorkLouderCodexState,+} from '../shared/workLouderCodex';import {ANALYTICS_SETTINGS_CHANGE_CHANNEL,type AnalyticsSettingsPayload,@@ -1532,6 +1549,45 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.send(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL),},+ workLouderCodex: {+ getState: (): Promise<WorkLouderCodexState> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_GET_STATE_CHANNEL),+ setSettings: (patch: WorkLouderCodexSettingsPatch): Promise<WorkLouderCodexState> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_SET_SETTINGS_CHANNEL, patch),+ resetSettings: (): Promise<WorkLouderCodexState> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_RESET_SETTINGS_CHANNEL),+ openInputMonitoringSettings: (): Promise<void> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_OPEN_INPUT_MONITORING_CHANNEL),+ probe: (): Promise<WorkLouderCodexState> => ipcRenderer.invoke(WORKLOUDER_CODEX_PROBE_CHANNEL),+ publishTasks: (tasks: WorkLouderCodexPublishedTask[]): Promise<void> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_PUBLISH_TASKS_CHANNEL, tasks),+ setLayoutPreviewActive: (active: boolean): Promise<void> =>+ ipcRenderer.invoke(WORKLOUDER_CODEX_SET_LAYOUT_PREVIEW_CHANNEL, active),+ onStateChanged: (callback: (state: WorkLouderCodexState) => void): (() => void) => {+ const listener = (_event: Electron.IpcRendererEvent, state: WorkLouderCodexState): void => {+ callback(state);+ };+ ipcRenderer.on(WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL, listener);+ return () => ipcRenderer.removeListener(WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL, listener);+ },+ onAction: (callback: (action: WorkLouderCodexRendererAction) => void): (() => void) => {+ const listener = (+ _event: Electron.IpcRendererEvent,+ action: WorkLouderCodexRendererAction,+ ): void => callback(action);+ ipcRenderer.on(WORKLOUDER_CODEX_ACTION_CHANNEL, listener);+ return () => ipcRenderer.removeListener(WORKLOUDER_CODEX_ACTION_CHANNEL, listener);+ },+ onPreviewInput: (callback: (input: WorkLouderCodexPreviewInput) => void): (() => void) => {+ const listener = (+ _event: Electron.IpcRendererEvent,+ input: WorkLouderCodexPreviewInput,+ ): void => callback(input);+ ipcRenderer.on(WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL, listener);+ return () => ipcRenderer.removeListener(WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL, listener);+ },+ },+// ── 右侧栏独立子窗口(RSB window)──────────────────────────────────────// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期。状态机在 main// (right-sidebar-window/controller.ts),renderer 只 invoke + 订阅广播。diff --git a/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts b/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.tsindex c6625ac4f4..363b0efe3e 100644--- a/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts+++ b/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts@@ -97,7 +97,9 @@ describe('resolveAgentIslandVisibleSessionIdFromPath', () => {});it('gates renderer visible-session IPC on the full Agent Island support check', () => {- expect(mainLayoutSource).toContain("import { isAgentIslandSupported, toggleAgentIslandSoundEnabled } from '@/hooks/useAgentIslandSettings';");+ expect(mainLayoutSource).toMatch(+ /import\s*\{\s*isAgentIslandSupported,\s*toggleAgentIslandSoundEnabled,?\s*\}\s*from '@\/hooks\/useAgentIslandSettings';/,+ );expect(mainLayoutSource).toContain('if (!isAgentIslandSupported()) return;');expect(mainLayoutSource).toContain('if (isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute(location.pathname)) return;');expect(orcaSplitViewSource).toContain("import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';");diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 37060fada1..66c5443d83 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -12,11 +12,26 @@ const sessionViewSource = readFileSync('utf8',).replace(/\r\n?/g, '\n');+const messageStreamSource = readFileSync(+ resolve(__dirname, '..', 'components', 'chat', 'MessageStream.tsx'),+ 'utf8',+).replace(/\r\n?/g, '\n');++const mainLayoutSource = readFileSync(+ resolve(__dirname, '..', 'components', 'layout', 'MainLayout.tsx'),+ 'utf8',+).replace(/\r\n?/g, '\n');+const newMakerDraftRouteSource = readFileSync(resolve(__dirname, '..', 'features', 'cc-agent', 'NewMakerDraftRoute.tsx'),'utf8',).replace(/\r\n?/g, '\n');+const sidebarUpperSource = readFileSync(+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),+ 'utf8',+).replace(/\r\n?/g, '\n');+const pluginPageSource = readFileSync(resolve(__dirname, '..', 'features', 'plugin', 'GhostPluginPage.tsx'),'utf8',@@ -67,6 +82,41 @@ describe('ChatInput session switch focus contract', () => {'const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);',);expect(sessionViewSource).toContain('focusOnStorageKeyChange={ownsRoute}');+ expect(sessionViewSource).toContain(+ 'ownsHardwareComposerActions={ownsHardwareTaskActions}',+ );+ expect(chatInputSource).toContain('workLouderVoiceGestureRef.current?.cancelHeldPress();');+ expect(sessionViewSource).toContain(+ 'ownsHardwareScrollActions={ownsHardwareTaskActions}',+ );+ expect(sessionViewSource).toContain("navigationMode !== 'split-pane'");+ expect(sessionViewSource).toContain("action.commandId === 'toggleTaskPin'");+ expect(sessionViewSource).toContain("action.commandId === 'archiveTask'");+ expect(sessionViewSource).toContain('void togglePin();');+ expect(sessionViewSource).toContain('void archive();');+ expect(messageStreamSource).toContain('ownsHardwareScrollActions?: boolean;');+ expect(messageStreamSource).toContain('if (!ownsHardwareScrollActions) return false;');+ expect(mainLayoutSource).toContain("const reviewTab = bucket.tabs.find((tab) => tab.kind === 'review');");+ expect(mainLayoutSource).toContain("routeSidebarCommand({ type: 'toggle-review-tab', sessionId })");+ expect(mainLayoutSource).toContain('if (reviewIsActive && reviewTab) {');+ expect(mainLayoutSource).toContain('await closeTab(sessionId, reviewTab.id);');+ expect(mainLayoutSource).toContain(+ "navigate('/cc-agent/new', { state: makeFolderPickerNewMakerRouteState() })",+ );+ expect(newMakerDraftRouteSource).toContain('readNewMakerFolderPickerRequest(location.state)');+ expect(newMakerDraftRouteSource).toContain('setFolderPickerOpen(true)');+ expect(sidebarUpperSource).toContain(+ "const catalogSessions = sessionsWithRemote.filter((session) => session.status === 'active');",+ );+ expect(sidebarUpperSource).toContain('catalogEligible: false');+ expect(sidebarUpperSource).toContain(+ 'const remainingCatalogSlots = Math.max(0, 100 - visibleProjection.length);',+ );+ expect(sidebarUpperSource).toContain('WORKLOUDER_CODEX_AGENT_SLOT_COUNT');+ expect(sidebarUpperSource).toContain('.slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT)');+ expect(sidebarUpperSource).not.toContain(+ '[...visibleSessionsWithRemote, ...remoteProjectSessions]',+ );expect(newMakerDraftRouteSource).toContain('focusOnStorageKeyChange');});diff --git a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.tsindex 497fb2799d..4168355a55 100644--- a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts@@ -84,7 +84,7 @@ describe('useDeviceProviders deviceId-aware cache', () => {expect(mod.getCachedDeviceProviders('dev-invalid')).toBeNull();});- it('provider 数组混入非法元素时整份进入 error,不得部分发布或落缓存', async () => {+ it('provider 数组混入非法元素时丢掉坏项,保留合法供应商', async () => {const invoke = vi.fn(async () => ({ providers: [provider('valid'), null] }));vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });const mod = await import('@/hooks/useDeviceProviders');@@ -93,12 +93,15 @@ describe('useDeviceProviders deviceId-aware cache', () => {await mod.prefetchDeviceProviders('dev-invalid-item');- expect(listener).toHaveBeenCalledWith({- status: 'error',- error: 'Invalid provider list response',- unsupported: false,- });- expect(mod.getCachedDeviceProviders('dev-invalid-item')).toBeNull();+ expect(mod.getCachedDeviceProviders('dev-invalid-item')?.providers.map((row) => row.id)).toEqual([+ 'valid',+ ]);+ expect(listener).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'ready',+ providers: [expect.objectContaining({ id: 'valid' })],+ }),+ );});it('接受不含执行字段的安全投影 provider', async () => {diff --git a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.tsindex d34e742bb6..006d637f2d 100644--- a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts+++ b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts@@ -18,7 +18,9 @@ describe('effort runtime send guard', () => {);expect(chatInputSource).toContain('editable: !composerEditorLocked');expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');- expect(chatInputSource).toContain("trigger.kind !== 'slash' || composerMutationLockedRef.current");+ expect(chatInputSource).toMatch(+ /trigger\.kind !== 'slash'\s*\|\|\s*composerMutationLockedRef\.current/,+ );expect(chatInputSource).toContain('if (composerMutationLocked) return;');expect(chatInputSource).toContain("id: 'attach-files'");expect(chatInputSource).toContain(diff --git a/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts b/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.tsindex e9bf458b1c..db3b650943 100644--- a/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts@@ -2,8 +2,11 @@ import { describe, expect, it, vi } from 'vitest';import {consumeNewMakerDialogueTargetRequest,+ consumeNewMakerFolderPickerRequest,makeDialogueNewMakerRouteState,+ makeFolderPickerNewMakerRouteState,readNewMakerDialogueTargetRequest,+ readNewMakerFolderPickerRequest,} from '@/features/cc-agent/lib/newMakerRouteState';describe('new maker dialogue route target request', () => {@@ -76,3 +79,25 @@ describe('new maker dialogue route target request', () => {expect(consumeNewMakerDialogueTargetRequest(null)).toBeNull();});});++describe('new maker folder picker request', () => {+ it('opens the picker again when the same route is already mounted', () => {+ vi.spyOn(Date, 'now').mockReturnValue(5678);+ const first = readNewMakerFolderPickerRequest(makeFolderPickerNewMakerRouteState());+ const second = readNewMakerFolderPickerRequest(makeFolderPickerNewMakerRouteState());+ expect(first?.requestId).toBeTruthy();+ expect(first?.requestId).not.toBe(second?.requestId);+ });++ it('consumes a folder picker request without dropping other route state', () => {+ const original = {+ workspacePrompt: 'generic',+ folderPickerRequest: { requestId: 'picker-1' },+ preserved: true,+ };+ const consumed = consumeNewMakerFolderPickerRequest(original);+ expect(consumed).toEqual({ workspacePrompt: 'generic', preserved: true });+ expect(readNewMakerFolderPickerRequest(consumed)).toBeNull();+ expect(readNewMakerFolderPickerRequest(original)).toEqual({ requestId: 'picker-1' });+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.tsindex 12a724d6c5..f9355c11d4 100644--- a/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionRemovalNavigation.test.ts@@ -154,4 +154,45 @@ describe('getVisibleSidebarSessionIds', () => {'visible-under-pointer-suppression',]);});++ it('reads search hits and ignores the list underneath a search overlay', () => {+ const aside = document.createElement('aside');+ const list = document.createElement('div');+ const covered = document.createElement('div');+ covered.dataset.sidebarSessionRow = 'true';+ covered.dataset.sessionId = 'old';+ list.append(covered);++ const overlay = document.createElement('div');+ overlay.dataset.conversationSearchSurface = '';+ overlay.dataset.conversationSearchOverlay = '';+ const hit = document.createElement('div');+ hit.dataset.sidebarSessionRow = 'true';+ hit.dataset.sessionId = 'hit';+ overlay.append(hit);++ aside.append(list, overlay);+ document.body.append(aside);+ try {+ expect(getVisibleSidebarSessionIds()).toEqual(['hit']);+ } finally {+ aside.remove();+ }+ });++ it('keeps the real sidebar list when only the resident search input is marked', () => {+ const aside = document.createElement('aside');+ const search = document.createElement('div');+ search.dataset.conversationSearchSurface = '';+ const row = document.createElement('div');+ row.dataset.sidebarSessionRow = 'true';+ row.dataset.sessionId = 'visible';+ aside.append(search, row);+ document.body.append(aside);+ try {+ expect(getVisibleSidebarSessionIds()).toEqual(['visible']);+ } finally {+ aside.remove();+ }+ });});diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.tsindex 6abb6b020b..7d4cc0f88f 100644--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts@@ -35,8 +35,8 @@ describe('sidebar remote project icon', () => {expect(sessionCardSource).toMatch(/const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,);- expect(sessionHeaderSource).toContain(- "const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null",+ expect(sessionHeaderSource).toMatch(+ /const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,);});diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 147e7bc9fe..a521259749 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -56,12 +56,11 @@ import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreferenceimport { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';import { resolveToolFilePath, type KnownLocalFileRef } from '@/lib/localPathResolver';import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';-import {- isRemoteSessionSticky,- subscribeTurnChangeSetUpdated,-} from '@/lib/makerTransport';+import { isRemoteSessionSticky, subscribeTurnChangeSetUpdated } from '@/lib/makerTransport';import { isEditableKeyboardTarget } from '@/lib/editableKeyboardTarget';import { createLogger } from '@/lib/logger';+import { subscribeWorkLouderCodexAction } from '@/lib/workLouderCodexActions';+import { joystickScrollDelta } from '../../../shared/workLouderCodexScroll';import { stopAllMedia } from '@/lib/mediaPlaybackBus';import { cn } from '@/lib/utils';import {@@ -363,6 +362,11 @@ interface MessageStreamProps {* behavior of treating every new tail user message as a local send.*/isLocalUserSend?: (clientId: string) => boolean;+ /**+ * Whether this stream should consume hardware scroll commands.+ * Split panes keep every MessageStream mounted; only the focused owner may act.+ */+ ownsHardwareScrollActions?: boolean;}// ---------------------------------------------------------------------------@@ -1991,8 +1995,8 @@ function isRunningAgentTask(it: RenderItem): boolean {if (it.type !== 'agent_task') return false;const status = deriveAgentTaskStatus(it.update?.status, it.result, {resultIsLaunchReceipt:- subagentSpawnReceiptName(it.toolCall?.toolName, it.toolCall?.toolInput, it.result) !== undefined- || subagentSpawnResultIndicatesRunning(it.toolCall?.toolName, it.result),+ subagentSpawnReceiptName(it.toolCall?.toolName, it.toolCall?.toolInput, it.result) !==+ undefined || subagentSpawnResultIndicatesRunning(it.toolCall?.toolName, it.result),});return status === 'running';}@@ -2795,6 +2799,7 @@ export function MessageStream({forkOrigin,onOpenForkOrigin,isLocalUserSend,+ ownsHardwareScrollActions = true,}: MessageStreamProps) {// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,@@ -2888,9 +2893,9 @@ export function MessageStream({const restoreDefaultViewportRef = useRef(Boolean(restoringRef.current &&- restoreSnapshotRef.current?.windowAnchorKey === null &&- restoreSnapshotRef.current?.isNearBottom === false &&- restoreSnapshotRef.current?.viewportTopKey,+ restoreSnapshotRef.current?.windowAnchorKey === null &&+ restoreSnapshotRef.current?.isNearBottom === false &&+ restoreSnapshotRef.current?.viewportTopKey,),);// 两段式默认窗口的当前尺寸(FIRST_PAINT → 空闲期扩到 INITIAL)。只影响@@ -2987,7 +2992,8 @@ export function MessageStream({return next;});});- void window.electronAPI.maker.listTurnChangeSets(sessionId)+ void window.electronAPI.maker+ .listTurnChangeSets(sessionId).then((next) => {if (cancelled) return;setTurnChangeSets((current) => {@@ -3126,23 +3132,26 @@ export function MessageStream({}const startIdx = snapRenderWindowStartIdx(allRenderItems, idx);- const windowItemCount = resolveAnchoredWindowItemCount(- startIdx,- idx,- anchoredForwardItems,- );+ const windowItemCount = resolveAnchoredWindowItemCount(startIdx, idx, anchoredForwardItems);return {items: allRenderItems.slice(startIdx, startIdx + windowItemCount),startIdx,};- }, [allRenderItems, firstVisibleItemKey, defaultWindowItems, anchoredForwardItems, firstMountDeferred]);+ }, [+ allRenderItems,+ firstVisibleItemKey,+ defaultWindowItems,+ anchoredForwardItems,+ firstMountDeferred,+ ]);// If a restored default-tail anchor fell out of the tail while this session// was backgrounded, permanently fall back to the bounded default window for// this mount. This also prevents expandWindow from treating the stale key as// a user-created anchored window.useLayoutEffect(() => {- if (!restoreDefaultViewportRef.current || !restoringRef.current || firstVisibleItemKey === null) return;+ if (!restoreDefaultViewportRef.current || !restoringRef.current || firstVisibleItemKey === null)+ return;const snap = restoreSnapshotRef.current;if (!snap?.viewportTopKey) return;if (allRenderItems.length === 0) return;@@ -4306,6 +4315,83 @@ export function MessageStream({}, CHIP_JUMP_SAFETY_MS);}, [beginProgrammaticScroll, cancelFocusJump, finishChipJump, finishProgrammaticScroll, refreshViewportAnchor]);+ // ── Codex Micro 摇杆:按住持续滚动 ──+ // 摇杆推住时主进程持续送 { type:'scroll', intensity },这里逐帧按速度改+ // scrollTop —— 像拖鼠标滚轮,而不是每拨一下跳一屏。速度走平方曲线(见+ // shared/workLouderCodexScroll.ts):轻推能微调,推到底才最快。+ // 不用 behavior:'smooth' —— 逐帧位移叠加缓动会互相打架,松手后还会惯性飘。+ const joystickScrollRef = useRef<{ direction: 'up' | 'down'; intensity: number } | null>(null);+ const joystickScrollFrameRef = useRef<number | null>(null);+ const stopJoystickScroll = useCallback(() => {+ joystickScrollRef.current = null;+ if (joystickScrollFrameRef.current !== null) {+ cancelAnimationFrame(joystickScrollFrameRef.current);+ joystickScrollFrameRef.current = null;+ }+ }, []);+ useEffect(() => stopJoystickScroll, [stopJoystickScroll]);++ useEffect(() => {+ if (!ownsHardwareScrollActions) stopJoystickScroll();+ return subscribeWorkLouderCodexAction((action) => {+ if (action.type === 'scroll-stop') {+ stopJoystickScroll();+ return ownsHardwareScrollActions;+ }+ if (!ownsHardwareScrollActions) return false;+ if (action.type === 'scroll') {+ joystickScrollRef.current = { direction: action.direction, intensity: action.intensity };+ if (joystickScrollFrameRef.current !== null) return true;+ let lastAt = performance.now();+ const step = (now: number): void => {+ joystickScrollFrameRef.current = null;+ const active = joystickScrollRef.current;+ const el = scrollRef.current;+ if (!active || !el) return;+ const delta = joystickScrollDelta(active.intensity, now - lastAt);+ lastAt = now;+ if (active.direction === 'up') {+ // 程序化改 scrollTop 不发 wheel 事件,所以不会自动解除 auto-follow;+ // 不显式解除的话,向上滚会被跟随逻辑一路拽回底部。+ unpinAutoFollowForUserUpIntent();+ el.scrollTop -= delta;+ } else {+ el.scrollTop += delta;+ }+ joystickScrollFrameRef.current = requestAnimationFrame(step);+ };+ joystickScrollFrameRef.current = requestAnimationFrame(step);+ return true;+ }+ if (action.type !== 'command') return false;+ if (action.commandId === 'conversation.scrollBottom') {+ scrollToBottomSmooth();+ return true;+ }+ // 键盘快捷键与改绑到其它键的场景仍走这条一次性路径。+ if (+ action.commandId !== 'conversation.scrollUp' &&+ action.commandId !== 'conversation.scrollDown'+ ) {+ return false;+ }+ const el = scrollRef.current;+ if (!el) return false;+ const direction = action.commandId === 'conversation.scrollUp' ? -1 : 1;+ if (direction < 0) unpinAutoFollowForUserUpIntent();+ el.scrollBy({+ top: direction * Math.max(160, el.clientHeight * 0.7),+ behavior: 'smooth',+ });+ return true;+ });+ }, [+ ownsHardwareScrollActions,+ scrollToBottomSmooth,+ stopJoystickScroll,+ unpinAutoFollowForUserUpIntent,+ ]);+// F2: messages diff → 按角色累计 unreadCount// - 计数规则抽成纯函数 countUnreadAdded(见 unreadCount.ts):新 clientId 才计、// 贴底不计、assistant/ask_user/plan_review 计;#2194 起非本端发送的 user 也计。@@ -4348,9 +4434,7 @@ export function MessageStream({visibleLastItem,realLastItem,userMessageId: (item) =>- item?.type === 'message' && item.message.role === 'user'- ? item.message.clientId- : null,+ item?.type === 'message' && item.message.role === 'user' ? item.message.clientId : null,});const lastUserMsg =tailUserMessageId === null@@ -4409,7 +4493,14 @@ export function MessageStream({const el = scrollRef.current;if (el) prevScrollTopRef.current = el.scrollTop;- }, [visibleRenderItems, bottomPadding, pinToBottom, firstVisibleItemKey, windowCoversEnd, allRenderItems]);+ }, [+ visibleRenderItems,+ bottomPadding,+ pinToBottom,+ firstVisibleItemKey,+ windowCoversEnd,+ allRenderItems,+ ]);// ── 还原浏览位置(layout effect,在上面的 pin-to-bottom effect 之后跑) ──// mount 首帧 + 还原期间窗口变化时把视口摆回锚点。settle(图片/markdown 异步加载@@ -4857,7 +4948,11 @@ export function MessageStream({// 用户向下滚动接近当前窗口下缘时,扩 anchoredForwardItems 纳入更多 item。// 向下 append 不改变已有内容的滚动偏移,不需要 F-SYNC-2 delta 补偿。// 扩到覆盖末尾后直接清除锚点,回到默认贴底窗口。- if (!windowCoversEnd && delta > SCROLL_DIRECTION_DEAD_ZONE_PX && distanceFromBottom < threshold) {+ if (+ !windowCoversEnd &&+ delta > SCROLL_DIRECTION_DEAD_ZONE_PX &&+ distanceFromBottom < threshold+ ) {const nextForward = anchoredForwardItems + RENDER_WINDOW_GROWTH_ITEMS;// 最后一批照常渲染:不在此处清除锚点。用户真正滚到窗口底部后,// 上面 effectiveNearBottom + windowCoversEnd 分支会自然清除锚点、diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 0f022ce093..761c5573f1 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -11,10 +11,7 @@ import { FadeSwitcher } from '@/components/layout/FadeSwitcher';import { RightSidebar, type RightSidebarHandle } from '@/components/layout/RightSidebar';import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';import { Sidebar } from '@/components/sidebar/Sidebar';-import {- getSplitSessionIds,- useSplitGroup,-} from '@/features/cc-agent/splitGroupStore';+import { getSplitSessionIds, useSplitGroup } from '@/features/cc-agent/splitGroupStore';import { LayoutRoot } from '@/layout/LayoutRoot';import { PanelDragController } from '@/layout/PanelDragController';import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';@@ -58,6 +55,7 @@ import { didUserCloseDetachedSidebarWindow } from '@/lib/rsbWindowTransitions';import { routeSidebarCommand } from '@/features/right-sidebar/lib/detachedSidebarRouting';import { openTerminalFromShortcut } from '@/features/right-sidebar/lib/openTerminalShortcut';import { executeSidebarCommand } from '@/features/right-sidebar/lib/executeSidebarCommand';+import { openUrlInSidebarBrowser } from '@/features/right-sidebar/lib/openInSidebarBrowser';import { useSidebarResize } from '@/hooks/useSidebarResize';import { useSidebarCardMode } from '@/hooks/useSidebarCardMode';import { useSidebarPeek } from '@/hooks/useSidebarPeek';@@ -69,7 +67,10 @@ import {import { isSecondaryWindow } from '@/lib/secondaryWindow';import { useUpdateNotice } from '@/hooks/useUpdateNotice';import { syncNotificationsEnabledToMain } from '@/hooks/useNotificationSettings';-import { isAgentIslandSupported, toggleAgentIslandSoundEnabled } from '@/hooks/useAgentIslandSettings';+import {+ isAgentIslandSupported,+ toggleAgentIslandSoundEnabled,+} from '@/hooks/useAgentIslandSettings';import { requestNewWorkerFromShortcut } from '@/features/cc-agent/lib/newWorkerShortcut';// chat-data-localization F1 V0.4 / M-FE6import { useCorruptionRestoredToast } from '@/hooks/useCorruptionRestoredToast';@@ -83,12 +84,15 @@ import { patchDraft } from '@/state/newMakerDraft';import { cn } from '@/lib/utils';import { checkForUpdateWithToast } from '@/lib/checkForUpdateWithToast';import { createLogger } from '@/lib/logger';+import { subscribeWorkLouderCodexAction } from '@/lib/workLouderCodexActions';import { cleanupLegacyGlobalKeys } from '@/lib/sessionLayoutPrefs';import {onRequestRightSidebarVisibility,requestRightSidebarVisibility,shouldAnimateSidebarVisibilityRequest,} from '@/features/right-sidebar/lib/sidebarCommands';+import { requestSessionSwitch } from '@/features/cc-agent/lib/sessionSwitchCommands';+import { makeFolderPickerNewMakerRouteState } from '@/features/cc-agent/lib/newMakerRouteState';import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import {@@ -273,6 +277,10 @@ export function MainLayout() {const [rightSidebarSessionId, setRightSidebarSessionId] = useState<string | null>(null);const rightSidebarSessionIdRef = useRef(rightSidebarSessionId);rightSidebarSessionIdRef.current = rightSidebarSessionId;+ const isRightSidebarCollapsedRef = useRef(isRightSidebarCollapsed);+ isRightSidebarCollapsedRef.current = isRightSidebarCollapsed;+ const rsbDetachedRef = useRef(rsbDetached);+ rsbDetachedRef.current = rsbDetached;const declareRightSidebarSessionId = useCallback((sessionId: string | null, opts: RightSidebarSessionDeclarationOptions = {}) => {rightSidebarSessionIdRef.current = sessionId;@@ -431,15 +439,12 @@ export function MainLayout() {}, [sidebarPeek.peekState, isRailMode, handleRailModeChange]);const routeSessionId = resolveAgentIslandVisibleSessionIdFromPath(location.pathname);- const splitVisibleSessionIds = useMemo(- () => {- const splitSessionIds = getSplitSessionIds(splitGroup.root);- return routeSessionId && splitSessionIds.length >= 2- ? [...new Set([routeSessionId, ...splitSessionIds])]- : [];- },- [routeSessionId, splitGroup.root],- );+ const splitVisibleSessionIds = useMemo(() => {+ const splitSessionIds = getSplitSessionIds(splitGroup.root);+ return routeSessionId && splitSessionIds.length >= 2+ ? [...new Set([routeSessionId, ...splitSessionIds])]+ : [];+ }, [routeSessionId, splitGroup.root]);const syncAgentIslandVisibleSession = useCallback(() => {if (!isAgentIslandSupported()) return;@@ -571,11 +576,16 @@ export function MainLayout() {if (!payload || typeof payload !== 'object') return;const { requestId, ghostId, ghostName, name, prompt, intervalMs } = payload;if (- typeof requestId !== 'string' || !requestId ||- typeof ghostId !== 'string' || !ghostId ||- typeof ghostName !== 'string' || !ghostName ||- typeof name !== 'string' || !name ||- typeof prompt !== 'string' || !prompt+ typeof requestId !== 'string' ||+ !requestId ||+ typeof ghostId !== 'string' ||+ !ghostId ||+ typeof ghostName !== 'string' ||+ !ghostName ||+ typeof name !== 'string' ||+ !name ||+ typeof prompt !== 'string' ||+ !prompt) {return;}@@ -716,6 +726,32 @@ export function MainLayout() {setIsRightSidebarCollapsed(true);}, [isRightSidebarCollapsed, rightSidebarSessionId, rsbDetached]);+ const handleToggleRightSidebar = useCallback(() => {+ if (!rsbWindow.loaded) return;+ if (rsbDetached) {+ if (rsbWindow.open) {+ void window.electronAPI.rightSidebarWindow+ .close()+ .catch((err) => log.warn('hide detached right sidebar failed', err));+ return;+ }+ handleOpenRightSidebar();+ return;+ }+ if (isRightSidebarCollapsed) {+ handleOpenRightSidebar();+ return;+ }+ handleCloseRightSidebar();+ }, [+ handleCloseRightSidebar,+ handleOpenRightSidebar,+ isRightSidebarCollapsed,+ rsbDetached,+ rsbWindow.loaded,+ rsbWindow.open,+ ]);+// 关掉右侧栏最后一个 tab 时自动收起(由 RightSidebarShell 在 tab 数 >0→0 时回调)。// detached 子窗口形态不在此处理(那时主窗根本不渲染内嵌 Shell,也收不到此回调)。// 走 requestAnimateNextChange 让收起有 250ms 动画,与用户手动折叠观感一致(规则 7)。@@ -1083,7 +1119,7 @@ export function MainLayout() {[rightSidebarSessionId],);- useAppShortcut('open-terminal', () => {+ const openTerminalForCurrentTask = useCallback((): boolean => {const sessionId = rightSidebarSessionId;if (!rightSidebarAvailable || !sessionId) return false;openTerminalShortcutAbortRef.current?.abort();@@ -1114,7 +1150,103 @@ export function MainLayout() {}});return true;- });+ }, [rightSidebarAvailable, rightSidebarSessionId]);++ useAppShortcut('open-terminal', openTerminalForCurrentTask);++ useEffect(() => {+ return subscribeWorkLouderCodexAction((action) => {+ if (action.type === 'keyboard') {+ const target =+ document.activeElement instanceof HTMLElement ? document.activeElement : document.body;+ target.dispatchEvent(+ new KeyboardEvent('keydown', {+ key: action.key,+ bubbles: true,+ cancelable: true,+ }),+ );+ return true;+ }+ if (action.type !== 'command') return false;+ switch (action.commandId) {+ case 'newTask':+ navigate('/cc-agent/new');+ return true;+ case 'settings':+ navigate('/settings?tab=shortcuts&workLouderCodex=1');+ return true;+ case 'manageTasks':+ navigate('/cc-agent/scheduled');+ return true;+ case 'openSkills':+ navigate('/skillhub/local');+ return true;+ case 'feedback':+ navigate('/issues');+ return true;+ case 'openFolder':+ navigate('/cc-agent/new', { state: makeFolderPickerNewMakerRouteState() });+ return true;+ case 'navigateBack':+ navigate(-1);+ return true;+ case 'navigateForward':+ navigate(1);+ return true;+ case 'toggleSidebar':+ handleToggleSidebar();+ return true;+ case 'toggleRightSidebar':+ // Goes through the same handler as the UI button so the detached+ // (separate window) preference keeps its open/close semantics.+ handleToggleRightSidebar();+ return true;+ case 'session.selectPrevious':+ requestSessionSwitch('previous');+ return true;+ case 'session.selectNext':+ requestSessionSwitch('next');+ return true;+ case 'toggleTerminal':+ return openTerminalForCurrentTask();+ case 'openBrowserTab': {+ const sessionId = rightSidebarSessionIdRef.current;+ if (!sessionId) return false;+ void openUrlInSidebarBrowser(sessionId, 'about:blank').catch((error) =>+ applicationMenuLog.warn('Codex Micro browser action failed', error),+ );+ return true;+ }+ case 'toggleReviewTab': {+ const sessionId = rightSidebarSessionIdRef.current;+ if (!sessionId) return false;+ void (async () => {+ const routed = await routeSidebarCommand({ type: 'toggle-review-tab', sessionId });+ if (routed !== 'attached') return;+ if (rightSidebarSessionIdRef.current !== sessionId) return;+ await ensureHydrated(sessionId);+ if (rightSidebarSessionIdRef.current !== sessionId) return;+ const bucket = getBucket(sessionId);+ const reviewTab = bucket.tabs.find((tab) => tab.kind === 'review');+ const reviewIsActive =+ !isRightSidebarCollapsedRef.current &&+ reviewTab != null &&+ bucket.activeTabId === reviewTab.id;+ if (reviewIsActive && reviewTab) {+ await closeTab(sessionId, reviewTab.id);+ return;+ }+ requestRightSidebarVisibility('open', { sessionId });+ await addOrFocusSingletonTab(sessionId, 'review', null);+ })().catch((error) => applicationMenuLog.warn('Codex Micro review action failed', error));+ return true;+ }+ default:+ return false;+ }+ });+ }, [handleToggleRightSidebar, handleToggleSidebar, navigate, openTerminalForCurrentTask]);// ⌘W / Ctrl+W ('close-tab-or-window', 不可改绑): 用户"在右侧栏内"且有激活// tab → 只关那个 tab (与点 tab 上的 × 同路径, terminal 走 onBeforeClosediff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 8a578d04f7..6710d8b408 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -266,6 +266,7 @@ import {} from '@/hooks/useComposerSendShortcutPreference';import { usePromptRecommendationPreference } from '@/hooks/usePromptRecommendationPreference';import { createLogger } from '@/lib/logger';+import { subscribeWorkLouderCodexAction } from '@/lib/workLouderCodexActions';import { createComposerDraftSaveScheduler } from '@/lib/composerDraftSaveScheduler';import {composerRenderSnapshot,@@ -342,6 +343,7 @@ import {import { VoiceInputPointerHintLayer } from '@/voice-input/VoiceInputPointerHintLayer';import { requestRendererMicrophonePermission } from '@/voice-input/startGuards';import { COMPOSER_MENTION_MIME, decodeComposerMentionPayload } from '@/lib/composerMentionDrag';+import { createWorkLouderCodexVoiceGesture } from '@/lib/workLouderCodexVoiceGesture';import { appendMentionChip } from './mentionChipInsertion';// device-link 远程会话:设置变更不落本地 DB(会 404),改写远程内存层 + 运行时隧道。import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';@@ -654,6 +656,11 @@ interface ChatInputProps {* 嵌入式 rail / split pane 保持 false,避免抢走当前页面快捷键或其它 pane 的焦点。*/focusOnStorageKeyChange?: boolean;+ /**+ * Whether this composer should consume hardware send / voice / text commands.+ * Split panes keep every ChatInput mounted; only the focused owner may act.+ */+ ownsHardwareComposerActions?: boolean;/*** 附加只读引用目录列表(绝对路径)。* 与 onExtraDirsChange 成对出现:@@ -1051,6 +1058,7 @@ export function ChatInput({draftKey,disableAutofocus = false,focusOnStorageKeyChange = false,+ ownsHardwareComposerActions = true,extraDirs,onExtraDirsChange,onNewGoal,@@ -2884,7 +2892,8 @@ export function ChatInput({[installedGhosts, workingDir],);const pluginAvailableIds = useMemo(- () => new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),+ () =>+ new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),[ghostsForCommand],);// 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或@@ -3159,6 +3168,9 @@ export function ChatInput({const localVoiceShortcutHandledAtRef = useRef(0);const globalVoiceShortcutStartHandledAtRef = useRef(0);const globalVoiceShortcutSuppressReleaseFromLocalRef = useRef(false);+ const workLouderVoiceGestureRef = useRef<ReturnType<+ typeof createWorkLouderCodexVoiceGesture+ > | null>(null);useEffect(() => {voiceShortcutRef.current = voiceInputSettings.shortcut;@@ -4010,9 +4022,7 @@ export function ChatInput({);// ── Slash / At panel state ─────────────────────────────────────────- const trigger: TriggerState = editor- ? detectTrigger(editor)- : { kind: 'none' };+ const trigger: TriggerState = editor ? detectTrigger(editor) : { kind: 'none' };// Slash commands — palette refactor 后改成 loadAllCommands 一次性拉三源(desktop +// agent-builtin + agent-skill); 内部并发, mergeCommands 按优先级合并去重。@@ -4194,9 +4204,10 @@ export function ChatInput({if (atScanSeqRef.current !== seq || !partial.success) return;setAtState((prev) => ({kind: 'ready',- items: preservePreviousItems && prev.kind === 'ready'- ? mergeAtResourceItems(prev.items, partial.items)- : partial.items,+ items:+ preservePreviousItems && prev.kind === 'ready'+ ? mergeAtResourceItems(prev.items, partial.items)+ : partial.items,truncated: partial.truncated || (prev.kind === 'ready' && prev.truncated),searching: true,}));@@ -4360,10 +4371,7 @@ export function ChatInput({workingDir,]);- const atResources = useMemo(- () => (atState.kind === 'ready' ? atState.items : []),- [atState],- );+ const atResources = useMemo(() => (atState.kind === 'ready' ? atState.items : []), [atState]);const filteredAt = useMemo(() =>@@ -4391,12 +4399,12 @@ export function ChatInput({// Keep keyboard focus on an executable row when filtering or runtime status changes.useEffect(() => {- setSlashFocus((current) => (- current >= filteredCommands.length- || (filteredCommands[current] && isSlashCommandUnavailable(filteredCommands[current]))+ setSlashFocus((current) =>+ current >= filteredCommands.length ||+ (filteredCommands[current] && isSlashCommandUnavailable(filteredCommands[current]))? firstAvailableSlashCommandIndex(filteredCommands)- : current- ));+ : current,+ );}, [filteredCommands]);useEffect(() => {if (@@ -4416,13 +4424,14 @@ export function ChatInput({if (normalizedQuery === atLastScanQueryRef.current) return;atLastScanQueryRef.current = normalizedQuery;const seq = ++atScanSeqRef.current;- setAtState((prev) => prev.kind === 'ready'- ? { ...prev, searching: true }- : prev);- atQueryScanTimerRef.current = window.setTimeout(() => {- atQueryScanTimerRef.current = null;- runAtScan(normalizedQuery, seq);- }, normalizedQuery ? 200 : 0);+ setAtState((prev) => (prev.kind === 'ready' ? { ...prev, searching: true } : prev));+ atQueryScanTimerRef.current = window.setTimeout(+ () => {+ atQueryScanTimerRef.current = null;+ runAtScan(normalizedQuery, seq);+ },+ normalizedQuery ? 200 : 0,+ );return () => {if (atQueryScanTimerRef.current !== null) {window.clearTimeout(atQueryScanTimerRef.current);@@ -4456,9 +4465,7 @@ export function ChatInput({const slashOpen = trigger.kind === 'slash' && suppressedSlashAt !== trigger.from;const typedAtOpen =- effectiveAt?.activation === 'typed' &&- !isRemoteSession &&- suppressedAtAt !== effectiveAt.from;+ effectiveAt?.activation === 'typed' && !isRemoteSession && suppressedAtAt !== effectiveAt.from;const syntheticAtOpen = effectiveAt?.activation === 'synthetic';const atOpen = typedAtOpen || syntheticAtOpen;@@ -4581,7 +4588,8 @@ export function ChatInput({if (!editor ||editor.isDestroyed ||- trigger.kind !== 'slash' || composerMutationLockedRef.current ||+ trigger.kind !== 'slash' ||+ composerMutationLockedRef.current ||editor.view.composing ||isSlashCommandUnavailable(cmd)) {@@ -4824,30 +4832,25 @@ export function ChatInput({[closeAtPanel, editor, insertAtResource, resolveEffectiveAtRange],);- const handleComposerSuggestionOpenChange = useCallback((nextOpen: boolean) => {- if (!nextOpen) {- setSyntheticAtAnchor(null);- return;- }- if (!editor || editor.isDestroyed || composerMutationLocked) return;- if (trigger.kind === 'slash') {- setSuppressedSlashAt(trigger.from);- } else if (trigger.kind === 'at') {- setSuppressedAtAt(trigger.from);- }- setSyntheticAtAnchor(editor.state.selection.from);- setAtFocus(0);- editor.commands.focus();- }, [- composerMutationLocked,- editor,- setSyntheticAtAnchor,- trigger,- ]);- const composerSuggestionFocusTarget = useCallback(- () => editor?.view.dom ?? null,- [editor],+ const handleComposerSuggestionOpenChange = useCallback(+ (nextOpen: boolean) => {+ if (!nextOpen) {+ setSyntheticAtAnchor(null);+ return;+ }+ if (!editor || editor.isDestroyed || composerMutationLocked) return;+ if (trigger.kind === 'slash') {+ setSuppressedSlashAt(trigger.from);+ } else if (trigger.kind === 'at') {+ setSuppressedAtAt(trigger.from);+ }+ setSyntheticAtAnchor(editor.state.selection.from);+ setAtFocus(0);+ editor.commands.focus();+ },+ [composerMutationLocked, editor, setSyntheticAtAnchor, trigger],);+ const composerSuggestionFocusTarget = useCallback(() => editor?.view.dom ?? null, [editor]);// ── Send / Stop wiring ─────────────────────────────────────────────const dispatchSendInFlightKeysRef = useRef(new Set<string>());@@ -5013,10 +5016,7 @@ export function ChatInput({}if (sourceStorageKey) {if (- shouldPreservePlanModeComposerDraft(- attachmentsForSend.length,- commentsForSend.length,- )+ shouldPreservePlanModeComposerDraft(attachmentsForSend.length, commentsForSend.length)) {const existingDraft = getComposerDraft(sourceStorageKey);saveComposerDraft(@@ -6854,6 +6854,101 @@ export function ChatInput({],);+ useEffect(() => {+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: VOICE_INPUT_LONG_PRESS_MS,+ getState: () => voiceInputStateRef.current,+ start: () => handleVoiceInputStartRef.current(),+ stop: () => voiceInputStopRef.current(),+ });+ workLouderVoiceGestureRef.current = gesture;+ return () => {+ gesture.dispose();+ if (workLouderVoiceGestureRef.current === gesture) {+ workLouderVoiceGestureRef.current = null;+ }+ };+ }, []);++ useEffect(() => {+ if (!ownsHardwareComposerActions) {+ workLouderVoiceGestureRef.current?.cancelHeldPress();+ }+ return subscribeWorkLouderCodexAction((action) => {+ if (action.type === 'voice' && !ownsHardwareComposerActions) {+ workLouderVoiceGestureRef.current?.cancelHeldPress();+ return false;+ }+ if (!ownsHardwareComposerActions) return false;+ if (action.type === 'skill') {+ if (!editor || editor.isDestroyed || composerMutationLocked) return false;+ editor.chain().focus().insertContent(`$${action.name} `).run();+ return true;+ }+ if (action.type === 'composer-text') {+ if (!editor || editor.isDestroyed || composerMutationLocked) return false;+ editor.chain().focus().insertContent(action.text).run();+ return true;+ }+ if (action.type === 'voice') {+ // One path for the key: the gesture already covers tap-to-start,+ // tap-again-to-stop, and hold-to-talk, matching Cindy's microphone.+ workLouderVoiceGestureRef.current?.handle({ phase: action.phase });+ return true;+ }+ if (action.type !== 'command') return false;+ switch (action.commandId) {+ case 'composer.submit':+ void handleClickSend();+ return true;+ case 'composer.toggleFastMode':+ void handleFastModeChange(!fastMode);+ return true;+ case 'composer.togglePlanMode':+ if (!planModeEntry) return false;+ planModeEntry.onToggle(!planModeEntry.enabled);+ return true;+ case 'composer.focus':+ editor?.commands.focus('end');+ return true;+ case 'composer.addFiles':+ case 'composer.addPhotos':+ suggestionFileInputRef.current?.click();+ return true;+ case 'composer.increaseReasoningEffort':+ case 'composer.decreaseReasoningEffort': {+ const { efforts } = resolveModelEfforts(activeModel, effectiveSourceId);+ if (efforts.length === 0) return false;+ const currentIndex = Math.max(0, efforts.indexOf(activeEffort));+ const delta = action.commandId === 'composer.increaseReasoningEffort' ? 1 : -1;+ const next = efforts[Math.max(0, Math.min(efforts.length - 1, currentIndex + delta))];+ if (!next || next === activeEffort) return true;+ void handleEffortChange(next);+ return true;+ }+ default:+ return false;+ }+ });+ }, [+ activeEffort,+ activeModel,+ composerMutationLocked,+ editor,+ ownsHardwareComposerActions,+ effectiveSourceId,+ fastMode,+ handleClickSend,+ handleEffortChange,+ handleFastModeChange,+ handleVoiceInputPlainStop,+ handleVoiceInputStart,+ planModeEntry,+ resolveModelEfforts,+ voiceInput.isBusy,+ voiceInput.isListening,+ ]);+// per-session 来源切换。镜像 model 持久化路径(handleModelChange 里的// `sessionService.update({ model }) + maker.setModel`):// - maker.setModel(sessionId, activeModel, providerId):第 3 参把显式来源记进diff --git a/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx b/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsxindex 3b53def320..f7b139cb03 100644--- a/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx@@ -45,6 +45,7 @@ import {import { getVoiceInputSettings } from '@/hooks/useVoiceInputSettings';import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';+import { WorkLouderCodexEntryContainer, WorkLouderCodexSettings } from './WorkLouderCodexSettings';const log = createLogger('settings:keyboard-shortcuts');@@ -65,9 +66,16 @@ export function KeyboardShortcutsSection() {Record<AppShortcutId, AppShortcutCombo | null>>;const [recordingId, setRecordingId] = useState<AppShortcutId | null>(null);+ const [workLouderSettingsOpen, setWorkLouderSettingsOpen] = useState(false);const [error, setError] = useState<RecordingError | null>(null);const [globalError, setGlobalError] = useState<string | null>(null);const mutationRequestIdRef = useRef(0);+ const workLouderOpenRequested =+ new URLSearchParams(window.location.search).get('workLouderCodex') === '1';++ useEffect(() => {+ if (workLouderOpenRequested) setWorkLouderSettingsOpen(true);+ }, [workLouderOpenRequested]);const mutationErrorMessage = useCallback((err: unknown) => {@@ -190,13 +198,11 @@ export function KeyboardShortcutsSection() {return;}const requestId = beginShortcutAction();- window.electronAPI.appShortcuts- .setOverride(recordingId, combo)- .catch((err: unknown) => {- // main 侧校验兜底失败 (理论上 renderer 已前置校验)- log.warn('setOverride failed', err);- reportMutationError(requestId, err, recordingId);- });+ window.electronAPI.appShortcuts.setOverride(recordingId, combo).catch((err: unknown) => {+ // main 侧校验兜底失败 (理论上 renderer 已前置校验)+ log.warn('setOverride failed', err);+ reportMutationError(requestId, err, recordingId);+ });cancel();};window.addEventListener('keydown', handler, true);@@ -217,25 +223,35 @@ export function KeyboardShortcutsSection() {});}, [beginShortcutAction, reportMutationError]);- const handleResetOne = useCallback((id: AppShortcutId) => {- const requestId = beginShortcutAction();- void window.electronAPI.appShortcuts.clearOverride(id).catch((err: unknown) => {- reportMutationError(requestId, err, id);- });- }, [beginShortcutAction, reportMutationError]);+ const handleResetOne = useCallback(+ (id: AppShortcutId) => {+ const requestId = beginShortcutAction();+ void window.electronAPI.appShortcuts.clearOverride(id).catch((err: unknown) => {+ reportMutationError(requestId, err, id);+ });+ },+ [beginShortcutAction, reportMutationError],+ );/** 删除绑定 = override 置 null, 该快捷键禁用 (显示"未设置")。 */- const handleDeleteOne = useCallback((id: AppShortcutId) => {- const requestId = beginShortcutAction();- setRecordingId(null);- void window.electronAPI.appShortcuts.setOverride(id, null).catch((err: unknown) => {- reportMutationError(requestId, err, id);- });- }, [beginShortcutAction, reportMutationError]);+ const handleDeleteOne = useCallback(+ (id: AppShortcutId) => {+ const requestId = beginShortcutAction();+ setRecordingId(null);+ void window.electronAPI.appShortcuts.setOverride(id, null).catch((err: unknown) => {+ reportMutationError(requestId, err, id);+ });+ },+ [beginShortcutAction, reportMutationError],+ );const iconButtonClass ='inline-flex h-[26px] w-[26px] items-center justify-center rounded-md text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-chip)] transition-colors';+ if (workLouderSettingsOpen) {+ return <WorkLouderCodexSettings onBack={() => setWorkLouderSettingsOpen(false)} />;+ }+return (<div className="flex flex-col gap-[14px]"><div className="flex items-center justify-between gap-3">@@ -254,6 +270,8 @@ export function KeyboardShortcutsSection() {</div>{globalError && <span className="text-12 text-[var(--error-fg)]">{globalError}</span>}+ <WorkLouderCodexEntryContainer onOpen={() => setWorkLouderSettingsOpen(true)} />+<divclassName={cn('flex flex-col rounded-xl p-5 gap-1',@@ -322,7 +340,10 @@ export function KeyboardShortcutsSection() {beginShortcutAction();setRecordingId(def.id);}}- className={cn(iconButtonClass, !def.rebindable && 'opacity-50 pointer-events-none')}+ className={cn(+ iconButtonClass,+ !def.rebindable && 'opacity-50 pointer-events-none',+ )}aria-label={t('settings.shortcuts.editAria', { name: itemLabel(def) })}title={t('settings.shortcuts.edit')}>@@ -333,7 +354,10 @@ export function KeyboardShortcutsSection() {type="button"disabled={!def.rebindable}onClick={() => handleDeleteOne(def.id)}- className={cn(iconButtonClass, !def.rebindable && 'opacity-50 pointer-events-none')}+ className={cn(+ iconButtonClass,+ !def.rebindable && 'opacity-50 pointer-events-none',+ )}aria-label={t('settings.shortcuts.deleteAria', { name: itemLabel(def) })}title={t('settings.shortcuts.delete')}>diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsxnew file mode 100644index 0000000000..36114fe46b--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx@@ -0,0 +1,530 @@+import type { CSSProperties, ReactNode } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { Search } from 'lucide-react';++import { Tip } from '@/components/ui/tooltip';+import { cn } from '@/lib/utils';++import {+ WORKLOUDER_CODEX_ENCODER_DETENT_DEG,+ WORKLOUDER_CODEX_KEYCAP_IDS,+ isWorkLouderCodexDoubleKeycap,+ workLouderCodexStickPreviewOffset,+ type WorkLouderCodexAgentSlotState,+ type WorkLouderCodexCommandSlot,+ type WorkLouderCodexKeycapId,+ type WorkLouderCodexLayout,+ type WorkLouderCodexPreviewPart,+} from '../../../shared/workLouderCodex';+import { WorkLouderCodexKeycapGlyph } from './WorkLouderCodexKeycapGlyphs';++/** A physical key location that can be opened by the layout editor. */+export type WorkLouderCodexAgentKey = `AG0${0 | 1 | 2 | 3 | 4 | 5}`;+/** The two parts of the board that are not keycaps but are still configurable. */+export type WorkLouderCodexControlPart = 'analog' | 'encoder';+export type WorkLouderCodexEditableKey =+ WorkLouderCodexCommandSlot | WorkLouderCodexAgentKey | WorkLouderCodexControlPart;++/** Hover copy for one part of the board: the legend, what it does, and why. */+export interface WorkLouderCodexKeyHint {+ /** Keycap legend or slot id, shown in bold on the first line. */+ legend: string;+ /** What the key is bound to. */+ name?: string | null;+ /** One line of detail under the name. */+ description?: string | null;+}++export interface WorkLouderCodexKeyboardLayoutProps {+ layout: WorkLouderCodexLayout;+ agentSlots: readonly WorkLouderCodexAgentSlotState[];+ disabled?: boolean;+ labels: {+ analogStick: string;+ encoder: string;+ indicator: string;+ };+ /** Hover copy per part; the board itself carries no lettering. */+ hintFor?(key: WorkLouderCodexEditableKey): WorkLouderCodexKeyHint | null;+ /**+ * Whether a part has anything of its own to edit. Task keys do not when all+ * six follow one shared rule, and a key that opens nothing should not look+ * like a button.+ */+ canEdit?(key: WorkLouderCodexEditableKey): boolean;+ onEditKeycap?(slot: WorkLouderCodexEditableKey): void;+ pressedParts?: ReadonlySet<WorkLouderCodexPreviewPart>;+ /** Cumulative encoder detents since the settings page opened. */+ encoderTurns?: number;+ /** Live stick report. Distance 0 keeps the cap centred. */+ analogStick?: { angle: number; distance: number } | null;+}++/**+ * Draws the Codex Micro as the physical object it is: a 4×4 board with the+ * analog stick in one corner and the encoder in the other.+ *+ * The real keycaps carry artwork and nothing else — no legends are printed on+ * them — so neither does this. What a key is bound to belongs in the hover+ * tooltip, and changing it belongs behind a click on the key itself, which is+ * why there are no separate per-key rows anywhere else in the panel.+ */+export function WorkLouderCodexKeyboardLayout({+ layout,+ agentSlots,+ disabled = false,+ labels,+ hintFor,+ canEdit,+ onEditKeycap,+ pressedParts,+ encoderTurns = 0,+ analogStick = null,+}: WorkLouderCodexKeyboardLayoutProps) {+ const editHandlerFor = (key: WorkLouderCodexEditableKey) =>+ canEdit && !canEdit(key) ? undefined : onEditKeycap;+ const agentKeys = Array.from(+ { length: 6 },+ (_, index) => `AG${index.toString().padStart(2, '0')}` as WorkLouderCodexAgentKey,+ );+ const microphoneSlots: WorkLouderCodexCommandSlot[] = layout.separateMicrophoneKeys+ ? ['ACT10', 'ACT11']+ : ['ACT10_ACT11'];++ const renderAgentKey = (slot: WorkLouderCodexAgentKey, index: number) => (+ <BoardPart+ key={slot}+ part={slot}+ hint={hintFor?.(slot) ?? { legend: slot, name: agentSlots[index]?.title ?? null }}+ disabled={disabled}+ pressed={pressedParts?.has(slot) ?? false}+ onEdit={editHandlerFor(slot)}+ className="bg-[var(--wl-agent-cap)] shadow-[var(--wl-agent-shadow)]"+ >+ {/* Agent keys wear no artwork — just the lit dot that marks a task slot. */}+ <span aria-hidden="true" className="block size-3 rounded-full bg-[var(--wl-agent-dot)]" />+ </BoardPart>+ );++ const renderCommandKey = (slot: WorkLouderCodexCommandSlot, className?: string) => {+ const keycapId = layout.slots[slot].keycapId;+ return (+ <BoardPart+ key={slot}+ part={slot}+ hint={hintFor?.(slot) ?? { legend: keycapId }}+ disabled={disabled}+ pressed={pressedParts?.has(slot) ?? false}+ onEdit={editHandlerFor(slot)}+ className={cn('bg-[var(--wl-command-cap)] shadow-[var(--wl-command-shadow)]', className)}+ >+ <WorkLouderCodexKeycapGlyph+ keycapId={keycapId}+ className="size-[22px] text-[var(--wl-command-glyph)]"+ />+ </BoardPart>+ );+ };++ return (+ <div+ className={cn(+ // The board is a fixed-size object, so it sizes to its keys rather than+ // stretching to whatever container it happens to sit in.+ 'flex w-fit flex-col gap-2 rounded-[20px] p-3',+ 'border border-[var(--wl-edge)] bg-[var(--wl-board)] shadow-[var(--wl-board-shadow)]',+ )}+ data-testid="worklouder-codex-keyboard-layout"+ style={WORKLOUDER_CODEX_BOARD_TOKENS}+ >+ {/* Row 1 — encoder, two agent keys, analog stick. */}+ <div className="grid grid-cols-[repeat(4,var(--wl-key-size))] gap-2">+ <BoardPart+ part="encoder"+ hint={hintFor?.('encoder') ?? { legend: labels.encoder }}+ disabled={disabled}+ pressed={pressedParts?.has('encoder') ?? false}+ onEdit={editHandlerFor('encoder')}+ rounded="full"+ className="bg-transparent shadow-none"+ >+ <Encoder label={labels.encoder} turns={encoderTurns} />+ </BoardPart>+ {agentKeys.slice(0, 2).map((slot, index) => renderAgentKey(slot, index))}+ <BoardPart+ part="analog"+ hint={hintFor?.('analog') ?? { legend: labels.analogStick }}+ disabled={disabled}+ pressed={pressedParts?.has('analog') ?? false}+ onEdit={editHandlerFor('analog')}+ className="bg-transparent shadow-none"+ >+ <AnalogStick label={labels.analogStick} analog={analogStick} />+ </BoardPart>+ </div>++ {/* Row 2 — the remaining four agent keys. */}+ <div className="grid grid-cols-[repeat(4,var(--wl-key-size))] gap-2">+ {agentKeys.slice(2).map((slot, index) => renderAgentKey(slot, index + 2))}+ </div>++ {/* Row 3 — the four command keys. */}+ <div className="grid grid-cols-[repeat(4,var(--wl-key-size))] gap-2">+ {(['ACT06', 'ACT07', 'ACT08', 'ACT09'] as const).map((slot) => renderCommandKey(slot))}+ </div>++ {/* Row 4 — status lights, the microphone key (double width unless split), Codex. */}+ <div className="grid grid-cols-[repeat(4,var(--wl-key-size))] gap-2">+ <div className="flex items-center gap-2 px-1" role="img" aria-label={labels.indicator}>+ <StatusLights />+ <span+ aria-hidden="true"+ className="size-8 rounded-full bg-[var(--wl-command-cap)] shadow-[var(--wl-command-shadow)]"+ />+ </div>+ {microphoneSlots.map((slot) =>+ renderCommandKey(slot, slot === 'ACT10_ACT11' ? 'col-span-2' : undefined),+ )}+ {renderCommandKey('ACT12')}+ </div>+ </div>+ );+}++/**+ * Board colours describe one physical object, so they are fixed values rather+ * than semantic tokens: the task keys ship with translucent white caps and the+ * command keys with dark ones, and that contrast has to survive in both themes.+ * Routing them through `--surface-*` inverted the board in dark mode, which is+ * exactly backwards from the hardware. Only the shell tracks the app theme.+ */+const WORKLOUDER_CODEX_BOARD_TOKENS = {+ // One key tall. Keys are square, so this is their width too; the double-width+ // microphone key spans two columns without getting any taller.+ '--wl-key-size': '64px',+ '--wl-board': 'var(--surface-chip)',+ // The rim reads as the edge of a case: a lit top edge, a shadow under it.+ '--wl-edge': 'var(--border-default)',+ '--wl-board-shadow':+ 'inset 0 1px 0 rgb(255 255 255 / 0.06), inset 0 0 0 1px rgb(0 0 0 / 0.12), 0 2px 8px rgb(0 0 0 / 0.22)',+ // Task keys: pale translucent caps, the lightest thing on the board.+ '--wl-agent-cap': 'rgb(214 214 214 / 0.92)',+ '--wl-agent-shadow':+ 'inset 0 0 0 1px rgb(255 255 255 / 0.5), inset 0 1px 2px rgb(255 255 255 / 0.6), 0 1px 3px rgb(0 0 0 / 0.35)',+ '--wl-agent-dot': '#8177c8',+ // Command keys: dark caps with light artwork.+ '--wl-command-cap': '#2a2b30',+ '--wl-command-shadow':+ 'inset 0 0 0 1px rgb(255 255 255 / 0.08), inset 0 1px 2px rgb(255 255 255 / 0.06), 0 1px 3px rgb(0 0 0 / 0.4)',+ '--wl-command-glyph': 'rgb(236 236 236)',+ // The stick: a well the same colour family as the task keys, so the dark+ // thumb cap reads against it instead of disappearing into a black square.+ '--wl-stick-housing': 'rgb(198 198 200 / 0.96)',+ '--wl-stick-housing-shadow':+ 'inset 0 1px 3px rgb(0 0 0 / 0.22), inset 0 0 0 1px rgb(0 0 0 / 0.08), 0 1px 0 rgb(255 255 255 / 0.35)',+ '--wl-stick-cap': '#2a2b30',+} as CSSProperties;++/**+ * One clickable part of the board. Everything the user can configure — keycaps,+ * agent keys, the stick, the encoder — renders through here so they share the+ * same press feedback, focus ring, and hover tooltip.+ */+function BoardPart({+ part,+ hint,+ children,+ className,+ disabled,+ pressed = false,+ onEdit,+ rounded = 'xl',+}: {+ part: WorkLouderCodexEditableKey;+ hint: WorkLouderCodexKeyHint;+ children: ReactNode;+ className?: string;+ disabled: boolean;+ pressed?: boolean;+ onEdit?: (part: WorkLouderCodexEditableKey) => void;+ rounded?: 'xl' | 'full';+}) {+ const label = [hint.legend, hint.name].filter(Boolean).join(' ');+ const classes = cn(+ 'flex min-w-0 items-center justify-center transition-transform',+ // Every part is one key tall. A double-width key spans two columns but must+ // not grow taller with them, so height is fixed rather than an aspect ratio.+ 'h-[var(--wl-key-size)]',+ rounded === 'full' ? 'aspect-square rounded-full' : 'rounded-xl',+ onEdit && !disabled && 'cursor-pointer active:scale-[0.97]',+ onEdit &&+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ pressed && 'scale-[0.97] ring-2 ring-[var(--focus-ring-soft)]',+ disabled && 'cursor-not-allowed opacity-60',+ className,+ );++ const key = onEdit ? (+ <button+ type="button"+ aria-label={label}+ aria-pressed={pressed}+ disabled={disabled}+ onClick={() => onEdit(part)}+ className={classes}+ >+ {children}+ </button>+ ) : (+ <div role="img" aria-label={label} data-pressed={pressed ? 'true' : undefined} className={classes}>+ {children}+ </div>+ );++ return (+ <Tip text={<KeyHint hint={hint} />} side="top">+ {key}+ </Tip>+ );+}++/** Three stacked lines: legend, what it runs, and what that means. */+function KeyHint({ hint }: { hint: WorkLouderCodexKeyHint }) {+ return (+ <span className="flex flex-col gap-0.5">+ <span className="font-semibold">{hint.legend}</span>+ {hint.name && <span>{hint.name}</span>}+ {hint.description && <span className="text-[var(--text-tertiary)]">{hint.description}</span>}+ </span>+ );+}++/**+ * The stick sits in a square well the size of a keycap, with a dark thumb+ * cap in the middle — it is not a bare circle like the encoder.+ */+function AnalogStick({+ label,+ analog,+}: {+ label: string;+ analog: { angle: number; distance: number } | null;+}) {+ const distance = analog?.distance ?? 0;+ const angle = analog?.angle ?? 0;+ const offset = workLouderCodexStickPreviewOffset(angle, distance);+ return (+ <span+ aria-hidden="true"+ title={label}+ data-stick-angle={distance > 0 ? String(angle) : undefined}+ data-stick-distance={String(distance)}+ className="relative flex size-full items-center justify-center rounded-xl bg-[var(--wl-stick-housing)] shadow-[var(--wl-stick-housing-shadow)]"+ >+ <span+ data-testid="worklouder-codex-stick-cap"+ className="block size-[68%] rounded-full bg-[var(--wl-stick-cap)] shadow-[inset_0_1px_1px_rgb(255_255_255/0.18),0_1px_2px_rgb(0_0_0/0.28)]"+ style={{ transform: `translate(${offset.x}px, ${offset.y}px)` }}+ />+ </span>+ );+}++/** The encoder is a round wheel that stands proud of the board. */+function Encoder({ label, turns }: { label: string; turns: number }) {+ // Firmware ENC_CW is visually counterclockwise on this board. CSS rotate()+ // is clockwise-positive, so the drawn knob has to flip the sign.+ return (+ <span+ aria-hidden="true"+ title={label}+ data-encoder-turns={String(turns)}+ className="block size-full overflow-hidden rounded-full bg-[var(--wl-command-cap)] shadow-[var(--wl-command-shadow)]"+ style={{ transform: `rotate(${-turns * WORKLOUDER_CODEX_ENCODER_DETENT_DEG}deg)` }}+ >+ <span className="relative block size-full bg-gradient-to-br from-white/[0.14] to-transparent">+ <span className="absolute left-1/2 top-[3px] h-[22%] w-[2px] -translate-x-1/2 rounded-full bg-white/55" />+ </span>+ </span>+ );+}++/** The board's three status LEDs. Decorative — they mirror hardware state. */+function StatusLights() {+ return (+ <span aria-hidden="true" className="flex flex-col gap-1">+ <span className="block size-1 rounded-full bg-[#4c8dff]" />+ <span className="block size-1 rounded-full bg-[var(--text-primary)]" />+ <span className="block size-1 rounded-full bg-[#e0b341]" />+ </span>+ );+}++export interface WorkLouderCodexKeycapPickerProps {+ open: boolean;+ slot: WorkLouderCodexCommandSlot | null;+ selectedKeycapId: WorkLouderCodexKeycapId | null;+ query: string;+ onQueryChange(query: string): void;+ onOpenChange(open: boolean): void;+ onSelect(keycapId: WorkLouderCodexKeycapId): void;+ onSave?(): void;+ onCancel?(): void;+ /** Extra controls shown under the grid, e.g. the action bound to this key. */+ children?: ReactNode;+ copy: {+ title: string;+ description: string;+ searchPlaceholder: string;+ close: string;+ cancel?: string;+ save?: string;+ };+}++/** Codex-style visual keycap library used by the keyboard layout editor. */+export function WorkLouderCodexKeycapPicker({+ open,+ slot,+ selectedKeycapId,+ query,+ onQueryChange,+ onOpenChange,+ onSelect,+ onSave,+ onCancel,+ children,+ copy,+}: WorkLouderCodexKeycapPickerProps) {+ const double = slot === 'ACT10_ACT11';+ const normalizedQuery = query.trim().toLowerCase();+ const keycaps = WORKLOUDER_CODEX_KEYCAP_IDS.filter((keycapId) => {+ if (double !== isWorkLouderCodexDoubleKeycap(keycapId)) return false;+ return normalizedQuery.length === 0 || keycapId.toLowerCase().includes(normalizedQuery);+ });++ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[10000] flex max-h-[min(760px,calc(100vh-48px))] w-[min(720px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)] focus:outline-none">+ <div className="flex items-start justify-between gap-4 px-6 pb-4 pt-6">+ <div className="min-w-0">+ <Dialog.Title className="text-18 font-medium leading-[1.3]">+ {copy.title}+ </Dialog.Title>+ <Dialog.Description className="mt-1 text-13 leading-[1.4] text-[var(--text-secondary)]">+ {copy.description}+ </Dialog.Description>+ </div>+ </div>+ <div className="px-6 pb-4">+ <label className="flex h-10 items-center gap-2 rounded-lg border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 focus-within:ring-2 focus-within:ring-[var(--focus-ring-soft)]">+ <Search size={16} className="text-[var(--text-tertiary)]" aria-hidden="true" />+ <input+ value={query}+ onChange={(event) => onQueryChange(event.currentTarget.value)}+ placeholder={copy.searchPlaceholder}+ autoFocus+ className="min-w-0 flex-1 bg-transparent text-13 text-[var(--settings-input-text)] outline-none placeholder:text-[var(--text-tertiary)]"+ />+ </label>+ </div>+ <div className="grid min-h-0 flex-1 grid-cols-6 gap-3 overflow-y-auto px-6 pb-6 max-md:grid-cols-4">+ {keycaps.map((keycapId) => (+ <button+ key={keycapId}+ type="button"+ aria-label={keycapId}+ aria-pressed={selectedKeycapId === keycapId}+ onClick={() => onSelect(keycapId)}+ className={cn(+ 'flex aspect-square min-w-0 flex-col items-center justify-center gap-2 rounded-xl border p-2 text-center transition-colors',+ 'bg-[var(--settings-theme-card-bg)] text-[var(--text-primary)] shadow-[0_1px_0_var(--settings-theme-card-border)]',+ selectedKeycapId === keycapId+ ? 'border-[var(--focus-ring)] ring-2 ring-[var(--focus-ring-soft)]'+ : 'border-[var(--settings-theme-card-border)] hover:border-[var(--focus-ring)] hover:bg-[var(--surface-chip)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ >+ <WorkLouderCodexKeycapGlyph keycapId={keycapId} className="size-[22px]" />+ <span className="max-w-full truncate text-11 font-medium tracking-wide">+ {keycapId}+ </span>+ </button>+ ))}+ </div>+ <div className="border-t border-[var(--border-default)] px-6 py-4">+ {children}+ <div className="mt-4 flex justify-end gap-2">+ <button+ type="button"+ onClick={() => {+ onCancel?.();+ onOpenChange(false);+ }}+ className="rounded-lg border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 py-2 text-12 font-medium text-[var(--settings-input-text)] transition-colors hover:bg-[var(--settings-menu-bg-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ >+ {copy.cancel ?? 'Cancel'}+ </button>+ <button+ type="button"+ disabled={!selectedKeycapId}+ onClick={() => {+ onSave?.();+ onOpenChange(false);+ }}+ className="rounded-lg bg-[var(--accent-cta-bg)] px-3 py-2 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-50"+ >+ {copy.save ?? 'Save'}+ </button>+ </div>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}++/** Shell for the non-keycap editors (agent keys, microphone, stick, encoder). */+export function WorkLouderCodexPartEditor({+ open,+ onOpenChange,+ title,+ description,+ closeLabel,+ children,+}: {+ open: boolean;+ onOpenChange(open: boolean): void;+ title: string;+ description: string;+ closeLabel: string;+ children: ReactNode;+}) {+ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[10000] flex max-h-[min(700px,calc(100vh-48px))] w-[min(520px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)] focus:outline-none">+ <div className="px-6 pb-4 pt-6">+ <Dialog.Title className="text-18 font-medium leading-[1.3]">{title}</Dialog.Title>+ <Dialog.Description className="mt-1 text-13 leading-[1.4] text-[var(--text-secondary)]">+ {description}+ </Dialog.Description>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-6 pb-4">{children}</div>+ <div className="flex justify-end border-t border-[var(--border-default)] px-6 py-4">+ <button+ type="button"+ onClick={() => onOpenChange(false)}+ className="rounded-lg bg-[var(--accent-cta-bg)] px-3 py-2 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ >+ {closeLabel}+ </button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsxnew file mode 100644index 0000000000..71cb01e606--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx@@ -0,0 +1,564 @@+/**+ * Codex Micro keycap glyphs.+ *+ * The artwork is a 1:1 copy of the glyphs the Codex desktop client draws on its+ * own keycaps, so a key here looks exactly like the same key over there. Do not+ * swap these for lookalikes from a generic icon set: several of them (codex,+ * openai, worktree, confetti, brain) have no equivalent anywhere else.+ */+import type { ReactElement, SVGProps } from 'react';++import type { WorkLouderCodexKeycapId } from '../../../shared/workLouderCodex';++type GlyphProps = SVGProps<SVGSVGElement>;++function AllProductsGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M7.94556 14.0276C7.9455 12.9376 7.06204 12.054 5.97192 12.054C4.88191 12.0541 3.99835 12.9376 3.99829 14.0276C3.99829 15.1177 4.88188 16.0012 5.97192 16.0013C7.06207 16.0013 7.94556 15.1178 7.94556 14.0276ZM16.0012 14.0276C16.0012 12.9376 15.1177 12.054 14.0276 12.054C12.9375 12.0541 12.054 12.9376 12.054 14.0276C12.054 15.1178 12.9375 16.0012 14.0276 16.0013C15.1177 16.0013 16.0012 15.1178 16.0012 14.0276ZM7.94556 5.97198C7.94544 4.88194 7.062 3.99835 5.97192 3.99835C4.88195 3.99847 3.99841 4.88201 3.99829 5.97198C3.99829 7.06206 4.88187 7.9455 5.97192 7.94562C7.06207 7.94562 7.94556 7.06213 7.94556 5.97198ZM16.0012 5.97198C16.0011 4.88194 15.1177 3.99835 14.0276 3.99835C12.9376 3.99841 12.0541 4.88197 12.054 5.97198C12.054 7.0621 12.9375 7.94556 14.0276 7.94562C15.1177 7.94562 16.0012 7.06213 16.0012 5.97198ZM9.27563 14.0276C9.27563 15.8523 7.79661 17.3314 5.97192 17.3314C4.14734 17.3312 2.66821 15.8523 2.66821 14.0276C2.66827 12.2031 4.14737 10.7241 5.97192 10.7239C7.79657 10.7239 9.27558 12.203 9.27563 14.0276ZM17.3313 14.0276C17.3313 15.8523 15.8523 17.3314 14.0276 17.3314C12.203 17.3313 10.7239 15.8523 10.7239 14.0276C10.7239 12.203 12.203 10.724 14.0276 10.7239C15.8522 10.7239 17.3312 12.203 17.3313 14.0276ZM9.27563 5.97198C9.27563 7.79667 7.79661 9.2757 5.97192 9.2757C4.14734 9.27558 2.66821 7.7966 2.66821 5.97198C2.66833 4.14747 4.14741 2.66839 5.97192 2.66827C7.79654 2.66827 9.27552 4.1474 9.27563 5.97198ZM17.3313 5.97198C17.3313 7.79667 15.8523 9.2757 14.0276 9.2757C12.203 9.27564 10.7239 7.79664 10.7239 5.97198C10.724 4.14743 12.203 2.66833 14.0276 2.66827C15.8522 2.66827 17.3312 4.1474 17.3313 5.97198Z"+ fill="currentColor"+ />+ </svg>+ );+}++function BrainMediumGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M3.57746 9.14006L4.04387 9.61406C4.17091 9.48906 4.24246 9.31829 4.24246 9.14006C4.24246 8.96183 4.17091 8.79106 4.04387 8.66605L3.57746 9.14006ZM5.15265 5.1067L5.24716 5.76495C5.576 5.71774 5.81955 5.43508 5.81764 5.10288L5.15265 5.1067ZM5.15249 5.07797H4.48747L4.4875 5.08179L5.15249 5.07797ZM14.8475 5.07797L15.5125 5.08179V5.07797H14.8475ZM14.8473 5.1067L14.1824 5.10288C14.1805 5.43509 14.424 5.71774 14.7528 5.76495L14.8473 5.1067ZM16.4225 9.14006L15.9561 8.66605C15.8291 8.79106 15.7575 8.96183 15.7575 9.14006C15.7575 9.31829 15.8291 9.48906 15.9561 9.61406L16.4225 9.14006ZM15.4449 14.6301L15.2085 14.0085C14.9942 14.09 14.837 14.2762 14.7925 14.5011L15.4449 14.6301ZM4.5551 14.6301L5.20748 14.5011C5.16302 14.2762 5.00581 14.09 4.79149 14.0085L4.5551 14.6301ZM3.08743 8.71947C2.82511 8.97653 2.82084 9.39756 3.07789 9.65988C3.33494 9.9222 3.75597 9.92647 4.01829 9.66941L3.55286 9.19445L3.08743 8.71947ZM5.52606 9.05389C5.89333 9.05389 6.19106 8.75616 6.19106 8.38889C6.19106 8.02162 5.89333 7.72389 5.52606 7.72389V8.38889V9.05389ZM17.9123 12.0141C17.9123 11.6468 17.6146 11.3491 17.2473 11.3491C16.88 11.3491 16.5823 11.6468 16.5823 12.0141H17.2473H17.9123ZM14.4279 14.1686C14.0606 14.1686 13.7629 14.4663 13.7629 14.8336C13.7629 15.2008 14.0606 15.4986 14.4279 15.4986V14.8336V14.1686ZM7.86868 11.5445C7.53694 11.3869 7.14026 11.5281 6.98267 11.8598C6.82507 12.1915 6.96625 12.5882 7.29799 12.7458L7.58333 12.1452L7.86868 11.5445ZM10.2853 12.7458C10.6171 12.5882 10.7583 12.1915 10.6007 11.8598C10.4431 11.5281 10.0464 11.3869 9.71465 11.5445L10 12.1452L10.2853 12.7458ZM15.4994 5.16667C15.4994 4.7994 15.2017 4.50167 14.8344 4.50167C14.4671 4.50167 14.1694 4.7994 14.1694 5.16667H14.8344H15.4994ZM13.1888 6.7401C12.8592 6.90206 12.7232 7.30057 12.8852 7.6302C13.0472 7.95983 13.4457 8.09576 13.7753 7.9338L13.482 7.33695L13.1888 6.7401ZM11.3077 10.009C11.675 10.009 11.9727 9.71123 11.9727 9.34396C11.9727 8.97669 11.675 8.67896 11.3077 8.67896V9.34396V10.009ZM5.15249 5.07797L4.4875 5.08179L4.48766 5.11052L5.15265 5.1067L5.81764 5.10288L5.81747 5.07414L5.15249 5.07797ZM14.8473 5.1067L15.5123 5.11052L15.5125 5.08179L14.8475 5.07797L14.1825 5.07415L14.1824 5.10288L14.8473 5.1067ZM4.5551 14.6301L3.90272 14.759C4.25542 16.5436 5.64061 17.7324 7.12679 17.8958C7.8764 17.9783 8.6507 17.7972 9.29938 17.2972C9.94755 16.7975 10.4211 16.0184 10.6493 14.9879L10 14.8441L9.35073 14.7003C9.17613 15.4888 8.84234 15.9702 8.48741 16.2438C8.133 16.517 7.70844 16.6218 7.27219 16.5738C6.38665 16.4764 5.45217 15.7392 5.20748 14.5011L4.5551 14.6301ZM10 14.8441L9.35073 14.9879C9.57891 16.0184 10.0524 16.7976 10.7006 17.2972C11.3493 17.7972 12.1236 17.9783 12.8732 17.8958C14.3594 17.7324 15.7446 16.5436 16.0973 14.759L15.4449 14.6301L14.7925 14.5011C14.5478 15.7392 13.6134 16.4764 12.7278 16.5738C12.2916 16.6218 11.867 16.517 11.5126 16.2438C11.1577 15.9702 10.8239 15.4888 10.6493 14.7003L10 14.8441ZM3.57746 9.14006L3.11104 8.66605C2.18352 9.57872 1.94758 11.0213 2.15576 12.2556C2.36354 13.4874 3.06106 14.7733 4.31871 15.2516L4.5551 14.6301L4.79149 14.0085C4.14378 13.7622 3.63213 13.0119 3.46724 12.0343C3.30276 11.0592 3.53068 10.119 4.04387 9.61406L3.57746 9.14006ZM5.15265 5.1067L5.05814 4.44845C3.73273 4.63874 2.69968 5.36578 2.28207 6.39936C1.85523 7.45578 2.14106 8.65961 3.11104 9.61406L3.57746 9.14006L4.04387 8.66605C3.39282 8.02542 3.32155 7.37692 3.51522 6.89761C3.71811 6.39545 4.28317 5.90335 5.24716 5.76495L5.15265 5.1067ZM16.4225 9.14006L16.889 9.61406C17.8589 8.65961 18.1448 7.45578 17.7179 6.39936C17.3003 5.36578 16.2673 4.63874 14.9419 4.44845L14.8473 5.1067L14.7528 5.76495C15.7168 5.90335 16.2819 6.39545 16.4848 6.89761C16.6785 7.37692 16.6072 8.02543 15.9561 8.66605L16.4225 9.14006ZM15.4449 14.6301L15.6813 15.2516C16.9389 14.7733 17.6365 13.4874 17.8442 12.2556C18.0524 11.0213 17.8165 9.57872 16.889 8.66605L16.4225 9.14006L15.9561 9.61406C16.4693 10.119 16.6972 11.0592 16.5328 12.0343C16.3679 13.0119 15.8562 13.7622 15.2085 14.0085L15.4449 14.6301ZM14.8475 5.07797H15.5125C15.5125 4.10684 15.1294 3.33433 14.5217 2.81587C13.9281 2.30941 13.1595 2.07735 12.4167 2.08519C11.6737 2.09304 10.9081 2.34139 10.3186 2.85899C9.71615 3.38803 9.335 4.16711 9.335 5.14295H10H10.665C10.665 4.53836 10.8898 4.12744 11.1962 3.85839C11.5156 3.57791 11.962 3.42007 12.4308 3.41512C12.8999 3.41017 13.3432 3.55869 13.6585 3.82767C13.9597 4.08466 14.1825 4.48245 14.1825 5.07797H14.8475ZM10 5.14295H10.665C10.665 4.16711 10.2839 3.38803 9.68135 2.85899C9.09187 2.34138 8.32633 2.09304 7.58327 2.08519C6.84051 2.07735 6.07193 2.30941 5.4783 2.81587C4.87061 3.33433 4.48749 4.10684 4.48749 5.07797H5.15249H5.81749C5.81749 4.48245 6.0403 4.08466 6.34152 3.82767C6.6568 3.55869 7.1001 3.41016 7.56922 3.41512C8.03803 3.42007 8.48437 3.57791 8.8038 3.85839C9.11021 4.12744 9.335 4.53836 9.335 5.14295H10ZM3.55286 9.19445L4.01829 9.66941C4.40755 9.28797 4.93881 9.05389 5.52606 9.05389V8.38889V7.72389C4.57687 7.72389 3.71521 8.1043 3.08743 8.71947L3.55286 9.19445ZM17.2473 12.0141H16.5823C16.5823 13.204 15.6177 14.1686 14.4279 14.1686V14.8336V15.4986C16.3523 15.4986 17.9123 13.9385 17.9123 12.0141H17.2473ZM8.79167 12.4165V11.7515C8.46002 11.7515 8.14763 11.677 7.86868 11.5445L7.58333 12.1452L7.29799 12.7458C7.75149 12.9613 8.25847 13.0815 8.79167 13.0815V12.4165ZM10 12.1452L9.71465 11.5445C9.4357 11.677 9.12331 11.7515 8.79167 11.7515V12.4165V13.0815C9.32487 13.0815 9.83184 12.9613 10.2853 12.7458L10 12.1452ZM14.8344 5.16667H14.1694C14.1694 5.85626 13.771 6.45405 13.1888 6.7401L13.482 7.33695L13.7753 7.9338C14.7951 7.43272 15.4994 6.38256 15.4994 5.16667H14.8344ZM10 5.14295H9.335V9.99353H10H10.665V5.14295H10ZM10 9.99353H9.335V14.8441H10H10.665V9.99353H10ZM10 9.99353L10.5453 10.3741C10.566 10.3445 10.6529 10.245 10.7997 10.1558C10.9392 10.0709 11.1103 10.009 11.3077 10.009V9.34396V8.67896C10.3455 8.67896 9.69036 9.27525 9.45467 9.61295L10 9.99353Z"+ fill="currentColor"+ />+ </svg>+ );+}++function BrainOutlineGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M10 5.14295V14.8441M10 5.14295C10 1.98209 14.8475 1.94468 14.8475 5.07797L14.8473 5.1067C17.1367 5.43539 18.0436 7.54498 16.4225 9.14006C17.8633 10.5577 17.3503 13.9054 15.4449 14.6301C14.8475 17.6527 10.8056 18.4821 10 14.8441M10 5.14295C10 1.98209 5.15249 1.94468 5.15249 5.07797L5.15265 5.1067C2.86325 5.43539 1.95642 7.54498 3.57746 9.14006C2.13674 10.5577 2.64974 13.9054 4.5551 14.6301C5.15249 17.6527 9.19444 18.4821 10 14.8441"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function BranchGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <circle cx="5.4165" cy="5" r="1.875" stroke="currentColor" strokeWidth="1.33" />+ <circle cx="5.4165" cy="15" r="1.875" stroke="currentColor" strokeWidth="1.33" />+ <circle cx="14.5833" cy="5" r="1.875" stroke="currentColor" strokeWidth="1.33" />+ <path+ d="M5.4165 6.66664V13.3333"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinejoin="round"+ />+ <path+ d="M5.41658 12.5V11.6667C5.41658 10.7462 6.16278 10 7.08325 10H12.9166C13.8371 10 14.5833 9.25381 14.5833 8.33333V7.5"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function BugGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M10 12.083C10.6903 12.083 11.25 12.8295 11.25 13.75C11.25 14.6705 10.6904 15.417 10 15.417C9.30964 15.417 8.75 14.6705 8.75 13.75C8.75002 12.8295 9.30965 12.083 10 12.083Z"+ fill="currentColor"+ />+ <path+ d="M7.91699 9.16699C8.60707 9.16713 9.16677 9.63296 9.16699 10.208C9.16699 10.7832 8.60721 11.2499 7.91699 11.25C7.22664 11.25 6.66699 10.7833 6.66699 10.208C6.66722 9.63287 7.22677 9.16699 7.91699 9.16699Z"+ fill="currentColor"+ />+ <path+ d="M12.083 9.16699C12.7732 9.16699 13.3328 9.63287 13.333 10.208C13.333 10.7833 12.7734 11.25 12.083 11.25C11.3928 11.2499 10.833 10.7832 10.833 10.208C10.8332 9.63296 11.3929 9.16713 12.083 9.16699Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M14.9355 1.83496C15.8895 1.83496 16.5003 2.36544 16.8438 2.83887C17.0139 3.07346 17.1281 3.30439 17.1992 3.47461C17.235 3.56037 17.2605 3.6336 17.2783 3.6875C17.2872 3.71448 17.2948 3.73684 17.2998 3.75391C17.3023 3.76229 17.3041 3.76965 17.3057 3.77539C17.3064 3.7782 17.307 3.78106 17.3076 3.7832C17.3079 3.7842 17.3084 3.78528 17.3086 3.78613L17.3096 3.78809C17.3062 3.78919 17.261 3.8011 16.666 3.95801L16.417 4.02344L17.3096 3.78809C17.403 4.1431 17.1909 4.50793 16.8359 4.60156C16.4809 4.695 16.1171 4.48291 16.0234 4.12793V4.12988L16.0244 4.13086V4.13281C16.0243 4.13251 16.0239 4.13143 16.0234 4.12988C16.0222 4.12556 16.0198 4.11621 16.0156 4.10352C16.0071 4.07776 15.9927 4.03673 15.9717 3.98633C15.9286 3.88318 15.8617 3.74891 15.7676 3.61914C15.5822 3.36365 15.3274 3.16504 14.9355 3.16504C14.1975 3.16516 13.658 3.58082 13.2207 4.30273C13.1067 4.491 13.0038 4.69355 12.9111 4.9043C15.4971 5.96132 17.3311 8.38367 17.3311 11.25C17.3311 15.1087 14.0079 18.1649 10 18.165C5.99205 18.1649 2.66797 15.1087 2.66797 11.25C2.66797 8.38418 4.50167 5.96162 7.08691 4.9043C6.99433 4.69371 6.89228 4.49087 6.77832 4.30273C6.34094 3.58089 5.80158 3.16504 5.06348 3.16504C4.6718 3.16524 4.41678 3.36363 4.23145 3.61914C4.13731 3.74896 4.07043 3.88319 4.02734 3.98633C4.00627 4.0368 3.99189 4.07779 3.9834 4.10352C3.97945 4.11549 3.97693 4.12438 3.97559 4.12891C3.97559 4.12887 3.97591 4.12831 3.97461 4.12793C3.88076 4.48278 3.51806 4.69518 3.16309 4.60156C2.80838 4.5077 2.597 4.14392 2.69043 3.78906L3.54688 4.01465C3.48502 3.99833 3.41396 3.97936 3.33301 3.95801C2.73598 3.80055 2.69337 3.79012 2.69043 3.78906V3.78613C2.69066 3.78527 2.69112 3.78423 2.69141 3.7832C2.69199 3.78105 2.69257 3.77824 2.69336 3.77539C2.69496 3.76964 2.69771 3.76233 2.7002 3.75391C2.70521 3.73688 2.71184 3.71438 2.7207 3.6875C2.73849 3.63356 2.76492 3.56051 2.80078 3.47461C2.87184 3.30444 2.98518 3.07343 3.15527 2.83887C3.49861 2.36548 4.10973 1.83519 5.06348 1.83496C6.44053 1.83496 7.34381 2.66973 7.91602 3.61426C8.08809 3.89836 8.23399 4.20218 8.3623 4.50977C8.88978 4.39594 9.43839 4.33498 10 4.33496C10.5611 4.33498 11.1087 4.39615 11.6357 4.50977C11.7641 4.20208 11.9109 3.89845 12.083 3.61426C12.6552 2.66975 13.5586 1.83509 14.9355 1.83496ZM10 5.66504C9.58617 5.66506 9.18255 5.70388 8.79395 5.77734C8.79964 5.79796 8.80596 5.8184 8.81152 5.83887L8.98145 6.51758L8.99805 6.65039C9.00594 6.95974 8.79567 7.24216 8.48242 7.31445C8.16932 7.38653 7.85695 7.22473 7.72852 6.94336L7.68457 6.81641L7.52539 6.17871C7.52388 6.17318 7.52202 6.16765 7.52051 6.16211C5.42918 7.0461 3.99805 9.01126 3.99805 11.25C3.99805 14.2946 6.64444 16.8348 10 16.835C13.3556 16.8348 16.001 14.2946 16.001 11.25C16.001 9.01078 14.5696 7.04582 12.4775 6.16211C12.4166 6.38459 12.3633 6.60491 12.3145 6.81641L12.2715 6.94336C12.143 7.22493 11.8299 7.38675 11.5166 7.31445C11.1592 7.23167 10.9363 6.87512 11.0186 6.51758L11.1875 5.83887C11.193 5.81848 11.1984 5.79788 11.2041 5.77734C10.816 5.70407 10.4133 5.66506 10 5.66504Z"+ fill="currentColor"+ />+ </svg>+ );+}++function CheckCircleGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M12.1599 7.63617C12.3713 7.33596 12.7863 7.26372 13.0866 7.47504C13.3867 7.68642 13.4589 8.10153 13.2477 8.40179L9.28876 14.0268C9.17264 14.1917 8.98808 14.2954 8.7868 14.308C8.61044 14.319 8.43764 14.2592 8.30634 14.144L8.25262 14.0912L6.16962 11.7993L6.08954 11.6918C5.93136 11.4259 5.97666 11.0761 6.21454 10.8598C6.45225 10.6439 6.80379 10.6326 7.05341 10.8149L7.15399 10.9047L8.67841 12.5815L12.1599 7.63617Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M9.99506 2.81226C14.3664 2.81226 17.9101 6.35596 17.9101 10.7273C17.9101 15.0986 14.3664 18.6423 9.99506 18.6423C5.62372 18.6423 2.08002 15.0986 2.08002 10.7273C2.08002 6.35596 5.62372 2.81226 9.99506 2.81226ZM9.99506 4.14233C6.35826 4.14233 3.4101 7.0905 3.4101 10.7273C3.4101 14.3641 6.35826 17.3123 9.99506 17.3123C13.6319 17.3123 16.58 14.3641 16.58 10.7273C16.58 7.0905 13.6319 4.14233 9.99506 4.14233Z"+ fill="currentColor"+ />+ </svg>+ );+}++function ClockGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M8 4.2168C8.24838 4.21697 8.44922 4.41857 8.44922 4.66699V7.8623C8.44911 8.06977 8.36732 8.26924 8.2207 8.41602L6.65137 9.98535C6.4756 10.1607 6.19025 10.161 6.01465 9.98535C5.83909 9.80975 5.83934 9.52439 6.01465 9.34863L7.5498 7.81348V4.66699C7.5498 4.41862 7.75168 4.21704 8 4.2168Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M8 1.5498C11.5622 1.5498 14.4502 4.43776 14.4502 8C14.4502 11.5622 11.5622 14.4502 8 14.4502C4.43776 14.4502 1.5498 11.5622 1.5498 8C1.5498 4.43776 4.43776 1.5498 8 1.5498ZM8 2.4502C4.93482 2.4502 2.4502 4.93482 2.4502 8C2.4502 11.0652 4.93482 13.5498 8 13.5498C11.0652 13.5498 13.5498 11.0652 13.5498 8C13.5498 4.93482 11.0652 2.4502 8 2.4502Z"+ fill="currentColor"+ />+ </svg>+ );+}++function CloudUploadGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M15.0001 14.9967C16.841 14.9967 18.3334 13.5044 18.3334 11.6634C18.3334 9.82246 16.841 8.33008 15.0001 8.33008C15.0001 5.56865 12.7615 3.33008 10.0001 3.33008C7.80904 3.33008 5.94715 4.73939 5.27148 6.70098C3.23605 6.97537 1.66675 8.71946 1.66675 10.8301C1.66675 12.8458 3.09817 14.5273 5 14.9134"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d="M7.5 12.5L10 10L12.5 12.5"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d="M10 10.5V17"+ stroke="currentColor"+ strokeWidth="1.33"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function CodexGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M13.333 11.418C13.7002 11.418 13.9978 11.7159 13.998 12.083C13.998 12.4503 13.7003 12.748 13.333 12.748H10.833C10.4657 12.748 10.168 12.4503 10.168 12.083C10.1682 11.7159 10.4659 11.418 10.833 11.418H13.333Z"+ fill="currentColor"+ />+ <path+ d="M6.74121 7.34668C7.0561 7.15796 7.46442 7.26036 7.65332 7.5752L8.90332 9.6582C9.02949 9.86874 9.02961 10.1323 8.90332 10.3428L7.65332 12.4258C7.46441 12.7403 7.05597 12.8427 6.74121 12.6543C6.42637 12.4654 6.32396 12.0561 6.5127 11.7412L7.55664 10L6.5127 8.25879C6.324 7.94395 6.4265 7.53562 6.74121 7.34668Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M9.00195 1.75C10.1157 1.75021 11.1362 2.15467 11.9238 2.82227C12.1849 2.77516 12.455 2.74903 12.7295 2.74902C15.2262 2.74978 17.2507 4.77449 17.251 7.27148C17.2509 7.54581 17.2238 7.81473 17.1768 8.0752C17.8448 8.86317 18.2499 9.88479 18.25 10.999C18.2496 12.9609 16.9996 14.6284 15.2549 15.2549C14.6285 16.9998 12.9608 18.2497 10.999 18.25C9.88486 18.25 8.86411 17.8448 8.07617 17.1768C7.8155 17.2239 7.54592 17.2509 7.27148 17.251C4.77445 17.2507 2.7504 15.2257 2.75 12.7285C2.75003 12.4539 2.77608 12.1848 2.82324 11.9238C2.20237 11.1913 1.80895 10.2574 1.75684 9.23438L1.75 9.00098C1.75022 7.03932 2.99952 5.36992 4.74414 4.74316C5.37104 2.99851 7.04034 1.75002 9.00195 1.75ZM9.00195 3.07812C7.52474 3.07814 6.27967 4.08156 5.91504 5.44531C5.85362 5.67419 5.67418 5.85363 5.44531 5.91504C4.08208 6.27984 3.07836 7.52408 3.07812 9.00098C3.07826 9.88321 3.43594 10.682 4.01465 11.2607C4.1816 11.4283 4.24663 11.6728 4.18555 11.9014C4.11505 12.1653 4.07719 12.4429 4.07715 12.7285C4.07755 14.4925 5.50753 15.9225 7.27148 15.9229C7.55712 15.9228 7.83548 15.886 8.09961 15.8154L8.18652 15.7979C8.38833 15.7722 8.59297 15.8403 8.73926 15.9863C9.31801 16.5649 10.1168 16.9218 10.999 16.9219C12.4759 16.9216 13.7203 15.9183 14.085 14.5547L14.1133 14.4707C14.1918 14.2821 14.3542 14.1386 14.5547 14.085C15.9181 13.7203 16.9225 12.4758 16.9229 10.999C16.9228 10.1168 16.5648 9.31802 15.9863 8.73926C15.819 8.57175 15.7544 8.3274 15.8154 8.09863C15.886 7.83454 15.9238 7.5568 15.9238 7.27148C15.9235 5.50751 14.4924 4.07762 12.7285 4.07715C12.4424 4.0772 12.164 4.11412 11.9004 4.18457C11.672 4.24541 11.4282 4.18048 11.2607 4.01367C10.7183 3.47141 9.98306 3.12271 9.16699 3.08105L9.00195 3.07812Z"+ fill="currentColor"+ />+ </svg>+ );+}++function ComposeGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M6.33325 1.88379C6.58178 1.88379 6.78345 2.08546 6.78345 2.33398C6.78328 2.58237 6.58168 2.78418 6.33325 2.78418H4.66626C3.62638 2.78435 2.78362 3.62711 2.78345 4.66699V11.334C2.78361 12.3739 3.62637 13.2176 4.66626 13.2178H11.3333C12.3733 13.2178 13.2169 12.374 13.217 11.334V9.66699C13.2172 9.41872 13.418 9.21795 13.6663 9.21777C13.9147 9.21777 14.1163 9.41861 14.1165 9.66699V11.334C14.1163 12.871 12.8703 14.1172 11.3333 14.1172H4.66626C3.12932 14.117 1.88322 12.8709 1.88306 11.334V4.66699C1.88323 3.13006 3.12933 1.88396 4.66626 1.88379H6.33325Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M10.8948 2.375C11.6494 1.63227 12.8628 1.63698 13.6116 2.38574C14.362 3.13643 14.3637 4.35266 13.6165 5.10644L9.36353 9.39355C9.01402 9.74579 8.56977 9.98985 8.08521 10.0967L6.17603 10.5166C5.74813 10.6107 5.36686 10.2296 5.46118 9.80176L5.88208 7.89746C5.98978 7.4105 6.23578 6.96428 6.59106 6.61426L10.8948 2.375ZM12.9749 3.02148C12.5756 2.62258 11.9289 2.62086 11.5266 3.0166L7.2229 7.25586C6.99148 7.4839 6.83116 7.77457 6.76099 8.0918L6.44165 9.53711L7.89185 9.21777C8.20744 9.14811 8.49721 8.98919 8.72485 8.75976L12.9778 4.47266C13.3759 4.07066 13.375 3.42164 12.9749 3.02148Z"+ fill="currentColor"+ />+ </svg>+ );+}++function ConfettiGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M5.27916 5.50684C5.70791 4.58738 6.94757 4.34064 7.6942 5.08691L14.9129 12.3057L15.0487 12.4609C15.6235 13.2137 15.3513 14.3204 14.493 14.7207L14.3006 14.7949L3.79967 18.0771C2.64613 18.4371 1.56223 17.3528 1.92272 16.1992L5.20397 5.69922L5.27916 5.50684ZM3.19225 16.5967C3.15211 16.726 3.27383 16.8477 3.40318 16.8076L9.08873 15.0293L4.96861 10.9092L3.19225 16.5967ZM6.75377 6.02734C6.6755 5.9494 6.54869 5.96802 6.49303 6.05469L6.4735 6.0957L5.41393 9.4834C5.43241 9.49826 5.4524 9.5122 5.46959 9.5293L10.4696 14.5293L10.5145 14.584L13.9032 13.5254L13.9452 13.5068C14.0195 13.459 14.0437 13.359 13.9999 13.2822L13.9725 13.2461L6.75377 6.02734Z"+ fill="currentColor"+ />+ <path+ d="M17.0829 8.75C17.7732 8.75 18.3329 9.30964 18.3329 10C18.3329 10.6904 17.7732 11.25 17.0829 11.25C16.3927 11.2498 15.8329 10.6902 15.8329 10C15.8329 9.30976 16.3927 8.75019 17.0829 8.75Z"+ fill="currentColor"+ />+ <path+ d="M17.4999 2.66797C17.8669 2.66814 18.1647 2.96599 18.1649 3.33301C18.1649 6.00146 16.0013 8.16504 13.3329 8.16504C12.9659 8.16485 12.668 7.867 12.6678 7.5C12.668 7.13299 12.9659 6.83515 13.3329 6.83496C15.2668 6.83496 16.8348 5.26692 16.8348 3.33301C16.835 2.966 17.1329 2.66816 17.4999 2.66797Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M11.6669 1.00195C12.9545 1.00213 13.9979 2.04635 13.9979 3.33398C13.9976 4.62133 12.9542 5.66486 11.6669 5.66504C10.3794 5.66498 9.33517 4.6214 9.33482 3.33398C9.33482 2.04628 10.3792 1.00201 11.6669 1.00195ZM11.6669 2.33203C11.1137 2.33209 10.6649 2.78082 10.6649 3.33398C10.6652 3.88686 11.1139 4.3349 11.6669 4.33496C12.2197 4.33478 12.6675 3.88679 12.6678 3.33398C12.6678 2.78089 12.2199 2.33221 11.6669 2.33203Z"+ fill="currentColor"+ />+ </svg>+ );+}++function DiffGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path d="M12.084 12.668a.666.666 0 0 1 0 1.33H7.917a.665.665 0 1 1 0-1.33h4.167ZM10 5.585c.367 0 .665.298.665.665v1.418h1.419a.666.666 0 0 1 0 1.33h-1.419v1.419a.666.666 0 0 1-1.33 0V8.998H7.917a.665.665 0 0 1 0-1.33h1.418V6.25c0-.367.298-.665.665-.665Z" />+ <path+ fillRule="evenodd"+ d="M12.667 2.668c.689 0 1.246 0 1.696.036.458.038.865.117 1.242.309a3.163 3.163 0 0 1 1.382 1.383c.192.377.272.783.309 1.24.037.45.036 1.008.036 1.697v5.333c0 .689 0 1.246-.036 1.696-.037.458-.117.865-.309 1.242a3.166 3.166 0 0 1-1.382 1.382c-.377.192-.784.271-1.242.309-.45.037-1.007.036-1.696.036H7.334c-.689 0-1.246 0-1.696-.036-.458-.038-.864-.117-1.24-.309a3.166 3.166 0 0 1-1.384-1.383c-.192-.376-.271-.783-.309-1.24-.037-.45-.036-1.008-.036-1.697V7.333c0-.689 0-1.246.036-1.696.038-.458.117-.864.309-1.24a3.17 3.17 0 0 1 1.383-1.384c.377-.192.783-.272 1.24-.309.45-.037 1.008-.036 1.697-.036h5.333Zm-5.333 1.33c-.71 0-1.204.001-1.588.032-.375.03-.587.088-.745.168A1.836 1.836 0 0 0 4.199 5c-.08.158-.137.37-.168.745C4 6.13 4 6.622 4 7.333v5.333c0 .71.001 1.204.032 1.588.03.375.088.587.168.745.176.345.457.627.802.803.158.08.37.137.745.168.384.031.877.031 1.588.031h5.333c.71 0 1.204 0 1.588-.031.375-.031.587-.088.745-.168a1.84 1.84 0 0 0 .803-.803c.08-.158.137-.37.168-.745.031-.383.031-.877.031-1.588V7.333c0-.71 0-1.204-.031-1.588-.031-.375-.088-.587-.168-.745A1.838 1.838 0 0 0 15 4.198c-.158-.08-.37-.137-.745-.168-.384-.031-.877-.032-1.588-.032H7.334Z"+ clipRule="evenodd"+ />+ </svg>+ );+}++function DownloadGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M2.66831 12.6664V12.5004C2.66831 12.1331 2.96607 11.8353 3.33334 11.8353C3.70061 11.8353 3.99838 12.1331 3.99838 12.5004V12.6664C3.99838 13.3773 3.99929 13.8708 4.03061 14.2543C4.0613 14.6299 4.11812 14.8414 4.19858 14.9994L4.26889 15.1263C4.4452 15.4138 4.69823 15.6482 5.00034 15.8021L5.13022 15.8578C5.27399 15.9092 5.4635 15.9471 5.74545 15.9701C6.12897 16.0014 6.62231 16.0013 7.33334 16.0013H12.6664C13.3772 16.0013 13.8708 16.0014 14.2542 15.9701C14.6296 15.9394 14.8414 15.8825 14.9994 15.8021L15.1263 15.7308C15.4137 15.5545 15.6482 15.3014 15.8021 14.9994L15.8578 14.8695C15.9092 14.7258 15.947 14.5361 15.9701 14.2543C16.0014 13.8708 16.0013 13.3772 16.0013 12.6664V12.5004C16.0013 12.1332 16.2992 11.8355 16.6664 11.8353C17.0336 11.8353 17.3314 12.1331 17.3314 12.5004V12.6664C17.3314 13.3554 17.332 13.9125 17.2953 14.3627C17.2625 14.7636 17.1975 15.1248 17.0531 15.4613L16.9867 15.6039C16.7212 16.1248 16.3173 16.5606 15.8216 16.8646L15.6039 16.9867C15.2271 17.1787 14.8206 17.2579 14.3626 17.2953C13.9124 17.3321 13.3554 17.3314 12.6664 17.3314H7.33334C6.64425 17.3314 6.0873 17.3321 5.63706 17.2953C5.23651 17.2626 4.87562 17.1982 4.5394 17.0541L4.39682 16.9867C3.8757 16.7212 3.4392 16.3175 3.1351 15.8217L3.01303 15.6039C2.82106 15.2271 2.74186 14.8207 2.70444 14.3627C2.66767 13.9125 2.66831 13.3554 2.66831 12.6664ZM9.3353 3.33337C9.3353 2.9661 9.63307 2.66833 10.0003 2.66833C10.3675 2.66851 10.6654 2.96621 10.6654 3.33337V10.8939L12.8626 8.69666L12.9671 8.61169C13.2253 8.44097 13.5767 8.4693 13.804 8.69666C14.0634 8.95633 14.0635 9.37748 13.804 9.63708L10.4701 12.9701C10.3454 13.0947 10.1766 13.1653 10.0003 13.1654C9.82397 13.1654 9.65434 13.0948 9.52963 12.9701L6.19663 9.63708L6.11166 9.53259C5.9411 9.27445 5.96934 8.92394 6.19663 8.69666C6.42392 8.46937 6.77442 8.44113 7.03256 8.61169L7.13705 8.69666L9.3353 10.8949V3.33337Z"+ fill="currentColor"+ />+ </svg>+ );+}++function FlaskGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M16.0013 14.4404C16.0012 13.9504 15.8514 13.4739 15.5736 13.0742L15.4467 12.9082L15.0121 12.3877C13.8615 12.8911 12.9154 13.1121 12.0619 13.1562C11.1476 13.2035 10.3805 13.0475 9.66541 12.8857C8.9421 12.7221 8.28162 12.5562 7.47302 12.5146C6.70041 12.475 5.77589 12.5504 4.56873 12.8887L4.5531 12.9082C4.19469 13.3383 3.99852 13.8806 3.99841 14.4404C3.99841 15.7627 5.07071 16.835 6.39294 16.835H13.6078C14.9299 16.8349 16.0013 15.7626 16.0013 14.4404ZM11.8353 3.16504H8.16541V7.72949C8.16541 8.20671 8.01889 8.6713 7.74841 9.06055L7.62439 9.22266L5.93396 11.25C6.52127 11.1756 7.05057 11.1614 7.54041 11.1865C8.48678 11.2351 9.2693 11.432 9.95837 11.5879C10.6557 11.7456 11.272 11.8653 11.9926 11.8281C12.5792 11.7978 13.2617 11.6591 14.1215 11.3184L12.3754 9.22266C12.0262 8.80363 11.8353 8.27494 11.8353 7.72949V3.16504ZM13.1654 7.72949C13.1654 7.96372 13.247 8.19111 13.3969 8.37109L16.4681 12.0566L16.6654 12.3154C17.0976 12.9371 17.3313 13.6782 17.3314 14.4404C17.3314 16.4971 15.6645 18.1649 13.6078 18.165H6.39294C4.33617 18.165 2.66833 16.4972 2.66833 14.4404C2.66844 13.5694 2.97398 12.7258 3.53162 12.0566L6.60291 8.37109L6.65564 8.30176C6.77198 8.13447 6.83533 7.93464 6.83533 7.72949V3.16504H6.66638C6.29926 3.16486 6.00134 2.86716 6.00134 2.5C6.00134 2.13284 6.29926 1.83514 6.66638 1.83496H13.3334L13.4672 1.84863C13.7703 1.91057 13.9984 2.17857 13.9984 2.5C13.9984 2.82143 13.7703 3.08943 13.4672 3.15137L13.3334 3.16504H13.1654V7.72949Z"+ fill="currentColor"+ />+ </svg>+ );+}++function FolderPlusGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M15.2041 17.5V15.665H13.3691C13.0019 15.665 12.7041 15.3673 12.7041 15C12.7041 14.6327 13.0019 14.335 13.3691 14.335H15.2041V12.5C15.2041 12.1327 15.5019 11.835 15.8691 11.835C16.2362 11.8352 16.5332 12.1329 16.5332 12.5V14.335H18.3691C18.7362 14.3352 19.0332 14.6329 19.0332 15C19.0332 15.3671 18.7362 15.6648 18.3691 15.665H16.5332V17.5C16.5332 17.8671 16.2362 18.1648 15.8691 18.165C15.5019 18.165 15.2041 17.8673 15.2041 17.5ZM2.12012 12.7002V7.29981C2.12012 6.64581 2.11922 6.1149 2.1543 5.68555C2.19002 5.24867 2.26619 4.85832 2.45117 4.49512L2.56836 4.28516C2.86045 3.80898 3.27979 3.42103 3.78028 3.16602L3.91797 3.10156C4.24192 2.96268 4.5885 2.90039 4.97071 2.86914C5.40006 2.83406 5.93096 2.83496 6.58496 2.83496H7.28028C7.42346 2.83496 7.52305 2.83479 7.6211 2.84082L7.875 2.86719C8.46133 2.95309 9.01189 3.20874 9.45703 3.60547L9.70215 3.84473C9.81425 3.95779 9.85105 3.99455 9.88672 4.02637L9.99805 4.11719C10.2646 4.31741 10.5851 4.43638 10.9199 4.45703L11.1797 4.45996H13.6914C14.2499 4.45996 14.703 4.45958 15.0713 4.48535C15.4458 4.51157 15.7828 4.56683 16.1025 4.70313L16.3662 4.83106C16.9638 5.15706 17.4378 5.67623 17.707 6.30762L17.7939 6.54981C17.868 6.79538 17.904 7.05317 17.9238 7.33203C17.9498 7.69789 17.9502 8.14747 17.9502 8.7002C17.9501 8.87631 17.8803 9.0453 17.7559 9.16992C17.6311 9.29464 17.4615 9.36524 17.2852 9.36524H3.4502V12.7002C3.4502 13.3761 3.45084 13.8434 3.48047 14.2061C3.50947 14.5608 3.56304 14.7568 3.63672 14.9014L3.70215 15.0195C3.86642 15.2873 4.10236 15.505 4.38379 15.6484L4.50391 15.7002C4.63661 15.7476 4.81329 15.783 5.0791 15.8047C5.44174 15.8343 5.90903 15.835 6.58496 15.835H9.40918L9.54395 15.8486C9.84681 15.9108 10.0742 16.1788 10.0742 16.5C10.0742 16.8212 9.84681 17.0892 9.54395 17.1514L9.40918 17.165H6.58496C5.93096 17.165 5.40006 17.1659 4.97071 17.1309C4.5885 17.0996 4.24192 17.0373 3.91797 16.8984L3.78028 16.834C3.27979 16.579 2.86045 16.191 2.56836 15.7148L2.45117 15.5049C2.26619 15.1417 2.19002 14.7513 2.1543 14.3145C2.11922 13.8851 2.12012 13.3542 2.12012 12.7002ZM3.4502 8.03516H16.6172C16.6146 7.79548 16.6098 7.59777 16.5977 7.42676C16.5816 7.20054 16.5552 7.04845 16.5205 6.9336L16.4834 6.8291C16.332 6.47411 16.0655 6.1824 15.7295 5.99903L15.5811 5.92676C15.4545 5.8728 15.2835 5.83385 14.9785 5.8125C14.6674 5.79073 14.2686 5.79004 13.6914 5.79004H11.1797L10.8379 5.78418C10.2426 5.74746 9.67313 5.53663 9.19922 5.18067L9.00196 5.01953C8.92848 4.95403 8.85889 4.88222 8.75781 4.78028L8.57227 4.59863C8.32169 4.37525 8.01175 4.23086 7.68164 4.18262L7.54004 4.16797C7.49225 4.16502 7.43987 4.16504 7.28028 4.16504H6.58496C5.90903 4.16504 5.44174 4.16569 5.0791 4.19531C4.81329 4.21705 4.63661 4.25237 4.50391 4.29981L4.38379 4.35156C4.10236 4.49499 3.86642 4.71271 3.70215 4.98047L3.63672 5.09863C3.56304 5.24324 3.50947 5.43924 3.48047 5.79395C3.45084 6.15659 3.4502 6.62388 3.4502 7.29981V8.03516Z"+ fill="currentColor"+ />+ </svg>+ );+}++function LightningOutlineGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M11.912 21.413c-.383.45-.883.683-1.5.7-.616.016-1.116-.192-1.5-.625-.375-.434-.454-1.034-.237-1.8L9.687 16H4.575c-.567 0-1.008-.162-1.325-.488a1.68 1.68 0 0 1-.475-1.2c0-.474.154-.9.462-1.274l8.9-10.563c.384-.45.884-.683 1.5-.7.617-.017 1.113.192 1.488.625.383.433.467 1.033.25 1.8L14.312 8h5.113c.567 0 1.008.167 1.325.5.325.333.488.737.488 1.212 0 .467-.159.884-.476 1.25l-8.85 10.45Z"+ stroke="currentColor"+ strokeWidth="1.875"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function MicGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" {...props}>+ <g transform="scale(0.8333333333333334)">+ <path d="M18.5848 13.4121C18.7715 12.9516 19.2961 12.7296 19.7567 12.916C20.217 13.1027 20.4391 13.6274 20.2528 14.0879C19.0405 17.0826 16.2438 19.2675 12.9003 19.6035V22C12.9003 22.4971 12.4969 22.9004 11.9999 22.9004C11.5029 22.9003 11.0995 22.497 11.0995 22V19.6035C7.75618 19.2673 4.96018 17.0823 3.74791 14.0879C3.56144 13.6272 3.78344 13.1026 4.244 12.916C4.70458 12.7298 5.22933 12.9517 5.41588 13.4121C6.46985 16.0157 9.02264 17.8496 12.0008 17.8496C14.9787 17.8493 17.531 16.0155 18.5848 13.4121Z" />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M11.9999 1.34961C14.7061 1.34961 16.9003 3.5438 16.9003 6.25V10.7334C16.9003 13.4396 14.7061 15.6338 11.9999 15.6338C9.29371 15.6337 7.09947 13.4396 7.09947 10.7334V6.25C7.09947 3.54384 9.29372 1.34967 11.9999 1.34961ZM11.9999 3.15039C10.2878 3.15045 8.90025 4.53795 8.90025 6.25V10.7334C8.90025 12.4454 10.2878 13.8339 11.9999 13.834C13.7119 13.834 15.0995 12.4455 15.0995 10.7334V6.25C15.0995 4.53792 13.7119 3.15039 11.9999 3.15039Z"+ />+ </g>+ </svg>+ );+}++function OpenaiGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M11.6475 18.3409C11.0975 18.3409 10.575 18.2364 10.08 18.0274C9.58502 17.8184 9.14502 17.5269 8.76002 17.1529C8.34202 17.2959 7.90751 17.3674 7.45651 17.3674C6.71951 17.3674 6.03751 17.1859 5.41051 16.8229C4.78351 16.4599 4.27751 15.9649 3.89251 15.3379C3.51851 14.7109 3.33151 14.0124 3.33151 13.2424C3.33151 12.9234 3.37551 12.5769 3.46351 12.2029C3.02351 11.7959 2.68251 11.3284 2.44051 10.8004C2.19851 10.2614 2.07751 9.70044 2.07751 9.11744C2.07751 8.52344 2.20401 7.95144 2.45701 7.40144C2.71001 6.85144 3.06201 6.37844 3.51301 5.98244C3.97501 5.57544 4.50851 5.29494 5.11351 5.14094C5.23451 4.51394 5.48751 3.95294 5.87251 3.45794C6.26851 2.95194 6.75252 2.55594 7.32452 2.26994C7.89652 1.98394 8.50702 1.84094 9.15602 1.84094C9.70602 1.84094 10.2285 1.94544 10.7235 2.15444C11.2185 2.36344 11.6585 2.65494 12.0435 3.02894C12.4615 2.88594 12.896 2.81444 13.347 2.81444C14.084 2.81444 14.766 2.99594 15.393 3.35894C16.02 3.72194 16.5205 4.21694 16.8945 4.84394C17.2795 5.47094 17.472 6.16944 17.472 6.93944C17.472 7.25844 17.428 7.60494 17.34 7.97894C17.78 8.38594 18.121 8.85894 18.363 9.39794C18.605 9.92594 18.726 10.4814 18.726 11.0644C18.726 11.6584 18.5995 12.2304 18.3465 12.7804C18.0935 13.3304 17.736 13.8089 17.274 14.2159C16.823 14.6119 16.295 14.8869 15.69 15.0409C15.569 15.6679 15.3105 16.2289 14.9145 16.7239C14.5295 17.2299 14.051 17.6259 13.479 17.9119C12.907 18.1979 12.2965 18.3409 11.6475 18.3409ZM7.57201 16.2784C8.12201 16.2784 8.60051 16.1629 9.00751 15.9319L12.1095 14.1499C12.2195 14.0729 12.2745 13.9684 12.2745 13.8364V12.4174L8.28152 14.7109C8.03952 14.8539 7.79751 14.8539 7.55552 14.7109L4.43701 12.9124C4.43701 12.9454 4.43151 12.9839 4.42051 13.0279C4.42051 13.0719 4.42051 13.1379 4.42051 13.2259C4.42051 13.7869 4.55252 14.3039 4.81651 14.7769C5.09152 15.2389 5.47101 15.6019 5.95501 15.8659C6.43901 16.1409 6.97801 16.2784 7.57201 16.2784ZM7.73701 13.5889C7.80301 13.6219 7.86351 13.6384 7.91851 13.6384C7.97351 13.6384 8.02852 13.6219 8.08352 13.5889L9.32101 12.8794L5.34451 10.5694C5.10251 10.4264 4.98151 10.2119 4.98151 9.92594V6.34544C4.43151 6.58744 3.99151 6.96144 3.66151 7.46744C3.33151 7.96244 3.16651 8.51244 3.16651 9.11744C3.16651 9.65644 3.30401 10.1734 3.57901 10.6684C3.85401 11.1634 4.21151 11.5374 4.65151 11.7904L7.73701 13.5889ZM11.6475 17.2519C12.2305 17.2519 12.7585 17.1199 13.2315 16.8559C13.7045 16.5919 14.0785 16.2289 14.3535 15.7669C14.6285 15.3049 14.766 14.7879 14.766 14.2159V10.6519C14.766 10.5199 14.711 10.4209 14.601 10.3549L13.347 9.62894V14.2324C13.347 14.5184 13.226 14.7329 12.984 14.8759L9.86551 16.6744C10.4045 17.0594 10.9985 17.2519 11.6475 17.2519ZM12.2745 11.2129V8.96894L10.41 7.91294L8.52902 8.96894V11.2129L10.41 12.2689L12.2745 11.2129ZM7.45651 5.94944C7.45651 5.66344 7.57752 5.44894 7.81952 5.30594L10.938 3.50744C10.399 3.12244 9.80502 2.92994 9.15602 2.92994C8.57302 2.92994 8.04501 3.06194 7.57201 3.32594C7.09902 3.58994 6.72502 3.95294 6.45002 4.41494C6.18602 4.87694 6.05401 5.39394 6.05401 5.96594V9.51344C6.05401 9.64544 6.10901 9.74994 6.21902 9.82694L7.45651 10.5529V5.94944ZM15.8385 13.8364C16.3885 13.5944 16.823 13.2204 17.142 12.7144C17.472 12.2084 17.637 11.6584 17.637 11.0644C17.637 10.5254 17.4995 10.0084 17.2245 9.51344C16.9495 9.01844 16.592 8.64444 16.152 8.39144L13.0665 6.60944C13.0005 6.56544 12.94 6.54894 12.885 6.55994C12.83 6.55994 12.775 6.57644 12.72 6.60944L11.4825 7.30244L15.4755 9.62894C15.5965 9.69494 15.6845 9.78294 15.7395 9.89294C15.8055 9.99194 15.8385 10.1129 15.8385 10.2559V13.8364ZM12.522 5.45444C12.764 5.30044 13.006 5.30044 13.248 5.45444L16.383 7.28594C16.383 7.20894 16.383 7.10994 16.383 6.98894C16.383 6.46094 16.251 5.96044 15.987 5.48744C15.734 5.00344 15.3655 4.61844 14.8815 4.33244C14.4085 4.04644 13.8585 3.90344 13.2315 3.90344C12.6815 3.90344 12.203 4.01894 11.796 4.24994L8.69402 6.03194C8.58402 6.10894 8.52902 6.21344 8.52902 6.34544V7.76444L12.522 5.45444Z"+ fill="currentColor"+ />+ </svg>+ );+}++function PaintGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M13.8858 2.71322C14.8344 1.92447 16.2473 1.9732 17.1387 2.86459L17.3057 3.04916C18.0315 3.94013 18.0264 5.22711 17.294 6.11263L17.126 6.29623L14.711 8.67513L14.8653 8.82943L15.043 9.02865C15.8122 9.9856 15.6958 11.3368 14.9453 12.2337L14.7754 12.4183C13.6883 13.4902 12.839 14.6622 12.1797 16.0052L11.9082 16.5912C11.3763 17.8145 9.89965 18.5876 8.58791 17.9271L8.46193 17.8587C7.40515 17.2458 6.64661 16.801 5.98147 16.2884C5.38839 15.8314 4.88053 15.3299 4.28713 14.6253L4.02736 14.3109C3.85244 14.0953 3.82982 13.7933 3.97072 13.554L4.35256 12.9046L3.73342 13.1204C3.48311 13.2076 3.20868 13.1373 3.03127 12.9495L2.96193 12.8626C2.82198 12.6535 2.68343 12.4395 2.5469 12.2201L2.14162 11.5453C1.36174 10.2032 2.14731 8.64808 3.41018 8.09994L3.99709 7.82943C5.34168 7.17073 6.51495 6.32179 7.58791 5.23568L7.77248 5.06576C8.7342 4.26289 10.2181 4.1871 11.1787 5.14681L11.3321 5.30013L13.7031 2.88217L13.8858 2.71322ZM6.89748 7.60385C6.08367 8.21683 5.21271 8.73808 4.26565 9.17513L3.94045 9.32064C3.24138 9.62398 2.99796 10.3713 3.29201 10.8773L3.67678 11.5169C3.71355 11.576 3.75214 11.6336 3.78908 11.6917L5.62697 11.0521L5.72658 11.0257C5.96153 10.9829 6.20558 11.0704 6.36037 11.2591C6.53689 11.4747 6.56033 11.7777 6.41897 12.0179L5.35451 13.8226C5.88263 14.4443 6.30957 14.8614 6.79397 15.2347C7.37731 15.6842 8.05546 16.0858 9.12893 16.7083L9.22658 16.7572C9.72862 16.9707 10.4042 16.7146 10.6885 16.0609L10.835 15.7357C11.2724 14.7898 11.7919 13.9186 12.4053 13.1058L6.89748 7.60385ZM16.1983 3.80502C15.7974 3.40419 15.1621 3.38226 14.7354 3.73666L14.6524 3.81283L11.8115 6.71029C11.6874 6.83692 11.5181 6.90945 11.3408 6.91049C11.1634 6.91141 10.9928 6.84059 10.8672 6.71517L10.2383 6.08724C9.83264 5.68229 9.12993 5.66436 8.63088 6.08138L8.5342 6.17123C8.33545 6.37241 8.13156 6.56445 7.9258 6.75131L13.2578 12.0785C13.4452 11.8726 13.6401 11.6709 13.8418 11.472L13.9307 11.3744C14.3203 10.9092 14.3309 10.2674 14.001 9.85482L13.9248 9.77084L13.2959 9.14291C13.1705 9.01761 13.101 8.84656 13.1016 8.66928C13.1023 8.49215 13.1736 8.32289 13.2998 8.19857L16.1924 5.34896L16.2676 5.26595C16.5971 4.86764 16.5999 4.28883 16.2735 3.88803L16.1983 3.80502Z"+ fill="currentColor"+ />+ </svg>+ );+}++function PlayOutlineGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M3.82422 4.74933C3.82427 3.32901 5.39273 2.46804 6.59102 3.23058L13.2698 7.48185C14.3813 8.18917 14.3813 9.81116 13.2698 10.5185L6.59102 14.7689C5.39281 15.5314 3.82448 14.6711 3.82422 13.251V4.74933ZM5.17422 13.251C5.17448 13.6058 5.56646 13.8211 5.86592 13.6307L12.5456 9.37941C12.8232 9.20249 12.8234 8.79681 12.5456 8.62004L5.86592 4.36964C5.56636 4.17902 5.17427 4.39428 5.17422 4.74933V13.251Z"+ fill="currentColor"+ />+ </svg>+ );+}++function PointerOutlineGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M12.725 20.288c-.367.716-.842 1.166-1.425 1.35-.583.191-1.15.12-1.7-.213-.55-.325-.954-.846-1.213-1.563L3.787 6.95c-.175-.492-.216-.958-.124-1.4.091-.45.291-.83.6-1.137a2.187 2.187 0 0 1 1.137-.6c.45-.092.92-.05 1.412.125l12.913 4.6c.717.258 1.237.662 1.563 1.212.333.542.404 1.104.212 1.688-.183.583-.633 1.058-1.35 1.425l-4.925 2.512-2.5 4.913Z"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function PullRequestGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <g transform="translate(2.87695 2.45996)">+ <path+ d="M2.54004 0C3.94284 0 5.08008 1.13724 5.08008 2.54004C5.08008 3.71238 4.28484 4.69567 3.20508 4.98828V10.0908C4.28496 10.3833 5.08008 11.3676 5.08008 12.54C5.08008 13.9428 3.94284 15.0801 2.54004 15.0801C1.13724 15.0801 0 13.9428 0 12.54C0 11.3676 0.795113 10.3833 1.875 10.0908V4.98828C0.795239 4.69567 0 3.71238 0 2.54004C0 1.13724 1.13724 0 2.54004 0ZM2.54004 11.3301C1.87177 11.3301 1.33008 11.8718 1.33008 12.54C1.33008 13.2083 1.87177 13.75 2.54004 13.75C3.2083 13.75 3.75 13.2083 3.75 12.54C3.75 11.8718 3.2083 11.3301 2.54004 11.3301ZM2.54004 1.33008C1.87177 1.33008 1.33008 1.87177 1.33008 2.54004C1.33008 3.2083 1.87177 3.75 2.54004 3.75C3.2083 3.75 3.75 3.2083 3.75 2.54004C3.75 1.87177 3.2083 1.33008 2.54004 1.33008Z"+ fill="currentColor"+ />+ <path+ d="M12.123 9.375C12.4903 9.375 12.7881 9.67277 12.7881 10.04V11.458H14.207L14.3408 11.4717C14.6437 11.5337 14.8719 11.8018 14.8721 12.123C14.8721 12.4443 14.6438 12.7123 14.3408 12.7744L14.207 12.7881H12.7881V14.207C12.7879 14.5742 12.4902 14.8721 12.123 14.8721C11.756 14.8719 11.4582 14.574 11.458 14.207V12.7881H10.04C9.67277 12.7881 9.375 12.4903 9.375 12.123C9.37518 11.7559 9.67288 11.458 10.04 11.458H11.458V10.04C11.458 9.67288 11.7559 9.37518 12.123 9.375Z"+ fill="currentColor"+ />+ <path+ d="M8.42383 0.317383C8.68176 0.147236 9.03258 0.175585 9.25977 0.402344C9.51942 0.662002 9.51934 1.08404 9.25977 1.34375L8.72852 1.875H10.457C11.7446 1.87526 12.7891 2.91945 12.7891 4.20703V6.70703C12.7889 7.07387 12.4908 7.37163 12.124 7.37207C11.7569 7.37207 11.4592 7.07414 11.459 6.70703V4.20703C11.459 3.65399 11.01 3.20534 10.457 3.20508H8.72852L9.25977 3.73633L9.34473 3.84082C9.51509 4.09889 9.48688 4.44953 9.25977 4.67676C9.03252 4.90385 8.68189 4.93213 8.42383 4.76172L8.31934 4.67676L6.65234 3.00977C6.39315 2.75009 6.39296 2.3289 6.65234 2.06934L8.31934 0.402344L8.42383 0.317383Z"+ fill="currentColor"+ />+ </g>+ </svg>+ );+}++function PullRequestDraftGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <g transform="translate(2.87695 2.45996)">+ <path+ d="M2.54004 0C3.94284 0 5.08008 1.13724 5.08008 2.54004C5.08008 3.71238 4.28484 4.69567 3.20508 4.98828V10.0908C4.28496 10.3833 5.08008 11.3676 5.08008 12.54C5.08008 13.9428 3.94284 15.0801 2.54004 15.0801C1.13724 15.0801 0 13.9428 0 12.54C0 11.3676 0.795113 10.3833 1.875 10.0908V4.98828C0.795239 4.69567 0 3.71238 0 2.54004C0 1.13724 1.13724 0 2.54004 0ZM2.54004 11.3301C1.87177 11.3301 1.33008 11.8718 1.33008 12.54C1.33008 13.2083 1.87177 13.75 2.54004 13.75C3.2083 13.75 3.75 13.2083 3.75 12.54C3.75 11.8718 3.2083 11.3301 2.54004 11.3301ZM2.54004 1.33008C1.87177 1.33008 1.33008 1.87177 1.33008 2.54004C1.33008 3.2083 1.87177 3.75 2.54004 3.75C3.2083 3.75 3.75 3.2083 3.75 2.54004C3.75 1.87177 3.2083 1.33008 2.54004 1.33008Z"+ fill="currentColor"+ />+ <path+ d="M11.707 10C13.1096 10.0003 14.2471 11.1374 14.2471 12.54C14.2471 13.9427 13.1096 15.0798 11.707 15.0801C10.3042 15.0801 9.16699 13.9428 9.16699 12.54C9.16699 11.1372 10.3042 10 11.707 10ZM11.707 11.3301C11.0388 11.3301 10.4971 11.8718 10.4971 12.54C10.4971 13.2083 11.0388 13.75 11.707 13.75C12.3751 13.7497 12.917 13.2081 12.917 12.54C12.917 11.8719 12.3751 11.3303 11.707 11.3301Z"+ fill="currentColor"+ />+ <path+ d="M11.7031 5.79004C12.2554 5.79004 12.7031 6.23775 12.7031 6.79004C12.7031 7.34232 12.2554 7.79004 11.7031 7.79004C11.1508 7.79004 10.7031 7.34232 10.7031 6.79004C10.7031 6.23775 11.1508 5.79004 11.7031 5.79004Z"+ fill="currentColor"+ />+ <path+ d="M11.7031 1.54004C12.2554 1.54004 12.7031 1.98775 12.7031 2.54004C12.7031 3.09232 12.2554 3.54004 11.7031 3.54004C11.1508 3.54004 10.7031 3.09232 10.7031 2.54004C10.7031 1.98775 11.1508 1.54004 11.7031 1.54004Z"+ fill="currentColor"+ />+ </g>+ </svg>+ );+}++function PullRequestMergedGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <g transform="translate(2.87695 2.45996)">+ <path+ d="M3.75 12.54C3.75 11.8718 3.2083 11.3301 2.54004 11.3301C1.87177 11.3301 1.33008 11.8718 1.33008 12.54C1.33008 13.2083 1.87177 13.75 2.54004 13.75C3.2083 13.75 3.75 13.2083 3.75 12.54ZM12.917 10.04C12.917 9.37188 12.3751 8.83025 11.707 8.83008C11.0388 8.83008 10.4971 9.37177 10.4971 10.04C10.4971 10.7083 11.0388 11.25 11.707 11.25C12.3751 11.2498 12.917 10.7082 12.917 10.04ZM3.75 2.54004C3.75 1.87177 3.2083 1.33008 2.54004 1.33008C1.87177 1.33008 1.33008 1.87177 1.33008 2.54004C1.33008 3.2083 1.87177 3.75 2.54004 3.75C3.2083 3.75 3.75 3.2083 3.75 2.54004ZM5.08008 2.54004C5.08008 3.47934 4.56861 4.29686 3.81055 4.73633C4.22936 5.91905 4.89909 6.81802 5.75879 7.48242C6.72602 8.22983 7.9664 8.70627 9.42676 8.9248C9.83996 8.08166 10.7048 7.5 11.707 7.5C13.1097 7.50018 14.2471 8.63734 14.2471 10.04C14.2471 11.4427 13.1097 12.5799 11.707 12.5801C10.3687 12.5801 9.2737 11.5448 9.17578 10.2314C7.57006 9.98395 6.12118 9.44292 4.94629 8.53516C4.25331 7.99967 3.66805 7.34453 3.20508 6.56836V10.0908C4.28496 10.3833 5.08008 11.3676 5.08008 12.54C5.08008 13.9428 3.94284 15.0801 2.54004 15.0801C1.13724 15.0801 0 13.9428 0 12.54C0 11.3676 0.795119 10.3833 1.875 10.0908V4.98828C0.795245 4.69568 0 3.71239 0 2.54004C0 1.13724 1.13724 0 2.54004 0C3.94284 0 5.08008 1.13724 5.08008 2.54004Z"+ fill="currentColor"+ />+ </g>+ </svg>+ );+}++function SettingsGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M9.99944 7.24939C11.5169 7.2495 12.7473 8.47995 12.7475 9.99744C12.7475 11.5151 11.517 12.7454 9.99944 12.7455C8.48176 12.7455 7.2514 11.5151 7.2514 9.99744C7.25155 8.47988 8.48186 7.24939 9.99944 7.24939ZM9.99944 8.57947C9.2164 8.57947 8.58163 9.21442 8.58148 9.99744C8.58148 10.7806 9.2163 11.4154 9.99944 11.4154C10.7825 11.4153 11.4174 10.7805 11.4174 9.99744C11.4173 9.21449 10.7824 8.57958 9.99944 8.57947Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M10.6391 1.67517C11.2939 1.67532 11.8991 2.02577 12.226 2.59314L13.2485 4.36755H15.2963C15.9505 4.36758 16.555 4.71709 16.8823 5.28357L17.5219 6.39001C17.8489 6.95668 17.8481 7.65542 17.5209 8.22205L16.4975 9.99451L17.5239 11.7689C17.8519 12.3357 17.8521 13.0347 17.5248 13.6019L16.8862 14.7084C16.559 15.2747 15.9543 15.6243 15.3002 15.6244H13.2514L12.2299 17.3988C11.9029 17.9663 11.297 18.3168 10.642 18.3168L9.3637 18.3158C8.71064 18.3155 8.10718 17.9678 7.77972 17.4027L6.74847 15.6234L4.69964 15.6244C4.04558 15.6242 3.44087 15.2747 3.1137 14.7084L2.47503 13.6019C2.14791 13.0349 2.14836 12.3366 2.47601 11.7699L3.50237 9.99548L2.47894 8.22205C2.15175 7.65533 2.15174 6.95673 2.47894 6.39001L3.11761 5.28259C3.44458 4.71663 4.04894 4.36813 4.70257 4.36755L6.75042 4.36658L7.77581 2.59119C8.10301 2.02476 8.7076 1.67527 9.36175 1.67517H10.6391ZM9.36273 3.00623C9.1835 3.00623 9.01679 3.10199 8.92718 3.2572L7.82659 5.16345C7.63652 5.49253 7.28473 5.69529 6.90472 5.69568L4.70355 5.69763C4.52451 5.69782 4.3585 5.79355 4.26898 5.94861L3.6303 7.05505C3.54091 7.2102 3.54077 7.40192 3.6303 7.55701L4.73089 9.46326C4.92108 9.7929 4.92135 10.1992 4.73089 10.5287L3.62737 12.4359C3.5378 12.591 3.53792 12.7817 3.62737 12.9369L4.26605 14.0433C4.35567 14.1982 4.52067 14.2932 4.69964 14.2933L6.90276 14.2943C7.28242 14.2946 7.63335 14.497 7.82366 14.8256L8.93011 16.7357C9.01984 16.8905 9.18578 16.9857 9.36468 16.9857H10.642C10.8213 16.9857 10.987 16.89 11.0766 16.7347L12.1752 14.8275C12.3653 14.4975 12.7182 14.2943 13.0991 14.2943H15.3002C15.4794 14.2942 15.6452 14.1985 15.7348 14.0433L16.3725 12.9379C16.4621 12.7826 16.4621 12.5911 16.3725 12.4359L15.27 10.5287C15.1032 10.2404 15.0808 9.89331 15.2055 9.59021L15.269 9.46326L16.3696 7.55701C16.4591 7.40189 16.459 7.21022 16.3696 7.05505L15.7309 5.94861C15.6412 5.79363 15.4754 5.69863 15.2963 5.69861L13.0951 5.69763L12.9535 5.68884C12.6751 5.65158 12.4217 5.50519 12.2504 5.28259L12.1723 5.16443L11.0737 3.2572C10.9841 3.10175 10.8175 3.00525 10.6381 3.00525L9.36273 3.00623Z"+ fill="currentColor"+ />+ </svg>+ );+}++function StarGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 15 14" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ fill="currentColor"+ d="M5.914.678a1.332 1.332 0 0 1 2.321 0L9.792 3.44a.268.268 0 0 0 .18.13l3.108.628a1.332 1.332 0 0 1 .717 2.207L11.652 8.74a.268.268 0 0 0-.07.211l.364 3.15a1.332 1.332 0 0 1-1.877 1.364l-2.883-1.32a.268.268 0 0 0-.222 0l-2.883 1.32a1.333 1.333 0 0 1-1.878-1.364l.364-3.15a.268.268 0 0 0-.069-.211L.353 6.405a1.332 1.332 0 0 1 .716-2.207l3.108-.627a.268.268 0 0 0 .18-.13L5.914.677Zm1.394.523a.268.268 0 0 0-.467 0L5.285 3.962c-.19.337-.518.575-.897.652L1.28 5.24a.268.268 0 0 0-.145.444l2.147 2.334c.261.285.386.67.342 1.055l-.364 3.15a.268.268 0 0 0 .378.273l2.883-1.32a1.332 1.332 0 0 1 1.108 0l2.883 1.32a.268.268 0 0 0 .377-.274l-.363-3.15c-.044-.384.08-.769.342-1.054l2.146-2.334a.268.268 0 0 0-.144-.444l-3.108-.627a1.332 1.332 0 0 1-.897-.652l-1.557-2.76Z"+ />+ </svg>+ );+}++function TerminalGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path+ d="M6.19629 7.86231C6.42357 7.63534 6.7752 7.60692 7.0332 7.77734L7.1377 7.86231L8.80371 9.5293C9.06329 9.78889 9.06307 10.21 8.80371 10.4697L7.1377 12.1367C6.878 12.3964 6.45599 12.3964 6.19629 12.1367C5.93686 11.8771 5.93697 11.456 6.19629 11.1963L7.39258 9.99902L6.19629 8.80371L6.11133 8.69922C5.94087 8.4411 5.96904 8.08955 6.19629 7.86231Z"+ fill="currentColor"+ />+ <path+ d="M13.4668 11.0156C13.7699 11.0776 13.998 11.3456 13.998 11.667C13.9979 11.9883 13.7698 12.2564 13.4668 12.3184L13.333 12.332H10.833C10.466 12.3319 10.1682 12.034 10.168 11.667C10.168 11.2998 10.4659 11.0021 10.833 11.002H13.333L13.4668 11.0156Z"+ fill="currentColor"+ />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M12.6602 2.66504C13.3492 2.66504 13.9062 2.66439 14.3564 2.70117C14.8142 2.73859 15.2201 2.81796 15.5967 3.00977C16.1922 3.31321 16.677 3.79805 16.9805 4.39356C17.1722 4.77014 17.2517 5.17604 17.2891 5.63379C17.3258 6.08402 17.3252 6.64102 17.3252 7.33008V12.6602C17.3252 13.3492 17.3258 13.9062 17.2891 14.3564C17.2516 14.8142 17.1723 15.2201 16.9805 15.5967C16.677 16.1922 16.1922 16.677 15.5967 16.9805C15.2201 17.1723 14.8142 17.2516 14.3564 17.2891C13.9062 17.3258 13.3492 17.3252 12.6602 17.3252H7.33008C6.64102 17.3252 6.08402 17.3258 5.63379 17.2891C5.17604 17.2517 4.77014 17.1722 4.39356 16.9805C3.79805 16.677 3.31321 16.1922 3.00977 15.5967C2.81796 15.2201 2.73859 14.8142 2.70117 14.3564C2.66439 13.9062 2.66504 13.3492 2.66504 12.6602V7.33008C2.66504 6.64101 2.66439 6.08402 2.70117 5.63379C2.73858 5.17601 2.81797 4.77016 3.00977 4.39356C3.31321 3.79802 3.79802 3.31321 4.39356 3.00977C4.77016 2.81797 5.17601 2.73858 5.63379 2.70117C6.08402 2.66439 6.64101 2.66504 7.33008 2.66504H12.6602ZM7.33008 3.99512C6.61907 3.99512 6.1257 3.99601 5.74219 4.02734C5.3665 4.05804 5.15508 4.11481 4.99707 4.19531C4.65183 4.37124 4.37124 4.65183 4.19531 4.99707C4.11481 5.15508 4.05805 5.3665 4.02734 5.74219C3.99601 6.1257 3.99512 6.61908 3.99512 7.33008V12.6602C3.99512 13.3711 3.99601 13.8646 4.02734 14.248C4.05805 14.6237 4.11481 14.8352 4.19531 14.9932C4.37124 15.3384 4.65186 15.619 4.99707 15.7949C5.15507 15.8754 5.36654 15.9322 5.74219 15.9629C6.1257 15.9942 6.61908 15.9951 7.33008 15.9951H12.6602C13.3711 15.9951 13.8646 15.9942 14.248 15.9629C14.6237 15.9322 14.8352 15.8754 14.9932 15.7949C15.3384 15.619 15.619 15.3384 15.7949 14.9932C15.8754 14.8352 15.9322 14.6237 15.9629 14.248C15.9942 13.8646 15.9951 13.3711 15.9951 12.6602V7.33008C15.9951 6.61908 15.9942 6.1257 15.9629 5.74219C15.9322 5.36654 15.8754 5.15507 15.7949 4.99707C15.619 4.65186 15.3384 4.37124 14.9932 4.19531C14.8352 4.11481 14.6237 4.05805 14.248 4.02734C13.8646 3.99601 13.3711 3.99512 12.6602 3.99512H7.33008Z"+ fill="currentColor"+ />+ </svg>+ );+}++function TrashGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path d="M10.6299 1.33496C12.0335 1.33496 13.2695 2.25996 13.666 3.60645L13.8809 4.33496H17L17.1338 4.34863C17.4369 4.41057 17.665 4.67858 17.665 5C17.665 5.32142 17.4369 5.58943 17.1338 5.65137L17 5.66504H16.6543L15.8574 14.9912C15.7177 16.629 14.3478 17.8877 12.7041 17.8877H7.2959C5.75502 17.8877 4.45439 16.7815 4.18262 15.2939L4.14258 14.9912L3.34668 5.66504H3C2.63273 5.66504 2.33496 5.36727 2.33496 5C2.33496 4.63273 2.63273 4.33496 3 4.33496H6.11914L6.33398 3.60645L6.41797 3.3584C6.88565 2.14747 8.05427 1.33496 9.37012 1.33496H10.6299ZM5.46777 14.8779L5.49121 15.0537C5.64881 15.9161 6.40256 16.5576 7.2959 16.5576H12.7041C13.6571 16.5576 14.4512 15.8275 14.5322 14.8779L15.3193 5.66504H4.68164L5.46777 14.8779ZM7.66797 12.8271V8.66016C7.66797 8.29299 7.96588 7.99528 8.33301 7.99512C8.70028 7.99512 8.99805 8.29289 8.99805 8.66016V12.8271C8.99779 13.1942 8.70012 13.4912 8.33301 13.4912C7.96604 13.491 7.66823 13.1941 7.66797 12.8271ZM11.002 12.8271V8.66016C11.002 8.29289 11.2997 7.99512 11.667 7.99512C12.0341 7.9953 12.332 8.293 12.332 8.66016V12.8271C12.3318 13.1941 12.0339 13.491 11.667 13.4912C11.2999 13.4912 11.0022 13.1942 11.002 12.8271ZM9.37012 2.66504C8.60726 2.66504 7.92938 3.13589 7.6582 3.83789L7.60938 3.98145L7.50586 4.33496H12.4941L12.3906 3.98145C12.1607 3.20084 11.4437 2.66504 10.6299 2.66504H9.37012Z" />+ </svg>+ );+}++function WorktreeGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path d="M15.8 11.535c.367 0 .665.298.665.665v5a.665.665 0 0 1-.665.665h-5a.665.665 0 1 1 0-1.33h3.394l-3.565-3.564a.666.666 0 0 1 .942-.942l3.564 3.565V12.2c0-.367.298-.665.665-.665Zm0-9.4c.367 0 .665.298.665.665v5a.665.665 0 0 1-1.33 0V4.405l-5.128 5.128c-.323.324-.558.565-.842.74a2.668 2.668 0 0 1-.771.319c-.324.078-.662.073-1.12.073H1.93a.665.665 0 1 1 0-1.33h5.345c.52 0 .673-.005.809-.037.136-.033.266-.086.385-.16.12-.072.23-.177.598-.545l5.128-5.128H10.8a.665.665 0 0 1 0-1.33h5Z" />+ </svg>+ );+}++function XCircleGlyph(props: GlyphProps) {+ return (+ <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" {...props}>+ <path d="M7.231 7.231a.665.665 0 0 1 .94 0L10 9.06l1.828-1.829.104-.085a.666.666 0 0 1 .921.922l-.084.104L10.94 10l1.829 1.828a.665.665 0 0 1-.94.94L10 10.94l-1.828 1.83a.665.665 0 0 1-.94-.94L9.06 10 7.23 8.172a.665.665 0 0 1 0-.94Z" />+ <path+ fillRule="evenodd"+ d="M10 2.085a7.915 7.915 0 1 1 0 15.83 7.915 7.915 0 0 1 0-15.83Zm0 1.33a6.585 6.585 0 1 0 0 13.17 6.585 6.585 0 0 0 0-13.17Z"+ clipRule="evenodd"+ />+ </svg>+ );+}++/**+ * Which glyph each keycap wears, mirroring Codex's own keycap catalogue.+ * `null` marks the blank keycaps, which Codex draws as a small empty square.+ */+const KEYCAP_GLYPHS: Record<WorkLouderCodexKeycapId, ((props: GlyphProps) => ReactElement) | null> =+ {+ FAST: LightningOutlineGlyph,+ APPR: CheckCircleGlyph,+ REJ: XCircleGlyph,+ SPLIT: WorktreeGlyph,+ MIC: MicGlyph,+ MIC1: MicGlyph,+ CODEX: CodexGlyph,+ BUG: BugGlyph,+ OAI: OpenaiGlyph,+ TERM: TerminalGlyph,+ DWN: DownloadGlyph,+ DEL: TrashGlyph,+ NEW: ComposeGlyph,+ NAV: PointerOutlineGlyph,+ MAGIC: StarGlyph,+ DIFF: DiffGlyph,+ PLAY: PlayOutlineGlyph,+ GIT: DiffGlyph,+ BRCH: PullRequestDraftGlyph,+ BRANCH: BranchGlyph,+ MRG: PullRequestMergedGlyph,+ PR: PullRequestGlyph,+ PAINT: PaintGlyph,+ LAB: FlaskGlyph,+ PARTY: ConfettiGlyph,+ TIME: ClockGlyph,+ 'MIND+': BrainMediumGlyph,+ 'MIND-': BrainOutlineGlyph,+ EMPT1: null,+ EMPT2: null,+ EMPT3: null,+ EMPT4: null,+ EMPT5: null,+ SETUP: SettingsGlyph,+ FOLD: FolderPlusGlyph,+ UPL: CloudUploadGlyph,+ APPS: AllProductsGlyph,+ YOLO: null,+ YEET: null,+ };++/** Literal legends Codex silk-screens onto keycaps instead of a glyph. */+const KEYCAP_LEGENDS: Partial<Record<WorkLouderCodexKeycapId, string>> = {+ YOLO: ':yolo:',+ YEET: ':yeet:',+};++export function WorkLouderCodexKeycapGlyph({+ keycapId,+ className,+}: {+ keycapId: WorkLouderCodexKeycapId;+ className?: string;+}) {+ const legend = KEYCAP_LEGENDS[keycapId];+ if (legend) {+ // Codex silk-screens this legend at 0.68rem; text-10 is the nearest step on our ladder.+ return (+ <span className="font-mono text-10 font-medium tracking-[0]" aria-hidden="true">+ {legend}+ </span>+ );+ }++ const Glyph = KEYCAP_GLYPHS[keycapId];+ if (!Glyph) {+ return (+ <span+ aria-hidden="true"+ className="size-3 rounded-sm border border-[var(--border-default)]"+ />+ );+ }++ return <Glyph aria-hidden="true" className={className ?? 'size-5'} />;+}diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsxnew file mode 100644index 0000000000..7943d2013b--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx@@ -0,0 +1,1266 @@+import {+ useEffect,+ useMemo,+ useState,+ type Dispatch,+ type ReactNode,+ type SetStateAction,+} from 'react';+import {+ ArrowLeft,+ BatteryCharging,+ Check,+ ChevronDown,+ ChevronRight,+ ChevronUp,+ Keyboard,+ RotateCcw,+ Usb,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import * as Select from '@radix-ui/react-select';+import { Switch } from '@/components/ui/switch';+import { useWorkLouderCodex } from '@/hooks/useWorkLouderCodex';+import { useSkillhub } from '@/features/skillhub/hooks/useSkillhub';+import { cn } from '@/lib/utils';+import {+ WorkLouderCodexKeyboardLayout,+ WorkLouderCodexKeycapPicker,+ WorkLouderCodexPartEditor,+ type WorkLouderCodexAgentKey,+ type WorkLouderCodexControlPart,+ type WorkLouderCodexEditableKey,+ type WorkLouderCodexKeyHint,+} from './WorkLouderCodexKeyboardLayout';+import {+ workLouderCodexCommandDescription,+ workLouderCodexCommandName,+} from './workLouderCodexCommandCopy';+import {+ WORKLOUDER_CODEX_AGENT_SOURCES,+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS,+ WORKLOUDER_CODEX_AUTO_DIM_OPTIONS,+ WORKLOUDER_CODEX_COMMAND_IDS,+ WORKLOUDER_CODEX_COMMAND_SLOTS,+ WORKLOUDER_CODEX_DEFAULT_LAYOUT,+ WORKLOUDER_CODEX_DEFAULT_SETTINGS,+ WORKLOUDER_CODEX_ENCODER_ACTIONS,+ WORKLOUDER_CODEX_ENCODER_MODES,+ WORKLOUDER_CODEX_KEYCAP_ACTIONS,+ WORKLOUDER_CODEX_KEYCAP_IDS,+ cloneWorkLouderCodexLayout,+ isWorkLouderCodexDoubleKeycap,+ isWorkLouderCodexMicrophoneKeycap,+ type WorkLouderCodexAction,+ type WorkLouderCodexAgentSource,+ type WorkLouderCodexAutoDim,+ type WorkLouderCodexCommandId,+ type WorkLouderCodexCommandSlot,+ type WorkLouderCodexConnectionStatus,+ type WorkLouderCodexKeycapId,+ type WorkLouderCodexLayout,+ type WorkLouderCodexPreviewInput,+ type WorkLouderCodexPreviewPart,+ type WorkLouderCodexSettingsPatch,+ type WorkLouderCodexState,+} from '../../../shared/workLouderCodex';++function applyPreviewInput(+ input: WorkLouderCodexPreviewInput,+ setPressedParts: Dispatch<SetStateAction<ReadonlySet<WorkLouderCodexPreviewPart>>>,+ setEncoderTurns: Dispatch<SetStateAction<number>>,+ setAnalogStick: Dispatch<SetStateAction<{ angle: number; distance: number } | null>>,+): void {+ setPressedParts((current) => {+ const next = new Set(current);+ if (input.pressed) next.add(input.part);+ else next.delete(input.part);+ return next;+ });+ if (input.part === 'encoder' && input.turn) {+ const turn = input.turn;+ setEncoderTurns((current) => current + turn);+ }+ if (input.part === 'analog') {+ const distance = input.distance ?? 0;+ setAnalogStick(distance > 0 ? { angle: input.angle ?? 0, distance } : null);+ }+}++/** After a merge/split, write the edited assignment onto the still-visible slot. */+function visibleCommandSlotAfterMicrophoneSplit(+ slot: WorkLouderCodexCommandSlot,+ separateMicrophoneKeys: boolean,+): WorkLouderCodexCommandSlot {+ if (separateMicrophoneKeys) {+ return slot === 'ACT10_ACT11' ? 'ACT10' : slot;+ }+ return slot === 'ACT10' || slot === 'ACT11' ? 'ACT10_ACT11' : slot;+}++function compatibleKeycapForSlot(+ slot: WorkLouderCodexCommandSlot,+ keycapId: WorkLouderCodexKeycapId,+): WorkLouderCodexKeycapId {+ const wantsDouble = slot === 'ACT10_ACT11';+ if (wantsDouble === isWorkLouderCodexDoubleKeycap(keycapId)) return keycapId;+ return wantsDouble ? 'MIC' : 'MIC1';+}++interface WorkLouderCodexEntryProps {+ state: WorkLouderCodexState | null;+ loading: boolean;+ onOpen(): void;+}++export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodexEntryProps) {+ const { t } = useTranslation();+ const status = state?.connectionStatus ?? 'connecting';+ return (+ <button+ type="button"+ onClick={onOpen}+ className={cn(+ 'flex w-full items-center gap-3 rounded-xl border p-4 text-left outline-none transition-colors',+ 'border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',+ 'hover:bg-[var(--settings-menu-bg-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ aria-label={t('settings.shortcuts.workLouderCodex.openAria')}+ >+ <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--surface-chip)] text-[var(--text-secondary)]">+ <CodexMicroGlyph />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-13 font-medium text-[var(--text-primary)]">+ {t('settings.shortcuts.workLouderCodex.title')}+ </span>+ <BetaBadge />+ </span>+ <span className="text-12 leading-[1.4] text-[var(--text-secondary)]">+ {t('settings.shortcuts.workLouderCodex.entryDescription')}+ </span>+ </span>+ <span className="flex shrink-0 items-center gap-2">+ <ConnectionStatus status={status} loading={loading} compact />+ <ChevronRight size={16} className="text-[var(--text-tertiary)]" aria-hidden="true" />+ </span>+ </button>+ );+}++export function WorkLouderCodexEntryContainer({ onOpen }: { onOpen(): void }) {+ const { state, loading } = useWorkLouderCodex();+ return <WorkLouderCodexEntry state={state} loading={loading} onOpen={onOpen} />;+}++export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {+ const { t } = useTranslation();+ const {+ state,+ loading,+ saving,+ error,+ setSettings,+ 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);+ const [editingSlot, setEditingSlot] = useState<WorkLouderCodexCommandSlot | null>(null);+ const [editingKeycapId, setEditingKeycapId] = useState<WorkLouderCodexKeycapId | null>(null);+ const [editingAction, setEditingAction] = useState<WorkLouderCodexAction | null>(null);+ const [editingSeparateMicrophoneKeys, setEditingSeparateMicrophoneKeys] = useState(false);+ const [keycapQuery, setKeycapQuery] = useState('');+ const [editingPart, setEditingPart] = useState<+ WorkLouderCodexAgentKey | WorkLouderCodexControlPart | null+ >(null);+ const [pressedParts, setPressedParts] = useState<ReadonlySet<WorkLouderCodexPreviewPart>>(+ () => new Set(),+ );+ const [encoderTurns, setEncoderTurns] = useState(0);+ const [analogStick, setAnalogStick] = useState<{ angle: number; distance: number } | null>(null);+ const settings = state?.settings ?? WORKLOUDER_CODEX_DEFAULT_SETTINGS;+ const enabledSkills = useMemo(+ () => skills.filter((skill) => skill.kind === 'skill' && !skill.parseError),+ [skills],+ );+ const isDefault =+ state !== null &&+ JSON.stringify(state.settings) === JSON.stringify(WORKLOUDER_CODEX_DEFAULT_SETTINGS);++ useEffect(() => {+ if (state) setBrightnessDraft(state.settings.lightingBrightness);+ }, [state?.settings.lightingBrightness]);++ useEffect(() => {+ if (!bootstrapped) void refreshSkills();+ }, [bootstrapped, refreshSkills]);++ useEffect(() => {+ const api = window.electronAPI?.workLouderCodex;+ void api?.setLayoutPreviewActive?.(true);+ return () => {+ void api?.setLayoutPreviewActive?.(false);+ };+ }, []);++ useEffect(() => {+ const unsubscribe = window.electronAPI?.workLouderCodex?.onPreviewInput?.((input) => {+ applyPreviewInput(input, setPressedParts, setEncoderTurns, setAnalogStick);+ });+ return () => unsubscribe?.();+ }, []);++ const commitBrightness = (): void => {+ if (!state || brightnessDraft === state.settings.lightingBrightness) return;+ void setSettings({ lightingBrightness: brightnessDraft });+ };++ const patchLayout = (update: (layout: WorkLouderCodexLayout) => void): void => {+ const layout = cloneWorkLouderCodexLayout(settings.layout);+ update(layout);+ void setSettings({ layout });+ };++ const visibleCommandSlots: WorkLouderCodexCommandSlot[] = settings.layout.separateMicrophoneKeys+ ? WORKLOUDER_CODEX_COMMAND_SLOTS.filter((slot) => slot !== 'ACT10_ACT11')+ : WORKLOUDER_CODEX_COMMAND_SLOTS.filter((slot) => slot !== 'ACT10' && slot !== 'ACT11');++ const applyCommandKeycap = (+ layout: WorkLouderCodexLayout,+ slot: WorkLouderCodexCommandSlot,+ keycapId: WorkLouderCodexKeycapId,+ ): void => {+ const activeSlots = layout.separateMicrophoneKeys+ ? WORKLOUDER_CODEX_COMMAND_SLOTS.filter((item) => item !== 'ACT10_ACT11')+ : WORKLOUDER_CODEX_COMMAND_SLOTS.filter((item) => item !== 'ACT10' && item !== 'ACT11');+ const duplicate = activeSlots.find(+ (item) => item !== slot && layout.slots[item].keycapId === keycapId,+ );+ const previous = { ...layout.slots[slot] };+ layout.slots[slot] = { ...layout.slots[slot], keycapId };+ if (duplicate) layout.slots[duplicate] = previous;+ };++ /**+ * Every part of the board is configured by clicking it. A command key opens+ * the keycap library; the other parts open a small editor of their own. That+ * is why the panel below carries no per-key rows.+ */+ const openPartEditor = (key: WorkLouderCodexEditableKey): void => {+ if (key.startsWith('ACT')) {+ const slot = key as WorkLouderCodexCommandSlot;+ setEditingSlot(slot);+ setEditingKeycapId(settings.layout.slots[slot].keycapId);+ setEditingAction(settings.layout.slots[slot].action);+ setEditingSeparateMicrophoneKeys(settings.layout.separateMicrophoneKeys);+ setKeycapQuery('');+ return;+ }+ // A task key is only its own thing under "custom"; otherwise all six follow+ // the shared rule and there is nothing per-key to edit.+ if (key.startsWith('AG') && settings.agentSource !== 'custom') return;+ setEditingPart(key as WorkLouderCodexAgentKey | WorkLouderCodexControlPart);+ };++ const closeKeycapEditor = (): void => {+ setEditingSlot(null);+ setEditingKeycapId(null);+ setEditingAction(null);+ setEditingSeparateMicrophoneKeys(false);+ setKeycapQuery('');+ };++ const saveKeycapEditor = (): void => {+ if (!editingSlot || !editingKeycapId) return;+ const sourceSlot = editingSlot;+ const keycapId = editingKeycapId;+ const slot = visibleCommandSlotAfterMicrophoneSplit(+ sourceSlot,+ editingSeparateMicrophoneKeys,+ );+ const previous = settings.layout.slots[sourceSlot];+ const draftChanged =+ previous.keycapId !== keycapId ||+ JSON.stringify(previous.action) !== JSON.stringify(editingAction);+ const nextKeycapId = compatibleKeycapForSlot(slot, keycapId);+ const nextAction = isWorkLouderCodexMicrophoneKeycap(nextKeycapId) ? null : editingAction;+ patchLayout((layout) => {+ layout.separateMicrophoneKeys = editingSeparateMicrophoneKeys;+ // Crossing merged/split changes which slot is visible. Keep the newly+ // revealed keys as they were unless this save also changed the keycap.+ if (slot === sourceSlot || draftChanged) {+ applyCommandKeycap(layout, slot, nextKeycapId);+ layout.slots[slot].action = nextAction;+ }+ });+ closeKeycapEditor();+ };++ /** Voice-only at runtime when the printed keycap is a microphone. */+ const editingMicrophoneKeycap = isWorkLouderCodexMicrophoneKeycap(editingKeycapId);+ /** Split/merge lives on the physical microphone position, not the keycap. */+ const editingMicrophoneSlot =+ editingSlot === 'ACT10' || editingSlot === 'ACT11' || editingSlot === 'ACT10_ACT11';++ const hintFor = (key: WorkLouderCodexEditableKey): WorkLouderCodexKeyHint | null => {+ if (key.startsWith('AG')) {+ const index = Number(key.slice(2));+ const slot = state?.agentSlots[index];+ const custom = settings.agentSource === 'custom';+ return {+ legend: key,+ name: custom+ ? (actionLabel(settings.customAgentKeys[index] ?? null, t, state) ??+ t('settings.shortcuts.workLouderCodex.agentKeys.newTask'))+ : (slot?.title || t('settings.shortcuts.workLouderCodex.agentKeys.newTask')),+ // Say which rule the key is following, so it is clear why it is not+ // individually editable outside "custom".+ description: custom+ ? t('settings.shortcuts.workLouderCodex.agentKeys.customDescription')+ : t(+ `settings.shortcuts.workLouderCodex.agentKeys.source.options.${settings.agentSource}`,+ ),+ };+ }+ if (key === 'analog') {+ return {+ legend: t('settings.shortcuts.workLouderCodex.layout.keyboard.analogStick'),+ name: t('settings.shortcuts.workLouderCodex.analog.description'),+ };+ }+ if (key === 'encoder') {+ return {+ legend: t('settings.shortcuts.workLouderCodex.layout.keyboard.encoder'),+ name: t(+ `settings.shortcuts.workLouderCodex.encoder.mode.options.${settings.layout.encoderMode}`,+ ),+ description: t('settings.shortcuts.workLouderCodex.encoder.mode.description'),+ };+ }+ const slot = key as WorkLouderCodexCommandSlot;+ const assignment = settings.layout.slots[slot];+ const action = assignment.action ?? WORKLOUDER_CODEX_KEYCAP_ACTIONS[assignment.keycapId] ?? null;+ if (isWorkLouderCodexMicrophoneKeycap(assignment.keycapId)) {+ return {+ legend: assignment.keycapId,+ name: t('settings.shortcuts.workLouderCodex.microphone.title'),+ description: t('settings.shortcuts.workLouderCodex.microphone.separate.description'),+ };+ }+ if (action) {+ return {+ legend: assignment.keycapId,+ name:+ actionLabel(action, t, state) ??+ t('settings.shortcuts.workLouderCodex.commandKeys.builtIn'),+ description:+ action.type === 'command' ? workLouderCodexCommandDescription(t, action.commandId) : undefined,+ };+ }+ return {+ legend: assignment.keycapId,+ name: t('settings.shortcuts.workLouderCodex.commandKeys.unmapped'),+ };+ };++ return (+ <div className="flex flex-col gap-[14px]">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onBack}+ className="flex size-8 items-center justify-center rounded-md text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-chip)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ aria-label={t('settings.shortcuts.workLouderCodex.back')}+ >+ <ArrowLeft size={17} />+ </button>+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">+ {t('settings.shortcuts.workLouderCodex.title')}+ </h2>+ <BetaBadge />+ </div>+ <button+ type="button"+ disabled={!state || saving || isDefault}+ onClick={() => void resetSettings()}+ className="shrink-0 text-12 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-50"+ >+ {t('settings.shortcuts.reset')}+ </button>+ </div>++ <SettingsCard className="flex items-center gap-4">+ <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')}+ </p>+ <ConnectionStatus status={state?.connectionStatus ?? 'connecting'} loading={loading} />+ </div>+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">+ {connectionDescription(t, state)}+ </p>+ {state?.connectionStatus === 'connected' && 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'}+ </DeviceChip>+ {state.device.isUsbConnection && (+ <DeviceChip icon={<Usb size={12} />}>USB</DeviceChip>+ )}+ {state.device.batteryPercentage !== null && (+ <DeviceChip+ icon={state.device.isCharging ? <BatteryCharging size={12} /> : undefined}+ >+ {state.device.batteryPercentage}%+ </DeviceChip>+ )}+ {state.device.firmwareVersion && (+ <DeviceChip>+ {t('settings.shortcuts.workLouderCodex.device.firmware', {+ version: state.device.firmwareVersion,+ })}+ </DeviceChip>+ )}+ </div>+ )}+ </div>+ </SettingsCard>++ <SettingsCard className="flex flex-col gap-3">+ <div className="flex flex-col gap-1">+ <h3 className="text-13 font-medium text-[var(--text-primary)]">+ {t('settings.shortcuts.workLouderCodex.layout.keyboard.title')}+ </h3>+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">+ {t('settings.shortcuts.workLouderCodex.layout.keyboard.description')}+ </p>+ </div>+ <div className="flex justify-center">+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={state?.agentSlots ?? []}+ disabled={!state || saving}+ labels={{+ analogStick: t('settings.shortcuts.workLouderCodex.layout.keyboard.analogStick'),+ encoder: t('settings.shortcuts.workLouderCodex.layout.keyboard.encoder'),+ indicator: t('settings.shortcuts.workLouderCodex.layout.keyboard.indicator'),+ }}+ hintFor={hintFor}+ canEdit={(key) => !key.startsWith('AG') || settings.agentSource === 'custom'}+ onEditKeycap={openPartEditor}+ pressedParts={pressedParts}+ encoderTurns={encoderTurns}+ analogStick={analogStick}+ />+ </div>+ </SettingsCard>++ {/* The six task keys follow one rule as a set, so it is chosen once here.+ Picking "custom" is what makes them individually clickable. */}+ <SettingsGroup title={t('settings.shortcuts.workLouderCodex.agentKeys.title')}>+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.agentKeys.source.label')}+ description={t(+ `settings.shortcuts.workLouderCodex.agentKeys.source.descriptions.${settings.agentSource}`,+ )}+ control={+ <SelectControl+ value={settings.agentSource}+ disabled={!state || saving}+ ariaLabel={t('settings.shortcuts.workLouderCodex.agentKeys.source.label')}+ onChange={(value) =>+ void setSettings({ agentSource: value as WorkLouderCodexAgentSource })+ }+ options={WORKLOUDER_CODEX_AGENT_SOURCES.map((source) => ({+ value: source,+ label: t(`settings.shortcuts.workLouderCodex.agentKeys.source.options.${source}`),+ }))}+ />+ }+ />+ <SettingsDivider />+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.agentKeys.singleTap.label')}+ description={t('settings.shortcuts.workLouderCodex.agentKeys.singleTap.description')}+ control={+ <Switch+ checked={settings.singleTapAgentKeys}+ disabled={!state || saving}+ onCheckedChange={(checked) => void setSettings({ singleTapAgentKeys: checked })}+ aria-label={t('settings.shortcuts.workLouderCodex.agentKeys.singleTap.aria')}+ />+ }+ />+ </SettingsGroup>++ <WorkLouderCodexKeycapPicker+ open={editingSlot !== null}+ slot={+ editingSlot+ ? visibleCommandSlotAfterMicrophoneSplit(+ editingSlot,+ editingSeparateMicrophoneKeys,+ )+ : editingSlot+ }+ selectedKeycapId={editingKeycapId}+ query={keycapQuery}+ onQueryChange={setKeycapQuery}+ onOpenChange={(open) => {+ if (!open) closeKeycapEditor();+ }}+ onSelect={setEditingKeycapId}+ onCancel={closeKeycapEditor}+ onSave={saveKeycapEditor}+ copy={{+ title: t('settings.shortcuts.workLouderCodex.layout.editor.title'),+ description: t('settings.shortcuts.workLouderCodex.layout.editor.description'),+ searchPlaceholder: t(+ 'settings.shortcuts.workLouderCodex.layout.editor.searchPlaceholder',+ ),+ close: t('settings.shortcuts.workLouderCodex.layout.editor.close'),+ cancel: t('settings.shortcuts.workLouderCodex.layout.editor.cancel'),+ save: t('settings.shortcuts.workLouderCodex.layout.editor.save'),+ }}+ >+ <div className="flex flex-col gap-3">+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.layout.editor.assignedShortcut')}+ description={t('settings.shortcuts.workLouderCodex.commandKeys.builtInDescription')}+ control={+ <ActionSelect+ action={editingAction}+ state={state}+ skills={enabledSkills}+ disabled={!state || saving || !editingSlot || editingMicrophoneKeycap}+ emptyLabel={+ editingMicrophoneKeycap+ ? t('settings.shortcuts.workLouderCodex.microphone.title')+ : t('settings.shortcuts.workLouderCodex.commandKeys.builtIn')+ }+ onChange={setEditingAction}+ />+ }+ />+ {editingMicrophoneSlot && (+ <>+ <SettingsDivider />+ <MicrophoneControls+ separateMicrophoneKeys={editingSeparateMicrophoneKeys}+ state={state}+ saving={saving}+ onSeparateChange={setEditingSeparateMicrophoneKeys}+ />+ </>+ )}+ </div>+ </WorkLouderCodexKeycapPicker>++ {/* Agent keys carry a task, not a keycap, so they get their own editor. */}+ <WorkLouderCodexPartEditor+ open={editingPart !== null && editingPart.startsWith('AG')}+ onOpenChange={(open) => {+ if (!open) setEditingPart(null);+ }}+ title={editingPart ?? ''}+ description={t('settings.shortcuts.workLouderCodex.agentKeys.customDescription')}+ closeLabel={t('settings.shortcuts.workLouderCodex.layout.editor.done')}+ >+ {/* Only this one key. What the six keys follow as a set is chosen once,+ under the board — repeating it here would let a single key's dialog+ silently rewrite the other five. */}+ {editingPart?.startsWith('AG') && (+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.agentKeys.source.options.custom')}+ description={t('settings.shortcuts.workLouderCodex.agentKeys.customDescription')}+ control={+ <ActionSelect+ action={settings.customAgentKeys[Number(editingPart.slice(2))] ?? null}+ state={state}+ skills={enabledSkills}+ disabled={!state || saving}+ emptyLabel={t('settings.shortcuts.workLouderCodex.agentKeys.newTask')}+ allowTasks+ allowKeycaps+ onChange={(action) => {+ const index = Number(editingPart.slice(2));+ const customAgentKeys = settings.customAgentKeys.map((item) =>+ item ? { ...item } : null,+ );+ customAgentKeys[index] = action;+ void setSettings({ customAgentKeys });+ }}+ />+ }+ />+ )}+ </WorkLouderCodexPartEditor>++ <WorkLouderCodexPartEditor+ open={editingPart === 'analog'}+ onOpenChange={(open) => {+ if (!open) setEditingPart(null);+ }}+ title={t('settings.shortcuts.workLouderCodex.analog.title')}+ description={t('settings.shortcuts.workLouderCodex.analog.description')}+ closeLabel={t('settings.shortcuts.workLouderCodex.layout.editor.done')}+ >+ <div className="flex flex-col gap-3">+ {WORKLOUDER_CODEX_ANALOG_DIRECTIONS.map((direction, index) => (+ <div key={direction}>+ {index > 0 && <SettingsDivider />}+ <SettingsRow+ label={t(`settings.shortcuts.workLouderCodex.analog.directions.${direction}`)}+ description={t('settings.shortcuts.workLouderCodex.analog.description')}+ control={+ <ActionSelect+ action={settings.layout.analogStick[direction]}+ state={state}+ skills={enabledSkills}+ disabled={!state || saving}+ emptyLabel={t('settings.shortcuts.workLouderCodex.actions.none')}+ onChange={(action) =>+ patchLayout((layout) => {+ layout.analogStick[direction] = action;+ })+ }+ />+ }+ />+ </div>+ ))}+ </div>+ </WorkLouderCodexPartEditor>++ <WorkLouderCodexPartEditor+ open={editingPart === 'encoder'}+ onOpenChange={(open) => {+ if (!open) setEditingPart(null);+ }}+ title={t('settings.shortcuts.workLouderCodex.encoder.title')}+ description={t('settings.shortcuts.workLouderCodex.encoder.mode.description')}+ closeLabel={t('settings.shortcuts.workLouderCodex.layout.editor.done')}+ >+ <div className="flex flex-col gap-3">+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.encoder.mode.label')}+ description={t('settings.shortcuts.workLouderCodex.encoder.mode.description')}+ control={+ <SelectControl+ value={settings.layout.encoderMode}+ disabled={!state || saving}+ ariaLabel={t('settings.shortcuts.workLouderCodex.encoder.mode.label')}+ onChange={(value) =>+ patchLayout((layout) => {+ layout.encoderMode = value as WorkLouderCodexLayout['encoderMode'];+ })+ }+ options={WORKLOUDER_CODEX_ENCODER_MODES.map((mode) => ({+ value: mode,+ label: t(`settings.shortcuts.workLouderCodex.encoder.mode.options.${mode}`),+ }))}+ />+ }+ />+ {settings.layout.encoderMode === 'custom' &&+ WORKLOUDER_CODEX_ENCODER_ACTIONS.map((gesture) => (+ <div key={gesture}>+ <SettingsDivider />+ <SettingsRow+ label={t(`settings.shortcuts.workLouderCodex.encoder.gestures.${gesture}`)}+ description={t('settings.shortcuts.workLouderCodex.encoder.customDescription')}+ control={+ <ActionSelect+ action={settings.layout.encoder[gesture]}+ state={state}+ skills={enabledSkills}+ disabled={!state || saving}+ emptyLabel={t('settings.shortcuts.workLouderCodex.actions.none')}+ onChange={(action) =>+ patchLayout((layout) => {+ layout.encoder[gesture] = action;+ })+ }+ />+ }+ />+ </div>+ ))}+ </div>+ </WorkLouderCodexPartEditor>++ {error && (+ <div className="flex items-center justify-between gap-3 rounded-xl border border-[var(--error-border)] bg-[var(--error-bg)] px-4 py-3 text-12 text-[var(--error-fg)]">+ <span>{t(`settings.shortcuts.workLouderCodex.errors.${error}`)}</span>+ {error === 'load' && (+ <button+ type="button"+ onClick={() => void reload()}+ className="font-medium underline underline-offset-2"+ >+ {t('settings.shortcuts.workLouderCodex.retry')}+ </button>+ )}+ </div>+ )}++ {state?.device.inputMonitoringPermission !== 'not-required' && (+ <SettingsGroup title={t('settings.shortcuts.workLouderCodex.device.title')}>+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.device.inputMonitoring.label')}+ description={t(+ `settings.shortcuts.workLouderCodex.device.inputMonitoring.${state?.device.inputMonitoringPermission ?? 'unknown'}`,+ )}+ control={+ <button+ type="button"+ onClick={() => void openInputMonitoringSettings()}+ className="rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 py-2 text-12 text-[var(--settings-input-text)] transition-colors hover:bg-[var(--settings-menu-bg-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ >+ {t('settings.shortcuts.workLouderCodex.device.inputMonitoring.open')}+ </button>+ }+ />+ </SettingsGroup>+ )}++ <SettingsGroup title={t('settings.shortcuts.workLouderCodex.lighting.title')}>+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.lighting.brightness.label')}+ description={t('settings.shortcuts.workLouderCodex.lighting.brightness.description')}+ control={+ <div className="flex min-w-[220px] items-center gap-3">+ <input+ type="range"+ min={0}+ max={100}+ step={10}+ value={brightnessDraft}+ disabled={!state || saving}+ onChange={(event) => setBrightnessDraft(Number(event.currentTarget.value))}+ onPointerUp={commitBrightness}+ onKeyUp={commitBrightness}+ onBlur={commitBrightness}+ className="h-1 flex-1 cursor-pointer accent-[var(--switch-track-on)] disabled:cursor-not-allowed disabled:opacity-50"+ aria-label={t('settings.shortcuts.workLouderCodex.lighting.brightness.aria')}+ />+ <span className="w-10 text-right text-12 tabular-nums text-[var(--text-secondary)]">+ {brightnessDraft}%+ </span>+ </div>+ }+ />+ <SettingsDivider />+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.lighting.autoDim.label')}+ description={t('settings.shortcuts.workLouderCodex.lighting.autoDim.description')}+ control={+ <SelectControl+ value={settings.lightingAutoDim}+ disabled={!state || saving}+ ariaLabel={t('settings.shortcuts.workLouderCodex.lighting.autoDim.aria')}+ onChange={(value) =>+ void setSettings({ lightingAutoDim: value as WorkLouderCodexAutoDim })+ }+ options={WORKLOUDER_CODEX_AUTO_DIM_OPTIONS.map((option) => ({+ value: option,+ label: t(`settings.shortcuts.workLouderCodex.lighting.autoDim.options.${option}`),+ }))}+ />+ }+ />+ </SettingsGroup>++ <SettingsCard className="flex items-center justify-between gap-4">+ <div className="flex min-w-0 flex-col gap-1">+ <p className="text-13 font-medium text-[var(--text-primary)]">+ {t('settings.shortcuts.workLouderCodex.layout.reset.title')}+ </p>+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">+ {t('settings.shortcuts.workLouderCodex.layout.reset.description')}+ </p>+ </div>+ <button+ type="button"+ disabled={!state || saving}+ onClick={() =>+ void setSettings({+ layout: cloneWorkLouderCodexLayout(WORKLOUDER_CODEX_DEFAULT_LAYOUT),+ })+ }+ className="inline-flex shrink-0 items-center gap-2 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 py-2 text-12 text-[var(--settings-input-text)] transition-colors hover:bg-[var(--settings-menu-bg-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-50"+ >+ <RotateCcw size={13} />+ {t('settings.shortcuts.workLouderCodex.layout.reset.button')}+ </button>+ </SettingsCard>+ </div>+ );+}++/**+ * Voice options live with the microphone key because that key is the control:+ * how it listens, and whether the board splits it into two single-width keys.+ */+function MicrophoneControls({+ separateMicrophoneKeys,+ state,+ saving,+ onSeparateChange,+}: {+ separateMicrophoneKeys: boolean;+ state: WorkLouderCodexState | null;+ saving: boolean;+ onSeparateChange(value: boolean): void;+}) {+ const { t } = useTranslation();+ return (+ <div className="flex flex-col gap-3">+ {/* How the key listens is not configurable: it behaves like Cindy's own+ microphone, taking both a tap and a hold. All that is left is whether+ the board splits this position into two keys. */}+ <SettingsRow+ label={t('settings.shortcuts.workLouderCodex.microphone.separate.label')}+ description={t('settings.shortcuts.workLouderCodex.microphone.separate.description')}+ control={+ <Switch+ checked={separateMicrophoneKeys}+ disabled={!state || saving}+ onCheckedChange={onSeparateChange}+ aria-label={t('settings.shortcuts.workLouderCodex.microphone.separate.label')}+ />+ }+ />+ </div>+ );+}++function ActionSelect({+ action,+ state,+ skills,+ disabled,+ emptyLabel,+ allowTasks = false,+ allowKeycaps = false,+ onChange,+ className,+}: {+ action: WorkLouderCodexAction | null;+ state: WorkLouderCodexState | null;+ skills: SkillhubSkill[];+ disabled: boolean;+ emptyLabel: string;+ allowTasks?: boolean;+ allowKeycaps?: boolean;+ onChange(action: WorkLouderCodexAction | null): void;+ className?: string;+}) {+ const { t } = useTranslation();+ const groups: SelectOptionGroup[] = [+ { options: [{ value: 'none', label: emptyLabel }] },+ ];+ if (allowTasks && state && state.taskOptions.length > 0) {+ groups.push({+ label: t('settings.shortcuts.workLouderCodex.actions.tasks'),+ options: state.taskOptions.map((task) => ({+ value: `task:${task.id}`,+ label: task.title || t('ccAgent.common.unnamedSession'),+ })),+ });+ }+ groups.push({+ label: t('settings.shortcuts.workLouderCodex.actions.commands'),+ options: WORKLOUDER_CODEX_COMMAND_IDS.map((commandId) => ({+ value: `command:${commandId}`,+ label: workLouderCodexCommandName(t, commandId),+ })),+ });+ if (allowKeycaps) {+ groups.push({+ label: t('settings.shortcuts.workLouderCodex.actions.keycaps'),+ options: WORKLOUDER_CODEX_KEYCAP_IDS.filter(+ (keycapId) => WORKLOUDER_CODEX_KEYCAP_ACTIONS[keycapId],+ ).map((keycapId) => ({+ value: `keycap:${keycapId}`,+ label: keycapId,+ })),+ });+ }+ if (skills.length > 0) {+ groups.push({+ label: t('settings.shortcuts.workLouderCodex.actions.skills'),+ options: skills.map((skill) => ({+ value: `skill:${skill.id}`,+ label: skill.name,+ })),+ });+ }+ return (+ <SelectControl+ value={actionValue(action)}+ disabled={disabled}+ ariaLabel={t('settings.shortcuts.workLouderCodex.actions.choose')}+ onChange={(value) => onChange(parseActionValue(value, state, skills))}+ className={cn('min-w-[190px]', className)}+ groups={groups}+ />+ );+}++interface SelectOption {+ value: string;+ label: string;+ disabled?: boolean;+}++interface SelectOptionGroup {+ label?: string;+ options: SelectOption[];+}++function SelectControl({+ value,+ disabled,+ ariaLabel,+ onChange,+ options,+ groups,+ className,+}: {+ value: string;+ disabled: boolean;+ ariaLabel: string;+ onChange(value: string): void;+ options?: SelectOption[];+ groups?: SelectOptionGroup[];+ className?: string;+}) {+ const resolvedGroups = groups ?? [{ options: options ?? [] }];+ return (+ <Select.Root value={value} onValueChange={onChange} disabled={disabled}>+ <Select.Trigger+ aria-label={ariaLabel}+ className={cn(+ 'flex h-9 min-w-[150px] items-center justify-between gap-2 rounded-full border px-3 text-12',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',+ 'outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',+ 'data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50',+ className,+ )}+ >+ <span className="min-w-0 truncate text-left">+ <Select.Value />+ </span>+ <Select.Icon asChild>+ <ChevronDown size={14} className="shrink-0 opacity-70" />+ </Select.Icon>+ </Select.Trigger>+ <Select.Portal>+ <Select.Content+ position="popper"+ side="bottom"+ align="end"+ sideOffset={4}+ className={cn(+ 'z-[10010] w-[var(--radix-select-trigger-width)] overflow-hidden rounded-xl border p-1.5',+ 'max-h-[min(15rem,var(--radix-select-content-available-height))]',+ 'border-[var(--border-default)] bg-[var(--surface-elevated)]',+ )}+ >+ <Select.ScrollUpButton className="flex h-5 items-center justify-center text-[var(--text-tertiary)]">+ <ChevronUp size={14} />+ </Select.ScrollUpButton>+ <Select.Viewport>+ {resolvedGroups.map((group, groupIndex) => (+ <Select.Group key={group.label ?? `group-${groupIndex}`}>+ {group.label && (+ <Select.Label className="px-2.5 py-1 text-11 text-[var(--text-tertiary)]">+ {group.label}+ </Select.Label>+ )}+ {group.options.map((option) => (+ <Select.Item+ key={option.value}+ value={option.value}+ disabled={option.disabled}+ className={cn(+ 'flex w-full cursor-pointer select-none items-center gap-2 rounded-[8px] px-2.5 py-1.5 text-left text-12 outline-none',+ 'text-[var(--text-primary)]',+ 'data-[highlighted]:bg-[var(--surface-hover)]',+ 'data-[state=checked]:font-medium',+ 'data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50',+ )}+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">+ <Select.ItemIndicator>+ <Check size={14} strokeWidth={2.25} />+ </Select.ItemIndicator>+ </span>+ <Select.ItemText>{option.label}</Select.ItemText>+ </Select.Item>+ ))}+ </Select.Group>+ ))}+ </Select.Viewport>+ <Select.ScrollDownButton className="flex h-5 items-center justify-center text-[var(--text-tertiary)]">+ <ChevronDown size={14} />+ </Select.ScrollDownButton>+ </Select.Content>+ </Select.Portal>+ </Select.Root>+ );+}++function SettingsCard({ className, children }: { className?: string; children: ReactNode }) {+ return (+ <div+ className={cn(+ 'rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5',+ className,+ )}+ >+ {children}+ </div>+ );+}++function SettingsGroup({ title, children }: { title: string; children: ReactNode }) {+ return (+ <div className="flex flex-col gap-2">+ <h3 className="px-1 text-13 font-medium text-[var(--settings-section-title)]">{title}</h3>+ <SettingsCard>{children}</SettingsCard>+ </div>+ );+}++function SettingsRow({+ label,+ description,+ control,+}: {+ label: string;+ description: string;+ control: ReactNode;+}) {+ return (+ <div className="flex flex-wrap items-center justify-between gap-5 py-2">+ <div className="flex min-w-[220px] flex-1 flex-col gap-1">+ <p className="text-13 font-medium text-[var(--text-primary)]">{label}</p>+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">{description}</p>+ </div>+ <div className="min-w-0 shrink-0 max-sm:w-full">{control}</div>+ </div>+ );+}++function SettingsDivider() {+ return <div className="my-1 h-px bg-[var(--settings-theme-card-border)]" />;+}++function BetaBadge() {+ const { t } = useTranslation();+ return (+ <span className="shrink-0 rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)] px-2 py-[1px] text-10 font-medium uppercase leading-[1.5] tracking-wide text-[var(--text-secondary)]">+ {t('settings.shortcuts.workLouderCodex.beta')}+ </span>+ );+}++function DeviceChip({ icon, children }: { icon?: ReactNode; children: ReactNode }) {+ return (+ <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--settings-theme-card-border)] bg-[var(--surface-chip)] px-2 py-1 text-11 text-[var(--text-secondary)]">+ {icon}+ {children}+ </span>+ );+}++function ConnectionStatus({+ status,+ loading,+ compact = false,+}: {+ status: WorkLouderCodexConnectionStatus;+ loading: boolean;+ compact?: boolean;+}) {+ const { t } = useTranslation();+ const effectiveStatus = loading ? 'connecting' : status;+ const dotClass =+ effectiveStatus === 'connected'+ ? 'bg-[var(--settings-badge-connected)]'+ : effectiveStatus === 'error' || effectiveStatus === 'unavailable'+ ? 'bg-[var(--error-fg)]'+ : 'bg-[var(--text-tertiary)]';+ return (+ <span+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full text-12 text-[var(--text-secondary)]',+ compact+ ? 'px-1.5 py-1'+ : 'border border-[var(--settings-theme-card-border)] bg-[var(--surface-chip)] px-2.5 py-1.5',+ )}+ >+ <span className={cn('size-1.5 rounded-full', dotClass)} aria-hidden="true" />+ {t(`settings.shortcuts.workLouderCodex.connection.status.${effectiveStatus}`)}+ </span>+ );+}++/**+ * Icon for the Codex Micro entry row: the device's own silhouette rather than a+ * generic keyboard. Round controls in the top corners, six task keys, a row of+ * command keys, and the double-width microphone — the same shape as the board+ * on the detail page, reduced to what still reads at 20px.+ *+ * Drawn as SVG so the 4.5-unit keys stay crisp, and in `currentColor` so it+ * picks up the chip's text colour in both themes.+ */+function CodexMicroGlyph() {+ // Four columns of 4.5 with 1 between them, inset half a unit.+ const track = [0.5, 6, 11.5, 17];+ return (+ <svg width={20} height={20} viewBox="0 0 22 22" fill="none" aria-hidden="true">+ {/* Row 1 — encoder, two task keys, analog stick. */}+ <circle cx={2.75} cy={2.75} r={2.25} fill="currentColor" opacity={0.55} />+ <rect x={6} y={0.5} width={4.5} height={4.5} rx={1} fill="currentColor" opacity={0.95} />+ <rect x={11.5} y={0.5} width={4.5} height={4.5} rx={1} fill="currentColor" opacity={0.95} />+ <circle cx={19.25} cy={2.75} r={2.25} fill="currentColor" opacity={0.55} />++ {/* Row 2 — the remaining four task keys, the brightest caps on the board. */}+ {track.map((x) => (+ <rect+ key={`task-${x}`}+ x={x}+ y={6}+ width={4.5}+ height={4.5}+ rx={1}+ fill="currentColor"+ opacity={0.95}+ />+ ))}++ {/* Row 3 — the four command keys. */}+ {track.map((x) => (+ <rect+ key={`command-${x}`}+ x={x}+ y={11.5}+ width={4.5}+ height={4.5}+ rx={1}+ fill="currentColor"+ opacity={0.45}+ />+ ))}++ {/* Row 4 — status lights, the double-width microphone key, Codex. */}+ <circle cx={2.75} cy={19.25} r={1} fill="currentColor" opacity={0.45} />+ <rect x={6} y={17} width={10} height={4.5} rx={1} fill="currentColor" opacity={0.45} />+ <rect x={17} y={17} width={4.5} height={4.5} rx={1} fill="currentColor" opacity={0.45} />+ </svg>+ );+}++function connectionDescription(+ t: ReturnType<typeof useTranslation>['t'],+ state: WorkLouderCodexState | null,+): string {+ const key = state?.connectionReason ?? state?.connectionStatus ?? 'connecting';+ return t(`settings.shortcuts.workLouderCodex.connection.descriptions.${key}`);+}++/**+ * 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.+ */+function actionLabel(+ action: WorkLouderCodexAction | null,+ t?: ReturnType<typeof useTranslation>['t'],+ state?: WorkLouderCodexState | null,+): string | null {+ if (!action) return null;+ switch (action.type) {+ case 'command':+ return t ? workLouderCodexCommandName(t, action.commandId) : action.commandId;+ case 'skill':+ return action.name;+ case 'keycap':+ return action.keycapId;+ case 'composer-text':+ return action.text;+ case 'external-url':+ return action.url;+ case 'task':+ return state?.taskOptions.find((task) => task.id === action.sessionId)?.title ?? action.sessionId;+ }+}++function actionValue(action: WorkLouderCodexAction | null): string {+ if (!action) return 'none';+ switch (action.type) {+ case 'command':+ return `command:${action.commandId}`;+ case 'task':+ return `task:${action.sessionId}`;+ case 'keycap':+ return `keycap:${action.keycapId}`;+ case 'skill':+ return `skill:${action.skillId}`;+ case 'composer-text':+ return `text:${action.text}`;+ case 'external-url':+ return `url:${action.url}`;+ }+}++function parseActionValue(+ value: string,+ state: WorkLouderCodexState | null,+ skills: SkillhubSkill[],+): WorkLouderCodexAction | null {+ if (value === 'none') return null;+ if (value.startsWith('command:')) {+ return { type: 'command', commandId: value.slice(8) as WorkLouderCodexCommandId };+ }+ if (value.startsWith('task:')) {+ const sessionId = value.slice(5);+ return state?.taskOptions.some((task) => task.id === sessionId)+ ? { type: 'task', sessionId }+ : null;+ }+ if (value.startsWith('keycap:')) {+ return { type: 'keycap', keycapId: value.slice(7) as WorkLouderCodexKeycapId };+ }+ if (value.startsWith('skill:')) {+ const skillId = value.slice(6);+ const skill = skills.find((item) => item.id === skillId);+ return skill ? { type: 'skill', skillId, name: skill.name } : null;+ }+ if (value.startsWith('text:')) {+ return { type: 'composer-text', text: value.slice(5) };+ }+ if (value.startsWith('url:')) {+ const url = value.slice(4);+ try {+ const parsed = new URL(url);+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;+ } catch {+ return null;+ }+ return { type: 'external-url', url };+ }+ return null;+}++export type { WorkLouderCodexSettingsPatch };diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsxindex a849d49d41..dbfc6591b8 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx@@ -181,9 +181,7 @@ describe('CustomProviderDialog accessibility', () => {await user.clear(baseUrl);await user.type(baseUrl, 'https://new.example.test/v1');await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));- expect(- screen.queryByText('settings.providers.custom.fields.apiKeySaved'),- ).toBeNull();+ expect(screen.queryByText('settings.providers.custom.fields.apiKeySaved')).toBeNull();expect(apiKey.getAttribute('placeholder')).toBe('settings.providers.custom.fields.apiKeyPlaceholder',);@@ -310,10 +308,14 @@ describe('CustomProviderDialog accessibility', () => {await user.clear(baseUrl);await user.type(baseUrl, 'https://new.example.test/v1');await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));- await user.click(screen.getByRole('button', { name: 'settings.providers.custom.authMode.none' }));+ await user.click(+ screen.getByRole('button', { name: 'settings.providers.custom.authMode.none' }),+ );await user.clear(baseUrl);await user.type(baseUrl, 'https://old.example.test/v1');- await user.click(screen.getByRole('button', { name: 'settings.providers.custom.authMode.apiKey' }));+ await user.click(+ screen.getByRole('button', { name: 'settings.providers.custom.authMode.apiKey' }),+ );const restoredApiKey = await screen.findByPlaceholderText('settings.providers.custom.fields.apiKeyEditPlaceholder',@@ -333,7 +335,9 @@ describe('CustomProviderDialog accessibility', () => {},},};- customProviderMocks.readCustomProviderKey.mockRejectedValue(new Error('safeStorage unavailable'));+ customProviderMocks.readCustomProviderKey.mockRejectedValue(+ new Error('safeStorage unavailable'),+ );const user = userEvent.setup();render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);@@ -416,9 +420,7 @@ describe('CustomProviderDialog accessibility', () => {render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);await waitFor(() => expect(customProviderMocks.readCustomProviderKey).toHaveBeenCalled());- expect(- screen.queryByText('settings.providers.custom.fields.requestPath'),- ).toBeNull();+ expect(screen.queryByText('settings.providers.custom.fields.requestPath')).toBeNull();await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());diff --git a/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.mutationRace.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.mutationRace.test.tsxindex 517efce6e6..b2b578116a 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.mutationRace.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.mutationRace.test.tsx@@ -16,6 +16,14 @@ const mocks = vi.hoisted(() => ({getCombos: vi.fn(),}));+vi.mock('@/features/skillhub/hooks/useSkillhub', () => ({+ useSkillhub: () => ({+ skills: [],+ bootstrapped: true,+ refresh: vi.fn(async () => []),+ }),+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));@@ -47,6 +55,22 @@ describe('KeyboardShortcutsSection mutation ordering', () => {vi.restoreAllMocks();});+ it('opens the Work Louder device settings from the keyboard-shortcuts page', () => {+ mocks.getOverrides.mockReturnValue({});+ mocks.getCombos.mockReturnValue([]);+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ onAuthStateChange: vi.fn(() => () => {}),+ },+ });++ render(<KeyboardShortcutsSection />);+ fireEvent.click(screen.getByLabelText('settings.shortcuts.workLouderCodex.openAria'));++ expect(screen.getByLabelText('settings.shortcuts.workLouderCodex.back')).toBeTruthy();+ });+it('ignores an older mutation failure after a newer mutation succeeds', async () => {let rejectOlder!: (reason: unknown) => void;const olderRequest = new Promise<{ overrides: Record<string, unknown> }>((_resolve, reject) => {@@ -59,6 +83,7 @@ describe('KeyboardShortcutsSection mutation ordering', () => {Object.defineProperty(window, 'electronAPI', {configurable: true,value: {+ onAuthStateChange: vi.fn(() => () => {}),appShortcuts: {setOverride,clearOverride,@@ -92,6 +117,7 @@ describe('KeyboardShortcutsSection mutation ordering', () => {Object.defineProperty(window, 'electronAPI', {configurable: true,value: {+ onAuthStateChange: vi.fn(() => () => {}),appShortcuts: {setOverride,clearOverride: vi.fn(async () => ({ overrides: {} })),diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexKeyboardLayout.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexKeyboardLayout.test.tsxnew file mode 100644index 0000000000..32eb841d04--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexKeyboardLayout.test.tsx@@ -0,0 +1,336 @@+// @vitest-environment jsdom++import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import {+ WORKLOUDER_CODEX_KEYCAP_IDS,+ createWorkLouderCodexDefaultSettings,+} from '../../../../shared/workLouderCodex';+import {+ WorkLouderCodexKeyboardLayout,+ WorkLouderCodexKeycapPicker,+} from '../WorkLouderCodexKeyboardLayout';+import { WorkLouderCodexKeycapGlyph } from '../WorkLouderCodexKeycapGlyphs';++const LABELS = { analogStick: '摇杆', encoder: '旋钮', indicator: '状态指示灯' };++function agentSlots(titles: (string | null)[] = []) {+ return Array.from({ length: 6 }, (_, slot) => ({+ slot,+ sessionId: null,+ title: titles[slot] ?? null,+ action: null,+ }));+}++describe('WorkLouderCodexKeyboardLayout', () => {+ it('draws the board as 4x4: stick, six agent keys, four command keys, mic and Codex', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots(['最近任务'])}+ labels={LABELS}+ onEditKeycap={vi.fn()}+ />,+ );++ expect(screen.getByTestId('worklouder-codex-keyboard-layout')).toBeTruthy();+ // Six agent keys, addressed by slot id since nothing is printed on them.+ for (let index = 0; index < 6; index += 1) {+ const slot = `AG0${index}`;+ expect(screen.getByRole('button', { name: new RegExp(`^${slot}`) })).toBeTruthy();+ }+ // The four command keys plus the merged microphone key and Codex.+ expect(screen.getByRole('button', { name: /^FAST/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^APPR/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^REJ/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^SPLIT/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^MIC/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^CODEX/ })).toBeTruthy();+ // The stick and the encoder are parts of the board, not decoration.+ expect(screen.getByRole('button', { name: /摇杆/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /旋钮/ })).toBeTruthy();+ });++ it('shows a pressed key when the physical board reports that part', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ pressedParts={new Set(['ACT06'])}+ onEditKeycap={vi.fn()}+ />,+ );++ expect(screen.getByRole('button', { name: /^FAST/ }).getAttribute('aria-pressed')).toBe('true');+ expect(screen.getByRole('button', { name: /^APPR/ }).getAttribute('aria-pressed')).toBe('false');+ });++ it('turns the encoder by each detent and moves the stick by angle and distance', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ const { rerender } = render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ encoderTurns={2}+ analogStick={{ angle: 0.75, distance: 1 }}+ onEditKeycap={vi.fn()}+ />,+ );++ const encoder = screen.getByRole('button', { name: /旋钮/ }).querySelector('[data-encoder-turns]');+ const stick = screen.getByTestId('worklouder-codex-stick-cap');+ expect(encoder?.getAttribute('data-encoder-turns')).toBe('2');+ expect((encoder as HTMLElement | null)?.style.transform).toBe('rotate(-36deg)');+ expect(stick.getAttribute('style')).toContain('translate(0px, -10px)');++ rerender(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ encoderTurns={-1}+ analogStick={{ angle: 0.5, distance: 0.5 }}+ onEditKeycap={vi.fn()}+ />,+ );++ const moved = screen.getByTestId('worklouder-codex-stick-cap');+ expect(+ screen.getByRole('button', { name: /旋钮/ }).querySelector('[data-encoder-turns]')?.getAttribute(+ 'data-encoder-turns',+ ),+ ).toBe('-1');+ expect(moved.getAttribute('style')).toContain('translate(-5px, 0px)');+ });++ it('puts the encoder and the stick in the corners they occupy on the device', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ const { container } = render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ onEditKeycap={vi.fn()}+ />,+ );++ // Encoder top-left, stick top-right. Naming alone never caught these being+ // swapped, so assert the order they appear in the first row.+ const firstRow = container.querySelector('[data-testid] > div');+ const labels = Array.from(firstRow?.children ?? []).map((child) =>+ child.matches('[aria-label]')+ ? child.getAttribute('aria-label')+ : child.querySelector('[aria-label]')?.getAttribute('aria-label'),+ );+ expect(labels).toHaveLength(4);+ expect(labels[0]).toMatch(/旋钮/);+ expect(labels[3]).toMatch(/摇杆/);+ });++ it('prints no lettering on the keys — the real keycaps carry artwork only', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ const { container } = render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots(['最近任务'])}+ labels={LABELS}+ onEditKeycap={vi.fn()}+ />,+ );++ // Legends and titles belong in the hover tooltip, never on the board.+ expect(container.textContent).toBe('');+ });++ it('splits the microphone into two single-width keys when the layout asks', () => {+ const settings = createWorkLouderCodexDefaultSettings();+ settings.layout.separateMicrophoneKeys = true;++ render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ onEditKeycap={vi.fn()}+ />,+ );++ expect(screen.getByRole('button', { name: /^MIC1/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /^EMPT1/ })).toBeTruthy();+ expect(screen.queryByRole('button', { name: /^MIC$/ })).toBeNull();+ });++ it('opens the editor for whichever part was clicked', () => {+ const onEditKeycap = vi.fn();+ const settings = createWorkLouderCodexDefaultSettings();++ render(+ <WorkLouderCodexKeyboardLayout+ layout={settings.layout}+ agentSlots={agentSlots()}+ labels={LABELS}+ onEditKeycap={onEditKeycap}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: /^FAST/ }));+ expect(onEditKeycap).toHaveBeenLastCalledWith('ACT06');++ fireEvent.click(screen.getByRole('button', { name: /^AG00/ }));+ expect(onEditKeycap).toHaveBeenLastCalledWith('AG00');++ fireEvent.click(screen.getByRole('button', { name: /摇杆/ }));+ expect(onEditKeycap).toHaveBeenLastCalledWith('analog');++ fireEvent.click(screen.getByRole('button', { name: /旋钮/ }));+ expect(onEditKeycap).toHaveBeenLastCalledWith('encoder');+ });+});++describe('WorkLouderCodexKeycapPicker', () => {+ const copy = {+ title: '编辑键帽',+ description: '选择键帽',+ searchPlaceholder: '搜索键帽',+ close: '关闭',+ cancel: '取消',+ save: '保存',+ };++ it('filters keycaps and keeps save/cancel explicit', () => {+ const onQueryChange = vi.fn();+ const onOpenChange = vi.fn();+ const onSelect = vi.fn();+ const onSave = vi.fn();+ const onCancel = vi.fn();++ const { rerender } = render(+ <WorkLouderCodexKeycapPicker+ open+ slot="ACT06"+ selectedKeycapId="FAST"+ query=""+ onQueryChange={onQueryChange}+ onOpenChange={onOpenChange}+ onSelect={onSelect}+ onSave={onSave}+ onCancel={onCancel}+ copy={copy}+ />,+ );++ const search = screen.getByPlaceholderText('搜索键帽');+ fireEvent.change(search, { target: { value: 'git' } });+ expect(onQueryChange).toHaveBeenCalledWith('git');++ rerender(+ <WorkLouderCodexKeycapPicker+ open+ slot="ACT06"+ selectedKeycapId="FAST"+ query="git"+ onQueryChange={onQueryChange}+ onOpenChange={onOpenChange}+ onSelect={onSelect}+ onSave={onSave}+ onCancel={onCancel}+ copy={copy}+ />,+ );++ expect(screen.queryByRole('button', { name: 'FAST' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'GIT' }));+ expect(onSelect).toHaveBeenCalledWith('GIT');++ fireEvent.click(screen.getByRole('button', { name: '取消' }));+ expect(onCancel).toHaveBeenCalledOnce();+ expect(onOpenChange).toHaveBeenCalledWith(false);++ fireEvent.click(screen.getByRole('button', { name: '保存' }));+ expect(onSave).toHaveBeenCalledOnce();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('shows the caller-supplied controls under the grid', () => {+ render(+ <WorkLouderCodexKeycapPicker+ open+ slot="ACT06"+ selectedKeycapId="FAST"+ query=""+ onQueryChange={vi.fn()}+ onOpenChange={vi.fn()}+ onSelect={vi.fn()}+ copy={copy}+ >+ <span>已分配动作</span>+ </WorkLouderCodexKeycapPicker>,+ );++ expect(screen.getByText('已分配动作')).toBeTruthy();+ });+});++describe('default stick and encoder bindings', () => {+ it('maps the stick to the two axes of the screen and the encoder to the task list', () => {+ // These defaults were wrong once (plan mode, history back/forward), which+ // no test caught. Pin them: the stick scrolls the conversation up/down and+ // opens the panel on whichever side it is pushed toward.+ const { layout } = createWorkLouderCodexDefaultSettings();++ expect(layout.analogStick.up).toEqual({+ type: 'command',+ commandId: 'conversation.scrollUp',+ });+ expect(layout.analogStick.down).toEqual({+ type: 'command',+ commandId: 'conversation.scrollDown',+ });+ expect(layout.analogStick.left).toEqual({ type: 'command', commandId: 'toggleSidebar' });+ expect(layout.analogStick.right).toEqual({+ type: 'command',+ commandId: 'toggleRightSidebar',+ });+ expect(layout.encoderMode).toBe('session-switch');+ });+});++describe('WorkLouderCodexKeycapGlyph', () => {+ it('draws Codex artwork for every keycap the hardware can wear', () => {+ for (const keycapId of WORKLOUDER_CODEX_KEYCAP_IDS) {+ const { container, unmount } = render(<WorkLouderCodexKeycapGlyph keycapId={keycapId} />);+ // Blank keycaps are a bordered square and the two joke keys are silk-screened+ // text; everything else must resolve to real Codex vector artwork.+ const blank = keycapId.startsWith('EMPT');+ const legend = keycapId === 'YOLO' || keycapId === 'YEET';+ if (blank) {+ expect(container.querySelector('svg')).toBeNull();+ expect(container.textContent).toBe('');+ } else if (legend) {+ expect(container.textContent).toBe(keycapId === 'YOLO' ? ':yolo:' : ':yeet:');+ } else {+ const svg = container.querySelector('svg');+ expect(svg, `${keycapId} has no glyph`).not.toBeNull();+ expect(+ svg?.querySelector('path, circle, rect'),+ `${keycapId} glyph is empty`,+ ).not.toBeNull();+ }+ unmount();+ }+ });++ it('gives the microphone keycaps the same glyph in both sizes', () => {+ const wide = render(<WorkLouderCodexKeycapGlyph keycapId="MIC" />);+ const single = render(<WorkLouderCodexKeycapGlyph keycapId="MIC1" />);+ expect(wide.container.querySelector('svg')?.innerHTML).toBe(+ single.container.querySelector('svg')?.innerHTML,+ );+ });+});diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsxnew file mode 100644index 0000000000..e01e0b8a70--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx@@ -0,0 +1,413 @@+// @vitest-environment jsdom++import { act, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ createWorkLouderCodexDefaultSettings,+} from '../../../../shared/workLouderCodex';++const mocks = vi.hoisted(() => ({+ setSettings: vi.fn(),+ resetSettings: vi.fn(),+ openInputMonitoringSettings: vi.fn(),+ reload: vi.fn(),+ setLayoutPreviewActive: vi.fn(),+ previewListeners: [] as Array<+ (input: {+ part: string;+ pressed: boolean;+ turn?: number;+ angle?: number;+ distance?: number;+ }) => void+ >,+ /** Which rule the six task keys follow; drives whether they are clickable. */+ agentSource: 'sidebar' as string,+ layout: null as ReturnType<typeof createWorkLouderCodexDefaultSettings>['layout'] | null,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/hooks/useWorkLouderCodex', () => ({+ useWorkLouderCodex: () => ({+ state: {+ connectionStatus: 'connected',+ connectionReason: null,+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },+ settings: {+ ...createWorkLouderCodexDefaultSettings(),+ lightingBrightness: 70,+ agentSource: mocks.agentSource,+ layout: mocks.layout ?? createWorkLouderCodexDefaultSettings().layout,+ },+ agentSlots: Array.from({ length: 6 }, (_, slot) => ({+ slot,+ sessionId: null,+ title: null,+ action: null,+ })),+ taskOptions: [],+ agentSlotCount: 6,+ },+ loading: false,+ saving: false,+ error: null,+ setSettings: mocks.setSettings,+ resetSettings: mocks.resetSettings,+ openInputMonitoringSettings: mocks.openInputMonitoringSettings,+ reload: mocks.reload,+ }),+}));++vi.mock('@/features/skillhub/hooks/useSkillhub', () => ({+ useSkillhub: () => ({+ skills: [],+ bootstrapped: true,+ refresh: vi.fn(),+ }),+}));++import { WorkLouderCodexEntry, WorkLouderCodexSettings } from '../WorkLouderCodexSettings';++async function chooseSelectOption(+ trigger: string | HTMLElement,+ optionName: string,+): Promise<void> {+ const combobox = typeof trigger === 'string' ? screen.getByRole('combobox', { name: trigger }) : trigger;+ fireEvent.keyDown(combobox, { key: 'Enter' });+ fireEvent.click(await screen.findByRole('option', { name: optionName }));+}++describe('WorkLouderCodexSettings', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ Element.prototype.scrollIntoView = vi.fn();+ mocks.agentSource = 'sidebar';+ mocks.layout = createWorkLouderCodexDefaultSettings().layout;+ mocks.previewListeners = [];+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ workLouderCodex: {+ setLayoutPreviewActive: mocks.setLayoutPreviewActive,+ onPreviewInput: (+ callback: (input: {+ part: string;+ pressed: boolean;+ turn?: number;+ angle?: number;+ distance?: number;+ }) => void,+ ) => {+ mocks.previewListeners.push(callback);+ return () => {+ mocks.previewListeners = mocks.previewListeners.filter((item) => item !== callback);+ };+ },+ },+ },+ });+ });++ afterEach(() => {+ Reflect.deleteProperty(window, 'electronAPI');+ });++ it('renders a keyboard-shortcuts entry with live connection status', () => {+ const onOpen = vi.fn();+ render(+ <WorkLouderCodexEntry+ state={{+ connectionStatus: 'connected',+ connectionReason: null,+ 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={onOpen}+ />,+ );++ fireEvent.click(+ screen.getByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),+ );++ expect(onOpen).toHaveBeenCalledOnce();+ expect(screen.getByText('settings.shortcuts.workLouderCodex.beta')).toBeTruthy();+ expect(+ screen.getByText('settings.shortcuts.workLouderCodex.connection.status.connected'),+ ).toBeTruthy();+ });++ it('shows the six task keys and writes the settings that remain on the panel', async () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ // Default source is "recent", so the keys follow the shared rule and are+ // not individually clickable.+ expect(screen.getByRole('img', { name: /AG00/ })).toBeTruthy();+ expect(screen.getByRole('img', { name: /AG05/ })).toBeTruthy();+ expect(screen.getByTestId('worklouder-codex-keyboard-layout').parentElement?.className).toContain(+ 'justify-center',+ );+ expect(mocks.setLayoutPreviewActive).toHaveBeenCalledWith(true);++ const slider = screen.getByRole('slider', {+ name: 'settings.shortcuts.workLouderCodex.lighting.brightness.aria',+ });+ fireEvent.change(slider, { target: { value: '40' } });+ fireEvent.pointerUp(slider);+ expect(mocks.setSettings).toHaveBeenCalledWith({ lightingBrightness: 40 });++ await chooseSelectOption(+ 'settings.shortcuts.workLouderCodex.lighting.autoDim.aria',+ 'settings.shortcuts.workLouderCodex.lighting.autoDim.options.10-minutes',+ );+ expect(mocks.setSettings).toHaveBeenCalledWith({ lightingAutoDim: '10-minutes' });+ });++ it('sets all six task keys at once, since they follow one shared rule', async () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ // One control for the set, not one per key.+ await chooseSelectOption(+ 'settings.shortcuts.workLouderCodex.agentKeys.source.label',+ 'settings.shortcuts.workLouderCodex.agentKeys.source.options.last-sent',+ );+ expect(mocks.setSettings).toHaveBeenCalledWith({ agentSource: 'last-sent' });++ fireEvent.click(+ screen.getByRole('switch', {+ name: 'settings.shortcuts.workLouderCodex.agentKeys.singleTap.aria',+ }),+ );+ expect(mocks.setSettings).toHaveBeenCalledWith({ singleTapAgentKeys: true });+ });++ it('only lets a task key be set on its own under "custom"', async () => {+ mocks.agentSource = 'custom';+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ // Now each key is its own target, and its editor writes only that slot.+ fireEvent.click(screen.getByRole('button', { name: /AG02/ }));+ await chooseSelectOption(+ 'settings.shortcuts.workLouderCodex.actions.choose',+ 'New Task',+ );++ expect(mocks.setSettings).toHaveBeenCalledWith({+ customAgentKeys: [null, null, { type: 'command', commandId: 'newTask' }, null, null, null],+ });+ });++ it('opens the analog stick and encoder editors from the board', async () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(+ screen.getByRole('button', {+ name: /settings\.shortcuts\.workLouderCodex\.layout\.keyboard\.analogStick/,+ }),+ );+ // One select per direction; the first is "up".+ const [up] = screen.getAllByRole('combobox', {+ name: 'settings.shortcuts.workLouderCodex.actions.choose',+ });+ await chooseSelectOption(up, 'Toggle Sidebar');+ expect(mocks.setSettings).toHaveBeenCalledWith({+ layout: expect.objectContaining({+ analogStick: expect.objectContaining({+ up: { type: 'command', commandId: 'toggleSidebar' },+ }),+ }),+ });+ });++ it('restores all device settings to their defaults', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: 'settings.shortcuts.reset' }));++ expect(mocks.resetSettings).toHaveBeenCalledOnce();+ });++ it('saves a graphical keycap choice and swaps a duplicate assignment', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^FAST/ }));+ fireEvent.click(screen.getByRole('button', { name: 'APPR' }));+ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.save',+ }),+ );++ expect(mocks.setSettings).toHaveBeenCalledWith({+ layout: expect.objectContaining({+ slots: expect.objectContaining({+ ACT06: expect.objectContaining({ keycapId: 'APPR' }),+ ACT07: expect.objectContaining({ keycapId: 'FAST' }),+ }),+ }),+ });+ });++ it('cancels graphical keycap editing without writing settings', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^FAST/ }));+ fireEvent.click(screen.getByRole('button', { name: 'GIT' }));+ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.cancel',+ }),+ );++ expect(mocks.setSettings).not.toHaveBeenCalled();+ });++ it('does not write microphone-split or assigned-action drafts until Save', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^MIC/ }));+ fireEvent.click(+ screen.getByRole('switch', {+ name: 'settings.shortcuts.workLouderCodex.microphone.separate.label',+ }),+ );+ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.cancel',+ }),+ );++ expect(mocks.setSettings).not.toHaveBeenCalled();+ });++ it('keeps existing single keys when only the microphone split is saved', () => {+ mocks.layout = {+ ...createWorkLouderCodexDefaultSettings().layout,+ slots: {+ ...createWorkLouderCodexDefaultSettings().layout.slots,+ ACT10: { keycapId: 'FAST', action: { type: 'command', commandId: 'newTask' } },+ },+ };+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^MIC/ }));+ fireEvent.click(+ screen.getByRole('switch', {+ name: 'settings.shortcuts.workLouderCodex.microphone.separate.label',+ }),+ );+ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.save',+ }),+ );++ expect(mocks.setSettings).toHaveBeenCalledWith({+ layout: expect.objectContaining({+ separateMicrophoneKeys: true,+ slots: expect.objectContaining({+ ACT10: expect.objectContaining({+ keycapId: 'FAST',+ action: { type: 'command', commandId: 'newTask' },+ }),+ ACT11: expect.objectContaining({ keycapId: 'EMPT1' }),+ ACT10_ACT11: expect.objectContaining({ keycapId: 'MIC' }),+ }),+ }),+ });+ });++ it('writes a compatible single-width keycap when a merged key is split', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^MIC/ }));+ fireEvent.click(screen.getByRole('button', { name: 'EMPT5' }));+ fireEvent.click(+ screen.getByRole('switch', {+ name: 'settings.shortcuts.workLouderCodex.microphone.separate.label',+ }),+ );+ fireEvent.click(screen.getByRole('button', { name: 'MIC1' }));+ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.save',+ }),+ );++ expect(mocks.setSettings).toHaveBeenCalledWith({+ layout: expect.objectContaining({+ separateMicrophoneKeys: true,+ slots: expect.objectContaining({+ ACT10: expect.objectContaining({ keycapId: 'MIC1', action: null }),+ ACT10_ACT11: expect.objectContaining({ keycapId: 'MIC' }),+ }),+ }),+ });+ });++ it('disables assigned actions for a microphone keycap on a regular command slot', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /^FAST/ }));+ fireEvent.click(screen.getByRole('button', { name: 'MIC1' }));++ expect(+ (+ screen.getByRole('combobox', {+ name: 'settings.shortcuts.workLouderCodex.actions.choose',+ }) as HTMLSelectElement+ ).disabled,+ ).toBe(true);++ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.shortcuts.workLouderCodex.layout.editor.save',+ }),+ );+ expect(mocks.setSettings).toHaveBeenCalledWith({+ layout: expect.objectContaining({+ slots: expect.objectContaining({+ ACT06: expect.objectContaining({ keycapId: 'MIC1', action: null }),+ }),+ }),+ });+ });++ it('draws encoder turns and stick travel from live preview input', () => {+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);++ act(() => {+ for (const listener of mocks.previewListeners) {+ listener({ part: 'encoder', pressed: false, turn: 1 });+ listener({ part: 'encoder', pressed: false, turn: 1 });+ listener({ part: 'analog', pressed: true, angle: 0, distance: 1 });+ }+ });++ expect(+ screen+ .getByRole('button', {+ name: /settings\.shortcuts\.workLouderCodex\.layout\.keyboard\.encoder/,+ })+ .querySelector('[data-encoder-turns]')+ ?.getAttribute('data-encoder-turns'),+ ).toBe('2');+ expect(screen.getByTestId('worklouder-codex-stick-cap').getAttribute('style')).toContain(+ 'translate(10px, 0px)',+ );+ });+});diff --git a/apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts b/apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.tsnew file mode 100644index 0000000000..faadbfc164--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts@@ -0,0 +1,34 @@+/**+ * Localized names and descriptions for the commands a Codex Micro key can fire.+ *+ * The board itself carries no lettering, so this copy is the only place a user+ * finds out what a key does — it feeds the hover tooltip on the layout as well+ * as the action pickers.+ */+import type { TFunction } from 'i18next';++const COMMAND_COPY_PREFIX = 'settings.shortcuts.workLouderCodex.commands';++/**+ * Falls back to the command id split into words. Only reachable if a command+ * ships without copy, which the i18n gate would normally catch first.+ */+function humanizeCommandId(commandId: string): string {+ return commandId+ .split('.')+ .at(-1)!+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/^./, (character) => character.toUpperCase());+}++export function workLouderCodexCommandName(t: TFunction, commandId: string): string {+ const key = `${COMMAND_COPY_PREFIX}.${commandId}.name`;+ const translated = t(key);+ return translated === key ? humanizeCommandId(commandId) : translated;+}++export function workLouderCodexCommandDescription(t: TFunction, commandId: string): string | null {+ const key = `${COMMAND_COPY_PREFIX}.${commandId}.description`;+ const translated = t(key);+ return translated === key ? null : translated;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex c60deaabb4..8c09af9646 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -182,6 +182,13 @@ import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';import { serializeAttachedFiles } from '@/lib/messageAttachmentPayload';import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';import { createLogger } from '@/lib/logger';+import { subscribeWorkLouderCodexAction } from '@/lib/workLouderCodexActions';+import {+ copyCurrentTaskMarkdown,+ forkCurrentTaskFromKeyboard,+} from '@/lib/workLouderCodexTaskActions';+import { useSessionHardwareTaskActions } from './lib/sessionHardwareTaskActions';+import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';import { getModelById, getDefaultModelForVendor, getModelsForVendor } from '@/lib/modelDefinitions';import { resolveDisplayContextWindow } from '@/lib/contextWindow';import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';@@ -589,19 +596,17 @@ export function CCAgentSessionView({return openSubagentsTab(sessionId, SUBAGENT_TAB_REGISTER_ONLY);}).catch(() => undefined);- const unsubscribe = window.electronAPI.localDb.subagentRuns.onChanged(- (payload, ownerStamp) => {- if (- disposed ||- !isDataOwnerPushCurrent(ownerStamp) ||- payload.runId === null ||- payload.sessionId !== sessionId- ) {- return;- }- void openSubagentsTab(sessionId, SUBAGENT_TAB_REGISTER_ONLY).catch(() => undefined);- },- );+ const unsubscribe = window.electronAPI.localDb.subagentRuns.onChanged((payload, ownerStamp) => {+ if (+ disposed ||+ !isDataOwnerPushCurrent(ownerStamp) ||+ payload.runId === null ||+ payload.sessionId !== sessionId+ ) {+ return;+ }+ void openSubagentsTab(sessionId, SUBAGENT_TAB_REGISTER_ONLY).catch(() => undefined);+ });return () => {disposed = true;unsubscribe();@@ -693,6 +698,16 @@ export function CCAgentSessionView({// 实例拥有右栏 / header 主权。SplitGroup 的常驻 pane 可用 routeOwner 显式转移// 主权;其它内嵌复用实例(doc rail / Orca worker)不传,行为保持不变。const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);+ // Header/right-sidebar ownership is narrower than hardware task actions.+ // A visible file-browse rail is still the open task, even when it is compact.+ // Split panes stay mounted together; only the route-owning pane may consume+ // hardware commands. The compact files rail is not a split pane.+ const ownsHardwareTaskActions =+ ownsRoute ||+ (Boolean(sessionId) &&+ viewVisible &&+ navigationMode !== 'sidebar-embedded' &&+ navigationMode !== 'split-pane');const showComposerControlledBanner = ownsRoute || showControlledBanner;const controlledBy = useControlledBy();const hasControlledBanner = showComposerControlledBanner && controlledBy.length > 0;@@ -835,6 +850,16 @@ export function CCAgentSessionView({const remoteConn = useRemoteSessionConnection(remoteDeviceId);const remoteLinkIssue = useDeviceLinkConnectionIssue(!!remoteDeviceId);const remoteSessionUnavailable = remoteConn === 'reconnecting' || remoteConn === 'host-offline';+ const remoteWritesBlocked = remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);+ const showRemoteWriteBlockedToast = useCallback(() => {+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));+ }, [t]);+ const { togglePin, archive } = useSessionHardwareTaskActions({+ session,+ remoteWritesBlocked,+ onRemoteWriteBlocked: showRemoteWriteBlockedToast,+ patchLocal: patchLocalSession,+ });// 列表级 activity 在重 topic 的 maker status 之前就可用。远程 turn 正在执行 / 等待// 交互时,session 行天然是 startedAt > endedAt,不能把这个正常在飞窗口误判成// 「应用退出中断」。直接门控首帧,再锁存本次视图,避免 activity 终态与 ended patch@@ -1458,6 +1483,71 @@ export function CCAgentSessionView({sessionId,t,]);+ useEffect(() => {+ return subscribeWorkLouderCodexAction((action) => {+ if (action.type !== 'command') return false;+ if (!sessionId || !ownsHardwareTaskActions) return false;+ if (action.commandId === 'approval.approve') {+ if (pendingPermission) {+ respondToPermission({ behavior: 'allow' });+ return true;+ }+ if (pendingPlanReview) {+ respondToPlanReview(pendingPlanReview.requestId, true);+ return true;+ }+ return false;+ }+ if (action.commandId === 'approval.decline') {+ if (pendingPermission) {+ respondToPermission({+ behavior: 'deny',+ message: 'User denied',+ decisionClassification: 'user_reject',+ });+ return true;+ }+ if (pendingPlanReview) {+ cancelPlanReview(pendingPlanReview.requestId);+ return true;+ }+ }+ if (action.commandId === 'forkTask') {+ if (!canNavigateSession) return false;+ void forkCurrentTaskFromKeyboard(sessionId, {+ navigate,+ t,+ });+ return true;+ }+ if (action.commandId === 'copyConversationMarkdown') {+ void copyCurrentTaskMarkdown(sessionId, { navigate, t });+ return true;+ }+ if (action.commandId === 'toggleTaskPin') {+ void togglePin();+ return true;+ }+ if (action.commandId === 'archiveTask') {+ void archive();+ return true;+ }+ return false;+ });+ }, [+ archive,+ canNavigateSession,+ cancelPlanReview,+ ownsHardwareTaskActions,+ navigate,+ pendingPermission,+ pendingPlanReview,+ respondToPermission,+ respondToPlanReview,+ sessionId,+ t,+ togglePin,+ ]);// 展示引擎可乐观跟随 intent;真实 event reducer 仍只读 store.agentKind。const displayAgentKind = agentSwitchIntent?.target ?? dbToMakerAgentKind(session?.agentKind);// 真实会话 agentKind(pending switch intent 不影响)——压缩分流必须用它,@@ -3829,6 +3919,7 @@ export function CCAgentSessionView({forkOrigin={forkOrigin}onOpenForkOrigin={handleOpenForkOrigin}isLocalUserSend={isLocalUserSend}+ ownsHardwareScrollActions={ownsHardwareTaskActions}/>);@@ -4401,6 +4492,7 @@ export function CCAgentSessionView({onSend={handleSend}onBeforeVoiceInputStart={handleBeforeVoiceInputStart}sessionId={sessionId}+ ownsHardwareComposerActions={ownsHardwareTaskActions}// session=null 是冷启动 / 直链 GET 尚未回流的合法首帧;显式传 null,// 让 ChatInput 暂不显示 Agent 身份,不能跟随 displayAgentKind 的 cc 回退。runtimeAgentKind={session ? dbToMakerAgentKind(session.agentKind) : null}@@ -4644,10 +4736,11 @@ export function CCAgentSessionView({// pi 回合运行中会拒绝压缩 → compact-session 通道在 running 时禁用// (与 SessionContentHeader 的 runningSessionIds 一致,codex P1);// claude-input 保留旧行为(turn 中可走 inputCoordinator)。- compactChannel !== null- && !(realAgentKind === 'pi' && !!session?.remoteHostId)- && session != null && agentStatus.contextTokens > 0- && !(compactChannel === 'compact-session' && agentStatus.isRunning)+ compactChannel !== null &&+ !(realAgentKind === 'pi' && !!session?.remoteHostId) &&+ session != null &&+ agentStatus.contextTokens > 0 &&+ !(compactChannel === 'compact-session' && agentStatus.isRunning)? handleCompactRequest: undefined}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 12a2bb1ef1..9dae743dc8 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -60,6 +60,7 @@ import {matchesKeyboardEvent,SWITCH_SESSION_SHORTCUT_IDS,} from '../../../shared/appShortcuts';+import { WORKLOUDER_CODEX_AGENT_SLOT_COUNT } from '../../../shared/workLouderCodex';import { setSessionOrdinalBadges } from './sidebar/sessionOrdinalBadges';import { useOwnTopNavScrollableRows, useSidebarCollapsedState } from '../feature-context';import { SidebarTopNav } from '@/components/sidebar/SidebarTopNav';@@ -164,6 +165,7 @@ import {getVisibleSidebarSessionIds,pickSessionIdAfterRemoval,} from './lib/sessionRemovalNavigation';+import { onRequestSessionSwitch, pickAdjacentSessionId } from './lib/sessionSwitchCommands';import type {AutomationScheduleAction,AutomationScheduleSessionInfo,@@ -615,6 +617,78 @@ export function CCAgentSidebarUpper() {[statusFilteredSessionsWithRemote, hiddenProjectKeys, localPlatform],);+ /* Codex Micro 的 6 个任务键跟侧栏走。主进程只能查本地 sessions 表,看不见被控+ * 机器上的任务(它们只活在渲染端的 remote store 里),也不知道用户当前选了哪台+ * 机器 —— 光靠主进程投影,连着远程用时 6 个键会全是空的。所以由这里上报。+ *+ * 顺序取真实渲染顺序(与 mod+1..9、旋钮切任务同一个口径),不是+ * visibleSessionsWithRemote 那份扁平的「按最近更新排序」列表 —— 后者不含置顶区+ * 与项目分组,和用户眼里看到的顺序对不上,AG00 会指向列表里根本不在第一行的任务。+ * 不限定容器:展开态与 rail 折叠态是两个不同组件,扫整个 document 才能两种形态+ * 都覆盖。只送键盘需要的三个字段,不整份 session 过 IPC。 */+ const publishedTaskKeyRef = useRef<string>('');+ const publishSidebarTasks = useCallback(() => {+ if (isSecondaryWindow()) return;+ const renderedIds = getVisibleSidebarSessionIds();+ const sidebarOrder = new Map(renderedIds.map((id, index) => [id, index] as const));+ // 空可见列表也要上报:换机器、折叠或搜索把可见行清掉时,侧栏映射必须让位,+ // 否则 AG 键还会打开上一份已经看不见的任务。完整活动表仍要带上,最近发送+ // / 优先 / 自定义不能被折叠裁掉。+ const catalogSessions = sessionsWithRemote.filter((session) => session.status === 'active');+ const visibleProjection = visibleSessionsWithRemote+ .filter((session) => !catalogSessions.some((active) => active.id === session.id))+ .slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT);+ const remainingCatalogSlots = Math.max(0, 100 - visibleProjection.length);+ const tasks = [...visibleProjection, ...catalogSessions.slice(0, remainingCatalogSlots)].map((session) => {+ const pinnedAtMs = session.pinnedAt ? Date.parse(session.pinnedAt) : Number.NaN;+ const userSendAtMs = session.userSendAt ? Date.parse(session.userSendAt) : Number.NaN;+ const order = sidebarOrder.get(session.id);+ const isActiveCatalog = session.status === 'active';+ return {+ id: session.id,+ title: session.title ?? null,+ pinnedAt: Number.isFinite(pinnedAtMs) ? pinnedAtMs : null,+ userSendAt: Number.isFinite(userSendAtMs) ? userSendAtMs : null,+ ...(order === undefined ? {} : { sidebarOrder: order }),+ ...(isActiveCatalog ? {} : { catalogEligible: false }),+ };+ });+ // 侧栏会因为各种无关状态重算;内容没变就不打扰主进程。+ const key = JSON.stringify(tasks);+ if (key === publishedTaskKeyRef.current) return;+ publishedTaskKeyRef.current = key;+ void window.electronAPI?.workLouderCodex?.publishTasks?.(tasks)?.catch(() => {+ // 键盘没接或 IPC 不可用都不影响侧栏本身。+ publishedTaskKeyRef.current = '';+ });+ }, [sessionsWithRemote, visibleSessionsWithRemote]);+ useEffect(() => {+ publishSidebarTasks();+ // 展开/折叠项目、分组重排这类纯 UI 变化不会动 visibleSessionsWithRemote,+ // 但会改渲染顺序 —— 跟序号徽标同样的做法,靠 DOM 变化跟住。+ if (typeof MutationObserver === 'undefined' || typeof document === 'undefined') return;+ // 观察面是整个 document(展开态与 rail 是两个组件),流式输出时 mutation 会非常+ // 密集 —— 每帧最多重算一次,别让它变成热路径。+ let frame: number | null = null;+ const observer = new MutationObserver(() => {+ if (frame !== null) return;+ frame = requestAnimationFrame(() => {+ frame = null;+ publishSidebarTasks();+ });+ });+ observer.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['class', 'hidden', 'aria-hidden'],+ });+ return () => {+ observer.disconnect();+ if (frame !== null) cancelAnimationFrame(frame);+ };+ }, [publishSidebarTasks]);+// rail 未读集与展开态(ExpandedView.sidebarNotifications)同口径:把"定时任务有未读运行"的// 会话并入 attention 未读集。否则 rail 模式下,靠 scheduleSessionIndex 恢复的定时任务// 完成未读(如重启后 attention store 还没填充)会丢绿点(codex review)。@@ -2108,6 +2182,32 @@ function ExpandedView({},[handleSessionClick],);+ /* Codex Micro 旋钮:左转沿侧栏列表往上,右转往下 —— 跟着屏幕上的列表走,+ * 不是抽象的"上一个/下一个"。序号口径与 mod+1..9 完全相同:都取+ * getVisibleSidebarSessionIds 的真实渲染顺序,所以分组、置顶区、折叠与搜索+ * 过滤天然一致,所见即所得。「新建」是列表最上面那一站(它在 SidebarTopNav+ * 里、不是会话行,所以由 pickAdjacentSessionId 单独补进序列)。到头停住不+ * 回绕:旋钮是连续控件,从末尾绕回开头会把用户甩到看不见的地方,还感觉不到+ * 列表已经到边。 */+ const onNewMakerMatchRef = useRef(onNewMakerMatch);+ onNewMakerMatchRef.current = onNewMakerMatch;+ useEffect(() => {+ if (!sessionSwitchEnabled) return;+ return onRequestSessionSwitch((direction) => {+ const visibleIds = getVisibleSidebarSessionIds(sidebarScrollRef.current);+ // 已经停在新建页时按"第 0 站"计,这样右转能进入列表第一条。+ const activeId = onNewMakerMatchRef.current ? null : (activeSessionIdRef.current ?? null);+ const target = pickAdjacentSessionId(visibleIds, activeId, direction);+ if (!target) return;+ if (target.kind === 'new-task') {+ navigate('/cc-agent/new');+ return;+ }+ // 同样复用行点击唯一入口,继承清通知 / 同对话去重 / Orca 角色路由。+ void handleSessionClick(target.sessionId);+ });+ }, [handleSessionClick, navigate, sessionSwitchEnabled]);+useAppShortcut('switch-session-1', () => handleSwitchSessionSlot(0), {enabled: sessionSwitchEnabled,});@@ -3276,6 +3376,7 @@ function ExpandedView({{searchActive ? (<divdata-conversation-search-surface+ data-conversation-search-overlayonContextMenu={(event) => event.stopPropagation()}><SearchResultsBodydiff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 9bd07460bc..318f4188cc 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -135,7 +135,9 @@ import { useRefreshWorktrees } from '@/contexts/WorktreeContext';import { crossAgentConvertService } from '@/lib/crossAgentConvertService';import {consumeNewMakerDialogueTargetRequest,+ consumeNewMakerFolderPickerRequest,readNewMakerDialogueTargetRequest,+ readNewMakerFolderPickerRequest,} from './lib/newMakerRouteState';import { useCrossAgentMigrationDialog } from '@/hooks/useCrossAgentConvertPrompt';import { getCollaborationStartErrorMessage } from './collaborationErrors';@@ -601,8 +603,13 @@ export function NewMakerDraftRoute() {() => readNewMakerDialogueTargetRequest(location.state),[location.state],);+ const folderPickerRequest = useMemo(+ () => readNewMakerFolderPickerRequest(location.state),+ [location.state],+ );const handledDialogueTargetRequestRef = useRef<string | null>(null);const modePickerSelectionSeqRef = useRef(0);+ const handledFolderPickerRequestRef = useRef<string | null>(null);// 首参 914=内容封顶宽(→ inputWidth 封顶 934):大屏留出左右呼吸空间,不再顶满全宽;// 与进行中对话页(CCAgentSessionView 同传 914)一致,发送首条消息时输入框宽度不跳变。// minWidth=640:小屏兜一个体面下限(与对话页对称);窄于下限时 hook 自动回落成@@ -2771,6 +2778,22 @@ export function NewMakerDraftRoute() {// 打开项目 picker 时收掉设备 picker(两个 popover 都是 absolute 浮层,会互相遮挡)。if (open) setDevicePickerOpen(false);}, []);++ useLayoutEffect(() => {+ if (+ !folderPickerRequest ||+ handledFolderPickerRequestRef.current === folderPickerRequest.requestId+ ) {+ return;+ }+ handledFolderPickerRequestRef.current = folderPickerRequest.requestId;+ setFolderPickerOpen(true);+ setDevicePickerOpen(false);+ navigate(`${location.pathname}${location.search}${location.hash}`, {+ replace: true,+ state: consumeNewMakerFolderPickerRequest(location.state),+ });+ }, [folderPickerRequest, location, navigate]);const handleDevicePickerOpenChange = useCallback((open: boolean) => {setDevicePickerOpen(open);if (open) setFolderPickerOpen(false);diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex 4e8b5e5c78..7b4c4e6e8a 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@ -20,7 +20,7 @@* 输入的控件挖 no-drag 洞,避免标题和 git 信息整块变成不可拖区域。*/-import { useCallback, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { ChevronRight, Ellipsis, Pin } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -147,8 +147,7 @@ export function SessionContentHeader({const isArchived = session.status === 'archived';// Draft 判定与 SessionItem 同口径:标题仍是默认哨兵且无消息。const isEmpty = isEmptyDraftSession(session);- const remoteWritesBlocked =- remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);+ const remoteWritesBlocked = remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);// 「移动到项目」/「导出会话…」可见性与 SessionItem 同条件。const canMoveToProject =!isEmpty && !session.remoteHostId && !session.deviceLinkDeviceId && !isArchived;@@ -177,9 +176,13 @@ export function SessionContentHeader({const displayTitle =getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'))?.trim() ||t('ccAgent.sessionHeader.untitled');- const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null;+ const remoteIconKind = session.deviceLinkDeviceId+ ? 'device-link'+ : session.remoteHostId+ ? 'ssh'+ : null;const remoteIconConnectionStatus = session.deviceLinkDeviceId- ? session.deviceLinkConnectionStatus ?? 'connected'+ ? (session.deviceLinkConnectionStatus ?? 'connected'): null;/* ---- 行内重命名(与 SessionItem 同交互:双击进入,Enter 提交 / Esc 取消 / Blur 提交,@@ -388,12 +391,7 @@ export function SessionContentHeader({);}},- [- patchLocal,- runningSessionIds,- session,- t,- ],+ [patchLocal, runningSessionIds, session, t],);/* ---- 导出会话(.cshare)---- 弹窗仅打开时挂载,与 SessionItem 同款。 */@@ -404,8 +402,10 @@ export function SessionContentHeader({[remoteProjectSessions, sessions],);const hasSessionFamily = useMemo(- () => allKnownSessions.some((item) =>- item.parentSessionId === session.id || item.id === session.parentSessionId),+ () =>+ allKnownSessions.some(+ (item) => item.parentSessionId === session.id || item.id === session.parentSessionId,+ ),[allKnownSessions, session.id, session.parentSessionId],);const canShowBranchTree = !isEmpty && (session.agentKind === 'pi' || hasSessionFamily);@@ -422,7 +422,8 @@ export function SessionContentHeader({toast.info(t('ccAgent.sidebar.sessionMenu.compactNothing'));} else if (result) {const hasNumbers =- typeof result.tokensBefore === 'number' && typeof result.estimatedTokensAfter === 'number';+ typeof result.tokensBefore === 'number' &&+ typeof result.estimatedTokensAfter === 'number';toast.success(hasNumbers? t('ccAgent.sidebar.sessionMenu.compactSuccessWithTokens', {@@ -490,10 +491,7 @@ export function SessionContentHeader({// 一起等,dirty 先返回 clean、接管查询还在飞的那段时间就是 clean 结论的失效窗口。// 改成接管结算之后再 resolve —— clean 一律重查(见 worktreeRemovalWarning),// 拿到的是此刻的结论;菜单打开时的 prefetch 仍然热了 git cache。- const preflight = await resolveWorktreeRemovalPreflight(- session.id,- session.deviceLinkDeviceId,- );+ const preflight = await resolveWorktreeRemovalPreflight(session.id, session.deviceLinkDeviceId);// 归档不弹确认框 —— 可逆操作(菜单里就有「恢复」),与 sidebar 同口径。// 免确认的判据是「**确认**干净」:worktree 脏、或预检失败拿不到结论('unknown')// 都要确认 —— 归档会顺带回收 worktree,不能静默带走改动(greptile review)。@@ -586,15 +584,15 @@ export function SessionContentHeader({)}{boundSchedules.length > 0 && (<span style={WINDOW_NO_DRAG_STYLE}>- <ScheduleBindingBadge- schedules={boundSchedules}- size={13}- className="mr-1 size-4"- />+ <ScheduleBindingBadge schedules={boundSchedules} size={13} className="mr-1 size-4" /></span>)}{!isEditing && remoteIconKind && (- <Tip text={session.deviceLinkDeviceName ?? session.deviceLinkDeviceId ?? session.remoteHostId ?? ''}>+ <Tip+ text={+ session.deviceLinkDeviceName ?? session.deviceLinkDeviceId ?? session.remoteHostId ?? ''+ }+ ><RemoteProjectIconkind={remoteIconKind}connectionStatus={remoteIconConnectionStatus}@@ -781,12 +779,8 @@ export function SessionContentHeader({onSelectProject={(workingDir) =>void handleMoveSession({ kind: 'project', workingDir })}- onBrowseProject={() =>- void handleMoveSession({ kind: 'browseProject' })- }- onMoveToDialogue={() =>- void handleMoveSession({ kind: 'dialogue' })- }+ onBrowseProject={() => void handleMoveSession({ kind: 'browseProject' })}+ onMoveToDialogue={() => void handleMoveSession({ kind: 'dialogue' })}/></DropdownMenuSubContent></DropdownMenuSub>diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionSwitchCommands.test.ts b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionSwitchCommands.test.tsnew file mode 100644index 0000000000..3720d7e7a6--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionSwitchCommands.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it, vi } from 'vitest';++import {+ onRequestSessionSwitch,+ pickAdjacentSessionId,+ requestSessionSwitch,+} from '../sessionSwitchCommands';++describe('pickAdjacentSessionId', () => {+ const list = ['a', 'b', 'c'];+ const session = (sessionId: string) => ({ kind: 'session', sessionId });++ it('moves one step in either direction', () => {+ expect(pickAdjacentSessionId(list, 'b', 'previous')).toEqual(session('a'));+ expect(pickAdjacentSessionId(list, 'b', 'next')).toEqual(session('c'));+ });++ it('treats the new-task row as the stop above the first task', () => {+ expect(pickAdjacentSessionId(list, 'a', 'previous')).toEqual({ kind: 'new-task' });+ // And from there, stepping down enters the list.+ expect(pickAdjacentSessionId(list, null, 'next')).toEqual(session('a'));+ });++ it('stops at both ends instead of wrapping', () => {+ // Wrapping would jump the user from one end of the list to the other with+ // no way to feel that the list had ended.+ expect(pickAdjacentSessionId(list, null, 'previous')).toBeNull();+ expect(pickAdjacentSessionId(list, 'c', 'next')).toBeNull();+ });++ it('stays put when the active task is filtered out of the visible list', () => {+ // Search or a status filter can hide the active task; moving relative to+ // something that is not on screen would be a guess.+ expect(pickAdjacentSessionId(list, 'hidden', 'next')).toBeNull();+ expect(pickAdjacentSessionId(list, 'hidden', 'previous')).toBeNull();+ });++ it('offers only the new-task row when no tasks are visible', () => {+ expect(pickAdjacentSessionId([], 'a', 'next')).toBeNull();+ expect(pickAdjacentSessionId([], null, 'next')).toBeNull();+ expect(pickAdjacentSessionId([], null, 'previous')).toBeNull();+ });+});++describe('session switch channel', () => {+ it('delivers to subscribers until they unsubscribe', () => {+ const listener = vi.fn();+ const unsubscribe = onRequestSessionSwitch(listener);++ requestSessionSwitch('next');+ expect(listener).toHaveBeenCalledWith('next');++ unsubscribe();+ requestSessionSwitch('previous');+ expect(listener).toHaveBeenCalledTimes(1);+ });++ it('keeps delivering after a subscriber throws', () => {+ const broken = vi.fn(() => {+ throw new Error('boom');+ });+ const healthy = vi.fn();+ const offBroken = onRequestSessionSwitch(broken);+ const offHealthy = onRequestSessionSwitch(healthy);++ expect(() => requestSessionSwitch('next')).not.toThrow();+ expect(healthy).toHaveBeenCalledWith('next');++ offBroken();+ offHealthy();+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts b/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.tsindex a44fa8972e..b405a37820 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts@@ -6,12 +6,18 @@ export interface NewMakerDialogueTargetRequest {deviceName: string | null;}+export interface NewMakerFolderPickerRequest {+ requestId: string;+}+export interface NewMakerRouteState {workspacePrompt: 'generic' | 'dialogue';dialogueTargetRequest?: NewMakerDialogueTargetRequest;+ folderPickerRequest?: NewMakerFolderPickerRequest;}let dialogueTargetRequestSequence = 0;+let folderPickerRequestSequence = 0;/*** “对话”分组每次点击都生成新 requestId。同路由重复 navigate 不会 remount 创建页,@@ -31,6 +37,32 @@ export function makeDialogueNewMakerRouteState(};}+export function makeFolderPickerNewMakerRouteState(): NewMakerRouteState {+ folderPickerRequestSequence += 1;+ return {+ workspacePrompt: 'generic',+ folderPickerRequest: {+ requestId: `${Date.now()}-${folderPickerRequestSequence}`,+ },+ };+}++export function readNewMakerFolderPickerRequest(state: unknown): NewMakerFolderPickerRequest | null {+ if (!state || typeof state !== 'object') return null;+ const request = (state as Record<string, unknown>).folderPickerRequest;+ if (!request || typeof request !== 'object') return null;+ const requestId = (request as Record<string, unknown>).requestId;+ if (typeof requestId !== 'string' || requestId.length === 0) return null;+ return { requestId };+}++export function consumeNewMakerFolderPickerRequest(state: unknown): unknown {+ if (!state || typeof state !== 'object' || Array.isArray(state)) return state;+ if (!Object.prototype.hasOwnProperty.call(state, 'folderPickerRequest')) return state;+ const { folderPickerRequest: _consumed, ...remainingState } = state as Record<string, unknown>;+ return remainingState;+}+export function readNewMakerDialogueTargetRequest(state: unknown,): NewMakerDialogueTargetRequest | null {diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.tsnew file mode 100644index 0000000000..6837d298e9--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts@@ -0,0 +1,98 @@+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';+import type { Session } from '@/lib/ccAgent.types';+import { createLogger } from '@/lib/logger';+import * as sessionService from '@/lib/sessionService';+import { toast } from '@/lib/toast';+import { resolveWorktreeRemovalPreflight } from '@/lib/worktreeRemovalWarning';++import { useSessionLifecycleActions } from '../hooks/useSessionLifecycleActions';++const log = createLogger('sessionHardwareTaskActions');++export function useSessionHardwareTaskActions({+ session,+ remoteWritesBlocked,+ onRemoteWriteBlocked,+ patchLocal,+}: {+ session: Session | null;+ remoteWritesBlocked: boolean;+ onRemoteWriteBlocked: () => void;+ patchLocal?: (sessionId: string, patch: Partial<Session>) => void;+}): {+ togglePin: () => Promise<void>;+ archive: () => Promise<void>;+} {+ const { t } = useTranslation();+ const { confirm: confirmDialog } = useConfirmDialog();+ const { runSessionAction } = useSessionLifecycleActions();+ const { runningSessionIds } = useSessionRunningStatus(session?.id);+ const sessionId = session?.id ?? null;+ const pinnedAt = session?.pinnedAt ?? null;+ const deviceLinkDeviceId = session?.deviceLinkDeviceId;++ const togglePin = useCallback(async () => {+ if (!sessionId) return;+ if (remoteWritesBlocked) {+ onRemoteWriteBlocked();+ return;+ }+ const newPinnedAt = pinnedAt ? null : new Date().toISOString();+ patchLocal?.(sessionId, { pinnedAt: newPinnedAt });+ try {+ await sessionService.patchMeta(sessionId, { pinnedAt: newPinnedAt });+ } catch (err) {+ log.error('[session pin]', err);+ toast.error(t('ccAgent.sidebar.pinFailed'));+ patchLocal?.(sessionId, { pinnedAt });+ }+ }, [onRemoteWriteBlocked, patchLocal, pinnedAt, remoteWritesBlocked, sessionId, t]);++ const archive = useCallback(async () => {+ if (!sessionId) return;+ if (remoteWritesBlocked) {+ onRemoteWriteBlocked();+ return;+ }+ if (runningSessionIds.has(sessionId)) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));+ return;+ }+ const attached = await window.electronAPI.binding+ .resolveSession(sessionId)+ .then((binding) => binding.attached)+ .catch(() => false);+ if (attached) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));+ return;+ }+ const preflight = await resolveWorktreeRemovalPreflight(sessionId, deviceLinkDeviceId);+ if (preflight !== 'clean') {+ const ok = await confirmDialog({+ title: t('ccAgent.sidebar.confirmArchive.title'),+ description:+ t('ccAgent.sidebar.confirmArchive.description') ++ (preflight === 'dirty' ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning') : ''),+ confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),+ cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),+ });+ if (!ok) return;+ }+ await runSessionAction(sessionId, 'archive', { activeSessionId: sessionId });+ }, [+ confirmDialog,+ deviceLinkDeviceId,+ onRemoteWriteBlocked,+ remoteWritesBlocked,+ runSessionAction,+ runningSessionIds,+ sessionId,+ t,+ ]);++ return { togglePin, archive };+}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.tsindex 53c958ab4c..0c4e8587dd 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts@@ -36,6 +36,7 @@ function getSidebarRowOrder(node: HTMLElement): number | null {function isRenderedVisible(node: HTMLElement): boolean {const view = node.ownerDocument?.defaultView;+ if (isCoveredBySearchOverlay(node)) return false;for (let current: HTMLElement | null = node; current != null; current = current.parentElement) {if (current.hasAttribute?.('hidden')) return false;@@ -49,6 +50,21 @@ function isRenderedVisible(node: HTMLElement): boolean {return true;}+/** Sidebar search sits on top of the real list without hiding it. */+function isCoveredBySearchOverlay(node: HTMLElement): boolean {+ if (typeof node.closest !== 'function') return false;+ if (node.closest('[data-conversation-search-overlay]')) return false;+ const root = node.ownerDocument;+ if (!root) return false;+ for (const overlay of root.querySelectorAll('[data-conversation-search-overlay]')) {+ if (!(overlay instanceof HTMLElement)) continue;+ if (overlay.contains(node)) continue;+ const ancestor = node.closest('aside, [data-sidebar], nav');+ if (ancestor && ancestor.contains(overlay)) return true;+ }+ return false;+}+export function pickSessionIdAfterRemoval(orderedSessionIds: readonly string[],removedSessionIds: ReadonlySet<string>,diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionSwitchCommands.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionSwitchCommands.tsnew file mode 100644index 0000000000..6ecda4a278--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionSwitchCommands.ts@@ -0,0 +1,79 @@+/**+ * "Previous / next task" command channel.+ *+ * The Codex Micro encoder turns through the task list, but the list only exists+ * inside the sidebar (`CCAgentSidebarUpper`'s `visibleSessionsWithRemote`) while+ * the command arrives in `MainLayout`, many layers away. Rather than thread the+ * list or a ref through everything in between, this mirrors the shape already+ * used by `features/right-sidebar/lib/sidebarCommands.ts`: one module-level+ * emitter, one payload, with the state owner subscribing.+ *+ * Direction only — the publisher does not know the list, and the subscriber+ * does not need to know why it was asked to move.+ */++export type SessionSwitchDirection = 'previous' | 'next';++type Listener = (direction: SessionSwitchDirection) => void;++const listeners = new Set<Listener>();++/** Ask whoever owns the visible task list to move one step. */+export function requestSessionSwitch(direction: SessionSwitchDirection): void {+ for (const listener of listeners) {+ try {+ listener(direction);+ } catch {+ // A broken subscriber must not poison-pill the caller.+ }+ }+}++/** Subscribe to switch requests. Returns an unsubscribe function. */+export function onRequestSessionSwitch(listener: Listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/**+ * Where one step of the knob lands: an existing task, or the "new task" row+ * that sits above the list — turning up from the first task lands there rather+ * than stopping.+ */+export type SessionSwitchTarget = { kind: 'session'; sessionId: string } | { kind: 'new-task' };++/**+ * The stop one step from where the user is, in the order the sidebar shows.+ *+ * The list the knob walks is the new-task row followed by the visible tasks,+ * so `previous` moves up it and `next` moves down.+ *+ * Stops at both ends rather than wrapping: the encoder is a continuous control,+ * and wrapping from the last task back to the top would move the user somewhere+ * far away with no way to feel where the list ended.+ *+ * Returns null when there is nowhere to go — already at an end, or the active+ * task is not in the visible list at all (filtered out by search or a status+ * filter), in which case moving relative to it would be a guess.+ */+export function pickAdjacentSessionId(+ visibleSessionIds: readonly string[],+ activeId: string | null,+ direction: SessionSwitchDirection,+): SessionSwitchTarget | null {+ // One list: the new-task row, then every visible task under it.+ const stops: SessionSwitchTarget[] = [+ { kind: 'new-task' },+ ...visibleSessionIds.map((sessionId) => ({ kind: 'session' as const, sessionId })),+ ];+ // `activeId === null` means the new-task page is open, which is stop 0.+ const index = activeId+ ? stops.findIndex((stop) => stop.kind === 'session' && stop.sessionId === activeId)+ : 0;+ if (index < 0) return null;+ const target = index + (direction === 'next' ? 1 : -1);+ if (target < 0 || target >= stops.length) return null;+ return stops[target] ?? null;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsxindex dabbc7bdf6..9b5278b68c 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx@@ -1043,6 +1043,8 @@ function SearchResultRow({return (<div+ data-sidebar-session-row="true"+ data-session-id={item.session.id}className={cn('rounded-lg transition-colors hover:bg-[var(--cmd-palette-item-hover)]',)}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.tsindex 973e648a54..fb77c77f43 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts@@ -1,8 +1,15 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('../../store', () => ({ensureHydrated: vi.fn(async () => undefined),addOrFocusSingletonTab: vi.fn(async () => undefined),+ closeTab: vi.fn(async () => undefined),+ getBucket: vi.fn(() => ({+ tabs: [{ id: 'review-1', kind: 'review' }],+ activeTabId: 'review-1',+ })),}));vi.mock('../openInSidebarBrowser', () => ({openUrlInSidebarBrowser: vi.fn(async () => undefined),@@ -20,7 +27,7 @@ vi.mock('../../plugins/orca-workers/actions', () => ({closeOrcaWorkersTabAfterTeamEnd: vi.fn(async () => undefined),}));-import { addOrFocusSingletonTab, ensureHydrated } from '../../store';+import { addOrFocusSingletonTab, closeTab, ensureHydrated, getBucket } from '../../store';import {closeOrcaWorkersTabAfterTeamEnd,ensureOrcaWorkersTab,@@ -105,4 +112,19 @@ describe('executeSidebarCommand', () => {userInitiated: false,});});++ it('keeps Review when the detached host is still hidden', async () => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ await executeSidebarCommand({ type: 'toggle-review-tab', sessionId: 's1' });+ expect(getBucket).toHaveBeenCalledWith('s1');+ expect(closeTab).not.toHaveBeenCalled();+ expect(addOrFocusSingletonTab).toHaveBeenCalledWith('s1', 'review', null);+ });++ it('hides Review only after the detached host is already visible', async () => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await executeSidebarCommand({ type: 'toggle-review-tab', sessionId: 's1' });+ expect(closeTab).toHaveBeenCalledWith('s1', 'review-1');+ expect(addOrFocusSingletonTab).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.tsindex feb9aa5a90..694f17f233 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts@@ -1,7 +1,7 @@/** 执行 main 已裁决并推给当前 renderer host 的 RSB command。 */import type { RsbWindowCommand } from '../../../../shared/rightSidebarWindow';-import { addOrFocusSingletonTab, ensureHydrated } from '../store';+import { addOrFocusSingletonTab, closeTab, ensureHydrated, getBucket } from '../store';import {closeOrcaWorkersTabAfterTeamEnd,ensureOrcaWorkersTab,@@ -72,6 +72,18 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<});return;}+ if (command.type === 'toggle-review-tab') {+ await ensureHydrated(command.sessionId);+ const bucket = getBucket(command.sessionId);+ const reviewTab = bucket.tabs.find((tab) => tab.kind === 'review');+ const hostAlreadyVisible = typeof document === 'undefined' || document.visibilityState === 'visible';+ if (reviewTab && bucket.activeTabId === reviewTab.id && hostAlreadyVisible) {+ await closeTab(command.sessionId, reviewTab.id);+ return;+ }+ await addOrFocusSingletonTab(command.sessionId, 'review', null);+ return;+ }await ensureHydrated(command.sessionId);await addOrFocusSingletonTab(command.sessionId, 'terminal');}diff --git a/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsxnew file mode 100644index 0000000000..b7ca6a374a--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useWorkLouderCodex.test.tsx@@ -0,0 +1,120 @@+// @vitest-environment jsdom++import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,+ createWorkLouderCodexDefaultSettings,+ type WorkLouderCodexState,+} from '../../../shared/workLouderCodex';+import { useWorkLouderCodex } from '../useWorkLouderCodex';++function state(+ connectionStatus: WorkLouderCodexState['connectionStatus'],+ lightingBrightness = 100,+): WorkLouderCodexState {+ return {+ connectionStatus,+ connectionReason: null,+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },+ settings: {+ ...createWorkLouderCodexDefaultSettings(),+ lightingBrightness,+ },+ agentSlots: Array.from({ length: 6 }, (_, slot) => ({+ slot,+ sessionId: null,+ title: null,+ action: null,+ })),+ taskOptions: [],+ agentSlotCount: 6,+ };+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((next, fail) => {+ resolve = next;+ reject = fail;+ });+ return { promise, resolve, reject };+}++function installApi(api: {+ getState: () => Promise<WorkLouderCodexState>;+ setSettings: (patch: unknown) => Promise<WorkLouderCodexState>;+ resetSettings: () => Promise<WorkLouderCodexState>;+ openInputMonitoringSettings: () => Promise<void>;+ onStateChanged: (callback: (next: WorkLouderCodexState) => void) => () => void;+}): void {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { workLouderCodex: api },+ });+}++afterEach(() => {+ Reflect.deleteProperty(window, 'electronAPI');+ vi.clearAllMocks();+});++describe('useWorkLouderCodex', () => {+ it('keeps a pushed state when the initial snapshot resolves late', async () => {+ const initial = deferred<WorkLouderCodexState>();+ let onStateChanged: ((next: WorkLouderCodexState) => void) | undefined;+ installApi({+ getState: vi.fn(() => initial.promise),+ setSettings: vi.fn(),+ resetSettings: vi.fn(),+ openInputMonitoringSettings: vi.fn(),+ onStateChanged: vi.fn((callback) => {+ onStateChanged = callback;+ return vi.fn();+ }),+ });+ const { result } = renderHook(() => useWorkLouderCodex());++ act(() => onStateChanged?.(state('connected', 60)));+ await act(async () => {+ initial.resolve(state('connecting', 100));+ await initial.promise;+ });++ expect(result.current.state).toEqual(state('connected', 60));+ });++ it('preserves a newer connection status when a settings save fails', async () => {+ const saving = deferred<WorkLouderCodexState>();+ let onStateChanged: ((next: WorkLouderCodexState) => void) | undefined;+ installApi({+ getState: vi.fn(async () => state('connected')),+ setSettings: vi.fn(() => saving.promise),+ resetSettings: vi.fn(),+ openInputMonitoringSettings: vi.fn(),+ onStateChanged: vi.fn((callback) => {+ onStateChanged = callback;+ return vi.fn();+ }),+ });+ const { result } = renderHook(() => useWorkLouderCodex());+ await waitFor(() => expect(result.current.state).toEqual(state('connected')));++ let mutation!: Promise<void>;+ await act(async () => {+ mutation = result.current.setSettings({ lightingBrightness: 40 });+ await Promise.resolve();+ });+ expect(result.current.state?.settings.lightingBrightness).toBe(40);+ act(() => onStateChanged?.(state('not-detected')));+ await act(async () => {+ saving.reject(new Error('write failed'));+ await mutation;+ });++ expect(result.current.state).toEqual(state('not-detected'));+ expect(result.current.error).toBe('save');+ });+});diff --git a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts b/apps/desktop/src/renderer/hooks/useDeviceProviders.tsindex 955802a574..b56f1af71e 100644--- a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts+++ b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts@@ -132,10 +132,14 @@ export function parseDeviceProvidersPayload(value: unknown): DeviceProvidersPaylif (!isRecord(value)) {throw new Error('Invalid provider list response');}- if (!Array.isArray(value.providers) || !value.providers.every(isProviderView)) {+ if (!Array.isArray(value.providers)) {+ throw new Error('Invalid provider list response');+ }+ const rawProviders = value.providers;+ const providersIn = rawProviders.filter(isProviderView);+ if (providersIn.length === 0 && rawProviders.length > 0) {throw new Error('Invalid provider list response');}- const providersIn = value.providers;const overrides = value.modelVisibilityOverrides;if (overrides !== undefined &&diff --git a/apps/desktop/src/renderer/hooks/useWorkLouderCodex.ts b/apps/desktop/src/renderer/hooks/useWorkLouderCodex.tsnew file mode 100644index 0000000000..7d29218c92--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useWorkLouderCodex.ts@@ -0,0 +1,215 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import type {+ WorkLouderCodexSettings,+ WorkLouderCodexSettingsPatch,+ WorkLouderCodexState,+} from '../../shared/workLouderCodex';++export interface WorkLouderCodexViewState {+ state: WorkLouderCodexState | null;+ loading: boolean;+ saving: boolean;+ error: 'load' | 'save' | null;+ setSettings(patch: WorkLouderCodexSettingsPatch): Promise<void>;+ resetSettings(): Promise<void>;+ openInputMonitoringSettings(): Promise<void>;+ reload(): Promise<void>;+}++export interface WorkLouderCodexOptions {+ /**+ * Poll the device while this view is on screen.+ *+ * The Work Louder SDK has no disconnect event, so an unplugged keyboard keeps+ * reading as connected until something tries to talk to it. Anywhere that+ * shows connection state has to ask. Only the settings page opts in: polling+ * wakes the device, which costs battery over Bluetooth, and nowhere else is+ * showing a status the user is watching.+ */+ watchConnection?: boolean;+}++/** How often the settings page re-checks the device while it is in view. */+const CONNECTION_PROBE_MS = 2_000;++export function useWorkLouderCodex(options: WorkLouderCodexOptions = {}): WorkLouderCodexViewState {+ const { watchConnection = false } = options;+ const [state, setState] = useState<WorkLouderCodexState | null>(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<'load' | 'save' | null>(null);+ const mountedRef = useRef(true);+ const mutationIdRef = useRef(0);+ const pushVersionRef = useRef(0);+ const confirmedSettingsRef = useRef<WorkLouderCodexSettings | null>(null);++ const reload = useCallback(async () => {+ const api = window.electronAPI?.workLouderCodex;+ if (!api) {+ if (mountedRef.current) {+ setLoading(false);+ setError('load');+ }+ return;+ }+ if (mountedRef.current) {+ setLoading(true);+ setError(null);+ }+ const pushVersion = pushVersionRef.current;+ try {+ const next = await api.getState();+ if (!mountedRef.current) return;+ if (pushVersion === pushVersionRef.current) {+ confirmedSettingsRef.current = { ...next.settings };+ setState(next);+ }+ setError(null);+ } catch {+ if (mountedRef.current) setError('load');+ } finally {+ if (mountedRef.current) setLoading(false);+ }+ }, []);++ useEffect(() => {+ mountedRef.current = true;+ const api = window.electronAPI?.workLouderCodex;+ const unsubscribe = api?.onStateChanged((next) => {+ if (!mountedRef.current) return;+ pushVersionRef.current += 1;+ confirmedSettingsRef.current = { ...next.settings };+ setState(next);+ });+ void reload();+ return () => {+ mountedRef.current = false;+ unsubscribe?.();+ };+ }, [reload]);++ /**+ * Poll for an unplug while the caller is showing connection state.+ *+ * Pauses whenever the window is hidden or in the background: an unattended+ * app has no reason to keep waking the keyboard, and whoever comes back gets+ * a fresh reading immediately because visibility change probes right away.+ */+ useEffect(() => {+ if (!watchConnection) return;+ const api = window.electronAPI?.workLouderCodex;+ if (!api?.probe) return;++ let timer: ReturnType<typeof setInterval> | null = null;+ const probe = (): void => {+ void api.probe().catch(() => {+ // A failed probe is itself inconclusive; the next one decides.+ });+ };+ const start = (): void => {+ if (timer) return;+ probe();+ timer = setInterval(probe, CONNECTION_PROBE_MS);+ };+ const stop = (): void => {+ if (!timer) return;+ clearInterval(timer);+ timer = null;+ };+ const sync = (): void => {+ if (document.visibilityState === 'visible') start();+ else stop();+ };++ sync();+ document.addEventListener('visibilitychange', sync);+ return () => {+ document.removeEventListener('visibilitychange', sync);+ stop();+ };+ }, [watchConnection]);++ const setSettings = useCallback(+ async (patch: WorkLouderCodexSettingsPatch) => {+ const api = window.electronAPI?.workLouderCodex;+ if (!api) {+ if (mountedRef.current) setError('save');+ return;+ }+ const requestId = ++mutationIdRef.current;+ const previous = state;+ if (mountedRef.current) {+ setSaving(true);+ setError(null);+ setState((current) =>+ current ? { ...current, settings: { ...current.settings, ...patch } } : current,+ );+ }+ try {+ const next = await api.setSettings(patch);+ if (!mountedRef.current || requestId !== mutationIdRef.current) return;+ confirmedSettingsRef.current = { ...next.settings };+ setState(next);+ } catch {+ if (!mountedRef.current || requestId !== mutationIdRef.current) return;+ const rollbackSettings = confirmedSettingsRef.current ?? previous?.settings;+ if (rollbackSettings) {+ setState((current) =>+ current+ ? { ...current, settings: { ...rollbackSettings } }+ : previous+ ? { ...previous, settings: { ...rollbackSettings } }+ : current,+ );+ }+ setError('save');+ } finally {+ if (mountedRef.current && requestId === mutationIdRef.current) setSaving(false);+ }+ },+ [state],+ );++ const resetSettings = useCallback(async () => {+ const api = window.electronAPI?.workLouderCodex;+ if (!api) {+ if (mountedRef.current) setError('save');+ return;+ }+ const requestId = ++mutationIdRef.current;+ if (mountedRef.current) {+ setSaving(true);+ setError(null);+ }+ try {+ const next = await api.resetSettings();+ if (!mountedRef.current || requestId !== mutationIdRef.current) return;+ confirmedSettingsRef.current = { ...next.settings };+ setState(next);+ } catch {+ if (mountedRef.current && requestId === mutationIdRef.current) setError('save');+ } finally {+ if (mountedRef.current && requestId === mutationIdRef.current) setSaving(false);+ }+ }, []);++ const openInputMonitoringSettings = useCallback(async () => {+ try {+ await window.electronAPI?.workLouderCodex?.openInputMonitoringSettings();+ } catch {+ if (mountedRef.current) setError('load');+ }+ }, []);++ return {+ state,+ loading,+ saving,+ error,+ setSettings,+ resetSettings,+ openInputMonitoringSettings,+ reload,+ };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ab07f30f27..866e748b5b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3247,6 +3247,311 @@"reset": "Reset to default","recording": "Press new shortcut…","editAria": "Change shortcut for {{name}}",+ "workLouderCodex": {+ "commands": {+ "session.selectPrevious": {+ "name": "Previous task",+ "description": "Open the task above the current one in the sidebar"+ },+ "session.selectNext": {+ "name": "Next task",+ "description": "Open the task below the current one in the sidebar"+ },+ "toggleRightSidebar": {+ "name": "Toggle right sidebar",+ "description": "Show or hide the right sidebar"+ },+ "composer.toggleFastMode": {+ "name": "Toggle Fast mode",+ "description": "Turn Fast mode on or off in the current composer"+ },+ "approval.approve": {+ "name": "Approve request",+ "description": "Approve the active request"+ },+ "approval.decline": {+ "name": "Decline request",+ "description": "Decline the active request"+ },+ "forkTask": {+ "name": "Continue in new task",+ "description": "Create a new task from the current one"+ },+ "composer.submit": {+ "name": "Send message",+ "description": "Send the current composer message"+ },+ "feedback": {+ "name": "Send feedback",+ "description": "Send product feedback to the Cindy team"+ },+ "toggleTerminal": {+ "name": "Open terminal",+ "description": "Open the terminal panel"+ },+ "copyConversationMarkdown": {+ "name": "Copy as Markdown",+ "description": "Copy the current task as Markdown",+ "copied": "Copied the task as Markdown",+ "empty": "This task has nothing to copy yet",+ "failed": "Could not copy the task"+ },+ "archiveTask": {+ "name": "Archive task",+ "description": "Archive the current task"+ },+ "newTask": {+ "name": "New task",+ "description": "Start a new task"+ },+ "openBrowserTab": {+ "name": "Open browser tab",+ "description": "Open a new browser tab"+ },+ "toggleTaskPin": {+ "name": "Toggle pin",+ "description": "Pin or unpin the current task"+ },+ "toggleReviewTab": {+ "name": "Toggle review",+ "description": "Show or hide review for the current task"+ },+ "composer.addPhotos": {+ "name": "Add photos",+ "description": "Add photos to the composer"+ },+ "settings": {+ "name": "Settings",+ "description": "Open Cindy settings"+ },+ "manageTasks": {+ "name": "Manage scheduled tasks",+ "description": "Create or manage scheduled tasks"+ },+ "composer.increaseReasoningEffort": {+ "name": "Increase reasoning effort",+ "description": "Raise the reasoning effort for the current composer"+ },+ "composer.decreaseReasoningEffort": {+ "name": "Decrease reasoning effort",+ "description": "Lower the reasoning effort for the current composer"+ },+ "openFolder": {+ "name": "Open folder",+ "description": "Add a local project to Cindy"+ },+ "composer.addFiles": {+ "name": "Attach files and folders",+ "description": "Attach files and folders to the composer"+ },+ "openSkills": {+ "name": "Go to skills",+ "description": "Browse installed and recommended skills"+ },+ "composer.togglePlanMode": {+ "name": "Toggle plan mode",+ "description": "Turn plan mode on or off in the current composer"+ },+ "navigateForward": {+ "name": "Forward",+ "description": "Go forward in navigation history"+ },+ "toggleSidebar": {+ "name": "Toggle sidebar",+ "description": "Show or hide the sidebar"+ },+ "navigateBack": {+ "name": "Back",+ "description": "Go back in navigation history"+ },+ "composer.focus": {+ "name": "Focus composer",+ "description": "Move the cursor into the composer"+ },+ "conversation.scrollUp": {+ "name": "Scroll up",+ "description": "Scroll the conversation up"+ },+ "conversation.scrollDown": {+ "name": "Scroll down",+ "description": "Scroll the conversation down"+ },+ "conversation.scrollBottom": {+ "name": "Jump to latest",+ "description": "Scroll to the latest message"+ }+ },+ "title": "Work Louder Codex Micro",+ "beta": "Beta",+ "entryDescription": "Open tasks with the Agent keys and mirror their status with lighting.",+ "openAria": "Open Work Louder Codex Micro settings",+ "back": "Back to keyboard shortcuts",+ "retry": "Try again",+ "device": {+ "title": "Device",+ "firmware": "Firmware {{version}}",+ "inputMonitoring": {+ "label": "Input Monitoring",+ "granted": "macOS allows Cindy to receive keyboard input.",+ "denied": "macOS is blocking keyboard input. Allow Cindy in System Settings.",+ "unknown": "Cindy has not checked the macOS Input Monitoring permission yet.",+ "not-required": "Input Monitoring is not required on this platform.",+ "open": "Open System Settings"+ }+ },+ "errors": {+ "load": "Failed to load Codex Micro settings",+ "save": "Failed to save Codex Micro settings"+ },+ "connection": {+ "label": "Connection",+ "status": {+ "connecting": "Connecting",+ "connected": "Connected",+ "not-detected": "Not detected",+ "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.",+ "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.",+ "connection-timeout": "The Work Louder service did not respond in time. Cindy will retry automatically.",+ "connection-failed": "The Work Louder service failed to start. Cindy will retry automatically.",+ "permission-required": "macOS denied keyboard access. Allow Cindy in Input Monitoring, then try again.",+ "sdk-unavailable": "The official Work Louder SDK was not found. Keep a supported ChatGPT or Codex app installed, then restart Cindy."+ }+ },+ "lighting": {+ "title": "Lighting",+ "brightness": {+ "label": "Brightness",+ "description": "Adjust the overall brightness of the key, task, and ambient lighting.",+ "aria": "Adjust Codex Micro lighting brightness"+ },+ "autoDim": {+ "label": "Auto-dim",+ "description": "Turn lighting off after inactivity and restore it when the keyboard is used or a task changes state.",+ "aria": "Choose Codex Micro auto-dim delay",+ "options": {+ "off": "Off",+ "30-seconds": "30 seconds",+ "1-minute": "1 minute",+ "3-minutes": "3 minutes",+ "10-minutes": "10 minutes",+ "30-minutes": "30 minutes",+ "1-hour": "1 hour"+ }+ }+ },+ "agentKeys": {+ "customDescription": "What this agent key opens when the source is set to custom.",+ "title": "Agent keys",+ "source": {+ "label": "Task order",+ "description": "AG00–AG05 follow the first six tasks in the sidebar, in the order shown there.",+ "descriptions": {+ "sidebar": "AG00–AG05 follow the first six tasks in the sidebar, in the order shown there.",+ "last-sent": "AG00–AG05 follow the six tasks you last sent a message in.",+ "priority": "AG00–AG05 follow the first six priority tasks.",+ "custom": "AG00–AG05 each open the task you assign."+ },+ "value": "Sidebar order",+ "options": {+ "sidebar": "Sidebar order",+ "last-sent": "Recent tasks",+ "priority": "Priority",+ "custom": "Custom"+ }+ },+ "singleTap": {+ "label": "Focus Cindy with a single tap",+ "description": "When enabled, one tap opens the task and brings Cindy forward. When disabled, one tap still switches tasks in the background; a second tap within 350 ms brings Cindy forward.",+ "aria": "Focus Cindy with a single Agent-key tap"+ },+ "newTask": "New task",+ "slot": "Recent {{position}}",+ "slotAria": "AG{{slot}} opens recent task {{position}}"+ },+ "commandKeys": {+ "builtInDescription": "Leave this on the keycap default, or bind the key to something else.",+ "builtIn": "Use the keycap's built-in action",+ "unmapped": "This keycap has no action"+ },+ "microphone": {+ "title": "Microphone",+ "separate": {+ "label": "Use separate microphone keys",+ "description": "Keep ACT10 and ACT11 separate instead of combining them into one MIC key."+ }+ },+ "analog": {+ "title": "Joystick",+ "description": "Choose the action for each joystick direction.",+ "directions": {+ "up": "Up",+ "right": "Right",+ "down": "Down",+ "left": "Left"+ }+ },+ "encoder": {+ "title": "Encoder",+ "mode": {+ "label": "Encoder mode",+ "description": "Choose what turning and pressing the encoder controls.",+ "options": {+ "session-switch": "Switch tasks",+ "composer-navigation": "Navigate the composer",+ "reasoning": "Reasoning effort",+ "conversation-scroll": "Scroll the conversation",+ "custom": "Custom"+ }+ },+ "gestures": {+ "left": "Turn left",+ "right": "Turn right",+ "click": "Press",+ "longPress": "Long press"+ },+ "customDescription": "Choose the action for this encoder gesture."+ },+ "actions": {+ "choose": "Choose an action",+ "none": "No action",+ "tasks": "Tasks",+ "commands": "Commands",+ "keycaps": "Keycaps",+ "skills": "Skills"+ },+ "layout": {+ "editor": {+ "done": "Done",+ "title": "Edit keycap",+ "description": "Choose the keycap shown on this physical key.",+ "searchPlaceholder": "Search keycaps",+ "close": "Close keycap editor",+ "cancel": "Cancel",+ "save": "Save",+ "assignedShortcut": "Assigned action",+ "selectKeycap": "Select keycap {{keycap}}"+ },+ "keyboard": {+ "indicator": "Status lights",+ "title": "Layout",+ "description": "Click a keycap to choose its label and built-in action.",+ "analogStick": "Joystick",+ "encoder": "Encoder"+ },+ "reset": {+ "title": "Reset key layout",+ "description": "Restore keycaps, joystick, encoder, and microphone assignments without changing task order or lighting.",+ "button": "Reset layout"+ }+ }+ },"errors": {"saveFailed": "Failed to save shortcut settings","notBindable": "This key combination cannot be used",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex b0afe627c1..129ba1f753 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3246,6 +3246,311 @@"reset": "デフォルトに戻す","recording": "新しいショートカットを入力…","editAria": "{{name}} のショートカットを変更",+ "workLouderCodex": {+ "commands": {+ "session.selectPrevious": {+ "name": "前のタスク",+ "description": "サイドバーで現在のタスクの上にあるタスクを開きます"+ },+ "session.selectNext": {+ "name": "次のタスク",+ "description": "サイドバーで現在のタスクの下にあるタスクを開きます"+ },+ "toggleRightSidebar": {+ "name": "右サイドバーの切り替え",+ "description": "右サイドバーを表示/非表示にします"+ },+ "composer.toggleFastMode": {+ "name": "高速モードの切り替え",+ "description": "現在の入力欄で高速モードをオン/オフにします"+ },+ "approval.approve": {+ "name": "リクエストを承認",+ "description": "確認待ちのリクエストを承認します"+ },+ "approval.decline": {+ "name": "リクエストを拒否",+ "description": "確認待ちのリクエストを拒否します"+ },+ "forkTask": {+ "name": "新しいタスクで続ける",+ "description": "現在のタスクから新しいタスクを作成します"+ },+ "composer.submit": {+ "name": "メッセージを送信",+ "description": "入力欄のメッセージを送信します"+ },+ "feedback": {+ "name": "フィードバックを送信",+ "description": "製品フィードバックを Cindy チームに送信します"+ },+ "toggleTerminal": {+ "name": "ターミナルを開く",+ "description": "ターミナルパネルを開きます"+ },+ "copyConversationMarkdown": {+ "name": "Markdown としてコピー",+ "description": "現在のタスクの内容を Markdown としてコピーします",+ "copied": "Markdown としてコピーしました",+ "empty": "このタスクにはまだコピーできる内容がありません",+ "failed": "コピーできませんでした"+ },+ "archiveTask": {+ "name": "タスクをアーカイブ",+ "description": "現在のタスクをアーカイブします"+ },+ "newTask": {+ "name": "新しいタスク",+ "description": "新しいタスクを開始します"+ },+ "openBrowserTab": {+ "name": "ブラウザタブを開く",+ "description": "新しいブラウザタブを開きます"+ },+ "toggleTaskPin": {+ "name": "ピン留めの切り替え",+ "description": "現在のタスクをピン留め、または解除します"+ },+ "toggleReviewTab": {+ "name": "レビューの切り替え",+ "description": "現在のタスクのレビューを表示/非表示にします"+ },+ "composer.addPhotos": {+ "name": "画像を追加",+ "description": "入力欄に画像を追加します"+ },+ "settings": {+ "name": "設定",+ "description": "Cindy の設定を開きます"+ },+ "manageTasks": {+ "name": "予約タスクを管理",+ "description": "予約タスクを作成または管理します"+ },+ "composer.increaseReasoningEffort": {+ "name": "推論強度を上げる",+ "description": "現在の入力欄の推論強度を上げます"+ },+ "composer.decreaseReasoningEffort": {+ "name": "推論強度を下げる",+ "description": "現在の入力欄の推論強度を下げます"+ },+ "openFolder": {+ "name": "フォルダを開く",+ "description": "ローカルプロジェクトを Cindy に追加します"+ },+ "composer.addFiles": {+ "name": "ファイルとフォルダを添付",+ "description": "入力欄にファイルとフォルダを添付します"+ },+ "openSkills": {+ "name": "スキルを開く",+ "description": "インストール済みおよびおすすめのスキルを表示します"+ },+ "composer.togglePlanMode": {+ "name": "プランモードの切り替え",+ "description": "現在の入力欄でプランモードをオン/オフにします"+ },+ "navigateForward": {+ "name": "進む",+ "description": "ナビゲーション履歴を前に進みます"+ },+ "toggleSidebar": {+ "name": "サイドバーの切り替え",+ "description": "サイドバーを表示/非表示にします"+ },+ "navigateBack": {+ "name": "戻る",+ "description": "ナビゲーション履歴を戻ります"+ },+ "composer.focus": {+ "name": "入力欄にフォーカス",+ "description": "カーソルを入力欄に移動します"+ },+ "conversation.scrollUp": {+ "name": "上にスクロール",+ "description": "対話を上にスクロールします"+ },+ "conversation.scrollDown": {+ "name": "下にスクロール",+ "description": "対話を下にスクロールします"+ },+ "conversation.scrollBottom": {+ "name": "最新へ移動",+ "description": "最新のメッセージまでスクロールします"+ }+ },+ "title": "Work Louder Codex Micro",+ "beta": "Beta",+ "entryDescription": "Agent キーでタスクを開き、ライトで状態を表示します。",+ "openAria": "Work Louder Codex Micro の設定を開く",+ "back": "キーボードショートカットに戻る",+ "retry": "再試行",+ "device": {+ "title": "デバイス",+ "firmware": "ファームウェア {{version}}",+ "inputMonitoring": {+ "label": "入力モニタリング",+ "granted": "macOS は Cindy のキーボード入力の受信を許可しています。",+ "denied": "macOS がキーボード入力をブロックしています。システム設定で Cindy を許可してください。",+ "unknown": "Cindy は macOS の入力モニタリング権限をまだ確認していません。",+ "not-required": "このプラットフォームでは入力モニタリングは必要ありません。",+ "open": "システム設定を開く"+ }+ },+ "errors": {+ "load": "Codex Micro の設定を読み込めませんでした",+ "save": "Codex Micro の設定を保存できませんでした"+ },+ "connection": {+ "label": "接続",+ "status": {+ "connecting": "接続中",+ "connected": "接続済み",+ "not-detected": "検出されていません",+ "error": "接続エラー",+ "unavailable": "SDK を利用できません"+ },+ "descriptions": {+ "connecting": "Cindy が Work Louder デバイスサービスを起動しています。",+ "connected": "USB 接続済みです。Cindy がキー入力を待ち受け、タスクのライトを同期しています。",+ "not-detected": "データ通信対応の USB ケーブルで接続してください。ChatGPT がデバイスを使用している場合は終了してください。",+ "error": "Cindy はキーボードと通信できませんでした。自動的に再試行しています。",+ "unavailable": "公式 Work Louder SDK が見つかりません。Codex Micro 対応の ChatGPT または Codex アプリを残した状態で Cindy を再起動してください。",+ "connection-timeout": "Work Louder サービスが時間内に応答しませんでした。Cindy は自動的に再試行します。",+ "connection-failed": "Work Louder サービスを起動できませんでした。Cindy は自動的に再試行します。",+ "permission-required": "macOS がキーボードへのアクセスを拒否しました。入力モニタリングで Cindy を許可してから再試行してください。",+ "sdk-unavailable": "公式 Work Louder SDK が見つかりません。Codex Micro 対応の ChatGPT または Codex アプリを残した状態で Cindy を再起動してください。"+ }+ },+ "lighting": {+ "title": "ライト",+ "brightness": {+ "label": "明るさ",+ "description": "キー、タスク、アンビエントライト全体の明るさを調整します。",+ "aria": "Codex Micro のライトの明るさを調整"+ },+ "autoDim": {+ "label": "自動消灯",+ "description": "操作がないとライトを消し、キーボードの使用またはタスク状態の変化で復帰します。",+ "aria": "Codex Micro の自動消灯時間を選択",+ "options": {+ "off": "オフ",+ "30-seconds": "30 秒",+ "1-minute": "1 分",+ "3-minutes": "3 分",+ "10-minutes": "10 分",+ "30-minutes": "30 分",+ "1-hour": "1 時間"+ }+ }+ },+ "agentKeys": {+ "customDescription": "ソースをカスタムにしたとき、このタスクキーが開く対象です。",+ "title": "Agent キー",+ "source": {+ "label": "タスクの順序",+ "description": "AG00~AG05 はサイドバーの上から 6 件で、並び順もサイドバーと同じです。",+ "descriptions": {+ "sidebar": "AG00~AG05 はサイドバーの上から 6 件で、並び順もサイドバーと同じです。",+ "last-sent": "AG00~AG05 は、最後にメッセージを送ったタスクの新しい順です。",+ "priority": "AG00~AG05 は優先タスクの上から 6 件です。",+ "custom": "AG00~AG05 はそれぞれ指定したタスクを開きます。"+ },+ "value": "サイドバー順",+ "options": {+ "sidebar": "サイドバー順",+ "last-sent": "最近のタスク",+ "priority": "優先タスク",+ "custom": "カスタム"+ }+ },+ "singleTap": {+ "label": "1 回押して Cindy をアクティブにする",+ "description": "オンにすると 1 回押すだけでタスクを開いて Cindy を前面に表示します。オフの場合も 1 回押すとタスクを切り替え、350 ミリ秒以内に同じキーをもう一度押すと Cindy を前面に表示します。",+ "aria": "Agent キーを 1 回押して Cindy をアクティブにする"+ },+ "newTask": "新しいタスク",+ "slot": "最近の {{position}} 件目",+ "slotAria": "AG{{slot}} で最近の {{position}} 件目のタスクを開く"+ },+ "commandKeys": {+ "builtInDescription": "キーキャップ既定の動作のままにするか、別の動作に割り当てます。",+ "builtIn": "キーキャップの組み込みアクションを使用",+ "unmapped": "このキーキャップには動作がありません"+ },+ "microphone": {+ "title": "マイク",+ "separate": {+ "label": "マイクキーを分ける",+ "description": "ACT10 と ACT11 を 1 つの MIC キーにまとめず、別々に使います。"+ }+ },+ "analog": {+ "title": "ジョイスティック",+ "description": "ジョイスティックの各方向に割り当てるアクションを選択します。",+ "directions": {+ "up": "上",+ "right": "右",+ "down": "下",+ "left": "左"+ }+ },+ "encoder": {+ "title": "エンコーダー",+ "mode": {+ "label": "エンコーダーモード",+ "description": "エンコーダーの回転と押下で操作する機能を選択します。",+ "options": {+ "session-switch": "タスクを切り替え",+ "composer-navigation": "コンポーザーを移動",+ "reasoning": "推論強度",+ "conversation-scroll": "会話をスクロール",+ "custom": "カスタム"+ }+ },+ "gestures": {+ "left": "左に回す",+ "right": "右に回す",+ "click": "押す",+ "longPress": "長押し"+ },+ "customDescription": "このエンコーダージェスチャーのアクションを選択します。"+ },+ "actions": {+ "choose": "アクションを選択",+ "none": "アクションなし",+ "tasks": "タスク",+ "commands": "コマンド",+ "keycaps": "キーキャップ",+ "skills": "スキル"+ },+ "layout": {+ "editor": {+ "done": "完了",+ "title": "キーキャップを編集",+ "description": "この物理キーに表示するキーキャップを選択します。",+ "searchPlaceholder": "キーキャップを検索",+ "close": "キーキャップエディターを閉じる",+ "cancel": "キャンセル",+ "save": "保存",+ "assignedShortcut": "割り当てられたアクション",+ "selectKeycap": "キーキャップ {{keycap}} を選択"+ },+ "keyboard": {+ "indicator": "ステータスライト",+ "title": "配置",+ "description": "キーキャップをクリックしてラベルと組み込みアクションを選択します。",+ "analogStick": "ジョイスティック",+ "encoder": "エンコーダー"+ },+ "reset": {+ "title": "キー配置をリセット",+ "description": "タスク順序やライト設定を変えずに、キーキャップ、ジョイスティック、エンコーダー、マイクの割り当てを初期状態に戻します。",+ "button": "配置をリセット"+ }+ }+ },"errors": {"saveFailed": "ショートカット設定の保存に失敗しました","notBindable": "このキーの組み合わせは使用できません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ab82c2fcaa..7adbf3151c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3246,6 +3246,311 @@"reset": "기본값으로 재설정","recording": "새 단축키를 누르세요…","editAria": "{{name}} 단축키 변경",+ "workLouderCodex": {+ "commands": {+ "session.selectPrevious": {+ "name": "이전 작업",+ "description": "사이드바에서 현재 작업 바로 위의 작업을 엽니다"+ },+ "session.selectNext": {+ "name": "다음 작업",+ "description": "사이드바에서 현재 작업 바로 아래의 작업을 엽니다"+ },+ "toggleRightSidebar": {+ "name": "오른쪽 사이드바 전환",+ "description": "오른쪽 사이드바를 표시하거나 숨깁니다"+ },+ "composer.toggleFastMode": {+ "name": "빠른 모드 전환",+ "description": "현재 입력창에서 빠른 모드를 켜거나 끕니다"+ },+ "approval.approve": {+ "name": "요청 승인",+ "description": "확인 대기 중인 요청을 승인합니다"+ },+ "approval.decline": {+ "name": "요청 거부",+ "description": "확인 대기 중인 요청을 거부합니다"+ },+ "forkTask": {+ "name": "새 작업에서 계속",+ "description": "현재 작업을 바탕으로 새 작업을 만듭니다"+ },+ "composer.submit": {+ "name": "메시지 보내기",+ "description": "입력창의 메시지를 보냅니다"+ },+ "feedback": {+ "name": "피드백 보내기",+ "description": "제품 피드백을 Cindy 팀에 보냅니다"+ },+ "toggleTerminal": {+ "name": "터미널 열기",+ "description": "터미널 패널을 엽니다"+ },+ "copyConversationMarkdown": {+ "name": "Markdown으로 복사",+ "description": "현재 작업의 대화를 Markdown으로 복사합니다",+ "copied": "Markdown으로 복사했습니다",+ "empty": "이 작업에는 아직 복사할 내용이 없습니다",+ "failed": "복사하지 못했습니다"+ },+ "archiveTask": {+ "name": "작업 보관",+ "description": "현재 작업을 보관합니다"+ },+ "newTask": {+ "name": "새 작업",+ "description": "새 작업을 시작합니다"+ },+ "openBrowserTab": {+ "name": "브라우저 탭 열기",+ "description": "새 브라우저 탭을 엽니다"+ },+ "toggleTaskPin": {+ "name": "고정 전환",+ "description": "현재 작업을 고정하거나 고정을 해제합니다"+ },+ "toggleReviewTab": {+ "name": "검토 전환",+ "description": "현재 작업의 검토를 표시하거나 숨깁니다"+ },+ "composer.addPhotos": {+ "name": "사진 추가",+ "description": "입력창에 사진을 추가합니다"+ },+ "settings": {+ "name": "설정",+ "description": "Cindy 설정을 엽니다"+ },+ "manageTasks": {+ "name": "예약 작업 관리",+ "description": "예약 작업을 만들거나 관리합니다"+ },+ "composer.increaseReasoningEffort": {+ "name": "추론 강도 높이기",+ "description": "현재 입력창의 추론 강도를 높입니다"+ },+ "composer.decreaseReasoningEffort": {+ "name": "추론 강도 낮추기",+ "description": "현재 입력창의 추론 강도를 낮춥니다"+ },+ "openFolder": {+ "name": "폴더 열기",+ "description": "로컬 프로젝트를 Cindy에 추가합니다"+ },+ "composer.addFiles": {+ "name": "파일 및 폴더 첨부",+ "description": "입력창에 파일과 폴더를 첨부합니다"+ },+ "openSkills": {+ "name": "스킬로 이동",+ "description": "설치된 스킬과 추천 스킬을 살펴봅니다"+ },+ "composer.togglePlanMode": {+ "name": "계획 모드 전환",+ "description": "현재 입력창에서 계획 모드를 켜거나 끕니다"+ },+ "navigateForward": {+ "name": "앞으로",+ "description": "탐색 기록에서 앞으로 이동합니다"+ },+ "toggleSidebar": {+ "name": "사이드바 전환",+ "description": "사이드바를 표시하거나 숨깁니다"+ },+ "navigateBack": {+ "name": "뒤로",+ "description": "탐색 기록에서 뒤로 이동합니다"+ },+ "composer.focus": {+ "name": "입력창에 포커스",+ "description": "커서를 입력창으로 옮깁니다"+ },+ "conversation.scrollUp": {+ "name": "위로 스크롤",+ "description": "대화를 위로 스크롤합니다"+ },+ "conversation.scrollDown": {+ "name": "아래로 스크롤",+ "description": "대화를 아래로 스크롤합니다"+ },+ "conversation.scrollBottom": {+ "name": "최신으로 이동",+ "description": "최신 메시지로 스크롤합니다"+ }+ },+ "title": "Work Louder Codex Micro",+ "beta": "Beta",+ "entryDescription": "Agent 키로 작업을 열고 조명으로 상태를 표시합니다.",+ "openAria": "Work Louder Codex Micro 설정 열기",+ "back": "키보드 단축키로 돌아가기",+ "retry": "다시 시도",+ "device": {+ "title": "기기",+ "firmware": "펌웨어 {{version}}",+ "inputMonitoring": {+ "label": "입력 모니터링",+ "granted": "macOS가 Cindy의 키보드 입력 수신을 허용했습니다.",+ "denied": "macOS가 키보드 입력을 차단하고 있습니다. 시스템 설정에서 Cindy를 허용하세요.",+ "unknown": "Cindy가 아직 macOS 입력 모니터링 권한을 확인하지 않았습니다.",+ "not-required": "이 플랫폼에서는 입력 모니터링이 필요하지 않습니다.",+ "open": "시스템 설정 열기"+ }+ },+ "errors": {+ "load": "Codex Micro 설정을 불러오지 못했습니다",+ "save": "Codex Micro 설정을 저장하지 못했습니다"+ },+ "connection": {+ "label": "연결",+ "status": {+ "connecting": "연결 중",+ "connected": "연결됨",+ "not-detected": "감지되지 않음",+ "error": "연결 문제",+ "unavailable": "SDK 사용 불가"+ },+ "descriptions": {+ "connecting": "Cindy가 Work Louder 장치 서비스를 시작하고 있습니다.",+ "connected": "USB가 연결되었습니다. Cindy가 키 입력을 수신하고 작업 조명을 동기화합니다.",+ "not-detected": "데이터 전송을 지원하는 USB 케이블로 연결하세요. ChatGPT가 장치를 사용 중이면 종료하세요.",+ "error": "Cindy가 키보드와 통신하지 못해 자동으로 다시 시도하고 있습니다.",+ "unavailable": "공식 Work Louder SDK를 찾지 못했습니다. Codex Micro를 지원하는 ChatGPT 또는 Codex 앱을 유지한 뒤 Cindy를 다시 시작하세요.",+ "connection-timeout": "Work Louder 서비스가 시간 내에 응답하지 않았습니다. Cindy가 자동으로 다시 시도합니다.",+ "connection-failed": "Work Louder 서비스를 시작하지 못했습니다. Cindy가 자동으로 다시 시도합니다.",+ "permission-required": "macOS가 키보드 접근을 거부했습니다. 입력 모니터링에서 Cindy를 허용한 뒤 다시 시도하세요.",+ "sdk-unavailable": "공식 Work Louder SDK를 찾지 못했습니다. Codex Micro를 지원하는 ChatGPT 또는 Codex 앱을 유지한 뒤 Cindy를 다시 시작하세요."+ }+ },+ "lighting": {+ "title": "조명",+ "brightness": {+ "label": "밝기",+ "description": "키, 작업, 주변 조명의 전체 밝기를 조절합니다.",+ "aria": "Codex Micro 조명 밝기 조절"+ },+ "autoDim": {+ "label": "자동 끄기",+ "description": "사용하지 않으면 조명을 끄고 키보드 사용 또는 작업 상태 변경 시 다시 켭니다.",+ "aria": "Codex Micro 자동 끄기 시간 선택",+ "options": {+ "off": "끄기",+ "30-seconds": "30초",+ "1-minute": "1분",+ "3-minutes": "3분",+ "10-minutes": "10분",+ "30-minutes": "30분",+ "1-hour": "1시간"+ }+ }+ },+ "agentKeys": {+ "customDescription": "소스를 사용자 지정으로 설정했을 때 이 작업 키가 여는 대상입니다.",+ "title": "Agent 키",+ "source": {+ "label": "작업 순서",+ "description": "AG00~AG05는 사이드바 위쪽 6개 작업이며 순서도 사이드바와 같습니다.",+ "descriptions": {+ "sidebar": "AG00~AG05는 사이드바 위쪽 6개 작업이며 순서도 사이드바와 같습니다.",+ "last-sent": "AG00~AG05는 마지막으로 메시지를 보낸 작업 순입니다.",+ "priority": "AG00~AG05는 우선 작업 위쪽 6개입니다.",+ "custom": "AG00~AG05는 각각 지정한 작업을 엽니다."+ },+ "value": "사이드바 순서",+ "options": {+ "sidebar": "사이드바 순서",+ "last-sent": "최근 작업",+ "priority": "우선 작업",+ "custom": "사용자 지정"+ }+ },+ "singleTap": {+ "label": "한 번 눌러 Cindy 활성화",+ "description": "켜면 한 번 눌러 작업을 열고 Cindy를 앞으로 가져옵니다. 꺼도 한 번 누르면 백그라운드에서 작업이 전환되며, 350밀리초 안에 같은 키를 다시 누르면 Cindy가 앞으로 옵니다.",+ "aria": "Agent 키를 한 번 눌러 Cindy 활성화"+ },+ "newTask": "새 작업",+ "slot": "최근 {{position}}번째",+ "slotAria": "AG{{slot}}로 최근 {{position}}번째 작업 열기"+ },+ "commandKeys": {+ "builtInDescription": "키캡 기본 동작을 유지하거나 다른 동작에 연결합니다.",+ "builtIn": "키캡 기본 동작 사용",+ "unmapped": "이 키캡에는 동작이 없습니다"+ },+ "microphone": {+ "title": "마이크",+ "separate": {+ "label": "마이크 키 분리",+ "description": "ACT10과 ACT11을 하나의 MIC 키로 합치지 않고 따로 사용합니다."+ }+ },+ "analog": {+ "title": "조이스틱",+ "description": "조이스틱 각 방향의 동작을 선택합니다.",+ "directions": {+ "up": "위",+ "right": "오른쪽",+ "down": "아래",+ "left": "왼쪽"+ }+ },+ "encoder": {+ "title": "인코더",+ "mode": {+ "label": "인코더 모드",+ "description": "인코더를 돌리거나 눌렀을 때 제어할 기능을 선택합니다.",+ "options": {+ "session-switch": "작업 전환",+ "composer-navigation": "입력창 이동",+ "reasoning": "추론 강도",+ "conversation-scroll": "대화 스크롤",+ "custom": "사용자 지정"+ }+ },+ "gestures": {+ "left": "왼쪽으로 돌리기",+ "right": "오른쪽으로 돌리기",+ "click": "누르기",+ "longPress": "길게 누르기"+ },+ "customDescription": "이 인코더 제스처의 동작을 선택합니다."+ },+ "actions": {+ "choose": "동작 선택",+ "none": "동작 없음",+ "tasks": "작업",+ "commands": "명령",+ "keycaps": "키캡",+ "skills": "스킬"+ },+ "layout": {+ "editor": {+ "done": "완료",+ "title": "키캡 편집",+ "description": "이 물리 키에 표시할 키캡을 선택합니다.",+ "searchPlaceholder": "키캡 검색",+ "close": "키캡 편집기 닫기",+ "cancel": "취소",+ "save": "저장",+ "assignedShortcut": "할당된 동작",+ "selectKeycap": "키캡 {{keycap}} 선택"+ },+ "keyboard": {+ "indicator": "상태 표시등",+ "title": "배치",+ "description": "키캡을 클릭해 레이블과 기본 동작을 선택합니다.",+ "analogStick": "조이스틱",+ "encoder": "인코더"+ },+ "reset": {+ "title": "키 배치 초기화",+ "description": "작업 순서나 조명 설정은 유지하고 키캡, 조이스틱, 인코더, 마이크 할당을 초기 상태로 되돌립니다.",+ "button": "배치 초기화"+ }+ }+ },"errors": {"saveFailed": "단축키 설정 저장에 실패했습니다","notBindable": "이 키 조합은 사용할 수 없습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4864a1bb11..75ef7967ed 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3246,6 +3246,311 @@"reset": "恢复默认","recording": "按下新快捷键…","editAria": "修改 {{name}} 的快捷键",+ "workLouderCodex": {+ "commands": {+ "session.selectPrevious": {+ "name": "上一个任务",+ "description": "打开侧边栏里当前任务上面的那个"+ },+ "session.selectNext": {+ "name": "下一个任务",+ "description": "打开侧边栏里当前任务下面的那个"+ },+ "toggleRightSidebar": {+ "name": "切换右侧栏",+ "description": "显示或隐藏右侧栏"+ },+ "composer.toggleFastMode": {+ "name": "切换快速模式",+ "description": "在当前输入框中开启或关闭快速模式"+ },+ "approval.approve": {+ "name": "批准请求",+ "description": "批准当前等待确认的请求"+ },+ "approval.decline": {+ "name": "拒绝请求",+ "description": "拒绝当前等待确认的请求"+ },+ "forkTask": {+ "name": "在新任务中继续",+ "description": "基于当前任务创建一个新任务"+ },+ "composer.submit": {+ "name": "发送消息",+ "description": "发送输入框中的消息"+ },+ "feedback": {+ "name": "发送反馈",+ "description": "把产品反馈发给 Cindy 团队"+ },+ "toggleTerminal": {+ "name": "打开终端",+ "description": "打开终端面板"+ },+ "copyConversationMarkdown": {+ "name": "复制为 Markdown",+ "description": "把当前任务的对话复制为 Markdown",+ "copied": "已复制为 Markdown",+ "empty": "这个任务还没有可复制的内容",+ "failed": "复制失败"+ },+ "archiveTask": {+ "name": "归档任务",+ "description": "归档当前任务"+ },+ "newTask": {+ "name": "新建任务",+ "description": "开始一个新任务"+ },+ "openBrowserTab": {+ "name": "打开浏览器标签页",+ "description": "打开一个新的浏览器标签页"+ },+ "toggleTaskPin": {+ "name": "切换置顶",+ "description": "置顶或取消置顶当前任务"+ },+ "toggleReviewTab": {+ "name": "切换复核",+ "description": "显示或隐藏当前任务的复核"+ },+ "composer.addPhotos": {+ "name": "添加图片",+ "description": "把图片添加到输入框"+ },+ "settings": {+ "name": "设置",+ "description": "打开 Cindy 设置"+ },+ "manageTasks": {+ "name": "管理定时任务",+ "description": "创建或管理定时任务"+ },+ "composer.increaseReasoningEffort": {+ "name": "提高推理强度",+ "description": "提高当前输入框的推理强度"+ },+ "composer.decreaseReasoningEffort": {+ "name": "降低推理强度",+ "description": "降低当前输入框的推理强度"+ },+ "openFolder": {+ "name": "打开文件夹",+ "description": "把本地项目添加到 Cindy"+ },+ "composer.addFiles": {+ "name": "附加文件和文件夹",+ "description": "把文件和文件夹附加到输入框"+ },+ "openSkills": {+ "name": "前往技能",+ "description": "浏览已安装和推荐的技能"+ },+ "composer.togglePlanMode": {+ "name": "切换计划模式",+ "description": "在当前输入框中开启或关闭计划模式"+ },+ "navigateForward": {+ "name": "前进",+ "description": "在浏览历史中前进"+ },+ "toggleSidebar": {+ "name": "切换侧边栏",+ "description": "显示或隐藏侧边栏"+ },+ "navigateBack": {+ "name": "后退",+ "description": "在浏览历史中后退"+ },+ "composer.focus": {+ "name": "聚焦输入框",+ "description": "把光标移到输入框"+ },+ "conversation.scrollUp": {+ "name": "向上滚动",+ "description": "向上滚动对话"+ },+ "conversation.scrollDown": {+ "name": "向下滚动",+ "description": "向下滚动对话"+ },+ "conversation.scrollBottom": {+ "name": "跳到最新",+ "description": "滚动到最新一条消息"+ }+ },+ "title": "Work Louder Codex Micro",+ "beta": "Beta",+ "entryDescription": "用 Agent 键打开任务,并用灯光显示任务状态。",+ "openAria": "打开 Work Louder Codex Micro 设置",+ "back": "返回键盘快捷键",+ "retry": "重试",+ "device": {+ "title": "设备",+ "firmware": "固件 {{version}}",+ "inputMonitoring": {+ "label": "输入监控权限",+ "granted": "macOS 允许 Cindy 接收键盘输入。",+ "denied": "macOS 正在阻止键盘输入,请在系统设置中允许 Cindy。",+ "unknown": "Cindy 尚未检查 macOS 的输入监控权限。",+ "not-required": "此平台不需要输入监控权限。",+ "open": "打开系统设置"+ }+ },+ "errors": {+ "load": "读取 Codex Micro 设置失败",+ "save": "保存 Codex Micro 设置失败"+ },+ "connection": {+ "label": "连接",+ "status": {+ "connecting": "正在连接",+ "connected": "已连接",+ "not-detected": "未检测到",+ "error": "连接异常",+ "unavailable": "SDK 不可用"+ },+ "descriptions": {+ "connecting": "Cindy 正在启动 Work Louder 设备服务。",+ "connected": "USB 已连接,Cindy 正在监听按键并同步任务灯效。",+ "not-detected": "请用支持数据传输的 USB 线连接键盘;如果 ChatGPT 正在占用设备,请先关闭。",+ "error": "Cindy 暂时无法与键盘通信,正在自动重试。",+ "unavailable": "未找到官方 Work Louder SDK。请保留支持 Codex Micro 的 ChatGPT 或 Codex 应用,重启 Cindy 后再试。",+ "connection-timeout": "Work Louder 服务在规定时间内没有响应,Cindy 会自动重试。",+ "connection-failed": "Work Louder 服务启动失败,Cindy 会自动重试。",+ "permission-required": "macOS 拒绝了键盘访问,请在输入监控中允许 Cindy 后重试。",+ "sdk-unavailable": "未找到官方 Work Louder SDK。请保留支持 Codex Micro 的 ChatGPT 或 Codex 应用,重启 Cindy 后再试。"+ }+ },+ "lighting": {+ "title": "灯光",+ "brightness": {+ "label": "亮度",+ "description": "调整键帽灯、任务灯和环形灯的整体亮度。",+ "aria": "调整 Codex Micro 灯光亮度"+ },+ "autoDim": {+ "label": "自动熄灯",+ "description": "闲置后关闭灯光;使用键盘或任务状态变化时自动恢复。",+ "aria": "选择 Codex Micro 自动熄灯时间",+ "options": {+ "off": "关闭",+ "30-seconds": "30 秒",+ "1-minute": "1 分钟",+ "3-minutes": "3 分钟",+ "10-minutes": "10 分钟",+ "30-minutes": "30 分钟",+ "1-hour": "1 小时"+ }+ }+ },+ "agentKeys": {+ "customDescription": "来源设为自定义时,这个任务键打开什么。",+ "title": "Agent 键",+ "source": {+ "label": "任务顺序",+ "description": "AG00~AG05 就是侧边栏从上到下的前 6 个任务,顺序与那里一致。",+ "descriptions": {+ "sidebar": "AG00~AG05 就是侧边栏从上到下的前 6 个任务,顺序与那里一致。",+ "last-sent": "AG00~AG05 按你最后一次发消息的时间,最近的排在前面。",+ "priority": "AG00~AG05 对应前 6 个优先任务。",+ "custom": "AG00~AG05 各自打开你指定的任务。"+ },+ "value": "侧边栏顺序",+ "options": {+ "sidebar": "侧边栏顺序",+ "last-sent": "最近任务",+ "priority": "优先任务",+ "custom": "自定义"+ }+ },+ "singleTap": {+ "label": "按一下激活 Cindy",+ "description": "开启后按一下就打开任务并激活 Cindy。关闭后按一下仍会在后台切换任务;350 毫秒内再按同一个键才会激活 Cindy。",+ "aria": "按一下 Agent 键激活 Cindy"+ },+ "newTask": "新任务",+ "slot": "最近第 {{position}} 个",+ "slotAria": "AG{{slot}} 打开最近第 {{position}} 个任务"+ },+ "commandKeys": {+ "builtInDescription": "保持键帽自带的动作,或把这个键改绑到别的动作。",+ "builtIn": "使用键帽预置动作",+ "unmapped": "这个键帽没有对应动作"+ },+ "microphone": {+ "title": "麦克风",+ "separate": {+ "label": "拆分麦克风键",+ "description": "保持 ACT10 和 ACT11 分开,不合并为一个 MIC 键。"+ }+ },+ "analog": {+ "title": "摇杆",+ "description": "分别设置摇杆四个方向的动作。",+ "directions": {+ "up": "上",+ "right": "右",+ "down": "下",+ "left": "左"+ }+ },+ "encoder": {+ "title": "旋钮",+ "mode": {+ "label": "旋钮模式",+ "description": "选择旋转和按下旋钮时控制的功能。",+ "options": {+ "session-switch": "切换任务",+ "composer-navigation": "导航输入框",+ "reasoning": "推理强度",+ "conversation-scroll": "滚动对话",+ "custom": "自定义"+ }+ },+ "gestures": {+ "left": "向左旋转",+ "right": "向右旋转",+ "click": "按下",+ "longPress": "长按"+ },+ "customDescription": "设置这个旋钮手势要执行的动作。"+ },+ "actions": {+ "choose": "选择动作",+ "none": "无动作",+ "tasks": "任务",+ "commands": "命令",+ "keycaps": "键帽",+ "skills": "技能"+ },+ "layout": {+ "editor": {+ "done": "完成",+ "title": "编辑键帽",+ "description": "选择这个实体按键上显示的键帽。",+ "searchPlaceholder": "搜索键帽",+ "close": "关闭键帽编辑器",+ "cancel": "取消",+ "save": "保存",+ "assignedShortcut": "已分配动作",+ "selectKeycap": "选择键帽 {{keycap}}"+ },+ "keyboard": {+ "indicator": "状态指示灯",+ "title": "布局",+ "description": "点击键帽,选择它的标签和预置动作。",+ "analogStick": "摇杆",+ "encoder": "旋钮"+ },+ "reset": {+ "title": "恢复键位布局",+ "description": "恢复键帽、摇杆、旋钮和麦克风分配,不改变任务顺序或灯光设置。",+ "button": "恢复布局"+ }+ }+ },"errors": {"saveFailed": "保存快捷键设置失败","notBindable": "该组合键不可用",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ef0183fef0..11f686ebf9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3246,6 +3246,311 @@"reset": "恢復預設","recording": "按下新快捷鍵…","editAria": "修改 {{name}} 的快捷鍵",+ "workLouderCodex": {+ "commands": {+ "session.selectPrevious": {+ "name": "上一個任務",+ "description": "開啟側邊欄中目前任務上面的那個"+ },+ "session.selectNext": {+ "name": "下一個任務",+ "description": "開啟側邊欄中目前任務下面的那個"+ },+ "toggleRightSidebar": {+ "name": "切換右側欄",+ "description": "顯示或隱藏右側欄"+ },+ "composer.toggleFastMode": {+ "name": "切換快速模式",+ "description": "在目前輸入框中開啟或關閉快速模式"+ },+ "approval.approve": {+ "name": "核准請求",+ "description": "核准目前等待確認的請求"+ },+ "approval.decline": {+ "name": "拒絕請求",+ "description": "拒絕目前等待確認的請求"+ },+ "forkTask": {+ "name": "在新任務中繼續",+ "description": "以目前任務為基礎建立新任務"+ },+ "composer.submit": {+ "name": "傳送訊息",+ "description": "傳送輸入框中的訊息"+ },+ "feedback": {+ "name": "傳送意見回饋",+ "description": "將產品意見回饋傳送給 Cindy 團隊"+ },+ "toggleTerminal": {+ "name": "開啟終端機",+ "description": "開啟終端機面板"+ },+ "copyConversationMarkdown": {+ "name": "複製為 Markdown",+ "description": "將目前任務的對話複製為 Markdown",+ "copied": "已複製為 Markdown",+ "empty": "這個任務還沒有可複製的內容",+ "failed": "複製失敗"+ },+ "archiveTask": {+ "name": "封存任務",+ "description": "封存目前任務"+ },+ "newTask": {+ "name": "新增任務",+ "description": "開始一個新任務"+ },+ "openBrowserTab": {+ "name": "開啟瀏覽器分頁",+ "description": "開啟一個新的瀏覽器分頁"+ },+ "toggleTaskPin": {+ "name": "切換釘選",+ "description": "釘選或取消釘選目前任務"+ },+ "toggleReviewTab": {+ "name": "切換複核",+ "description": "顯示或隱藏目前任務的複核"+ },+ "composer.addPhotos": {+ "name": "新增圖片",+ "description": "將圖片新增至輸入框"+ },+ "settings": {+ "name": "設定",+ "description": "開啟 Cindy 設定"+ },+ "manageTasks": {+ "name": "管理排程任務",+ "description": "建立或管理排程任務"+ },+ "composer.increaseReasoningEffort": {+ "name": "提高推理強度",+ "description": "提高目前輸入框的推理強度"+ },+ "composer.decreaseReasoningEffort": {+ "name": "降低推理強度",+ "description": "降低目前輸入框的推理強度"+ },+ "openFolder": {+ "name": "開啟資料夾",+ "description": "將本機專案新增至 Cindy"+ },+ "composer.addFiles": {+ "name": "附加檔案和資料夾",+ "description": "將檔案和資料夾附加到輸入框"+ },+ "openSkills": {+ "name": "前往技能",+ "description": "瀏覽已安裝和推薦的技能"+ },+ "composer.togglePlanMode": {+ "name": "切換計畫模式",+ "description": "在目前輸入框中開啟或關閉計畫模式"+ },+ "navigateForward": {+ "name": "前進",+ "description": "在瀏覽記錄中前進"+ },+ "toggleSidebar": {+ "name": "切換側邊欄",+ "description": "顯示或隱藏側邊欄"+ },+ "navigateBack": {+ "name": "返回",+ "description": "在瀏覽記錄中返回"+ },+ "composer.focus": {+ "name": "聚焦輸入框",+ "description": "將游標移至輸入框"+ },+ "conversation.scrollUp": {+ "name": "向上捲動",+ "description": "向上捲動對話"+ },+ "conversation.scrollDown": {+ "name": "向下捲動",+ "description": "向下捲動對話"+ },+ "conversation.scrollBottom": {+ "name": "跳到最新",+ "description": "捲動到最新一則訊息"+ }+ },+ "title": "Work Louder Codex Micro",+ "beta": "Beta",+ "entryDescription": "用 Agent 鍵開啟任務,並用燈光顯示任務狀態。",+ "openAria": "開啟 Work Louder Codex Micro 設定",+ "back": "返回鍵盤快捷鍵",+ "retry": "重試",+ "device": {+ "title": "裝置",+ "firmware": "韌體 {{version}}",+ "inputMonitoring": {+ "label": "輸入監控權限",+ "granted": "macOS 允許 Cindy 接收鍵盤輸入。",+ "denied": "macOS 正在阻擋鍵盤輸入,請在系統設定中允許 Cindy。",+ "unknown": "Cindy 尚未檢查 macOS 的輸入監控權限。",+ "not-required": "此平台不需要輸入監控權限。",+ "open": "開啟系統設定"+ }+ },+ "errors": {+ "load": "讀取 Codex Micro 設定失敗",+ "save": "儲存 Codex Micro 設定失敗"+ },+ "connection": {+ "label": "連線",+ "status": {+ "connecting": "正在連線",+ "connected": "已連線",+ "not-detected": "未偵測到",+ "error": "連線異常",+ "unavailable": "SDK 無法使用"+ },+ "descriptions": {+ "connecting": "Cindy 正在啟動 Work Louder 裝置服務。",+ "connected": "USB 已連線,Cindy 正在監聽按鍵並同步任務燈效。",+ "not-detected": "請用支援資料傳輸的 USB 線連接鍵盤;如果 ChatGPT 正在占用裝置,請先關閉。",+ "error": "Cindy 暫時無法與鍵盤通訊,正在自動重試。",+ "unavailable": "找不到官方 Work Louder SDK。請保留支援 Codex Micro 的 ChatGPT 或 Codex 應用程式,重新啟動 Cindy 後再試。",+ "connection-timeout": "Work Louder 服務未在期限內回應,Cindy 會自動重試。",+ "connection-failed": "Work Louder 服務啟動失敗,Cindy 會自動重試。",+ "permission-required": "macOS 拒絕鍵盤存取,請在輸入監控中允許 Cindy 後重試。",+ "sdk-unavailable": "找不到官方 Work Louder SDK。請保留支援 Codex Micro 的 ChatGPT 或 Codex 應用程式,重新啟動 Cindy 後再試。"+ }+ },+ "lighting": {+ "title": "燈光",+ "brightness": {+ "label": "亮度",+ "description": "調整鍵帽燈、任務燈和環形燈的整體亮度。",+ "aria": "調整 Codex Micro 燈光亮度"+ },+ "autoDim": {+ "label": "自動熄燈",+ "description": "閒置後關閉燈光;使用鍵盤或任務狀態變更時自動恢復。",+ "aria": "選擇 Codex Micro 自動熄燈時間",+ "options": {+ "off": "關閉",+ "30-seconds": "30 秒",+ "1-minute": "1 分鐘",+ "3-minutes": "3 分鐘",+ "10-minutes": "10 分鐘",+ "30-minutes": "30 分鐘",+ "1-hour": "1 小時"+ }+ }+ },+ "agentKeys": {+ "customDescription": "來源設為自訂時,這個任務鍵開啟什麼。",+ "title": "Agent 鍵",+ "source": {+ "label": "任務順序",+ "description": "AG00~AG05 就是側邊欄從上到下的前 6 個任務,順序與那裡一致。",+ "descriptions": {+ "sidebar": "AG00~AG05 就是側邊欄從上到下的前 6 個任務,順序與那裡一致。",+ "last-sent": "AG00~AG05 依你最後一次傳送訊息的時間,最近的排在前面。",+ "priority": "AG00~AG05 對應前 6 個優先任務。",+ "custom": "AG00~AG05 各自開啟你指定的任務。"+ },+ "value": "側邊欄順序",+ "options": {+ "sidebar": "側邊欄順序",+ "last-sent": "最近任務",+ "priority": "優先任務",+ "custom": "自訂"+ }+ },+ "singleTap": {+ "label": "按一下啟用 Cindy",+ "description": "開啟後按一下就開啟任務並啟用 Cindy。關閉後按一下仍會在背景切換任務;350 毫秒內再按同一個鍵才會啟用 Cindy。",+ "aria": "按一下 Agent 鍵啟用 Cindy"+ },+ "newTask": "新任務",+ "slot": "最近第 {{position}} 個",+ "slotAria": "AG{{slot}} 開啟最近第 {{position}} 個任務"+ },+ "commandKeys": {+ "builtInDescription": "保持鍵帽內建的動作,或將這個鍵改綁到其他動作。",+ "builtIn": "使用鍵帽預設動作",+ "unmapped": "這個鍵帽沒有對應動作"+ },+ "microphone": {+ "title": "麥克風",+ "separate": {+ "label": "拆分麥克風鍵",+ "description": "保持 ACT10 和 ACT11 分開,不合併為一個 MIC 鍵。"+ }+ },+ "analog": {+ "title": "搖桿",+ "description": "分別設定搖桿四個方向的動作。",+ "directions": {+ "up": "上",+ "right": "右",+ "down": "下",+ "left": "左"+ }+ },+ "encoder": {+ "title": "旋鈕",+ "mode": {+ "label": "旋鈕模式",+ "description": "選擇旋轉和按下旋鈕時控制的功能。",+ "options": {+ "session-switch": "切換任務",+ "composer-navigation": "導覽輸入框",+ "reasoning": "推理強度",+ "conversation-scroll": "捲動對話",+ "custom": "自訂"+ }+ },+ "gestures": {+ "left": "向左旋轉",+ "right": "向右旋轉",+ "click": "按下",+ "longPress": "長按"+ },+ "customDescription": "設定這個旋鈕手勢要執行的動作。"+ },+ "actions": {+ "choose": "選擇動作",+ "none": "無動作",+ "tasks": "任務",+ "commands": "命令",+ "keycaps": "鍵帽",+ "skills": "技能"+ },+ "layout": {+ "editor": {+ "done": "完成",+ "title": "編輯鍵帽",+ "description": "選擇這個實體按鍵上顯示的鍵帽。",+ "searchPlaceholder": "搜尋鍵帽",+ "close": "關閉鍵帽編輯器",+ "cancel": "取消",+ "save": "儲存",+ "assignedShortcut": "已分配動作",+ "selectKeycap": "選擇鍵帽 {{keycap}}"+ },+ "keyboard": {+ "indicator": "狀態指示燈",+ "title": "配置",+ "description": "點選鍵帽,選擇它的標籤和預設動作。",+ "analogStick": "搖桿",+ "encoder": "旋鈕"+ },+ "reset": {+ "title": "恢復鍵位配置",+ "description": "恢復鍵帽、搖桿、旋鈕和麥克風分配,不變更任務順序或燈光設定。",+ "button": "恢復配置"+ }+ }+ },"errors": {"saveFailed": "儲存快捷鍵設定失敗","notBindable": "該組合鍵不可用",diff --git a/apps/desktop/src/renderer/lib/__tests__/inputDeviceActions.test.ts b/apps/desktop/src/renderer/lib/__tests__/inputDeviceActions.test.tsnew file mode 100644index 0000000000..dff563bd63--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/inputDeviceActions.test.ts@@ -0,0 +1,37 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ __resetInputDeviceActionsForTests,+ dispatchInputDeviceAction,+ subscribeInputDeviceAction,+} from '../inputDeviceActions';++describe('inputDeviceActions', () => {+ afterEach(() => {+ __resetInputDeviceActionsForTests();+ });++ it('lets the newest subscriber consume a command first', () => {+ const older = vi.fn(() => true);+ const newer = vi.fn(() => true);+ subscribeInputDeviceAction(older);+ subscribeInputDeviceAction(newer);++ dispatchInputDeviceAction({ type: 'command', commandId: 'forkTask' });++ expect(newer).toHaveBeenCalledOnce();+ expect(older).not.toHaveBeenCalled();+ });++ it('continues to older subscribers when the newer one declines', () => {+ const older = vi.fn(() => true);+ const newer = vi.fn(() => false);+ subscribeInputDeviceAction(older);+ subscribeInputDeviceAction(newer);++ dispatchInputDeviceAction({ type: 'command', commandId: 'copyConversationMarkdown' });++ expect(newer).toHaveBeenCalledOnce();+ expect(older).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/renderer/lib/__tests__/workLouderCodexTaskActions.test.ts b/apps/desktop/src/renderer/lib/__tests__/workLouderCodexTaskActions.test.tsnew file mode 100644index 0000000000..e59014cc1b--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/workLouderCodexTaskActions.test.ts@@ -0,0 +1,115 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ listMessagesFor: vi.fn(),+ forkAtMessage: vi.fn(),+ emitRefresh: vi.fn(),+ getSessionDeviceId: vi.fn(),+ refreshRemoteDeviceSessions: vi.fn(),+ toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },+}));++vi.mock('@/lib/makerTransport', () => ({+ listMessagesFor: mocks.listMessagesFor,+}));+vi.mock('@/lib/sessionService', () => ({+ forkAtMessage: mocks.forkAtMessage,+}));+vi.mock('@/lib/sessionsBus', () => ({+ emitRefresh: mocks.emitRefresh,+}));+vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ getSessionDeviceId: mocks.getSessionDeviceId,+}));+vi.mock('@/features/device-link/refreshRemoteSessions', () => ({+ refreshRemoteDeviceSessions: mocks.refreshRemoteDeviceSessions,+}));+vi.mock('@/lib/toast', () => ({+ toast: mocks.toast,+}));+vi.mock('@/lib/sessionMessageText', () => ({+ sessionMessageDisplayText: (message: { content?: string }) => message.content ?? null,+}));++import {+ copyCurrentTaskMarkdown,+ forkCurrentTaskFromKeyboard,+} from '../workLouderCodexTaskActions';++describe('workLouderCodexTaskActions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getSessionDeviceId.mockReturnValue(undefined);+ });++ it('forks at the latest assistant reply and opens the new task', async () => {+ mocks.listMessagesFor.mockResolvedValue([+ { role: 'assistant', clientId: 'a2', content: 'later', id: 'm2', createdAt: '2026-08-18T01:00:00.000Z' },+ { role: 'user', clientId: 'u2', content: 'again', id: 'm3', createdAt: '2026-08-18T00:30:00.000Z' },+ { role: 'assistant', clientId: 'a1', content: 'hi', id: 'm1', createdAt: '2026-08-18T00:00:00.000Z' },+ ]);+ mocks.forkAtMessage.mockResolvedValue({ id: 'forked' });+ const navigate = vi.fn();++ await forkCurrentTaskFromKeyboard('session-1', { navigate, t: (key) => key });++ expect(mocks.forkAtMessage).toHaveBeenCalledWith('session-1', 'a2');+ expect(mocks.emitRefresh).toHaveBeenCalledOnce();+ expect(navigate).toHaveBeenCalledWith('/cc-agent/forked');+ });++ it('copies readable conversation markdown', async () => {+ const newestPage: Array<{+ role: 'user' | 'assistant';+ content: string;+ id: string;+ createdAt: string;+ }> = Array.from({ length: 100 }, (_, index) => ({+ role: 'user',+ content: `later-${index}`,+ id: `later-${index}`,+ createdAt: '2026-08-18T02:00:00.000Z',+ }));+ newestPage[0] = {+ role: 'assistant',+ content: 'latest',+ id: 'latest',+ createdAt: '2026-08-18T02:01:00.000Z',+ };+ mocks.listMessagesFor+ .mockResolvedValueOnce(newestPage)+ .mockResolvedValueOnce([+ { role: 'assistant', content: 'world', id: 'old-2', createdAt: '2026-08-18T00:01:00.000Z' },+ { role: 'user', content: 'hello', id: 'old-1', createdAt: '2026-08-18T00:00:00.000Z' },+ ]);+ const writeText = vi.fn().mockResolvedValue(undefined);+ Object.assign(navigator, { clipboard: { writeText } });++ await copyCurrentTaskMarkdown('session-1', { navigate: vi.fn(), t: (key) => key });++ expect(writeText).toHaveBeenCalledWith(+ expect.stringMatching(/^## User\n\nhello\n\n## Cindy\n\nworld[\s\S]*## Cindy\n\nlatest$/),+ );+ expect(mocks.listMessagesFor).toHaveBeenCalledTimes(2);+ expect(mocks.toast.success).toHaveBeenCalled();+ });++ it('shows an error when there is no assistant reply to fork from', async () => {+ mocks.listMessagesFor.mockResolvedValue([{ role: 'user', clientId: 'u1', content: 'hello' }]);++ await forkCurrentTaskFromKeyboard('session-1', { navigate: vi.fn(), t: (key) => key });++ expect(mocks.forkAtMessage).not.toHaveBeenCalled();+ expect(mocks.toast.error).toHaveBeenCalledWith('chat.userMessage.forkErrors.noPriorAssistant');+ });++ it('warns when there is no conversation text to copy', async () => {+ mocks.listMessagesFor.mockResolvedValue([]);++ await copyCurrentTaskMarkdown('session-1', { navigate: vi.fn(), t: (key) => key });++ expect(mocks.toast.warning).toHaveBeenCalledWith(+ 'settings.shortcuts.workLouderCodex.commands.copyConversationMarkdown.empty',+ );+ });+});diff --git a/apps/desktop/src/renderer/lib/__tests__/workLouderCodexVoiceGesture.test.ts b/apps/desktop/src/renderer/lib/__tests__/workLouderCodexVoiceGesture.test.tsnew file mode 100644index 0000000000..755c910f8b--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/workLouderCodexVoiceGesture.test.ts@@ -0,0 +1,228 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { VoiceInputState } from '@cindy/voice-input-core';+import { createWorkLouderCodexVoiceGesture } from '../workLouderCodexVoiceGesture';++const press = { phase: 'press' as const };+const release = { phase: 'release' as const };++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ const promise = new Promise<T>((nextResolve) => {+ resolve = nextResolve;+ });+ return { promise, resolve };+}++async function settle(): Promise<void> {+ for (let index = 0; index < 8; index += 1) await Promise.resolve();+}++describe('createWorkLouderCodexVoiceGesture', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps recording after a short click', async () => {+ let state: VoiceInputState = 'idle';+ const start = vi.fn(async () => {+ state = 'listening';+ });+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ gesture.handle(release);+ await settle();++ expect(start).toHaveBeenCalledOnce();+ expect(stop).not.toHaveBeenCalled();+ expect(state).toBe('listening');+ });++ it('stops on the next short click', async () => {+ let state: VoiceInputState = 'listening';+ const start = vi.fn();+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ gesture.handle(release);+ await settle();++ expect(start).not.toHaveBeenCalled();+ expect(stop).toHaveBeenCalledOnce();+ expect(state).toBe('done');+ });++ it('stops when a long press is released', async () => {+ let state: VoiceInputState = 'idle';+ const start = vi.fn(async () => {+ state = 'listening';+ });+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ await vi.advanceTimersByTimeAsync(450);+ gesture.handle(release);+ await settle();++ expect(start).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+ expect(state).toBe('done');+ });++ it('stops after startup resolves when a long press was already released', async () => {+ let state: VoiceInputState = 'idle';+ const startGate = deferred<void>();+ const start = vi.fn(async () => {+ await startGate.promise;+ state = 'listening';+ });+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ await vi.advanceTimersByTimeAsync(450);+ gesture.handle(release);+ await settle();+ expect(stop).not.toHaveBeenCalled();++ startGate.resolve();+ await settle();++ expect(start).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+ expect(state).toBe('done');+ });++ it('does not depend on a React state-ref update after startup resolves', async () => {+ const startGate = deferred<void>();+ const start = vi.fn(async () => startGate.promise);+ const stop = vi.fn();+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => 'idle',+ start,+ stop,+ });++ gesture.handle(press);+ await vi.advanceTimersByTimeAsync(450);+ gesture.handle(release);+ startGate.resolve();+ await settle();++ expect(stop).toHaveBeenCalledOnce();+ });++ it('turns a second click into stop even while the first start is pending', async () => {+ let state: VoiceInputState = 'idle';+ const startGate = deferred<void>();+ const start = vi.fn(async () => {+ await startGate.promise;+ state = 'listening';+ });+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ gesture.handle(release);+ gesture.handle(press);+ gesture.handle(release);+ startGate.resolve();+ await settle();++ expect(stop).toHaveBeenCalledOnce();+ });++ it('ignores duplicate events and clears its timer on dispose', async () => {+ let state: VoiceInputState = 'idle';+ const start = vi.fn(async () => {+ state = 'listening';+ });+ const stop = vi.fn();+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ gesture.handle(press);+ gesture.dispose();+ await vi.advanceTimersByTimeAsync(450);+ gesture.handle(release);+ await settle();++ expect(start).toHaveBeenCalledOnce();+ expect(stop).not.toHaveBeenCalled();+ });++ it('stops a held long press when the owning composer loses focus', async () => {+ let state: VoiceInputState = 'idle';+ const start = vi.fn(async () => {+ state = 'listening';+ });+ const stop = vi.fn(async () => {+ state = 'done';+ });+ const gesture = createWorkLouderCodexVoiceGesture({+ longPressMs: 450,+ getState: () => state,+ start,+ stop,+ });++ gesture.handle(press);+ await vi.advanceTimersByTimeAsync(450);+ await settle();+ gesture.cancelHeldPress();+ await settle();++ expect(start).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+ expect(state).toBe('done');+ });+});diff --git a/apps/desktop/src/renderer/lib/inputDeviceActions.ts b/apps/desktop/src/renderer/lib/inputDeviceActions.tsnew file mode 100644index 0000000000..8ab70f2edd--- /dev/null+++ b/apps/desktop/src/renderer/lib/inputDeviceActions.ts@@ -0,0 +1,36 @@+import type { InputDeviceRendererAction } from '../../shared/inputDevices';++export type InputDeviceActionHandler = (action: InputDeviceRendererAction) => boolean | void;++const handlers = new Set<InputDeviceActionHandler>();+const bridges = new Set<() => void>();++/**+ * Hardware adapters fan into one renderer bus. Newest subscribers run first+ * so the focused task can consume a command before the shell fallback.+ */+export function subscribeInputDeviceAction(handler: InputDeviceActionHandler): () => void {+ handlers.add(handler);+ return () => {+ handlers.delete(handler);+ };+}++export function dispatchInputDeviceAction(action: InputDeviceRendererAction): void {+ for (const listener of [...handlers].reverse()) {+ if (listener(action) === true) break;+ }+}++/** Let an adapter attach its preload channel without owning the subscriber set. */+export function attachInputDeviceActionBridge(connect: () => (() => void) | null | undefined): void {+ if (typeof window === 'undefined') return;+ const unsubscribe = connect();+ if (unsubscribe) bridges.add(unsubscribe);+}++export function __resetInputDeviceActionsForTests(): void {+ handlers.clear();+ for (const unsubscribe of bridges) unsubscribe();+ bridges.clear();+}diff --git a/apps/desktop/src/renderer/lib/workLouderCodexActions.ts b/apps/desktop/src/renderer/lib/workLouderCodexActions.tsnew file mode 100644index 0000000000..aa4049b96a--- /dev/null+++ b/apps/desktop/src/renderer/lib/workLouderCodexActions.ts@@ -0,0 +1,31 @@+import {+ attachInputDeviceActionBridge,+ dispatchInputDeviceAction,+ subscribeInputDeviceAction,+ type InputDeviceActionHandler,+} from './inputDeviceActions';++export type WorkLouderCodexActionHandler = InputDeviceActionHandler;++let bridged = false;++/**+ * Codex Micro still owns the preload channel. The subscriber set is shared+ * so a later keyboard can attach another bridge without a second bus.+ */+export function subscribeWorkLouderCodexAction(handler: InputDeviceActionHandler): () => void {+ ensureCodexMicroBridge();+ return subscribeInputDeviceAction(handler);+}++function ensureCodexMicroBridge(): void {+ if (bridged) return;+ bridged = true;+ attachInputDeviceActionBridge(+ () =>+ window.electronAPI?.workLouderCodex?.onAction((action) => {+ if (action.type === 'keycap') return;+ dispatchInputDeviceAction(action);+ }) ?? null,+ );+}diff --git a/apps/desktop/src/renderer/lib/workLouderCodexTaskActions.ts b/apps/desktop/src/renderer/lib/workLouderCodexTaskActions.tsnew file mode 100644index 0000000000..f162cfef54--- /dev/null+++ b/apps/desktop/src/renderer/lib/workLouderCodexTaskActions.ts@@ -0,0 +1,104 @@+import { ApiError } from '@/lib/httpClient';+import { toast } from '@/lib/toast';+import { forkAtMessage } from '@/lib/sessionService';+import { listMessagesFor } from '@/lib/makerTransport';+import { sessionMessageDisplayText } from '@/lib/sessionMessageText';+import { emitRefresh } from '@/lib/sessionsBus';+import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';+import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';+import { createLogger } from '@/lib/logger';++const log = createLogger('workLouderCodexTaskActions');++export interface WorkLouderCodexTaskActionHost {+ navigate(path: string): void;+ t(key: string): string;+}++/** Fork the current task at its latest assistant reply, then open the new one. */+export async function forkCurrentTaskFromKeyboard(+ sessionId: string,+ host: WorkLouderCodexTaskActionHost,+): Promise<void> {+ try {+ const messages = await listRecentMessages(sessionId);+ const latestAssistant = messages.find(+ (message) => message.role === 'assistant' && message.clientId,+ );+ if (!latestAssistant?.clientId) {+ toast.error(host.t('chat.userMessage.forkErrors.noPriorAssistant'));+ return;+ }+ const newSession = await forkAtMessage(sessionId, latestAssistant.clientId);+ emitRefresh();+ const deviceId = getSessionDeviceId(sessionId);+ if (deviceId) await refreshRemoteDeviceSessions(deviceId);+ host.navigate(`/cc-agent/${newSession.id}`);+ } catch (error) {+ log.warn('fork from keyboard failed', error);+ toast.error(forkErrorMessage(error, host.t));+ }+}++/** Copy the current task as readable Markdown. */+export async function copyCurrentTaskMarkdown(+ sessionId: string,+ host: WorkLouderCodexTaskActionHost,+): Promise<void> {+ try {+ const messages = [...(await listAllMessagesNewestFirst(sessionId))].reverse();+ const lines = messages.flatMap((message) => {+ const text = sessionMessageDisplayText(message);+ if (!text) return [];+ const heading =+ message.role === 'user' ? 'User' : message.role === 'assistant' ? 'Cindy' : null;+ return heading ? [`## ${heading}`, '', text, ''] : [];+ });+ if (lines.length === 0) {+ toast.warning(host.t('settings.shortcuts.workLouderCodex.commands.copyConversationMarkdown.empty'));+ return;+ }+ await navigator.clipboard.writeText(lines.join('\n').trimEnd());+ toast.success(host.t('settings.shortcuts.workLouderCodex.commands.copyConversationMarkdown.copied'));+ } catch (error) {+ log.warn('copy conversation markdown failed', error);+ toast.error(host.t('settings.shortcuts.workLouderCodex.commands.copyConversationMarkdown.failed'));+ }+}++const MESSAGE_PAGE_LIMIT = 100;++/** Newest-first pages from `listMessagesFor`, walking older with `before`. */+async function listRecentMessages(+ sessionId: string,+): Promise<Awaited<ReturnType<typeof listMessagesFor>>> {+ return listMessagesFor(sessionId, { limit: MESSAGE_PAGE_LIMIT });+}++async function listAllMessagesNewestFirst(+ sessionId: string,+): Promise<Awaited<ReturnType<typeof listMessagesFor>>> {+ const pages: Awaited<ReturnType<typeof listMessagesFor>> = [];+ let cursor: { before?: string; beforeTs?: number } = {};+ for (;;) {+ const page = await listMessagesFor(sessionId, { limit: MESSAGE_PAGE_LIMIT, ...cursor });+ pages.push(...page);+ if (page.length < MESSAGE_PAGE_LIMIT) break;+ const oldest = page[page.length - 1];+ if (!oldest?.id) break;+ const nextBeforeTs = Date.parse(oldest.createdAt);+ cursor = {+ before: oldest.id,+ ...(Number.isFinite(nextBeforeTs) ? { beforeTs: nextBeforeTs } : {}),+ };+ }+ return pages;+}++function forkErrorMessage(error: unknown, t: (key: string) => string): string {+ const code = error instanceof ApiError ? error.code : 'UNKNOWN';+ if (code === 'FORK_UNSUPPORTED_HISTORY') return t('chat.userMessage.forkErrors.unsupportedHistory');+ if (code === 'NO_PRIOR_ASSISTANT') return t('chat.userMessage.forkErrors.noPriorAssistant');+ if (code === 'SOURCE_NEVER_RAN') return t('chat.userMessage.forkErrors.sourceNeverRan');+ return t('chat.userMessage.forkErrors.generic');+}diff --git a/apps/desktop/src/renderer/lib/workLouderCodexVoiceGesture.ts b/apps/desktop/src/renderer/lib/workLouderCodexVoiceGesture.tsnew file mode 100644index 0000000000..6220a0678a--- /dev/null+++ b/apps/desktop/src/renderer/lib/workLouderCodexVoiceGesture.ts@@ -0,0 +1,159 @@+import type { VoiceInputState } from '@cindy/voice-input-core';++export type WorkLouderPushToTalkAction = {+ phase: 'press' | 'release';+};++export type WorkLouderCodexVoiceGestureOptions = {+ longPressMs: number;+ getState: () => VoiceInputState;+ start: () => void | Promise<void>;+ stop: () => void | Promise<void>;+};++type Press = {+ stopOnRelease: boolean;+ longPress: boolean;+ timer: ReturnType<typeof setTimeout> | null;+};++const isIdleLike = (state: VoiceInputState): boolean =>+ state === 'idle' || state === 'done' || state === 'error';++/**+ * Bridges a Work Louder press/release pair to the composer's microphone+ * semantics:+ *+ * - a short press starts and stays recording;+ * - a later short press stops;+ * - a long press stops when released.+ *+ * `start` is asynchronous. A long-release (or a click-to-stop made while+ * startup is still in flight) is therefore remembered and applied after the+ * start promise settles. This is intentionally independent from React so the+ * event stream can survive renderer rerenders while a key is held.+ */+export function createWorkLouderCodexVoiceGesture(options: WorkLouderCodexVoiceGestureOptions): {+ handle(action: WorkLouderPushToTalkAction): void;+ cancelHeldPress(): void;+ dispose(): void;+} {+ let press: Press | null = null;+ let startPromise: Promise<void> | null = null;+ let stopAfterStart = false;+ let stopInFlight = false;+ let disposed = false;++ const clearPressTimer = (current: Press | null = press): void => {+ if (current?.timer === null) return;+ if (current?.timer !== undefined) clearTimeout(current.timer);+ if (current) current.timer = null;+ };++ const requestStop = (): void => {+ if (disposed) return;+ if (options.getState() !== 'listening') {+ if (startPromise) stopAfterStart = true;+ return;+ }+ if (stopInFlight) return;+ stopInFlight = true;+ void Promise.resolve()+ .then(() => options.stop())+ .catch(() => undefined)+ .finally(() => {+ stopInFlight = false;+ });+ };++ const requestStopAfterStart = (): void => {+ if (disposed || stopInFlight) return;+ stopInFlight = true;+ void Promise.resolve()+ .then(() => options.stop())+ .catch(() => undefined)+ .finally(() => {+ stopInFlight = false;+ });+ };++ const observeStart = (currentStart: Promise<void>): void => {+ void currentStart+ .then(() => {+ if (disposed || startPromise !== currentStart || !stopAfterStart) return;+ stopAfterStart = false;+ // `useVoiceInput.start()` flips its internal state synchronously, but+ // ChatInput's mirrored state ref updates on the next React effect. Do+ // not wait for that render: `stop()` has its own authoritative ref and+ // already coordinates a stop that lands at the end of startup.+ requestStopAfterStart();+ })+ .catch(() => {+ if (startPromise === currentStart) stopAfterStart = false;+ })+ .finally(() => {+ if (startPromise === currentStart) startPromise = null;+ });+ };++ const handlePress = (): void => {+ if (disposed || press || stopAfterStart) return;++ const state = options.getState();+ if (state === 'listening') {+ press = { stopOnRelease: true, longPress: false, timer: null };+ return;+ }+ if (!isIdleLike(state)) return;++ // A second click can arrive before the first asynchronous start has+ // resolved. Treat it as the composer's click-to-stop gesture rather than+ // starting a second run.+ if (startPromise) {+ press = { stopOnRelease: true, longPress: false, timer: null };+ return;+ }++ const current: Press = { stopOnRelease: false, longPress: false, timer: null };+ current.timer = setTimeout(() => {+ current.timer = null;+ if (press === current) current.longPress = true;+ }, options.longPressMs);+ press = current;++ const currentStart = Promise.resolve().then(() => options.start());+ startPromise = currentStart;+ observeStart(currentStart);+ };++ const handleRelease = (): void => {+ if (disposed || !press) return;+ const current = press;+ clearPressTimer(current);+ press = null;+ if (current.stopOnRelease || current.longPress) requestStop();+ };++ const cancelHeldPress = (): void => {+ if (disposed || !press) return;+ const current = press;+ clearPressTimer(current);+ press = null;+ stopAfterStart = Boolean(startPromise);+ if (current.stopOnRelease || current.longPress || startPromise) requestStop();+ };++ return {+ handle(action) {+ if (action.phase === 'press') handlePress();+ else handleRelease();+ },+ cancelHeldPress,+ dispose() {+ disposed = true;+ clearPressTimer();+ press = null;+ stopAfterStart = false;+ },+ };+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex f5d114d709..70ca1041a2 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -71,6 +71,11 @@ type PendingRemotePrecreatedWorktreeTarget =type RemotePrecreatedWorktreeLedgerSnapshot =import('../shared/remotePrecreatedWorktreeLedger').RemotePrecreatedWorktreeLedgerSnapshot;type RawReleaseNotesPayload = import('../shared/releaseNotesContent').RawReleaseNotes;+type WorkLouderCodexSettingsPatch =+ import('../shared/workLouderCodex').WorkLouderCodexSettingsPatch;+type WorkLouderCodexState = import('../shared/workLouderCodex').WorkLouderCodexState;+type WorkLouderCodexRendererAction =+ import('../shared/workLouderCodex').WorkLouderCodexRendererAction;interface NewMakerWorktreeBranchPreferenceSnapshot {baseRepo: string;@@ -1809,6 +1814,28 @@ interface ElectronAPI {notifyWindowsCloseBehaviorPromptShown: () => void;};+ workLouderCodex: {+ getState: () => Promise<WorkLouderCodexState>;+ setSettings: (patch: WorkLouderCodexSettingsPatch) => Promise<WorkLouderCodexState>;+ resetSettings: () => Promise<WorkLouderCodexState>;+ openInputMonitoringSettings: () => Promise<void>;+ /** Re-check whether the device is still attached; the SDK never says so itself. */+ probe: () => Promise<WorkLouderCodexState>;+ /**+ * Hand the sidebar's task list to the agent keys. Main cannot see tasks on+ * linked machines, nor which machine filter is applied.+ */+ publishTasks: (+ tasks: import('../shared/workLouderCodex').WorkLouderCodexPublishedTask[],+ ) => Promise<void>;+ setLayoutPreviewActive: (active: boolean) => Promise<void>;+ onStateChanged: (callback: (state: WorkLouderCodexState) => void) => () => void;+ onAction: (callback: (action: WorkLouderCodexRendererAction) => void) => () => void;+ onPreviewInput: (+ callback: (input: import('../shared/workLouderCodex').WorkLouderCodexPreviewInput) => void,+ ) => () => void;+ };+// ── 右侧栏独立子窗口(RSB window)──────────────────────────────────────// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期(main: right-sidebar-window/)。rightSidebarWindow: {diff --git a/apps/desktop/src/shared/__tests__/inputDevices.test.ts b/apps/desktop/src/shared/__tests__/inputDevices.test.tsnew file mode 100644index 0000000000..5f28f24d37--- /dev/null+++ b/apps/desktop/src/shared/__tests__/inputDevices.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import {+ INPUT_DEVICE_COMMAND_IDS,+ inputDeviceHasCapability,+ isInputDeviceCommandId,+} from '../inputDevices';+import {+ WORKLOUDER_CODEX_COMMAND_IDS,+ WORKLOUDER_CODEX_DEVICE,+} from '../workLouderCodex';++describe('input device contract', () => {+ it('keeps Codex Micro commands on the shared action list', () => {+ expect(WORKLOUDER_CODEX_COMMAND_IDS).toBe(INPUT_DEVICE_COMMAND_IDS);+ expect(isInputDeviceCommandId('forkTask')).toBe(true);+ expect(isInputDeviceCommandId('not-a-command')).toBe(false);+ });++ it('describes Codex Micro as one adapter with its own capabilities', () => {+ expect(WORKLOUDER_CODEX_DEVICE.id).toBe('worklouder-codex-micro');+ expect(inputDeviceHasCapability(WORKLOUDER_CODEX_DEVICE, 'task-slots')).toBe(true);+ expect(inputDeviceHasCapability(WORKLOUDER_CODEX_DEVICE, 'voice')).toBe(true);+ expect(inputDeviceHasCapability(WORKLOUDER_CODEX_DEVICE, 'lighting')).toBe(true);+ });+});diff --git a/apps/desktop/src/shared/__tests__/workLouderCodexPreview.test.ts b/apps/desktop/src/shared/__tests__/workLouderCodexPreview.test.tsnew file mode 100644index 0000000000..3f6c7488f1--- /dev/null+++ b/apps/desktop/src/shared/__tests__/workLouderCodexPreview.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import {+ WORKLOUDER_CODEX_ENCODER_DETENT_DEG,+ WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+ workLouderCodexStickPreviewOffset,+} from '../workLouderCodex';++describe('workLouderCodexStickPreviewOffset', () => {+ it('follows the hardware circle: 0 right, 0.25 down, 0.5 left, 0.75 up', () => {+ expect(workLouderCodexStickPreviewOffset(0, 1)).toEqual({+ x: WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+ y: 0,+ });+ expect(workLouderCodexStickPreviewOffset(0.25, 1).x).toBeCloseTo(0, 8);+ expect(workLouderCodexStickPreviewOffset(0.25, 1).y).toBeCloseTo(+ WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+ 8,+ );+ expect(workLouderCodexStickPreviewOffset(0.5, 1).x).toBeCloseTo(+ -WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+ 8,+ );+ expect(workLouderCodexStickPreviewOffset(0.5, 1).y).toBeCloseTo(0, 8);+ expect(workLouderCodexStickPreviewOffset(0.75, 1).x).toBeCloseTo(0, 8);+ expect(workLouderCodexStickPreviewOffset(0.75, 1).y).toBeCloseTo(+ -WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+ 8,+ );+ });++ it('scales with how far the stick is pushed', () => {+ expect(workLouderCodexStickPreviewOffset(0, 0.5)).toEqual({+ x: WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX / 2,+ y: 0,+ });+ expect(workLouderCodexStickPreviewOffset(0, 0)).toEqual({ x: 0, y: 0 });+ });++ it('treats a detent as a fixed encoder step', () => {+ expect(WORKLOUDER_CODEX_ENCODER_DETENT_DEG).toBe(18);+ });+});diff --git a/apps/desktop/src/shared/__tests__/workLouderCodexScroll.test.ts b/apps/desktop/src/shared/__tests__/workLouderCodexScroll.test.tsnew file mode 100644index 0000000000..4f831e258e--- /dev/null+++ b/apps/desktop/src/shared/__tests__/workLouderCodexScroll.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import {+ WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE,+ joystickScrollDelta,+ joystickScrollSpeed,+ normalizeJoystickIntensity,+} from '../workLouderCodexScroll';++describe('normalizeJoystickIntensity', () => {+ it('starts from zero at the activation point, not half speed', () => {+ // The stick only registers past the activation distance; without remapping,+ // the lightest usable push would already be halfway up the curve.+ expect(normalizeJoystickIntensity(WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE)).toBe(0);+ expect(normalizeJoystickIntensity(1)).toBe(1);+ });++ it('clamps anything below the activation point or past full travel', () => {+ expect(normalizeJoystickIntensity(0)).toBe(0);+ expect(normalizeJoystickIntensity(0.2)).toBe(0);+ expect(normalizeJoystickIntensity(1.5)).toBe(1);+ expect(normalizeJoystickIntensity(Number.NaN)).toBe(0);+ });+});++describe('joystickScrollSpeed', () => {+ it('is nothing at rest and fastest at full deflection', () => {+ expect(joystickScrollSpeed(0)).toBe(0);+ expect(joystickScrollSpeed(1)).toBeGreaterThan(joystickScrollSpeed(0.5));+ });++ it('keeps most of the travel slow so a light push can place a message', () => {+ // Squared, not linear: half deflection is well under half speed.+ const half = joystickScrollSpeed(0.5);+ const full = joystickScrollSpeed(1);+ expect(half).toBeLessThan(full * 0.4);+ });+});++describe('joystickScrollDelta', () => {+ it('scales with elapsed time so speed holds when frames drop', () => {+ const oneFrame = joystickScrollDelta(1, 16);+ const twoFrames = joystickScrollDelta(1, 32);+ expect(twoFrames).toBeCloseTo(oneFrame * 2, 5);+ });++ it('caps a long gap so a backgrounded tab does not teleport the view', () => {+ const capped = joystickScrollDelta(1, 5_000);+ expect(capped).toBe(joystickScrollDelta(1, 100));+ });++ it('moves nothing without time or pressure', () => {+ expect(joystickScrollDelta(1, 0)).toBe(0);+ expect(joystickScrollDelta(0, 16)).toBe(0);+ expect(joystickScrollDelta(1, Number.NaN)).toBe(0);+ });+});diff --git a/apps/desktop/src/shared/inputDevices.ts b/apps/desktop/src/shared/inputDevices.tsnew file mode 100644index 0000000000..04daa7fa98--- /dev/null+++ b/apps/desktop/src/shared/inputDevices.ts@@ -0,0 +1,97 @@+/** Device-neutral input actions and capability cards for hardware adapters. */++export const INPUT_DEVICE_COMMAND_IDS = [+ 'composer.toggleFastMode',+ 'approval.approve',+ 'approval.decline',+ 'forkTask',+ 'composer.submit',+ 'feedback',+ 'toggleTerminal',+ 'copyConversationMarkdown',+ 'archiveTask',+ 'newTask',+ 'openBrowserTab',+ 'toggleTaskPin',+ 'toggleReviewTab',+ 'composer.addPhotos',+ 'settings',+ 'manageTasks',+ 'composer.increaseReasoningEffort',+ 'composer.decreaseReasoningEffort',+ 'openFolder',+ 'composer.addFiles',+ 'openSkills',+ 'composer.togglePlanMode',+ 'navigateForward',+ 'toggleSidebar',+ 'toggleRightSidebar',+ 'navigateBack',+ 'composer.focus',+ 'conversation.scrollUp',+ 'conversation.scrollDown',+ 'conversation.scrollBottom',+ 'session.selectPrevious',+ 'session.selectNext',+] as const;++export type InputDeviceCommandId = (typeof INPUT_DEVICE_COMMAND_IDS)[number];++export type InputDeviceAction =+ | { type: 'command'; commandId: InputDeviceCommandId }+ | { type: 'task'; sessionId: string }+ | { type: 'skill'; skillId: string; name: string }+ | { type: 'composer-text'; text: string }+ | { type: 'external-url'; url: string };++export type InputDeviceRendererAction =+ | Exclude<InputDeviceAction, { type: 'task' }>+ | { type: 'voice'; phase: 'press' | 'release' }+ | {+ type: 'scroll';+ direction: 'up' | 'down';+ intensity: number;+ }+ | { type: 'scroll-stop' }+ | { type: 'keyboard'; key: 'ArrowUp' | 'ArrowDown' | 'Enter' };++export type InputDeviceCapability =+ | { kind: 'task-slots'; count: number }+ | { kind: 'commands' }+ | { kind: 'voice' }+ | { kind: 'encoder' }+ | { kind: 'stick' }+ | { kind: 'lighting'; model: 'task-slots' | 'global' | 'none' };++export interface InputDeviceDescriptor {+ id: string;+ label: string;+ capabilities: readonly InputDeviceCapability[];+}++export interface InputDevicePublishedTask {+ id: string;+ title: string | null;+ pinnedAt: number | null;+ /** Last time the user sent a message, in unix ms. Null if they never have. */+ userSendAt: number | null;+ /** 0-based order among currently visible sidebar rows. Absent when hidden. */+ sidebarOrder?: number;+ /**+ * False when this row is only a visible projection (for example an archived+ * task in the current sidebar filter) and must not occupy last-sent /+ * priority / custom catalogs.+ */+ catalogEligible?: boolean;+}++export function isInputDeviceCommandId(value: unknown): value is InputDeviceCommandId {+ return typeof value === 'string' && (INPUT_DEVICE_COMMAND_IDS as readonly string[]).includes(value);+}++export function inputDeviceHasCapability(+ device: InputDeviceDescriptor,+ kind: InputDeviceCapability['kind'],+): boolean {+ return device.capabilities.some((capability) => capability.kind === kind);+}diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex d9a23a0dbd..b88823dd53 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -36,6 +36,7 @@ export interface RsbWindowContext {/** main → 子窗口的命令推送(如主窗终端快捷键转发 / detached RSB 内定位文件)。 */export type RsbWindowCommand =| { type: 'open-terminal'; sessionId: string }+ | { type: 'toggle-review-tab'; sessionId: string }| { type: 'open-web-browser'; sessionId: string; url: string }| {type: 'ensure-orca-workers-tab';diff --git a/apps/desktop/src/shared/workLouderCodex.ts b/apps/desktop/src/shared/workLouderCodex.tsnew file mode 100644index 0000000000..f34e7c6845--- /dev/null+++ b/apps/desktop/src/shared/workLouderCodex.ts@@ -0,0 +1,436 @@+/** Work Louder Codex Micro settings, device state, and IPC contracts. */++import {+ INPUT_DEVICE_COMMAND_IDS,+ isInputDeviceCommandId,+ type InputDeviceAction,+ type InputDeviceCommandId,+ type InputDeviceDescriptor,+ type InputDevicePublishedTask,+ type InputDeviceRendererAction,+} from './inputDevices';++export const WORKLOUDER_CODEX_DEVICE_ID = 'worklouder-codex-micro';++export const WORKLOUDER_CODEX_DEVICE: InputDeviceDescriptor = {+ id: WORKLOUDER_CODEX_DEVICE_ID,+ label: 'Work Louder Codex Micro',+ capabilities: [+ { kind: 'task-slots', count: 6 },+ { kind: 'commands' },+ { kind: 'voice' },+ { kind: 'encoder' },+ { kind: 'stick' },+ { kind: 'lighting', model: 'task-slots' },+ ],+};++export const WORKLOUDER_CODEX_GET_STATE_CHANNEL = 'worklouder-codex:get-state';+export const WORKLOUDER_CODEX_SET_SETTINGS_CHANNEL = 'worklouder-codex:set-settings';+export const WORKLOUDER_CODEX_RESET_SETTINGS_CHANNEL = 'worklouder-codex:reset-settings';+export const WORKLOUDER_CODEX_OPEN_INPUT_MONITORING_CHANNEL =+ 'worklouder-codex:open-input-monitoring-settings';+export const WORKLOUDER_CODEX_PROBE_CHANNEL = 'worklouder-codex:probe';+export const WORKLOUDER_CODEX_PUBLISH_TASKS_CHANNEL = 'worklouder-codex:publish-tasks';+export const WORKLOUDER_CODEX_SET_LAYOUT_PREVIEW_CHANNEL = 'worklouder-codex:set-layout-preview';++/** One sidebar task, as the renderer reports it for the agent keys. */+export type WorkLouderCodexPublishedTask = InputDevicePublishedTask;+export const WORKLOUDER_CODEX_STATE_CHANGED_CHANNEL = 'worklouder-codex:state-changed';+export const WORKLOUDER_CODEX_ACTION_CHANNEL = 'worklouder-codex:action';+export const WORKLOUDER_CODEX_PREVIEW_INPUT_CHANNEL = 'worklouder-codex:preview-input';++export const WORKLOUDER_CODEX_AGENT_SLOT_COUNT = 6;++export const WORKLOUDER_CODEX_AUTO_DIM_OPTIONS = [+ 'off',+ '30-seconds',+ '1-minute',+ '3-minutes',+ '10-minutes',+ '30-minutes',+ '1-hour',+] as const;++export const WORKLOUDER_CODEX_AGENT_SOURCES = ['sidebar', 'last-sent', 'priority', 'custom'] as const;++export const WORKLOUDER_CODEX_COMMAND_SLOTS = [+ 'ACT06',+ 'ACT07',+ 'ACT08',+ 'ACT09',+ 'ACT10',+ 'ACT11',+ 'ACT10_ACT11',+ 'ACT12',+] as const;++export const WORKLOUDER_CODEX_ANALOG_DIRECTIONS = ['up', 'right', 'down', 'left'] as const;+export const WORKLOUDER_CODEX_ENCODER_ACTIONS = ['left', 'right', 'click', 'longPress'] as const;+export const WORKLOUDER_CODEX_ENCODER_MODES = [+ 'session-switch',+ 'composer-navigation',+ 'reasoning',+ 'conversation-scroll',+ 'custom',+] as const;++export const WORKLOUDER_CODEX_COMMAND_IDS = INPUT_DEVICE_COMMAND_IDS;++export const WORKLOUDER_CODEX_KEYCAP_IDS = [+ 'FAST',+ 'APPR',+ 'REJ',+ 'SPLIT',+ 'MIC',+ 'MIC1',+ 'CODEX',+ 'BUG',+ 'OAI',+ 'TERM',+ 'DWN',+ 'DEL',+ 'NEW',+ 'NAV',+ 'MAGIC',+ 'DIFF',+ 'PLAY',+ 'GIT',+ 'BRCH',+ 'BRANCH',+ 'MRG',+ 'PR',+ 'PAINT',+ 'LAB',+ 'PARTY',+ 'TIME',+ 'MIND+',+ 'MIND-',+ 'EMPT1',+ 'EMPT2',+ 'EMPT3',+ 'EMPT4',+ 'EMPT5',+ 'SETUP',+ 'FOLD',+ 'UPL',+ 'APPS',+ 'YOLO',+ 'YEET',+] as const;++export type WorkLouderCodexAutoDim = (typeof WORKLOUDER_CODEX_AUTO_DIM_OPTIONS)[number];+export type WorkLouderCodexAgentSource = (typeof WORKLOUDER_CODEX_AGENT_SOURCES)[number];+export type WorkLouderCodexCommandSlot = (typeof WORKLOUDER_CODEX_COMMAND_SLOTS)[number];+export type WorkLouderCodexPreviewPart =+ | WorkLouderCodexCommandSlot+ | `AG0${0 | 1 | 2 | 3 | 4 | 5}`+ | 'analog'+ | 'encoder';++export interface WorkLouderCodexPreviewInput {+ part: WorkLouderCodexPreviewPart;+ pressed: boolean;+ /** Encoder detents: +1 is firmware ENC_CW, −1 is ENC_CC. Visual rotation flips this. */+ turn?: number;+ /** Stick angle on the hardware circle, 0–1. 0 is right, 0.25 down, 0.5 left, 0.75 up. */+ angle?: number;+ /** Stick deflection, 0–1. */+ distance?: number;+}++/** One detent on the drawn encoder. The hardware reports ticks, not a continuous angle. */+export const WORKLOUDER_CODEX_ENCODER_DETENT_DEG = 18;++/** How far the drawn stick cap travels at full deflection, in pixels. */+export const WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX = 10;++/**+ * Pixel offset for the settings-page stick cap.+ *+ * The hardware circle is clockwise from the right, which matches screen+ * coordinates: x grows right, y grows down.+ */+export function workLouderCodexStickPreviewOffset(+ angle: number,+ distance: number,+ radius: number = WORKLOUDER_CODEX_STICK_PREVIEW_TRAVEL_PX,+): { x: number; y: number } {+ if (!Number.isFinite(angle) || !Number.isFinite(distance) || !Number.isFinite(radius)) {+ return { x: 0, y: 0 };+ }+ const travel = Math.max(0, Math.min(1, distance));+ const theta = angle * Math.PI * 2;+ return {+ x: snapPreviewPx(Math.cos(theta) * travel * radius),+ y: snapPreviewPx(Math.sin(theta) * travel * radius),+ };+}++function snapPreviewPx(value: number): number {+ return Math.round(value * 100) / 100;+}+export type WorkLouderCodexAnalogDirection = (typeof WORKLOUDER_CODEX_ANALOG_DIRECTIONS)[number];+export type WorkLouderCodexEncoderAction = (typeof WORKLOUDER_CODEX_ENCODER_ACTIONS)[number];+export type WorkLouderCodexEncoderMode = (typeof WORKLOUDER_CODEX_ENCODER_MODES)[number];+export type WorkLouderCodexCommandId = InputDeviceCommandId;+export type WorkLouderCodexKeycapId = (typeof WORKLOUDER_CODEX_KEYCAP_IDS)[number];++export type WorkLouderCodexAction =+ | InputDeviceAction+ | { type: 'keycap'; keycapId: WorkLouderCodexKeycapId };++export interface WorkLouderCodexKeyAssignment {+ keycapId: WorkLouderCodexKeycapId;+ /** Null means use the physical keycap's built-in Cindy action. */+ action: WorkLouderCodexAction | null;+}++export interface WorkLouderCodexLayout {+ version: 1;+ slots: Record<WorkLouderCodexCommandSlot, WorkLouderCodexKeyAssignment>;+ analogStick: Record<WorkLouderCodexAnalogDirection, WorkLouderCodexAction | null>;+ encoder: Record<WorkLouderCodexEncoderAction, WorkLouderCodexAction | null>;+ encoderMode: WorkLouderCodexEncoderMode;+ separateMicrophoneKeys: boolean;+}++export interface WorkLouderCodexSettings {+ /** Overall lighting intensity, in percent. Zero keeps HID input active with LEDs off. */+ lightingBrightness: number;+ lightingAutoDim: WorkLouderCodexAutoDim;+ agentSource: WorkLouderCodexAgentSource;+ customAgentKeys: Array<WorkLouderCodexAction | null>;+ /** When false, a single press switches tasks and a double press brings Cindy forward. */+ singleTapAgentKeys: boolean;+ layout: WorkLouderCodexLayout;+}++export type WorkLouderCodexSettingsPatch = Partial<WorkLouderCodexSettings>;++export type WorkLouderCodexConnectionStatus =+ 'connecting' | 'connected' | 'not-detected' | 'error' | 'unavailable';++export type WorkLouderCodexConnectionReason =+ 'connection-timeout' | 'connection-failed' | 'permission-required' | 'sdk-unavailable' | null;++export interface WorkLouderCodexDeviceState {+ deviceType: 'codex-micro' | 'creator-micro-2' | null;+ isUsbConnection: boolean | null;+ firmwareVersion: string | null;+ batteryPercentage: number | null;+ isCharging: boolean | null;+ inputMonitoringPermission: 'granted' | 'denied' | 'unknown' | 'not-required';+}++export interface WorkLouderCodexTaskOption {+ id: string;+ title: string | null;+ pinned: boolean;+}++export interface WorkLouderCodexAgentSlotState {+ slot: number;+ sessionId: string | null;+ title: string | null;+ action: WorkLouderCodexAction | null;+}++export interface WorkLouderCodexState {+ connectionStatus: WorkLouderCodexConnectionStatus;+ connectionReason: WorkLouderCodexConnectionReason;+ device: WorkLouderCodexDeviceState;+ settings: WorkLouderCodexSettings;+ agentSlots: WorkLouderCodexAgentSlotState[];+ taskOptions: WorkLouderCodexTaskOption[];+ agentSlotCount: typeof WORKLOUDER_CODEX_AGENT_SLOT_COUNT;+}++export type WorkLouderCodexRendererAction =+ | InputDeviceRendererAction+ | { type: 'keycap'; keycapId: WorkLouderCodexKeycapId };++/** Built-in Cindy behavior printed on each official Work Louder keycap. */+export const WORKLOUDER_CODEX_KEYCAP_ACTIONS: Readonly<+ Partial<Record<WorkLouderCodexKeycapId, WorkLouderCodexAction>>+> = {+ FAST: { type: 'command', commandId: 'composer.toggleFastMode' },+ APPR: { type: 'command', commandId: 'approval.approve' },+ REJ: { type: 'command', commandId: 'approval.decline' },+ SPLIT: { type: 'command', commandId: 'forkTask' },+ CODEX: { type: 'command', commandId: 'composer.submit' },+ BUG: { type: 'command', commandId: 'feedback' },+ OAI: { type: 'external-url', url: 'https://developers.openai.com' },+ TERM: { type: 'command', commandId: 'toggleTerminal' },+ DWN: { type: 'command', commandId: 'copyConversationMarkdown' },+ DEL: { type: 'command', commandId: 'archiveTask' },+ NEW: { type: 'command', commandId: 'newTask' },+ NAV: { type: 'command', commandId: 'openBrowserTab' },+ MAGIC: { type: 'command', commandId: 'toggleTaskPin' },+ DIFF: { type: 'command', commandId: 'toggleReviewTab' },+ PAINT: { type: 'command', commandId: 'composer.addPhotos' },+ LAB: { type: 'command', commandId: 'settings' },+ TIME: { type: 'command', commandId: 'manageTasks' },+ 'MIND+': { type: 'command', commandId: 'composer.increaseReasoningEffort' },+ 'MIND-': { type: 'command', commandId: 'composer.decreaseReasoningEffort' },+ SETUP: { type: 'command', commandId: 'settings' },+ FOLD: { type: 'command', commandId: 'openFolder' },+ UPL: { type: 'command', commandId: 'composer.addFiles' },+ APPS: { type: 'command', commandId: 'openSkills' },+ YOLO: { type: 'composer-text', text: ':yolo:' },+ YEET: { type: 'composer-text', text: ':yeet:' },+};++export const WORKLOUDER_CODEX_DEFAULT_LAYOUT: WorkLouderCodexLayout = {+ version: 1,+ slots: {+ ACT06: { keycapId: 'FAST', action: null },+ ACT07: { keycapId: 'APPR', action: null },+ ACT08: { keycapId: 'REJ', action: null },+ ACT09: { keycapId: 'SPLIT', action: null },+ ACT10: { keycapId: 'MIC1', action: null },+ ACT11: { keycapId: 'EMPT1', action: null },+ ACT10_ACT11: { keycapId: 'MIC', action: null },+ ACT12: { keycapId: 'CODEX', action: null },+ },+ // The stick maps to the two axes of the screen: up/down moves through the+ // conversation, left/right opens and closes the panel on that side.+ analogStick: {+ up: { type: 'command', commandId: 'conversation.scrollUp' },+ right: { type: 'command', commandId: 'toggleRightSidebar' },+ down: { type: 'command', commandId: 'conversation.scrollDown' },+ left: { type: 'command', commandId: 'toggleSidebar' },+ },+ encoder: { left: null, right: null, click: null, longPress: null },+ encoderMode: 'session-switch',+ separateMicrophoneKeys: false,+};++export const WORKLOUDER_CODEX_DEFAULT_SETTINGS: WorkLouderCodexSettings = {+ lightingBrightness: 100,+ lightingAutoDim: '3-minutes',+ agentSource: 'sidebar',+ customAgentKeys: Array.from({ length: WORKLOUDER_CODEX_AGENT_SLOT_COUNT }, () => null),+ singleTapAgentKeys: false,+ layout: WORKLOUDER_CODEX_DEFAULT_LAYOUT,+};++export const WORKLOUDER_CODEX_EMPTY_DEVICE_STATE: WorkLouderCodexDeviceState = {+ deviceType: null,+ isUsbConnection: null,+ firmwareVersion: null,+ batteryPercentage: null,+ isCharging: null,+ inputMonitoringPermission: 'unknown',+};++export function cloneWorkLouderCodexLayout(layout: WorkLouderCodexLayout): WorkLouderCodexLayout {+ return {+ ...layout,+ slots: Object.fromEntries(+ WORKLOUDER_CODEX_COMMAND_SLOTS.map((slot) => [+ slot,+ {+ ...layout.slots[slot],+ action: cloneWorkLouderCodexAction(layout.slots[slot].action),+ },+ ]),+ ) as WorkLouderCodexLayout['slots'],+ analogStick: Object.fromEntries(+ WORKLOUDER_CODEX_ANALOG_DIRECTIONS.map((direction) => [+ direction,+ cloneWorkLouderCodexAction(layout.analogStick[direction]),+ ]),+ ) as WorkLouderCodexLayout['analogStick'],+ encoder: Object.fromEntries(+ WORKLOUDER_CODEX_ENCODER_ACTIONS.map((action) => [+ action,+ cloneWorkLouderCodexAction(layout.encoder[action]),+ ]),+ ) as WorkLouderCodexLayout['encoder'],+ };+}++export function cloneWorkLouderCodexSettings(+ settings: WorkLouderCodexSettings,+): WorkLouderCodexSettings {+ return {+ ...settings,+ customAgentKeys: settings.customAgentKeys.map(cloneWorkLouderCodexAction),+ layout: cloneWorkLouderCodexLayout(settings.layout),+ };+}++export function createWorkLouderCodexDefaultSettings(): WorkLouderCodexSettings {+ return cloneWorkLouderCodexSettings(WORKLOUDER_CODEX_DEFAULT_SETTINGS);+}++export function isWorkLouderCodexAutoDim(value: unknown): value is WorkLouderCodexAutoDim {+ return isStringOption(value, WORKLOUDER_CODEX_AUTO_DIM_OPTIONS);+}++export function isWorkLouderCodexAgentSource(value: unknown): value is WorkLouderCodexAgentSource {+ return isStringOption(value, WORKLOUDER_CODEX_AGENT_SOURCES);+}++/**+ * Saved values from older builds: `recent` was the visible sidebar, `pinned`+ * was a separate pinned-only list. Both now mean sidebar order.+ */+export function normalizeWorkLouderCodexAgentSource(value: unknown): WorkLouderCodexAgentSource {+ if (value === 'recent' || value === 'pinned') return 'sidebar';+ return isWorkLouderCodexAgentSource(value) ? value : WORKLOUDER_CODEX_DEFAULT_SETTINGS.agentSource;+}++export function isWorkLouderCodexCommandId(value: unknown): value is WorkLouderCodexCommandId {+ return isInputDeviceCommandId(value);+}++export function isWorkLouderCodexKeycapId(value: unknown): value is WorkLouderCodexKeycapId {+ return isStringOption(value, WORKLOUDER_CODEX_KEYCAP_IDS);+}++export function isWorkLouderCodexMicrophoneKeycap(+ keycapId: WorkLouderCodexKeycapId | null | undefined,+): boolean {+ return keycapId === 'MIC' || keycapId === 'MIC1';+}++export function isWorkLouderCodexDoubleKeycap(+ keycapId: WorkLouderCodexKeycapId | null | undefined,+): boolean {+ return keycapId === 'MIC' || keycapId === 'EMPT5';+}++export function isWorkLouderCodexEncoderMode(value: unknown): value is WorkLouderCodexEncoderMode {+ return isStringOption(value, WORKLOUDER_CODEX_ENCODER_MODES);+}++export function workLouderCodexAutoDimMs(value: WorkLouderCodexAutoDim): number | null {+ switch (value) {+ case 'off':+ return null;+ case '30-seconds':+ return 30_000;+ case '1-minute':+ return 60_000;+ case '3-minutes':+ return 180_000;+ case '10-minutes':+ return 600_000;+ case '30-minutes':+ return 1_800_000;+ case '1-hour':+ return 3_600_000;+ }+}++function isStringOption<T extends string>(value: unknown, options: readonly T[]): value is T {+ return typeof value === 'string' && (options as readonly string[]).includes(value);+}++function cloneWorkLouderCodexAction(+ action: WorkLouderCodexAction | null,+): WorkLouderCodexAction | null {+ return action ? { ...action } : null;+}diff --git a/apps/desktop/src/shared/workLouderCodexScroll.ts b/apps/desktop/src/shared/workLouderCodexScroll.tsnew file mode 100644index 0000000000..9b0d138dad--- /dev/null+++ b/apps/desktop/src/shared/workLouderCodexScroll.ts@@ -0,0 +1,55 @@+/**+ * Speed curve for held-stick scrolling.+ *+ * Lives in shared/ because both halves need it: the main process normalises the+ * raw stick distance into an intensity, and the renderer turns that intensity+ * into pixels per frame.+ */++/** Below this the stick is treated as centred; matches the direction threshold. */+export const WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE = 0.5;++/** Pixels per second at the lightest push that still registers. */+const MIN_SCROLL_SPEED = 90;+/** Pixels per second with the stick pushed all the way. */+const MAX_SCROLL_SPEED = 2600;++/**+ * Map raw stick distance onto 0–1 across the usable travel.+ *+ * The stick only registers past the activation point, so without this the+ * lightest possible push would already start at half speed.+ */+export function normalizeJoystickIntensity(distance: number): number {+ if (!Number.isFinite(distance)) return 0;+ const usable =+ (distance - WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE) /+ (1 - WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE);+ return Math.max(0, Math.min(1, usable));+}++/**+ * Scroll speed in pixels per second for a given intensity.+ *+ * Squared rather than linear: most of the travel stays slow enough to place a+ * message precisely, and full deflection is what gets you across a long+ * conversation quickly.+ */+export function joystickScrollSpeed(intensity: number): number {+ if (!Number.isFinite(intensity) || intensity <= 0) return 0;+ const clamped = Math.min(1, intensity);+ return MIN_SCROLL_SPEED + (MAX_SCROLL_SPEED - MIN_SCROLL_SPEED) * clamped * clamped;+}++/**+ * How far to scroll this frame.+ *+ * Driven by the real time since the last frame so the speed stays the same+ * whether the renderer is hitting 120fps or dropping frames.+ */+export function joystickScrollDelta(intensity: number, elapsedMs: number): number {+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0) return 0;+ // A long gap (tab was backgrounded) must not teleport the view.+ const cappedMs = Math.min(elapsedMs, 100);+ return (joystickScrollSpeed(intensity) * cappedMs) / 1000;+}diff --git a/scripts/hardcoded-color-exemptions.json b/scripts/hardcoded-color-exemptions.jsonindex 6dfae4d8c5..071b6d0ff7 100644--- a/scripts/hardcoded-color-exemptions.json+++ b/scripts/hardcoded-color-exemptions.json@@ -223,5 +223,15 @@"glob": "apps/desktop/native/agent-island/macos-agent-island-helper.swift","reason": "原生 helper 注释里引用的角色素材固有色 hex(便于与设计素材对照);渲染值本身是 Color(red:green:blue:),不经过 renderer token 体系","owner": "agent-island"+ },+ {+ "glob": "apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx",+ "reason": "Codex Micro 设置页复刻实体键盘的固有色(透白任务帽/深灰命令帽/摇杆座),不是界面语义色;走 surface token 会在 dark mode 反相",+ "owner": "worklouder-codex"+ },+ {+ "glob": "apps/desktop/src/main/worklouder-codex/protocol.ts",+ "reason": "Codex Micro 灯效协议注释对照品牌红(#DF0C27/#A61629);运行色走数字通道,不是 UI 硬编码",+ "owner": "worklouder-codex"}]