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): 集成 Codex Micro 设备保护 (#3698)

Chris Zhang838e3cf7c9a5
diff --git a/apps/desktop/src/main/vendor.d.ts b/apps/desktop/src/main/vendor.d.ts
index 38129e4c67..59a9063f26 100644
--- a/apps/desktop/src/main/vendor.d.ts
+++ b/apps/desktop/src/main/vendor.d.ts
@@ -13,3 +13,8 @@ declare module '*.md?raw' {
const content: string;
export default content;
}
+
+declare module '*.cjs?raw' {
+ const content: string;
+ export default content;
+}
diff --git a/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
new file mode 100644
index 0000000000..27fcbfb032
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
@@ -0,0 +1,295 @@
+import crypto from 'node:crypto';
+import os from 'node:os';
+import path from 'node:path';
+import { app } from 'electron';
+
+import type { CodexMicroGuardState } from '../../shared/codexMicroGuard.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import {
+ createOverrideSettingsFile,
+ type OverrideSettingsFile,
+} from '../maker-host/override-settings-file.js';
+import hookContents from './codexMicroGuardHook.cjs?raw';
+import {
+ CodexMicroGuardManager,
+ CodexMicroGuardStore,
+ LaunchctlGuardCommandRunner,
+ type GuardCommandRunner,
+} from './codexMicroGuardCore.js';
+
+interface CodexMicroGuardSettings {
+ enabled: boolean;
+}
+
+interface CodexMicroGuardServiceOptions {
+ platform?: NodeJS.Platform;
+ supportPath?: string;
+ settingsPath?: string;
+ launchctlDomain?: string;
+ runner?: GuardCommandRunner;
+ hookContents?: string;
+ heartbeatIntervalMs?: number;
+}
+
+const log = desktopMakerLogger.child('codex-micro-guard');
+const DEFAULT_SETTINGS: CodexMicroGuardSettings = { enabled: false };
+const MAX_SETTINGS_BYTES = 8 * 1024;
+const HEARTBEAT_INTERVAL_MS = 5_000;
+
+export class CodexMicroGuardService {
+ private readonly platform: NodeJS.Platform;
+ private readonly store: CodexMicroGuardStore;
+ private readonly manager: CodexMicroGuardManager;
+ private readonly settingsStore: OverrideSettingsFile<CodexMicroGuardSettings>;
+ private readonly hookContents: string;
+ private readonly heartbeatIntervalMs: number;
+ private readonly listeners = new Set<(state: CodexMicroGuardState) => void>();
+ private initializePromise: Promise<void> | null = null;
+ private mutation: Promise<void> = Promise.resolve();
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
+ private active = false;
+ private failed = false;
+ private recoveryRequired = false;
+ private disposed = false;
+ private lastEmittedState: string | null = null;
+
+ constructor(options: CodexMicroGuardServiceOptions = {}) {
+ this.platform = options.platform ?? process.platform;
+ const supportPath = options.supportPath ?? defaultSupportPath();
+ this.store = new CodexMicroGuardStore(supportPath);
+ this.manager = new CodexMicroGuardManager(
+ this.store,
+ options.runner ?? new LaunchctlGuardCommandRunner(),
+ options.launchctlDomain ??
+ (this.platform === 'darwin' ? `gui/${currentUid()}` : 'gui/unsupported'),
+ crypto.randomUUID(),
+ );
+ this.hookContents = options.hookContents ?? hookContents;
+ this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
+ const settingsPath =
+ options.settingsPath ?? path.join(app.getPath('userData'), 'codex-micro-guard.json');
+ this.settingsStore = createOverrideSettingsFile<CodexMicroGuardSettings>({
+ filePath: () => settingsPath,
+ defaults: DEFAULT_SETTINGS,
+ normalize: normalizeSettings,
+ log,
+ label: 'Codex Micro guard',
+ maxBytes: MAX_SETTINGS_BYTES,
+ preserveUnreadableFile: true,
+ logLoadedValue: false,
+ logReadErrorDetails: false,
+ });
+ }
+
+ initialize(): Promise<void> {
+ if (!this.initializePromise) this.initializePromise = this.initializeInternal();
+ return this.initializePromise;
+ }
+
+ async getState(): Promise<CodexMicroGuardState> {
+ await this.initialize();
+ return this.snapshot();
+ }
+
+ async setEnabled(enabled: boolean): Promise<CodexMicroGuardState> {
+ await this.initialize();
+ if (this.platform !== 'darwin') return this.snapshot();
+ await this.enqueue(async () => {
+ if (this.disposed) throw new Error('Codex Micro guard service is disposed');
+ if (enabled) await this.enable();
+ else await this.disable({ persistSetting: true });
+ });
+ return this.snapshot();
+ }
+
+ async recover(): Promise<CodexMicroGuardState> {
+ await this.initialize();
+ if (this.platform !== 'darwin') return this.snapshot();
+ await this.enqueue(async () => {
+ if (this.disposed) throw new Error('Codex Micro guard service is disposed');
+ this.settingsStore.writePatch({ enabled: false });
+ this.stopHeartbeat();
+ this.active = false;
+ await this.manager.disable();
+ this.failed = false;
+ this.recoveryRequired = false;
+ this.emitIfChanged();
+ });
+ return this.snapshot();
+ }
+
+ subscribe(listener: (state: CodexMicroGuardState) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ async dispose(): Promise<void> {
+ await this.initialize();
+ await this.enqueue(async () => {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.stopHeartbeat();
+ if (this.platform !== 'darwin') return;
+ try {
+ if (this.active || this.hasRecoveryState()) await this.manager.disable();
+ this.active = false;
+ this.recoveryRequired = false;
+ } catch {
+ this.active = false;
+ this.recoveryRequired = true;
+ log.warn('Codex Micro guard shutdown recovery failed');
+ }
+ });
+ this.listeners.clear();
+ }
+
+ private async initializeInternal(): Promise<void> {
+ if (this.platform !== 'darwin') return;
+ const enabled = this.settingsStore.read().enabled;
+ try {
+ if (enabled) {
+ await this.manager.enable(this.hookContents);
+ this.active = true;
+ this.startHeartbeat();
+ } else if (this.hasRecoveryState()) {
+ // A previous Cindy process stopped during restoration. The hook is
+ // already fail-open once its heartbeat expires; finish restoring the
+ // launch environment before exposing the disabled state.
+ await this.manager.disable();
+ }
+ this.failed = false;
+ this.recoveryRequired = false;
+ } catch {
+ this.active = false;
+ this.failed = true;
+ this.recoveryRequired = this.hasRecoveryState();
+ log.warn('Codex Micro guard initialization failed');
+ }
+ this.emitIfChanged();
+ }
+
+ private async enable(): Promise<void> {
+ if (this.active && this.store.isFresh()) return;
+ this.failed = false;
+ this.recoveryRequired = false;
+ await this.manager.enable(this.hookContents);
+ try {
+ this.settingsStore.writePatch({ enabled: true });
+ } catch (error) {
+ try {
+ await this.manager.disable();
+ } catch {
+ this.recoveryRequired = true;
+ }
+ throw error;
+ }
+ this.active = true;
+ this.startHeartbeat();
+ this.emitIfChanged();
+ }
+
+ private async disable(options: { persistSetting: boolean }): Promise<void> {
+ if (options.persistSetting) this.settingsStore.writePatch({ enabled: false });
+ this.stopHeartbeat();
+ this.active = false;
+ try {
+ await this.manager.disable();
+ this.failed = false;
+ this.recoveryRequired = false;
+ } catch (error) {
+ this.failed = true;
+ this.recoveryRequired = true;
+ this.emitIfChanged();
+ throw error;
+ }
+ this.emitIfChanged();
+ }
+
+ private startHeartbeat(): void {
+ this.stopHeartbeat();
+ this.heartbeatTimer = setInterval(() => {
+ void this.enqueue(async () => {
+ if (!this.active || this.disposed) return;
+ try {
+ await this.manager.refreshHeartbeat();
+ } catch {
+ this.stopHeartbeat();
+ this.active = false;
+ this.failed = true;
+ try {
+ await this.manager.disable();
+ this.recoveryRequired = false;
+ } catch {
+ this.recoveryRequired = true;
+ }
+ log.warn('Codex Micro guard heartbeat failed and protection was stopped');
+ }
+ this.emitIfChanged();
+ });
+ }, this.heartbeatIntervalMs);
+ this.heartbeatTimer.unref?.();
+ }
+
+ private stopHeartbeat(): void {
+ if (!this.heartbeatTimer) return;
+ clearInterval(this.heartbeatTimer);
+ this.heartbeatTimer = null;
+ }
+
+ private hasRecoveryState(): boolean {
+ try {
+ return this.store.readState() !== null;
+ } catch {
+ return true;
+ }
+ }
+
+ private snapshot(): CodexMicroGuardState {
+ if (this.platform !== 'darwin') {
+ return { supported: false, enabled: false, status: 'unsupported' };
+ }
+ const enabled = this.settingsStore.read().enabled;
+ let status: CodexMicroGuardState['status'];
+ if (this.recoveryRequired) status = 'recovery-required';
+ else if (this.failed) status = 'error';
+ else if (!this.active || !this.store.isFresh()) status = 'disabled';
+ else status = this.store.hasInterceptionReceipt() ? 'intercepted' : 'protecting';
+ return { supported: true, enabled, status };
+ }
+
+ private emitIfChanged(): void {
+ const state = this.snapshot();
+ const serialized = JSON.stringify(state);
+ if (serialized === this.lastEmittedState) return;
+ this.lastEmittedState = serialized;
+ for (const listener of this.listeners) listener(state);
+ }
+
+ private async enqueue(operation: () => Promise<void>): Promise<void> {
+ const next = this.mutation.then(operation, operation);
+ this.mutation = next.catch(() => undefined);
+ await next;
+ }
+}
+
+function normalizeSettings(raw: unknown): CodexMicroGuardSettings {
+ const enabled =
+ raw && typeof raw === 'object' ? (raw as { enabled?: unknown }).enabled : undefined;
+ return { enabled: typeof enabled === 'boolean' ? enabled : DEFAULT_SETTINGS.enabled };
+}
+
+function defaultSupportPath(): string {
+ const identity = crypto
+ .createHash('sha256')
+ .update(app.getPath('userData'))
+ .digest('hex')
+ .slice(0, 12);
+ return path.join(os.homedir(), 'Library', 'CindyCodexMicroGuard', identity);
+}
+
+function currentUid(): number {
+ if (typeof process.getuid !== 'function') throw new Error('macOS user id is unavailable');
+ return process.getuid();
+}
+
+export const __testing = { normalizeSettings, defaultSupportPath };
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
new file mode 100644
index 0000000000..69d8b16199
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
@@ -0,0 +1,197 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { GuardCommandResult, GuardCommandRunner } from '../codexMicroGuardCore.js';
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/unused' },
+}));
+
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({ info: vi.fn(), warn: vi.fn() }),
+ },
+}));
+
+import { CodexMicroGuardService } from '../CodexMicroGuardService.js';
+
+const roots: string[] = [];
+
+class EnvironmentRunner implements GuardCommandRunner {
+ nodeOptions: string | null;
+ readonly commands: string[][] = [];
+ failNextMutation = false;
+
+ constructor(nodeOptions: string | null) {
+ this.nodeOptions = nodeOptions;
+ }
+
+ async run(arguments_: readonly string[]): Promise<GuardCommandResult> {
+ this.commands.push([...arguments_]);
+ if (arguments_[0] === 'print') {
+ return {
+ status: 0,
+ stdout: printEnvironment(this.nodeOptions),
+ stderr: '',
+ };
+ }
+ if (this.failNextMutation) {
+ this.failNextMutation = false;
+ return { status: 7, stdout: '', stderr: 'failed' };
+ }
+ if (arguments_[0] === 'setenv') this.nodeOptions = arguments_[2] ?? '';
+ if (arguments_[0] === 'unsetenv') this.nodeOptions = null;
+ return { status: 0, stdout: '', stderr: '' };
+ }
+}
+
+function printEnvironment(nodeOptions: string | null): string {
+ return `gui/501 = {\n\tenvironment = {\n\t\tPATH => /bin\n${
+ nodeOptions === null ? '' : `\t\tNODE_OPTIONS =>${nodeOptions ? ` ${nodeOptions}` : ''}\n`
+ }\t}\n}\n`;
+}
+
+function paths() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-guard-service-'));
+ roots.push(root);
+ return {
+ supportPath: path.join(root, 'support'),
+ settingsPath: path.join(root, 'settings.json'),
+ };
+}
+
+function service(
+ paths_: ReturnType<typeof paths>,
+ runner: GuardCommandRunner,
+): CodexMicroGuardService {
+ return new CodexMicroGuardService({
+ platform: 'darwin',
+ ...paths_,
+ launchctlDomain: 'gui/501',
+ runner,
+ hookContents: '// safe test hook\n',
+ heartbeatIntervalMs: 60_000,
+ });
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('CodexMicroGuardService', () => {
+ it('reports unsupported without touching launchctl on other platforms', async () => {
+ const locations = paths();
+ const runner = new EnvironmentRunner('--trace-warnings');
+ const instance = new CodexMicroGuardService({
+ platform: 'win32',
+ ...locations,
+ runner,
+ hookContents: '// hook\n',
+ });
+
+ expect(await instance.getState()).toEqual({
+ supported: false,
+ enabled: false,
+ status: 'unsupported',
+ });
+ expect(runner.commands).toEqual([]);
+ await instance.dispose();
+ });
+
+ it('persists an override, reports interception, and restores on graceful quit', async () => {
+ const locations = paths();
+ const runner = new EnvironmentRunner('--trace-warnings');
+ const instance = service(locations, runner);
+
+ expect(await instance.getState()).toMatchObject({ enabled: false, status: 'disabled' });
+ expect(await instance.setEnabled(true)).toMatchObject({ enabled: true, status: 'protecting' });
+ expect(runner.nodeOptions).toBe(
+ `--trace-warnings --require=${path.join(locations.supportPath, 'guard-hook.cjs')}`,
+ );
+ expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: true });
+
+ fs.writeFileSync(
+ path.join(locations.supportPath, 'receipt.json'),
+ JSON.stringify({ interceptedAt: Date.now() / 1_000, service: 'service-fixture.js' }),
+ { mode: 0o600 },
+ );
+ expect(await instance.getState()).toMatchObject({ status: 'intercepted' });
+
+ await instance.dispose();
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ // Graceful quit restores the environment but preserves the user's setting,
+ // so the next Cindy launch resumes protection.
+ expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: true });
+ });
+
+ it('keeps shared protection until the final live instance exits', async () => {
+ const locations = paths();
+ const runner = new EnvironmentRunner(null);
+ const first = service(locations, runner);
+ const second = service(locations, runner);
+ const token = `--require=${path.join(locations.supportPath, 'guard-hook.cjs')}`;
+
+ await first.setEnabled(true);
+ expect(await second.getState()).toMatchObject({ enabled: true, status: 'protecting' });
+
+ await first.dispose();
+ expect(runner.nodeOptions).toBe(token);
+ expect(fs.existsSync(path.join(locations.supportPath, 'enabled'))).toBe(true);
+ expect(await second.getState()).toMatchObject({ enabled: true, status: 'protecting' });
+
+ await second.dispose();
+ expect(runner.nodeOptions).toBeNull();
+ expect(fs.existsSync(path.join(locations.supportPath, 'enabled'))).toBe(false);
+ });
+
+ it('re-enables a persisted preference on startup and recover turns it off', async () => {
+ const locations = paths();
+ fs.writeFileSync(locations.settingsPath, JSON.stringify({ enabled: true }));
+ const runner = new EnvironmentRunner(null);
+ const instance = service(locations, runner);
+
+ expect(await instance.getState()).toMatchObject({ enabled: true, status: 'protecting' });
+ expect(runner.nodeOptions).toBe(
+ `--require=${path.join(locations.supportPath, 'guard-hook.cjs')}`,
+ );
+
+ expect(await instance.recover()).toMatchObject({ enabled: false, status: 'disabled' });
+ expect(runner.nodeOptions).toBeNull();
+ expect(fs.existsSync(locations.settingsPath)).toBe(false);
+ await instance.dispose();
+ });
+
+ it('serializes rapid toggles and preserves the original environment', async () => {
+ const locations = paths();
+ const runner = new EnvironmentRunner('--trace-warnings');
+ const instance = service(locations, runner);
+
+ const enable = instance.setEnabled(true);
+ const disable = instance.setEnabled(false);
+ await Promise.all([enable, disable]);
+
+ expect(await instance.getState()).toMatchObject({ enabled: false, status: 'disabled' });
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ expect(fs.existsSync(locations.settingsPath)).toBe(false);
+ await instance.dispose();
+ });
+
+ it('deactivates markers and exposes recovery when restoration fails', async () => {
+ const locations = paths();
+ const runner = new EnvironmentRunner(null);
+ const instance = service(locations, runner);
+ await instance.setEnabled(true);
+ runner.failNextMutation = true;
+
+ await expect(instance.setEnabled(false)).rejects.toThrow();
+ expect(await instance.getState()).toMatchObject({
+ enabled: false,
+ status: 'recovery-required',
+ });
+ expect(fs.existsSync(path.join(locations.supportPath, 'enabled'))).toBe(false);
+ await instance.recover();
+ await instance.dispose();
+ });
+});
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts
new file mode 100644
index 0000000000..e02bc6ca78
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts
@@ -0,0 +1,237 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ CodexMicroGuardManager,
+ CodexMicroGuardStore,
+ mergeNodeOptions,
+ nodeOptionsContains,
+ parseLaunchEnvironmentNodeOptions,
+ removeNodeOption,
+ restoreNodeOptions,
+ type GuardCommandResult,
+ type GuardCommandRunner,
+} from '../codexMicroGuardCore.js';
+
+const roots: string[] = [];
+const LEASE_ID = '11111111-1111-4111-8111-111111111111';
+
+class FakeRunner implements GuardCommandRunner {
+ readonly commands: string[][] = [];
+
+ constructor(private readonly responses: GuardCommandResult[]) {}
+
+ async run(arguments_: readonly string[]): Promise<GuardCommandResult> {
+ this.commands.push([...arguments_]);
+ const response = this.responses.shift();
+ if (!response) throw new Error('unexpected launchctl command');
+ return response;
+ }
+}
+
+function temporaryStore(): CodexMicroGuardStore {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-guard-'));
+ roots.push(root);
+ return new CodexMicroGuardStore(path.join(root, 'support'));
+}
+
+function printed(nodeOptions?: string): string {
+ return `gui/501 = {\n\ttype = login\n\tenvironment = {\n\t\tPATH => /bin\n${
+ nodeOptions === undefined ? '' : `\t\tNODE_OPTIONS =>${nodeOptions ? ` ${nodeOptions}` : ''}\n`
+ }\t}\n\tservices = {\n\t\t 900 - application.example\n\t}\n}\n`;
+}
+
+function result(stdout = '', status = 0): GuardCommandResult {
+ return { status, stdout, stderr: '' };
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('Codex Micro guard NODE_OPTIONS handling', () => {
+ it('merges once and removes only the bounded guard token', () => {
+ const token = '--require=/tmp/guard.cjs';
+ expect(mergeNodeOptions('--trace-warnings', token)).toBe(`--trace-warnings ${token}`);
+ expect(mergeNodeOptions(`--trace-warnings ${token}`, token)).toBe(`--trace-warnings ${token}`);
+ expect(nodeOptionsContains(token, `--trace-warnings ${token}`)).toBe(true);
+ expect(removeNodeOption(token, `--trace-warnings ${token} --inspect=9229`)).toBe(
+ '--trace-warnings --inspect=9229',
+ );
+ expect(removeNodeOption(token, `${token}-other`)).toBe(`${token}-other`);
+ });
+
+ it('keeps independently managed preload tokens composable in either shutdown order', () => {
+ const first = '--require=/tmp/first.cjs';
+ const second = '--require=/tmp/second.cjs';
+ expect(restoreNodeOptions(null, first, `${first} ${second}`, first)).toBe(second);
+ expect(restoreNodeOptions(first, `${first} ${second}`, second, second)).toBeNull();
+ expect(restoreNodeOptions(first, `${first} ${second}`, `${first} ${second}`, second)).toBe(
+ first,
+ );
+ });
+
+ it('restores the exact original but preserves later external changes', () => {
+ const token = '--require=/tmp/guard.cjs';
+ const original = " --title='two spaces' ";
+ const installed = `${original} ${token}`;
+ expect(restoreNodeOptions(original, installed, installed, token)).toBe(original);
+ expect(restoreNodeOptions(original, installed, `${installed}\t--inspect=9229`, token)).toBe(
+ `${original}\t--inspect=9229`,
+ );
+ expect(
+ restoreNodeOptions(
+ `${original} ${token}`,
+ `${original} ${token}`,
+ `${original} ${token} --inspect`,
+ token,
+ ),
+ ).toBe(`${original} ${token} --inspect`);
+ });
+});
+
+describe('Codex Micro guard launchctl parsing', () => {
+ it('distinguishes absent, empty, and present NODE_OPTIONS', () => {
+ expect(parseLaunchEnvironmentNodeOptions(printed())).toEqual({ kind: 'absent' });
+ expect(parseLaunchEnvironmentNodeOptions(printed(''))).toEqual({ kind: 'present', value: '' });
+ expect(parseLaunchEnvironmentNodeOptions(printed('--trace-warnings'))).toEqual({
+ kind: 'present',
+ value: '--trace-warnings',
+ });
+ });
+
+ it('ignores opaque service rows and nested service environments', () => {
+ const input =
+ 'gui/501 = {\n\tenvironment = {\n\t\tPATH => /bin\n\t}\n\tservices = {\n' +
+ '\t\t 58963 - application.example\n\t\tcom.example = {\n\t\t\tenvironment = {\n' +
+ '\t\t\t\tNODE_OPTIONS => --wrong\n\t\t\t}\n\t\t}\n\t}\n}\n';
+ expect(parseLaunchEnvironmentNodeOptions(input)).toEqual({ kind: 'absent' });
+ });
+
+ it.each([
+ '',
+ 'gui/501 = {\n\tenvironment = {\n',
+ 'unexpected = {\n\tenvironment = {\n\t}\n}\n',
+ 'gui/501 = {\n\tservices = {\n\t}\n}\n',
+ ])('rejects an unverified launchctl snapshot', (input) => {
+ expect(parseLaunchEnvironmentNodeOptions(input)).toEqual({ kind: 'invalid' });
+ });
+});
+
+describe('Codex Micro guard store and manager', () => {
+ it('writes private files and rejects a symlinked support directory', () => {
+ const store = temporaryStore();
+ store.writeState({ version: 1, originalNodeOptions: null, installedNodeOptions: 'x' });
+ if (process.platform !== 'win32') {
+ expect(fs.statSync(store.supportPath).mode & 0o777).toBe(0o700);
+ expect(fs.statSync(store.statePath).mode & 0o777).toBe(0o600);
+ }
+
+ const linkedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-guard-link-'));
+ roots.push(linkedRoot);
+ fs.mkdirSync(path.join(linkedRoot, 'real'));
+ fs.symlinkSync(path.join(linkedRoot, 'real'), path.join(linkedRoot, 'support'));
+ expect(() => new CodexMicroGuardStore(path.join(linkedRoot, 'support')).prepare()).toThrow(
+ 'unsafe',
+ );
+ });
+
+ it('rejects an expired lease heartbeat and safely reclaims stale leases', async () => {
+ const store = temporaryStore();
+ const staleLease = '22222222-2222-4222-8222-222222222222';
+ const manager = new CodexMicroGuardManager(
+ store,
+ new FakeRunner([]),
+ 'gui/501',
+ staleLease,
+ );
+ store.registerLease(staleLease, 100_000);
+
+ await expect(manager.refreshHeartbeat(115_001)).rejects.toThrow(
+ 'lease is no longer fresh',
+ );
+ expect(store.releaseLease(LEASE_ID, 115_001)).toBe(false);
+ expect(
+ fs.existsSync(path.join(store.supportPath, `lease-${staleLease}.json`)),
+ ).toBe(false);
+ });
+
+ it('enables from a verified snapshot and restores the original value', async () => {
+ const store = temporaryStore();
+ const runner = new FakeRunner([
+ result(printed('--trace-warnings')),
+ result(),
+ result(printed(`--trace-warnings --require=${store.hookPath}`)),
+ result(),
+ ]);
+ const manager = new CodexMicroGuardManager(store, runner, 'gui/501', LEASE_ID);
+
+ await manager.enable('// hook\n', 100_000);
+ expect(store.isFresh(100_000)).toBe(true);
+ expect(store.readState()).toEqual({
+ version: 1,
+ originalNodeOptions: '--trace-warnings',
+ installedNodeOptions: `--trace-warnings ${manager.token}`,
+ });
+ expect(runner.commands.slice(0, 2)).toEqual([
+ ['print', 'gui/501'],
+ ['setenv', 'NODE_OPTIONS', `--trace-warnings ${manager.token}`],
+ ]);
+
+ await manager.disable(100_000);
+ expect(runner.commands.at(-1)).toEqual(['setenv', 'NODE_OPTIONS', '--trace-warnings']);
+ expect(store.readState()).toBeNull();
+ expect(store.isFresh(100_000)).toBe(false);
+ });
+
+ it('preserves NODE_OPTIONS changes made after activation', async () => {
+ const store = temporaryStore();
+ const token = `--require=${store.hookPath}`;
+ store.writeState({
+ version: 1,
+ originalNodeOptions: '--trace-warnings',
+ installedNodeOptions: `--trace-warnings ${token}`,
+ });
+ store.markEnabled();
+ store.writeHeartbeat(100_000);
+ const runner = new FakeRunner([
+ result(printed(`--trace-warnings ${token} --inspect=9229`)),
+ result(),
+ ]);
+ await new CodexMicroGuardManager(store, runner, 'gui/501', LEASE_ID).disable();
+ expect(runner.commands.at(-1)).toEqual([
+ 'setenv',
+ 'NODE_OPTIONS',
+ '--trace-warnings --inspect=9229',
+ ]);
+ });
+
+ it('rolls markers and recovery state back when launchctl activation fails', async () => {
+ const store = temporaryStore();
+ const runner = new FakeRunner([result(printed()), result('', 9)]);
+ const manager = new CodexMicroGuardManager(store, runner, 'gui/501', LEASE_ID);
+
+ await expect(manager.enable('// hook\n')).rejects.toThrow(
+ 'launchctl command failed',
+ );
+ expect(store.readState()).toBeNull();
+ expect(store.isFresh()).toBe(false);
+ });
+
+ it('deactivates the hook but keeps recovery state when restoration fails', async () => {
+ const store = temporaryStore();
+ const token = `--require=${store.hookPath}`;
+ store.writeState({ version: 1, originalNodeOptions: null, installedNodeOptions: token });
+ store.markEnabled();
+ store.writeHeartbeat();
+ const runner = new FakeRunner([result(printed(token)), result('', 7)]);
+
+ await expect(
+ new CodexMicroGuardManager(store, runner, 'gui/501', LEASE_ID).disable(),
+ ).rejects.toThrow();
+ expect(store.isFresh()).toBe(false);
+ expect(store.readState()).not.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardHook.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardHook.test.ts
new file mode 100644
index 0000000000..b673658f3b
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardHook.test.ts
@@ -0,0 +1,167 @@
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+const roots: string[] = [];
+const hookSourcePath = path.resolve(__dirname, '../codexMicroGuardHook.cjs');
+const SERVICE_SOURCE = `
+// HID topology watcher addon not found
+// @worklouder/device-kit-oai
+// exports.CodexMicroService=
+// getState(){
+// start(){
+// async updateLighting(
+// async stop(){
+// dispose(){
+throw new Error('real hardware service evaluated');
+`;
+
+interface Fixture {
+ root: string;
+ support: string;
+ build: string;
+ hook: string;
+ productionHook: string;
+}
+
+function fixture(): Fixture {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-hook-'));
+ roots.push(root);
+ const support = path.join(root, 'support');
+ const build = path.join(
+ root,
+ 'Applications',
+ 'ChatGPT.app',
+ 'Contents',
+ 'Resources',
+ 'app.asar',
+ '.vite',
+ 'build',
+ );
+ fs.mkdirSync(support, { recursive: true, mode: 0o700 });
+ fs.mkdirSync(build, { recursive: true });
+ const source = fs.readFileSync(hookSourcePath, 'utf8');
+ const productionHook = path.join(support, 'production-hook.cjs');
+ fs.writeFileSync(productionHook, source, { mode: 0o600 });
+ const transformed = source.replace(
+ /function runtimeScope\(\) \{[\s\S]*?\n\}/u,
+ `function runtimeScope() { return ${JSON.stringify(fs.realpathSync(build))}; }`,
+ );
+ const hook = path.join(support, 'guard-hook.cjs');
+ fs.writeFileSync(hook, transformed, { mode: 0o600 });
+ fs.writeFileSync(path.join(support, 'enabled'), '', { mode: 0o600 });
+ fs.writeFileSync(path.join(support, 'heartbeat'), JSON.stringify(Date.now() / 1_000), {
+ mode: 0o600,
+ });
+ return { root, support, build, hook, productionHook };
+}
+
+function run(
+ value: Fixture,
+ serviceSource: string,
+ mainName = 'main-fixture.js',
+): ReturnType<typeof spawnSync> {
+ const main = path.join(value.build, mainName);
+ const service = path.join(value.build, 'service-fixture.js');
+ fs.writeFileSync(
+ main,
+ "const { CodexMicroService } = require('./service-fixture.js');\n" +
+ 'const service = new CodexMicroService({});\n' +
+ 'service.start();\nprocess.stdout.write(JSON.stringify(service.getState()));\n',
+ );
+ fs.writeFileSync(service, serviceSource);
+ return spawnSync(process.execPath, ['--require', value.hook, main], {
+ encoding: 'utf8',
+ env: process.env,
+ });
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('Codex Micro preload guard', () => {
+ it('ships without a test-mode escape and validates private stable files', () => {
+ const source = fs.readFileSync(hookSourcePath, 'utf8');
+ expect(source).not.toMatch(/CODEX_MICRO_GUARD_TEST/u);
+ expect(source).toMatch(/O_NOFOLLOW/u);
+ expect(source).toMatch(/captureSupportChain/u);
+ expect(source).toMatch(/assertSupportChainStable/u);
+ expect(source).not.toMatch(/process\.platform !== 'win32'/u);
+ expect(source).toMatch(/HID topology watcher addon not found/u);
+ expect(source).toMatch(/@worklouder\/device-kit-oai/u);
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'intercepts only the marked service under a main bundle parent',
+ () => {
+ const value = fixture();
+ const result = run(value, SERVICE_SOURCE);
+ expect(result.status, String(result.stderr)).toBe(0);
+ expect(JSON.parse(String(result.stdout))).toEqual({
+ status: 'unavailable',
+ controlPlaneStatus: 'unavailable',
+ transport: null,
+ model: null,
+ error: null,
+ battery: null,
+ });
+ const receiptPath = path.join(value.support, 'receipt.json');
+ expect(JSON.parse(fs.readFileSync(receiptPath, 'utf8')).service).toBe(
+ 'service-fixture.js',
+ );
+ expect(fs.statSync(receiptPath).mode & 0o777).toBe(0o600);
+ },
+ );
+
+ it.each([
+ [
+ 'stale heartbeat',
+ (value: Fixture) =>
+ fs.writeFileSync(
+ path.join(value.support, 'heartbeat'),
+ JSON.stringify(Date.now() / 1_000 - 16),
+ { mode: 0o600 },
+ ),
+ ],
+ [
+ 'missing enabled marker',
+ (value: Fixture) => fs.unlinkSync(path.join(value.support, 'enabled')),
+ ],
+ ['public marker', (value: Fixture) => fs.chmodSync(path.join(value.support, 'enabled'), 0o644)],
+ ])('fails open for a %s', (_name, mutate) => {
+ const value = fixture();
+ mutate(value);
+ const result = run(value, SERVICE_SOURCE);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('real hardware service evaluated');
+ });
+
+ it('fails open for missing service markers and a non-main parent', () => {
+ const value = fixture();
+ expect(
+ run(
+ value,
+ '// HID topology watcher addon not found\n// @worklouder/device-kit-oai\n' +
+ "throw new Error('real hardware service evaluated');\n",
+ ).status,
+ ).toBe(1);
+ expect(run(value, SERVICE_SOURCE, 'renderer-fixture.js').status).toBe(1);
+ });
+
+ it('does not affect an ordinary Node process with the shipped production scope', () => {
+ const value = fixture();
+ const main = path.join(value.build, 'main-fixture.js');
+ const service = path.join(value.build, 'service-fixture.js');
+ fs.writeFileSync(main, "require('./service-fixture.js');\n");
+ fs.writeFileSync(service, SERVICE_SOURCE);
+ const result = spawnSync(process.execPath, ['--require', value.productionHook, main], {
+ encoding: 'utf8',
+ env: process.env,
+ });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('real hardware service evaluated');
+ });
+});
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardIpc.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardIpc.test.ts
new file mode 100644
index 0000000000..68682f97de
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardIpc.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { CodexMicroGuardState } from '../../../shared/codexMicroGuard.js';
+import { createCodexMicroGuardIpc } from '../codexMicroGuardIpc.js';
+
+const EVENT = { senderFrame: 'trusted' };
+const DISABLED: CodexMicroGuardState = {
+ supported: true,
+ enabled: false,
+ status: 'disabled',
+};
+
+describe('Codex Micro guard IPC', () => {
+ it('checks sender trust before every operation', async () => {
+ const assertTrustedSender = vi.fn(() => {
+ throw new Error('untrusted');
+ });
+ const getState = vi.fn(async () => DISABLED);
+ const setEnabled = vi.fn(async () => DISABLED);
+ const recover = vi.fn(async () => DISABLED);
+ const ipc = createCodexMicroGuardIpc({
+ assertTrustedSender,
+ getState,
+ setEnabled,
+ recover,
+ });
+
+ await expect(ipc.get(EVENT)).rejects.toThrow('untrusted');
+ await expect(ipc.setEnabled(EVENT, true)).rejects.toThrow('untrusted');
+ await expect(ipc.recover(EVENT)).rejects.toThrow('untrusted');
+ expect(getState).not.toHaveBeenCalled();
+ expect(setEnabled).not.toHaveBeenCalled();
+ expect(recover).not.toHaveBeenCalled();
+ });
+
+ it('accepts only a boolean setting and returns the service state', async () => {
+ const enabled: CodexMicroGuardState = {
+ supported: true,
+ enabled: true,
+ status: 'protecting',
+ };
+ const setEnabled = vi.fn(async () => enabled);
+ const ipc = createCodexMicroGuardIpc({
+ assertTrustedSender: vi.fn(),
+ getState: vi.fn(async () => DISABLED),
+ setEnabled,
+ recover: vi.fn(async () => DISABLED),
+ });
+
+ await expect(ipc.setEnabled(EVENT, 'yes')).rejects.toThrow('[INVALID_PARAMS]');
+ await expect(ipc.setEnabled(EVENT, true)).resolves.toEqual(enabled);
+ expect(setEnabled).toHaveBeenCalledWith(true);
+ });
+
+ it('maps service failures to INTERNAL without leaking details', async () => {
+ const ipc = createCodexMicroGuardIpc({
+ assertTrustedSender: vi.fn(),
+ getState: vi.fn(async () => {
+ throw new Error('private /Users/example/path');
+ }),
+ setEnabled: vi.fn(async () => {
+ throw new Error('private /Users/example/path');
+ }),
+ recover: vi.fn(async () => {
+ throw new Error('private /Users/example/path');
+ }),
+ });
+
+ await expect(ipc.get(EVENT)).rejects.toThrow('[INTERNAL] Codex Micro guard state unavailable');
+ await expect(ipc.setEnabled(EVENT, true)).rejects.toThrow(
+ '[INTERNAL] Codex Micro guard update failed',
+ );
+ await expect(ipc.recover(EVENT)).rejects.toThrow(
+ '[INTERNAL] Codex Micro guard recovery failed',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
new file mode 100644
index 0000000000..623b2f7d85
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
@@ -0,0 +1,640 @@
+import { spawn } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+
+export interface CodexMicroGuardStateRecord {
+ version: 1;
+ originalNodeOptions: string | null;
+ installedNodeOptions: string;
+}
+
+export type LaunchEnvironmentNodeOptions =
+ { kind: 'present'; value: string } | { kind: 'absent' } | { kind: 'invalid' };
+
+export interface GuardCommandResult {
+ status: number;
+ stdout: string;
+ stderr: string;
+}
+
+export interface GuardCommandRunner {
+ run(arguments_: readonly string[]): Promise<GuardCommandResult>;
+}
+
+const MAX_COMMAND_OUTPUT_BYTES = 16 * 1024 * 1024;
+const COMMAND_TIMEOUT_MS = 2_000;
+const PRIVATE_FILE_MODE = 0o600;
+const PRIVATE_DIRECTORY_MODE = 0o700;
+const LEASE_NAME = /^lease-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/u;
+const LEASE_MAX_AGE_MS = 15_000;
+const LEASE_LOCK_NAME = '.lease-lock';
+
+export class LaunchctlGuardCommandRunner implements GuardCommandRunner {
+ async run(arguments_: readonly string[]): Promise<GuardCommandResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn('/bin/launchctl', [...arguments_], { stdio: ['ignore', 'pipe', 'pipe'] });
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ let outputBytes = 0;
+ let settled = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const fail = (error: Error): void => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ child.kill();
+ reject(error);
+ };
+ timer = setTimeout(() => {
+ fail(new Error('launchctl command timed out'));
+ }, COMMAND_TIMEOUT_MS);
+ const capture =
+ (target: Buffer[]) =>
+ (chunk: Buffer): void => {
+ outputBytes += chunk.length;
+ if (outputBytes > MAX_COMMAND_OUTPUT_BYTES) {
+ fail(new Error('launchctl output exceeded the safety limit'));
+ return;
+ }
+ target.push(chunk);
+ };
+ child.stdout.on('data', capture(stdout));
+ child.stderr.on('data', capture(stderr));
+ child.once('error', fail);
+ child.once('close', (status) => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ resolve({
+ status: status ?? -1,
+ stdout: Buffer.concat(stdout).toString('utf8'),
+ stderr: Buffer.concat(stderr).toString('utf8'),
+ });
+ });
+ });
+ }
+}
+
+export class CodexMicroGuardStore {
+ readonly statePath: string;
+ readonly enabledPath: string;
+ readonly heartbeatPath: string;
+ readonly hookPath: string;
+ readonly receiptPath: string;
+
+ constructor(readonly supportPath: string) {
+ this.statePath = path.join(supportPath, 'state.json');
+ this.enabledPath = path.join(supportPath, 'enabled');
+ this.heartbeatPath = path.join(supportPath, 'heartbeat');
+ this.hookPath = path.join(supportPath, 'guard-hook.cjs');
+ this.receiptPath = path.join(supportPath, 'receipt.json');
+ }
+
+ prepare(): void {
+ fs.mkdirSync(this.supportPath, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
+ const stat = fs.lstatSync(this.supportPath);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || !ownedByCurrentUser(stat)) {
+ throw new Error('guard support path is unsafe');
+ }
+ fs.chmodSync(this.supportPath, PRIVATE_DIRECTORY_MODE);
+ }
+
+ installHook(contents: string): void {
+ this.atomicWrite('guard-hook.cjs', contents);
+ if (this.readPrivateFile('guard-hook.cjs') !== contents) {
+ throw new Error('guard hook verification failed');
+ }
+ }
+
+ readState(): CodexMicroGuardStateRecord | null {
+ const text = this.readPrivateFileIfPresent('state.json');
+ if (text === null) return null;
+ const value = JSON.parse(text) as Partial<CodexMicroGuardStateRecord>;
+ if (
+ value.version !== 1 ||
+ (value.originalNodeOptions !== null && typeof value.originalNodeOptions !== 'string') ||
+ typeof value.installedNodeOptions !== 'string'
+ ) {
+ throw new Error('guard recovery state is invalid');
+ }
+ return value as CodexMicroGuardStateRecord;
+ }
+
+ writeState(state: CodexMicroGuardStateRecord): void {
+ this.atomicWrite('state.json', JSON.stringify(state));
+ }
+
+ markEnabled(): void {
+ this.atomicWrite('enabled', '');
+ }
+
+ writeHeartbeat(now: number = Date.now()): void {
+ this.atomicWrite('heartbeat', JSON.stringify(now / 1_000));
+ }
+
+ isFresh(now: number = Date.now(), maximumAgeMs = 15_000): boolean {
+ try {
+ this.readPrivateFile('enabled');
+ const heartbeat = JSON.parse(this.readPrivateFile('heartbeat')) as unknown;
+ if (typeof heartbeat !== 'number' || !Number.isFinite(heartbeat)) return false;
+ const ageMs = now - heartbeat * 1_000;
+ return ageMs >= 0 && ageMs <= maximumAgeMs;
+ } catch {
+ return false;
+ }
+ }
+
+ hasInterceptionReceipt(): boolean {
+ try {
+ const receipt = JSON.parse(this.readPrivateFile('receipt.json')) as Record<string, unknown>;
+ return (
+ typeof receipt.interceptedAt === 'number' &&
+ Number.isFinite(receipt.interceptedAt) &&
+ typeof receipt.service === 'string' &&
+ /^service-[A-Za-z0-9_-]+\.js$/.test(receipt.service)
+ );
+ } catch {
+ return false;
+ }
+ }
+
+ removeEnabled(): void {
+ this.removePrivateFile('enabled');
+ }
+
+ removeHeartbeat(): void {
+ this.removePrivateFile('heartbeat');
+ }
+
+ removeState(): void {
+ this.removePrivateFile('state.json');
+ }
+
+ removeReceipt(): void {
+ this.removePrivateFile('receipt.json');
+ }
+
+ async withLeaseLock<T>(operation: () => Promise<T>): Promise<T> {
+ const deadline = Date.now() + 5_000;
+ let identity: fs.Stats | null = null;
+ while (!identity) {
+ identity = this.tryCreateLeaseLock();
+ if (identity) break;
+ if (this.reclaimAbandonedLeaseLock()) continue;
+ if (Date.now() >= deadline) throw new Error('guard lease lock timed out');
+ await delay(25);
+ }
+ try {
+ return await operation();
+ } finally {
+ this.releaseLeaseLock(identity);
+ }
+ }
+
+ registerLease(leaseId: string, now: number): void {
+ this.listFreshLeaseTimes(now);
+ this.atomicWrite(leaseFilename(leaseId), JSON.stringify(now / 1_000));
+ this.writeHeartbeat(now);
+ }
+
+ refreshLease(leaseId: string, now: number): void {
+ const timestamp = parseLeaseTimestamp(this.readPrivateFile(leaseFilename(leaseId)));
+ if (!isFreshTimestamp(timestamp, now)) throw new Error('guard lease is no longer fresh');
+ this.atomicWrite(leaseFilename(leaseId), JSON.stringify(now / 1_000));
+ this.writeHeartbeat(now);
+ }
+
+ releaseLease(leaseId: string, now: number): boolean {
+ this.removePrivateFile(leaseFilename(leaseId));
+ const fresh = this.listFreshLeaseTimes(now);
+ if (fresh.length === 0) {
+ this.removeHeartbeat();
+ return false;
+ }
+ this.writeHeartbeat(Math.max(...fresh));
+ return true;
+ }
+
+ private listFreshLeaseTimes(now: number): number[] {
+ this.prepare();
+ const fresh: number[] = [];
+ for (const name of fs.readdirSync(this.supportPath)) {
+ if (!LEASE_NAME.test(name)) continue;
+ let timestamp: number;
+ try {
+ timestamp = parseLeaseTimestamp(this.readPrivateFile(name));
+ } catch (error) {
+ if (isNotFound(error)) continue;
+ throw error;
+ }
+ if (isFreshTimestamp(timestamp, now)) fresh.push(timestamp);
+ else this.removePrivateFile(name);
+ }
+ return fresh;
+ }
+
+ private releaseLeaseLock(identity: fs.Stats): void {
+ const lockPath = path.join(this.supportPath, LEASE_LOCK_NAME);
+ const current = fs.lstatSync(lockPath);
+ if (current.isSymbolicLink() || !sameIdentity(current, identity)) {
+ throw new Error('guard lease lock changed while held');
+ }
+ fs.rmdirSync(lockPath);
+ }
+
+ private tryCreateLeaseLock(): fs.Stats | null {
+ this.prepare();
+ const lockPath = path.join(this.supportPath, LEASE_LOCK_NAME);
+ try {
+ fs.mkdirSync(lockPath, { mode: PRIVATE_DIRECTORY_MODE });
+ fs.chmodSync(lockPath, PRIVATE_DIRECTORY_MODE);
+ return fs.lstatSync(lockPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return null;
+ throw error;
+ }
+ }
+
+ private reclaimAbandonedLeaseLock(): boolean {
+ const lockPath = path.join(this.supportPath, LEASE_LOCK_NAME);
+ try {
+ const stat = fs.lstatSync(lockPath);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || !ownedByCurrentUser(stat)) {
+ throw new Error('guard lease lock is unsafe');
+ }
+ if (Date.now() - stat.mtimeMs <= 30_000) return false;
+ const stalePath = path.join(this.supportPath, `.stale-lock-${randomSuffix()}`);
+ fs.renameSync(lockPath, stalePath);
+ fs.rmdirSync(stalePath);
+ } catch (error) {
+ if (!isNotFound(error)) throw error;
+ }
+ return true;
+ }
+
+ private readPrivateFileIfPresent(name: string): string | null {
+ try {
+ return this.readPrivateFile(name);
+ } catch (error) {
+ if (isNotFound(error)) return null;
+ throw error;
+ }
+ }
+
+ private readPrivateFile(name: string): string {
+ this.prepare();
+ const filename = path.join(this.supportPath, name);
+ const descriptor = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ try {
+ const opened = fs.fstatSync(descriptor);
+ const linked = fs.lstatSync(filename);
+ if (
+ !opened.isFile() ||
+ opened.isSymbolicLink() ||
+ !ownedByCurrentUser(opened) ||
+ !hasPrivatePermissions(opened) ||
+ opened.dev !== linked.dev ||
+ opened.ino !== linked.ino
+ ) {
+ throw new Error('guard file is unsafe');
+ }
+ return fs.readFileSync(descriptor, 'utf8');
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ }
+
+ private removePrivateFile(name: string): void {
+ this.prepare();
+ const filename = path.join(this.supportPath, name);
+ try {
+ const stat = fs.lstatSync(filename);
+ if (stat.isSymbolicLink()) throw new Error('refusing to remove a symlinked guard file');
+ fs.unlinkSync(filename);
+ } catch (error) {
+ if (!isNotFound(error)) throw error;
+ }
+ }
+
+ private atomicWrite(name: string, contents: string): void {
+ this.prepare();
+ const supportStat = fs.lstatSync(this.supportPath);
+ const temporaryName = `.tmp-${process.pid}-${Date.now()}-${randomSuffix()}`;
+ const temporaryPath = path.join(this.supportPath, temporaryName);
+ const destinationPath = path.join(this.supportPath, name);
+ let descriptor: number | null = null;
+ try {
+ descriptor = fs.openSync(
+ temporaryPath,
+ fs.constants.O_WRONLY |
+ fs.constants.O_CREAT |
+ fs.constants.O_EXCL |
+ fs.constants.O_NOFOLLOW,
+ PRIVATE_FILE_MODE,
+ );
+ fs.fchmodSync(descriptor, PRIVATE_FILE_MODE);
+ fs.writeFileSync(descriptor, contents, 'utf8');
+ fs.fsyncSync(descriptor);
+ fs.closeSync(descriptor);
+ descriptor = null;
+ const currentSupportStat = fs.lstatSync(this.supportPath);
+ if (
+ currentSupportStat.dev !== supportStat.dev ||
+ currentSupportStat.ino !== supportStat.ino ||
+ currentSupportStat.isSymbolicLink()
+ ) {
+ throw new Error('guard support path changed while writing');
+ }
+ fs.renameSync(temporaryPath, destinationPath);
+ } catch (error) {
+ if (descriptor !== null) fs.closeSync(descriptor);
+ try {
+ const temporaryStat = fs.lstatSync(temporaryPath);
+ if (!temporaryStat.isSymbolicLink()) fs.unlinkSync(temporaryPath);
+ } catch {
+ // Best effort cleanup after the primary write failure.
+ }
+ throw error;
+ }
+ }
+}
+
+export class CodexMicroGuardManager {
+ readonly token: string;
+
+ constructor(
+ readonly store: CodexMicroGuardStore,
+ private readonly runner: GuardCommandRunner,
+ private readonly launchctlDomain: string,
+ private readonly leaseId: string,
+ ) {
+ this.token = `--require=${store.hookPath}`;
+ }
+
+ async enable(hookContents: string, now: number = Date.now()): Promise<void> {
+ await this.store.withLeaseLock(() => this.enableLocked(hookContents, now));
+ }
+
+ async disable(now: number = Date.now()): Promise<void> {
+ await this.store.withLeaseLock(() => this.disableLocked(now));
+ }
+
+ async refreshHeartbeat(now: number = Date.now()): Promise<void> {
+ await this.store.withLeaseLock(async () => this.store.refreshLease(this.leaseId, now));
+ }
+
+ private async enableLocked(hookContents: string, now: number): Promise<void> {
+ if (/\s/u.test(this.store.hookPath)) {
+ throw new Error('guard hook path must not contain whitespace');
+ }
+ this.store.removeReceipt();
+ const original = await this.readNodeOptions();
+ this.store.installHook(hookContents);
+ const existing = this.store.readState();
+ const canReuse = existing !== null && nodeOptionsContains(this.token, original);
+ if (canReuse && !nodeOptionsContains(this.token, existing.installedNodeOptions)) {
+ throw new Error('guard recovery state is inconsistent');
+ }
+ const installed = canReuse ? (original ?? this.token) : mergeNodeOptions(original, this.token);
+ const stateWasCreated = !canReuse;
+ if (stateWasCreated) {
+ this.store.writeState({
+ version: 1,
+ originalNodeOptions: original,
+ installedNodeOptions: installed,
+ });
+ }
+
+ let environmentInstalled = false;
+ try {
+ if (installed !== original) {
+ await this.runLaunchctl(['setenv', 'NODE_OPTIONS', installed]);
+ environmentInstalled = true;
+ }
+ this.store.registerLease(this.leaseId, now);
+ this.store.markEnabled();
+ } catch (error) {
+ let rollbackFailed = false;
+ let otherLeasesRemain = false;
+ try {
+ otherLeasesRemain = this.store.releaseLease(this.leaseId, now);
+ if (!otherLeasesRemain) this.store.removeEnabled();
+ } catch {
+ rollbackFailed = true;
+ }
+ if (environmentInstalled && !otherLeasesRemain) {
+ try {
+ await this.restoreEnvironment(original);
+ } catch {
+ rollbackFailed = true;
+ }
+ }
+ if (stateWasCreated && !otherLeasesRemain && !rollbackFailed) this.store.removeState();
+ if (rollbackFailed) throw new Error('guard activation rollback failed');
+ throw error;
+ }
+ }
+
+ private async disableLocked(now: number): Promise<void> {
+ if (this.store.releaseLease(this.leaseId, now)) return;
+ this.store.removeEnabled();
+ try {
+ let state: CodexMicroGuardStateRecord | null;
+ try {
+ state = this.store.readState();
+ } catch {
+ // Emergency recovery cannot reconstruct a corrupt snapshot. Removing
+ // only Cindy's bounded token is safer than leaving a global preload in
+ // place, and preserves every unrelated current option.
+ state = null;
+ }
+ const current = await this.readNodeOptions();
+ const restored = state
+ ? restoreNodeOptions(
+ state.originalNodeOptions,
+ state.installedNodeOptions,
+ current,
+ this.token,
+ )
+ : removeNodeOption(this.token, current);
+ await this.restoreEnvironment(restored);
+ this.store.removeState();
+ } finally {
+ this.store.removeHeartbeat();
+ this.store.removeReceipt();
+ }
+ }
+
+ private async readNodeOptions(): Promise<string | null> {
+ const result = await this.runLaunchctl(['print', this.launchctlDomain]);
+ const parsed = parseLaunchEnvironmentNodeOptions(result.stdout);
+ if (parsed.kind === 'invalid') throw new Error('launchctl environment snapshot is invalid');
+ return parsed.kind === 'present' ? parsed.value : null;
+ }
+
+ private async restoreEnvironment(value: string | null): Promise<void> {
+ if (value === null) await this.runLaunchctl(['unsetenv', 'NODE_OPTIONS']);
+ else await this.runLaunchctl(['setenv', 'NODE_OPTIONS', value]);
+ }
+
+ private async runLaunchctl(arguments_: readonly string[]): Promise<GuardCommandResult> {
+ const result = await this.runner.run(arguments_);
+ if (result.status !== 0) throw new Error('launchctl command failed');
+ return result;
+ }
+}
+
+export function parseLaunchEnvironmentNodeOptions(input: string): LaunchEnvironmentNodeOptions {
+ let depth = 0;
+ let environmentDepth: number | null = null;
+ let sawRoot = false;
+ let rootClosed = false;
+ let sawEnvironment = false;
+ let nodeOptions: string | null = null;
+
+ for (const rawLine of input.split('\n')) {
+ const line = rawLine.replace(/^[ \t]+/u, '');
+ if (line.length === 0) continue;
+ if (depth === 0) {
+ if (sawRoot || !/^gui\/\d+ = \{$/u.test(line)) return { kind: 'invalid' };
+ sawRoot = true;
+ depth = 1;
+ continue;
+ }
+ if (line === '}') {
+ depth -= 1;
+ if (depth < 0) return { kind: 'invalid' };
+ if (environmentDepth !== null && depth < environmentDepth) environmentDepth = null;
+ if (depth === 0) rootClosed = true;
+ continue;
+ }
+ const opensBlock = !line.includes('=>') && line.endsWith(' = {');
+ if (opensBlock) {
+ if (depth === 1 && line === 'environment = {') {
+ if (sawEnvironment || environmentDepth !== null) return { kind: 'invalid' };
+ sawEnvironment = true;
+ environmentDepth = depth + 1;
+ } else if (environmentDepth !== null) {
+ return { kind: 'invalid' };
+ }
+ depth += 1;
+ continue;
+ }
+ if (depth > 1 && environmentDepth === null) continue;
+ if (!line.includes(' = ') && !line.includes(' => ') && !line.endsWith(' =>')) {
+ return { kind: 'invalid' };
+ }
+ if (environmentDepth !== null && depth === environmentDepth) {
+ const key = 'NODE_OPTIONS =>';
+ if (line === key) {
+ if (nodeOptions !== null) return { kind: 'invalid' };
+ nodeOptions = '';
+ } else if (line.startsWith(`${key} `)) {
+ if (nodeOptions !== null) return { kind: 'invalid' };
+ nodeOptions = line.slice(key.length + 1);
+ } else if (line.startsWith('NODE_OPTIONS')) {
+ return { kind: 'invalid' };
+ }
+ }
+ }
+
+ if (!sawRoot || !rootClosed || !sawEnvironment || depth !== 0 || environmentDepth !== null) {
+ return { kind: 'invalid' };
+ }
+ return nodeOptions === null ? { kind: 'absent' } : { kind: 'present', value: nodeOptions };
+}
+
+export function nodeOptionsContains(token: string, value: string | null): boolean {
+ return value?.split(/\s+/u).includes(token) ?? false;
+}
+
+export function mergeNodeOptions(current: string | null, token: string): string {
+ if (!current) return token;
+ return nodeOptionsContains(token, current) ? current : `${current} ${token}`;
+}
+
+export function removeNodeOption(token: string, current: string | null): string | null {
+ if (current === null) return null;
+ const range = boundedTokenRange(current, token);
+ if (!range) return current;
+ let [start, end] = range;
+ if (start > 0) start -= 1;
+ else if (end < current.length) end += 1;
+ const result = current.slice(0, start) + current.slice(end);
+ return result.length > 0 ? result : null;
+}
+
+export function restoreNodeOptions(
+ original: string | null,
+ installed: string,
+ current: string | null,
+ token: string,
+): string | null {
+ if (current === installed) return original;
+ if (installed === original || current === null) return current;
+ const range = boundedTokenRange(current, token);
+ if (!range) return current;
+ let [start, end] = range;
+ if (start > 0) start -= 1;
+ else if (end < current.length) end += 1;
+ const result = current.slice(0, start) + current.slice(end);
+ return result.length > 0 ? result : null;
+}
+
+function boundedTokenRange(value: string, token: string): [number, number] | null {
+ let from = 0;
+ while (from <= value.length - token.length) {
+ const start = value.indexOf(token, from);
+ if (start < 0) return null;
+ const end = start + token.length;
+ const beforeBoundary = start === 0 || /\s/u.test(value[start - 1] ?? '');
+ const afterBoundary = end === value.length || /\s/u.test(value[end] ?? '');
+ if (beforeBoundary && afterBoundary) return [start, end];
+ from = end;
+ }
+ return null;
+}
+
+function leaseFilename(leaseId: string): string {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(leaseId)) {
+ throw new Error('guard lease id is invalid');
+ }
+ return `lease-${leaseId}.json`;
+}
+
+function parseLeaseTimestamp(input: string): number {
+ const seconds = JSON.parse(input) as unknown;
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return Number.NaN;
+ return seconds * 1_000;
+}
+
+function isFreshTimestamp(timestamp: number, now: number): boolean {
+ const age = now - timestamp;
+ return age >= 0 && age <= LEASE_MAX_AGE_MS;
+}
+
+function sameIdentity(left: fs.Stats, right: fs.Stats): boolean {
+ return left.dev === right.dev && left.ino === right.ino;
+}
+
+function delay(milliseconds: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
+}
+
+function ownedByCurrentUser(stat: fs.Stats): boolean {
+ return typeof process.getuid !== 'function' || stat.uid === process.getuid();
+}
+
+function hasPrivatePermissions(stat: fs.Stats): boolean {
+ // Windows does not expose POSIX permission bits and this guard is unsupported
+ // there. Keep the store testable without weakening the macOS runtime check.
+ return process.platform === 'win32' || (stat.mode & 0o077) === 0;
+}
+
+function isNotFound(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT';
+}
+
+function randomSuffix(): string {
+ return Math.random().toString(36).slice(2, 12);
+}
diff --git a/apps/desktop/src/main/worklouder-codex/codexMicroGuardHook.cjs b/apps/desktop/src/main/worklouder-codex/codexMicroGuardHook.cjs
new file mode 100644
index 0000000000..7d92fa1a1e
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/codexMicroGuardHook.cjs
@@ -0,0 +1,226 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const Module = require('node:module');
+
+const TARGET_APPS = Object.freeze([
+ {
+ executable: '/Applications/ChatGPT.app/Contents/MacOS/ChatGPT',
+ bundleRoot: '/Applications/ChatGPT.app/Contents/Resources/app.asar/.vite/build',
+ },
+ {
+ executable: '/Applications/Codex.app/Contents/MacOS/Codex',
+ bundleRoot: '/Applications/Codex.app/Contents/Resources/app.asar/.vite/build',
+ },
+]);
+const SUPPORT_PATH = __dirname;
+const RECEIPT_PATH = path.join(SUPPORT_PATH, 'receipt.json');
+const MAX_HEARTBEAT_AGE_SECONDS = 15;
+const SERVICE_MARKERS = [
+ 'HID topology watcher addon not found',
+ '@worklouder/device-kit-oai',
+ 'exports.CodexMicroService=',
+ 'getState(){',
+ 'start(){',
+ 'async updateLighting(',
+ 'async stop(){',
+ 'dispose(){',
+];
+
+function sameIdentity(left, right) {
+ return left.dev === right.dev && left.ino === right.ino;
+}
+
+function captureSupportChain() {
+ const parsed = path.parse(SUPPORT_PATH);
+ const chain = [];
+ let current = parsed.root;
+ const components = SUPPORT_PATH.slice(parsed.root.length).split(path.sep).filter(Boolean);
+ for (const component of ['', ...components]) {
+ if (component) current = path.join(current, component);
+ const descriptor = fs.openSync(
+ current,
+ fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
+ );
+ try {
+ const stat = fs.fstatSync(descriptor);
+ if (!stat.isDirectory()) throw new Error('guard support ancestor is not a directory');
+ chain.push({ pathname: current, stat });
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ }
+ return chain;
+}
+
+let supportChain;
+try {
+ supportChain = captureSupportChain();
+} catch {
+ supportChain = null;
+}
+
+function assertSupportChainStable() {
+ if (supportChain === null) throw new Error('guard support path was not safely opened');
+ for (const entry of supportChain) {
+ const current = fs.lstatSync(entry.pathname);
+ if (!current.isDirectory() || !sameIdentity(current, entry.stat)) {
+ throw new Error('guard support path changed after preload');
+ }
+ }
+}
+
+function openPrivateRegularFile(name) {
+ assertSupportChainStable();
+ const filename = path.join(SUPPORT_PATH, name);
+ const descriptor = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ try {
+ const stat = fs.fstatSync(descriptor);
+ if (!stat.isFile()) throw new Error('guard marker is not a regular file');
+ if ((stat.mode & 0o077) !== 0) {
+ throw new Error('guard marker permissions are not private');
+ }
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
+ throw new Error('guard marker owner mismatch');
+ }
+ assertSupportChainStable();
+ if (!sameIdentity(stat, fs.lstatSync(filename))) {
+ throw new Error('guard marker path changed while opening');
+ }
+ return descriptor;
+ } catch (error) {
+ fs.closeSync(descriptor);
+ throw error;
+ }
+}
+
+function guardIsFresh() {
+ let enabledDescriptor;
+ let heartbeatDescriptor;
+ try {
+ enabledDescriptor = openPrivateRegularFile('enabled');
+ heartbeatDescriptor = openPrivateRegularFile('heartbeat');
+ const heartbeat = JSON.parse(fs.readFileSync(heartbeatDescriptor, 'utf8'));
+ if (!Number.isFinite(heartbeat)) return false;
+ const age = Date.now() / 1000 - heartbeat;
+ return age >= 0 && age <= MAX_HEARTBEAT_AGE_SECONDS;
+ } catch {
+ return false;
+ } finally {
+ if (heartbeatDescriptor !== undefined) fs.closeSync(heartbeatDescriptor);
+ if (enabledDescriptor !== undefined) fs.closeSync(enabledDescriptor);
+ }
+}
+
+function sourceHasServiceMarkers(filename) {
+ try {
+ const source = fs.readFileSync(filename, 'utf8');
+ return SERVICE_MARKERS.every((marker) => source.includes(marker));
+ } catch {
+ return false;
+ }
+}
+
+function isExpectedBundleFile(filename, root, prefix) {
+ return (
+ typeof filename === 'string' &&
+ path.dirname(filename) === root &&
+ new RegExp(`^${prefix}-[A-Za-z0-9_-]+\\.js$`).test(path.basename(filename))
+ );
+}
+
+function writeReceipt(serviceFilename) {
+ const temporary = path.join(SUPPORT_PATH, `.receipt-${process.pid}-${Date.now()}.tmp`);
+ let descriptor;
+ try {
+ assertSupportChainStable();
+ const receipt = JSON.stringify({
+ interceptedAt: Date.now() / 1000,
+ service: path.basename(serviceFilename),
+ });
+ descriptor = fs.openSync(
+ temporary,
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW,
+ 0o600,
+ );
+ fs.fchmodSync(descriptor, 0o600);
+ fs.writeFileSync(descriptor, receipt, 'utf8');
+ fs.fsyncSync(descriptor);
+ const temporaryStat = fs.fstatSync(descriptor);
+ assertSupportChainStable();
+ if (!sameIdentity(temporaryStat, fs.lstatSync(temporary))) {
+ throw new Error('guard receipt path changed while writing');
+ }
+ fs.closeSync(descriptor);
+ descriptor = undefined;
+ assertSupportChainStable();
+ fs.renameSync(temporary, RECEIPT_PATH);
+ assertSupportChainStable();
+ if (!sameIdentity(temporaryStat, fs.lstatSync(RECEIPT_PATH))) {
+ throw new Error('guard receipt path changed while replacing');
+ }
+ } catch (error) {
+ if (descriptor !== undefined) fs.closeSync(descriptor);
+ try {
+ assertSupportChainStable();
+ fs.unlinkSync(temporary);
+ } catch {}
+ throw error;
+ }
+}
+
+function runtimeScope() {
+ const isElectronMain = Boolean(process.versions.electron) && process.type === 'browser';
+ if (!isElectronMain) return null;
+ return TARGET_APPS.find((target) => target.executable === process.execPath)?.bundleRoot ?? null;
+}
+
+class CodexMicroService {
+ start() {}
+
+ getState() {
+ return {
+ status: 'unavailable',
+ controlPlaneStatus: 'unavailable',
+ transport: null,
+ model: null,
+ error: null,
+ battery: null,
+ };
+ }
+
+ async stop() {}
+
+ async updateLighting() {
+ return false;
+ }
+
+ dispose() {}
+}
+
+const serviceStub = Object.freeze({ CodexMicroService });
+const bundleRoot = runtimeScope();
+
+if (bundleRoot !== null) {
+ const originalLoad = Module._load;
+ const originalResolveFilename = Module._resolveFilename;
+
+ Module._load = function guardedLoad(request, parent, isMain) {
+ try {
+ const resolved = originalResolveFilename.call(Module, request, parent, isMain);
+ if (
+ isExpectedBundleFile(parent && parent.filename, bundleRoot, 'main') &&
+ isExpectedBundleFile(resolved, bundleRoot, 'service') &&
+ guardIsFresh() &&
+ sourceHasServiceMarkers(resolved)
+ ) {
+ writeReceipt(resolved);
+ return serviceStub;
+ }
+ } catch {
+ // Fail open: preserve Node's original loading behavior on any guard error.
+ }
+ return originalLoad.apply(this, arguments);
+ };
+}
diff --git a/apps/desktop/src/main/worklouder-codex/codexMicroGuardIpc.ts b/apps/desktop/src/main/worklouder-codex/codexMicroGuardIpc.ts
new file mode 100644
index 0000000000..1bb47d3039
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/codexMicroGuardIpc.ts
@@ -0,0 +1,43 @@
+import type { CodexMicroGuardState } from '../../shared/codexMicroGuard.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+export interface CodexMicroGuardIpcDeps {
+ assertTrustedSender(event: unknown): void;
+ getState(): Promise<CodexMicroGuardState>;
+ setEnabled(enabled: boolean): Promise<CodexMicroGuardState>;
+ recover(): Promise<CodexMicroGuardState>;
+}
+
+export function createCodexMicroGuardIpc(deps: CodexMicroGuardIpcDeps) {
+ return {
+ async get(event: unknown): Promise<CodexMicroGuardState> {
+ deps.assertTrustedSender(event);
+ try {
+ return await deps.getState();
+ } catch {
+ throwIpcError('INTERNAL', 'Codex Micro guard state unavailable');
+ }
+ },
+
+ async setEnabled(event: unknown, value: unknown): Promise<CodexMicroGuardState> {
+ deps.assertTrustedSender(event);
+ if (typeof value !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'Codex Micro guard enabled flag must be a boolean');
+ }
+ try {
+ return await deps.setEnabled(value);
+ } catch {
+ throwIpcError('INTERNAL', 'Codex Micro guard update failed');
+ }
+ },
+
+ async recover(event: unknown): Promise<CodexMicroGuardState> {
+ deps.assertTrustedSender(event);
+ try {
+ return await deps.recover();
+ } catch {
+ throwIpcError('INTERNAL', 'Codex Micro guard recovery failed');
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/worklouder-codex/index.ts b/apps/desktop/src/main/worklouder-codex/index.ts
index 44128167d9..98a0032357 100644
--- a/apps/desktop/src/main/worklouder-codex/index.ts
+++ b/apps/desktop/src/main/worklouder-codex/index.ts
@@ -8,6 +8,13 @@ import { getDeepLinkMainWindow, openMainWindowSession, sendMainWindowMessage } f
import { createLayoutPreviewLease, layoutPreviewOwnerFromEvent } from '../input-devices/previewLease.js';
import { registerInputDevice } from '../input-devices/registry.js';
import { isSecondaryAppWindow } from '../secondary-windows.js';
+import {
+ CODEX_MICRO_GUARD_GET_STATE_CHANNEL,
+ CODEX_MICRO_GUARD_RECOVER_CHANNEL,
+ CODEX_MICRO_GUARD_SET_ENABLED_CHANNEL,
+ CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL,
+ type CodexMicroGuardState,
+} from '../../shared/codexMicroGuard.js';
import {
WORKLOUDER_CODEX_ACTION_CHANNEL,
WORKLOUDER_CODEX_DEVICE,
@@ -34,6 +41,8 @@ import {
} from './WorkLouderCodexHostClient.js';
import { WorkLouderCodexLightingController } from './WorkLouderCodexLightingController.js';
import { createWorkLouderCodexSettingsIpc } from './settingsIpc.js';
+import { CodexMicroGuardService } from './CodexMicroGuardService.js';
+import { createCodexMicroGuardIpc } from './codexMicroGuardIpc.js';
import { createWorkLouderCodexActiveWindowRouter } from './actionWindow.js';
import { createWorkLouderCodexSystemFrontmostInput } from './systemFrontmostInput.js';
import {
@@ -115,6 +124,7 @@ const hostClient = new WorkLouderCodexHostClient({
fork: forkWorkLouderHost,
log,
});
+const codexMicroGuardService = new CodexMicroGuardService();
/**
* Tasks as the sidebar currently shows them, published by the renderer.
@@ -198,7 +208,12 @@ export function registerWorkLouderCodexInputDevice(): void {
rendererTaskCatalogScope = null;
workLouderCodexLightingController.suspendTaskSlots();
},
- dispose: () => workLouderCodexLightingController.dispose(),
+ dispose: async () => {
+ await Promise.all([
+ workLouderCodexLightingController.dispose(),
+ codexMicroGuardService.dispose(),
+ ]);
+ },
});
}
@@ -220,6 +235,7 @@ export function registerWorkLouderCodexSettingsIpc(): void {
workLouderCodexLightingController.applySettings(readWorkLouderCodexSettings());
workLouderCodexLightingController.start();
+ void codexMicroGuardService.initialize();
const handlers = createWorkLouderCodexSettingsIpc({
assertTrustedSender: (event) => assertTrustedAppRendererEvent(event as never),
getState: () => workLouderCodexLightingController.getState(),
@@ -267,6 +283,19 @@ export function registerWorkLouderCodexSettingsIpc(): void {
handlers.setLayoutPreviewActive(event, active),
);
+ const guardHandlers = createCodexMicroGuardIpc({
+ assertTrustedSender: (event) => assertTrustedAppRendererEvent(event as never),
+ getState: () => codexMicroGuardService.getState(),
+ setEnabled: (enabled) => codexMicroGuardService.setEnabled(enabled),
+ recover: () => codexMicroGuardService.recover(),
+ });
+ ipcMain.handle(CODEX_MICRO_GUARD_GET_STATE_CHANNEL, (event) => guardHandlers.get(event));
+ ipcMain.handle(CODEX_MICRO_GUARD_SET_ENABLED_CHANNEL, (event, enabled: unknown) =>
+ guardHandlers.setEnabled(event, enabled),
+ );
+ ipcMain.handle(CODEX_MICRO_GUARD_RECOVER_CHANNEL, (event) => guardHandlers.recover(event));
+ codexMicroGuardService.subscribe((state) => broadcastGuardState(state));
+
workLouderCodexLightingController.subscribeState((state) => {
broadcastState(state);
});
@@ -321,6 +350,13 @@ function broadcastState(state: WorkLouderCodexState): void {
}
}
+function broadcastGuardState(state: CodexMicroGuardState): void {
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!isTrustedAppRendererWindow(window)) continue;
+ window.webContents.send(CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL, state);
+ }
+}
+
const windowRevealGates = new WeakMap<
BrowserWindow,
ReturnType<typeof createWorkLouderCodexWindowRevealGate>
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7f5c7cb214..360ae873eb 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -41,6 +41,13 @@ import {
WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL,
type WindowsCloseBehavior,
} from '../shared/windowBehavior';
+import {
+ CODEX_MICRO_GUARD_GET_STATE_CHANNEL,
+ CODEX_MICRO_GUARD_RECOVER_CHANNEL,
+ CODEX_MICRO_GUARD_SET_ENABLED_CHANNEL,
+ CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL,
+ type CodexMicroGuardState,
+} from '../shared/codexMicroGuard';
import {
WORKLOUDER_CODEX_ACTION_CHANNEL,
WORKLOUDER_CODEX_GET_STATE_CHANNEL,
@@ -1621,6 +1628,22 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.send(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL),
},
+ codexMicroGuard: {
+ getState: (): Promise<CodexMicroGuardState> =>
+ ipcRenderer.invoke(CODEX_MICRO_GUARD_GET_STATE_CHANNEL),
+ setEnabled: (enabled: boolean): Promise<CodexMicroGuardState> =>
+ ipcRenderer.invoke(CODEX_MICRO_GUARD_SET_ENABLED_CHANNEL, enabled),
+ recover: (): Promise<CodexMicroGuardState> =>
+ ipcRenderer.invoke(CODEX_MICRO_GUARD_RECOVER_CHANNEL),
+ onStateChanged: (callback: (state: CodexMicroGuardState) => void): (() => void) => {
+ const listener = (_event: Electron.IpcRendererEvent, state: CodexMicroGuardState): void => {
+ callback(state);
+ };
+ ipcRenderer.on(CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL, listener);
+ return () => ipcRenderer.removeListener(CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL, listener);
+ },
+ },
+
workLouderCodex: {
getState: (): Promise<WorkLouderCodexState> =>
ipcRenderer.invoke(WORKLOUDER_CODEX_GET_STATE_CHANNEL),
diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
index f335ba6fa9..2ef265df13 100644
--- a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
@@ -2,6 +2,7 @@ import {
useEffect,
useMemo,
useState,
+ type ButtonHTMLAttributes,
type Dispatch,
type ReactNode,
type SetStateAction,
@@ -21,6 +22,7 @@ import { useTranslation } from 'react-i18next';
import * as Select from '@radix-ui/react-select';
import { Switch } from '@/components/ui/switch';
+import { useCodexMicroGuard } from '@/hooks/useCodexMicroGuard';
import { useWorkLouderCodex } from '@/hooks/useWorkLouderCodex';
import { useSkillhub } from '@/features/skillhub/hooks/useSkillhub';
import { cn } from '@/lib/utils';
@@ -184,6 +186,14 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {
openInputMonitoringSettings,
reload,
} = useWorkLouderCodex({ watchConnection: true });
+ const {
+ state: guardState,
+ loading: guardLoading,
+ saving: guardSaving,
+ error: guardError,
+ setEnabled: setGuardEnabled,
+ recover: recoverGuard,
+ } = useCodexMicroGuard();
const { skills, bootstrapped, refresh: refreshSkills } = useSkillhub();
const [brightnessDraft, setBrightnessDraft] = useState(100);
const [editingSlot, setEditingSlot] = useState<WorkLouderCodexCommandSlot | null>(null);
@@ -462,6 +472,41 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {
</div>
</SettingsCard>
+ <SettingsGroup title={t('settings.shortcuts.workLouderCodex.codexGuard.title')}>
+ <SettingsRow
+ label={t('settings.shortcuts.workLouderCodex.codexGuard.label')}
+ description={t(
+ `settings.shortcuts.workLouderCodex.codexGuard.descriptions.${guardDescriptionKey(
+ guardState?.status,
+ guardError,
+ )}`,
+ )}
+ control={
+ <div className="flex items-center justify-end gap-2">
+ {guardState?.status === 'recovery-required' ? (
+ <SettingsSecondaryButton disabled={guardSaving} onClick={() => void recoverGuard()}>
+ {t('settings.shortcuts.workLouderCodex.codexGuard.recover')}
+ </SettingsSecondaryButton>
+ ) : (
+ <Switch
+ checked={guardState?.enabled ?? false}
+ disabled={guardLoading || guardSaving || !guardState || !guardState.supported}
+ onCheckedChange={(checked) => void setGuardEnabled(checked)}
+ aria-label={t('settings.shortcuts.workLouderCodex.codexGuard.aria')}
+ />
+ )}
+ <DeviceChip>
+ {t(
+ `settings.shortcuts.workLouderCodex.codexGuard.status.${
+ guardState?.status ?? (guardError ? 'error' : 'disabled')
+ }`,
+ )}
+ </DeviceChip>
+ </div>
+ }
+ />
+ </SettingsGroup>
+
<SettingsCard className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<h3 className="text-13 font-medium text-[var(--text-primary)]">
@@ -816,19 +861,17 @@ export function WorkLouderCodexSettings({ onBack }: { onBack(): void }) {
{t('settings.shortcuts.workLouderCodex.layout.reset.description')}
</p>
</div>
- <button
- type="button"
+ <SettingsSecondaryButton
disabled={!state || saving}
onClick={() =>
void setSettings({
layout: cloneWorkLouderCodexLayout(WORKLOUDER_CODEX_DEFAULT_LAYOUT),
})
}
- className="inline-flex shrink-0 items-center gap-2 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 py-2 text-12 text-[var(--settings-input-text)] transition-colors hover:bg-[var(--settings-menu-bg-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-50"
>
<RotateCcw size={13} />
{t('settings.shortcuts.workLouderCodex.layout.reset.button')}
- </button>
+ </SettingsSecondaryButton>
</SettingsCard>
</div>
);
@@ -1094,6 +1137,21 @@ function SettingsDivider() {
return <div className="my-1 h-px bg-[var(--settings-theme-card-border)]" />;
}
+function SettingsSecondaryButton({
+ children,
+ ...props
+}: Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'className' | 'type'>) {
+ return (
+ <button
+ {...props}
+ type="button"
+ 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"
+ >
+ {children}
+ </button>
+ );
+}
+
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)]">
@@ -1190,6 +1248,28 @@ function CodexMicroGlyph() {
);
}
+function guardDescriptionKey(
+ status: import('../../../shared/codexMicroGuard').CodexMicroGuardStatus | undefined,
+ requestFailed: boolean,
+): string {
+ if (requestFailed) return 'error';
+ switch (status) {
+ case 'unsupported':
+ return 'unsupported';
+ case 'protecting':
+ return 'protecting';
+ case 'intercepted':
+ return 'intercepted';
+ case 'recovery-required':
+ return 'recovery-required';
+ case 'error':
+ return 'error';
+ case 'disabled':
+ case undefined:
+ return 'disabled';
+ }
+}
+
function connectionDescription(
t: ReturnType<typeof useTranslation>['t'],
state: WorkLouderCodexState | null,
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 0d9df8ef3c..e3bfda32f0 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
@@ -13,6 +13,13 @@ const mocks = vi.hoisted(() => ({
resetSettings: vi.fn(),
openInputMonitoringSettings: vi.fn(),
reload: vi.fn(),
+ setGuardEnabled: vi.fn(),
+ recoverGuard: vi.fn(),
+ guardStatus: 'disabled' as
+ | 'disabled'
+ | 'protecting'
+ | 'intercepted'
+ | 'recovery-required',
setLayoutPreviewActive: vi.fn(),
previewListeners: [] as Array<
(input: {
@@ -32,6 +39,22 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+vi.mock('@/hooks/useCodexMicroGuard', () => ({
+ useCodexMicroGuard: () => ({
+ state: {
+ supported: true,
+ enabled: mocks.guardStatus === 'protecting' || mocks.guardStatus === 'intercepted',
+ status: mocks.guardStatus,
+ },
+ loading: false,
+ saving: false,
+ error: false,
+ setEnabled: mocks.setGuardEnabled,
+ recover: mocks.recoverGuard,
+ reload: vi.fn(),
+ }),
+}));
+
vi.mock('@/hooks/useWorkLouderCodex', () => ({
useWorkLouderCodex: () => ({
state: {
@@ -93,6 +116,7 @@ describe('WorkLouderCodexSettings', () => {
Element.prototype.scrollIntoView = vi.fn();
mocks.agentSource = 'sidebar';
mocks.layout = createWorkLouderCodexDefaultSettings().layout;
+ mocks.guardStatus = 'disabled';
mocks.previewListeners = [];
Object.defineProperty(window, 'electronAPI', {
configurable: true,
@@ -222,6 +246,30 @@ describe('WorkLouderCodexSettings', () => {
expect(mocks.setSettings).toHaveBeenCalledWith({ lightingAutoDim: '10-minutes' });
});
+ it('lets Cindy protect the device from Codex and exposes recovery failures', () => {
+ const { unmount } = render(<WorkLouderCodexSettings onBack={vi.fn()} />);
+
+ fireEvent.click(
+ screen.getByRole('switch', {
+ name: 'settings.shortcuts.workLouderCodex.codexGuard.aria',
+ }),
+ );
+ expect(mocks.setGuardEnabled).toHaveBeenCalledWith(true);
+ expect(
+ screen.getByText('settings.shortcuts.workLouderCodex.codexGuard.status.disabled'),
+ ).toBeTruthy();
+ unmount();
+
+ mocks.guardStatus = 'recovery-required';
+ render(<WorkLouderCodexSettings onBack={vi.fn()} />);
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'settings.shortcuts.workLouderCodex.codexGuard.recover',
+ }),
+ );
+ expect(mocks.recoverGuard).toHaveBeenCalledOnce();
+ });
+
it('sets all six task keys at once, since they follow one shared rule', async () => {
render(<WorkLouderCodexSettings onBack={vi.fn()} />);
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexMicroGuard.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useCodexMicroGuard.test.tsx
new file mode 100644
index 0000000000..a9a91de8ce
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexMicroGuard.test.tsx
@@ -0,0 +1,77 @@
+// @vitest-environment jsdom
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { CodexMicroGuardState } from '../../../shared/codexMicroGuard';
+import { useCodexMicroGuard } from '../useCodexMicroGuard';
+
+const DISABLED: CodexMicroGuardState = {
+ supported: true,
+ enabled: false,
+ status: 'disabled',
+};
+
+const listeners = new Set<(state: CodexMicroGuardState) => void>();
+const api = {
+ getState: vi.fn(async () => DISABLED),
+ setEnabled: vi.fn(async (enabled: boolean): Promise<CodexMicroGuardState> => ({
+ supported: true,
+ enabled,
+ status: enabled ? 'protecting' : 'disabled',
+ })),
+ recover: vi.fn(async () => DISABLED),
+ onStateChanged: vi.fn((listener: (state: CodexMicroGuardState) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+};
+
+describe('useCodexMicroGuard', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ listeners.clear();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { codexMicroGuard: api },
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'electronAPI');
+ });
+
+ it('loads, mutates, and follows main-process state pushes', async () => {
+ const { result } = renderHook(() => useCodexMicroGuard());
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.state).toEqual(DISABLED);
+
+ await act(async () => result.current.setEnabled(true));
+ expect(api.setEnabled).toHaveBeenCalledWith(true);
+ expect(result.current.state?.status).toBe('protecting');
+
+ act(() => {
+ for (const listener of listeners) {
+ listener({ supported: true, enabled: true, status: 'intercepted' });
+ }
+ });
+ expect(result.current.state?.status).toBe('intercepted');
+ });
+
+ it('reloads authoritative state after a failed mutation', async () => {
+ api.setEnabled.mockRejectedValueOnce(new Error('failed'));
+ const { result } = renderHook(() => useCodexMicroGuard());
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => result.current.setEnabled(true));
+
+ expect(result.current.error).toBe(true);
+ expect(api.getState).toHaveBeenCalledTimes(2);
+ expect(result.current.state).toEqual(DISABLED);
+
+ act(() => {
+ for (const listener of listeners) listener(DISABLED);
+ });
+ expect(result.current.error).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useCodexMicroGuard.ts b/apps/desktop/src/renderer/hooks/useCodexMicroGuard.ts
new file mode 100644
index 0000000000..f27c4b8671
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useCodexMicroGuard.ts
@@ -0,0 +1,104 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { CodexMicroGuardState } from '../../shared/codexMicroGuard';
+
+export interface CodexMicroGuardViewState {
+ state: CodexMicroGuardState | null;
+ loading: boolean;
+ saving: boolean;
+ error: boolean;
+ setEnabled(enabled: boolean): Promise<void>;
+ recover(): Promise<void>;
+ reload(): Promise<void>;
+}
+
+export function useCodexMicroGuard(): CodexMicroGuardViewState {
+ const [state, setState] = useState<CodexMicroGuardState | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(false);
+ const mountedRef = useRef(true);
+ const mutationRef = useRef(0);
+
+ const reload = useCallback(async () => {
+ const api = window.electronAPI?.codexMicroGuard;
+ if (!api) {
+ if (mountedRef.current) {
+ setLoading(false);
+ setError(true);
+ }
+ return;
+ }
+ if (mountedRef.current) {
+ setLoading(true);
+ setError(false);
+ }
+ try {
+ const next = await api.getState();
+ if (mountedRef.current) setState(next);
+ } catch {
+ if (mountedRef.current) setError(true);
+ } finally {
+ if (mountedRef.current) setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ const unsubscribe = window.electronAPI?.codexMicroGuard?.onStateChanged((next) => {
+ if (!mountedRef.current) return;
+ setState(next);
+ setError(false);
+ });
+ void reload();
+ return () => {
+ mountedRef.current = false;
+ unsubscribe?.();
+ };
+ }, [reload]);
+
+ const mutate = useCallback(
+ async (operation: () => Promise<CodexMicroGuardState>) => {
+ const request = ++mutationRef.current;
+ if (mountedRef.current) {
+ setSaving(true);
+ setError(false);
+ }
+ try {
+ const next = await operation();
+ if (mountedRef.current && request === mutationRef.current) setState(next);
+ } catch {
+ if (mountedRef.current && request === mutationRef.current) {
+ await reload();
+ if (mountedRef.current && request === mutationRef.current) setError(true);
+ }
+ } finally {
+ if (mountedRef.current && request === mutationRef.current) setSaving(false);
+ }
+ },
+ [reload],
+ );
+
+ const setEnabled = useCallback(
+ async (enabled: boolean) => {
+ const api = window.electronAPI?.codexMicroGuard;
+ if (!api) {
+ if (mountedRef.current) setError(true);
+ return;
+ }
+ await mutate(() => api.setEnabled(enabled));
+ },
+ [mutate],
+ );
+
+ const recover = useCallback(async () => {
+ const api = window.electronAPI?.codexMicroGuard;
+ if (!api) {
+ if (mountedRef.current) setError(true);
+ return;
+ }
+ await mutate(() => api.recover());
+ }, [mutate]);
+
+ return { state, loading, saving, error, setEnabled, recover, reload };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 922de7f347..9f1e5e0917 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3695,6 +3695,28 @@
"recording": "Press new shortcut…",
"editAria": "Change shortcut for {{name}}",
"workLouderCodex": {
+ "codexGuard": {
+ "title": "Codex compatibility",
+ "label": "Prevent Codex from occupying the device",
+ "aria": "Prevent Codex from occupying Codex Micro",
+ "recover": "Restore environment",
+ "status": {
+ "unsupported": "macOS only",
+ "disabled": "Off",
+ "protecting": "Restart Codex",
+ "intercepted": "Protected",
+ "recovery-required": "Recovery needed",
+ "error": "Unavailable"
+ },
+ "descriptions": {
+ "unsupported": "This protection is available on macOS only.",
+ "disabled": "While Cindy is running, stop Codex from connecting to Codex Micro. Cindy itself is not restricted.",
+ "protecting": "Protection is ready. Completely quit and reopen Codex; an already-running Codex is unaffected.",
+ "intercepted": "Codex's Work Louder service was blocked. Cindy can keep using the device.",
+ "recovery-required": "Protection stopped, but NODE_OPTIONS has not been safely restored. Retry the recovery before enabling it again.",
+ "error": "Cindy could not update Codex protection. Your previous NODE_OPTIONS value was preserved or queued for recovery."
+ }
+ },
"commands": {
"session.selectPrevious": {
"name": "Previous task",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index dfbde36e49..9f04793763 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3694,6 +3694,28 @@
"recording": "新しいショートカットを入力…",
"editAria": "{{name}} のショートカットを変更",
"workLouderCodex": {
+ "codexGuard": {
+ "title": "Codex との互換性",
+ "label": "Codex によるデバイスの占有を防ぐ",
+ "aria": "Codex による Codex Micro の占有を防ぐ",
+ "recover": "環境を復元",
+ "status": {
+ "unsupported": "macOS のみ",
+ "disabled": "オフ",
+ "protecting": "Codex を再起動",
+ "intercepted": "保護中",
+ "recovery-required": "復元が必要",
+ "error": "利用不可"
+ },
+ "descriptions": {
+ "unsupported": "この保護機能は macOS でのみ利用できます。",
+ "disabled": "Cindy の実行中、Codex が Codex Micro に接続するのを防ぎます。Cindy 自体は制限されません。",
+ "protecting": "保護の準備ができました。Codex を完全に終了してから開き直してください。実行中の Codex には影響しません。",
+ "intercepted": "Codex の Work Louder サービスをブロックしました。Cindy は引き続きデバイスを使用できます。",
+ "recovery-required": "保護は停止しましたが、NODE_OPTIONS は安全に復元されていません。再度有効にする前に復元を再試行してください。",
+ "error": "Codex の保護を更新できませんでした。以前の NODE_OPTIONS は保持されているか、復元待ちです。"
+ }
+ },
"commands": {
"session.selectPrevious": {
"name": "前のタスク",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 79c852b778..202a2cfce8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3694,6 +3694,28 @@
"recording": "새 단축키를 누르세요…",
"editAria": "{{name}} 단축키 변경",
"workLouderCodex": {
+ "codexGuard": {
+ "title": "Codex 호환성",
+ "label": "Codex의 장치 점유 방지",
+ "aria": "Codex의 Codex Micro 점유 방지",
+ "recover": "환경 복원",
+ "status": {
+ "unsupported": "macOS 전용",
+ "disabled": "꺼짐",
+ "protecting": "Codex 재시작 필요",
+ "intercepted": "보호 중",
+ "recovery-required": "복원 필요",
+ "error": "사용 불가"
+ },
+ "descriptions": {
+ "unsupported": "이 보호 기능은 macOS에서만 사용할 수 있습니다.",
+ "disabled": "Cindy가 실행되는 동안 Codex가 Codex Micro에 연결하지 못하게 합니다. Cindy 자체는 제한하지 않습니다.",
+ "protecting": "보호 준비가 완료되었습니다. Codex를 완전히 종료한 뒤 다시 여세요. 이미 실행 중인 Codex에는 영향을 주지 않습니다.",
+ "intercepted": "Codex의 Work Louder 서비스를 차단했습니다. Cindy는 장치를 계속 사용할 수 있습니다.",
+ "recovery-required": "보호가 중지되었지만 NODE_OPTIONS가 안전하게 복원되지 않았습니다. 다시 켜기 전에 복원을 재시도하세요.",
+ "error": "Codex 보호를 업데이트하지 못했습니다. 기존 NODE_OPTIONS는 유지되었거나 복원 대기 중입니다."
+ }
+ },
"commands": {
"session.selectPrevious": {
"name": "이전 작업",
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 000cf86f44..4d731c199c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3680,6 +3680,28 @@
"recording": "按下新快捷键…",
"editAria": "修改 {{name}} 的快捷键",
"workLouderCodex": {
+ "codexGuard": {
+ "title": "Codex 兼容性",
+ "label": "防止 Codex 占用设备",
+ "aria": "防止 Codex 占用 Codex Micro",
+ "recover": "恢复环境",
+ "status": {
+ "unsupported": "仅 macOS",
+ "disabled": "已关闭",
+ "protecting": "请重启 Codex",
+ "intercepted": "保护中",
+ "recovery-required": "需要恢复",
+ "error": "不可用"
+ },
+ "descriptions": {
+ "unsupported": "此保护仅在 macOS 上可用。",
+ "disabled": "Cindy 运行期间阻止 Codex 连接 Codex Micro;不会限制 Cindy 本身。",
+ "protecting": "保护已就绪。请完全退出后重新打开 Codex;已经运行的 Codex 不受影响。",
+ "intercepted": "已阻止 Codex 的 Work Louder 服务,Cindy 可以继续使用设备。",
+ "recovery-required": "保护已停止,但 NODE_OPTIONS 尚未安全恢复。请先重试恢复,再重新开启。",
+ "error": "Cindy 无法更新 Codex 保护;原有 NODE_OPTIONS 已保留或等待恢复。"
+ }
+ },
"commands": {
"session.selectPrevious": {
"name": "上一个任务",
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 aff5d109e2..6c17ac84de 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3686,6 +3686,28 @@
"recording": "按下新快捷鍵…",
"editAria": "修改 {{name}} 的快捷鍵",
"workLouderCodex": {
+ "codexGuard": {
+ "title": "Codex 相容性",
+ "label": "防止 Codex 佔用裝置",
+ "aria": "防止 Codex 佔用 Codex Micro",
+ "recover": "還原環境",
+ "status": {
+ "unsupported": "僅 macOS",
+ "disabled": "已關閉",
+ "protecting": "請重新啟動 Codex",
+ "intercepted": "保護中",
+ "recovery-required": "需要還原",
+ "error": "無法使用"
+ },
+ "descriptions": {
+ "unsupported": "此保護僅可在 macOS 上使用。",
+ "disabled": "Cindy 執行期間會阻止 Codex 連線至 Codex Micro;不會限制 Cindy 本身。",
+ "protecting": "保護已就緒。請完全結束後重新開啟 Codex;已在執行的 Codex 不受影響。",
+ "intercepted": "已阻止 Codex 的 Work Louder 服務,Cindy 可以繼續使用裝置。",
+ "recovery-required": "保護已停止,但 NODE_OPTIONS 尚未安全還原。請先重試還原,再重新開啟。",
+ "error": "Cindy 無法更新 Codex 保護;原有 NODE_OPTIONS 已保留或等待還原。"
+ }
+ },
"commands": {
"session.selectPrevious": {
"name": "上一個任務",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index dbcd15e2ca..2590a6f866 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -73,6 +73,7 @@ type PendingRemotePrecreatedWorktreeTarget =
type RemotePrecreatedWorktreeLedgerSnapshot =
import('../shared/remotePrecreatedWorktreeLedger').RemotePrecreatedWorktreeLedgerSnapshot;
type RawReleaseNotesPayload = import('../shared/releaseNotesContent').RawReleaseNotes;
+type CodexMicroGuardState = import('../shared/codexMicroGuard').CodexMicroGuardState;
type WorkLouderCodexSettingsPatch =
import('../shared/workLouderCodex').WorkLouderCodexSettingsPatch;
type WorkLouderCodexState = import('../shared/workLouderCodex').WorkLouderCodexState;
@@ -1847,6 +1848,13 @@ interface ElectronAPI {
notifyWindowsCloseBehaviorPromptShown: () => void;
};
+ codexMicroGuard: {
+ getState: () => Promise<CodexMicroGuardState>;
+ setEnabled: (enabled: boolean) => Promise<CodexMicroGuardState>;
+ recover: () => Promise<CodexMicroGuardState>;
+ onStateChanged: (callback: (state: CodexMicroGuardState) => void) => () => void;
+ };
+
workLouderCodex: {
getState: () => Promise<WorkLouderCodexState>;
setSettings: (patch: WorkLouderCodexSettingsPatch) => Promise<WorkLouderCodexState>;
diff --git a/apps/desktop/src/shared/codexMicroGuard.ts b/apps/desktop/src/shared/codexMicroGuard.ts
new file mode 100644
index 0000000000..aefb8f6da5
--- /dev/null
+++ b/apps/desktop/src/shared/codexMicroGuard.ts
@@ -0,0 +1,16 @@
+/** macOS protection that keeps Codex from opening the Work Louder HID service. */
+
+export const CODEX_MICRO_GUARD_GET_STATE_CHANNEL = 'codex-micro-guard:get-state';
+export const CODEX_MICRO_GUARD_SET_ENABLED_CHANNEL = 'codex-micro-guard:set-enabled';
+export const CODEX_MICRO_GUARD_RECOVER_CHANNEL = 'codex-micro-guard:recover';
+export const CODEX_MICRO_GUARD_STATE_CHANGED_CHANNEL = 'codex-micro-guard:state-changed';
+
+export type CodexMicroGuardStatus =
+ 'unsupported' | 'disabled' | 'protecting' | 'intercepted' | 'recovery-required' | 'error';
+
+export interface CodexMicroGuardState {
+ supported: boolean;
+ /** Machine-local user override. The system default is false. */
+ enabled: boolean;
+ status: CodexMicroGuardStatus;
+}