Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 添加 Xbox 手柄支持 (#3287)

Dashd57e78695dbb
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 4fdab7ecd6..fa865e6ce7 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -891,6 +891,7 @@ const MACOS_VOICE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
const MACOS_AGENT_ISLAND_HELPER_DEPLOYMENT_TARGET = 'macos14.0';
const MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET = 'macos13.0';
const MACOS_SESSION_DRAG_RELEASE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
+const MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET = 'macos11.0';
function swiftTargetTriple(cpuArch: 'arm64' | 'x86_64', deploymentTarget: string): string {
return `${cpuArch}-apple-${deploymentTarget}`;
@@ -996,6 +997,26 @@ function buildSwiftHelperForForgeArch(
}
}
+function buildMacXboxGamepadHelper(platform: ForgePlatform, arch: ForgeArch): void {
+ if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
+ const src = path.join(__dirname, 'native', 'xbox-gamepad', 'macos-xbox-gamepad-helper.swift');
+ const destDir = path.join(__dirname, 'resources', 'tools', 'xbox-gamepad');
+ const dest = path.join(destDir, 'cindy-macos-xbox-gamepad-helper');
+ if (!fs.existsSync(src)) {
+ throw new Error(`[forge] Xbox gamepad helper source missing at ${src}`);
+ }
+ fs.mkdirSync(destDir, { recursive: true });
+ buildSwiftHelperForForgeArch(
+ src,
+ dest,
+ arch,
+ MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET,
+ ['-framework', 'GameController', '-framework', 'IOKit'],
+ 'Xbox gamepad helper',
+ );
+ fs.chmodSync(dest, 0o755);
+}
+
function buildMacVoiceInputTextInsertionHelper(platform: ForgePlatform, arch: ForgeArch): void {
if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
const src = path.join(__dirname, 'native', 'voice-input', 'macos-text-insertion-helper.swift');
@@ -1463,6 +1484,7 @@ const config: ForgeConfig = {
buildWindowsVoiceInputFunctionKeyListener(targetPlatform);
buildMacIOSSimulatorHelper(platform, arch);
buildMacVoiceInputTextInsertionHelper(platform, arch);
+ buildMacXboxGamepadHelper(platform, arch);
buildMacVoiceInputModifierShortcutListener(platform, arch);
buildMacAgentIslandHelper(platform, arch);
buildMacComputerPermissionGuideHelper(platform, arch);
diff --git a/apps/desktop/native/xbox-gamepad/macos-xbox-gamepad-helper.swift b/apps/desktop/native/xbox-gamepad/macos-xbox-gamepad-helper.swift
new file mode 100644
index 0000000000..4eb0df62bf
--- /dev/null
+++ b/apps/desktop/native/xbox-gamepad/macos-xbox-gamepad-helper.swift
@@ -0,0 +1,248 @@
+import Foundation
+import GameController
+import IOKit.hid
+
+struct Options {
+ var command = "listen"
+}
+
+func parseOptions() -> Options {
+ var options = Options()
+ var iterator = CommandLine.arguments.dropFirst().makeIterator()
+ while let arg = iterator.next() {
+ if arg == "--command", let value = iterator.next() {
+ options.command = value
+ }
+ }
+ return options
+}
+
+func emit(_ payload: [String: Any]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]),
+ let text = String(data: data, encoding: .utf8) else { return }
+ fputs(text + "\n", stdout)
+ fflush(stdout)
+}
+
+func isXboxController(_ controller: GCController) -> Bool {
+ if controller.extendedGamepad is GCXboxGamepad { return true }
+ let vendor = controller.vendorName?.lowercased() ?? ""
+ let category = controller.productCategory.lowercased()
+ let haystack = vendor + " " + category
+ // Wired Xbox pads often advertise USB product "Controller" and vendor Microsoft.
+ return haystack.contains("xbox")
+ || haystack.contains("microsoft")
+ || vendor == "controller"
+}
+
+func homePressed(_ controller: GCController) -> Bool {
+ controller.physicalInputProfile.buttons[GCInputButtonHome]?.isPressed ?? false
+}
+
+func batteryStateName(_ state: GCDeviceBattery.State) -> String {
+ switch state {
+ case .charging: return "charging"
+ case .full: return "full"
+ case .discharging: return "discharging"
+ default: return "unknown"
+ }
+}
+
+/// Best-effort USB vs Bluetooth from IOHID. GameController does not expose transport.
+func controllerTransport(for controller: GCController) -> String {
+ let controllerTokens = transportMatchTokens(controller.vendorName, controller.productCategory)
+ if controllerTokens.isEmpty { return "unknown" }
+
+ let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))
+ IOHIDManagerSetDeviceMatching(manager, [kIOHIDVendorIDKey as String: 0x45e] as CFDictionary)
+ IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone))
+ defer { IOHIDManagerClose(manager, IOOptionBits(kIOHIDOptionsTypeNone)) }
+ guard let devices = IOHIDManagerCopyDevices(manager) as? Set<IOHIDDevice> else { return "unknown" }
+
+ var matched = Set<String>()
+ for device in devices {
+ let deviceTokens = transportMatchTokens(
+ IOHIDDeviceGetProperty(device, kIOHIDProductKey as CFString) as? String,
+ IOHIDDeviceGetProperty(device, kIOHIDManufacturerKey as CFString) as? String
+ )
+ guard deviceTokens.contains(where: { controllerTokens.contains($0) }) else { continue }
+ if let transport = hidTransportName(device) {
+ matched.insert(transport)
+ }
+ }
+ if matched.count == 1 { return matched.first! }
+ return "unknown"
+}
+
+func transportMatchTokens(_ values: String?...) -> Set<String> {
+ var tokens = Set<String>()
+ for value in values {
+ let lowered = (value ?? "").lowercased()
+ for part in lowered.split(whereSeparator: { !$0.isLetter && !$0.isNumber }) {
+ let token = String(part)
+ if token.count >= 3 { tokens.insert(token) }
+ }
+ }
+ // Generic Microsoft HID tokens would match keyboards, mice, and dongles.
+ tokens.subtract(["usb", "hid", "device", "microsoft", "controller"])
+ return tokens
+}
+
+func hidTransportName(_ device: IOHIDDevice) -> String? {
+ let transport = (IOHIDDeviceGetProperty(device, kIOHIDTransportKey as CFString) as? String ?? "")
+ .lowercased()
+ if transport.contains("usb") { return "usb" }
+ if transport.contains("blue") || transport.contains("wireless") { return "bluetooth" }
+ return nil
+}
+
+func presencePayload(from controller: GCController) -> [String: Any] {
+ var payload: [String: Any] = [
+ "kind": "presence",
+ "present": true,
+ "name": controller.vendorName ?? controller.productCategory,
+ "category": controller.productCategory,
+ "transport": controllerTransport(for: controller),
+ "batteryState": "unknown",
+ ]
+ if let battery = controller.battery {
+ payload["batteryState"] = batteryStateName(battery.batteryState)
+ let level = battery.batteryLevel
+ if level >= 0 && level <= 1 {
+ payload["batteryPercentage"] = Int((Double(level) * 100).rounded())
+ }
+ }
+ return payload
+}
+
+final class XboxGamepadReporter {
+ private var observed: GCController?
+ /// nil until the first refresh, so an empty device list still gets logged once.
+ private var lastSeenSummary: String?
+ private var lastPresenceSignature = ""
+
+ func start() {
+ if #available(macOS 11.3, *) {
+ GCController.shouldMonitorBackgroundEvents = true
+ }
+ NotificationCenter.default.addObserver(
+ forName: .GCControllerDidConnect,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ self?.refresh()
+ }
+ NotificationCenter.default.addObserver(
+ forName: .GCControllerDidDisconnect,
+ object: nil,
+ queue: .main
+ ) { [weak self] _ in
+ self?.refresh()
+ }
+ refresh()
+ }
+
+ func refresh() {
+ let all = GCController.controllers()
+ let summary = all
+ .map { controller in
+ let vendor = controller.vendorName ?? "?"
+ let category = controller.productCategory
+ let xboxPad = controller.extendedGamepad is GCXboxGamepad
+ return "\(vendor)/\(category)/xboxPad=\(xboxPad)"
+ }
+ .joined(separator: "; ")
+ if summary != lastSeenSummary {
+ lastSeenSummary = summary
+ emit([
+ "kind": "log",
+ "level": "info",
+ "message": summary.isEmpty ? "no GameController devices" : "controllers: \(summary)",
+ ])
+ }
+ let next = all.first(where: isXboxController)
+ if next == nil {
+ observed = nil
+ lastPresenceSignature = ""
+ emit(["kind": "presence", "present": false])
+ return
+ }
+ if observed !== next {
+ observed = next
+ attach(next!)
+ }
+ emitPresence(from: next!)
+ emitFrame(from: next!)
+ }
+
+ private func attach(_ controller: GCController) {
+ guard let pad = controller.extendedGamepad else { return }
+ pad.valueChangedHandler = { [weak self] _, _ in
+ self?.emitFrame(from: controller)
+ }
+ }
+
+ private func emitPresence(from controller: GCController) {
+ let payload = presencePayload(from: controller)
+ let signature = String(describing: payload)
+ if signature == lastPresenceSignature { return }
+ lastPresenceSignature = signature
+ emit(payload)
+ }
+
+ private func emitFrame(from controller: GCController) {
+ guard let pad = controller.extendedGamepad else { return }
+ let buttons: [String: Any] = [
+ "a": pad.buttonA.isPressed,
+ "b": pad.buttonB.isPressed,
+ "x": pad.buttonX.isPressed,
+ "y": pad.buttonY.isPressed,
+ "lb": pad.leftShoulder.isPressed,
+ "rb": pad.rightShoulder.isPressed,
+ "lt": pad.leftTrigger.isPressed,
+ "rt": pad.rightTrigger.isPressed,
+ "view": pad.buttonOptions?.isPressed ?? false,
+ "menu": pad.buttonMenu.isPressed,
+ "xbox": homePressed(controller),
+ "ls": pad.leftThumbstickButton?.isPressed ?? false,
+ "rs": pad.rightThumbstickButton?.isPressed ?? false,
+ "dpadUp": pad.dpad.up.isPressed,
+ "dpadDown": pad.dpad.down.isPressed,
+ "dpadLeft": pad.dpad.left.isPressed,
+ "dpadRight": pad.dpad.right.isPressed,
+ ]
+ let axes: [String: Any] = [
+ "lx": Double(pad.leftThumbstick.xAxis.value),
+ "ly": Double(pad.leftThumbstick.yAxis.value),
+ "rx": Double(pad.rightThumbstick.xAxis.value),
+ "ry": Double(pad.rightThumbstick.yAxis.value),
+ ]
+ emit([
+ "kind": "frame",
+ "buttons": buttons,
+ "axes": axes,
+ "ltAnalog": Double(pad.leftTrigger.value),
+ "rtAnalog": Double(pad.rightTrigger.value),
+ ])
+ }
+}
+
+let reporter = XboxGamepadReporter()
+reporter.start()
+
+DispatchQueue.global(qos: .utility).async {
+ while let line = readLine() {
+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed == "stop" {
+ exit(0)
+ }
+ if trimmed == "probe" {
+ DispatchQueue.main.async {
+ reporter.refresh()
+ }
+ }
+ }
+ exit(0)
+}
+
+RunLoop.main.run()
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 69c0101056..3274ce8302 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -4418,6 +4418,16 @@ const registerIpcHandlers = () => {
return win.isFullScreen() || win.isSimpleFullScreen();
});
+ ipcMain.handle('toggle-fullscreen', (event): boolean => {
+ assertTrustedAppRendererEvent(event);
+ const win = BrowserWindow.fromWebContents(event.sender) ?? getWindow();
+ if (!win) return false;
+ const next = !(win.isFullScreen() || win.isSimpleFullScreen());
+ if (win.isSimpleFullScreen()) win.setSimpleFullScreen(false);
+ win.setFullScreen(next);
+ return next;
+ });
+
// Find-in-page (F-FIP-1): renderer overlay drives Chromium's native page search.
// start: returns the requestId Chromium assigns; renderer correlates with the
// result event sent from createWindow's `found-in-page` listener.
diff --git a/apps/desktop/src/main/input-devices/__tests__/previewLease.test.ts b/apps/desktop/src/main/input-devices/__tests__/previewLease.test.ts
new file mode 100644
index 0000000000..78db627abc
--- /dev/null
+++ b/apps/desktop/src/main/input-devices/__tests__/previewLease.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLayoutPreviewLease, layoutPreviewOwnerFromEvent } from '../previewLease.js';
+
+function fakeOwner(id: number) {
+ const listeners = new Map<string, Array<() => void>>();
+ return {
+ id,
+ once(event: 'destroyed' | 'render-process-gone', listener: () => void) {
+ const bucket = listeners.get(event) ?? [];
+ bucket.push(listener);
+ listeners.set(event, bucket);
+ },
+ emit(event: 'destroyed' | 'render-process-gone') {
+ for (const listener of listeners.get(event) ?? []) listener();
+ },
+ };
+}
+
+describe('createLayoutPreviewLease', () => {
+ it('releases preview when the owning renderer disappears', () => {
+ const setActive = vi.fn();
+ const lease = createLayoutPreviewLease(setActive);
+ const owner = fakeOwner(1);
+
+ lease.setActive(true, owner);
+ expect(setActive).toHaveBeenCalledWith(true);
+ setActive.mockClear();
+
+ owner.emit('destroyed');
+ expect(setActive).toHaveBeenCalledWith(false);
+ });
+
+ it('ignores a stale owner after another renderer takes the lease', () => {
+ const setActive = vi.fn();
+ const lease = createLayoutPreviewLease(setActive);
+ const first = fakeOwner(1);
+ const second = fakeOwner(2);
+
+ lease.setActive(true, first);
+ lease.setActive(true, second);
+ setActive.mockClear();
+
+ first.emit('destroyed');
+ expect(setActive).not.toHaveBeenCalled();
+
+ second.emit('render-process-gone');
+ expect(setActive).toHaveBeenCalledWith(false);
+ });
+
+ it('extracts a trusted IPC sender and ignores empty events', () => {
+ const owner = fakeOwner(7);
+ expect(layoutPreviewOwnerFromEvent({ sender: owner })).toEqual(
+ expect.objectContaining({ id: 7 }),
+ );
+ expect(layoutPreviewOwnerFromEvent({})).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/input-devices/index.ts b/apps/desktop/src/main/input-devices/index.ts
index 691e6baf9b..7eadd27c38 100644
--- a/apps/desktop/src/main/input-devices/index.ts
+++ b/apps/desktop/src/main/input-devices/index.ts
@@ -1,10 +1,12 @@
import { registerWorkLouderCodexInputDevice } from '../worklouder-codex/index.js';
+import { registerXboxGamepadInputDevice } from '../xbox-gamepad/index.js';
let started = false;
/** Register first-party adapters. Each adapter owns its HID, lights, and settings. */
export function registerBuiltInInputDevices(): void {
registerWorkLouderCodexInputDevice();
+ registerXboxGamepadInputDevice();
}
export function startInputDeviceRuntime(): void {
diff --git a/apps/desktop/src/main/input-devices/previewLease.ts b/apps/desktop/src/main/input-devices/previewLease.ts
new file mode 100644
index 0000000000..bedba25e6b
--- /dev/null
+++ b/apps/desktop/src/main/input-devices/previewLease.ts
@@ -0,0 +1,39 @@
+export interface LayoutPreviewOwner {
+ id: number;
+ once(event: 'destroyed' | 'render-process-gone', listener: () => void): void;
+}
+
+export function createLayoutPreviewLease(setActive: (active: boolean) => void) {
+ let ownerId: number | null = null;
+
+ const releaseIfOwner = (id: number): void => {
+ if (ownerId !== id) return;
+ ownerId = null;
+ setActive(false);
+ };
+
+ return {
+ setActive(active: boolean, owner: LayoutPreviewOwner | null): void {
+ if (active) {
+ if (!owner) return;
+ if (ownerId === owner.id) return;
+ ownerId = owner.id;
+ setActive(true);
+ const release = (): void => releaseIfOwner(owner.id);
+ owner.once('destroyed', release);
+ owner.once('render-process-gone', release);
+ return;
+ }
+ if (ownerId !== null && owner && owner.id !== ownerId) return;
+ ownerId = null;
+ setActive(false);
+ },
+ };
+}
+
+export function layoutPreviewOwnerFromEvent(event: unknown): LayoutPreviewOwner | null {
+ if (!event || typeof event !== 'object' || !('sender' in event)) return null;
+ const sender = (event as { sender?: Partial<LayoutPreviewOwner> }).sender;
+ if (!sender || typeof sender.id !== 'number' || typeof sender.once !== 'function') return null;
+ return sender as LayoutPreviewOwner;
+}
diff --git a/apps/desktop/src/main/maker-host/override-settings-file.ts b/apps/desktop/src/main/maker-host/override-settings-file.ts
index 35fb043eb7..4c0e50e2e1 100644
--- a/apps/desktop/src/main/maker-host/override-settings-file.ts
+++ b/apps/desktop/src/main/maker-host/override-settings-file.ts
@@ -49,7 +49,7 @@ interface CachedState<T> extends OverrideSettingsState<T> {
*/
export function createOverrideSettingsFile<T>(options: {
filePath: () => string;
- defaults: T;
+ defaults: T | (() => T);
normalize: (raw: unknown) => T;
mergeOverrides?: (args: {
patch: Partial<T>;
@@ -75,7 +75,8 @@ export function createOverrideSettingsFile<T>(options: {
/** 缓存装载时文件的 mtimeMs;null = 装载时文件不存在(默认态)。 */
let cachedFileMtimeMs: number | null = null;
- const defaults = (): T => clone(options.defaults);
+ const defaults = (): T =>
+ clone(typeof options.defaults === 'function' ? (options.defaults as () => T)() : options.defaults);
/** 当前文件 mtimeMs;文件不存在/不可 stat 时 null(与"无文件"同态)。 */
function statFileMtimeMs(): number | null {
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts
index 6f65b3e625..65748aa48f 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/settingsIpc.test.ts
@@ -241,8 +241,8 @@ describe('Work Louder Codex settings IPC business body', () => {
ipc.setLayoutPreviewActive(EVENT, true);
ipc.setLayoutPreviewActive(EVENT, false);
- expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(1, true);
- expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(2, false);
+ expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(1, true, EVENT);
+ expect(setLayoutPreviewActive).toHaveBeenNthCalledWith(2, false, EVENT);
expect(writeSettings).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/worklouder-codex/index.ts b/apps/desktop/src/main/worklouder-codex/index.ts
index b119ea76df..a007ef38b0 100644
--- a/apps/desktop/src/main/worklouder-codex/index.ts
+++ b/apps/desktop/src/main/worklouder-codex/index.ts
@@ -5,6 +5,7 @@ import { BrowserWindow, ipcMain, shell, utilityProcess } from 'electron';
import { createLogger } from '../logger.js';
import { getDeepLinkMainWindow, openMainWindowSession, sendMainWindowMessage } from '../deepLink.js';
+import { createLayoutPreviewLease, layoutPreviewOwnerFromEvent } from '../input-devices/previewLease.js';
import { registerInputDevice } from '../input-devices/registry.js';
import { isSecondaryAppWindow } from '../secondary-windows.js';
import {
@@ -165,6 +166,10 @@ export const workLouderCodexLightingController = new WorkLouderCodexLightingCont
},
);
+const layoutPreviewLease = createLayoutPreviewLease((active) => {
+ workLouderCodexLightingController.setLayoutPreviewActive(active);
+});
+
let settingsIpcRegistered = false;
let inputDeviceRegistered = false;
@@ -223,8 +228,8 @@ export function registerWorkLouderCodexSettingsIpc(): void {
rendererTaskCatalogScope = scope;
void workLouderCodexLightingController.refreshTaskSlots().catch(() => undefined);
},
- setLayoutPreviewActive: (active) => {
- workLouderCodexLightingController.setLayoutPreviewActive(active);
+ setLayoutPreviewActive: (active, event) => {
+ layoutPreviewLease.setActive(active, layoutPreviewOwnerFromEvent(event));
},
});
diff --git a/apps/desktop/src/main/worklouder-codex/settingsIpc.ts b/apps/desktop/src/main/worklouder-codex/settingsIpc.ts
index 60cc7f2c7c..33d782862e 100644
--- a/apps/desktop/src/main/worklouder-codex/settingsIpc.ts
+++ b/apps/desktop/src/main/worklouder-codex/settingsIpc.ts
@@ -40,7 +40,7 @@ export interface WorkLouderCodexSettingsIpcDeps {
openInputMonitoringSettings(): Promise<void>;
probeDevice(): void;
publishTasks(tasks: readonly WorkLouderCodexPublishedTask[]): void;
- setLayoutPreviewActive(active: boolean): void;
+ setLayoutPreviewActive(active: boolean, event: unknown): void;
}
function parseSettingsPatch(value: unknown): WorkLouderCodexSettingsPatch {
@@ -335,7 +335,7 @@ export function createWorkLouderCodexSettingsIpc(deps: WorkLouderCodexSettingsIp
if (typeof value !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'layout preview flag must be a boolean');
}
- deps.setLayoutPreviewActive(value);
+ deps.setLayoutPreviewActive(value, event);
},
};
}
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/bindings.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/bindings.test.ts
new file mode 100644
index 0000000000..2bfacb5d5c
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/bindings.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ cloneXboxGamepadLayout,
+ createXboxGamepadDefaultLayout,
+} from '../../../shared/xboxGamepad.js';
+import {
+ digitalTriggerPressed,
+ reduceXboxGamepadFrame,
+ xboxGamepadHoldReleases,
+ XBOX_GAMEPAD_EMPTY_FRAME,
+ type XboxGamepadFrame,
+} from '../bindings.js';
+
+function press(...ids: Array<keyof XboxGamepadFrame['buttons']>): XboxGamepadFrame {
+ const buttons = { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons };
+ for (const id of ids) buttons[id] = true;
+ return { ...XBOX_GAMEPAD_EMPTY_FRAME, buttons };
+}
+
+function axes(partial: Partial<XboxGamepadFrame['axes']>): XboxGamepadFrame {
+ return {
+ ...XBOX_GAMEPAD_EMPTY_FRAME,
+ axes: { ...XBOX_GAMEPAD_EMPTY_FRAME.axes, ...partial },
+ };
+}
+
+describe('reduceXboxGamepadFrame', () => {
+ const layout = createXboxGamepadDefaultLayout();
+
+ it('does not fire button edges on the first frame', () => {
+ expect(
+ reduceXboxGamepadFrame(null, { ...press('a', 'lt'), axes: { ...XBOX_GAMEPAD_EMPTY_FRAME.axes, ry: 1 } }, layout),
+ ).toEqual([{ type: 'scroll', direction: 'up', intensity: expect.any(Number) }]);
+ });
+
+ it('maps face and bumper edges to Cindy commands', () => {
+ const idle = XBOX_GAMEPAD_EMPTY_FRAME;
+ expect(reduceXboxGamepadFrame(idle, press('a'), layout)).toEqual([
+ { type: 'command', commandId: 'composer.submit' },
+ ]);
+ expect(reduceXboxGamepadFrame(idle, press('y'), layout)).toEqual([
+ { type: 'command', commandId: 'newTask' },
+ ]);
+ expect(reduceXboxGamepadFrame(idle, press('lb'), layout)).toEqual([
+ { type: 'command', commandId: 'composer.decreaseReasoningEffort' },
+ ]);
+ expect(reduceXboxGamepadFrame(idle, press('rb'), layout)).toEqual([
+ { type: 'command', commandId: 'composer.increaseReasoningEffort' },
+ ]);
+ expect(reduceXboxGamepadFrame(idle, press('menu'), layout)).toEqual([
+ { type: 'command', commandId: 'settings' },
+ ]);
+ });
+
+ it('starts and stops voice from the bound trigger', () => {
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, press('lt'), layout)).toEqual([
+ { type: 'voice', phase: 'press' },
+ ]);
+ expect(reduceXboxGamepadFrame(press('lt'), XBOX_GAMEPAD_EMPTY_FRAME, layout)).toEqual([
+ { type: 'voice', phase: 'release' },
+ ]);
+ });
+
+ it('scrolls with a conversation-scroll stick and stops at center', () => {
+ const started = reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ ry: 1 }), layout);
+ expect(started[0]).toMatchObject({ type: 'scroll', direction: 'up' });
+ expect(reduceXboxGamepadFrame(axes({ ry: 1 }), XBOX_GAMEPAD_EMPTY_FRAME, layout)).toEqual([
+ { type: 'scroll-stop' },
+ ]);
+ });
+
+ it('ignores horizontal-only conversation-scroll input', () => {
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ rx: 1 }), layout)).toEqual([]);
+ });
+
+ it('uses remapped button bindings', () => {
+ const remapped = cloneXboxGamepadLayout(layout);
+ remapped.buttons.a = { type: 'command', commandId: 'newTask' };
+ remapped.buttons.b = { type: 'command', commandId: 'composer.submit' };
+ remapped.buttons.lt = { type: 'command', commandId: 'settings' };
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, press('a'), remapped)).toEqual([
+ { type: 'command', commandId: 'newTask' },
+ ]);
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, press('b'), remapped)).toEqual([
+ { type: 'command', commandId: 'composer.submit' },
+ ]);
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, press('lt'), remapped)).toEqual([
+ { type: 'command', commandId: 'settings' },
+ ]);
+ });
+
+ it('fires custom stick directions on entering a quadrant', () => {
+ const remapped = cloneXboxGamepadLayout(layout);
+ remapped.sticks.right.mode = 'custom';
+ remapped.sticks.right.directions.up = { type: 'command', commandId: 'toggleSidebar' };
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ ry: 1 }), remapped)).toEqual([
+ { type: 'command', commandId: 'toggleSidebar' },
+ ]);
+ expect(reduceXboxGamepadFrame(axes({ ry: 1 }), axes({ ry: 1 }), remapped)).toEqual([]);
+ });
+
+ it('does not fire unmapped buttons', () => {
+ const remapped = cloneXboxGamepadLayout(layout);
+ remapped.buttons.x = null;
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, press('x'), remapped)).toEqual([]);
+ });
+
+ it('selects tasks from the left stick and opens sidebars from its sides', () => {
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ ly: 1 }), layout)).toEqual([
+ { type: 'command', commandId: 'session.selectPrevious' },
+ ]);
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ ly: -1 }), layout)).toEqual([
+ { type: 'command', commandId: 'session.selectNext' },
+ ]);
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ lx: -1 }), layout)).toEqual([
+ { type: 'command', commandId: 'toggleSidebar' },
+ ]);
+ expect(reduceXboxGamepadFrame(XBOX_GAMEPAD_EMPTY_FRAME, axes({ lx: 1 }), layout)).toEqual([
+ { type: 'command', commandId: 'toggleRightSidebar' },
+ ]);
+ });
+});
+
+describe('digitalTriggerPressed', () => {
+ it('uses hysteresis so a noisy trigger does not chatter', () => {
+ expect(digitalTriggerPressed(false, 0.5)).toBe(false);
+ expect(digitalTriggerPressed(false, 0.55)).toBe(true);
+ expect(digitalTriggerPressed(true, 0.45)).toBe(true);
+ expect(digitalTriggerPressed(true, 0.4)).toBe(false);
+ });
+});
+
+describe('xboxGamepadHoldReleases', () => {
+ it('releases voice and scroll that were still held', () => {
+ const layout = createXboxGamepadDefaultLayout();
+ expect(
+ xboxGamepadHoldReleases({ ...press('lt'), axes: { ...XBOX_GAMEPAD_EMPTY_FRAME.axes, ry: -1 } }, layout),
+ ).toEqual([
+ { type: 'voice', phase: 'release' },
+ { type: 'scroll-stop' },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts
new file mode 100644
index 0000000000..73f4ac862b
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/controller.test.ts
@@ -0,0 +1,175 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createXboxGamepadDefaultSettings } from '../../../shared/xboxGamepad.js';
+import { XBOX_GAMEPAD_EMPTY_FRAME } from '../bindings.js';
+import { XboxGamepadController } from '../controller.js';
+
+function enabledSettings() {
+ return { ...createXboxGamepadDefaultSettings(), deviceEnabled: true };
+}
+
+describe('XboxGamepadController', () => {
+ it('ignores input until the adapter is enabled and Cindy is frontmost', () => {
+ const dispatch = vi.fn();
+ const preview = vi.fn();
+ const frontmost = { value: false };
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => frontmost.value,
+ dispatch,
+ preview,
+ });
+
+ controller.handleHostMessage({
+ kind: 'presence',
+ present: true,
+ name: 'Xbox Wireless Controller',
+ });
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, a: true },
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(preview).not.toHaveBeenCalled();
+
+ controller.applySettings(enabledSettings());
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, a: true },
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ expect(dispatch).not.toHaveBeenCalled();
+
+ frontmost.value = true;
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: XBOX_GAMEPAD_EMPTY_FRAME.buttons,
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, a: true },
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'command', commandId: 'composer.submit' });
+ });
+
+ it('releases holds when Cindy leaves the foreground', () => {
+ const dispatch = vi.fn();
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => true,
+ dispatch,
+ });
+ controller.applySettings(enabledSettings());
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: XBOX_GAMEPAD_EMPTY_FRAME.buttons,
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, lt: true },
+ axes: { lx: 0, ly: 0, rx: 0, ry: 1 },
+ triggers: { lt: 1, rt: 0 },
+ });
+ dispatch.mockClear();
+
+ controller.setCindyFrontmost(false);
+ expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'release' });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'scroll-stop' });
+ });
+
+ it('reports a helper failure as an error, not as a missing controller', () => {
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => true,
+ dispatch: vi.fn(),
+ });
+ controller.applySettings(enabledSettings());
+
+ controller.handleHostMessage({ kind: 'host-error', message: 'swiftc failed' });
+ expect(controller.getState().connectionStatus).toBe('error');
+ expect(controller.getState().devicePresent).toBe(false);
+
+ // A later presence report means the helper recovered.
+ controller.handleHostMessage({ kind: 'presence', present: true, name: 'Xbox' });
+ expect(controller.getState().connectionStatus).toBe('connected');
+ });
+
+ it('surfaces transport and battery from the helper presence report', () => {
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => true,
+ dispatch: vi.fn(),
+ });
+ controller.handleHostMessage({
+ kind: 'presence',
+ present: true,
+ name: 'Xbox Wireless Controller',
+ category: 'Xbox One',
+ transport: 'bluetooth',
+ batteryPercentage: 64,
+ batteryState: 'discharging',
+ });
+ expect(controller.getState().device).toEqual({
+ name: 'Xbox Wireless Controller',
+ category: 'Xbox One',
+ transport: 'bluetooth',
+ batteryPercentage: 64,
+ batteryState: 'discharging',
+ });
+ controller.handleHostMessage({ kind: 'presence', present: false });
+ expect(controller.getState().device.transport).toBe('unknown');
+ expect(controller.getState().device.batteryPercentage).toBeNull();
+ });
+ it('previews input without dispatching while the layout editor is open', () => {
+ const dispatch = vi.fn();
+ const preview = vi.fn();
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => true,
+ dispatch,
+ preview,
+ });
+ controller.applySettings(enabledSettings());
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: XBOX_GAMEPAD_EMPTY_FRAME.buttons,
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ controller.setLayoutPreviewActive(true);
+ dispatch.mockClear();
+ preview.mockClear();
+
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, a: true },
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(preview).toHaveBeenCalledWith(
+ expect.objectContaining({ buttons: expect.objectContaining({ a: true }) }),
+ );
+ });
+
+ it('does not broadcast preview frames until the layout editor holds the lease', () => {
+ const preview = vi.fn();
+ const controller = new XboxGamepadController({
+ isCindyFrontmost: () => true,
+ dispatch: vi.fn(),
+ preview,
+ });
+ controller.applySettings(enabledSettings());
+ controller.handleHostMessage({
+ kind: 'frame',
+ buttons: { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons, a: true },
+ axes: XBOX_GAMEPAD_EMPTY_FRAME.axes,
+ triggers: XBOX_GAMEPAD_EMPTY_FRAME.triggers,
+ });
+ expect(preview).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts
new file mode 100644
index 0000000000..1f06d19b13
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts
@@ -0,0 +1,262 @@
+import type { ChildProcessWithoutNullStreams } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import { readFileSync } from 'node:fs';
+import { PassThrough } from 'node:stream';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: true,
+ getAppPath: () => '/app',
+ getPath: () => '/tmp',
+ },
+}));
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+import { createXboxGamepadHost } from '../host.js';
+
+function fakeChild(): ChildProcessWithoutNullStreams {
+ const child = new EventEmitter() as EventEmitter & {
+ stdin: PassThrough;
+ stdout: PassThrough;
+ stderr: PassThrough;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.stdin = new PassThrough();
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.kill = vi.fn();
+ return child as unknown as ChildProcessWithoutNullStreams;
+}
+
+async function flush(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('XboxGamepadHost', () => {
+ it('turns a spawn error into host-error instead of crashing the process', async () => {
+ const onMessage = vi.fn();
+ const child = fakeChild();
+ const spawnHelper = vi.fn(() => child);
+ const host = createXboxGamepadHost(onMessage, {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ child.emit('error', new Error('EACCES'));
+
+ expect(onMessage).toHaveBeenCalledWith({ kind: 'host-error', message: 'EACCES' });
+ expect(spawnHelper).toHaveBeenCalledTimes(1);
+ await flush();
+ expect(spawnHelper).toHaveBeenCalledTimes(1);
+ host.stop();
+ });
+
+ it('does not respawn immediately after an unexpected exit', async () => {
+ vi.useFakeTimers();
+ const onMessage = vi.fn();
+ const child = fakeChild();
+ const spawnHelper = vi.fn(() => child);
+ const host = createXboxGamepadHost(onMessage, {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ child.emit('exit', 1, null);
+ await flush();
+
+ expect(onMessage).toHaveBeenCalledWith({
+ kind: 'host-error',
+ message: 'Xbox gamepad helper exited unexpectedly (1)',
+ });
+ expect(spawnHelper).toHaveBeenCalledTimes(1);
+ host.stop();
+ vi.useRealTimers();
+ });
+
+ it('restarts a still-wanted helper after a bounded delay', async () => {
+ vi.useFakeTimers();
+ const first = fakeChild();
+ const second = fakeChild();
+ const spawnHelper = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ first.emit('exit', 1, null);
+ await flush();
+ expect(spawnHelper).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ await flush();
+ expect(spawnHelper).toHaveBeenCalledTimes(2);
+ host.stop();
+ vi.useRealTimers();
+ });
+
+ it('stops automatic restarts after three crashes', async () => {
+ vi.useFakeTimers();
+ const spawnHelper = vi.fn(() => fakeChild());
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ for (const delay of [1_000, 2_000, 4_000]) {
+ const current = spawnHelper.mock.results.at(-1)?.value as ReturnType<typeof fakeChild>;
+ current.emit('exit', 1, null);
+ await flush();
+ await vi.advanceTimersByTimeAsync(delay);
+ await flush();
+ }
+ expect(spawnHelper).toHaveBeenCalledTimes(4);
+ const last = spawnHelper.mock.results.at(-1)?.value as ReturnType<typeof fakeChild>;
+ last.emit('exit', 1, null);
+ await flush();
+ await vi.advanceTimersByTimeAsync(8_000);
+ await flush();
+ expect(spawnHelper).toHaveBeenCalledTimes(4);
+ host.stop();
+ vi.useRealTimers();
+ });
+
+ it('does not reset the restart budget when a helper emits presence then dies', async () => {
+ vi.useFakeTimers();
+ const spawnHelper = vi.fn(() => fakeChild());
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ for (const delay of [1_000, 2_000, 4_000]) {
+ const current = spawnHelper.mock.results.at(-1)?.value as ReturnType<typeof fakeChild>;
+ (current.stdout as PassThrough).write(`${JSON.stringify({ kind: 'presence', present: false })}\n`);
+ current.emit('exit', 1, null);
+ await flush();
+ await vi.advanceTimersByTimeAsync(delay);
+ await flush();
+ }
+ expect(spawnHelper).toHaveBeenCalledTimes(4);
+ const last = spawnHelper.mock.results.at(-1)?.value as ReturnType<typeof fakeChild>;
+ (last.stdout as PassThrough).write(`${JSON.stringify({ kind: 'presence', present: false })}\n`);
+ last.emit('exit', 1, null);
+ await flush();
+ host.probe();
+ await vi.advanceTimersByTimeAsync(8_000);
+ await flush();
+ expect(spawnHelper).toHaveBeenCalledTimes(4);
+ host.stop();
+ vi.useRealTimers();
+ });
+
+ it('lets an explicit probe retry after a crash', async () => {
+ vi.useFakeTimers();
+ const first = fakeChild();
+ const second = fakeChild();
+ const spawnHelper = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ first.emit('exit', 1, null);
+ await flush();
+ host.probe();
+ await flush();
+
+ expect(spawnHelper).toHaveBeenCalledTimes(2);
+ host.stop();
+ vi.useRealTimers();
+ });
+
+ it('swallows helper stdin write errors instead of crashing', async () => {
+ const child = fakeChild();
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper: () => child,
+ });
+
+ host.start();
+ await flush();
+ child.stdin.destroy();
+ expect(() => host.probe()).not.toThrow();
+ host.stop();
+ });
+
+ it('does not spawn after stop wins the resolve race', async () => {
+ let finishResolve: ((path: string) => void) | undefined;
+ const spawnHelper = vi.fn(() => fakeChild());
+ const host = createXboxGamepadHost(vi.fn(), {
+ resolveHelperPath: () =>
+ new Promise((resolve) => {
+ finishResolve = resolve;
+ }),
+ spawnHelper,
+ });
+
+ host.start();
+ await flush();
+ host.stop();
+ finishResolve?.('/helper');
+ await flush();
+
+ expect(spawnHelper).not.toHaveBeenCalled();
+ });
+
+ it('does not report host-error when the helper is stopped on purpose', async () => {
+ const onMessage = vi.fn();
+ const child = fakeChild();
+ const host = createXboxGamepadHost(onMessage, {
+ resolveHelperPath: async () => '/helper',
+ spawnHelper: () => child,
+ });
+
+ host.start();
+ await flush();
+ host.stop();
+ child.emit('exit', 0, null);
+ await flush();
+
+ expect(onMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('Xbox gamepad helper packaging contract', () => {
+ it('matches HID transport to the current controller instead of any Microsoft USB device', () => {
+ const source = readFileSync(
+ new URL('../../../../native/xbox-gamepad/macos-xbox-gamepad-helper.swift', import.meta.url),
+ 'utf8',
+ );
+ expect(source).toContain('func controllerTransport(for controller: GCController)');
+ expect(source).not.toContain('func microsoftControllerTransport()');
+ expect(source).not.toContain('if sawUsb { return "usb" }');
+ });
+
+ it('compiles the helper for macOS 11 so GameController Xbox APIs are available', () => {
+ const source = readFileSync(new URL('../../../../forge.config.ts', import.meta.url), 'utf8');
+ expect(source).toContain("MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET = 'macos11.0'");
+ expect(source).toContain('MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET');
+ });
+});
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/layoutOverride.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/layoutOverride.test.ts
new file mode 100644
index 0000000000..f7c5aaf250
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/layoutOverride.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ cloneXboxGamepadLayout,
+ createXboxGamepadDefaultLayout,
+} from '../../../shared/xboxGamepad.js';
+import { xboxGamepadLayoutOverrides } from '../layoutOverride.js';
+
+describe('xboxGamepadLayoutOverrides', () => {
+ it('persists only the remapped control so later defaults still apply', () => {
+ const defaults = createXboxGamepadDefaultLayout();
+ const layout = cloneXboxGamepadLayout(defaults);
+ layout.buttons.a = { type: 'command', commandId: 'newTask' };
+
+ expect(xboxGamepadLayoutOverrides(layout, defaults)).toEqual({
+ version: 1,
+ buttons: { a: { type: 'command', commandId: 'newTask' } },
+ sticks: {},
+ });
+ });
+
+ it('persists an explicit unbind as null instead of omitting the key', () => {
+ const defaults = createXboxGamepadDefaultLayout();
+ const layout = cloneXboxGamepadLayout(defaults);
+ layout.buttons.x = null;
+
+ expect(xboxGamepadLayoutOverrides(layout, defaults)?.buttons).toEqual({ x: null });
+ });
+
+ it('stores nothing when the layout still matches the live defaults', () => {
+ const defaults = createXboxGamepadDefaultLayout();
+ expect(xboxGamepadLayoutOverrides(cloneXboxGamepadLayout(defaults), defaults)).toBeNull();
+ });
+
+ it('persists only the changed stick mode or direction', () => {
+ const defaults = createXboxGamepadDefaultLayout();
+ const layout = cloneXboxGamepadLayout(defaults);
+ layout.sticks.right.mode = 'custom';
+ layout.sticks.right.directions.up = { type: 'command', commandId: 'newTask' };
+
+ expect(xboxGamepadLayoutOverrides(layout, defaults)?.sticks).toEqual({
+ right: {
+ mode: 'custom',
+ directions: { up: { type: 'command', commandId: 'newTask' } },
+ },
+ });
+ });
+});
diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/settingsIpc.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/settingsIpc.test.ts
new file mode 100644
index 0000000000..17691ef64a
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/settingsIpc.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createXboxGamepadDefaultSettings } from '../../../shared/xboxGamepad.js';
+import { createXboxGamepadSettingsIpc } from '../settingsIpc.js';
+
+describe('Xbox gamepad settings IPC', () => {
+ it('enables the adapter through a trusted sender', () => {
+ let settings = createXboxGamepadDefaultSettings();
+ const applySettings = vi.fn();
+ const handlers = createXboxGamepadSettingsIpc({
+ assertTrustedSender: vi.fn(),
+ getState: () => ({
+ connectionStatus: 'disabled',
+ devicePresent: true,
+ deviceName: 'Xbox Wireless Controller',
+ device: {
+ name: 'Xbox Wireless Controller',
+ category: 'Xbox One',
+ transport: 'unknown',
+ batteryPercentage: null,
+ batteryState: 'unknown',
+ },
+ settings,
+ }),
+ writeSettings: (patch) => {
+ settings = { ...settings, ...patch, layout: patch.layout ?? settings.layout };
+ return settings;
+ },
+ resetSettings: () => {
+ settings = createXboxGamepadDefaultSettings();
+ return settings;
+ },
+ applySettings,
+ probeDevice: vi.fn(),
+ setLayoutPreviewActive: vi.fn(),
+ });
+
+ const next = handlers.set({}, { deviceEnabled: true });
+ expect(next.settings.deviceEnabled).toBe(true);
+ expect(applySettings).toHaveBeenCalledWith(expect.objectContaining({ deviceEnabled: true }));
+ });
+
+ it('accepts a remapped layout', () => {
+ let settings = createXboxGamepadDefaultSettings();
+ const handlers = createXboxGamepadSettingsIpc({
+ assertTrustedSender: vi.fn(),
+ getState: () => ({
+ connectionStatus: 'disabled',
+ devicePresent: true,
+ deviceName: 'Xbox Wireless Controller',
+ device: {
+ name: 'Xbox Wireless Controller',
+ category: 'Xbox One',
+ transport: 'unknown',
+ batteryPercentage: null,
+ batteryState: 'unknown',
+ },
+ settings,
+ }),
+ writeSettings: (patch) => {
+ settings = { ...settings, ...patch, layout: patch.layout ?? settings.layout };
+ return settings;
+ },
+ resetSettings: () => settings,
+ applySettings: vi.fn(),
+ probeDevice: vi.fn(),
+ setLayoutPreviewActive: vi.fn(),
+ });
+ const layout = createXboxGamepadDefaultSettings().layout;
+ layout.buttons.a = { type: 'command', commandId: 'newTask' };
+ const next = handlers.set({}, { layout });
+ expect(next.settings.layout.buttons.a).toEqual({ type: 'command', commandId: 'newTask' });
+ });
+
+ it('rejects unknown settings keys', () => {
+ const handlers = createXboxGamepadSettingsIpc({
+ assertTrustedSender: vi.fn(),
+ getState: vi.fn(),
+ writeSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ applySettings: vi.fn(),
+ probeDevice: vi.fn(),
+ setLayoutPreviewActive: vi.fn(),
+ });
+ expect(() => handlers.set({}, { rumble: true })).toThrow('[INVALID_PARAMS]');
+ });
+
+ it('forwards the renderer event when toggling layout preview', () => {
+ const setLayoutPreviewActive = vi.fn();
+ const event = { sender: { id: 9 } };
+ const handlers = createXboxGamepadSettingsIpc({
+ assertTrustedSender: vi.fn(),
+ getState: vi.fn(),
+ writeSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ applySettings: vi.fn(),
+ probeDevice: vi.fn(),
+ setLayoutPreviewActive,
+ });
+
+ handlers.setLayoutPreviewActive(event, true);
+ expect(setLayoutPreviewActive).toHaveBeenCalledWith(true, event);
+ });
+});
diff --git a/apps/desktop/src/main/xbox-gamepad/bindings.ts b/apps/desktop/src/main/xbox-gamepad/bindings.ts
new file mode 100644
index 0000000000..221af24000
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/bindings.ts
@@ -0,0 +1,189 @@
+import type { InputDeviceRendererAction } from '../../shared/inputDevices.js';
+import {
+ normalizeJoystickIntensity,
+ WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE,
+} from '../../shared/workLouderCodexScroll.js';
+import {
+ XBOX_GAMEPAD_BUTTON_IDS,
+ XBOX_GAMEPAD_STICK_IDS,
+ type XboxGamepadBinding,
+ type XboxGamepadButtonId,
+ type XboxGamepadLayout,
+ type XboxGamepadStickDirection,
+ type XboxGamepadStickId,
+} from '../../shared/xboxGamepad.js';
+
+export type XboxGamepadButtons = Record<XboxGamepadButtonId, boolean>;
+
+export interface XboxGamepadAxes {
+ lx: number;
+ ly: number;
+ rx: number;
+ ry: number;
+}
+
+export interface XboxGamepadTriggers {
+ lt: number;
+ rt: number;
+}
+
+export interface XboxGamepadFrame {
+ buttons: XboxGamepadButtons;
+ axes: XboxGamepadAxes;
+ triggers: XboxGamepadTriggers;
+}
+
+const EMPTY_BUTTONS = Object.fromEntries(XBOX_GAMEPAD_BUTTON_IDS.map((id) => [id, false])) as XboxGamepadButtons;
+
+export const XBOX_GAMEPAD_EMPTY_FRAME: XboxGamepadFrame = {
+ buttons: { ...EMPTY_BUTTONS },
+ axes: { lx: 0, ly: 0, rx: 0, ry: 0 },
+ triggers: { lt: 0, rt: 0 },
+};
+
+const TRIGGER_PRESS = 0.55;
+const TRIGGER_RELEASE = 0.4;
+
+export function digitalTriggerPressed(previous: boolean, value: number): boolean {
+ if (!Number.isFinite(value)) return previous;
+ if (previous) return value > TRIGGER_RELEASE;
+ return value >= TRIGGER_PRESS;
+}
+
+/**
+ * Turns one gamepad snapshot into Cindy hardware actions using the saved layout.
+ *
+ * The first frame after listen starts never fires button edges, so enabling
+ * the adapter mid-hold cannot submit or start voice by accident.
+ */
+export function reduceXboxGamepadFrame(
+ previous: XboxGamepadFrame | null,
+ next: XboxGamepadFrame,
+ layout: XboxGamepadLayout,
+): InputDeviceRendererAction[] {
+ const actions: InputDeviceRendererAction[] = [];
+ if (previous) {
+ for (const id of XBOX_GAMEPAD_BUTTON_IDS) {
+ const binding = layout.buttons[id];
+ if (!binding || binding.type === 'voice') continue;
+ if (pressed(previous.buttons[id], next.buttons[id])) {
+ const action = actionFromBinding(binding);
+ if (action) actions.push(action);
+ }
+ }
+ const wasVoice = voiceHeld(previous, layout);
+ const isVoice = voiceHeld(next, layout);
+ if (wasVoice !== isVoice) {
+ actions.push({ type: 'voice', phase: isVoice ? 'press' : 'release' });
+ }
+ for (const stick of XBOX_GAMEPAD_STICK_IDS) {
+ if (layout.sticks[stick].mode !== 'custom') continue;
+ const previousHat = hatFromStick(stickAxes(previous, stick));
+ const nextHat = hatFromStick(stickAxes(next, stick));
+ if (!nextHat || nextHat === previousHat) continue;
+ const binding = layout.sticks[stick].directions[nextHat];
+ if (!binding || binding.type === 'voice') continue;
+ const action = actionFromBinding(binding);
+ if (action) actions.push(action);
+ }
+ }
+
+ const previousScroll = previous ? combinedScroll(previous, layout) : null;
+ const nextScroll = combinedScroll(next, layout);
+ if (!sameScroll(previousScroll, nextScroll)) {
+ actions.push(nextScroll ?? { type: 'scroll-stop' });
+ }
+ return actions;
+}
+
+export function xboxGamepadHoldReleases(
+ frame: XboxGamepadFrame | null,
+ layout: XboxGamepadLayout,
+): InputDeviceRendererAction[] {
+ if (!frame) return [];
+ const actions: InputDeviceRendererAction[] = [];
+ if (voiceHeld(frame, layout)) actions.push({ type: 'voice', phase: 'release' });
+ if (combinedScroll(frame, layout)) actions.push({ type: 'scroll-stop' });
+ return actions;
+}
+
+export function xboxGamepadPreviewFromFrame(frame: XboxGamepadFrame) {
+ return {
+ buttons: { ...frame.buttons },
+ sticks: {
+ left: { x: frame.axes.lx, y: frame.axes.ly },
+ right: { x: frame.axes.rx, y: frame.axes.ry },
+ },
+ triggers: { ...frame.triggers },
+ };
+}
+
+function pressed(wasDown: boolean, isDown: boolean): boolean {
+ return !wasDown && isDown;
+}
+
+function voiceHeld(frame: XboxGamepadFrame, layout: XboxGamepadLayout): boolean {
+ return XBOX_GAMEPAD_BUTTON_IDS.some(
+ (id) => layout.buttons[id]?.type === 'voice' && frame.buttons[id],
+ );
+}
+
+function actionFromBinding(binding: XboxGamepadBinding): InputDeviceRendererAction | null {
+ if (binding.type === 'command') return { type: 'command', commandId: binding.commandId };
+ if (binding.type === 'skill') {
+ return { type: 'skill', skillId: binding.skillId, name: binding.name };
+ }
+ return null;
+}
+
+function stickAxes(
+ frame: XboxGamepadFrame,
+ stick: XboxGamepadStickId,
+): { x: number; y: number } {
+ return stick === 'left'
+ ? { x: frame.axes.lx, y: frame.axes.ly }
+ : { x: frame.axes.rx, y: frame.axes.ry };
+}
+
+function hatFromStick(axes: { x: number; y: number }): XboxGamepadStickDirection | null {
+ const distance = Math.hypot(axes.x, axes.y);
+ if (distance < WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE) return null;
+ if (Math.abs(axes.y) >= Math.abs(axes.x)) return axes.y >= 0 ? 'up' : 'down';
+ return axes.x >= 0 ? 'right' : 'left';
+}
+
+function combinedScroll(
+ frame: XboxGamepadFrame,
+ layout: XboxGamepadLayout,
+): Extract<InputDeviceRendererAction, { type: 'scroll' }> | null {
+ let best: Extract<InputDeviceRendererAction, { type: 'scroll' }> | null = null;
+ for (const stick of XBOX_GAMEPAD_STICK_IDS) {
+ if (layout.sticks[stick].mode !== 'conversation-scroll') continue;
+ const next = scrollFromStick(stickAxes(frame, stick));
+ if (next && (!best || next.intensity > best.intensity)) best = next;
+ }
+ return best;
+}
+
+function scrollFromStick(
+ axes: { x: number; y: number },
+): Extract<InputDeviceRendererAction, { type: 'scroll' }> | null {
+ const distance = Math.abs(axes.y);
+ if (distance < WORKLOUDER_JOYSTICK_ACTIVATION_DISTANCE) return null;
+ const intensity = normalizeJoystickIntensity(distance);
+ if (intensity <= 0) return null;
+ return {
+ type: 'scroll',
+ direction: axes.y >= 0 ? 'up' : 'down',
+ intensity,
+ };
+}
+
+function sameScroll(
+ left: Extract<InputDeviceRendererAction, { type: 'scroll' }> | null,
+ right: Extract<InputDeviceRendererAction, { type: 'scroll' }> | null,
+): boolean {
+ if (left === null && right === null) return true;
+ if (!left || !right) return false;
+ return left.direction === right.direction && Math.abs(left.intensity - right.intensity) < 0.02;
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/controller.ts b/apps/desktop/src/main/xbox-gamepad/controller.ts
new file mode 100644
index 0000000000..e9b2658879
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/controller.ts
@@ -0,0 +1,172 @@
+import type { InputDeviceRendererAction } from '../../shared/inputDevices.js';
+import {
+ cloneXboxGamepadSettings,
+ createXboxGamepadDefaultSettings,
+ XBOX_GAMEPAD_EMPTY_DEVICE,
+ XBOX_GAMEPAD_EMPTY_PREVIEW,
+ type XboxGamepadConnectionStatus,
+ type XboxGamepadDeviceInfo,
+ type XboxGamepadPreviewInput,
+ type XboxGamepadSettings,
+ type XboxGamepadState,
+} from '../../shared/xboxGamepad.js';
+import {
+ reduceXboxGamepadFrame,
+ xboxGamepadHoldReleases,
+ xboxGamepadPreviewFromFrame,
+ type XboxGamepadFrame,
+} from './bindings.js';
+import { parseXboxGamepadFrame, type XboxGamepadHostMessage } from './protocol.js';
+
+export interface XboxGamepadControllerDeps {
+ isCindyFrontmost(): boolean;
+ dispatch(action: InputDeviceRendererAction): void;
+ preview?(input: XboxGamepadPreviewInput): void;
+}
+
+export class XboxGamepadController {
+ private settings: XboxGamepadSettings = createXboxGamepadDefaultSettings();
+ private devicePresent: boolean | null = null;
+ private deviceName: string | null = null;
+ private device: XboxGamepadDeviceInfo = { ...XBOX_GAMEPAD_EMPTY_DEVICE };
+ private connectionStatus: XboxGamepadConnectionStatus = 'disabled';
+ private previousFrame: XboxGamepadFrame | null = null;
+ private hostError: string | null = null;
+ private layoutPreviewActive = false;
+ private listeners = new Set<(state: XboxGamepadState) => void>();
+
+ constructor(private readonly deps: XboxGamepadControllerDeps) {}
+
+ getState(): XboxGamepadState {
+ return {
+ connectionStatus: this.connectionStatus,
+ devicePresent: this.devicePresent,
+ deviceName: this.deviceName,
+ device: { ...this.device },
+ settings: cloneXboxGamepadSettings(this.settings),
+ };
+ }
+
+ subscribe(listener: (state: XboxGamepadState) => void): () => void {
+ this.listeners.add(listener);
+ listener(this.getState());
+ return () => this.listeners.delete(listener);
+ }
+
+ applySettings(settings: XboxGamepadSettings): void {
+ const wasDispatching = this.shouldDispatch();
+ const layoutChanged =
+ JSON.stringify(this.settings.layout) !== JSON.stringify(settings.layout);
+ if (layoutChanged) this.releaseHolds();
+ this.settings = cloneXboxGamepadSettings(settings);
+ this.syncConnectionStatus();
+ if (wasDispatching && !this.shouldDispatch()) this.releaseHolds();
+ this.emit();
+ }
+
+ setCindyFrontmost(frontmost: boolean): void {
+ if (frontmost) return;
+ this.releaseHolds();
+ }
+
+ setLayoutPreviewActive(active: boolean): void {
+ if (this.layoutPreviewActive === active) return;
+ this.layoutPreviewActive = active;
+ if (active) this.releaseHolds();
+ }
+
+ handleHostMessage(message: XboxGamepadHostMessage): void {
+ if (message.kind === 'host-error') {
+ this.hostError = message.message;
+ this.devicePresent = false;
+ this.deviceName = null;
+ this.device = { ...XBOX_GAMEPAD_EMPTY_DEVICE };
+ this.syncConnectionStatus();
+ this.releaseHolds();
+ this.emitPreview(XBOX_GAMEPAD_EMPTY_PREVIEW);
+ this.emit();
+ return;
+ }
+ if (message.kind === 'presence') {
+ this.hostError = null;
+ this.devicePresent = message.present;
+ this.deviceName = message.present ? (message.name ?? this.deviceName) : null;
+ this.device = message.present ? deviceFromPresence(message) : { ...XBOX_GAMEPAD_EMPTY_DEVICE };
+ this.syncConnectionStatus();
+ if (!message.present) {
+ this.releaseHolds();
+ this.emitPreview(XBOX_GAMEPAD_EMPTY_PREVIEW);
+ }
+ this.emit();
+ return;
+ }
+ if (message.kind !== 'frame') return;
+ const frame = parseXboxGamepadFrame(message);
+ if (!frame) return;
+ this.hostError = null;
+ this.emitPreview(xboxGamepadPreviewFromFrame(frame));
+ if (!this.shouldDispatch()) {
+ this.previousFrame = null;
+ return;
+ }
+ const actions = reduceXboxGamepadFrame(this.previousFrame, frame, this.settings.layout);
+ this.previousFrame = frame;
+ for (const action of actions) this.deps.dispatch(action);
+ }
+
+ markUnavailable(): void {
+ this.connectionStatus = this.settings.deviceEnabled ? 'unavailable' : 'disabled';
+ this.devicePresent = false;
+ this.deviceName = null;
+ this.device = { ...XBOX_GAMEPAD_EMPTY_DEVICE };
+ this.releaseHolds();
+ this.emitPreview(XBOX_GAMEPAD_EMPTY_PREVIEW);
+ this.emit();
+ }
+
+ private shouldDispatch(): boolean {
+ return this.settings.deviceEnabled && this.deps.isCindyFrontmost() && !this.layoutPreviewActive;
+ }
+
+ private emitPreview(input: XboxGamepadPreviewInput): void {
+ if (!this.layoutPreviewActive) return;
+ this.deps.preview?.(input);
+ }
+
+ private syncConnectionStatus(): void {
+ if (!this.settings.deviceEnabled) {
+ this.connectionStatus = this.devicePresent
+ ? 'disabled'
+ : this.devicePresent === false
+ ? 'not-detected'
+ : 'disabled';
+ return;
+ }
+ if (this.hostError) this.connectionStatus = 'error';
+ else if (this.devicePresent) this.connectionStatus = 'connected';
+ else if (this.devicePresent === false) this.connectionStatus = 'not-detected';
+ else this.connectionStatus = 'connecting';
+ }
+
+ private releaseHolds(): void {
+ const actions = xboxGamepadHoldReleases(this.previousFrame, this.settings.layout);
+ this.previousFrame = null;
+ for (const action of actions) this.deps.dispatch(action);
+ }
+
+ private emit(): void {
+ const state = this.getState();
+ for (const listener of this.listeners) listener(state);
+ }
+}
+
+function deviceFromPresence(message: Extract<XboxGamepadHostMessage, { kind: 'presence' }>): XboxGamepadDeviceInfo {
+ return {
+ name: message.name ?? null,
+ category: message.category ?? null,
+ transport: message.transport ?? 'unknown',
+ batteryPercentage:
+ typeof message.batteryPercentage === 'number' ? Math.round(message.batteryPercentage) : null,
+ batteryState: message.batteryState ?? 'unknown',
+ };
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/host.ts b/apps/desktop/src/main/xbox-gamepad/host.ts
new file mode 100644
index 0000000000..c317698188
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/host.ts
@@ -0,0 +1,261 @@
+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { app } from 'electron';
+
+import { createLogger } from '../logger.js';
+import {
+ isXboxGamepadHostMessage,
+ type XboxGamepadHostMessage,
+} from './protocol.js';
+
+const execFilePromise = promisify(execFile);
+const log = createLogger('xbox-gamepad-host');
+
+const MAC_HELPER_SOURCE = path.join('native', 'xbox-gamepad', 'macos-xbox-gamepad-helper.swift');
+const MAC_HELPER_RESOURCE = path.join('tools', 'xbox-gamepad', 'cindy-macos-xbox-gamepad-helper');
+
+/** Skip recompiling the same broken helper source on every 2s probe. */
+let failedHelperSourceMtime = 0;
+
+export interface XboxGamepadHost {
+ start(): void;
+ probe(): void;
+ stop(): void;
+}
+
+export interface XboxGamepadHostDeps {
+ spawnHelper?(command: string): ChildProcessWithoutNullStreams;
+ resolveHelperPath?(): Promise<string>;
+}
+
+const HELPER_RESTART_LIMIT = 3;
+const HELPER_RESTART_BASE_MS = 1_000;
+const HELPER_STABLE_MS = 10_000;
+
+export function createXboxGamepadHost(
+ onMessage: (message: XboxGamepadHostMessage) => void,
+ deps: XboxGamepadHostDeps = {},
+): XboxGamepadHost {
+ let child: ChildProcessWithoutNullStreams | null = null;
+ let starting = false;
+ let wanted = false;
+ let buffer = '';
+ let consecutiveFailures = 0;
+ let crashAccounted = false;
+ let restartTimer: ReturnType<typeof setTimeout> | null = null;
+ let stableTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const handleLine = (line: string): void => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ if (!isXboxGamepadHostMessage(parsed)) return;
+ if (parsed.kind === 'log') {
+ log[parsed.level](`[host] ${parsed.message}`);
+ return;
+ }
+ onMessage(parsed);
+ } catch {
+ log.debug('ignored malformed Xbox gamepad helper line');
+ }
+ };
+
+ const clearTimer = (timer: ReturnType<typeof setTimeout> | null): null => {
+ if (timer) clearTimeout(timer);
+ return null;
+ };
+
+ const clearRestart = (): void => {
+ restartTimer = clearTimer(restartTimer);
+ };
+
+ const clearStable = (): void => {
+ stableTimer = clearTimer(stableTimer);
+ };
+
+ const noteChildGone = (): void => {
+ clearStable();
+ if (!wanted || crashAccounted) return;
+ crashAccounted = true;
+ consecutiveFailures += 1;
+ if (restartTimer || consecutiveFailures > HELPER_RESTART_LIMIT) return;
+ const delayMs = HELPER_RESTART_BASE_MS * 2 ** (consecutiveFailures - 1);
+ restartTimer = setTimeout(() => {
+ restartTimer = null;
+ if (wanted) void startChild();
+ }, delayMs);
+ restartTimer.unref?.();
+ };
+
+ const writeHelper = (line: string): boolean => {
+ if (!child?.stdin || child.stdin.destroyed) return false;
+ try {
+ child.stdin.write(line, (error) => {
+ if (error) log.debug('xbox gamepad helper stdin write failed', { error: error.message });
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+
+ const attach = (next: ChildProcessWithoutNullStreams): void => {
+ child = next;
+ starting = false;
+ crashAccounted = false;
+ clearStable();
+ stableTimer = setTimeout(() => {
+ if (child === next) consecutiveFailures = 0;
+ }, HELPER_STABLE_MS);
+ stableTimer.unref?.();
+ next.stdout.setEncoding('utf8');
+ next.stdout.on('data', (chunk: string) => {
+ buffer += chunk;
+ const lines = buffer.split('\n');
+ buffer = lines.pop() ?? '';
+ for (const line of lines) handleLine(line);
+ });
+ next.stderr.setEncoding('utf8');
+ next.stderr.on('data', (chunk: string) => {
+ const message = chunk.trim();
+ if (message) log.debug('xbox gamepad helper stderr', { message });
+ });
+ next.stdin.on('error', (error: Error) => {
+ log.debug('xbox gamepad helper stdin error', { error: error.message });
+ });
+ next.on('error', (error: Error) => {
+ if (child === next) child = null;
+ starting = false;
+ if (!wanted) return;
+ reportHostFailure(error.message);
+ noteChildGone();
+ });
+ next.on('exit', (code, signal) => {
+ if (child === next) child = null;
+ if (!wanted) return;
+ reportHostFailure(`Xbox gamepad helper exited unexpectedly (${code ?? signal ?? 'unknown'})`);
+ noteChildGone();
+ });
+ };
+
+ const reportHostFailure = (message: string): void => {
+ log.warn('Xbox gamepad helper failed', { error: message });
+ onMessage({ kind: 'host-error', message });
+ };
+
+ const startChild = async (): Promise<void> => {
+ if (!wanted || child || starting || consecutiveFailures > HELPER_RESTART_LIMIT) return;
+ starting = true;
+ try {
+ const helperPath = await (deps.resolveHelperPath ?? resolveXboxGamepadHelperPath)();
+ if (!wanted) {
+ starting = false;
+ return;
+ }
+ const next = (deps.spawnHelper ?? defaultSpawnHelper)(helperPath);
+ attach(next);
+ } catch (error) {
+ starting = false;
+ const message = error instanceof Error ? error.message : String(error);
+ // Not `presence: false` — a helper that won't build is an error state, not
+ // "no controller plugged in", and the settings page must say so.
+ reportHostFailure(message);
+ noteChildGone();
+ }
+ };
+
+ return {
+ start() {
+ wanted = true;
+ consecutiveFailures = 0;
+ crashAccounted = false;
+ void startChild();
+ },
+ probe() {
+ if (writeHelper('probe\n')) return;
+ void startChild();
+ },
+ stop() {
+ wanted = false;
+ clearRestart();
+ clearStable();
+ const current = child;
+ child = null;
+ if (!current) return;
+ try {
+ if (!current.stdin.destroyed) {
+ current.stdin.write('stop\n', (error) => {
+ if (error) log.debug('xbox gamepad helper stdin write failed', { error: error.message });
+ });
+ current.stdin.end();
+ }
+ } catch {
+ // The helper may already have exited.
+ }
+ current.kill();
+ },
+ };
+}
+
+function defaultSpawnHelper(command: string): ChildProcessWithoutNullStreams {
+ return spawn(command, [], { stdio: ['pipe', 'pipe', 'pipe'] });
+}
+
+async function resolveXboxGamepadHelperPath(): Promise<string> {
+ if (process.platform === 'darwin') return resolveMacHelperPath();
+ throw new Error(`Xbox gamepad helper is not available on ${process.platform}`);
+}
+
+async function resolveMacHelperPath(): Promise<string> {
+ const packaged = path.join(process.resourcesPath, MAC_HELPER_RESOURCE);
+ if (app.isPackaged && fs.existsSync(packaged)) return packaged;
+
+ const source = resolveMacHelperSource();
+ const binary = path.join(app.getPath('userData'), 'xbox-gamepad', 'cindy-macos-xbox-gamepad-helper');
+ if (!fs.existsSync(source)) {
+ throw new Error(`Xbox gamepad helper source missing at ${source}`);
+ }
+ const sourceMtime = fs.statSync(source).mtimeMs;
+ if (fs.existsSync(binary) && fs.statSync(binary).mtimeMs >= sourceMtime) {
+ failedHelperSourceMtime = 0;
+ return binary;
+ }
+ if (failedHelperSourceMtime === sourceMtime) {
+ throw new Error('Xbox gamepad helper compile failed; waiting for source change');
+ }
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ try {
+ await execFilePromise(
+ 'swiftc',
+ [
+ source,
+ '-O',
+ '-framework',
+ 'Foundation',
+ '-framework',
+ 'GameController',
+ '-framework',
+ 'IOKit',
+ '-o',
+ binary,
+ ],
+ { timeout: 20_000 },
+ );
+ } catch (error) {
+ failedHelperSourceMtime = sourceMtime;
+ throw error;
+ }
+ failedHelperSourceMtime = 0;
+ fs.chmodSync(binary, 0o755);
+ log.info('built Xbox gamepad helper', { path: binary });
+ return binary;
+}
+
+function resolveMacHelperSource(): string {
+ const fromApp = path.join(app.getAppPath(), MAC_HELPER_SOURCE);
+ if (fs.existsSync(fromApp)) return fromApp;
+ return path.join(__dirname, '..', '..', MAC_HELPER_SOURCE);
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/index.ts b/apps/desktop/src/main/xbox-gamepad/index.ts
new file mode 100644
index 0000000000..be15adb37e
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/index.ts
@@ -0,0 +1,169 @@
+import { app, BrowserWindow, ipcMain, shell } from 'electron';
+
+import { createLogger } from '../logger.js';
+import { getDeepLinkMainWindow } from '../deepLink.js';
+import { registerInputDevice } from '../input-devices/registry.js';
+import { isSecondaryAppWindow } from '../secondary-windows.js';
+import { isAppContentWindow } from '../windowFocusClassifier.js';
+import {
+ WORKLOUDER_CODEX_ACTION_CHANNEL,
+ type WorkLouderCodexRendererAction,
+} from '../../shared/workLouderCodex.js';
+import {
+ XBOX_GAMEPAD_DEVICE,
+ XBOX_GAMEPAD_GET_STATE_CHANNEL,
+ XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL,
+ XBOX_GAMEPAD_PROBE_CHANNEL,
+ XBOX_GAMEPAD_RESET_SETTINGS_CHANNEL,
+ XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL,
+ XBOX_GAMEPAD_SET_SETTINGS_CHANNEL,
+ XBOX_GAMEPAD_STATE_CHANGED_CHANNEL,
+ type XboxGamepadPreviewInput,
+ type XboxGamepadState,
+} from '../../shared/xboxGamepad.js';
+import { assertTrustedAppRendererEvent, isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
+import { createWorkLouderCodexActiveWindowRouter } from '../worklouder-codex/actionWindow.js';
+import { XboxGamepadController } from './controller.js';
+import { createXboxGamepadHost } from './host.js';
+import { createLayoutPreviewLease, layoutPreviewOwnerFromEvent } from '../input-devices/previewLease.js';
+import { createXboxGamepadSettingsIpc } from './settingsIpc.js';
+import {
+ readXboxGamepadSettings,
+ resetXboxGamepadSettings,
+ writeXboxGamepadSettingsPatch,
+} from './settingsStore.js';
+
+const log = createLogger('xbox-gamepad');
+
+const actionWindowRouter = createWorkLouderCodexActiveWindowRouter({
+ getFocusedWindow: () => BrowserWindow.getFocusedWindow(),
+ getMainWindow: getDeepLinkMainWindow,
+ isActionWindow: (win) => {
+ if (!win) return false;
+ const main = getDeepLinkMainWindow();
+ return win === main || isSecondaryAppWindow(win);
+ },
+});
+
+function isCindyFrontmost(): boolean {
+ return isAppContentWindow(BrowserWindow.getFocusedWindow());
+}
+
+function sendWindowMessage(win: BrowserWindow, channel: string, payload: unknown): boolean {
+ if (win.webContents.isDestroyed() || win.webContents.isLoading()) return false;
+ win.webContents.send(channel, payload);
+ return true;
+}
+
+function dispatchRendererAction(action: WorkLouderCodexRendererAction): void {
+ if (action.type === 'external-url') {
+ void shell.openExternal(action.url).catch((error: unknown) => {
+ log.warn('failed to open Xbox gamepad external action', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ return;
+ }
+ const win = actionWindowRouter.resolve(action);
+ if (win && sendWindowMessage(win, WORKLOUDER_CODEX_ACTION_CHANNEL, action)) return;
+ log.debug('Xbox gamepad action skipped because Cindy is not the frontmost app', {
+ type: action.type,
+ });
+}
+
+function broadcastState(state: XboxGamepadState): void {
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!isTrustedAppRendererWindow(window)) continue;
+ window.webContents.send(XBOX_GAMEPAD_STATE_CHANGED_CHANNEL, state);
+ }
+}
+
+function broadcastPreview(input: XboxGamepadPreviewInput): void {
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!isTrustedAppRendererWindow(window)) continue;
+ window.webContents.send(XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL, input);
+ }
+}
+
+const controller = new XboxGamepadController({
+ isCindyFrontmost,
+ dispatch: dispatchRendererAction,
+ preview: broadcastPreview,
+});
+
+const host = createXboxGamepadHost((message) => {
+ controller.handleHostMessage(message);
+});
+const layoutPreviewLease = createLayoutPreviewLease((active) => {
+ controller.setLayoutPreviewActive(active);
+});
+
+let inputDeviceRegistered = false;
+let settingsIpcRegistered = false;
+let focusHooksInstalled = false;
+
+export function registerXboxGamepadInputDevice(): void {
+ if (inputDeviceRegistered) return;
+ inputDeviceRegistered = true;
+ registerInputDevice({
+ descriptor: XBOX_GAMEPAD_DEVICE,
+ start: () => {
+ registerXboxGamepadSettingsIpc();
+ },
+ updateSessionActivity: () => undefined,
+ resumeTaskSlots: async () => {
+ controller.applySettings(readXboxGamepadSettings());
+ },
+ suspendTaskSlots: () => {
+ controller.applySettings({ ...readXboxGamepadSettings(), deviceEnabled: false });
+ },
+ dispose: async () => {
+ host.stop();
+ },
+ });
+}
+
+export function registerXboxGamepadSettingsIpc(): void {
+ if (settingsIpcRegistered) return;
+ settingsIpcRegistered = true;
+ controller.applySettings(readXboxGamepadSettings());
+ if (process.platform === 'darwin') host.start();
+ else controller.markUnavailable();
+ installFocusHooks();
+
+ const handlers = createXboxGamepadSettingsIpc({
+ assertTrustedSender: (event) => assertTrustedAppRendererEvent(event as never),
+ getState: () => controller.getState(),
+ writeSettings: writeXboxGamepadSettingsPatch,
+ resetSettings: resetXboxGamepadSettings,
+ applySettings: (settings) => controller.applySettings(settings),
+ probeDevice: () => host.probe(),
+ setLayoutPreviewActive: (active, event) => {
+ layoutPreviewLease.setActive(active, layoutPreviewOwnerFromEvent(event));
+ },
+ });
+
+ ipcMain.handle(XBOX_GAMEPAD_GET_STATE_CHANNEL, (event) => handlers.get(event));
+ ipcMain.handle(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, (event, patch: unknown) =>
+ handlers.set(event, patch),
+ );
+ ipcMain.handle(XBOX_GAMEPAD_RESET_SETTINGS_CHANNEL, (event) => handlers.reset(event));
+ ipcMain.handle(XBOX_GAMEPAD_PROBE_CHANNEL, (event) => handlers.probe(event));
+ ipcMain.handle(XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL, (event, active: unknown) =>
+ handlers.setLayoutPreviewActive(event, active),
+ );
+
+ controller.subscribe((state) => {
+ broadcastState(state);
+ });
+}
+
+function installFocusHooks(): void {
+ if (focusHooksInstalled) return;
+ focusHooksInstalled = true;
+ const sync = (): void => {
+ controller.setCindyFrontmost(isCindyFrontmost());
+ };
+ app.on('browser-window-focus', sync);
+ app.on('browser-window-blur', sync);
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/layoutOverride.ts b/apps/desktop/src/main/xbox-gamepad/layoutOverride.ts
new file mode 100644
index 0000000000..f4fd68a9e4
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/layoutOverride.ts
@@ -0,0 +1,43 @@
+import {
+ createXboxGamepadDefaultLayout,
+ XBOX_GAMEPAD_BUTTON_IDS,
+ XBOX_GAMEPAD_STICK_DIRECTIONS,
+ XBOX_GAMEPAD_STICK_IDS,
+ type XboxGamepadLayout,
+ type XboxGamepadStickBinding,
+} from '../../shared/xboxGamepad.js';
+
+export function xboxGamepadLayoutOverrides(
+ layout: XboxGamepadLayout,
+ defaults: XboxGamepadLayout = createXboxGamepadDefaultLayout(),
+): { version: 1; buttons: Record<string, unknown>; sticks: Record<string, unknown> } | null {
+ const buttons: Record<string, unknown> = {};
+ for (const id of XBOX_GAMEPAD_BUTTON_IDS) {
+ if (JSON.stringify(layout.buttons[id]) !== JSON.stringify(defaults.buttons[id])) {
+ buttons[id] = layout.buttons[id];
+ }
+ }
+ const sticks: Record<string, unknown> = {};
+ for (const id of XBOX_GAMEPAD_STICK_IDS) {
+ const override = xboxGamepadStickOverrides(layout.sticks[id], defaults.sticks[id]);
+ if (override) sticks[id] = override;
+ }
+ if (Object.keys(buttons).length === 0 && Object.keys(sticks).length === 0) return null;
+ return { version: 1, buttons, sticks };
+}
+
+export function xboxGamepadStickOverrides(
+ stick: XboxGamepadStickBinding,
+ defaults: XboxGamepadStickBinding,
+): { mode?: XboxGamepadStickBinding['mode']; directions?: Record<string, unknown> } | null {
+ const directions: Record<string, unknown> = {};
+ for (const direction of XBOX_GAMEPAD_STICK_DIRECTIONS) {
+ if (JSON.stringify(stick.directions[direction]) !== JSON.stringify(defaults.directions[direction])) {
+ directions[direction] = stick.directions[direction];
+ }
+ }
+ const override: { mode?: XboxGamepadStickBinding['mode']; directions?: Record<string, unknown> } = {};
+ if (stick.mode !== defaults.mode) override.mode = stick.mode;
+ if (Object.keys(directions).length > 0) override.directions = directions;
+ return Object.keys(override).length > 0 ? override : null;
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/protocol.ts b/apps/desktop/src/main/xbox-gamepad/protocol.ts
new file mode 100644
index 0000000000..c2bc1822d6
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/protocol.ts
@@ -0,0 +1,168 @@
+import { XBOX_GAMEPAD_BUTTON_IDS } from '../../shared/xboxGamepad.js';
+import {
+ digitalTriggerPressed,
+ XBOX_GAMEPAD_EMPTY_FRAME,
+ type XboxGamepadAxes,
+ type XboxGamepadButtons,
+ type XboxGamepadFrame,
+ type XboxGamepadTriggers,
+} from './bindings.js';
+
+export type XboxGamepadHostMessage =
+ | {
+ kind: 'presence';
+ present: boolean;
+ name?: string;
+ category?: string;
+ transport?: 'usb' | 'bluetooth' | 'unknown';
+ batteryPercentage?: number;
+ batteryState?: 'unknown' | 'discharging' | 'charging' | 'full';
+ }
+ | {
+ kind: 'frame';
+ buttons: XboxGamepadButtons;
+ axes: XboxGamepadAxes;
+ triggers: XboxGamepadTriggers;
+ }
+ | { kind: 'log'; level: 'debug' | 'info' | 'warn' | 'error'; message: string }
+ /**
+ * Synthesized by the host when the helper cannot be built or spawned. It is
+ * deliberately absent from isXboxGamepadHostMessage: only main may report it,
+ * never a line off the helper's stdout.
+ */
+ | { kind: 'host-error'; message: string };
+
+export function isXboxGamepadHostMessage(value: unknown): value is XboxGamepadHostMessage {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const message = value as { kind?: unknown };
+ if (message.kind === 'presence') {
+ const record = message as {
+ present?: unknown;
+ name?: unknown;
+ category?: unknown;
+ transport?: unknown;
+ batteryPercentage?: unknown;
+ batteryState?: unknown;
+ };
+ if (typeof record.present !== 'boolean') return false;
+ if (record.name !== undefined && typeof record.name !== 'string') return false;
+ if (record.category !== undefined && typeof record.category !== 'string') return false;
+ if (
+ record.transport !== undefined &&
+ record.transport !== 'usb' &&
+ record.transport !== 'bluetooth' &&
+ record.transport !== 'unknown'
+ ) {
+ return false;
+ }
+ if (
+ record.batteryPercentage !== undefined &&
+ (typeof record.batteryPercentage !== 'number' ||
+ !Number.isFinite(record.batteryPercentage) ||
+ record.batteryPercentage < 0 ||
+ record.batteryPercentage > 100)
+ ) {
+ return false;
+ }
+ if (
+ record.batteryState !== undefined &&
+ record.batteryState !== 'unknown' &&
+ record.batteryState !== 'discharging' &&
+ record.batteryState !== 'charging' &&
+ record.batteryState !== 'full'
+ ) {
+ return false;
+ }
+ return true;
+ }
+ if (message.kind === 'log') {
+ const level = (message as { level?: unknown }).level;
+ const text = (message as { message?: unknown }).message;
+ return (
+ (level === 'debug' || level === 'info' || level === 'warn' || level === 'error') &&
+ typeof text === 'string'
+ );
+ }
+ if (message.kind !== 'frame') return false;
+ return parseXboxGamepadFrame(message) !== null;
+}
+
+export function parseXboxGamepadFrame(value: unknown): XboxGamepadFrame | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as {
+ buttons?: unknown;
+ axes?: unknown;
+ ltAnalog?: unknown;
+ rtAnalog?: unknown;
+ triggers?: unknown;
+ };
+ const buttons = parseButtons(record.buttons);
+ const axes = parseAxes(record.axes);
+ if (!buttons || !axes) return null;
+ const triggers = parseTriggers(record.triggers, record.ltAnalog, record.rtAnalog);
+ if (triggers.ltAnalogPresent) buttons.lt = digitalTriggerPressed(buttons.lt, triggers.values.lt);
+ if (triggers.rtAnalogPresent) buttons.rt = digitalTriggerPressed(buttons.rt, triggers.values.rt);
+ return { buttons, axes, triggers: triggers.values };
+}
+
+function parseButtons(value: unknown): XboxGamepadButtons | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const buttons = { ...XBOX_GAMEPAD_EMPTY_FRAME.buttons };
+ for (const id of XBOX_GAMEPAD_BUTTON_IDS) {
+ if (record[id] === undefined) continue;
+ if (typeof record[id] !== 'boolean') return null;
+ buttons[id] = record[id];
+ }
+ return buttons;
+}
+
+function parseAxes(value: unknown): XboxGamepadAxes | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const lx = optionalUnit(record.lx);
+ const ly = optionalUnit(record.ly);
+ const rx = optionalUnit(record.rx);
+ const ry = optionalUnit(record.ry);
+ if (
+ (record.lx !== undefined && lx === null) ||
+ (record.ly !== undefined && ly === null) ||
+ (record.rx !== undefined && rx === null) ||
+ (record.ry !== undefined && ry === null)
+ ) {
+ return null;
+ }
+ return { lx: lx ?? 0, ly: ly ?? 0, rx: rx ?? 0, ry: ry ?? 0 };
+}
+
+function parseTriggers(
+ value: unknown,
+ ltAnalog: unknown,
+ rtAnalog: unknown,
+): {
+ values: XboxGamepadTriggers;
+ ltAnalogPresent: boolean;
+ rtAnalogPresent: boolean;
+} {
+ const record =
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+ const lt = optionalUnit(record.lt) ?? optionalUnit(ltAnalog);
+ const rt = optionalUnit(record.rt) ?? optionalUnit(rtAnalog);
+ return {
+ values: { lt: clamp01(lt ?? 0), rt: clamp01(rt ?? 0) },
+ ltAnalogPresent: lt !== null,
+ rtAnalogPresent: rt !== null,
+ };
+}
+
+function optionalUnit(value: unknown): number | null {
+ if (value === undefined) return null;
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;
+ return Math.max(-1, Math.min(1, value));
+}
+
+function clamp01(value: number): number {
+ return Math.max(0, Math.min(1, value));
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/settingsIpc.ts b/apps/desktop/src/main/xbox-gamepad/settingsIpc.ts
new file mode 100644
index 0000000000..9838879f9b
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/settingsIpc.ts
@@ -0,0 +1,163 @@
+import { isInputDeviceCommandId } from '../../shared/inputDevices.js';
+import {
+ isXboxGamepadStickMode,
+ XBOX_GAMEPAD_BUTTON_IDS,
+ XBOX_GAMEPAD_STICK_DIRECTIONS,
+ XBOX_GAMEPAD_STICK_IDS,
+ type XboxGamepadBinding,
+ type XboxGamepadLayout,
+ type XboxGamepadSettings,
+ type XboxGamepadSettingsPatch,
+ type XboxGamepadState,
+ type XboxGamepadStickBinding,
+} from '../../shared/xboxGamepad.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+const SETTING_KEYS = ['deviceEnabled', 'layout'] as const;
+
+export interface XboxGamepadSettingsIpcDeps {
+ assertTrustedSender(event: unknown): void;
+ getState(): XboxGamepadState;
+ writeSettings(patch: XboxGamepadSettingsPatch): XboxGamepadSettings;
+ resetSettings(): XboxGamepadSettings;
+ applySettings(settings: XboxGamepadSettings): void;
+ probeDevice(): void;
+ setLayoutPreviewActive(active: boolean, event: unknown): void;
+}
+
+export function createXboxGamepadSettingsIpc(deps: XboxGamepadSettingsIpcDeps) {
+ return {
+ get(event: unknown): XboxGamepadState {
+ deps.assertTrustedSender(event);
+ return deps.getState();
+ },
+ set(event: unknown, patch: unknown): XboxGamepadState {
+ deps.assertTrustedSender(event);
+ const next = deps.writeSettings(parseSettingsPatch(patch));
+ deps.applySettings(next);
+ return deps.getState();
+ },
+ reset(event: unknown): XboxGamepadState {
+ deps.assertTrustedSender(event);
+ const next = deps.resetSettings();
+ deps.applySettings(next);
+ return deps.getState();
+ },
+ probe(event: unknown): XboxGamepadState {
+ deps.assertTrustedSender(event);
+ deps.probeDevice();
+ return deps.getState();
+ },
+ 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, event);
+ },
+ };
+}
+
+function parseSettingsPatch(value: unknown): XboxGamepadSettingsPatch {
+ const record = requireRecord(value, 'Xbox gamepad settings patch required');
+ rejectUnknownKeys(record, SETTING_KEYS, 'Xbox gamepad setting');
+ if (Object.keys(record).length === 0) {
+ throwIpcError('INVALID_PARAMS', 'Xbox gamepad settings patch cannot be empty');
+ }
+ const patch: XboxGamepadSettingsPatch = {};
+ if ('deviceEnabled' in record) {
+ if (typeof record.deviceEnabled !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'deviceEnabled must be a boolean');
+ }
+ patch.deviceEnabled = record.deviceEnabled;
+ }
+ if ('layout' in record) patch.layout = parseLayout(record.layout);
+ return patch;
+}
+
+function parseLayout(value: unknown): XboxGamepadLayout {
+ const record = requireRecord(value, 'layout must be an object');
+ rejectUnknownKeys(record, ['version', 'buttons', 'sticks'], 'layout field');
+ if (record.version !== 1) throwIpcError('INVALID_PARAMS', 'layout version must be 1');
+ const buttonsRecord = requireRecord(record.buttons, 'layout buttons must be an object');
+ rejectUnknownKeys(buttonsRecord, XBOX_GAMEPAD_BUTTON_IDS, 'layout button');
+ const buttons = Object.fromEntries(
+ XBOX_GAMEPAD_BUTTON_IDS.map((id) => [id, parseBinding(buttonsRecord[id] ?? null)]),
+ ) as XboxGamepadLayout['buttons'];
+
+ const sticksRecord = requireRecord(record.sticks, 'layout sticks must be an object');
+ rejectUnknownKeys(sticksRecord, XBOX_GAMEPAD_STICK_IDS, 'layout stick');
+ const sticks = Object.fromEntries(
+ XBOX_GAMEPAD_STICK_IDS.map((id) => [id, parseStick(sticksRecord[id], id)]),
+ ) as XboxGamepadLayout['sticks'];
+
+ return { version: 1, buttons, sticks };
+}
+
+function parseStick(value: unknown, id: string): XboxGamepadStickBinding {
+ const record = requireRecord(value, `${id} stick assignment is required`);
+ rejectUnknownKeys(record, ['mode', 'directions'], `${id} stick field`);
+ if (!isXboxGamepadStickMode(record.mode)) {
+ throwIpcError('INVALID_PARAMS', `${id} stick mode is invalid`);
+ }
+ const directionsRecord = requireRecord(record.directions, `${id} stick directions must be an object`);
+ rejectUnknownKeys(directionsRecord, XBOX_GAMEPAD_STICK_DIRECTIONS, `${id} stick direction`);
+ const directions = Object.fromEntries(
+ XBOX_GAMEPAD_STICK_DIRECTIONS.map((direction) => {
+ const binding = parseBinding(directionsRecord[direction] ?? null);
+ if (binding?.type === 'voice') {
+ throwIpcError('INVALID_PARAMS', `${id} stick directions cannot use voice`);
+ }
+ return [direction, binding];
+ }),
+ ) as XboxGamepadStickBinding['directions'];
+ return { mode: record.mode, directions };
+}
+
+function parseBinding(value: unknown): XboxGamepadBinding | null {
+ if (value === null) return null;
+ const record = requireRecord(value, 'gamepad binding must be an object');
+ if (record.type === 'command') {
+ rejectUnknownKeys(record, ['type', 'commandId'], 'command binding field');
+ if (!isInputDeviceCommandId(record.commandId)) {
+ throwIpcError('INVALID_PARAMS', 'command binding is invalid');
+ }
+ return { type: 'command', commandId: record.commandId };
+ }
+ if (record.type === 'skill') {
+ rejectUnknownKeys(record, ['type', 'skillId', 'name'], 'skill binding field');
+ return {
+ type: 'skill',
+ skillId: requireBoundedString(record.skillId, 1_024, 'skillId'),
+ name: requireBoundedString(record.name, 256, 'skill name'),
+ };
+ }
+ if (record.type === 'voice') {
+ rejectUnknownKeys(record, ['type'], 'voice binding field');
+ return { type: 'voice' };
+ }
+ throwIpcError('INVALID_PARAMS', 'gamepad binding type is invalid');
+}
+
+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;
+}
diff --git a/apps/desktop/src/main/xbox-gamepad/settingsStore.ts b/apps/desktop/src/main/xbox-gamepad/settingsStore.ts
new file mode 100644
index 0000000000..25b4894dd8
--- /dev/null
+++ b/apps/desktop/src/main/xbox-gamepad/settingsStore.ts
@@ -0,0 +1,132 @@
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+import {
+ cloneXboxGamepadBinding,
+ createXboxGamepadDefaultLayout,
+ createXboxGamepadDefaultSettings,
+ isXboxGamepadBinding,
+ isXboxGamepadStickMode,
+ XBOX_GAMEPAD_BUTTON_IDS,
+ XBOX_GAMEPAD_STICK_DIRECTIONS,
+ XBOX_GAMEPAD_STICK_IDS,
+ type XboxGamepadLayout,
+ type XboxGamepadSettings,
+ type XboxGamepadSettingsPatch,
+ type XboxGamepadStickBinding,
+} from '../../shared/xboxGamepad.js';
+import { xboxGamepadLayoutOverrides } from './layoutOverride.js';
+
+const log = desktopMakerLogger.child('xbox-gamepad-settings-store');
+
+function settingsFilePath(): string {
+ return ownerScopedUserDataPath('xbox-gamepad-settings.json');
+}
+
+function normalizeStick(raw: unknown, fallback: XboxGamepadStickBinding): XboxGamepadStickBinding {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return fallback;
+ const value = raw as Record<string, unknown>;
+ const directionsRaw =
+ value.directions && typeof value.directions === 'object' && !Array.isArray(value.directions)
+ ? (value.directions as Record<string, unknown>)
+ : {};
+ return {
+ mode: isXboxGamepadStickMode(value.mode) ? value.mode : fallback.mode,
+ directions: Object.fromEntries(
+ XBOX_GAMEPAD_STICK_DIRECTIONS.map((direction) => {
+ if (!Object.prototype.hasOwnProperty.call(directionsRaw, direction)) {
+ return [direction, cloneXboxGamepadBinding(fallback.directions[direction])];
+ }
+ const rawDirection = directionsRaw[direction];
+ if (rawDirection === null) return [direction, null];
+ const binding = cloneXboxGamepadBinding(
+ isXboxGamepadBinding(rawDirection) ? rawDirection : fallback.directions[direction],
+ );
+ return [direction, binding?.type === 'voice' ? null : binding];
+ }),
+ ) as XboxGamepadStickBinding['directions'],
+ };
+}
+
+function normalizeLayout(raw: unknown): XboxGamepadLayout {
+ const defaults = createXboxGamepadDefaultLayout();
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return defaults;
+ const value = raw as Record<string, unknown>;
+ const buttonsRaw =
+ value.buttons && typeof value.buttons === 'object' && !Array.isArray(value.buttons)
+ ? (value.buttons as Record<string, unknown>)
+ : {};
+ const sticksRaw =
+ value.sticks && typeof value.sticks === 'object' && !Array.isArray(value.sticks)
+ ? (value.sticks as Record<string, unknown>)
+ : {};
+ return {
+ version: 1,
+ buttons: Object.fromEntries(
+ XBOX_GAMEPAD_BUTTON_IDS.map((id) => [
+ id,
+ cloneXboxGamepadBinding(
+ buttonsRaw[id] === null
+ ? null
+ : isXboxGamepadBinding(buttonsRaw[id])
+ ? buttonsRaw[id]
+ : defaults.buttons[id],
+ ),
+ ]),
+ ) as XboxGamepadLayout['buttons'],
+ sticks: Object.fromEntries(
+ XBOX_GAMEPAD_STICK_IDS.map((id) => [id, normalizeStick(sticksRaw[id], defaults.sticks[id])]),
+ ) as XboxGamepadLayout['sticks'],
+ };
+}
+
+function normalizeSettings(raw: unknown): XboxGamepadSettings {
+ const defaults = createXboxGamepadDefaultSettings();
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return defaults;
+ const value = raw as Record<string, unknown>;
+ return {
+ deviceEnabled: typeof value.deviceEnabled === 'boolean' ? value.deviceEnabled : defaults.deviceEnabled,
+ layout: normalizeLayout(value.layout),
+ };
+}
+
+const store = createOverrideSettingsFile<XboxGamepadSettings>({
+ filePath: settingsFilePath,
+ defaults: createXboxGamepadDefaultSettings,
+ normalize: normalizeSettings,
+ mergeOverrides: ({ patch, next, defaults, overrides }) => {
+ const nextOverrides = { ...overrides };
+ if ('deviceEnabled' in patch) {
+ if (next.deviceEnabled === defaults.deviceEnabled) delete nextOverrides.deviceEnabled;
+ else nextOverrides.deviceEnabled = next.deviceEnabled;
+ }
+ if ('layout' in patch) {
+ const layout = xboxGamepadLayoutOverrides(next.layout, defaults.layout);
+ if (layout) nextOverrides.layout = layout;
+ else delete nextOverrides.layout;
+ }
+ return nextOverrides;
+ },
+ log,
+ label: 'Xbox gamepad',
+ maxBytes: 64 * 1024,
+});
+
+export function readXboxGamepadSettings(): XboxGamepadSettings {
+ store.invalidateIfChanged();
+ return store.read();
+}
+
+export function writeXboxGamepadSettingsPatch(patch: XboxGamepadSettingsPatch): XboxGamepadSettings {
+ store.writePatch(patch);
+ log.info('Xbox gamepad settings written', { keys: Object.keys(patch) });
+ return store.read();
+}
+
+export function resetXboxGamepadSettings(): XboxGamepadSettings {
+ const keepEnabled = store.read().deviceEnabled;
+ store.reset();
+ log.info('Xbox gamepad settings reset');
+ if (keepEnabled) return writeXboxGamepadSettingsPatch({ deviceEnabled: true });
+ return store.read();
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 810785e228..9923baa0b4 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -58,6 +58,18 @@ import {
type WorkLouderCodexSettingsPatch,
type WorkLouderCodexState,
} from '../shared/workLouderCodex';
+import {
+ XBOX_GAMEPAD_GET_STATE_CHANNEL,
+ XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL,
+ XBOX_GAMEPAD_PROBE_CHANNEL,
+ XBOX_GAMEPAD_RESET_SETTINGS_CHANNEL,
+ XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL,
+ XBOX_GAMEPAD_SET_SETTINGS_CHANNEL,
+ XBOX_GAMEPAD_STATE_CHANGED_CHANNEL,
+ type XboxGamepadPreviewInput,
+ type XboxGamepadSettingsPatch,
+ type XboxGamepadState,
+} from '../shared/xboxGamepad';
import {
ANALYTICS_SETTINGS_CHANGE_CHANNEL,
type AnalyticsSettingsPayload,
@@ -1640,6 +1652,32 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
},
+ xboxGamepad: {
+ getState: (): Promise<XboxGamepadState> => ipcRenderer.invoke(XBOX_GAMEPAD_GET_STATE_CHANNEL),
+ setSettings: (patch: XboxGamepadSettingsPatch): Promise<XboxGamepadState> =>
+ ipcRenderer.invoke(XBOX_GAMEPAD_SET_SETTINGS_CHANNEL, patch),
+ resetSettings: (): Promise<XboxGamepadState> =>
+ ipcRenderer.invoke(XBOX_GAMEPAD_RESET_SETTINGS_CHANNEL),
+ probe: (): Promise<XboxGamepadState> => ipcRenderer.invoke(XBOX_GAMEPAD_PROBE_CHANNEL),
+ setLayoutPreviewActive: (active: boolean): Promise<void> =>
+ ipcRenderer.invoke(XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL, active),
+ onStateChanged: (callback: (state: XboxGamepadState) => void): (() => void) => {
+ const listener = (_event: Electron.IpcRendererEvent, state: XboxGamepadState): void => {
+ callback(state);
+ };
+ ipcRenderer.on(XBOX_GAMEPAD_STATE_CHANGED_CHANNEL, listener);
+ return () => ipcRenderer.removeListener(XBOX_GAMEPAD_STATE_CHANGED_CHANNEL, listener);
+ },
+ onPreviewInput: (callback: (input: XboxGamepadPreviewInput) => void): (() => void) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ input: XboxGamepadPreviewInput,
+ ): void => callback(input);
+ ipcRenderer.on(XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL, listener);
+ return () => ipcRenderer.removeListener(XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL, listener);
+ },
+ },
+
// ── 右侧栏独立子窗口(RSB window)──────────────────────────────────────
// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期。状态机在 main
// (right-sidebar-window/controller.ts),renderer 只 invoke + 订阅广播。
@@ -3918,6 +3956,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Fullscreen state
onFullscreenChange: fanOutFullscreenChange,
getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),
+ toggleFullscreen: (): Promise<boolean> => ipcRenderer.invoke('toggle-fullscreen'),
// 窗口是否对用户不可见(最小化 / hide)。装饰动画闸门订阅它来决定要不要冻结常驻动画;
// 关掉 backgroundThrottling 的窗口里 document.visibilityState 不可信,只能靠这条。
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index a744231129..6a6233f925 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1168,7 +1168,7 @@ export function MainLayout() {
navigate('/cc-agent/new');
return true;
case 'settings':
- navigate('/settings?tab=shortcuts&workLouderCodex=1');
+ navigate('/settings?tab=shortcuts');
return true;
case 'manageTasks':
navigate('/cc-agent/scheduled');
@@ -1188,6 +1188,9 @@ export function MainLayout() {
case 'navigateForward':
navigate(1);
return true;
+ case 'toggleFullscreen':
+ void window.electronAPI?.toggleFullscreen?.();
+ return true;
case 'toggleSidebar':
handleToggleSidebar();
return true;
diff --git a/apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx b/apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx
new file mode 100644
index 0000000000..cf5045b14d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx
@@ -0,0 +1,79 @@
+import { cn } from '@/lib/utils';
+
+export type InputDeviceConnectionTone = 'connected' | 'error' | 'neutral';
+
+/**
+ * Shared connection status for input-device rows (Work Louder, Xbox, …).
+ *
+ * DESIGN.md treats these as Micro Label status badges, and status dots are the
+ * sanctioned way to carry hue. One device must not invent a text-only variant.
+ */
+export function InputDeviceConnectionStatus({
+ label,
+ tone,
+ compact = false,
+}: {
+ label: string;
+ tone: InputDeviceConnectionTone;
+ compact?: boolean;
+}) {
+ const dotClass =
+ tone === 'connected'
+ ? 'bg-[var(--settings-badge-connected)]'
+ : tone === 'error'
+ ? '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" />
+ {label}
+ </span>
+ );
+}
+
+export type InputDeviceStatusKey =
+ | 'connecting'
+ | 'connected'
+ | 'not-detected'
+ | 'present'
+ | 'disabled'
+ | 'error'
+ | 'unavailable';
+
+export function resolveInputDeviceStatusKey(input: {
+ enabled: boolean;
+ present: boolean | null | undefined;
+ connectionStatus?: string | null;
+ loading?: boolean;
+}): InputDeviceStatusKey {
+ if (input.loading) return 'connecting';
+ if (!input.enabled) return 'disabled';
+ if (input.connectionStatus === 'error' || input.connectionStatus === 'unavailable') {
+ return input.connectionStatus;
+ }
+ if (input.present === false || input.connectionStatus === 'not-detected') return 'not-detected';
+ if (input.present === true || input.connectionStatus === 'connected') return 'connected';
+ return 'connecting';
+}
+
+export function inputDeviceStatusLabelKey(status: InputDeviceStatusKey): InputDeviceStatusKey {
+ return status === 'present' ? 'connected' : status;
+}
+
+export function inputDeviceConnectionTone(input: {
+ status: string;
+ present?: boolean | null;
+}): InputDeviceConnectionTone {
+ if (input.status === 'error' || input.status === 'unavailable') return 'error';
+ if (input.present === true || input.status === 'connected' || input.status === 'present') {
+ return 'connected';
+ }
+ return 'neutral';
+}
diff --git a/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx b/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx
index f7b139cb03..99c51b65ff 100644
--- a/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx
@@ -14,11 +14,14 @@
* override; 生效值与显示通过 appShortcutStore 单例热更新。
* 录制期间设置 body.dataset.appShortcutRecording 旗标, useAppShortcut 全体
* 让路, 避免录制 ⌘B 时误触发侧边栏切换。
+ *
+ * 已检测或已启用的硬件设备出现在快捷键这一级。其余不展开,
+ * 收到「配件」入口里。
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
-import { Pencil, RotateCcw, Trash2 } from 'lucide-react';
+import { ArrowLeft, ChevronRight, Package, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
@@ -43,12 +46,54 @@ import {
subscribeAppShortcuts,
} from '@/lib/appShortcutStore';
import { getVoiceInputSettings } from '@/hooks/useVoiceInputSettings';
+import { useWorkLouderCodex } from '@/hooks/useWorkLouderCodex';
+import { useXboxGamepad } from '@/hooks/useXboxGamepad';
import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
-import { WorkLouderCodexEntryContainer, WorkLouderCodexSettings } from './WorkLouderCodexSettings';
+import { WorkLouderCodexEntry, WorkLouderCodexSettings } from './WorkLouderCodexSettings';
+import { XboxGamepadEntry, XboxGamepadSettings } from './XboxGamepadSettings';
const log = createLogger('settings:keyboard-shortcuts');
+function shouldShowHardwareOutside(device: {
+ present: boolean | null | undefined;
+ enabled: boolean | undefined;
+}): boolean {
+ return device.present === true || device.enabled === true;
+}
+
+type HardwarePane = 'list' | 'accessories' | 'worklouder' | 'xbox';
+
+function AccessoriesEntry({ onOpen }: { onOpen(): void }) {
+ const { t } = useTranslation();
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ data-testid="settings-shortcuts-accessories"
+ 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.accessories.openAria')}
+ >
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <Package size={18} aria-hidden="true" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="truncate text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.shortcuts.accessories.title')}
+ </span>
+ <span className="text-12 leading-[1.4] text-[var(--text-secondary)]">
+ {t('settings.shortcuts.accessories.description')}
+ </span>
+ </span>
+ <ChevronRight size={16} className="shrink-0 text-[var(--text-tertiary)]" aria-hidden="true" />
+ </button>
+ );
+}
+
interface RecordingError {
id: AppShortcutId;
message: string;
@@ -66,7 +111,20 @@ export function KeyboardShortcutsSection() {
Record<AppShortcutId, AppShortcutCombo | null>
>;
const [recordingId, setRecordingId] = useState<AppShortcutId | null>(null);
- const [workLouderSettingsOpen, setWorkLouderSettingsOpen] = useState(false);
+ const [hardwarePane, setHardwarePane] = useState<HardwarePane>('list');
+ const [hardwareReturnTo, setHardwareReturnTo] = useState<'list' | 'accessories'>('list');
+ const workLouder = useWorkLouderCodex({ watchConnection: true });
+ const xboxGamepad = useXboxGamepad({ watchConnection: true });
+ const workLouderConnected = shouldShowHardwareOutside({
+ present: workLouder.state?.devicePresent,
+ enabled: workLouder.state?.settings.deviceEnabled,
+ });
+ const xboxConnected = shouldShowHardwareOutside({
+ present: xboxGamepad.state?.devicePresent,
+ enabled: xboxGamepad.state?.settings.deviceEnabled,
+ });
+ const hasAccessories = !workLouderConnected || !xboxConnected;
+ const showAccessoriesEntry = hasAccessories;
const [error, setError] = useState<RecordingError | null>(null);
const [globalError, setGlobalError] = useState<string | null>(null);
const mutationRequestIdRef = useRef(0);
@@ -74,9 +132,25 @@ export function KeyboardShortcutsSection() {
new URLSearchParams(window.location.search).get('workLouderCodex') === '1';
useEffect(() => {
- if (workLouderOpenRequested) setWorkLouderSettingsOpen(true);
+ if (workLouderOpenRequested) {
+ setHardwareReturnTo('list');
+ setHardwarePane('worklouder');
+ }
}, [workLouderOpenRequested]);
+ useEffect(() => {
+ if (hardwarePane === 'accessories' && !hasAccessories) setHardwarePane('list');
+ }, [hardwarePane, hasAccessories]);
+
+ const openWorkLouder = (from: 'list' | 'accessories') => {
+ setHardwareReturnTo(from);
+ setHardwarePane('worklouder');
+ };
+ const openXbox = (from: 'list' | 'accessories') => {
+ setHardwareReturnTo(from);
+ setHardwarePane('xbox');
+ };
+
const mutationErrorMessage = useCallback(
(err: unknown) => {
// Decode the IPC envelope so persistence failures never look successful.
@@ -248,8 +322,55 @@ export function KeyboardShortcutsSection() {
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)} />;
+ if (hardwarePane === 'worklouder') {
+ return <WorkLouderCodexSettings onBack={() => setHardwarePane(hardwareReturnTo)} />;
+ }
+ if (hardwarePane === 'xbox') {
+ return <XboxGamepadSettings onBack={() => setHardwarePane(hardwareReturnTo)} />;
+ }
+ if (hardwarePane === 'accessories' && hasAccessories) {
+ return (
+ <div className="flex flex-col gap-[14px]">
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => setHardwarePane('list')}
+ 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.accessories.back')}
+ >
+ <ArrowLeft size={17} />
+ </button>
+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">
+ {t('settings.shortcuts.accessories.title')}
+ </h2>
+ </div>
+ <div
+ className={cn(
+ 'flex flex-col overflow-hidden rounded-xl',
+ 'bg-[var(--settings-theme-card-bg)]',
+ 'border border-[var(--settings-theme-card-border)]',
+ '[&>*+*]:border-t [&>*+*]:border-[var(--settings-theme-card-border)]',
+ )}
+ >
+ {!workLouderConnected && (
+ <WorkLouderCodexEntry
+ state={workLouder.state}
+ loading={workLouder.loading}
+ grouped
+ onOpen={() => openWorkLouder('accessories')}
+ />
+ )}
+ {!xboxConnected && (
+ <XboxGamepadEntry
+ state={xboxGamepad.state}
+ loading={xboxGamepad.loading}
+ grouped
+ onOpen={() => openXbox('accessories')}
+ />
+ )}
+ </div>
+ </div>
+ );
}
return (
@@ -270,7 +391,21 @@ export function KeyboardShortcutsSection() {
</div>
{globalError && <span className="text-12 text-[var(--error-fg)]">{globalError}</span>}
- <WorkLouderCodexEntryContainer onOpen={() => setWorkLouderSettingsOpen(true)} />
+ {workLouderConnected && (
+ <WorkLouderCodexEntry
+ state={workLouder.state}
+ loading={workLouder.loading}
+ onOpen={() => openWorkLouder('list')}
+ />
+ )}
+ {xboxConnected && (
+ <XboxGamepadEntry
+ state={xboxGamepad.state}
+ loading={xboxGamepad.loading}
+ onOpen={() => openXbox('list')}
+ />
+ )}
+ {showAccessoriesEntry && <AccessoriesEntry onOpen={() => setHardwarePane('accessories')} />}
<div
className={cn(
diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
index 50a064e777..f335ba6fa9 100644
--- a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
@@ -37,6 +37,12 @@ import {
workLouderCodexCommandDescription,
workLouderCodexCommandName,
} from './workLouderCodexCommandCopy';
+import {
+ InputDeviceConnectionStatus,
+ inputDeviceConnectionTone,
+ inputDeviceStatusLabelKey,
+ resolveInputDeviceStatusKey,
+} from './InputDeviceConnectionStatus';
import {
WORKLOUDER_CODEX_AGENT_SOURCES,
WORKLOUDER_CODEX_ANALOG_DIRECTIONS,
@@ -111,20 +117,27 @@ function compatibleKeycapForSlot(
interface WorkLouderCodexEntryProps {
state: WorkLouderCodexState | null;
loading: boolean;
+ grouped?: boolean;
onOpen(): void;
}
-export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodexEntryProps) {
+export function WorkLouderCodexEntry({
+ state,
+ loading,
+ grouped = false,
+ onOpen,
+}: WorkLouderCodexEntryProps) {
const { t } = useTranslation();
const enabled = state?.settings.deviceEnabled ?? false;
- const status = enabled ? (state?.connectionStatus ?? 'connecting') : 'disabled';
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)]',
+ 'flex w-full items-center gap-3 text-left outline-none transition-colors',
+ grouped
+ ? 'rounded-none border-0 bg-transparent px-4 py-[14px]'
+ : 'rounded-xl border p-4 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')}
@@ -133,11 +146,8 @@ export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodex
<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 className="truncate text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.shortcuts.workLouderCodex.title')}
</span>
<span className="text-12 leading-[1.4] text-[var(--text-secondary)]">
{t('settings.shortcuts.workLouderCodex.entryDescription')}
@@ -145,8 +155,9 @@ export function WorkLouderCodexEntry({ state, loading, onOpen }: WorkLouderCodex
</span>
<span className="flex shrink-0 items-center gap-2">
<ConnectionStatus
- status={status}
+ enabled={enabled}
present={state?.devicePresent ?? null}
+ connectionStatus={state?.connectionStatus}
loading={loading}
compact
/>
@@ -387,7 +398,6 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {
<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"
@@ -413,12 +423,9 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {
aria-label={t('settings.shortcuts.workLouderCodex.connection.toggle.aria')}
/>
<ConnectionStatus
- status={
- settings.deviceEnabled
- ? (state?.connectionStatus ?? 'connecting')
- : 'disabled'
- }
+ enabled={settings.deviceEnabled}
present={state?.devicePresent ?? null}
+ connectionStatus={state?.connectionStatus}
loading={loading}
/>
</div>
@@ -1087,15 +1094,6 @@ 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)]">
@@ -1106,44 +1104,33 @@ function DeviceChip({ icon, children }: { icon?: ReactNode; children: ReactNode
}
function ConnectionStatus({
- status,
+ enabled,
present = null,
+ connectionStatus = null,
loading,
compact = false,
}: {
- status: WorkLouderCodexConnectionStatus;
+ enabled: boolean;
present?: boolean | null;
+ connectionStatus?: WorkLouderCodexConnectionStatus | null;
loading: boolean;
compact?: boolean;
}) {
const { t } = useTranslation();
- const effectiveStatus = loading && status !== 'disabled' ? 'connecting' : status;
- const label =
- effectiveStatus === 'disabled'
- ? present === true
- ? t('settings.shortcuts.workLouderCodex.connection.status.connected')
- : present === false
- ? t('settings.shortcuts.workLouderCodex.connection.status.not-detected')
- : t('settings.shortcuts.workLouderCodex.connection.status.disabled')
- : t(`settings.shortcuts.workLouderCodex.connection.status.${effectiveStatus}`);
- const dotClass =
- effectiveStatus === 'connected' || (effectiveStatus === 'disabled' && present === true)
- ? 'bg-[var(--settings-badge-connected)]'
- : effectiveStatus === 'error' || effectiveStatus === 'unavailable'
- ? 'bg-[var(--error-fg)]'
- : 'bg-[var(--text-tertiary)]';
+ const key = resolveInputDeviceStatusKey({
+ enabled,
+ present,
+ connectionStatus,
+ loading,
+ });
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',
+ <InputDeviceConnectionStatus
+ label={t(
+ `settings.shortcuts.workLouderCodex.connection.status.${inputDeviceStatusLabelKey(key)}`,
)}
- >
- <span className={cn('size-1.5 rounded-full', dotClass)} aria-hidden="true" />
- {label}
- </span>
+ tone={inputDeviceConnectionTone({ status: key, present })}
+ compact={compact}
+ />
);
}
diff --git a/apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx b/apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx
new file mode 100644
index 0000000000..77a3d19964
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx
@@ -0,0 +1,422 @@
+import type { CSSProperties } from 'react';
+
+import { Tip } from '@/components/ui/tooltip';
+import { cn } from '@/lib/utils';
+import type {
+ XboxGamepadButtonId,
+ XboxGamepadLayout as XboxGamepadLayoutModel,
+ XboxGamepadPreviewInput,
+ XboxGamepadStickId,
+} from '../../../shared/xboxGamepad';
+
+export type XboxGamepadEditablePart = XboxGamepadButtonId | XboxGamepadStickId;
+
+export interface XboxGamepadKeyHint {
+ legend: string;
+ name?: string | null;
+ description?: string | null;
+}
+
+export interface XboxGamepadLayoutProps {
+ layout: XboxGamepadLayoutModel;
+ disabled?: boolean;
+ hintFor(part: XboxGamepadEditablePart): XboxGamepadKeyHint;
+ onEdit(part: XboxGamepadEditablePart): void;
+ preview: XboxGamepadPreviewInput | null;
+ labels: {
+ leftStick: string;
+ rightStick: string;
+ };
+}
+
+/**
+ * Drawn over Dash's Xbox Series line-art in its own pixel grid, then verified
+ * by rasterizing this SVG and diffing it against that reference — every
+ * coordinate below is measured, not guessed. The viewBox is the reference
+ * crop, so a measurement on the picture can be used here as-is.
+ */
+const VIEWBOX = { x: 60, y: 80, w: 1050, h: 660 };
+
+/** Outer silhouette traced along the reference's outline stroke. */
+const BODY_PATH =
+ 'M 282 89 C 286 89 292 88 297 89 C 302 90 306 91 310 93 C 314 95 317 97 320 102 C 324 108 327 122 331 126 C 335 131 336 129 342 129 C 349 129 363 128 370 128 C 377 128 380 129 384 130 C 388 131 393 134 396 136 C 400 139 402 143 405 145 C 409 148 413 150 417 151 C 421 152 422 153 431 153 C 440 153 459 153 473 153 C 487 153 501 153 515 153 C 529 153 543 153 557 153 C 571 153 585 153 599 153 C 613 153 627 153 641 153 C 655 153 669 153 683 153 C 697 153 716 153 725 153 C 734 153 734 153 739 153 C 744 153 749 153 753 151 C 757 150 761 147 765 144 C 769 141 771 138 775 135 C 779 133 783 130 787 129 C 791 128 794 128 801 128 C 808 128 823 130 829 129 C 836 128 836 129 840 124 C 844 119 848 105 852 100 C 856 95 859 94 863 92 C 867 90 872 89 876 89 C 881 89 886 89 890 90 C 895 91 899 92 903 94 C 907 96 909 96 914 103 C 919 111 928 127 935 139 C 942 151 951 165 957 175 C 963 185 967 193 971 199 C 975 205 976 201 980 209 C 984 217 991 234 996 246 C 1001 259 1006 271 1011 284 C 1016 297 1021 310 1026 323 C 1031 336 1036 348 1041 361 C 1046 374 1051 386 1055 399 C 1060 412 1064 424 1068 437 C 1072 450 1076 463 1080 476 C 1084 489 1087 502 1090 515 C 1093 528 1096 546 1098 555 C 1100 564 1100 562 1101 569 C 1102 576 1103 588 1103 597 C 1103 606 1102 616 1101 625 C 1100 634 1099 641 1095 651 C 1091 661 1082 677 1075 686 C 1069 695 1065 699 1056 705 C 1047 711 1030 719 1020 723 C 1010 727 1001 729 994 730 C 987 731 989 732 980 730 C 971 728 954 723 941 718 C 929 713 917 705 905 698 C 893 691 881 685 869 678 C 857 671 843 663 833 658 C 823 653 820 649 809 646 C 798 643 782 640 768 639 C 754 638 740 639 726 639 C 712 639 698 639 684 639 C 670 639 656 639 642 639 C 628 639 614 639 600 639 C 586 639 572 639 558 639 C 544 639 530 639 516 639 C 502 639 488 639 474 639 C 460 639 444 639 432 639 C 420 639 413 638 404 639 C 395 640 383 642 376 643 C 369 644 371 643 363 646 C 355 650 338 658 326 664 C 314 670 302 677 290 684 C 278 691 266 698 254 704 C 242 711 228 719 218 723 C 208 727 199 729 192 730 C 185 731 187 732 178 730 C 169 728 150 723 139 719 C 129 715 121 710 115 706 C 109 702 108 700 104 697 C 101 694 98 692 94 686 C 90 680 82 668 79 662 C 76 656 76 658 74 649 C 72 640 68 620 67 608 C 66 597 66 589 67 580 C 68 571 70 563 72 552 C 74 541 77 525 80 512 C 83 499 89 482 91 473 C 93 464 93 464 94 460 C 95 456 98 451 99 447 C 100 443 99 443 102 434 C 105 426 111 409 116 396 C 121 383 126 370 131 357 C 136 344 141 332 146 319 C 151 306 156 294 161 281 C 166 268 172 254 176 243 C 180 232 183 223 186 217 C 189 211 190 209 193 205 C 196 201 197 202 202 194 C 207 186 217 170 224 158 C 231 146 238 133 244 123 C 250 113 255 104 259 99 C 264 94 267 94 271 92 C 275 90 278 90 282 89 Z';
+
+/**
+ * The d-pad is a raised cross on a disc. Each arm's sides run out to the disc
+ * edge — the edge itself closes the arm tips — and the inner corners meet in
+ * rounded fillets, so the middle is a true cross with no center plate.
+ */
+/**
+ * Public Xbox emblem (88×88), four petals. Scaled onto the guide button so
+ * the X is the leftover gap — not two crossed strokes.
+ */
+const XBOX_EMBLEM_PATH =
+ 'M39.73 86.91c-6.628-.635-13.338-3.015-19.102-6.776-4.83-3.15-5.92-4.447-5.92-7.032 0-5.193 5.71-14.29 15.48-24.658 5.547-5.89 13.275-12.79 14.11-12.604 1.626.363 14.616 13.034 19.48 19 7.69 9.43 11.224 17.154 9.428 20.597-1.365 2.617-9.837 7.733-16.06 9.698-5.13 1.62-11.867 2.306-17.416 1.775zM8.184 67.703c-4.014-6.158-6.042-12.22-7.02-20.988-.324-2.895-.21-4.55.733-10.494 1.173-7.4 5.39-15.97 10.46-21.24 2.158-2.24 2.35-2.3 4.982-1.41 3.19 1.08 6.6 3.436 11.89 8.22l3.09 2.794-1.69 2.07c-7.828 9.61-16.09 23.24-19.2 31.67-1.69 4.58-2.37 9.18-1.64 11.095.49 1.294.04.812-1.61-1.714zm70.453 1.047c.397-1.936-.105-5.49-1.28-9.076-2.545-7.765-11.054-22.21-18.867-32.032l-2.46-3.092 2.662-2.443c3.474-3.19 5.886-5.1 8.49-6.723 2.053-1.28 4.988-2.413 6.25-2.413.777 0 3.516 2.85 5.726 5.95 3.424 4.8 5.942 10.63 7.218 16.69.825 3.92.894 12.3.133 16.21-.63 3.208-1.95 7.366-3.23 10.187-.97 2.113-3.36 6.218-4.41 7.554-.54.687-.54.686-.24-.796zM40.44 11.505C36.834 9.675 31.272 7.71 28.2 7.18c-1.076-.185-2.913-.29-4.08-.23-2.536.128-2.423-.004 1.643-1.925 3.38-1.597 6.2-2.536 10.03-3.34C40.098.78 48.193.77 52.43 1.663c4.575.965 9.964 2.97 13 4.84l.904.554-2.07-.104C60.148 6.745 54.15 8.408 47.71 11.54c-1.942.946-3.63 1.7-3.754 1.68-.123-.024-1.706-.795-3.52-1.715z';
+
+const DPAD_DISC = { cx: 447, cy: 522, rx: 75, ry: 72 };
+
+/**
+ * Arm sides run out to the disc. Endpoints are the ellipse intersections so
+ * the disc stroke itself closes each tip — no flat chord.
+ */
+const DPAD_CROSS_PATH = [
+ 'M 421 454.5 V 486 Q 421 496 411 496 H 377.1',
+ 'M 377.1 548 H 411 Q 421 548 421 558 V 589.5',
+ 'M 473 589.5 V 558 Q 473 548 483 548 H 516.9',
+ 'M 516.9 496 H 483 Q 473 496 473 486 V 454.5',
+].join(' ');
+
+type Point = [number, number];
+
+const LEFT_STICK: Point = [311, 366];
+const RIGHT_STICK: Point = [724, 524];
+const FACE: Record<'y' | 'x' | 'b' | 'a', Point> = {
+ y: [861, 296],
+ x: [787, 369],
+ b: [931, 360],
+ a: [860, 432],
+};
+
+/** Backing color for carved / inverted glyphs — the card the drawing sits on. */
+const CARVE = 'var(--settings-theme-card-bg)';
+
+/** Shared press overlay — same gray on every control. */
+const PRESS_FILL = 'currentColor';
+const PRESS_OPACITY = 0.2;
+
+export function XboxGamepadLayout({
+ disabled = false,
+ hintFor,
+ onEdit,
+ preview,
+ labels,
+}: XboxGamepadLayoutProps) {
+ const pressed = (id: XboxGamepadButtonId) => preview?.buttons[id] ?? false;
+ const analog = (id: XboxGamepadStickId) => preview?.sticks[id] ?? { x: 0, y: 0 };
+ const trigger = (id: 'lt' | 'rt') => preview?.triggers[id] ?? 0;
+
+ return (
+ <div
+ className="relative mx-auto w-full max-w-[560px] text-[var(--text-primary)]"
+ data-testid="xbox-gamepad-layout"
+ style={{ aspectRatio: `${VIEWBOX.w} / ${VIEWBOX.h}` }}
+ >
+ <svg
+ viewBox={`${VIEWBOX.x} ${VIEWBOX.y} ${VIEWBOX.w} ${VIEWBOX.h}`}
+ className="pointer-events-none absolute inset-0 h-full w-full"
+ aria-hidden="true"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2.6"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ >
+ <path d={BODY_PATH} strokeWidth="3" />
+
+ {/* Trigger horns light up on pull; the horn itself is part of the outline. */}
+ <HornFill side="left" on={pressed('lt') || trigger('lt') > 0.08} />
+ <HornFill side="right" on={pressed('rt') || trigger('rt') > 0.08} />
+
+ {/*
+ * The bumper bar is its own plastic piece. Its top edge runs from the
+ * shoulder tip, behind the trigger horn, down onto the deck; the seam
+ * below runs tip to tip; the short vertical notches are where LB / RB
+ * end against the center deck.
+ */}
+ <path d="M 205 198 C 214 178 226 161 240 149 C 272 143 300 140 332 137 C 362 139 390 145 416 152" />
+ <path d="M 965 198 C 956 178 944 161 930 149 C 898 143 870 140 838 137 C 808 139 780 145 754 152" />
+ <path d="M 205 199 C 290 191 360 188 435 188 C 535 186 635 186 735 188 C 810 188 880 191 965 199" />
+ <path d="M 437 154 L 435 187 M 736 152 L 734 187" />
+ <path d="M 440 172 C 545 170 640 170 731 172" />
+ <BumperFill side="left" on={pressed('lb')} />
+ <BumperFill side="right" on={pressed('rb')} />
+
+ {/* Pairing oval and its ))) marks. */}
+ <ellipse cx="505" cy="164" rx="12" ry="6" />
+ <path d="M 527 159 C 529 162 529 166 527 169 M 535 158 C 538 161 538 167 535 170 M 543 156 C 547 160 547 168 543 172" />
+
+ {/* Each trigger horn's near edge, wrapping down to the bumper. */}
+ <path d="M 262 141 C 264 130 266 119 270 108 M 908 141 C 906 130 904 119 900 108" />
+
+ <Stick center={LEFT_STICK} analog={analog('left')} clicked={pressed('ls')} />
+ <Stick center={RIGHT_STICK} analog={analog('right')} clicked={pressed('rs')} />
+
+ {/* D-pad disc and raised cross; pressed fill is clipped to the disc so tips follow the rim. */}
+ <ellipse cx={DPAD_DISC.cx} cy={DPAD_DISC.cy} rx={DPAD_DISC.rx} ry={DPAD_DISC.ry} />
+ <path d={DPAD_CROSS_PATH} />
+ <clipPath id="xbox-dpad-disc">
+ <ellipse cx={DPAD_DISC.cx} cy={DPAD_DISC.cy} rx={DPAD_DISC.rx} ry={DPAD_DISC.ry} />
+ </clipPath>
+ <g clipPath="url(#xbox-dpad-disc)" fill={PRESS_FILL} fillOpacity={PRESS_OPACITY} stroke="none">
+ {pressed('dpadUp') && <rect x="421" y="448" width="52" height="48" />}
+ {pressed('dpadDown') && <rect x="421" y="548" width="52" height="48" />}
+ {pressed('dpadLeft') && <rect x="370" y="496" width="51" height="52" />}
+ {pressed('dpadRight') && <rect x="473" y="496" width="51" height="52" />}
+ </g>
+
+ <FaceButton center={FACE.y} label="Y" pressed={pressed('y')} />
+ <FaceButton center={FACE.x} label="X" pressed={pressed('x')} />
+ <FaceButton center={FACE.b} label="B" pressed={pressed('b')} />
+ <FaceButton center={FACE.a} label="A" pressed={pressed('a')} />
+
+ {/* View: two stacked screens, front one occludes the back. */}
+ <circle
+ cx="509"
+ cy="369"
+ r="22"
+ fill={pressed('view') ? PRESS_FILL : 'none'}
+ fillOpacity={pressed('view') ? PRESS_OPACITY : undefined}
+ />
+ <g stroke="currentColor" strokeWidth="1.8">
+ <rect x="500" y="360" width="11" height="11" rx="1.6" fill="none" />
+ <rect x="507" y="366" width="11" height="11" rx="1.6" fill={CARVE} />
+ </g>
+ <circle
+ cx="661"
+ cy="369"
+ r="22"
+ fill={pressed('menu') ? PRESS_FILL : 'none'}
+ fillOpacity={pressed('menu') ? PRESS_OPACITY : undefined}
+ />
+ <path d="M 654 362 H 668 M 654 369 H 668 M 654 376 H 668" stroke="currentColor" strokeWidth="2" />
+ {/* Share is decor: empty pill, no binding slot. */}
+ <rect x="561.51" y="412.85" width="46.98" height="24.3" rx="12.15" />
+
+ {/* Xbox guide: official four-petal emblem. The X is the gap between the leaves. */}
+ <g transform="translate(546 222) scale(0.8409)" fill="currentColor" stroke="none">
+ <path d={XBOX_EMBLEM_PATH} />
+ </g>
+ {pressed('xbox') && (
+ <circle cx="583" cy="259" r="37" fill={PRESS_FILL} fillOpacity={PRESS_OPACITY} stroke="none" />
+ )}
+ </svg>
+
+ <Hit part="lt" hint={hintFor('lt')} disabled={disabled} pressed={pressed('lt')} onEdit={onEdit} box={[238, 86, 96, 62]} />
+ <Hit part="rt" hint={hintFor('rt')} disabled={disabled} pressed={pressed('rt')} onEdit={onEdit} box={[836, 86, 96, 62]} />
+ <Hit part="lb" hint={hintFor('lb')} disabled={disabled} pressed={pressed('lb')} onEdit={onEdit} box={[205, 136, 232, 64]} />
+ <Hit part="rb" hint={hintFor('rb')} disabled={disabled} pressed={pressed('rb')} onEdit={onEdit} box={[734, 136, 231, 64]} />
+
+ <Hit part="xbox" hint={hintFor('xbox')} disabled={disabled} pressed={pressed('xbox')} onEdit={onEdit} box={[546, 222, 74, 74]} round />
+ <Hit part="view" hint={hintFor('view')} disabled={disabled} pressed={pressed('view')} onEdit={onEdit} box={[485, 345, 48, 48]} round />
+ <Hit part="menu" hint={hintFor('menu')} disabled={disabled} pressed={pressed('menu')} onEdit={onEdit} box={[637, 345, 48, 48]} round />
+
+ <Hit
+ part="left"
+ hint={hintFor('left')}
+ disabled={disabled}
+ pressed={pressed('ls')}
+ onEdit={onEdit}
+ box={[234, 292, 154, 148]}
+ round
+ testId="xbox-gamepad-stick-left"
+ title={labels.leftStick}
+ />
+ <Hit
+ part="right"
+ hint={hintFor('right')}
+ disabled={disabled}
+ pressed={pressed('rs')}
+ onEdit={onEdit}
+ box={[647, 449, 154, 150]}
+ round
+ testId="xbox-gamepad-stick-right"
+ title={labels.rightStick}
+ />
+
+ <div data-testid="xbox-gamepad-face">
+ <Hit part="y" hint={hintFor('y')} disabled={disabled} pressed={pressed('y')} onEdit={onEdit} box={[825, 260, 72, 72]} round />
+ <Hit part="x" hint={hintFor('x')} disabled={disabled} pressed={pressed('x')} onEdit={onEdit} box={[751, 333, 72, 72]} round />
+ <Hit part="b" hint={hintFor('b')} disabled={disabled} pressed={pressed('b')} onEdit={onEdit} box={[895, 324, 72, 72]} round />
+ <Hit part="a" hint={hintFor('a')} disabled={disabled} pressed={pressed('a')} onEdit={onEdit} box={[824, 396, 72, 72]} round />
+ </div>
+
+ <div data-testid="xbox-gamepad-dpad">
+ <Hit part="dpadUp" hint={hintFor('dpadUp')} disabled={disabled} pressed={pressed('dpadUp')} onEdit={onEdit} box={[423, 459, 52, 38]} />
+ <Hit part="dpadLeft" hint={hintFor('dpadLeft')} disabled={disabled} pressed={pressed('dpadLeft')} onEdit={onEdit} box={[383, 497, 40, 52]} />
+ <Hit part="dpadRight" hint={hintFor('dpadRight')} disabled={disabled} pressed={pressed('dpadRight')} onEdit={onEdit} box={[475, 497, 42, 52]} />
+ <Hit part="dpadDown" hint={hintFor('dpadDown')} disabled={disabled} pressed={pressed('dpadDown')} onEdit={onEdit} box={[423, 549, 52, 40]} />
+ </div>
+ </div>
+ );
+}
+
+function boxStyle([x, y, w, h]: [number, number, number, number]): CSSProperties {
+ return {
+ left: `${((x - VIEWBOX.x) / VIEWBOX.w) * 100}%`,
+ top: `${((y - VIEWBOX.y) / VIEWBOX.h) * 100}%`,
+ width: `${(w / VIEWBOX.w) * 100}%`,
+ height: `${(h / VIEWBOX.h) * 100}%`,
+ };
+}
+
+function Hit({
+ part,
+ hint,
+ disabled,
+ pressed,
+ onEdit,
+ box,
+ round = false,
+ testId,
+ title,
+}: {
+ part: XboxGamepadEditablePart;
+ hint: XboxGamepadKeyHint;
+ disabled: boolean;
+ pressed: boolean;
+ onEdit(part: XboxGamepadEditablePart): void;
+ box: [number, number, number, number];
+ round?: boolean;
+ testId?: string;
+ title?: string;
+}) {
+ const label = [hint.legend, hint.name].filter(Boolean).join(' ');
+ return (
+ <Tip text={<KeyHint hint={hint} />} side="top">
+ <button
+ type="button"
+ aria-label={label}
+ aria-pressed={pressed}
+ title={title}
+ disabled={disabled}
+ data-testid={testId}
+ onClick={() => onEdit(part)}
+ style={boxStyle(box)}
+ className={cn(
+ 'absolute z-[1] border-0 bg-transparent',
+ round ? 'rounded-full' : 'rounded-[8px]',
+ !disabled && 'cursor-pointer',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ disabled && 'cursor-not-allowed opacity-60',
+ )}
+ />
+ </Tip>
+ );
+}
+
+/** Translucent fill inside the horn outline while the trigger is pulled. */
+function HornFill({ side, on }: { side: 'left' | 'right'; on: boolean }) {
+ if (!on) return null;
+ const d =
+ side === 'left'
+ ? [
+ 'M 224 158',
+ 'C 231 146 238 133 244 123',
+ 'C 250 113 255 104 259 99',
+ 'C 264 94 267 94 271 92',
+ 'C 275 90 278 90 282 89',
+ 'C 286 89 292 88 297 89',
+ 'C 302 90 306 91 310 93',
+ 'C 314 95 317 97 320 102',
+ 'C 324 108 327 122 331 126',
+ 'L 332 137',
+ 'C 300 140 272 143 240 149',
+ 'Z',
+ ].join(' ')
+ : [
+ 'M 840 124',
+ 'C 844 119 848 105 852 100',
+ 'C 856 95 859 94 863 92',
+ 'C 867 90 872 89 876 89',
+ 'C 881 89 886 89 890 90',
+ 'C 895 91 899 92 903 94',
+ 'C 907 96 909 96 914 103',
+ 'C 919 111 928 127 935 139',
+ 'L 930 149',
+ 'C 898 143 870 140 838 137',
+ 'Z',
+ ].join(' ');
+ return <path d={d} fill={PRESS_FILL} fillOpacity={PRESS_OPACITY} stroke="none" />;
+}
+
+/** Translucent fill over the bumper segment while it is held. */
+function BumperFill({ side, on }: { side: 'left' | 'right'; on: boolean }) {
+ if (!on) return null;
+ const d =
+ side === 'left'
+ ? 'M 205 198 C 214 178 226 161 240 149 C 272 143 300 140 332 137 C 362 139 390 145 416 152 L 437 154 L 435 188 C 360 188 290 191 205 199 Z'
+ : 'M 965 198 C 956 178 944 161 930 149 C 898 143 870 140 838 137 C 808 139 780 145 754 152 L 736 152 L 734 188 C 810 188 880 191 965 199 Z';
+ return <path d={d} fill={PRESS_FILL} fillOpacity={PRESS_OPACITY} stroke="none" />;
+}
+
+/**
+ * A stick seen from above. The camera looks down into the recessed well, so
+ * everything stacks toward the near (lower) side: the cap sits low in the
+ * well, the concave top's floor sits low inside the cap — you look into the
+ * dish, its far wall visible at the top. The leftover far-rim arc is completed
+ * into a full circle behind the cap so the socket can be judged as a ring.
+ * The cap group follows the live analog value.
+ */
+function Stick({
+ center,
+ analog,
+ clicked,
+}: {
+ center: Point;
+ analog: { x: number; y: number };
+ clicked: boolean;
+}) {
+ const [cx, cy] = center;
+ const dx = Math.max(-1, Math.min(1, analog.x)) * 14;
+ const dy = -Math.max(-1, Math.min(1, analog.y)) * 14;
+ return (
+ <g>
+ <ellipse cx={cx} cy={cy} rx="77" ry="72" />
+ {/* Full socket circle fitted to the leftover far-rim crescent. */}
+ <circle cx={cx - 2} cy={cy - 3.2} r="44.8" />
+ <g transform={`translate(${dx} ${dy})`}>
+ <circle cx={cx - 2} cy={cy + 14} r="53" fill={CARVE} />
+ {clicked && (
+ <circle cx={cx - 2} cy={cy + 14} r="53" fill={PRESS_FILL} fillOpacity={PRESS_OPACITY} />
+ )}
+ <circle cx={cx - 3} cy={cy + 22} r="41" />
+ </g>
+ </g>
+ );
+}
+
+function FaceButton({
+ center,
+ label,
+ pressed,
+}: {
+ center: Point;
+ label: string;
+ pressed: boolean;
+}) {
+ const [cx, cy] = center;
+ return (
+ <g>
+ <circle
+ cx={cx}
+ cy={cy}
+ r="36"
+ fill={pressed ? PRESS_FILL : 'none'}
+ fillOpacity={pressed ? PRESS_OPACITY : undefined}
+ />
+ <text
+ x={cx}
+ y={cy + 2}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ fill="currentColor"
+ stroke="none"
+ fontSize="28"
+ fontWeight="600"
+ fontFamily="Inter, system-ui, sans-serif"
+ >
+ {label}
+ </text>
+ </g>
+ );
+}
+
+function KeyHint({ hint }: { hint: XboxGamepadKeyHint }) {
+ 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>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx b/apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx
new file mode 100644
index 0000000000..cf6d97970f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx
@@ -0,0 +1,765 @@
+import { useEffect, useMemo, useState, type ReactNode } from 'react';
+import {
+ ArrowLeft,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ ChevronUp,
+ BatteryCharging,
+ Bluetooth,
+ Gamepad2,
+ RotateCcw,
+ Usb,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import * as Dialog from '@radix-ui/react-dialog';
+import * as Select from '@radix-ui/react-select';
+
+import { Switch } from '@/components/ui/switch';
+import { useXboxGamepad } from '@/hooks/useXboxGamepad';
+import { useSkillhub } from '@/features/skillhub/hooks/useSkillhub';
+import { cn } from '@/lib/utils';
+import {
+ InputDeviceConnectionStatus,
+ inputDeviceConnectionTone,
+ inputDeviceStatusLabelKey,
+ resolveInputDeviceStatusKey,
+} from './InputDeviceConnectionStatus';
+import {
+ workLouderCodexCommandDescription,
+ workLouderCodexCommandName,
+} from './workLouderCodexCommandCopy';
+import {
+ XboxGamepadLayout,
+ type XboxGamepadEditablePart,
+ type XboxGamepadKeyHint,
+} from './XboxGamepadLayout';
+import { INPUT_DEVICE_COMMAND_IDS, type InputDeviceCommandId } from '../../../shared/inputDevices';
+import {
+ cloneXboxGamepadLayout,
+ createXboxGamepadDefaultLayout,
+ createXboxGamepadDefaultSettings,
+ XBOX_GAMEPAD_STICK_DIRECTIONS,
+ type XboxGamepadBinding,
+ type XboxGamepadButtonId,
+ type XboxGamepadConnectionStatus,
+ type XboxGamepadDeviceInfo,
+ type XboxGamepadLayout as XboxGamepadLayoutModel,
+ type XboxGamepadPreviewInput,
+ type XboxGamepadSettings as XboxGamepadSettingsModel,
+ type XboxGamepadState,
+ type XboxGamepadStickId,
+ type XboxGamepadStickMode,
+} from '../../../shared/xboxGamepad';
+
+function ConnectionBadge({
+ state,
+ loading,
+ compact = false,
+}: {
+ state: XboxGamepadState | null;
+ loading: boolean;
+ compact?: boolean;
+}) {
+ const { t } = useTranslation();
+ const key = resolveInputDeviceStatusKey({
+ enabled: state?.settings.deviceEnabled ?? false,
+ present: state?.devicePresent,
+ connectionStatus: state?.connectionStatus,
+ loading,
+ });
+ return (
+ <InputDeviceConnectionStatus
+ label={t(
+ `settings.shortcuts.xboxGamepad.connection.status.${inputDeviceStatusLabelKey(key)}`,
+ )}
+ tone={inputDeviceConnectionTone({ status: key, present: state?.devicePresent })}
+ compact={compact}
+ />
+ );
+}
+
+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 XboxDeviceChips({ device }: { device: XboxGamepadDeviceInfo }) {
+ const { t } = useTranslation();
+ const label = deviceTitle(device);
+ return (
+ <div className="flex flex-wrap gap-2 pt-1">
+ {label && (
+ <DeviceChip icon={<Gamepad2 size={12} />}>{label}</DeviceChip>
+ )}
+ {device.transport === 'usb' && (
+ <DeviceChip icon={<Usb size={12} />}>
+ {t('settings.shortcuts.xboxGamepad.device.usb')}
+ </DeviceChip>
+ )}
+ {device.transport === 'bluetooth' && (
+ <DeviceChip icon={<Bluetooth size={12} />}>
+ {t('settings.shortcuts.xboxGamepad.device.bluetooth')}
+ </DeviceChip>
+ )}
+ {device.batteryPercentage !== null && (
+ <DeviceChip
+ icon={device.batteryState === 'charging' ? <BatteryCharging size={12} /> : undefined}
+ >
+ {device.batteryState === 'charging'
+ ? t('settings.shortcuts.xboxGamepad.device.charging', {
+ percent: device.batteryPercentage,
+ })
+ : t('settings.shortcuts.xboxGamepad.device.battery', {
+ percent: device.batteryPercentage,
+ })}
+ </DeviceChip>
+ )}
+ </div>
+ );
+}
+
+function deviceTitle(device: XboxGamepadDeviceInfo): string | null {
+ const name = device.name?.trim() ?? '';
+ const category = device.category?.trim() ?? '';
+ if (name && name.toLowerCase() !== 'controller') return name;
+ if (category) return category;
+ return name || null;
+}
+
+export function XboxGamepadEntry({
+ state,
+ loading,
+ grouped = false,
+ onOpen,
+}: {
+ state: XboxGamepadState | null;
+ loading: boolean;
+ grouped?: boolean;
+ onOpen(): void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className={cn(
+ 'flex w-full items-center gap-3 text-left outline-none transition-colors',
+ grouped
+ ? 'rounded-none border-0 bg-transparent px-4 py-[14px]'
+ : 'rounded-xl border p-4 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.xboxGamepad.openAria')}
+ >
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <Gamepad2 size={18} aria-hidden="true" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="truncate text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.shortcuts.xboxGamepad.title')}
+ </span>
+ <span className="text-12 leading-[1.4] text-[var(--text-secondary)]">
+ {t('settings.shortcuts.xboxGamepad.entryDescription')}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-2">
+ <ConnectionBadge state={state} loading={loading} compact />
+ <ChevronRight size={16} className="text-[var(--text-tertiary)]" aria-hidden="true" />
+ </span>
+ </button>
+ );
+}
+
+export function XboxGamepadEntryContainer({ onOpen }: { onOpen(): void }) {
+ const { state, loading } = useXboxGamepad({ watchConnection: true });
+ return <XboxGamepadEntry state={state} loading={loading} onOpen={onOpen} />;
+}
+
+function isStickPart(part: XboxGamepadEditablePart): part is XboxGamepadStickId {
+ return part === 'left' || part === 'right';
+}
+
+function stickClickButton(stick: XboxGamepadStickId): XboxGamepadButtonId {
+ return stick === 'left' ? 'ls' : 'rs';
+}
+
+export function XboxGamepadSettings({ onBack }: { onBack(): void }) {
+ const { t } = useTranslation();
+ const { state, loading, saving, error, setSettings, resetSettings, reload } = useXboxGamepad({
+ watchConnection: true,
+ });
+ const { skills, bootstrapped, refresh: refreshSkills } = useSkillhub();
+ const [preview, setPreview] = useState<XboxGamepadPreviewInput | null>(null);
+ const [editing, setEditing] = useState<XboxGamepadEditablePart | null>(null);
+ const settings = resolveXboxGamepadSettings(state?.settings);
+ const enabled = settings.deviceEnabled;
+ const key = resolveInputDeviceStatusKey({
+ enabled,
+ present: state?.devicePresent,
+ connectionStatus: state?.connectionStatus,
+ loading,
+ });
+ const enabledSkills = useMemo(
+ () => skills.filter((skill) => skill.kind === 'skill' && !skill.parseError),
+ [skills],
+ );
+ const isDefault =
+ state !== null && xboxGamepadSettingsMatchRestoreDefaults(settings);
+
+ useEffect(() => {
+ if (!bootstrapped) void refreshSkills();
+ }, [bootstrapped, refreshSkills]);
+
+ useEffect(() => {
+ const api = window.electronAPI?.xboxGamepad;
+ void api?.setLayoutPreviewActive?.(true);
+ return () => {
+ void api?.setLayoutPreviewActive?.(false);
+ };
+ }, []);
+
+ useEffect(() => {
+ const unsubscribe = window.electronAPI?.xboxGamepad?.onPreviewInput?.((input) => {
+ setPreview(input);
+ });
+ return () => unsubscribe?.();
+ }, []);
+
+ const patchLayout = (update: (layout: XboxGamepadLayoutModel) => void): void => {
+ if (!state) return;
+ const layout = cloneXboxGamepadLayout(settings.layout);
+ update(layout);
+ void setSettings({ layout });
+ };
+
+ const hintFor = (part: XboxGamepadEditablePart): XboxGamepadKeyHint => {
+ if (isStickPart(part)) {
+ const stick = settings.layout.sticks[part];
+ return {
+ legend: t(`settings.shortcuts.xboxGamepad.controls.${part}Stick`),
+ name: stick
+ ? t(`settings.shortcuts.xboxGamepad.stick.mode.options.${stick.mode}`)
+ : undefined,
+ description: t('settings.shortcuts.xboxGamepad.layout.clickToEdit'),
+ };
+ }
+ const binding = settings.layout.buttons[part] ?? null;
+ return {
+ legend: t(`settings.shortcuts.xboxGamepad.controls.${part}`),
+ name: bindingLabel(binding, t) ?? t('settings.shortcuts.xboxGamepad.actions.none'),
+ description:
+ binding?.type === 'command'
+ ? workLouderCodexCommandDescription(t, binding.commandId)
+ : binding?.type === 'voice'
+ ? t('settings.shortcuts.xboxGamepad.actions.voiceDescription')
+ : t('settings.shortcuts.xboxGamepad.layout.clickToEdit'),
+ };
+ };
+
+ 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.xboxGamepad.back')}
+ >
+ <ArrowLeft size={17} />
+ </button>
+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">
+ {t('settings.shortcuts.xboxGamepad.title')}
+ </h2>
+ </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>
+
+ {error && (
+ <div className="flex items-center justify-between gap-3 text-12 text-[var(--error-fg)]">
+ <span>{t(`settings.shortcuts.xboxGamepad.errors.${error}`)}</span>
+ <button type="button" onClick={() => void reload()} className="underline">
+ {t('settings.shortcuts.xboxGamepad.retry')}
+ </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.xboxGamepad.connection.toggle.label')}
+ </p>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={enabled}
+ disabled={loading || saving || !state}
+ onCheckedChange={(next) => {
+ void setSettings({ deviceEnabled: next });
+ }}
+ aria-label={t('settings.shortcuts.xboxGamepad.connection.toggle.aria')}
+ />
+ <ConnectionBadge state={state} loading={loading} />
+ </div>
+ </div>
+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">
+ {t(`settings.shortcuts.xboxGamepad.connection.descriptions.${key}`)}
+ </p>
+ {state?.devicePresent && <XboxDeviceChips device={state.device} />}
+ </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.xboxGamepad.layout.title')}
+ </h3>
+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">
+ {t('settings.shortcuts.xboxGamepad.layout.description')}
+ </p>
+ </div>
+ <div className="flex justify-center">
+ <XboxGamepadLayout
+ layout={settings.layout}
+ disabled={!state || saving}
+ hintFor={hintFor}
+ onEdit={setEditing}
+ preview={preview}
+ labels={{
+ leftStick: t('settings.shortcuts.xboxGamepad.controls.leftStick'),
+ rightStick: t('settings.shortcuts.xboxGamepad.controls.rightStick'),
+ }}
+ />
+ </div>
+ </SettingsCard>
+
+ <XboxGamepadPartEditor
+ open={editing !== null && !isStickPart(editing)}
+ onOpenChange={(open) => {
+ if (!open) setEditing(null);
+ }}
+ title={
+ editing && !isStickPart(editing)
+ ? t(`settings.shortcuts.xboxGamepad.controls.${editing}`)
+ : t('settings.shortcuts.xboxGamepad.layout.editor.title')
+ }
+ description={t('settings.shortcuts.xboxGamepad.layout.editor.description')}
+ closeLabel={t('settings.shortcuts.xboxGamepad.layout.editor.done')}
+ >
+ {editing && !isStickPart(editing) && settings && (
+ <SettingsRow
+ label={t('settings.shortcuts.xboxGamepad.layout.editor.assigned')}
+ description={t('settings.shortcuts.xboxGamepad.layout.editor.assignedDescription')}
+ control={
+ <BindingSelect
+ binding={settings.layout.buttons[editing]}
+ skills={enabledSkills}
+ disabled={!state || saving}
+ allowVoice
+ onChange={(binding) =>
+ patchLayout((layout) => {
+ layout.buttons[editing] = binding;
+ })
+ }
+ />
+ }
+ />
+ )}
+ </XboxGamepadPartEditor>
+
+ <XboxGamepadPartEditor
+ open={editing !== null && isStickPart(editing)}
+ onOpenChange={(open) => {
+ if (!open) setEditing(null);
+ }}
+ title={
+ editing && isStickPart(editing)
+ ? t(`settings.shortcuts.xboxGamepad.controls.${editing}Stick`)
+ : t('settings.shortcuts.xboxGamepad.layout.editor.title')
+ }
+ description={t('settings.shortcuts.xboxGamepad.stick.description')}
+ closeLabel={t('settings.shortcuts.xboxGamepad.layout.editor.done')}
+ >
+ {editing && isStickPart(editing) && settings && (
+ <div className="flex flex-col gap-3">
+ <SettingsRow
+ label={t('settings.shortcuts.xboxGamepad.stick.mode.label')}
+ description={t('settings.shortcuts.xboxGamepad.stick.mode.description')}
+ control={
+ <SelectControl
+ value={settings.layout.sticks[editing].mode}
+ disabled={!state || saving}
+ ariaLabel={t('settings.shortcuts.xboxGamepad.stick.mode.label')}
+ onChange={(value) =>
+ patchLayout((layout) => {
+ layout.sticks[editing].mode = value as XboxGamepadStickMode;
+ })
+ }
+ options={[
+ {
+ value: 'conversation-scroll',
+ label: t('settings.shortcuts.xboxGamepad.stick.mode.options.conversation-scroll'),
+ },
+ {
+ value: 'custom',
+ label: t('settings.shortcuts.xboxGamepad.stick.mode.options.custom'),
+ },
+ ]}
+ />
+ }
+ />
+ {settings.layout.sticks[editing].mode === 'custom' &&
+ XBOX_GAMEPAD_STICK_DIRECTIONS.map((direction) => (
+ <div key={direction}>
+ <SettingsDivider />
+ <SettingsRow
+ label={t(`settings.shortcuts.xboxGamepad.directions.${direction}`)}
+ description={t('settings.shortcuts.xboxGamepad.stick.customDescription')}
+ control={
+ <BindingSelect
+ binding={settings.layout.sticks[editing].directions[direction]}
+ skills={enabledSkills}
+ disabled={!state || saving}
+ onChange={(binding) =>
+ patchLayout((layout) => {
+ layout.sticks[editing].directions[direction] = binding;
+ })
+ }
+ />
+ }
+ />
+ </div>
+ ))}
+ <SettingsDivider />
+ <SettingsRow
+ label={t(`settings.shortcuts.xboxGamepad.controls.${stickClickButton(editing)}`)}
+ description={t('settings.shortcuts.xboxGamepad.layout.editor.assignedDescription')}
+ control={
+ <BindingSelect
+ binding={settings.layout.buttons[stickClickButton(editing)]}
+ skills={enabledSkills}
+ disabled={!state || saving}
+ allowVoice
+ onChange={(binding) =>
+ patchLayout((layout) => {
+ layout.buttons[stickClickButton(editing)] = binding;
+ })
+ }
+ />
+ }
+ />
+ </div>
+ )}
+ </XboxGamepadPartEditor>
+
+ <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.xboxGamepad.layout.reset.title')}
+ </p>
+ <p className="text-12 leading-[1.45] text-[var(--text-secondary)]">
+ {t('settings.shortcuts.xboxGamepad.layout.reset.description')}
+ </p>
+ </div>
+ <button
+ type="button"
+ disabled={!state || saving}
+ onClick={() => void resetSettings()}
+ 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.xboxGamepad.layout.reset.button')}
+ </button>
+ </SettingsCard>
+ </div>
+ );
+}
+
+function XboxGamepadPartEditor({
+ 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>
+ );
+}
+
+function BindingSelect({
+ binding,
+ skills,
+ disabled,
+ allowVoice = false,
+ onChange,
+}: {
+ binding: XboxGamepadBinding | null;
+ skills: Array<{ id: string; name: string }>;
+ disabled: boolean;
+ allowVoice?: boolean;
+ onChange(binding: XboxGamepadBinding | null): void;
+}) {
+ const { t } = useTranslation();
+ const groups: SelectOptionGroup[] = [{ options: [{ value: 'none', label: t('settings.shortcuts.xboxGamepad.actions.none') }] }];
+ if (allowVoice) {
+ groups.push({
+ options: [{ value: 'voice', label: t('settings.shortcuts.xboxGamepad.actions.voice') }],
+ });
+ }
+ groups.push({
+ label: t('settings.shortcuts.xboxGamepad.actions.commands'),
+ options: INPUT_DEVICE_COMMAND_IDS.map((commandId) => ({
+ value: `command:${commandId}`,
+ label: workLouderCodexCommandName(t, commandId),
+ })),
+ });
+ if (skills.length > 0) {
+ groups.push({
+ label: t('settings.shortcuts.xboxGamepad.actions.skills'),
+ options: skills.map((skill) => ({
+ value: `skill:${skill.id}`,
+ label: skill.name,
+ })),
+ });
+ }
+ return (
+ <SelectControl
+ value={bindingValue(binding)}
+ disabled={disabled}
+ ariaLabel={t('settings.shortcuts.xboxGamepad.actions.choose')}
+ onChange={(value) => onChange(parseBindingValue(value, skills))}
+ className="min-w-[190px]"
+ groups={groups}
+ />
+ );
+}
+
+interface SelectOption {
+ value: string;
+ label: string;
+}
+
+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}
+ 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',
+ )}
+ >
+ <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 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 resolveXboxGamepadSettings(
+ settings: XboxGamepadSettingsModel | undefined,
+): XboxGamepadSettingsModel {
+ if (!settings) return createXboxGamepadDefaultSettings();
+ if (settings.layout?.buttons && settings.layout.sticks) return settings;
+ return { ...settings, layout: createXboxGamepadDefaultLayout() };
+}
+
+function xboxGamepadSettingsMatchRestoreDefaults(settings: XboxGamepadSettingsModel): boolean {
+ return (
+ JSON.stringify({ ...settings, deviceEnabled: false }) ===
+ JSON.stringify({ ...createXboxGamepadDefaultSettings(), deviceEnabled: false })
+ );
+}
+
+function bindingLabel(
+ binding: XboxGamepadBinding | null,
+ t: ReturnType<typeof useTranslation>['t'],
+): string | null {
+ if (!binding) return null;
+ if (binding.type === 'command') return workLouderCodexCommandName(t, binding.commandId);
+ if (binding.type === 'skill') return binding.name;
+ return t('settings.shortcuts.xboxGamepad.actions.voice');
+}
+
+function bindingValue(binding: XboxGamepadBinding | null): string {
+ if (!binding) return 'none';
+ if (binding.type === 'command') return `command:${binding.commandId}`;
+ if (binding.type === 'skill') return `skill:${binding.skillId}`;
+ return 'voice';
+}
+
+function parseBindingValue(
+ value: string,
+ skills: Array<{ id: string; name: string }>,
+): XboxGamepadBinding | null {
+ if (value === 'none') return null;
+ if (value === 'voice') return { type: 'voice' };
+ if (value.startsWith('command:')) {
+ return { type: 'command', commandId: value.slice(8) as InputDeviceCommandId };
+ }
+ 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;
+ }
+ return null;
+}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/InputDeviceConnectionStatus.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/InputDeviceConnectionStatus.test.tsx
new file mode 100644
index 0000000000..00d6e99d3b
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/InputDeviceConnectionStatus.test.tsx
@@ -0,0 +1,48 @@
+// @vitest-environment jsdom
+
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import {
+ InputDeviceConnectionStatus,
+ inputDeviceConnectionTone,
+ resolveInputDeviceStatusKey,
+} from '../InputDeviceConnectionStatus';
+
+describe('InputDeviceConnectionStatus', () => {
+ it('renders the same status-dot + label for every device', () => {
+ const { container } = render(
+ <InputDeviceConnectionStatus label="未检测到" tone="neutral" compact />,
+ );
+
+ expect(screen.getByText('未检测到')).toBeTruthy();
+ expect(container.querySelector('[aria-hidden="true"]')).toBeTruthy();
+ });
+
+ it('uses Off for every unused accessory, and Not detected only after it is enabled', () => {
+ expect(
+ resolveInputDeviceStatusKey({ enabled: false, present: false, connectionStatus: 'not-detected' }),
+ ).toBe('disabled');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: false, present: null, connectionStatus: 'connecting' }),
+ ).toBe('disabled');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: true, present: false, connectionStatus: 'not-detected' }),
+ ).toBe('not-detected');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: false, present: true, connectionStatus: 'connected' }),
+ ).toBe('disabled');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: true, present: true, connectionStatus: 'connected' }),
+ ).toBe('connected');
+ expect(inputDeviceConnectionTone({ status: 'disabled', present: true })).toBe('connected');
+ expect(inputDeviceConnectionTone({ status: 'disabled', present: false })).toBe('neutral');
+ expect(inputDeviceConnectionTone({ status: 'not-detected', present: false })).toBe('neutral');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: true, present: false, connectionStatus: 'error' }),
+ ).toBe('error');
+ expect(
+ resolveInputDeviceStatusKey({ enabled: true, present: false, connectionStatus: 'unavailable' }),
+ ).toBe('unavailable');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.accessories.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.accessories.test.tsx
new file mode 100644
index 0000000000..77e24e91ac
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/KeyboardShortcutsSection.accessories.test.tsx
@@ -0,0 +1,181 @@
+// @vitest-environment jsdom
+
+import { 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';
+import {
+ XBOX_GAMEPAD_EMPTY_DEVICE,
+ createXboxGamepadDefaultSettings,
+} from '../../../../shared/xboxGamepad';
+
+const mocks = vi.hoisted(() => ({
+ workLouderPresent: false as boolean | null,
+ workLouderEnabled: false,
+ xboxPresent: false as boolean | null,
+ xboxEnabled: false,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+
+vi.mock('@/lib/appShortcutStore', () => ({
+ getAppShortcutCombos: () => [],
+ getAppShortcutOverrides: () => ({}),
+ getAppShortcutPlatform: () => 'darwin',
+ subscribeAppShortcuts: () => () => {},
+}));
+
+vi.mock('@/hooks/useVoiceInputSettings', () => ({
+ getVoiceInputSettings: () => ({ shortcut: null }),
+}));
+
+vi.mock('@/features/skillhub/hooks/useSkillhub', () => ({
+ useSkillhub: () => ({
+ skills: [],
+ bootstrapped: true,
+ refresh: vi.fn(),
+ }),
+}));
+
+vi.mock('@/hooks/useWorkLouderCodex', () => ({
+ useWorkLouderCodex: () => ({
+ state: {
+ connectionStatus: mocks.workLouderPresent === true ? 'connected' : 'not-detected',
+ connectionReason: null,
+ devicePresent: mocks.workLouderPresent,
+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },
+ settings: {
+ ...createWorkLouderCodexDefaultSettings(),
+ deviceEnabled: mocks.workLouderEnabled,
+ },
+ agentSlots: [],
+ taskOptions: [],
+ agentSlotCount: 6,
+ },
+ loading: false,
+ saving: false,
+ error: null,
+ setSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ openInputMonitoringSettings: vi.fn(),
+ reload: vi.fn(),
+ }),
+}));
+
+vi.mock('@/hooks/useXboxGamepad', () => ({
+ useXboxGamepad: () => ({
+ state: {
+ connectionStatus: mocks.xboxPresent === true ? 'connected' : 'not-detected',
+ devicePresent: mocks.xboxPresent,
+ deviceName: mocks.xboxPresent === true ? 'Xbox Wireless Controller' : null,
+ device: { ...XBOX_GAMEPAD_EMPTY_DEVICE },
+ settings: {
+ ...createXboxGamepadDefaultSettings(),
+ deviceEnabled: mocks.xboxEnabled,
+ },
+ },
+ loading: false,
+ saving: false,
+ error: null,
+ setSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ reload: vi.fn(),
+ }),
+}));
+
+import { KeyboardShortcutsSection } from '../KeyboardShortcutsSection';
+
+describe('KeyboardShortcutsSection accessories', () => {
+ beforeEach(() => {
+ mocks.workLouderPresent = false;
+ mocks.workLouderEnabled = false;
+ mocks.xboxPresent = false;
+ mocks.xboxEnabled = false;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ onAuthStateChange: vi.fn(() => () => {}),
+ },
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'electronAPI');
+ });
+
+ it('keeps undetected hardware behind a single Accessories entry', () => {
+ render(<KeyboardShortcutsSection />);
+
+ expect(screen.getByTestId('settings-shortcuts-accessories')).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.shortcuts.accessories.openAria' }));
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeTruthy();
+ });
+
+ it('shows a detected device here and keeps the rest behind Accessories', () => {
+ mocks.xboxPresent = true;
+ render(<KeyboardShortcutsSection />);
+
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.shortcuts.accessories.openAria' }));
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeNull();
+ });
+
+ it('shows an enabled device here even when it is not detected', () => {
+ mocks.xboxEnabled = true;
+ render(<KeyboardShortcutsSection />);
+
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeNull();
+ expect(screen.getByTestId('settings-shortcuts-accessories')).toBeTruthy();
+ });
+
+ it('hides Accessories when every hardware device is connected', () => {
+ mocks.workLouderPresent = true;
+ mocks.xboxPresent = true;
+ render(<KeyboardShortcutsSection />);
+
+ expect(screen.queryByTestId('settings-shortcuts-accessories')).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.workLouderCodex.openAria' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'settings.shortcuts.xboxGamepad.openAria' }),
+ ).toBeTruthy();
+ });
+});
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.tsx
index b2b578116a..59179b4ed6 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
@@ -14,6 +14,7 @@ const combo = {
const mocks = vi.hoisted(() => ({
getOverrides: vi.fn(),
getCombos: vi.fn(),
+ workLouderPresent: false as boolean,
}));
vi.mock('@/features/skillhub/hooks/useSkillhub', () => ({
@@ -43,11 +44,60 @@ vi.mock('@/hooks/useVoiceInputSettings', () => ({
getVoiceInputSettings: () => ({ shortcut: null }),
}));
+vi.mock('@/hooks/useWorkLouderCodex', async () => {
+ const { WORKLOUDER_CODEX_EMPTY_DEVICE_STATE, createWorkLouderCodexDefaultSettings } =
+ await import('../../../../shared/workLouderCodex');
+ return {
+ useWorkLouderCodex: () => ({
+ state: {
+ connectionStatus: mocks.workLouderPresent ? 'connected' : 'not-detected',
+ connectionReason: null,
+ devicePresent: mocks.workLouderPresent,
+ device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },
+ settings: createWorkLouderCodexDefaultSettings(),
+ agentSlots: [],
+ taskOptions: [],
+ agentSlotCount: 6,
+ },
+ loading: false,
+ saving: false,
+ error: null,
+ setSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ openInputMonitoringSettings: vi.fn(),
+ reload: vi.fn(),
+ }),
+ };
+});
+
+vi.mock('@/hooks/useXboxGamepad', async () => {
+ const { XBOX_GAMEPAD_EMPTY_DEVICE, createXboxGamepadDefaultSettings } =
+ await import('../../../../shared/xboxGamepad');
+ return {
+ useXboxGamepad: () => ({
+ state: {
+ connectionStatus: 'not-detected',
+ devicePresent: false,
+ deviceName: null,
+ device: { ...XBOX_GAMEPAD_EMPTY_DEVICE },
+ settings: createXboxGamepadDefaultSettings(),
+ },
+ loading: false,
+ saving: false,
+ error: null,
+ setSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ reload: vi.fn(),
+ }),
+ };
+});
+
import { KeyboardShortcutsSection } from '../KeyboardShortcutsSection';
describe('KeyboardShortcutsSection mutation ordering', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.workLouderPresent = false;
});
afterEach(() => {
@@ -65,6 +115,7 @@ describe('KeyboardShortcutsSection mutation ordering', () => {
},
});
+ mocks.workLouderPresent = true;
render(<KeyboardShortcutsSection />);
fireEvent.click(screen.getByLabelText('settings.shortcuts.workLouderCodex.openAria'));
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
index e9ff798456..0d9df8ef3c 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
@@ -131,7 +131,7 @@ describe('WorkLouderCodexSettings', () => {
connectionReason: null,
devicePresent: true,
device: { ...WORKLOUDER_CODEX_EMPTY_DEVICE_STATE },
- settings: createWorkLouderCodexDefaultSettings(),
+ settings: { ...createWorkLouderCodexDefaultSettings(), deviceEnabled: true },
agentSlots: Array.from({ length: 6 }, (_, slot) => ({
slot,
sessionId: null,
@@ -151,13 +151,13 @@ describe('WorkLouderCodexSettings', () => {
);
expect(onOpen).toHaveBeenCalledOnce();
- expect(screen.getByText('settings.shortcuts.workLouderCodex.beta')).toBeTruthy();
+ expect(screen.queryByText('settings.shortcuts.workLouderCodex.beta')).toBeNull();
expect(
screen.getByText('settings.shortcuts.workLouderCodex.connection.status.connected'),
).toBeTruthy();
});
- it('shows connected on the shortcuts entry when the keyboard is present but this instance is off', () => {
+ it('shows off on the shortcuts entry when the keyboard is present but this instance is off', () => {
render(
<WorkLouderCodexEntry
state={{
@@ -181,8 +181,11 @@ describe('WorkLouderCodexSettings', () => {
);
expect(
- screen.getByText('settings.shortcuts.workLouderCodex.connection.status.connected'),
+ screen.getByText('settings.shortcuts.workLouderCodex.connection.status.disabled'),
).toBeTruthy();
+ expect(
+ screen.queryByText('settings.shortcuts.workLouderCodex.connection.status.connected'),
+ ).toBeNull();
expect(
screen.queryByText('settings.shortcuts.workLouderCodex.connection.status.connecting'),
).toBeNull();
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadLayout.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadLayout.test.tsx
new file mode 100644
index 0000000000..b82c8ef41b
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadLayout.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createXboxGamepadDefaultLayout, type XboxGamepadPreviewInput } from '../../../../shared/xboxGamepad';
+import {
+ XboxGamepadLayout,
+ type XboxGamepadEditablePart,
+ type XboxGamepadKeyHint,
+} from '../XboxGamepadLayout';
+
+const LABELS = { leftStick: '左摇杆', rightStick: '右摇杆' };
+
+function hintFor(part: XboxGamepadEditablePart): XboxGamepadKeyHint {
+ return { legend: part };
+}
+
+function renderPad(preview: XboxGamepadPreviewInput | null = null) {
+ const onEdit = vi.fn();
+ render(
+ <XboxGamepadLayout
+ layout={createXboxGamepadDefaultLayout()}
+ hintFor={hintFor}
+ onEdit={onEdit}
+ preview={preview}
+ labels={LABELS}
+ />,
+ );
+ return onEdit;
+}
+
+describe('XboxGamepadLayout', () => {
+ it('draws an Xbox Series pad: left stick above d-pad, ABXY above right stick', () => {
+ renderPad();
+ expect(screen.getByTestId('xbox-gamepad-layout')).toBeTruthy();
+ expect(screen.getByTestId('xbox-gamepad-stick-left')).toBeTruthy();
+ expect(screen.getByTestId('xbox-gamepad-stick-right')).toBeTruthy();
+ expect(screen.getByTestId('xbox-gamepad-dpad')).toBeTruthy();
+ expect(screen.getByTestId('xbox-gamepad-face')).toBeTruthy();
+ for (const part of ['a', 'b', 'x', 'y', 'lb', 'rb', 'lt', 'rt', 'view', 'menu', 'xbox'] as const) {
+ expect(screen.getByRole('button', { name: part })).toBeTruthy();
+ }
+ });
+
+ it('opens the matching control when a face button is clicked', () => {
+ const onEdit = renderPad();
+ fireEvent.click(screen.getByRole('button', { name: 'a' }));
+ expect(onEdit).toHaveBeenCalledWith('a');
+ });
+
+ it('marks a pressed physical button', () => {
+ const preview = {
+ buttons: { a: true },
+ sticks: { left: { x: 0, y: 0 }, right: { x: 0, y: 0 } },
+ triggers: { lt: 0, rt: 0 },
+ } as XboxGamepadPreviewInput;
+ renderPad(preview);
+ expect(screen.getByRole('button', { name: 'a' }).getAttribute('aria-pressed')).toBe('true');
+ expect(screen.getByRole('button', { name: 'b' }).getAttribute('aria-pressed')).toBe('false');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadSettings.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadSettings.test.tsx
new file mode 100644
index 0000000000..c6cf29b0d4
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/XboxGamepadSettings.test.tsx
@@ -0,0 +1,110 @@
+// @vitest-environment jsdom
+
+import { render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createXboxGamepadDefaultSettings,
+ type XboxGamepadSettings as XboxGamepadSettingsModel,
+ type XboxGamepadState,
+} from '../../../../shared/xboxGamepad';
+
+const mocks = vi.hoisted(() => ({
+ state: null as XboxGamepadState | null,
+ loading: true,
+ saving: false,
+ error: null as 'load' | 'save' | null,
+ setSettings: vi.fn(),
+ resetSettings: vi.fn(),
+ reload: vi.fn(),
+ setLayoutPreviewActive: vi.fn(),
+ previewListeners: [] as Array<(input: unknown) => void>,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/hooks/useXboxGamepad', () => ({
+ useXboxGamepad: () => ({
+ state: mocks.state,
+ loading: mocks.loading,
+ saving: mocks.saving,
+ error: mocks.error,
+ setSettings: mocks.setSettings,
+ resetSettings: mocks.resetSettings,
+ reload: mocks.reload,
+ }),
+}));
+
+vi.mock('@/features/skillhub/hooks/useSkillhub', () => ({
+ useSkillhub: () => ({
+ skills: [],
+ bootstrapped: true,
+ refresh: vi.fn(),
+ }),
+}));
+
+import { XboxGamepadSettings } from '../XboxGamepadSettings';
+
+function loadedState(
+ settings: XboxGamepadSettingsModel = createXboxGamepadDefaultSettings(),
+): XboxGamepadState {
+ return {
+ connectionStatus: 'connected',
+ devicePresent: true,
+ deviceName: 'Xbox Wireless Controller',
+ device: {
+ name: 'Xbox Wireless Controller',
+ category: 'Xbox One',
+ transport: 'usb',
+ batteryPercentage: 80,
+ batteryState: 'discharging',
+ },
+ settings,
+ };
+}
+
+describe('XboxGamepadSettings', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.state = null;
+ mocks.loading = true;
+ mocks.saving = false;
+ mocks.error = null;
+ mocks.previewListeners = [];
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ xboxGamepad: {
+ setLayoutPreviewActive: mocks.setLayoutPreviewActive,
+ onPreviewInput: (callback: (input: unknown) => void) => {
+ mocks.previewListeners.push(callback);
+ return () => {
+ mocks.previewListeners = mocks.previewListeners.filter((item) => item !== callback);
+ };
+ },
+ },
+ },
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'electronAPI');
+ });
+
+ it('renders the controller while settings are still loading', () => {
+ expect(() => render(<XboxGamepadSettings onBack={vi.fn()} />)).not.toThrow();
+ expect(screen.getByTestId('xbox-gamepad-layout')).toBeTruthy();
+ });
+
+ it('renders the controller when a live state is missing layout', () => {
+ mocks.state = loadedState({ deviceEnabled: true } as XboxGamepadSettingsModel);
+ mocks.loading = false;
+ expect(() => render(<XboxGamepadSettings onBack={vi.fn()} />)).not.toThrow();
+ expect(screen.getByTestId('xbox-gamepad-layout')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: /settings.shortcuts.xboxGamepad.controls.a/ }),
+ ).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 72f67ca028..59a27baf5e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1606,7 +1606,10 @@ export function CCAgentSessionView({
return subscribeWorkLouderCodexAction((action) => {
if (action.type !== 'command') return false;
if (!sessionId || !ownsHardwareTaskActions) return false;
- if (action.commandId === 'approval.approve') {
+ if (
+ action.commandId === 'approval.approve' ||
+ action.commandId === 'composer.submit'
+ ) {
if (pendingPermission) {
respondToPermission({ behavior: 'allow' });
return true;
@@ -1617,7 +1620,10 @@ export function CCAgentSessionView({
}
return false;
}
- if (action.commandId === 'approval.decline') {
+ if (
+ action.commandId === 'approval.decline' ||
+ action.commandId === 'navigateBack'
+ ) {
if (pendingPermission) {
respondToPermission({
behavior: 'deny',
@@ -1630,6 +1636,7 @@ export function CCAgentSessionView({
cancelPlanReview(pendingPlanReview.requestId);
return true;
}
+ return false;
}
if (action.commandId === 'forkTask') {
if (!canNavigateSession) return false;
diff --git a/apps/desktop/src/renderer/hooks/useXboxGamepad.ts b/apps/desktop/src/renderer/hooks/useXboxGamepad.ts
new file mode 100644
index 0000000000..b28d6c1098
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useXboxGamepad.ts
@@ -0,0 +1,105 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type {
+ XboxGamepadSettings,
+ XboxGamepadSettingsPatch,
+ XboxGamepadState,
+} from '../../shared/xboxGamepad';
+
+export function useXboxGamepad(options: { watchConnection?: boolean } = {}) {
+ const { watchConnection = false } = options;
+ const [state, setState] = useState<XboxGamepadState | 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 reload = useCallback(async () => {
+ const api = window.electronAPI?.xboxGamepad;
+ if (!api) {
+ if (mountedRef.current) {
+ setLoading(false);
+ setError('load');
+ }
+ return;
+ }
+ if (mountedRef.current) {
+ setLoading(true);
+ setError(null);
+ }
+ try {
+ const next = await api.getState();
+ if (!mountedRef.current) return;
+ setState(next);
+ setError(null);
+ } catch {
+ if (mountedRef.current) setError('load');
+ } finally {
+ if (mountedRef.current) setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ const api = window.electronAPI?.xboxGamepad;
+ const unsubscribe = api?.onStateChanged((next) => {
+ if (!mountedRef.current) return;
+ setState(next);
+ setLoading(false);
+ });
+ void reload();
+ return () => {
+ mountedRef.current = false;
+ unsubscribe?.();
+ };
+ }, [reload]);
+
+ useEffect(() => {
+ if (!watchConnection) return;
+ const api = window.electronAPI?.xboxGamepad;
+ if (!api) return;
+ const timer = window.setInterval(() => {
+ void api.probe();
+ }, 2_000);
+ void api.probe();
+ return () => window.clearInterval(timer);
+ }, [watchConnection]);
+
+ const setSettings = useCallback(async (patch: XboxGamepadSettingsPatch) => {
+ const api = window.electronAPI?.xboxGamepad;
+ if (!api) return;
+ setSaving(true);
+ try {
+ const next = await api.setSettings(patch);
+ if (mountedRef.current) {
+ setState(next);
+ setError(null);
+ }
+ } catch {
+ if (mountedRef.current) setError('save');
+ } finally {
+ if (mountedRef.current) setSaving(false);
+ }
+ }, []);
+
+ const resetSettings = useCallback(async () => {
+ const api = window.electronAPI?.xboxGamepad;
+ if (!api) return;
+ setSaving(true);
+ try {
+ const next = await api.resetSettings();
+ if (mountedRef.current) {
+ setState(next);
+ setError(null);
+ }
+ } catch {
+ if (mountedRef.current) setError('save');
+ } finally {
+ if (mountedRef.current) setSaving(false);
+ }
+ }, []);
+
+ return { state, loading, saving, error, setSettings, resetSettings, reload };
+}
+
+export type { XboxGamepadSettings };
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 83d83a71d8..885f788204 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3500,6 +3500,12 @@
},
"shortcuts": {
"title": "Keyboard Shortcuts",
+ "accessories": {
+ "title": "Accessories",
+ "description": "Keyboards, gamepads, and other input devices",
+ "openAria": "Open accessories",
+ "back": "Back"
+ },
"resetAll": "Reset all to defaults",
"reset": "Reset to default",
"recording": "Press new shortcut…",
@@ -3536,7 +3542,7 @@
},
"composer.submit": {
"name": "Send message",
- "description": "Send the current composer message"
+ "description": "Send the composer message, or approve the pending request"
},
"feedback": {
"name": "Send feedback",
@@ -3619,7 +3625,11 @@
},
"navigateBack": {
"name": "Back",
- "description": "Go back in navigation history"
+ "description": "Go back, or decline the pending request"
+ },
+ "toggleFullscreen": {
+ "name": "Toggle fullscreen",
+ "description": "Enter or exit fullscreen"
},
"composer.focus": {
"name": "Focus composer",
@@ -3639,7 +3649,6 @@
}
},
"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",
@@ -3940,7 +3949,113 @@
"edit": "Edit",
"delete": "Delete",
"deleteAria": "Delete shortcut for {{name}}",
- "cancel": "Cancel"
+ "cancel": "Cancel",
+ "xboxGamepad": {
+ "title": "Xbox controller",
+ "openAria": "Open Xbox controller settings",
+ "entryDescription": "Scroll, talk, send, and switch tasks with a controller",
+ "back": "Back",
+ "retry": "Retry",
+ "layout": {
+ "title": "Controls",
+ "description": "Click a control to change what it does. Pressing the pad lights the matching control here.",
+ "clickToEdit": "Click to set",
+ "editor": {
+ "title": "Control",
+ "description": "Choose a Cindy action for this control. Unmapped controls do nothing.",
+ "done": "Done",
+ "assigned": "Action",
+ "assignedDescription": "Fires on press. Hold-to-talk ends when you release."
+ },
+ "reset": {
+ "title": "Reset mapping",
+ "description": "Restores each control’s action without turning the controller off.",
+ "button": "Reset mapping"
+ }
+ },
+ "stick": {
+ "description": "A stick can scroll the conversation, or fire a different action in each direction.",
+ "customDescription": "Fires once when the stick enters this direction.",
+ "mode": {
+ "label": "Stick mode",
+ "description": "Conversation scroll follows how far you push. Custom assigns an action per direction.",
+ "options": {
+ "conversation-scroll": "Scroll conversation",
+ "custom": "Custom directions"
+ }
+ }
+ },
+ "directions": {
+ "up": "Up",
+ "right": "Right",
+ "down": "Down",
+ "left": "Left"
+ },
+ "controls": {
+ "a": "A",
+ "b": "B",
+ "x": "X",
+ "y": "Y",
+ "lb": "LB",
+ "rb": "RB",
+ "lt": "LT",
+ "rt": "RT",
+ "view": "View",
+ "menu": "Menu",
+ "xbox": "Xbox",
+ "ls": "Left stick click",
+ "rs": "Right stick click",
+ "dpadUp": "D-pad up",
+ "dpadDown": "D-pad down",
+ "dpadLeft": "D-pad left",
+ "dpadRight": "D-pad right",
+ "leftStick": "Left stick",
+ "rightStick": "Right stick"
+ },
+ "actions": {
+ "none": "Unmapped",
+ "voice": "Voice input",
+ "voiceDescription": "Hold for voice input, release to stop.",
+ "commands": "Commands",
+ "skills": "Skills",
+ "choose": "Choose action"
+ },
+ "errors": {
+ "load": "Could not load controller settings",
+ "save": "Could not save controller settings"
+ },
+ "connection": {
+ "label": "Connection",
+ "toggle": {
+ "label": "Enable",
+ "aria": "Let this Cindy use an Xbox controller while it is in the foreground"
+ },
+ "status": {
+ "connecting": "Connecting",
+ "connected": "Connected",
+ "not-detected": "Not detected",
+ "present": "Connected",
+ "disabled": "Off",
+ "error": "Connection error",
+ "unavailable": "Not supported on this system"
+ },
+ "descriptions": {
+ "connecting": "Cindy is looking for an Xbox controller.",
+ "connected": "Cindy listens to this controller while it is in the foreground.",
+ "disabled": "Turn it on to listen while Cindy is in the foreground.",
+ "present": "Turn it on to listen while Cindy is in the foreground.",
+ "not-detected": "Connect an Xbox controller with USB or Bluetooth.",
+ "error": "Cindy cannot read the controller right now and is retrying.",
+ "unavailable": "This computer cannot read an Xbox controller yet."
+ }
+ },
+ "device": {
+ "usb": "Wired",
+ "bluetooth": "Bluetooth",
+ "battery": "{{percent}}%",
+ "charging": "Charging {{percent}}%"
+ }
+ }
},
"ghosts": {
"title": "Plugins",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5d562064d8..a0c05e99ac 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3499,6 +3499,12 @@
},
"shortcuts": {
"title": "キーボードショートカット",
+ "accessories": {
+ "title": "アクセサリ",
+ "description": "キーボードやゲームパッドなどの入力デバイス",
+ "openAria": "アクセサリを開く",
+ "back": "戻る"
+ },
"resetAll": "すべてデフォルトに戻す",
"reset": "デフォルトに戻す",
"recording": "新しいショートカットを入力…",
@@ -3535,7 +3541,7 @@
},
"composer.submit": {
"name": "メッセージを送信",
- "description": "入力欄のメッセージを送信します"
+ "description": "入力中のメッセージを送信します。承認待ちがあれば承認します"
},
"feedback": {
"name": "フィードバックを送信",
@@ -3618,7 +3624,11 @@
},
"navigateBack": {
"name": "戻る",
- "description": "ナビゲーション履歴を戻ります"
+ "description": "前の画面に戻ります。承認待ちがあれば拒否します"
+ },
+ "toggleFullscreen": {
+ "name": "全画面を切り替え",
+ "description": "全画面表示の開始または終了"
},
"composer.focus": {
"name": "入力欄にフォーカス",
@@ -3638,7 +3648,6 @@
}
},
"title": "Work Louder Codex Micro",
- "beta": "Beta",
"entryDescription": "Agent キーでタスクを開き、ライトで状態を表示します。",
"openAria": "Work Louder Codex Micro の設定を開く",
"back": "キーボードショートカットに戻る",
@@ -3939,7 +3948,113 @@
"edit": "編集",
"delete": "削除",
"deleteAria": "{{name}} のショートカットを削除",
- "cancel": "キャンセル"
+ "cancel": "キャンセル",
+ "xboxGamepad": {
+ "title": "Xbox コントローラー",
+ "openAria": "Xbox コントローラー設定を開く",
+ "entryDescription": "コントローラーでスクロール、音声入力、送信、タスク切り替え",
+ "back": "戻る",
+ "retry": "再試行",
+ "layout": {
+ "title": "コントローラー",
+ "description": "ボタンをタップして割り当てを変更できます。実機を押すと、図の同じ位置が点灯します。",
+ "clickToEdit": "タップして設定",
+ "editor": {
+ "title": "ボタン",
+ "description": "このボタンに Cindy の機能を割り当てます。未設定のボタンは何もしません。",
+ "done": "完了",
+ "assigned": "機能",
+ "assignedDescription": "押したときに実行します。押し話しは離すと終了します。"
+ },
+ "reset": {
+ "title": "割り当てをリセット",
+ "description": "各ボタンの機能だけを戻します。コントローラーはオフになりません。",
+ "button": "割り当てをリセット"
+ }
+ },
+ "stick": {
+ "description": "スティックは会話のスクロールにも、方向ごとの機能にも使えます。",
+ "customDescription": "スティックがこの方向に入ったときに 1 回実行します。",
+ "mode": {
+ "label": "スティックの用途",
+ "description": "会話スクロールは倒した量に応じて連続します。カスタムは方向ごとに機能を指定します。",
+ "options": {
+ "conversation-scroll": "会話をスクロール",
+ "custom": "方向をカスタム"
+ }
+ }
+ },
+ "directions": {
+ "up": "上",
+ "right": "右",
+ "down": "下",
+ "left": "左"
+ },
+ "controls": {
+ "a": "A",
+ "b": "B",
+ "x": "X",
+ "y": "Y",
+ "lb": "LB",
+ "rb": "RB",
+ "lt": "LT",
+ "rt": "RT",
+ "view": "View",
+ "menu": "Menu",
+ "xbox": "Xbox",
+ "ls": "左スティック押し込み",
+ "rs": "右スティック押し込み",
+ "dpadUp": "十字キー上",
+ "dpadDown": "十字キー下",
+ "dpadLeft": "十字キー左",
+ "dpadRight": "十字キー右",
+ "leftStick": "左スティック",
+ "rightStick": "右スティック"
+ },
+ "actions": {
+ "none": "未設定",
+ "voice": "音声入力",
+ "voiceDescription": "押している間音声入力し、離すと終了します。",
+ "commands": "コマンド",
+ "skills": "スキル",
+ "choose": "機能を選択"
+ },
+ "errors": {
+ "load": "コントローラー設定を読み込めませんでした",
+ "save": "コントローラー設定を保存できませんでした"
+ },
+ "connection": {
+ "label": "接続",
+ "toggle": {
+ "label": "有効にする",
+ "aria": "Cindy が前面にあるとき Xbox コントローラーを使う"
+ },
+ "status": {
+ "connecting": "接続中",
+ "connected": "接続済み",
+ "not-detected": "未検出",
+ "present": "接続済み",
+ "disabled": "オフ",
+ "error": "接続エラー",
+ "unavailable": "このシステムでは未対応"
+ },
+ "descriptions": {
+ "connecting": "Cindy は Xbox コントローラーを探しています。",
+ "connected": "Cindy が前面にあるとき、このコントローラーを受け付けます。",
+ "disabled": "有効にすると、Cindy が前面にあるときにコントローラーを受け付けます。",
+ "present": "有効にすると、Cindy が前面にあるときにコントローラーを受け付けます。",
+ "not-detected": "USB または Bluetooth で Xbox コントローラーを接続してください。",
+ "error": "Cindy はコントローラーを読み取れず、再試行しています。",
+ "unavailable": "このコンピューターはまだ Xbox コントローラーを読めません。"
+ }
+ },
+ "device": {
+ "usb": "有線",
+ "bluetooth": "Bluetooth",
+ "battery": "{{percent}}%",
+ "charging": "充電中 {{percent}}%"
+ }
+ }
},
"ghosts": {
"title": "プラグイン",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a4ebab153c..cb757e4f87 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3499,6 +3499,12 @@
},
"shortcuts": {
"title": "키보드 단축키",
+ "accessories": {
+ "title": "액세서리",
+ "description": "키보드, 게임패드 등 입력 장치",
+ "openAria": "액세서리 열기",
+ "back": "뒤로"
+ },
"resetAll": "모두 기본값으로 재설정",
"reset": "기본값으로 재설정",
"recording": "새 단축키를 누르세요…",
@@ -3535,7 +3541,7 @@
},
"composer.submit": {
"name": "메시지 보내기",
- "description": "입력창의 메시지를 보냅니다"
+ "description": "입력창의 메시지를 보내거나, 대기 중인 요청이 있으면 승인합니다"
},
"feedback": {
"name": "피드백 보내기",
@@ -3618,7 +3624,11 @@
},
"navigateBack": {
"name": "뒤로",
- "description": "탐색 기록에서 뒤로 이동합니다"
+ "description": "이전 화면으로 돌아가거나, 대기 중인 요청이 있으면 거절합니다"
+ },
+ "toggleFullscreen": {
+ "name": "전체 화면 전환",
+ "description": "전체 화면을 시작하거나 종료합니다"
},
"composer.focus": {
"name": "입력창에 포커스",
@@ -3638,7 +3648,6 @@
}
},
"title": "Work Louder Codex Micro",
- "beta": "Beta",
"entryDescription": "Agent 키로 작업을 열고 조명으로 상태를 표시합니다.",
"openAria": "Work Louder Codex Micro 설정 열기",
"back": "키보드 단축키로 돌아가기",
@@ -3939,7 +3948,113 @@
"edit": "편집",
"delete": "삭제",
"deleteAria": "{{name}} 단축키 삭제",
- "cancel": "취소"
+ "cancel": "취소",
+ "xboxGamepad": {
+ "title": "Xbox 컨트롤러",
+ "openAria": "Xbox 컨트롤러 설정 열기",
+ "entryDescription": "컨트롤러로 스크롤, 말하기, 보내기, 작업 전환",
+ "back": "뒤로",
+ "retry": "다시 시도",
+ "layout": {
+ "title": "컨트롤러",
+ "description": "버튼을 눌러 동작을 바꿀 수 있습니다. 패드를 누르면 그림의 같은 위치가 켜집니다.",
+ "clickToEdit": "눌러서 설정",
+ "editor": {
+ "title": "버튼",
+ "description": "이 버튼에 Cindy 기능을 지정합니다. 지정하지 않은 버튼은 아무 것도 하지 않습니다.",
+ "done": "완료",
+ "assigned": "기능",
+ "assignedDescription": "누르면 실행됩니다. 눌러서 말하기는 떼면 끝납니다."
+ },
+ "reset": {
+ "title": "기본 키 배치 복원",
+ "description": "각 버튼의 기능만 되돌리며, 컨트롤러는 꺼지지 않습니다.",
+ "button": "기본 키 배치 복원"
+ }
+ },
+ "stick": {
+ "description": "스틱으로 대화를 스크롤하거나, 방향마다 다른 기능을 지정할 수 있습니다.",
+ "customDescription": "스틱이 이 방향으로 들어갈 때 한 번 실행됩니다.",
+ "mode": {
+ "label": "스틱 용도",
+ "description": "대화 스크롤은 기울인 정도에 따라 연속됩니다. 사용자 지정은 방향마다 기능을 정합니다.",
+ "options": {
+ "conversation-scroll": "대화 스크롤",
+ "custom": "방향 사용자 지정"
+ }
+ }
+ },
+ "directions": {
+ "up": "위",
+ "right": "오른쪽",
+ "down": "아래",
+ "left": "왼쪽"
+ },
+ "controls": {
+ "a": "A",
+ "b": "B",
+ "x": "X",
+ "y": "Y",
+ "lb": "LB",
+ "rb": "RB",
+ "lt": "LT",
+ "rt": "RT",
+ "view": "View",
+ "menu": "Menu",
+ "xbox": "Xbox",
+ "ls": "왼쪽 스틱 클릭",
+ "rs": "오른쪽 스틱 클릭",
+ "dpadUp": "십자키 위",
+ "dpadDown": "십자키 아래",
+ "dpadLeft": "십자키 왼쪽",
+ "dpadRight": "십자키 오른쪽",
+ "leftStick": "왼쪽 스틱",
+ "rightStick": "오른쪽 스틱"
+ },
+ "actions": {
+ "none": "지정 안 함",
+ "voice": "음성 입력",
+ "voiceDescription": "누르고 있는 동안 음성 입력하고, 떼면 끝납니다.",
+ "commands": "명령",
+ "skills": "스킬",
+ "choose": "기능 선택"
+ },
+ "errors": {
+ "load": "컨트롤러 설정을 불러올 수 없습니다",
+ "save": "컨트롤러 설정을 저장할 수 없습니다"
+ },
+ "connection": {
+ "label": "연결",
+ "toggle": {
+ "label": "사용",
+ "aria": "Cindy가 앞에 있을 때 Xbox 컨트롤러를 사용합니다"
+ },
+ "status": {
+ "connecting": "연결 중",
+ "connected": "연결됨",
+ "not-detected": "감지되지 않음",
+ "present": "연결됨",
+ "disabled": "꺼짐",
+ "error": "연결 오류",
+ "unavailable": "이 시스템에서는 지원되지 않음"
+ },
+ "descriptions": {
+ "connecting": "Cindy가 Xbox 컨트롤러를 찾고 있습니다.",
+ "connected": "Cindy가 앞에 있을 때 이 컨트롤러를 듣습니다.",
+ "disabled": "켜면 Cindy가 앞에 있을 때 컨트롤러를 듣습니다.",
+ "present": "켜면 Cindy가 앞에 있을 때 컨트롤러를 듣습니다.",
+ "not-detected": "USB 또는 Bluetooth로 Xbox 컨트롤러를 연결하세요.",
+ "error": "Cindy가 컨트롤러를 읽지 못해 다시 시도하고 있습니다.",
+ "unavailable": "이 컴퓨터는 아직 Xbox 컨트롤러를 읽을 수 없습니다."
+ }
+ },
+ "device": {
+ "usb": "유선",
+ "bluetooth": "블루투스",
+ "battery": "{{percent}}%",
+ "charging": "충전 중 {{percent}}%"
+ }
+ }
},
"ghosts": {
"title": "플러그인",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 001ffcf42c..b791b384d9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3535,7 +3535,7 @@
},
"composer.submit": {
"name": "发送消息",
- "description": "发送输入框中的消息"
+ "description": "发送输入框中的消息;若有待确认的请求则改为批准"
},
"feedback": {
"name": "发送反馈",
@@ -3618,7 +3618,7 @@
},
"navigateBack": {
"name": "后退",
- "description": "在浏览历史中后退"
+ "description": "返回上一页;若有待确认的请求则改为拒绝"
},
"composer.focus": {
"name": "聚焦输入框",
@@ -3635,10 +3635,13 @@
"conversation.scrollBottom": {
"name": "跳到最新",
"description": "滚动到最新一条消息"
+ },
+ "toggleFullscreen": {
+ "name": "切换全屏",
+ "description": "进入或退出全屏"
}
},
"title": "Work Louder Codex Micro",
- "beta": "Beta",
"entryDescription": "用 Agent 键打开任务,并用灯光显示任务状态。",
"openAria": "打开 Work Louder Codex Micro 设置",
"back": "返回键盘快捷键",
@@ -3663,7 +3666,7 @@
"label": "连接",
"toggle": {
"label": "启用",
- "aria": "让这个 Cindy 占用 Codex Micro"
+ "aria": "让这个 Cindy 在前台时使用 Xbox 手柄"
},
"status": {
"connecting": "正在连接",
@@ -3672,16 +3675,16 @@
"present": "已连接",
"disabled": "未启用",
"error": "连接异常",
- "unavailable": "SDK 不可用"
+ "unavailable": "当前系统暂不支持"
},
"descriptions": {
- "connecting": "Cindy 正在启动 Work Louder 设备服务。",
- "connected": "USB 已连接,Cindy 正在监听按键并同步任务灯效。",
- "disabled": "启用后,Cindy 会监听按键,并用灯光显示任务状态。",
- "present": "启用后,Cindy 会监听按键,并用灯光显示任务状态。",
- "not-detected": "请用支持数据传输的 USB 线连接键盘;如果 ChatGPT 正在占用设备,请先关闭。",
- "error": "Cindy 暂时无法与键盘通信,正在自动重试。",
- "unavailable": "未找到官方 Work Louder SDK。请保留支持 Codex Micro 的 ChatGPT 或 Codex 应用,重启 Cindy 后再试。",
+ "connecting": "Cindy 正在查找 Xbox 手柄。",
+ "connected": "Cindy 在前台时会监听这只手柄。",
+ "disabled": "启用后,Cindy 在前台时会监听手柄。",
+ "present": "启用后,Cindy 在前台时会监听手柄。",
+ "not-detected": "请用 USB 或蓝牙连接 Xbox 手柄。",
+ "error": "Cindy 暂时无法读取手柄,正在重试。",
+ "unavailable": "这台电脑还不能读取 Xbox 手柄。",
"connection-timeout": "Work Louder 服务在规定时间内没有响应,Cindy 会自动重试。",
"connection-failed": "Work Louder 服务启动失败,Cindy 会自动重试。",
"permission-required": "macOS 拒绝了键盘访问,请在输入监控中允许 Cindy 后重试。",
@@ -3939,7 +3942,119 @@
"edit": "编辑",
"delete": "删除",
"deleteAria": "删除 {{name}} 的快捷键",
- "cancel": "取消"
+ "cancel": "取消",
+ "accessories": {
+ "title": "配件",
+ "description": "键盘、手柄等输入设备",
+ "openAria": "打开配件",
+ "back": "返回"
+ },
+ "xboxGamepad": {
+ "title": "Xbox 手柄",
+ "openAria": "打开 Xbox 手柄设置",
+ "entryDescription": "Cindy 在前台时,用手柄滚动、说话、发送和切换任务",
+ "back": "返回键盘快捷键",
+ "retry": "重试",
+ "layout": {
+ "title": "键位",
+ "description": "点按键位即可改它做什么。按下手柄时,图上对应的键会亮起。",
+ "clickToEdit": "点按即可设置",
+ "editor": {
+ "title": "按键",
+ "description": "给这个按键选一个 Cindy 功能。未设置的按键不会做任何事。",
+ "done": "完成",
+ "assigned": "功能",
+ "assignedDescription": "按下时触发。按住说话会在松开时结束。"
+ },
+ "reset": {
+ "title": "恢复默认键位",
+ "description": "只还原每个按键的功能,不会关掉手柄。",
+ "button": "恢复默认键位"
+ }
+ },
+ "stick": {
+ "description": "摇杆可以滚动对话,也可以给四个方向分别指定功能。",
+ "customDescription": "摇杆进入这个方向时触发一次。",
+ "mode": {
+ "label": "摇杆用途",
+ "description": "滚动对话会按推杆力度连续滚动;自定义则为每个方向单独指定功能。",
+ "options": {
+ "conversation-scroll": "滚动对话",
+ "custom": "自定义方向"
+ }
+ }
+ },
+ "directions": {
+ "up": "上",
+ "right": "右",
+ "down": "下",
+ "left": "左"
+ },
+ "controls": {
+ "a": "A",
+ "b": "B",
+ "x": "X",
+ "y": "Y",
+ "lb": "LB",
+ "rb": "RB",
+ "lt": "LT",
+ "rt": "RT",
+ "view": "View",
+ "menu": "Menu",
+ "xbox": "Xbox",
+ "ls": "左摇杆按下",
+ "rs": "右摇杆按下",
+ "dpadUp": "方向键上",
+ "dpadDown": "方向键下",
+ "dpadLeft": "方向键左",
+ "dpadRight": "方向键右",
+ "leftStick": "左摇杆",
+ "rightStick": "右摇杆"
+ },
+ "actions": {
+ "none": "未设置",
+ "voice": "语音输入",
+ "voiceDescription": "按住进行语音输入,松开结束。",
+ "commands": "命令",
+ "skills": "技能",
+ "choose": "选择功能"
+ },
+ "errors": {
+ "load": "无法读取手柄设置",
+ "save": "无法保存手柄设置"
+ },
+ "connection": {
+ "label": "连接",
+ "toggle": {
+ "label": "启用",
+ "aria": "让这个 Cindy 在前台时使用 Xbox 手柄"
+ },
+ "status": {
+ "connecting": "正在连接",
+ "connected": "已连接",
+ "not-detected": "未检测到",
+ "present": "已连接",
+ "disabled": "未启用",
+ "error": "连接异常",
+ "unavailable": "当前系统暂不支持"
+ },
+ "descriptions": {
+ "connecting": "Cindy 正在查找 Xbox 手柄。",
+ "connected": "Cindy 在前台时会监听这只手柄。",
+ "disabled": "启用后,Cindy 在前台时会监听手柄。",
+ "present": "启用后,Cindy 在前台时会监听手柄。",
+ "not-detected": "请用 USB 或蓝牙连接 Xbox 手柄。",
+ "error": "Cindy 暂时无法读取手柄,正在重试。",
+ "unavailable": "这台电脑还不能读取 Xbox 手柄。"
+ }
+ },
+ "device": {
+ "usb": "有线",
+ "bluetooth": "蓝牙",
+ "battery": "{{percent}}%",
+ "charging": "充电中 {{percent}}%"
+ }
+ }
},
"ghosts": {
"title": "插件",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9015462404..668e475d44 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3499,6 +3499,12 @@
},
"shortcuts": {
"title": "鍵盤快捷鍵",
+ "accessories": {
+ "title": "配件",
+ "description": "鍵盤、手把等輸入裝置",
+ "openAria": "打開配件",
+ "back": "返回"
+ },
"resetAll": "恢復全部預設",
"reset": "恢復預設",
"recording": "按下新快捷鍵…",
@@ -3535,7 +3541,7 @@
},
"composer.submit": {
"name": "傳送訊息",
- "description": "傳送輸入框中的訊息"
+ "description": "傳送輸入框中的訊息;若有待確認的請求則改為批准"
},
"feedback": {
"name": "傳送意見回饋",
@@ -3618,7 +3624,11 @@
},
"navigateBack": {
"name": "返回",
- "description": "在瀏覽記錄中返回"
+ "description": "返回上一頁;若有待確認的請求則改為拒絕"
+ },
+ "toggleFullscreen": {
+ "name": "切換全螢幕",
+ "description": "進入或退出全螢幕"
},
"composer.focus": {
"name": "聚焦輸入框",
@@ -3638,7 +3648,6 @@
}
},
"title": "Work Louder Codex Micro",
- "beta": "Beta",
"entryDescription": "用 Agent 鍵開啟任務,並用燈光顯示任務狀態。",
"openAria": "開啟 Work Louder Codex Micro 設定",
"back": "返回鍵盤快捷鍵",
@@ -3939,7 +3948,113 @@
"edit": "編輯",
"delete": "刪除",
"deleteAria": "刪除 {{name}} 的快捷鍵",
- "cancel": "取消"
+ "cancel": "取消",
+ "xboxGamepad": {
+ "title": "Xbox 手把",
+ "openAria": "打開 Xbox 手把設定",
+ "entryDescription": "Cindy 在前景時,用手把捲動、說話、傳送和切換任務",
+ "back": "返回鍵盤快捷鍵",
+ "retry": "重試",
+ "layout": {
+ "title": "鍵位",
+ "description": "點按鍵位即可改它做什麼。按下手把時,圖上對應的鍵會亮起。",
+ "clickToEdit": "點按即可設定",
+ "editor": {
+ "title": "按鍵",
+ "description": "給這個按鍵選一個 Cindy 功能。未設定的按鍵不會做任何事。",
+ "done": "完成",
+ "assigned": "功能",
+ "assignedDescription": "按下時觸發。按住說話會在鬆開時結束。"
+ },
+ "reset": {
+ "title": "恢復預設鍵位",
+ "description": "只還原每個按鍵的功能,不會關掉手把。",
+ "button": "恢復預設鍵位"
+ }
+ },
+ "stick": {
+ "description": "搖桿可以捲動對話,也可以給四個方向分別指定功能。",
+ "customDescription": "搖桿進入這個方向時觸發一次。",
+ "mode": {
+ "label": "搖桿用途",
+ "description": "捲動對話會依推桿力度連續捲動;自訂則為每個方向單獨指定功能。",
+ "options": {
+ "conversation-scroll": "捲動對話",
+ "custom": "自訂方向"
+ }
+ }
+ },
+ "directions": {
+ "up": "上",
+ "right": "右",
+ "down": "下",
+ "left": "左"
+ },
+ "controls": {
+ "a": "A",
+ "b": "B",
+ "x": "X",
+ "y": "Y",
+ "lb": "LB",
+ "rb": "RB",
+ "lt": "LT",
+ "rt": "RT",
+ "view": "View",
+ "menu": "Menu",
+ "xbox": "Xbox",
+ "ls": "左搖桿按下",
+ "rs": "右搖桿按下",
+ "dpadUp": "方向鍵上",
+ "dpadDown": "方向鍵下",
+ "dpadLeft": "方向鍵左",
+ "dpadRight": "方向鍵右",
+ "leftStick": "左搖桿",
+ "rightStick": "右搖桿"
+ },
+ "actions": {
+ "none": "未設定",
+ "voice": "語音輸入",
+ "voiceDescription": "按住進行語音輸入,鬆開結束。",
+ "commands": "命令",
+ "skills": "技能",
+ "choose": "選擇功能"
+ },
+ "errors": {
+ "load": "無法讀取手把設定",
+ "save": "無法儲存手把設定"
+ },
+ "connection": {
+ "label": "連線",
+ "toggle": {
+ "label": "啟用",
+ "aria": "讓這個 Cindy 在前景時使用 Xbox 手把"
+ },
+ "status": {
+ "connecting": "正在連線",
+ "connected": "已連線",
+ "not-detected": "未偵測到",
+ "present": "已連線",
+ "disabled": "未啟用",
+ "error": "連線異常",
+ "unavailable": "目前系統暫不支援"
+ },
+ "descriptions": {
+ "connecting": "Cindy 正在尋找 Xbox 手把。",
+ "connected": "Cindy 在前景時會監聽這只手把。",
+ "disabled": "啟用後,Cindy 在前景時會監聽手把。",
+ "present": "啟用後,Cindy 在前景時會監聽手把。",
+ "not-detected": "請用 USB 或藍牙連接 Xbox 手把。",
+ "error": "Cindy 暫時無法讀取手把,正在重試。",
+ "unavailable": "這台電腦還不能讀取 Xbox 手把。"
+ }
+ },
+ "device": {
+ "usb": "有線",
+ "bluetooth": "藍牙",
+ "battery": "{{percent}}%",
+ "charging": "充電中 {{percent}}%"
+ }
+ }
},
"ghosts": {
"title": "插件",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index ac5c969cbf..b3ef948712 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1865,6 +1865,22 @@ interface ElectronAPI {
) => () => void;
};
+ xboxGamepad: {
+ getState: () => Promise<import('../shared/xboxGamepad').XboxGamepadState>;
+ setSettings: (
+ patch: import('../shared/xboxGamepad').XboxGamepadSettingsPatch,
+ ) => Promise<import('../shared/xboxGamepad').XboxGamepadState>;
+ resetSettings: () => Promise<import('../shared/xboxGamepad').XboxGamepadState>;
+ probe: () => Promise<import('../shared/xboxGamepad').XboxGamepadState>;
+ setLayoutPreviewActive: (active: boolean) => Promise<void>;
+ onStateChanged: (
+ callback: (state: import('../shared/xboxGamepad').XboxGamepadState) => void,
+ ) => () => void;
+ onPreviewInput: (
+ callback: (input: import('../shared/xboxGamepad').XboxGamepadPreviewInput) => void,
+ ) => () => void;
+ };
+
// ── 右侧栏独立子窗口(RSB window)──────────────────────────────────────
// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期(main: right-sidebar-window/)。
rightSidebarWindow: {
@@ -3570,6 +3586,7 @@ interface ElectronAPI {
/** Query current fullscreen state synchronously on mount (covers IPC events
* that fired before the renderer had a chance to subscribe). */
getFullscreenState: () => Promise<boolean>;
+ toggleFullscreen: () => Promise<boolean>;
/** 窗口是否对用户不可见(最小化 / hide)。装饰动画闸门用它兜底 ——
* backgroundThrottling 关闭时 document.visibilityState 会一直停在 visible。 */
diff --git a/apps/desktop/src/shared/inputDevices.ts b/apps/desktop/src/shared/inputDevices.ts
index 04daa7fa98..a7868daa88 100644
--- a/apps/desktop/src/shared/inputDevices.ts
+++ b/apps/desktop/src/shared/inputDevices.ts
@@ -27,6 +27,7 @@ export const INPUT_DEVICE_COMMAND_IDS = [
'toggleSidebar',
'toggleRightSidebar',
'navigateBack',
+ 'toggleFullscreen',
'composer.focus',
'conversation.scrollUp',
'conversation.scrollDown',
diff --git a/apps/desktop/src/shared/xboxGamepad.ts b/apps/desktop/src/shared/xboxGamepad.ts
new file mode 100644
index 0000000000..16258cc65f
--- /dev/null
+++ b/apps/desktop/src/shared/xboxGamepad.ts
@@ -0,0 +1,288 @@
+import {
+ isInputDeviceCommandId,
+ type InputDeviceCommandId,
+ type InputDeviceDescriptor,
+} from './inputDevices';
+
+export const XBOX_GAMEPAD_DEVICE_ID = 'xbox-gamepad';
+
+export const XBOX_GAMEPAD_DEVICE: InputDeviceDescriptor = {
+ id: XBOX_GAMEPAD_DEVICE_ID,
+ label: 'Xbox',
+ capabilities: [{ kind: 'commands' }, { kind: 'voice' }, { kind: 'stick' }],
+};
+
+export const XBOX_GAMEPAD_GET_STATE_CHANNEL = 'xbox-gamepad:get-state';
+export const XBOX_GAMEPAD_SET_SETTINGS_CHANNEL = 'xbox-gamepad:set-settings';
+export const XBOX_GAMEPAD_RESET_SETTINGS_CHANNEL = 'xbox-gamepad:reset-settings';
+export const XBOX_GAMEPAD_PROBE_CHANNEL = 'xbox-gamepad:probe';
+export const XBOX_GAMEPAD_STATE_CHANGED_CHANNEL = 'xbox-gamepad:state-changed';
+export const XBOX_GAMEPAD_PREVIEW_INPUT_CHANNEL = 'xbox-gamepad:preview-input';
+export const XBOX_GAMEPAD_SET_LAYOUT_PREVIEW_CHANNEL = 'xbox-gamepad:set-layout-preview';
+
+export const XBOX_GAMEPAD_BUTTON_IDS = [
+ 'a',
+ 'b',
+ 'x',
+ 'y',
+ 'lb',
+ 'rb',
+ 'lt',
+ 'rt',
+ 'view',
+ 'menu',
+ 'xbox',
+ 'ls',
+ 'rs',
+ 'dpadUp',
+ 'dpadDown',
+ 'dpadLeft',
+ 'dpadRight',
+] as const;
+
+export const XBOX_GAMEPAD_STICK_IDS = ['left', 'right'] as const;
+export const XBOX_GAMEPAD_STICK_DIRECTIONS = ['up', 'right', 'down', 'left'] as const;
+export const XBOX_GAMEPAD_STICK_MODES = ['conversation-scroll', 'custom'] as const;
+
+export type XboxGamepadButtonId = (typeof XBOX_GAMEPAD_BUTTON_IDS)[number];
+export type XboxGamepadStickId = (typeof XBOX_GAMEPAD_STICK_IDS)[number];
+export type XboxGamepadStickDirection = (typeof XBOX_GAMEPAD_STICK_DIRECTIONS)[number];
+export type XboxGamepadStickMode = (typeof XBOX_GAMEPAD_STICK_MODES)[number];
+
+export type XboxGamepadBinding =
+ | { type: 'command'; commandId: InputDeviceCommandId }
+ | { type: 'skill'; skillId: string; name: string }
+ | { type: 'voice' };
+
+export interface XboxGamepadStickBinding {
+ mode: XboxGamepadStickMode;
+ directions: Record<XboxGamepadStickDirection, XboxGamepadBinding | null>;
+}
+
+export interface XboxGamepadLayout {
+ version: 1;
+ buttons: Record<XboxGamepadButtonId, XboxGamepadBinding | null>;
+ sticks: Record<XboxGamepadStickId, XboxGamepadStickBinding>;
+}
+
+export type XboxGamepadConnectionStatus =
+ | 'connecting'
+ | 'connected'
+ | 'not-detected'
+ | 'disabled'
+ | 'error'
+ | 'unavailable';
+
+export interface XboxGamepadSettings {
+ deviceEnabled: boolean;
+ layout: XboxGamepadLayout;
+}
+
+export type XboxGamepadSettingsPatch = Partial<XboxGamepadSettings>;
+
+export type XboxGamepadTransport = 'usb' | 'bluetooth' | 'unknown';
+export type XboxGamepadBatteryState = 'unknown' | 'discharging' | 'charging' | 'full';
+
+export interface XboxGamepadDeviceInfo {
+ name: string | null;
+ category: string | null;
+ transport: XboxGamepadTransport;
+ batteryPercentage: number | null;
+ batteryState: XboxGamepadBatteryState;
+}
+
+export const XBOX_GAMEPAD_EMPTY_DEVICE: XboxGamepadDeviceInfo = {
+ name: null,
+ category: null,
+ transport: 'unknown',
+ batteryPercentage: null,
+ batteryState: 'unknown',
+};
+
+export interface XboxGamepadState {
+ connectionStatus: XboxGamepadConnectionStatus;
+ devicePresent: boolean | null;
+ deviceName: string | null;
+ device: XboxGamepadDeviceInfo;
+ settings: XboxGamepadSettings;
+}
+
+export interface XboxGamepadPreviewInput {
+ buttons: Record<XboxGamepadButtonId, boolean>;
+ sticks: Record<XboxGamepadStickId, { x: number; y: number }>;
+ triggers: { lt: number; rt: number };
+}
+
+export const XBOX_GAMEPAD_STICK_PREVIEW_TRAVEL_PX = 10;
+
+function emptyButtonBindings(): Record<XboxGamepadButtonId, XboxGamepadBinding | null> {
+ return Object.fromEntries(XBOX_GAMEPAD_BUTTON_IDS.map((id) => [id, null])) as Record<
+ XboxGamepadButtonId,
+ XboxGamepadBinding | null
+ >;
+}
+
+function emptyStickDirections(): Record<XboxGamepadStickDirection, XboxGamepadBinding | null> {
+ return { up: null, right: null, down: null, left: null };
+}
+
+/**
+ * Default map, split the way the Work Louder stick + encoder already work:
+ * left stick is the task list, right stick is the conversation, left/right
+ * open the panel on that side. Face / shoulder / system keys cover the rest
+ * of a hands-on Cindy loop so every control does something.
+ */
+export const XBOX_GAMEPAD_DEFAULT_LAYOUT: XboxGamepadLayout = {
+ version: 1,
+ buttons: {
+ ...emptyButtonBindings(),
+ a: { type: 'command', commandId: 'composer.submit' },
+ b: { type: 'command', commandId: 'navigateBack' },
+ x: { type: 'command', commandId: 'composer.toggleFastMode' },
+ y: { type: 'command', commandId: 'newTask' },
+ lb: { type: 'command', commandId: 'composer.decreaseReasoningEffort' },
+ rb: { type: 'command', commandId: 'composer.increaseReasoningEffort' },
+ lt: { type: 'voice' },
+ rt: { type: 'voice' },
+ view: { type: 'command', commandId: 'toggleFullscreen' },
+ menu: { type: 'command', commandId: 'settings' },
+ xbox: { type: 'command', commandId: 'manageTasks' },
+ ls: { type: 'command', commandId: 'composer.focus' },
+ rs: { type: 'command', commandId: 'conversation.scrollBottom' },
+ dpadUp: { type: 'command', commandId: 'conversation.scrollUp' },
+ dpadDown: { type: 'command', commandId: 'conversation.scrollDown' },
+ dpadLeft: { type: 'command', commandId: 'toggleSidebar' },
+ dpadRight: { type: 'command', commandId: 'toggleRightSidebar' },
+ },
+ sticks: {
+ left: {
+ mode: 'custom',
+ directions: {
+ up: { type: 'command', commandId: 'session.selectPrevious' },
+ down: { type: 'command', commandId: 'session.selectNext' },
+ left: { type: 'command', commandId: 'toggleSidebar' },
+ right: { type: 'command', commandId: 'toggleRightSidebar' },
+ },
+ },
+ right: { mode: 'conversation-scroll', directions: emptyStickDirections() },
+ },
+};
+
+export const XBOX_GAMEPAD_DEFAULT_SETTINGS: XboxGamepadSettings = {
+ deviceEnabled: false,
+ layout: XBOX_GAMEPAD_DEFAULT_LAYOUT,
+};
+
+export const XBOX_GAMEPAD_EMPTY_PREVIEW: XboxGamepadPreviewInput = {
+ buttons: Object.fromEntries(XBOX_GAMEPAD_BUTTON_IDS.map((id) => [id, false])) as Record<
+ XboxGamepadButtonId,
+ boolean
+ >,
+ sticks: {
+ left: { x: 0, y: 0 },
+ right: { x: 0, y: 0 },
+ },
+ triggers: { lt: 0, rt: 0 },
+};
+
+export function isXboxGamepadButtonId(value: unknown): value is XboxGamepadButtonId {
+ return typeof value === 'string' && (XBOX_GAMEPAD_BUTTON_IDS as readonly string[]).includes(value);
+}
+
+export function isXboxGamepadStickId(value: unknown): value is XboxGamepadStickId {
+ return typeof value === 'string' && (XBOX_GAMEPAD_STICK_IDS as readonly string[]).includes(value);
+}
+
+export function isXboxGamepadStickDirection(value: unknown): value is XboxGamepadStickDirection {
+ return (
+ typeof value === 'string' && (XBOX_GAMEPAD_STICK_DIRECTIONS as readonly string[]).includes(value)
+ );
+}
+
+export function isXboxGamepadStickMode(value: unknown): value is XboxGamepadStickMode {
+ return typeof value === 'string' && (XBOX_GAMEPAD_STICK_MODES as readonly string[]).includes(value);
+}
+
+export function cloneXboxGamepadBinding(
+ binding: XboxGamepadBinding | null,
+): XboxGamepadBinding | null {
+ return binding ? { ...binding } : null;
+}
+
+export function cloneXboxGamepadLayout(layout: XboxGamepadLayout): XboxGamepadLayout {
+ return {
+ version: 1,
+ buttons: Object.fromEntries(
+ XBOX_GAMEPAD_BUTTON_IDS.map((id) => [id, cloneXboxGamepadBinding(layout.buttons[id] ?? null)]),
+ ) as XboxGamepadLayout['buttons'],
+ sticks: Object.fromEntries(
+ XBOX_GAMEPAD_STICK_IDS.map((id) => {
+ const stick = layout.sticks[id] ?? XBOX_GAMEPAD_DEFAULT_LAYOUT.sticks[id];
+ return [
+ id,
+ {
+ mode: isXboxGamepadStickMode(stick.mode) ? stick.mode : 'custom',
+ directions: Object.fromEntries(
+ XBOX_GAMEPAD_STICK_DIRECTIONS.map((direction) => [
+ direction,
+ cloneXboxGamepadBinding(stick.directions[direction] ?? null),
+ ]),
+ ) as XboxGamepadStickBinding['directions'],
+ },
+ ];
+ }),
+ ) as XboxGamepadLayout['sticks'],
+ };
+}
+
+export function cloneXboxGamepadSettings(settings: XboxGamepadSettings): XboxGamepadSettings {
+ return {
+ deviceEnabled: settings.deviceEnabled,
+ layout: cloneXboxGamepadLayout(settings.layout),
+ };
+}
+
+export function createXboxGamepadDefaultLayout(): XboxGamepadLayout {
+ return cloneXboxGamepadLayout(XBOX_GAMEPAD_DEFAULT_LAYOUT);
+}
+
+export function createXboxGamepadDefaultSettings(): XboxGamepadSettings {
+ return cloneXboxGamepadSettings(XBOX_GAMEPAD_DEFAULT_SETTINGS);
+}
+
+export function isXboxGamepadBinding(value: unknown): value is XboxGamepadBinding {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const record = value as { type?: unknown; commandId?: unknown; skillId?: unknown; name?: unknown };
+ if (record.type === 'command') return isInputDeviceCommandId(record.commandId);
+ if (record.type === 'skill') {
+ return (
+ typeof record.skillId === 'string' &&
+ record.skillId.length > 0 &&
+ record.skillId.length <= 1_024 &&
+ typeof record.name === 'string' &&
+ record.name.length > 0 &&
+ record.name.length <= 256
+ );
+ }
+ return record.type === 'voice';
+}
+
+/**
+ * Pixel offset for a drawn stick cap. GameController y is up-positive; the
+ * screen's y grows down, so the preview flips that axis.
+ */
+export function xboxGamepadStickPreviewOffset(
+ x: number,
+ y: number,
+ radius: number = XBOX_GAMEPAD_STICK_PREVIEW_TRAVEL_PX,
+): { x: number; y: number } {
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(radius)) {
+ return { x: 0, y: 0 };
+ }
+ const cx = Math.max(-1, Math.min(1, x));
+ const cy = Math.max(-1, Math.min(1, y));
+ return {
+ x: Math.round(cx * radius * 100) / 100,
+ y: Math.round(-cy * radius * 100) / 100,
+ };
+}
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 413437d28e..14f8d081d8 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -155,6 +155,10 @@
**注意别指望 `--update-baseline` 帮你收尾。** `proposed` 存在的理由正是「已知有存量不一致」,改成 `decided` 的那一刻这些告警会变成阻断违规;而 `--update-baseline` 只删不加,遇到 baseline 里没有的指纹会直接拒绝。所以裁决时只有两条路:要么把命中逐条读语境改掉,要么先人工把已 review 过的指纹写进 `i18n/glossary-baseline.json` 冻结存量,之后再用 `--update-baseline` 做修剪。
+### Accessories
+
+设置 → 键盘快捷键里,尚未检测到的硬件输入设备(Work Louder 键盘、Xbox 手柄等)收在这一栏。已插入的设备单独成卡,不进这一栏。与 device-link 的「设备/设备互联」不是同一概念。
+
### Anthropic Messages
Anthropic Messages API / wire protocol 的用户可见名称。四语统一保留官方英文名称,避免与普通的“消息”概念混译;先登记为 proposed,待产品术语评审后固化。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index e54a99ef35..5eea0b7b44 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -68,6 +68,18 @@
},
"note": "远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。"
},
+ {
+ "id": "accessories",
+ "status": "proposed",
+ "en": "Accessories",
+ "translations": {
+ "zh-CN": "配件",
+ "zh-TW": "配件",
+ "ja": "アクセサリ",
+ "ko": "액세서리"
+ },
+ "note": "设置 → 键盘快捷键里,尚未检测到的硬件输入设备(Work Louder 键盘、Xbox 手柄等)收在这一栏。已插入的设备单独成卡,不进这一栏。与 device-link 的「设备/设备互联」不是同一概念。"
+ },
{
"id": "captcha",
"status": "proposed",