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(work-louder): 默认开启「防止 Codex 占用设备」 (#5338)

Dashf9663db2376a
diff --git a/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
index 3ef2b3185f..fa1533d81f 100644
--- a/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
+++ b/apps/desktop/src/main/worklouder-codex/CodexMicroGuardService.ts
@@ -37,7 +37,7 @@ interface CodexMicroGuardServiceOptions {
}
const log = desktopMakerLogger.child('codex-micro-guard');
-const DEFAULT_SETTINGS: CodexMicroGuardSettings = { enabled: false };
+const DEFAULT_SETTINGS: CodexMicroGuardSettings = { enabled: true };
const MAX_SETTINGS_BYTES = 8 * 1024;
const HEARTBEAT_INTERVAL_MS = 5_000;
@@ -59,6 +59,8 @@ export class CodexMicroGuardService {
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;
@@ -107,6 +109,7 @@ export class CodexMicroGuardService {
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();
}
@@ -156,7 +159,8 @@ export class CodexMicroGuardService {
private async initializeInternal(): Promise<void> {
if (this.platform !== 'darwin') return;
- const enabled = this.settingsStore.read().enabled;
+ this.legacyOptOutPending = !this.preserveLegacyOptOut();
+ const enabled = !this.legacyOptOutPending && this.settingsStore.read().enabled;
try {
if (enabled) {
await this.manager.enable(this.hookContents);
@@ -180,6 +184,35 @@ export class CodexMicroGuardService {
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');
+ }
+ return true;
+ }
+
private async enable(): Promise<void> {
if (this.active && this.store.isFresh()) return;
this.failed = false;
@@ -292,7 +325,7 @@ export class CodexMicroGuardService {
if (this.platform !== 'darwin') {
return { supported: false, enabled: false, status: 'unsupported' };
}
- const enabled = this.settingsStore.read().enabled;
+ const enabled = !this.legacyOptOutPending && this.settingsStore.read().enabled;
let status: CodexMicroGuardState['status'];
if (this.recoveryRequired) status = 'recovery-required';
else if (this.failed) status = 'error';
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 40c82b17c0..4e47bf9f3e 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/CodexMicroGuardService.test.ts
@@ -54,12 +54,18 @@ function printEnvironment(nodeOptions: string | null): string {
}\t}\n}\n`;
}
-function paths() {
+/**
+ * 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 }) {
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: path.join(root, 'settings.json'),
+ settingsPath,
};
}
@@ -196,7 +202,8 @@ describe('CodexMicroGuardService', () => {
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 });
+ // 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'),
@@ -207,9 +214,124 @@ describe('CodexMicroGuardService', () => {
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 });
+ // 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(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);
+ 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 () => {
@@ -245,7 +367,7 @@ describe('CodexMicroGuardService', () => {
expect(await instance.recover()).toMatchObject({ enabled: false, status: 'disabled' });
expect(runner.nodeOptions).toBeNull();
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: false });
await instance.dispose();
});
@@ -260,7 +382,7 @@ describe('CodexMicroGuardService', () => {
expect(await instance.getState()).toMatchObject({ enabled: false, status: 'disabled' });
expect(runner.nodeOptions).toBe('--trace-warnings');
- expect(fs.existsSync(locations.settingsPath)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(locations.settingsPath, 'utf8'))).toEqual({ enabled: false });
await instance.dispose();
});
diff --git a/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
index 623b2f7d85..62d3610353 100644
--- a/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
+++ b/apps/desktop/src/main/worklouder-codex/codexMicroGuardCore.ts
@@ -25,7 +25,8 @@ 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_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';
@@ -81,6 +82,8 @@ export class CodexMicroGuardStore {
readonly heartbeatPath: string;
readonly hookPath: string;
readonly receiptPath: string;
+ /** Written by releases where protection defaults on; legacy migration then never reruns. */
+ readonly defaultOnPath: string;
constructor(readonly supportPath: string) {
this.statePath = path.join(supportPath, 'state.json');
@@ -88,6 +91,7 @@ export class CodexMicroGuardStore {
this.heartbeatPath = path.join(supportPath, 'heartbeat');
this.hookPath = path.join(supportPath, 'guard-hook.cjs');
this.receiptPath = path.join(supportPath, 'receipt.json');
+ this.defaultOnPath = path.join(supportPath, 'default-on');
}
prepare(): void {
@@ -104,6 +108,16 @@ export class CodexMicroGuardStore {
if (this.readPrivateFile('guard-hook.cjs') !== contents) {
throw new Error('guard hook verification failed');
}
+ this.markDefaultOn();
+ }
+
+ markDefaultOn(): void {
+ this.atomicWrite('default-on', '');
+ }
+
+ /** The hook outlives disabling; without the marker it came from a default-off release. */
+ hasLegacyHook(): boolean {
+ return fs.existsSync(this.hookPath) && !fs.existsSync(this.defaultOnPath);
}
readState(): CodexMicroGuardStateRecord | null {
diff --git a/apps/desktop/src/shared/codexMicroGuard.ts b/apps/desktop/src/shared/codexMicroGuard.ts
index 75d992335c..fe66d4fcac 100644
--- a/apps/desktop/src/shared/codexMicroGuard.ts
+++ b/apps/desktop/src/shared/codexMicroGuard.ts
@@ -10,7 +10,7 @@ export type CodexMicroGuardStatus =
export interface CodexMicroGuardState {
supported: boolean;
- /** Machine-local override shared by Codex Micro and Creator Micro 2. Defaults to false. */
+ /** Machine-local override shared by Codex Micro and Creator Micro 2. Defaults to true. */
enabled: boolean;
status: CodexMicroGuardStatus;
/** A running desktop Codex predates protection and has not applied it. */