Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 暂停 Codex Micro 全局注入并清理遗留环境 (#5990)

Lizi133d532089be
diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
index 3634bbe1b2..73e7046bd2 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts
@@ -152,9 +152,18 @@ function readOwnerGuestIndex(): Record<string, { controller: string; forgetPendi
return JSON.parse(fs.readFileSync(path.join(root, 'owner', 'guest-sessions.json'), 'utf8'));
}
-async function waitForGuestPurge(controller: string): Promise<void> {
+async function waitForGuestPurge(controller: string, env: ReturnType<typeof setup>): Promise<void> {
+ for (
+ let requestIndex = 0;
+ requestIndex < env.relay.forget.mock.results.length;
+ requestIndex += 1
+ ) {
+ await Promise.allSettled([env.relay.forget.mock.results[requestIndex].value]);
+ }
// 远端删目录后还会写索引;等组所在电脑确认远端完成并落盘,避免 teardown 与后台写入竞争。
- await waitFor(() => Object.values(readOwnerGuestIndex()).every((record) => record.controller !== controller));
+ await waitFor(() =>
+ Object.values(readOwnerGuestIndex()).every((record) => record.controller !== controller),
+ );
}
const MEMBER_MINI: GroupRelayMember = { memberKey: 'device:mini:anthropic-2', agentDeviceId: 'mini', providerId: 'anthropic-2', sameAccount: true };
@@ -399,7 +408,7 @@ describe('provider group relay for shared users', () => {
const homeB = env.memberStarted.mini[1].input.guestHome!;
expect(fs.existsSync(homeA) && fs.existsSync(homeB)).toBe(true);
await env.owner.purgeControllers((controller) => controller === GUEST_A);
- await waitForGuestPurge(GUEST_A);
+ await waitForGuestPurge(GUEST_A, env);
expect(fs.existsSync(homeA)).toBe(false);
expect(env.relay.forget).toHaveBeenCalledWith('mini', relayKeyFor(GUEST_A));
expect(fs.existsSync(homeB)).toBe(true);
@@ -478,11 +487,82 @@ describe('provider group relay: starting, load and cleanup', () => {
expect(env.memberStarted.studio).toHaveLength(1);
await client.close('close', 'navigation');
await env.owner.purgeControllers((controller) => controller === GUEST_A);
- await waitForGuestPurge(GUEST_A);
+ await waitForGuestPurge(GUEST_A, env);
expect(env.relay.forget).toHaveBeenCalledWith('mini', relayKeyFor(GUEST_A));
expect(env.relay.forget).toHaveBeenCalledWith('studio', relayKeyFor(GUEST_A));
});
+ it('waits for both computers to finish cleanup before polling the persisted guest index', async () => {
+ function cleanupGate() {
+ let release = () => {};
+ let enter = () => {};
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const entered = new Promise<void>((resolve) => {
+ enter = resolve;
+ });
+ return { pending, entered, release, enter };
+ }
+ const cleanups = { mini: cleanupGate(), studio: cleanupGate() };
+ const env = setup({
+ mini: { failStart: true },
+ plans: [
+ { kind: 'member', ...MEMBER_MINI },
+ { kind: 'member', ...MEMBER_STUDIO },
+ ],
+ intercept: async (agentDeviceId, request, forward) => {
+ if (request.op === 'forget') {
+ const cleanup = cleanups[agentDeviceId as keyof typeof cleanups];
+ cleanup.enter();
+ await cleanup.pending;
+ }
+ return forward();
+ },
+ });
+ const { client } = await openAsGuest(env, GUEST_A, openPayload(SESSION));
+ await client.close('close', 'navigation');
+ await env.owner.purgeControllers((controller) => controller === GUEST_A);
+ await cleanups.studio.entered;
+
+ let outcome: 'purged' | Error | undefined;
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout'] });
+ const purged = waitForGuestPurge(GUEST_A, env).then(
+ () => {
+ outcome = 'purged';
+ },
+ (error: Error) => {
+ outcome = error;
+ },
+ );
+ try {
+ await vi.advanceTimersByTimeAsync(3_100);
+ const whileStudioPending = outcome;
+ vi.useRealTimers();
+ cleanups.studio.release();
+ await cleanups.mini.entered;
+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout'] });
+ await vi.advanceTimersByTimeAsync(3_100);
+ const whileMiniPending = outcome;
+ vi.useRealTimers();
+ cleanups.mini.release();
+ await purged;
+ for (const request of env.relay.forget.mock.results) await request.value;
+ await waitForGuestPurge(GUEST_A, env);
+
+ expect(whileMiniPending).toBeUndefined();
+ expect(whileStudioPending).toBeUndefined();
+ expect(outcome).toBe('purged');
+ expect(env.relay.forget).toHaveBeenCalledTimes(2);
+ expect(env.relay.forget).toHaveBeenCalledWith('mini', relayKeyFor(GUEST_A));
+ expect(env.relay.forget).toHaveBeenCalledWith('studio', relayKeyFor(GUEST_A));
+ } finally {
+ vi.useRealTimers();
+ cleanups.mini.release();
+ cleanups.studio.release();
+ }
+ });
+
it('keeps the computers it could not reach when deleting a shared user, and asks them again later', async () => {
const env = setup();
const { client } = await openAsGuest(env, GUEST_A, openPayload(SESSION));
@@ -496,7 +576,7 @@ describe('provider group relay: starting, load and cleanup', () => {
await env.owner.purgeControllers((controller) => controller === GUEST_A);
await waitFor(() => env.relay.forget.mock.calls.length === 2);
- await waitForGuestPurge(GUEST_A);
+ await waitForGuestPurge(GUEST_A, env);
expect(Object.keys(readOwnerGuestIndex())).toHaveLength(0);
});
diff --git a/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
index fa1533d81f..d3c78d27b2 100644
--- a/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
+++ b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
@@ -5,15 +5,6 @@ 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 {
- listCodexMicroGuardProcesses,
- type CodexMicroGuardProcess,
-} from './codexMicroGuardProcesses.js';
import {
CodexMicroGuardManager,
CodexMicroGuardStore,
@@ -21,113 +12,69 @@ import {
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;
- listProcesses?: () => Promise<CodexMicroGuardProcess[]>;
+ environment?: NodeJS.ProcessEnv;
}
const log = desktopMakerLogger.child('codex-micro-guard');
-const DEFAULT_SETTINGS: CodexMicroGuardSettings = { enabled: true };
-const MAX_SETTINGS_BYTES = 8 * 1024;
-const HEARTBEAT_INTERVAL_MS = 5_000;
+/**
+ * Cleanup-only while Codex protection is suspended (#5985). Legacy preferences
+ * stay on disk, but neither startup nor IPC can reactivate global injection.
+ */
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;
- private readonly listProcesses: () => Promise<CodexMicroGuardProcess[]>;
- private restartProcesses: CodexMicroGuardProcess[] = [];
- /** A legacy opt-out was detected but could not be saved; report off until a toggle. */
- private legacyOptOutPending = false;
constructor(options: CodexMicroGuardServiceOptions = {}) {
this.platform = options.platform ?? process.platform;
- this.listProcesses = options.listProcesses ?? listCodexMicroGuardProcesses;
- const supportPath = options.supportPath ?? defaultSupportPath();
- this.store = new CodexMicroGuardStore(supportPath);
this.manager = new CodexMicroGuardManager(
- this.store,
+ new CodexMicroGuardStore(options.supportPath ?? defaultSupportPath()),
options.runner ?? new LaunchctlGuardCommandRunner(),
options.launchctlDomain ??
(this.platform === 'darwin' ? `gui/${currentUid()}` : 'gui/unsupported'),
- crypto.randomUUID(),
+ options.environment ?? process.env,
);
- 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();
+ if (!this.initializePromise) {
+ this.initializePromise =
+ this.platform === 'darwin' ? this.cleanup().catch(() => undefined) : Promise.resolve();
+ }
return this.initializePromise;
}
async getState(): Promise<CodexMicroGuardState> {
await this.initialize();
- await this.enqueue(() => this.refreshRestartRequired());
+ await this.mutation;
return this.snapshot();
}
+ // Keep the existing IPC contract, including stale renderer requests, without
+ // interpreting any preference as permission to resume the retired injection.
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 });
- this.legacyOptOutPending = false;
- });
- return this.snapshot();
+ return enabled ? this.getState() : this.recover();
}
async recover(): Promise<CodexMicroGuardState> {
await this.initialize();
if (this.platform !== 'darwin') return this.snapshot();
- await this.enqueue(async () => {
+ const next = this.mutation.then(async () => {
if (this.disposed) throw new Error('Codex Micro guard service is disposed');
- this.settingsStore.writePatch({ enabled: false });
- this.stopHeartbeat();
- this.active = false;
- this.restartProcesses = [];
- await this.manager.disable();
- this.failed = false;
- this.recoveryRequired = false;
- this.emitIfChanged();
+ await this.cleanup();
});
+ this.mutation = next.catch(() => undefined);
+ await next;
return this.snapshot();
}
@@ -138,186 +85,27 @@ export class CodexMicroGuardService {
async dispose(): Promise<void> {
await this.initialize();
- await this.enqueue(async () => {
- if (this.disposed) return;
- this.disposed = true;
- this.stopHeartbeat();
- this.restartProcesses = [];
- 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;
- this.legacyOptOutPending = !this.preserveLegacyOptOut();
- const enabled = !this.legacyOptOutPending && this.settingsStore.read().enabled;
- try {
- if (enabled) {
- await this.manager.enable(this.hookContents);
- // Restart hints belong only to an explicit toggle, not startup recovery.
- 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();
- }
-
- /**
- * Default-off releases stored nothing when the user turned protection off,
- * because off matched the old default. Their leftover hook (without the
- * default-on marker) identifies that opt-out, so keep it off once. The
- * marker then records the migration, so a later restore-defaults follows
- * the new default instead of re-running it.
- *
- * Returns false while a detected opt-out is not yet persisted: protection
- * stays off and the marker is not written, so the next launch retries.
- */
- private preserveLegacyOptOut(): boolean {
- if (!this.store.hasLegacyHook()) return true;
- try {
- if (!this.settingsStore.readState().isCustomized) {
- this.settingsStore.writePatch({ enabled: false });
- }
- } catch {
- log.warn('Codex Micro guard legacy opt-out could not be saved; protection stays off');
- return false;
- }
- try {
- this.store.markDefaultOn();
- } catch {
- // The saved override already decides this launch; the next one retries the marker.
- log.warn('Codex Micro guard legacy opt-out marker could not be written');
+ await this.mutation;
+ if (this.disposed) return;
+ this.disposed = true;
+ // Retry incomplete restoration on a normal exit as well as on next startup.
+ if (this.platform === 'darwin') {
+ await this.cleanup().catch(() => undefined);
}
- return true;
- }
-
- private async enable(): Promise<void> {
- if (this.active && this.store.isFresh()) return;
- this.failed = false;
- this.recoveryRequired = false;
- let processes: CodexMicroGuardProcess[] = [];
- try {
- processes = await this.listProcesses();
- } catch {
- // Process detection is only a hint; it must not fail protection activation.
- }
- 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.restartProcesses = processes;
- this.startHeartbeat();
- this.emitIfChanged();
+ this.listeners.clear();
}
- private async disable(options: { persistSetting: boolean }): Promise<void> {
- if (options.persistSetting) this.settingsStore.writePatch({ enabled: false });
- this.stopHeartbeat();
- this.active = false;
- this.restartProcesses = [];
+ private async cleanup(): Promise<void> {
try {
- await this.manager.disable();
- this.failed = false;
+ await this.manager.recover();
this.recoveryRequired = false;
} catch (error) {
- this.failed = true;
this.recoveryRequired = true;
- this.emitIfChanged();
+ log.warn('Codex Micro guard legacy environment recovery failed');
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');
- }
- await this.refreshRestartRequired();
- 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 async refreshRestartRequired(): Promise<void> {
- if (!this.active || this.disposed) {
- this.restartProcesses = [];
- return;
- }
- if (this.restartProcesses.length === 0) return;
- try {
- const processes = await this.listProcesses();
- // Only keep processes observed at activation. A later launch cannot
- // bring the hint back, even if the OS reuses the same PID.
- this.restartProcesses = this.restartProcesses.filter((previous) =>
- processes.some(
- (current) =>
- current.pid === previous.pid &&
- current.startedAt === previous.startedAt &&
- current.executable === previous.executable,
- ),
- );
- } catch {
- this.restartProcesses = [];
+ } finally {
+ const state = this.snapshot();
+ for (const listener of this.listeners) listener(state);
}
}
@@ -325,40 +113,13 @@ export class CodexMicroGuardService {
if (this.platform !== 'darwin') {
return { supported: false, enabled: false, status: 'unsupported' };
}
- const enabled = !this.legacyOptOutPending && 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,
- restartRequired:
- (status === 'protecting' || status === 'intercepted') && this.restartProcesses.length > 0,
+ enabled: false,
+ status: this.recoveryRequired ? 'recovery-required' : 'paused',
+ restartRequired: false,
};
}
-
- 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 {
@@ -374,5 +135,3 @@ 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
index 4e47bf9f3e..c2d0f0b2e1 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
@@ -3,403 +3,235 @@ 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';
-import type { CodexMicroGuardProcess } from '../codexMicroGuardProcesses.js';
-
-vi.mock('electron', () => ({
- app: { getPath: () => '/unused' },
-}));
-
+vi.mock('electron', () => ({ app: { getPath: () => '/unused' } }));
vi.mock('../../maker-host/logger-adapter.js', () => ({
- desktopMakerLogger: {
- child: () => ({ info: vi.fn(), warn: vi.fn() }),
- },
+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn() }) },
}));
import { CodexMicroGuardService } from '../CodexMicroGuardService.js';
+import { CodexMicroGuardStore } from '../codexMicroGuardCore.js';
+import { createCodexMicroGuardIpc } from '../codexMicroGuardIpc.js';
+import { GuardEnvironmentRunner, seedLegacyGuard } from './guardRecoveryFixture';
const roots: string[] = [];
+const services: CodexMicroGuardService[] = [];
+const PAUSED = { supported: true, enabled: false, status: 'paused', restartRequired: false };
-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`;
-}
-
-/**
- * Protection defaults to on. Most cases exercise explicit toggles, so they
- * start from a user who has turned it off; pass `'default'` for a fresh install.
- */
-function paths(initial: { enabled: boolean } | 'default' = { enabled: false }) {
+function fixture(legacy = false) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-guard-service-'));
roots.push(root);
- const settingsPath = path.join(root, 'settings.json');
- if (initial !== 'default') fs.writeFileSync(settingsPath, JSON.stringify(initial));
- return {
- supportPath: path.join(root, 'support'),
- settingsPath,
+ const supportPath = path.join(root, 'CindyCodexMicroGuard', 'aaaaaaaaaaaa');
+ const store = new CodexMicroGuardStore(supportPath);
+ const runner = new GuardEnvironmentRunner(legacy ? seedLegacyGuard(store) : null);
+ const environment = { NODE_OPTIONS: runner.nodeOptions ?? '' };
+ const make = (overrides: ConstructorParameters<typeof CodexMicroGuardService>[0] = {}) => {
+ const service = new CodexMicroGuardService({
+ platform: 'darwin',
+ supportPath,
+ launchctlDomain: 'gui/501',
+ runner,
+ environment,
+ ...overrides,
+ });
+ services.push(service);
+ return service;
};
+ return { root, supportPath, store, runner, environment, make };
}
-function service(
- paths_: ReturnType<typeof paths>,
- runner: GuardCommandRunner,
- listProcesses: () => Promise<CodexMicroGuardProcess[]> = async () => [],
-): CodexMicroGuardService {
- return new CodexMicroGuardService({
- platform: 'darwin',
- ...paths_,
- launchctlDomain: 'gui/501',
- runner,
- listProcesses,
- hookContents: '// safe test hook\n',
- heartbeatIntervalMs: 5_000,
- });
-}
-
-afterEach(() => {
- vi.useRealTimers();
+afterEach(async () => {
+ for (const service of services.splice(0)) await service.dispose();
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
});
-describe('CodexMicroGuardService', () => {
- const runningCodex = () => ({
- pid: 101,
- startedAt: Date.now() - 60_000,
- executable: '/Applications/Codex.app/Contents/MacOS/Codex',
+describe('CodexMicroGuardService suspension', () => {
+ it('starts paused without installing a hook, setting NODE_OPTIONS or scheduling a heartbeat', async () => {
+ const f = fixture();
+ const interval = vi.spyOn(globalThis, 'setInterval');
+ try {
+ expect(await f.make().getState()).toEqual(PAUSED);
+ expect(f.runner.commands).toEqual([['print', 'gui/501']]);
+ expect(fs.existsSync(f.store.hookPath)).toBe(false);
+ expect(interval).not.toHaveBeenCalled();
+ } finally {
+ interval.mockRestore();
+ }
});
- it('clears the restart hint on exit or restart through the existing heartbeat', async () => {
- vi.useFakeTimers();
- let processes = [runningCodex()];
- const instance = service(paths(), new EnvironmentRunner(null), async () => processes);
+ it.each(['{"enabled":true}', '{"enabled":false}', 'broken'])(
+ 'retires previous protection regardless of legacy preference %s and preserves that file',
+ async (preference) => {
+ const f = fixture(true);
+ const settingsPath = path.join(f.root, 'codex-micro-guard.json');
+ fs.writeFileSync(settingsPath, preference);
+ const service = f.make();
+ expect(await service.getState()).toEqual(PAUSED);
+ expect(f.runner.nodeOptions).toBeNull();
+ expect(f.environment.NODE_OPTIONS).toBeUndefined();
+ expect(f.store.isFresh()).toBe(false);
+ expect(fs.existsSync(f.store.hookPath)).toBe(true);
+ expect(fs.readFileSync(settingsPath, 'utf8')).toBe(preference);
+ await service.dispose();
+ expect(await f.make().getState()).toEqual(PAUSED);
+ expect(f.runner.commands.filter(([command]) => command === 'setenv')).toEqual([]);
+ },
+ );
+
+ it('cannot reactivate through old IPC enable requests, rapid toggles or subsequent startup', async () => {
+ const f = fixture();
+ const service = f.make();
+ const assertTrustedSender = vi.fn();
+ const ipc = createCodexMicroGuardIpc({
+ assertTrustedSender,
+ getState: () => service.getState(),
+ setEnabled: (enabled) => service.setEnabled(enabled),
+ recover: () => service.recover(),
+ });
+ const results = await Promise.all([
+ ipc.setEnabled({}, true),
+ ipc.setEnabled({}, false),
+ ipc.setEnabled({}, true),
+ ]);
+ expect(results).toEqual([PAUSED, PAUSED, PAUSED]);
+ expect(assertTrustedSender).toHaveBeenCalledTimes(3);
+ await service.dispose();
+ expect(await f.make().getState()).toEqual(PAUSED);
+ expect(f.runner.commands.every(([command]) => command === 'print')).toBe(true);
+ expect(fs.existsSync(f.store.hookPath)).toBe(false);
+ });
+
+ it('exposes failed restoration and broadcasts the paused state after a manual retry', async () => {
+ const f = fixture(true);
+ f.runner.failNextMutation = true;
+ const service = f.make();
const listener = vi.fn();
- instance.subscribe(listener);
- expect(await instance.setEnabled(true)).toMatchObject({ restartRequired: true });
- processes = [];
- await vi.advanceTimersByTimeAsync(5_000);
+ service.subscribe(listener);
+ expect(await service.getState()).toMatchObject({ enabled: false, status: 'recovery-required' });
+ expect(f.store.readState()).not.toBeNull();
expect(listener).toHaveBeenLastCalledWith(
- expect.objectContaining({ status: 'protecting', enabled: true, restartRequired: false }),
+ expect.objectContaining({ status: 'recovery-required' }),
);
- processes = [{ ...runningCodex(), startedAt: Date.now(), pid: 102 }];
- expect(await instance.getState()).toMatchObject({
- status: 'protecting',
- restartRequired: false,
+ expect(await service.recover()).toEqual(PAUSED);
+ expect(listener).toHaveBeenLastCalledWith(PAUSED);
+ expect(f.runner.nodeOptions).toBeNull();
+ });
+
+ it('keeps failed recovery visible through IPC instead of treating the request as completed', async () => {
+ const f = fixture(true);
+ f.runner.ignoreMutations = true;
+ const service = f.make();
+ const ipc = createCodexMicroGuardIpc({
+ assertTrustedSender: () => undefined,
+ getState: () => service.getState(),
+ setEnabled: (enabled) => service.setEnabled(enabled),
+ recover: () => service.recover(),
});
- await instance.dispose();
- });
-
- it('only considers processes running when the switch is enabled', async () => {
- const list = vi.fn(async (): Promise<CodexMicroGuardProcess[]> => []);
- const instance = service(paths(), new EnvironmentRunner(null), list);
- expect(await instance.setEnabled(true)).toMatchObject({ restartRequired: false });
- list.mockResolvedValue([runningCodex()]);
- expect(await instance.getState()).toMatchObject({ restartRequired: false });
- expect(list).toHaveBeenCalledTimes(1);
- await instance.setEnabled(false);
- expect(await instance.setEnabled(true)).toMatchObject({ restartRequired: true });
- expect(await instance.setEnabled(false)).toMatchObject({ restartRequired: false });
- await instance.dispose();
- });
-
- it('clears restarted processes even when their PIDs are reused', async () => {
- const original = runningCodex();
- let processes = [original, { ...original, pid: 102 }];
- const instance = service(paths(), new EnvironmentRunner(null), async () => processes);
- expect(await instance.setEnabled(true)).toMatchObject({ restartRequired: true });
- processes = [{ ...original, startedAt: original.startedAt + 10_000 }, processes[1]];
- expect(await instance.getState()).toMatchObject({ restartRequired: true });
- processes = [processes[0]];
- expect(await instance.getState()).toMatchObject({ restartRequired: false });
- await instance.dispose();
+ expect(await ipc.get({})).toMatchObject({ status: 'recovery-required' });
+ await expect(ipc.recover({})).rejects.toThrow('INTERNAL');
+ expect(await service.getState()).toMatchObject({ status: 'recovery-required' });
+ f.runner.ignoreMutations = false;
});
- it('keeps protection active when process detection fails', async () => {
- const list = vi.fn(async (): Promise<CodexMicroGuardProcess[]> => {
- throw new Error('ps unavailable');
- });
- const instance = service(paths(), new EnvironmentRunner(null), list);
- expect(await instance.setEnabled(true)).toMatchObject({
- enabled: true,
- restartRequired: false,
- });
- await instance.setEnabled(false);
- list.mockResolvedValue([runningCodex()]);
- expect(await instance.setEnabled(true)).toMatchObject({ restartRequired: true });
- list.mockRejectedValue(new Error('ps unavailable'));
- expect(await instance.getState()).toMatchObject({ enabled: true, restartRequired: false });
- await instance.dispose();
- });
-
- it('does not carry restart hints across Cindy restarts', async () => {
- const locations = paths();
- const runner = new EnvironmentRunner(null);
- const list = vi.fn(async () => [runningCodex()]);
- const first = service(locations, runner, list);
- expect(await first.setEnabled(true)).toMatchObject({ restartRequired: true });
+ it('retries failed recovery on normal exit and on a later launch', async () => {
+ const f = fixture(true);
+ f.runner.ignoreMutations = true;
+ const first = f.make();
+ expect(await first.getState()).toMatchObject({ status: 'recovery-required' });
await first.dispose();
- list.mockClear();
- const second = service(locations, runner, list);
- expect(await second.getState()).toMatchObject({ enabled: true, restartRequired: false });
- expect(list).not.toHaveBeenCalled();
- await second.dispose();
- });
-
- 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')}`,
- );
- // Turning it back on matches the default, so the override is cleared.
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
-
- 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 without writing a preference, so
- // the next Cindy launch resumes protection from the default.
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
- });
-
- it('protects by default on a fresh install without a restart hint', async () => {
- const locations = paths('default');
- const runner = new EnvironmentRunner(null);
- const list = vi.fn(async () => [runningCodex()]);
- const instance = service(locations, runner, list);
-
- expect(await instance.getState()).toMatchObject({
- enabled: true,
- status: 'protecting',
- restartRequired: false,
- });
- expect(runner.nodeOptions).toBe(
- `--require=${path.join(locations.supportPath, 'guard-hook.cjs')}`,
+ expect(f.runner.commands.filter(([command]) => command === 'unsetenv')).toHaveLength(2);
+ f.runner.ignoreMutations = false;
+ expect(await f.make().getState()).toEqual(PAUSED);
+ expect(f.runner.nodeOptions).toBeNull();
+ });
+
+ it.each(['current', 'previous'] as const)(
+ 'rechecks late injection from the %s profile on normal exit after successful startup cleanup',
+ async (profile) => {
+ const testFixture = fixture(true);
+ const service = testFixture.make();
+ expect(await service.getState()).toEqual(PAUSED);
+ expect(testFixture.runner.nodeOptions).toBeNull();
+ const legacyStore =
+ profile === 'current'
+ ? testFixture.store
+ : new CodexMicroGuardStore(
+ path.join(path.dirname(testFixture.supportPath), 'bbbbbbbbbbbb'),
+ );
+ const externalOptions = '--trace-warnings --require=unrelated-preload.cjs';
+ const token = seedLegacyGuard(legacyStore, externalOptions);
+ testFixture.runner.nodeOptions = `${externalOptions} ${token}`;
+ expect(await service.getState()).toEqual(PAUSED);
+
+ await service.dispose();
+
+ expect(testFixture.runner.nodeOptions).toBe(externalOptions);
+ expect(legacyStore.isFresh()).toBe(false);
+ expect(legacyStore.readState()).toBeNull();
+ expect(fs.existsSync(legacyStore.hookPath)).toBe(true);
+ const commandCount = testFixture.runner.commands.length;
+ await service.dispose();
+ expect(testFixture.runner.commands).toHaveLength(commandCount);
+ },
+ );
+
+ it('preserves failed late-injection recovery for the next startup without blocking exit', async () => {
+ const testFixture = fixture(true);
+ const service = testFixture.make();
+ expect(await service.getState()).toEqual(PAUSED);
+ const token = seedLegacyGuard(testFixture.store);
+ testFixture.runner.nodeOptions = token;
+ testFixture.runner.failNextMutation = true;
+
+ await expect(service.dispose()).resolves.toBeUndefined();
+
+ expect(testFixture.runner.nodeOptions).toBe(token);
+ expect(testFixture.store.readState()).not.toBeNull();
+ expect(await service.getState()).toMatchObject({ status: 'recovery-required' });
+ expect(await testFixture.make().getState()).toEqual(PAUSED);
+ expect(testFixture.runner.nodeOptions).toBeNull();
+ expect(testFixture.store.readState()).toBeNull();
+ });
+
+ it('cleans old profiles on an upgrade with no current-profile recovery state', async () => {
+ const f = fixture();
+ const previous = new CodexMicroGuardStore(
+ path.join(path.dirname(f.supportPath), 'bbbbbbbbbbbb'),
);
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
-
- expect(await instance.setEnabled(false)).toMatchObject({ enabled: false, status: 'disabled' });
- expect(runner.nodeOptions).toBeNull();
- expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({
- enabled: false,
- });
- await instance.dispose();
-
- // An explicit opt-out survives the next launch.
- const next = service(locations, runner, list);
- expect(await next.getState()).toMatchObject({ enabled: false, status: 'disabled' });
- expect(runner.nodeOptions).toBeNull();
- await next.dispose();
- });
-
- it('keeps default protection on across launches once this release installed the hook', async () => {
- const locations = paths('default');
- const runner = new EnvironmentRunner(null);
- const first = service(locations, runner);
- expect(await first.getState()).toMatchObject({ enabled: true, status: 'protecting' });
- expect(fs.existsSync(path.join(locations.supportPath, 'default-on'))).toBe(true);
+ f.runner.nodeOptions = seedLegacyGuard(previous);
+ expect(await f.make().getState()).toEqual(PAUSED);
+ expect(f.runner.nodeOptions).toBeNull();
+ expect(previous.isFresh()).toBe(false);
+ expect(previous.readState()).toBeNull();
+ });
+
+ it('allows multiple new instances to start and exit without reinstalling any preload', async () => {
+ const f = fixture(true);
+ const first = f.make();
+ const second = f.make();
+ expect(await Promise.all([first.getState(), second.getState()])).toEqual([PAUSED, PAUSED]);
await first.dispose();
-
- const second = service(locations, runner);
- expect(await second.getState()).toMatchObject({ enabled: true, status: 'protecting' });
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
- await second.dispose();
- });
-
- it('keeps a default-off release opt-out after upgrading', async () => {
- // Default-off releases left the hook behind and stored nothing on opt-out.
- const locations = paths('default');
- fs.mkdirSync(locations.supportPath, { recursive: true, mode: 0o700 });
- fs.writeFileSync(path.join(locations.supportPath, 'guard-hook.cjs'), '// old hook\n', {
- mode: 0o600,
- });
- const runner = new EnvironmentRunner(null);
- const instance = service(locations, runner);
-
- expect(await instance.getState()).toMatchObject({ enabled: false, status: 'disabled' });
- expect(runner.nodeOptions).toBeNull();
- expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({
- enabled: false,
- });
-
- expect(fs.existsSync(path.join(locations.supportPath, 'default-on'))).toBe(true);
- await instance.dispose();
-
- // Restoring defaults removes the override; the migration must not run again.
- fs.rmSync(locations.settingsPath);
- const restored = service(locations, runner);
- expect(await restored.getState()).toMatchObject({ enabled: true, status: 'protecting' });
- await restored.dispose();
- });
-
- it('keeps a legacy opt-out off and retries when it cannot be saved', async () => {
- const locations = paths('default');
- fs.mkdirSync(locations.supportPath, { recursive: true, mode: 0o700 });
- fs.writeFileSync(path.join(locations.supportPath, 'guard-hook.cjs'), '// old hook\n', {
- mode: 0o600,
- });
- // An unreadable settings path makes the override write fail.
- fs.mkdirSync(locations.settingsPath);
- const runner = new EnvironmentRunner(null);
- const blocked = service(locations, runner);
-
- expect(await blocked.getState()).toMatchObject({ enabled: false, status: 'disabled' });
- expect(runner.nodeOptions).toBeNull();
- expect(fs.existsSync(path.join(locations.supportPath, 'default-on'))).toBe(false);
- await blocked.dispose();
-
- fs.rmSync(locations.settingsPath, { recursive: true });
- const retried = service(locations, runner);
- expect(await retried.getState()).toMatchObject({ enabled: false, status: 'disabled' });
- expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({
- enabled: false,
- });
- expect(fs.existsSync(path.join(locations.supportPath, 'default-on'))).toBe(true);
- await retried.dispose();
- });
-
- it('turns a migrated opt-out back on and keeps it on after relaunch', async () => {
- const locations = paths('default');
- fs.mkdirSync(locations.supportPath, { recursive: true, mode: 0o700 });
- fs.writeFileSync(path.join(locations.supportPath, 'guard-hook.cjs'), '// old hook\n', {
- mode: 0o600,
- });
- const runner = new EnvironmentRunner(null);
- const instance = service(locations, runner);
- expect(await instance.getState()).toMatchObject({ enabled: false, status: 'disabled' });
-
- // Turning it back on records the new default and the marker for later launches.
- expect(await instance.setEnabled(true)).toMatchObject({ enabled: true, status: 'protecting' });
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
- await instance.dispose();
- const next = service(locations, runner);
- expect(await next.getState()).toMatchObject({ enabled: true, status: 'protecting' });
- await next.dispose();
- });
-
- 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(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: 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(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: 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();
- });
+ expect(await second.getState()).toEqual(PAUSED);
+ expect(f.runner.nodeOptions).toBeNull();
+ expect(f.runner.commands.filter(([command]) => command === 'unsetenv')).toHaveLength(1);
+ });
+
+ it.each(['win32', 'linux'] as const)(
+ 'leaves the environment and filesystem alone on %s',
+ async (platform) => {
+ const f = fixture();
+ f.runner.nodeOptions = '--trace-warnings';
+ f.environment.NODE_OPTIONS = '--require=' + f.store.hookPath;
+ const service = f.make({ platform });
+ expect(await service.getState()).toEqual({
+ supported: false,
+ enabled: false,
+ status: 'unsupported',
+ });
+ expect(await service.setEnabled(true)).toMatchObject({ status: 'unsupported' });
+ await service.dispose();
+ expect(f.runner.commands).toEqual([]);
+ expect(f.environment.NODE_OPTIONS).toBe('--require=' + f.store.hookPath);
+ expect(fs.existsSync(path.dirname(f.supportPath))).toBe(false);
+ },
+ );
});
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts
index 6c6fe243b0..fe981dba9e 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/codexMicroGuardCore.test.ts
@@ -11,25 +11,12 @@ import {
parseLaunchEnvironmentNodeOptions,
removeNodeOption,
restoreNodeOptions,
- type GuardCommandResult,
- type GuardCommandRunner,
+ stripLegacyGuardNodeOptions,
} 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[]) {}
+import { GuardEnvironmentRunner, seedLegacyGuard } from './guardRecoveryFixture';
- 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;
- }
-}
+const roots: string[] = [];
function temporaryStore(): CodexMicroGuardStore {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-guard-'));
@@ -43,10 +30,6 @@ function printed(nodeOptions?: string): string {
}\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 });
});
@@ -120,122 +103,261 @@ describe('Codex Micro guard launchctl parsing', () => {
});
});
-describe('Codex Micro guard store and manager', () => {
- it('writes private files and rejects a symlinked support directory', () => {
+describe('paused Codex Micro guard recovery', () => {
+ function fixture(original: string | null = '--trace-warnings') {
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 token = seedLegacyGuard(store, original);
+ const runner = new GuardEnvironmentRunner(original ? original + ' ' + token : token);
+ const environment = { NODE_OPTIONS: runner.nodeOptions! };
+ const manager = new CodexMicroGuardManager(store, runner, 'gui/501', environment);
+ return { store, token, runner, environment, manager };
+ }
- 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'),
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- expect(() => new CodexMicroGuardStore(path.join(linkedRoot, 'support')).prepare()).toThrow(
- 'unsafe',
- );
+ it('clears an active legacy lease, retains its hook, and preserves external options exactly', async () => {
+ const original = ' --title="two spaces" ';
+ const { store, runner, manager, environment } = fixture(original);
+ await manager.recover();
+ expect(runner.nodeOptions).toBe(original);
+ expect(environment.NODE_OPTIONS).toBe(original);
+ expect(store.isFresh()).toBe(false);
+ expect(store.readState()).toBeNull();
+ expect(fs.readFileSync(store.hookPath, 'utf8')).toBe('// retained legacy hook\n');
+ expect(fs.existsSync(store.receiptPath)).toBe(false);
+ const mutations = runner.commands.filter(([command]) => command !== 'print');
+ expect(mutations).toEqual([['setenv', 'NODE_OPTIONS', original]]);
+ await manager.recover();
+ expect(runner.commands.filter(([command]) => command !== 'print')).toEqual(mutations);
});
- 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);
+ it.each([null, ''])('restores an original %j environment distinctly', async (original) => {
+ const { runner, manager } = fixture(original);
+ await manager.recover();
+ expect(runner.nodeOptions).toBe(original);
+ });
+
+ it.each([
+ { original: null, profileCount: 2 },
+ { original: '', profileCount: 2 },
+ { original: null, profileCount: 3 },
+ { original: '', profileCount: 3 },
+ ])(
+ 'restores original $original distinctly through $profileCount sequential profile snapshots',
+ async ({ original, profileCount }) => {
+ const { store, runner, manager } = fixture(original);
+ const stores = [store];
+ for (let profileIndex = 1; profileIndex < profileCount; profileIndex += 1) {
+ const nextStore = new CodexMicroGuardStore(
+ path.join(path.dirname(store.supportPath), profileIndex.toString(16).padStart(12, '0')),
+ );
+ const nextToken = seedLegacyGuard(nextStore, runner.nodeOptions);
+ runner.nodeOptions = mergeNodeOptions(runner.nodeOptions, nextToken);
+ stores.push(nextStore);
+ }
- await expect(manager.refreshHeartbeat(115_001)).rejects.toThrow(
- 'lease is no longer fresh',
+ await manager.recover();
+
+ expect(runner.nodeOptions).toBe(original);
+ const expectedMutations =
+ original === null ? [['unsetenv', 'NODE_OPTIONS']] : [['setenv', 'NODE_OPTIONS', '']];
+ expect(runner.commands.filter(([command]) => command !== 'print')).toEqual(expectedMutations);
+ for (const profileStore of stores) {
+ expect(profileStore.isFresh()).toBe(false);
+ expect(profileStore.readState()).toBeNull();
+ expect(fs.existsSync(profileStore.hookPath)).toBe(true);
+ }
+ await manager.recover();
+ expect(runner.nodeOptions).toBe(original);
+ expect(runner.commands.filter(([command]) => command !== 'print')).toEqual(expectedMutations);
+ },
+ );
+
+ it('does not infer an empty original from an unrelated profile snapshot', async () => {
+ const { store, runner, manager } = fixture(null);
+ const unrelated = new CodexMicroGuardStore(
+ path.join(path.dirname(store.supportPath), 'aaaaaaaaaaaa'),
);
- expect(store.releaseLease(LEASE_ID, 115_001)).toBe(false);
- expect(
- fs.existsSync(path.join(store.supportPath, `lease-${staleLease}.json`)),
- ).toBe(false);
- });
+ seedLegacyGuard(unrelated, '');
- 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(),
+ await manager.recover();
+
+ expect(runner.nodeOptions).toBeNull();
+ expect(runner.commands.filter(([command]) => command !== 'print')).toEqual([
+ ['unsetenv', 'NODE_OPTIONS'],
]);
- 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({
+ it('terminates a cyclic snapshot chain without inventing an empty original', async () => {
+ const { store, token, runner, manager } = fixture(null);
+ const second = new CodexMicroGuardStore(
+ path.join(path.dirname(store.supportPath), 'aaaaaaaaaaaa'),
+ );
+ const secondToken = seedLegacyGuard(second, token);
+ runner.nodeOptions = mergeNodeOptions(token, secondToken);
+ store.writeState({
version: 1,
- originalNodeOptions: '--trace-warnings',
- installedNodeOptions: `--trace-warnings ${manager.token}`,
+ originalNodeOptions: runner.nodeOptions,
+ installedNodeOptions: 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']);
+ await manager.recover();
+
+ expect(runner.nodeOptions).toBeNull();
expect(store.readState()).toBeNull();
- expect(store.isFresh(100_000)).toBe(false);
+ expect(second.readState()).toBeNull();
});
- 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('removes all profiles and duplicate arguments without restoring another profile from a snapshot', async () => {
+ const { store, token, runner, manager } = fixture(null);
+ const second = new CodexMicroGuardStore(
+ path.join(path.dirname(store.supportPath), 'aaaaaaaaaaaa'),
+ );
+ const secondToken = seedLegacyGuard(second, token);
+ runner.nodeOptions = token + ' ' + secondToken + ' ' + token + ' --inspect=9229';
+ await manager.recover();
+ expect(runner.nodeOptions).toBe('--inspect=9229');
+ expect(second.isFresh()).toBe(false);
+ expect(second.readState()).toBeNull();
+ expect(fs.existsSync(second.hookPath)).toBe(true);
});
- 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);
+ it('cleans known preload paths even when a profile or its recovery state has disappeared', async () => {
+ const { store, token, runner, manager } = fixture();
+ store.removeState();
+ const missing = path.join(path.dirname(store.supportPath), 'bbbbbbbbbbbb', 'guard-hook.cjs');
+ runner.nodeOptions = '--require=' + missing + ' ' + token;
+ await manager.recover();
+ expect(runner.nodeOptions).toBeNull();
+ expect(fs.existsSync(path.dirname(missing))).toBe(false);
+ });
- await expect(manager.enable('// hook\n')).rejects.toThrow(
- 'launchctl command failed',
- );
+ it('cleans a corrupt recovery snapshot without using its contents', async () => {
+ const { store, runner, manager } = fixture();
+ fs.writeFileSync(store.statePath, 'broken');
+ await manager.recover();
+ expect(runner.nodeOptions).toBe('--trace-warnings');
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();
+ it('keeps options added after activation', async () => {
+ const { runner, manager } = fixture();
+ runner.nodeOptions += ' --inspect=9229';
+ await manager.recover();
+ expect(runner.nodeOptions).toBe('--trace-warnings --inspect=9229');
+ });
+
+ it('stops interception and keeps recovery evidence after a failed write, then retries', async () => {
+ const { store, runner, manager, environment } = fixture();
+ runner.failNextMutation = true;
+ await expect(manager.recover()).rejects.toThrow('launchctl command failed');
expect(store.isFresh()).toBe(false);
expect(store.readState()).not.toBeNull();
+ expect(environment.NODE_OPTIONS).toBe('--trace-warnings');
+ await manager.recover();
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ expect(store.readState()).toBeNull();
+ });
+
+ it('does not report cleanup complete when launchctl still contains the preload', async () => {
+ const { store, runner, manager } = fixture();
+ runner.ignoreMutations = true;
+ await expect(manager.recover()).rejects.toThrow('remains in the launch environment');
+ expect(store.readState()).not.toBeNull();
+ });
+
+ it('still clears the GUI environment if the inherited options cannot be safely parsed', async () => {
+ const { runner, manager, environment } = fixture();
+ environment.NODE_OPTIONS = '--title="unfinished';
+ await expect(manager.recover()).rejects.toThrow('inherited environment');
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ expect(environment.NODE_OPTIONS).toBe('--title="unfinished');
+ });
+
+ it('does not mutate an unverified launchctl snapshot', async () => {
+ const { store, runner, manager } = fixture();
+ runner.invalidSnapshot = true;
+ await expect(manager.recover()).rejects.toThrow('snapshot is invalid');
+ expect(runner.commands).toEqual([['print', 'gui/501']]);
+ expect(store.isFresh()).toBe(false);
+ });
+
+ it('serializes concurrent cleanup from different profiles without losing unrelated options', async () => {
+ const { store, runner, manager } = fixture();
+ const second = new CodexMicroGuardStore(
+ path.join(path.dirname(store.supportPath), 'cccccccccccc'),
+ );
+ runner.nodeOptions += ' ' + seedLegacyGuard(second, runner.nodeOptions);
+ const other = new CodexMicroGuardManager(second, runner, 'gui/501', {});
+ await Promise.all([manager.recover(), other.recover()]);
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ expect(runner.commands.filter(([command]) => command === 'setenv')).toHaveLength(1);
+ });
+
+ it('clears the preload but does not follow a symlinked profile or erase the target files', async () => {
+ const { store, runner, manager } = fixture();
+ const outside = path.join(path.dirname(store.supportPath), 'unrelated');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, 'enabled'), 'keep');
+ const linked = path.join(path.dirname(store.supportPath), 'dddddddddddd');
+ fs.symlinkSync(outside, linked, process.platform === 'win32' ? 'junction' : 'dir');
+ runner.nodeOptions += ' --require=' + path.join(linked, 'guard-hook.cjs');
+ await expect(manager.recover()).rejects.toThrow('legacy files could not be deactivated');
+ expect(runner.nodeOptions).toBe('--trace-warnings');
+ expect(fs.readFileSync(path.join(outside, 'enabled'), 'utf8')).toBe('keep');
+ });
+
+ it('writes private state and rejects a symlinked support root', async () => {
+ 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 outside = temporaryStore();
+ outside.prepare();
+ const linked = path.join(path.dirname(store.supportPath), 'linked');
+ fs.symlinkSync(outside.supportPath, linked, process.platform === 'win32' ? 'junction' : 'dir');
+ const manager = new CodexMicroGuardManager(
+ new CodexMicroGuardStore(path.join(linked, 'aaaaaaaaaaaa')),
+ new GuardEnvironmentRunner(null),
+ 'gui/501',
+ {},
+ );
+ await expect(manager.recover()).rejects.toThrow('unsafe');
+ expect(fs.readdirSync(outside.supportPath)).toEqual([]);
+ });
+});
+
+describe('legacy preload argument boundaries', () => {
+ const root = path.join(os.tmpdir(), 'CindyCodexMicroGuard');
+ const hook = path.join(root, 'aaaaaaaaaaaa', 'guard-hook.cjs');
+ // Quoted NODE_OPTIONS strings escape Windows separators just as Node expects.
+ const quotedHook = JSON.stringify(hook);
+ const strip = (value: string | null) => stripLegacyGuardNodeOptions(value, root, hook);
+
+ it.each([
+ '--require=' + hook,
+ '--require=' + quotedHook,
+ '--require ' + quotedHook,
+ '-r ' + quotedHook,
+ ])('removes a real preload argument: %s', (argument) => {
+ expect(strip('--trace-warnings ' + argument + ' --inspect=9229')).toBe(
+ '--trace-warnings --inspect=9229',
+ );
+ expect(strip(argument)).toBeNull();
+ });
+
+ it('preserves similarly named files, other scripts, and quoted option values', () => {
+ const lookalike = '--require=' + hook + '.backup';
+ const elsewhere = '--require=' + path.join(os.tmpdir(), 'other', 'guard-hook.cjs');
+ const embedded = '--title=' + JSON.stringify('literal --require=' + hook + ' text');
+ const value = lookalike + ' ' + elsewhere + ' ' + embedded;
+ expect(strip(value)).toBe(value);
+ expect(strip(value + ' --require=' + hook)).toBe(value);
+ });
+
+ it('keeps absence and empty values unchanged and rejects malformed quotes', () => {
+ expect(strip(null)).toBeNull();
+ expect(strip('')).toBe('');
+ expect(() => strip('--title="unfinished')).toThrow('cannot safely parse');
});
});
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/guardRecoveryFixture.ts b/apps/desktop/src/main/worklouder-codex/__tests__/guardRecoveryFixture.ts
new file mode 100644
index 0000000000..0e4949472f
--- /dev/null
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/guardRecoveryFixture.ts
@@ -0,0 +1,55 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import {
+ CodexMicroGuardStore,
+ type GuardCommandResult,
+ type GuardCommandRunner,
+} from '../codexMicroGuardCore.js';
+
+/** In-memory launchctl replacement; never reads or changes the real GUI environment. */
+export class GuardEnvironmentRunner implements GuardCommandRunner {
+ readonly commands: string[][] = [];
+ failNextMutation = false;
+ ignoreMutations = false;
+ invalidSnapshot = false;
+
+ constructor(public nodeOptions: string | null) {}
+
+ async run(arguments_: readonly string[]): Promise<GuardCommandResult> {
+ this.commands.push([...arguments_]);
+ if (arguments_[0] === 'print') {
+ const entry = this.nodeOptions === null ? '' : 'NODE_OPTIONS => ' + this.nodeOptions + '\n';
+ return {
+ status: 0,
+ stdout: this.invalidSnapshot
+ ? 'invalid'
+ : 'gui/501 = {\n\tenvironment = {\n' + entry + '\t}\n}\n',
+ stderr: '',
+ };
+ }
+ if (this.failNextMutation) {
+ this.failNextMutation = false;
+ return { status: 7, stdout: '', stderr: 'fixture failure' };
+ }
+ if (!this.ignoreMutations) {
+ if (arguments_[0] === 'setenv') this.nodeOptions = arguments_[2];
+ if (arguments_[0] === 'unsetenv') this.nodeOptions = null;
+ }
+ return { status: 0, stdout: '', stderr: '' };
+ }
+}
+
+/** Materialize only legacy-format files, including the lease of a still-running old version. */
+export function seedLegacyGuard(store: CodexMicroGuardStore, original: string | null = null) {
+ const token = '--require=' + store.hookPath;
+ store.installHook('// retained legacy hook\n');
+ store.writeState({
+ version: 1,
+ originalNodeOptions: original,
+ installedNodeOptions: original ? original + ' ' + token : token,
+ });
+ store.markEnabled();
+ store.registerLease('11111111-1111-4111-8111-111111111111', Date.now());
+ fs.writeFileSync(path.join(store.supportPath, 'receipt.json'), '{}', { mode: 0o600 });
+ return token;
+}
diff --git a/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
index 62d3610353..24d9ff81eb 100644
--- a/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
+++ b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
@@ -373,110 +373,100 @@ export class CodexMicroGuardStore {
}
}
+/** Retires legacy global preloads across all Cindy profiles in the current user's GUI domain. */
export class CodexMicroGuardManager {
readonly token: string;
+ private readonly rootStore: CodexMicroGuardStore;
constructor(
readonly store: CodexMicroGuardStore,
private readonly runner: GuardCommandRunner,
private readonly launchctlDomain: string,
- private readonly leaseId: string,
+ private readonly environment: NodeJS.ProcessEnv = process.env,
) {
this.token = `--require=${store.hookPath}`;
+ this.rootStore = new CodexMicroGuardStore(path.dirname(store.supportPath));
+ }
+
+ /**
+ * Protection is suspended (#5985). Retire every profile's preload, even if
+ * an old instance still has a live lease. Keep hook files for processes that
+ * already inherited NODE_OPTIONS; removing the environment cannot update them.
+ */
+ async recover(): Promise<void> {
+ const inherited = this.environment.NODE_OPTIONS;
+ let inheritedFailed = false;
+ if (inherited !== undefined) {
+ try {
+ const cleaned = this.stripNodeOptions(inherited);
+ if (cleaned === null) delete this.environment.NODE_OPTIONS;
+ else this.environment.NODE_OPTIONS = cleaned;
+ } catch {
+ inheritedFailed = true;
+ }
+ }
+ // Profiles share launchctl's environment. New instances must serialize the
+ // complete read/remove/write transaction, not just each profile's files.
+ await this.rootStore.withLeaseLock(() => this.recoverLocked());
+ if (inheritedFailed) throw new Error('guard inherited environment could not be cleaned');
}
- 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 stripNodeOptions(value: string | null): string | null {
+ return stripLegacyGuardNodeOptions(value, this.rootStore.supportPath, this.store.hookPath);
}
- 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,
- });
+ private async recoverLocked(): Promise<void> {
+ const profiles = new Set<string>();
+ if (fs.existsSync(this.store.supportPath)) profiles.add(this.store.supportPath);
+ for (const name of fs.readdirSync(this.rootStore.supportPath)) {
+ if (/^[0-9a-f]{12}$/u.test(name)) profiles.add(path.join(this.rootStore.supportPath, name));
}
-
- 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;
+ const cleanedStores: CodexMicroGuardStore[] = [];
+ const states: CodexMicroGuardStateRecord[] = [];
+ let filesFailed = false;
+ for (const profile of profiles) {
+ const store = new CodexMicroGuardStore(profile);
try {
- otherLeasesRemain = this.store.releaseLease(this.leaseId, now);
- if (!otherLeasesRemain) this.store.removeEnabled();
+ await store.withLeaseLock(async () => {
+ store.removeEnabled();
+ store.removeHeartbeat();
+ store.removeReceipt();
+ try {
+ const state = store.readState();
+ if (state) states.push(state);
+ } catch {
+ // A missing/corrupt snapshot must not keep the known preload active.
+ }
+ });
+ cleanedStores.push(store);
} catch {
- rollbackFailed = true;
- }
- if (environmentInstalled && !otherLeasesRemain) {
- try {
- await this.restoreEnvironment(original);
- } catch {
- rollbackFailed = true;
- }
+ // Still remove the global preload if one profile's files are unsafe or
+ // inaccessible. Expose recovery-required so cleanup can be retried.
+ filesFailed = 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;
+ const current = await this.readNodeOptions();
+ let restored = this.stripNodeOptions(current);
+ // Preserve an explicitly empty original value. Never restore snapshot text:
+ // another profile's original value can contain a preload already retired.
+ if (restored === null && current !== null && hasEmptyOriginalNodeOptions(current, states))
+ restored = '';
+ if (restored !== current) {
+ await this.restoreEnvironment(restored);
+ const actual = await this.readNodeOptions();
+ if (this.stripNodeOptions(actual) !== actual) {
+ throw new Error('guard preload remains in the launch environment');
+ }
+ }
+ for (const store of cleanedStores) {
try {
- state = this.store.readState();
+ await store.withLeaseLock(async () => store.removeState());
} 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;
+ filesFailed = true;
}
- 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();
}
+ if (filesFailed) throw new Error('guard legacy files could not be deactivated');
}
private async readNodeOptions(): Promise<string | null> {
@@ -498,6 +488,21 @@ export class CodexMicroGuardManager {
}
}
+function hasEmptyOriginalNodeOptions(
+ current: string,
+ states: readonly CodexMicroGuardStateRecord[],
+): boolean {
+ const values = new Set([current]);
+ for (const value of values) {
+ for (const state of states) {
+ if (state.installedNodeOptions !== value) continue;
+ if (state.originalNodeOptions === '') return true;
+ if (state.originalNodeOptions !== null) values.add(state.originalNodeOptions);
+ }
+ }
+ return false;
+}
+
export function parseLaunchEnvironmentNodeOptions(input: string): LaunchEnvironmentNodeOptions {
let depth = 0;
let environmentDepth: number | null = null;
@@ -558,6 +563,68 @@ export function parseLaunchEnvironmentNodeOptions(input: string): LaunchEnvironm
return nodeOptions === null ? { kind: 'absent' } : { kind: 'present', value: nodeOptions };
}
+/** Remove only preload arguments pointing at Cindy's known legacy hook layout. */
+export function stripLegacyGuardNodeOptions(
+ value: string | null,
+ supportRoot: string,
+ currentHookPath: string,
+): string | null {
+ if (value === null) return null;
+ const arguments_: Array<{ start: number; end: number; value: string }> = [];
+ let cursor = 0;
+ while (cursor < value.length) {
+ if (/\s/u.test(value[cursor])) {
+ cursor += 1;
+ continue;
+ }
+ const start = cursor;
+ let argument = '';
+ let quoted = false;
+ while (cursor < value.length) {
+ const character = value[cursor];
+ if (!quoted && /\s/u.test(character)) break;
+ if (character === '"') quoted = !quoted;
+ else if (quoted && character === '\\' && cursor + 1 < value.length) {
+ argument += value[++cursor];
+ } else argument += character;
+ cursor += 1;
+ }
+ if (quoted) throw new Error('guard cannot safely parse NODE_OPTIONS');
+ arguments_.push({ start, end: cursor, value: argument });
+ }
+ const isGuardHook = (filename: string): boolean => {
+ if (filename === currentHookPath) return true;
+ const profile = path.basename(path.dirname(filename));
+ return (
+ /^[0-9a-f]{12}$/u.test(profile) &&
+ filename === path.join(supportRoot, profile, 'guard-hook.cjs')
+ );
+ };
+ const removals: Array<{ start: number; end: number }> = [];
+ for (let index = 0; index < arguments_.length; index += 1) {
+ const argument = arguments_[index];
+ if (argument.value.startsWith('--require=') && isGuardHook(argument.value.slice(10))) {
+ removals.push(argument);
+ } else if (
+ (argument.value === '--require' || argument.value === '-r') &&
+ arguments_[index + 1] &&
+ isGuardHook(arguments_[index + 1].value)
+ ) {
+ removals.push({ start: argument.start, end: arguments_[++index].end });
+ }
+ }
+ let cleaned = value;
+ for (const removal of removals.reverse()) {
+ let { start, end } = removal;
+ // Retain unrelated options, quoting and whitespace byte-for-byte, removing
+ // just one separator owned by the appended token (as legacy recovery did).
+ if (start > 0) start -= 1;
+ else if (end < cleaned.length) end += 1;
+ cleaned = cleaned.slice(0, start) + cleaned.slice(end);
+ }
+ return cleaned.length > 0 || removals.length === 0 ? cleaned : null;
+}
+
export function nodeOptionsContains(token: string, value: string | null): boolean {
return value?.split(/\s+/u).includes(token) ?? false;
}
diff --git a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
index af8b1ed03e..d383b9cef8 100644
--- a/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
+++ b/apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx
@@ -1077,7 +1077,13 @@ export function WorkLouderCodexSettings({
) : (
<Switch
checked={guardState?.enabled ?? false}
- disabled={guardLoading || guardSaving || !guardState || !guardState.supported}
+ disabled={
+ guardLoading ||
+ guardSaving ||
+ !guardState ||
+ !guardState.supported ||
+ guardState.status === 'paused'
+ }
onCheckedChange={(checked) => void setGuardEnabled(checked)}
aria-label={t('settings.shortcuts.workLouderCodex.codexGuard.aria')}
/>
@@ -1560,6 +1566,8 @@ function guardDescriptionKey(
): string {
if (requestFailed) return 'error';
switch (status) {
+ case 'paused':
+ return 'paused';
case 'unsupported':
return 'unsupported';
case 'protecting':
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 37992c6a72..139d868134 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkLouderCodexSettings.test.tsx
@@ -2,6 +2,12 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import zhCN from '../../../i18n/locales/zh-CN/common.json';
+import zhTW from '../../../i18n/locales/zh-TW/common.json';
+import en from '../../../i18n/locales/en/common.json';
+import ja from '../../../i18n/locales/ja/common.json';
+import ko from '../../../i18n/locales/ko/common.json';
beforeAll(() => {
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
@@ -21,7 +27,13 @@ const mocks = vi.hoisted(() => ({
setGuardEnabled: vi.fn(),
recoverGuard: vi.fn(),
guardRestartRequired: false,
- guardStatus: 'disabled' as 'disabled' | 'protecting' | 'intercepted' | 'recovery-required',
+ guardStatus: 'disabled' as
+ | 'disabled'
+ | 'paused'
+ | 'protecting'
+ | 'intercepted'
+ | 'recovery-required',
+ translate: null as ((key: string) => string) | null,
setLayoutPreviewActive: vi.fn(),
previewListeners: [] as Array<
(input: {
@@ -42,7 +54,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({ t: (key: string) => mocks.translate?.(key) ?? key }),
}));
vi.mock('@/hooks/useCodexMicroGuard', () => ({
@@ -126,6 +138,7 @@ describe('WorkLouderCodexSettings', () => {
mocks.agentSource = 'sidebar';
mocks.layout = createWorkLouderCodexDefaultSettings().layout;
mocks.guardStatus = 'disabled';
+ mocks.translate = null;
mocks.guardRestartRequired = false;
mocks.deviceEnabled = true;
mocks.connectionStatus = 'connected';
@@ -320,6 +333,64 @@ describe('WorkLouderCodexSettings', () => {
},
);
+ it.each(['codex-micro', 'creator-micro-2'] as const)(
+ 'disables the paused protection switch while retaining recovery for %s',
+ (model) => {
+ mocks.deviceType = model;
+ mocks.layout = createWorkLouderCodexDefaultSettings(model).layout;
+ mocks.guardStatus = 'paused';
+ const { rerender } = render(<WorkLouderCodexSettings model={model} onBack={vi.fn()} />);
+ const toggle = screen.getByRole('switch', {
+ name: 'settings.shortcuts.workLouderCodex.codexGuard.aria',
+ });
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ expect(toggle.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(toggle);
+ expect(mocks.setGuardEnabled).not.toHaveBeenCalled();
+ expect(
+ screen.getByText('settings.shortcuts.workLouderCodex.codexGuard.descriptions.paused'),
+ ).toBeTruthy();
+ mocks.guardStatus = 'recovery-required';
+ rerender(<WorkLouderCodexSettings model={model} onBack={vi.fn()} />);
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'settings.shortcuts.workLouderCodex.codexGuard.recover',
+ }),
+ );
+ expect(mocks.recoverGuard).toHaveBeenCalledOnce();
+ },
+ );
+
+ it.each([
+ ['zh-CN', zhCN],
+ ['zh-TW', zhTW],
+ ['en', en],
+ ['ja', ja],
+ ['ko', ko],
+ ] as const)(
+ 'renders the real %s pause and recovery copy without falling back to a key',
+ async (locale, catalog) => {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: locale,
+ fallbackLng: false,
+ resources: { [locale]: { translation: catalog } },
+ });
+ mocks.translate = (key) => String(i18n.t(key));
+ mocks.guardStatus = 'paused';
+ const copy = catalog.settings.shortcuts.workLouderCodex.codexGuard;
+ const { rerender } = render(<WorkLouderCodexSettings onBack={vi.fn()} />);
+ const text = screen.getByText(copy.descriptions.paused).textContent!;
+ expect(text).not.toContain('?');
+ if (locale === 'zh-CN') expect(text).toContain('已暂停');
+ expect(screen.getByRole('switch', { name: copy.aria }).hasAttribute('disabled')).toBe(true);
+ mocks.guardStatus = 'recovery-required';
+ rerender(<WorkLouderCodexSettings onBack={vi.fn()} />);
+ expect(screen.getByText(copy.descriptions['recovery-required'])).toBeTruthy();
+ expect(screen.getByRole('button', { name: copy.recover })).toBeTruthy();
+ },
+ );
+
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/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 897cc47c19..a9aa328f51 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5288,8 +5288,9 @@
"descriptions": {
"unsupported": "This protection is available on macOS only.",
"disabled": "While Cindy is running, stop Codex from connecting to Work Louder keyboards. Cindy itself is not restricted.",
- "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."
+ "paused": "Protection is paused because it can affect other apps. If problems persist, quit older Cindy versions, then fully quit and reopen the affected apps.",
+ "recovery-required": "Protection is paused, but its old startup settings still need to be removed. Select “Restore environment”, then fully quit and reopen the affected apps.",
+ "error": "Cindy could not read or remove the old protection settings. Protection remains paused."
},
"restartRequired": "Quit and reopen Codex to apply"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index ebaba8cc00..104f713322 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5263,8 +5263,9 @@
"descriptions": {
"unsupported": "この保護機能は macOS でのみ利用できます。",
"disabled": "Cindy の実行中、Codex が Work Louder キーボード に接続するのを防ぎます。Cindy 自体は制限されません。",
- "recovery-required": "保護は停止しましたが、NODE_OPTIONS は安全に復元されていません。再度有効にする前に復元を再試行してください。",
- "error": "Codex の保護を更新できませんでした。以前の NODE_OPTIONS は保持されているか、復元待ちです。"
+ "paused": "他のアプリに影響するため、この保護機能は一時停止しています。問題が続く場合は、旧バージョンの Cindy を終了し、影響を受けたアプリを完全に終了してから開き直してください。",
+ "recovery-required": "保護機能は一時停止していますが、以前の起動設定が残っています。「環境を復元」を選択し、完了後に影響を受けたアプリを完全に終了してから開き直してください。",
+ "error": "以前の保護設定を読み取るか削除することができませんでした。保護機能は一時停止したままです。"
},
"restartRequired": "適用するには Codex を完全に終了して再起動"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index bbcf607ffa..23c8d9c0bf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5263,8 +5263,9 @@
"descriptions": {
"unsupported": "이 보호 기능은 macOS에서만 사용할 수 있습니다.",
"disabled": "Cindy가 실행되는 동안 Codex가 Work Louder 키보드에 연결하지 못하게 합니다. Cindy 자체는 제한하지 않습니다.",
- "recovery-required": "보호가 중지되었지만 NODE_OPTIONS가 안전하게 복원되지 않았습니다. 다시 켜기 전에 복원을 재시도하세요.",
- "error": "Codex 보호를 업데이트하지 못했습니다. 기존 NODE_OPTIONS는 유지되었거나 복원 대기 중입니다."
+ "paused": "다른 앱에 영향을 줄 수 있어 보호 기능이 일시 중지되었습니다. 문제가 계속되면 이전 버전의 Cindy를 종료한 다음 영향을 받는 앱을 완전히 종료하고 다시 여세요.",
+ "recovery-required": "보호 기능은 일시 중지되었지만 이전 시작 설정이 남아 있습니다. “환경 복원”을 선택한 후 영향을 받는 앱을 완전히 종료하고 다시 여세요.",
+ "error": "Cindy가 이전 보호 설정을 읽거나 제거하지 못했습니다. 보호 기능은 일시 중지된 상태로 유지됩니다."
},
"restartRequired": "적용하려면 Codex를 완전히 종료한 뒤 다시 여세요"
},
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 3ef7a29b9e..1b55093c8a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5257,8 +5257,9 @@
"descriptions": {
"unsupported": "此保护仅在 macOS 上可用。",
"disabled": "Cindy 运行期间阻止 Codex 连接 Work Louder 键盘;不会限制 Cindy 本身。",
- "recovery-required": "保护已停止,但 NODE_OPTIONS 尚未安全恢复。请先重试恢复,再重新开启。",
- "error": "Cindy 无法更新 Codex 保护;原有 NODE_OPTIONS 已保留或等待恢复。"
+ "paused": "此保护因影响其他应用已暂停。若应用仍异常,请退出旧版 Cindy,再完全退出并重新打开受影响应用。",
+ "recovery-required": "保护已暂停,但旧的启动设置尚未清理完成。请点击“恢复环境”,完成后完全退出并重新打开受影响应用。",
+ "error": "Cindy 无法读取或清理旧的保护设置;此保护仍保持暂停。"
},
"restartRequired": "请完全退出并重新打开 Codex 以生效"
},
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 96178b42e5..b254184594 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5263,8 +5263,9 @@
"descriptions": {
"unsupported": "此保護僅可在 macOS 上使用。",
"disabled": "Cindy 執行期間會阻止 Codex 連線至 Work Louder 鍵盤;不會限制 Cindy 本身。",
- "recovery-required": "保護已停止,但 NODE_OPTIONS 尚未安全還原。請先重試還原,再重新開啟。",
- "error": "Cindy 無法更新 Codex 保護;原有 NODE_OPTIONS 已保留或等待還原。"
+ "paused": "此保護因影響其他應用程式已暫停。若應用程式仍異常,請結束舊版 Cindy,再完全結束並重新開啟受影響的應用程式。",
+ "recovery-required": "保護已暫停,但舊的啟動設定尚未清理完成。請點擊「還原環境」,完成後完全結束並重新開啟受影響的應用程式。",
+ "error": "Cindy 無法讀取或清理舊的保護設定;此保護仍保持暫停。"
},
"restartRequired": "請完全結束並重新開啟 Codex 以生效"
},
diff --git a/apps/desktop/src/shared/codexMicroGuard.ts b/apps/desktop/src/shared/codexMicroGuard.ts
index fe66d4fcac..6b3bc28b85 100644
--- a/apps/desktop/src/shared/codexMicroGuard.ts
+++ b/apps/desktop/src/shared/codexMicroGuard.ts
@@ -6,11 +6,17 @@ 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';
+ | 'unsupported'
+ | 'paused'
+ | 'disabled'
+ | 'protecting'
+ | 'intercepted'
+ | 'recovery-required'
+ | 'error';
export interface CodexMicroGuardState {
supported: boolean;
- /** Machine-local override shared by Codex Micro and Creator Micro 2. Defaults to true. */
+ /** Effective state shared by both keyboards. Always false while protection is paused. */
enabled: boolean;
status: CodexMicroGuardStatus;
/** A running desktop Codex predates protection and has not applied it. */
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
index 8d58846c45..e2e352d873 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
@@ -899,9 +899,14 @@ describe('Cindy durable PI Subagent runner', () => {
const claimPath = path.join(fixture.root, first.runId, 'resume.claim');
await writeFile(claimPath, '', { mode: 0o600 });
- const attempt = resumePiSubagentRun(
- fixture.root, first.runId, 'continue', resumeLaunch(fixture),
- );
+ const attempt = Promise.allSettled([
+ resumePiSubagentRun(
+ fixture.root,
+ first.runId,
+ "continue",
+ resumeLaunch(fixture),
+ ),
+ ]);
// The racer completes its write inside the re-read budget. Late enough
// that a single-read implementation has certainly already given up on it,
// early enough to land before the budget expires.
@@ -913,7 +918,13 @@ describe('Cindy durable PI Subagent runner', () => {
{ mode: 0o600 },
);
- await expect(attempt).rejects.toThrow(/already resuming this Subagent generation/i);
+ const [outcome] = await attempt;
+ expect(outcome.status).toBe("rejected");
+ if (outcome.status === "rejected") {
+ expect(() => {
+ throw outcome.reason;
+ }).toThrow(/already resuming this Subagent generation/i);
+ }
// The decisive part: no second generation was launched over that session.
const runs = await listPiSubagentRuns(fixture.root);
expect(runs.filter((run) => run.taskId === first.taskId)).toHaveLength(1);