Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

53.8 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdir, writeFile, rm, readFile } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { join, relative, resolve, basename } from 'path';
import { tmpdir } from 'os';
import { EventEmitter } from 'events';
import sharp from 'sharp';
import { ChildProcess } from 'child_process';
import { pinPlatform } from '../../lib/testHelper.js';

const admissionFault = vi.hoisted(() => ({ error: null }));
vi.mock('../../lib/backupSnapshotBoundary.js', async original => {
  const actual = await original();
  return { ...actual, withBackupAssetPublication: (...args) => {
    if (admissionFault.error) return Promise.reject(admissionFault.error);
    return actual.withBackupAssetPublication(...args);
  } };
});

// Each test runs against a synthetic ~/.codex layout so it never touches
// the user's real generated_images dir. We mock os.homedir() directly —
// node's homedir() uses getpwuid() on macOS and ignores $HOME, so just
// setting the env var isn't enough.
const TEST_HOME = join(tmpdir(), `portos-codex-test-${process.pid}-${Date.now()}`);
vi.mock('os', async () => {
  const actual = await vi.importActual('os');
  return { ...actual, homedir: () => TEST_HOME };
});

// Spawn mock — capture every spawn call so tests can assert args, drive
// stdout/stderr lines, and trigger the close event whenever they want.
const spawnCalls = [];
const makeFakeChild = () => {
  const child = new ChildProcess();
  child.unref = vi.fn();
  child.stdout = new EventEmitter();
  child.stderr = new EventEmitter();
  child.kill = vi.fn();
  child.exitCode = null;
  child.signalCode = null;
  return child;
};
// Partial mock — keep execFile/exec real for fileUtils.dirSize and friends,
// only swap spawn so we can assert + drive the codex child.
vi.mock('../../lib/childProcess.js', async (importOriginal) => {
  const actual = await importOriginal();
  return {
    ...actual,
    spawn: vi.fn((bin, args, options) => {
      const child = makeFakeChild();
      spawnCalls.push({ bin, args, options, child });
      return child;
    }),
  };
});

// Exercise the real launch/tree-kill helpers with injectable platform facts.
vi.mock('../../lib/bufferedSpawn.js', async original => {
  const actual = await original();
  return {
    ...actual,
    prepareCliSpawn: (bin, args) => actual.prepareCliSpawn(bin, args, process.env, process.platform === 'win32'),
    killProcessTree: child => actual.killProcessTree(child, 'SIGTERM', {}, process.platform === 'win32'),
  };
});

let restorePlatform;
const setPlatform = value => {
  restorePlatform?.();
  restorePlatform = pinPlatform(value);
};

// Stable PATHS.images under the fake HOME so the harvest's copyFile lands
// in a predictable place we can read back.
const FAKE_IMAGES_DIR = join(TEST_HOME, 'data-images');
vi.mock('../../lib/fileUtils.js', async () => {
  const actual = await vi.importActual('../../lib/fileUtils.js');
  // Mutate the actual PATHS object so functions inside fileUtils.js
  // (e.g. resolveGalleryImage) see the test images dir at call time —
  // a spread-only override would leave the original PATHS.images intact
  // for any function closing over the actual module's binding.
  actual.PATHS.images = FAKE_IMAGES_DIR;
  actual.PATHS.data = join(TEST_HOME, 'data');
  // NOTE: do not invent PATHS keys here. An earlier revision set `PATHS.tmp`,
  // a key the real object has never had, so the suite exercised a property
  // that exists only under test while every production render threw
  // ERR_INVALID_ARG_TYPE on it. The render scratch dir is rooted at the OS
  // temp dir and needs no PATHS entry; `pathsKeysAreReal` below pins that.
  return {
    ...actual,
    ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
  };
});

// imageGenEvents is fine to import for real, but we don't want stray
// listeners between tests. Reset its emitter state in beforeEach.
const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
// Read back through the mocked module so this is the same PATHS the service sees.
const { PATHS } = await import('../../lib/fileUtils.js');
const codex = await import('./codex.js');
const { imageGenEvents } = await import('../imageGenEvents.js');
const { spawn } = await import('../../lib/childProcess.js');
const { spawn: realSpawn } = await vi.importActual('../../lib/childProcess.js');
const { SSE_CLEANUP_DELAY_MS } = await import('../../lib/sseUtils.js');

const flush = () => new Promise((r) => setImmediate(r));

beforeEach(async () => {
  setPlatform('linux');
  vi.stubEnv('CODEX_HOME', join(TEST_HOME, '.codex'));
  spawnCalls.length = 0;
  imageGenEvents.removeAllListeners();
  codex._internals.setHarvestTimeoutForTests(10);
  await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
  await mkdir(TEST_HOME, { recursive: true });
});

afterEach(async () => {
  restorePlatform?.();
  vi.unstubAllEnvs();
  vi.useRealTimers();
  codex._internals.setHarvestTimeoutForTests();
  await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
});

describe('codex provider — checkConnection', () => {
  it('uses the same credential boundary for the version probe as rendering', async () => {
    vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');
    vi.stubEnv('CLAUDE_CODE_OAUTH_TOKEN', 'claude');
    vi.stubEnv('FAL_KEY', 'fal');
    vi.stubEnv('OPENAI_API_KEY', 'codex-own');
    const result = codex.checkConnection();
    await flush();
    const call = spawnCalls[0];
    expect(call.options.env).not.toHaveProperty('PRIVACY_VAULT_KEY');
    expect(call.options.env).not.toHaveProperty('CLAUDE_CODE_OAUTH_TOKEN');
    expect(call.options.env).not.toHaveProperty('FAL_KEY');
    expect(call.options.env.OPENAI_API_KEY).toBe('codex-own');
    call.child.emit('close', 0);
    expect((await result).connected).toBe(true);
  });
  it.each([
    ['stdout', 'codex-cli 1.2.3', 'codex-cli 1.2.3'],
    ['stderr', 'Codex version 2.3.4', 'codex-cli 2.3.4'],
    ['stdout', 'unknown version', 'codex-cli'],
  ])('preserves the model label from %s output: %s', async (stream, output, model) => {
    const result = codex.checkConnection({ codexPath: '/opt/example/codex' });
    const { bin, args, options, child } = spawnCalls[0];
    expect(bin).toBe('/opt/example/codex');
    expect(args).toEqual(['--version']);
    expect(options.shell).toBe(false);
    child[stream].emit('data', Buffer.from(output));
    child.emit('close', 0);
    await expect(result).resolves.toEqual({ connected: true, mode: 'codex', model });
  });

  it('preserves spawn-error and nonzero-exit reasons', async () => {
    const missing = codex.checkConnection();
    spawnCalls[0].child.emit('error', new Error('spawn codex ENOENT'));
    await expect(missing).resolves.toEqual({
      connected: false, mode: 'codex', reason: 'Codex CLI not found (spawn codex ENOENT)',
    });
    const failed = codex.checkConnection();
    spawnCalls[1].child.emit('close', 2);
    await expect(failed).resolves.toEqual({
      connected: false, mode: 'codex', reason: 'codex --version exited 2',
    });
  });

  it('settles a stalled version probe at 15 seconds and requests termination', async () => {
    vi.useFakeTimers();
    const result = codex.checkConnection();
    const settled = vi.fn();
    result.then(settled);
    expect(spawnCalls).toHaveLength(1);
    expect(spawnCalls[0].args).toEqual(['--version']);
    await vi.advanceTimersByTimeAsync(14_999);
    expect(settled).not.toHaveBeenCalled();
    await vi.advanceTimersByTimeAsync(1);
    await expect(result).resolves.toEqual({
      connected: false, mode: 'codex', reason: 'codex --version timed out',
    });
    expect(spawnCalls[0].child.kill).toHaveBeenCalled();
    vi.clearAllTimers();
  });
});

describe('codex provider — generateImage', () => {
  it('spawns codex exec with $imagegen prompt prefix and the configured model', async () => {
    const p = codex.generateImage({ prompt: 'a small fox', model: 'gpt-5.4' });
    // generateImage resolves immediately (fire-and-forget run); resolved
    // value is the job descriptor.
    const job = await p;
    expect(job.mode).toBe('codex');
    expect(job.filename).toMatch(/^[0-9a-f-]{36}\.png$/);
    expect(spawnCalls.length).toBe(1);
    const { bin, args } = spawnCalls[0];
    expect(bin).toBe('codex');
    expect(args[0]).toBe('exec');
    expect(args).toContain('--skip-git-repo-check');
    expect(args).toContain('--sandbox');
    expect(args).toContain('workspace-write');
    // Codex's startup update check is disabled so image-gen never stalls on it.
    expect(args).toEqual(expect.arrayContaining(['-c', 'check_for_update_on_startup=false']));
    expect(args).toContain('-m');
    expect(args).toContain('gpt-5.4');
    // The prompt must be prefixed with `$imagegen ` so codex's bundled
    // imagegen skill triggers the built-in image_gen tool.
    const promptArg = args[args.length - 1];
    expect(promptArg.startsWith('$imagegen ')).toBe(true);
    expect(promptArg).toContain('a small fox');

    // Cleanup: end the spawned child so the tracking state resets.
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('appends a "(high quality)" hint when width or height ≥ 1536', async () => {
    await codex.generateImage({ prompt: 'a fox', width: 1536, height: 1024 });
    const promptArg = spawnCalls[0].args[spawnCalls[0].args.length - 1];
    expect(promptArg).toContain('(3:2 landscape frame, 1536x1024)');
    expect(promptArg).toContain('(high quality)');
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('does not append "(high quality)" for sub-1536 dimensions', async () => {
    await codex.generateImage({ prompt: 'a fox', width: 1024, height: 1024 });
    const promptArg = spawnCalls[0].args[spawnCalls[0].args.length - 1];
    expect(promptArg).toContain('(1:1 square frame, 1024x1024)');
    expect(promptArg).not.toContain('high quality');
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('honors codexPath override (custom binary)', async () => {
    await codex.generateImage({ prompt: 'a fox', codexPath: '/opt/custom/codex' });
    expect(spawnCalls[0].bin).toBe('/opt/custom/codex');
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('defaults to the cheap gpt-6-luna model at low effort when none is configured', async () => {
    const job = await codex.generateImage({ prompt: 'a small fox' });
    // The resolved default surfaces on the job descriptor so the gallery/UI reflects it.
    expect(job.model).toBe('gpt-6-luna');
    const { args } = spawnCalls[0];
    // Model default → `-m gpt-6-luna`.
    const mIdx = args.indexOf('-m');
    expect(mIdx).toBeGreaterThan(-1);
    expect(args[mIdx + 1]).toBe('gpt-6-luna');
    // Effort default → `-c model_reasoning_effort=low`.
    expect(args).toEqual(expect.arrayContaining(['-c', 'model_reasoning_effort=low']));
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('honors an explicit model and effort override', async () => {
    const job = await codex.generateImage({ prompt: 'a fox', model: 'gpt-5.6-terra', effort: 'high' });
    expect(job.model).toBe('gpt-5.6-terra');
    const { args } = spawnCalls[0];
    const mIdx = args.indexOf('-m');
    expect(args[mIdx + 1]).toBe('gpt-5.6-terra');
    expect(args).toEqual(expect.arrayContaining(['-c', 'model_reasoning_effort=high']));
    // The shipped defaults must NOT leak in when an override is set.
    expect(args).not.toContain('gpt-6-luna');
    expect(args).not.toEqual(expect.arrayContaining(['model_reasoning_effort=low']));
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('falls back to low when a stored effort value is unrecognized', async () => {
    // A hand-edited settings.json / the unvalidated settings PUT could carry a
    // garbage effort; it must not silently disable the cheap-default guarantee.
    await codex.generateImage({ prompt: 'a fox', effort: 'banana' });
    const { args } = spawnCalls[0];
    expect(args).toEqual(expect.arrayContaining(['-c', 'model_reasoning_effort=low']));
    expect(args).not.toContain('model_reasoning_effort=banana');
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('places the effort arg before the variadic -i so it is not swallowed as an image path', async () => {
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    await writeFile(join(FAKE_IMAGES_DIR, 'ref.png'), 'fake');
    await codex.generateImage({ prompt: 'edit', initImagePath: 'ref.png', initImageStrength: 0.2 });
    const { args } = spawnCalls[0];
    const effortValIdx = args.indexOf('model_reasoning_effort=low');
    const iIdx = args.indexOf('-i');
    expect(effortValIdx).toBeGreaterThan(-1);
    expect(iIdx).toBeGreaterThan(-1);
    // Effort config pair sits ahead of the variadic image flag.
    expect(effortValIdx).toBeLessThan(iIdx);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('attaches every reference image on the one variadic -i flag', async () => {
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    for (const n of ['proof.png', 'ref-a.png', 'ref-b.png']) {
      await writeFile(join(FAKE_IMAGES_DIR, n), 'fake');
    }
    await codex.generateImage({
      prompt: 'cover art', initImagePath: 'proof.png', initImageStrength: 0.2,
      referenceImagePaths: ['ref-a.png', 'ref-b.png'],
    });
    const { args } = spawnCalls[0];
    const i = args.indexOf('-i');
    expect(args.slice(i + 1, i + 4)).toEqual([
      join(FAKE_IMAGES_DIR, 'proof.png'),
      join(FAKE_IMAGES_DIR, 'ref-a.png'),
      join(FAKE_IMAGES_DIR, 'ref-b.png'),
    ]);
    // The `--` terminator still bounds the variadic so the prompt lands as the
    // positional rather than being swallowed as a fourth image path.
    expect(args).toContain('--');
    expect(args[args.length - 1]).toMatch(/edit the FIRST attached image/i);
    expect(args[args.length - 1]).toMatch(/other 2 attached images as visual references/i);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('describes a reference-only render as conditioning, not an edit', async () => {
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    await writeFile(join(FAKE_IMAGES_DIR, 'ref-a.png'), 'fake');
    await codex.generateImage({ prompt: 'a fox', referenceImagePaths: ['ref-a.png'] });
    const { args } = spawnCalls[0];
    expect(args.slice(args.indexOf('-i') + 1, args.indexOf('-i') + 2))
      .toEqual([join(FAKE_IMAGES_DIR, 'ref-a.png')]);
    expect(args[args.length - 1]).toMatch(/conditioned on the attached image/i);
    expect(args[args.length - 1]).not.toMatch(/^\$imagegen Edit /);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('rejects when prompt is empty and there is no init image', async () => {
    await expect(codex.generateImage({ prompt: '   ' })).rejects.toThrow(/Prompt is required/);
  });

  it('allows an empty prompt when editing an init image', async () => {
    // resolveGalleryImage requires the file to exist under PATHS.images.
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    await writeFile(join(FAKE_IMAGES_DIR, 'editme.png'), 'fake');
    await codex.generateImage({ prompt: '', initImagePath: 'editme.png', initImageStrength: 0.2 });
    const { args } = spawnCalls[0];
    expect(args.indexOf('-i')).toBeGreaterThan(-1);
    // Edit-prefix still drives the render even with no text target.
    expect(args[args.length - 1]).toMatch(/edit the attached reference image/i);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('forwards initImagePath via `-i <FILE>` and reshapes the prompt for image-edit', async () => {
    // resolveGalleryImage requires the file to exist under PATHS.images.
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    await writeFile(join(FAKE_IMAGES_DIR, 'proof.png'), 'fake');
    await codex.generateImage({
      prompt: 'cover art',
      width: 1024, height: 1536,
      initImagePath: 'proof.png',
      initImageStrength: 0.2,
    });
    const { args } = spawnCalls[0];
    const iIdx = args.indexOf('-i');
    expect(iIdx).toBeGreaterThan(-1);
    expect(args[iIdx + 1]).toBe(join(FAKE_IMAGES_DIR, 'proof.png'));
    // `-i` is VARIADIC in codex exec — without a `--` terminator it swallows the
    // prompt as a second image file ("No prompt provided"). Assert `--` follows
    // the options and the prompt is the positional AFTER it.
    const dashIdx = args.indexOf('--');
    expect(dashIdx).toBeGreaterThan(iIdx);
    expect(dashIdx).toBe(args.length - 2);
    const promptArg = args[args.length - 1];
    // The `$imagegen` prefix is preserved so the bundled skill still triggers.
    expect(promptArg.startsWith('$imagegen ')).toBe(true);
    // Edit-prefix tells codex to use the attachment rather than redraw.
    expect(promptArg).toMatch(/edit the attached reference image/i);
    // Low strength → composition-preserving fidelity phrase.
    expect(promptArg).toMatch(/preserve composition/i);
    expect(promptArg).toContain('cover art');
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('drops initImagePath that escapes the gallery (defense-in-depth)', async () => {
    await codex.generateImage({
      prompt: 'cover art',
      // Absolute outside-gallery path — resolveGalleryImage rejects via basename.
      initImagePath: '/etc/passwd',
      initImageStrength: 0.2,
    });
    const { args } = spawnCalls[0];
    expect(args).not.toContain('-i');
    // No init image → no variadic to terminate, so no `--` is added.
    expect(args).not.toContain('--');
    const promptArg = args[args.length - 1];
    // No edit prefix when the init image is dropped.
    expect(promptArg).not.toMatch(/edit the attached reference image/i);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('omits `-i` and the edit-prefix when no initImagePath is passed', async () => {
    await codex.generateImage({ prompt: 'cover art', width: 1024, height: 1024 });
    const { args } = spawnCalls[0];
    expect(args).not.toContain('-i');
    const promptArg = args[args.length - 1];
    expect(promptArg).not.toMatch(/edit the attached reference image/i);
    spawnCalls[0].child.exitCode = 1;
    spawnCalls[0].child.emit('close', 1, null);
    await flush();
  });

  it('allows concurrent generations (parallel codex lane)', async () => {
    const a = await codex.generateImage({ prompt: 'one' });
    const b = await codex.generateImage({ prompt: 'two' });
    expect(a.jobId).not.toBe(b.jobId);
    expect(spawnCalls.length).toBe(2);
    for (const c of spawnCalls) {
      c.child.exitCode = 1;
      c.child.emit('close', 1, null);
    }
    await flush();
  });
});

describe('codex provider — image harvest', () => {
  it('copies the latest PNG from ~/.codex/generated_images/<session-id>/ into PATHS.images', async () => {
    const sessionId = '019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    const fakePngBytes = Buffer.from('fakepngbytes');
    await writeFile(join(codexDir, 'ig_first.png'), fakePngBytes);

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);

    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    await writeFile(join(FAKE_IMAGES_DIR, 'source.png'), fakePngBytes);
    await writeFile(join(FAKE_IMAGES_DIR, 'reference.png'), fakePngBytes);
    const job = await codex.generateImage({ prompt: 'a fox', initImagePath: 'source.png', referenceImagePaths: ['reference.png', 'missing.png'] });
    const child = spawnCalls[0].child;

    // Drive the session id banner on stderr (codex prints it there).
    child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\ntokens used\n1,234\n`));
    // Then close cleanly.
    child.exitCode = 0;
    const releaseCut = await acquireBackupSnapshotCut();
    try {
    child.emit('close', 0, null);
      await new Promise(resolve => setImmediate(resolve));
      expect(existsSync(join(FAKE_IMAGES_DIR, job.filename)), 'provider completion must wait outside a held snapshot').toBe(false);
    } finally { releaseCut(); }

    // Poll until the completed event fires (the harvest is async).
    const deadline = Date.now() + 3000;
    while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
      await new Promise((r) => setTimeout(r, 50));
    }

    expect(completedListener).toHaveBeenCalledTimes(1);
    await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
    const finalPath = join(FAKE_IMAGES_DIR, job.filename);
    expect(existsSync(finalPath)).toBe(true);
    const written = await readFile(finalPath);
    expect(Buffer.compare(written, fakePngBytes)).toBe(0);

    const { getImageRenderUsage } = await import('../imageRenderUsage.js');
    expect(await getImageRenderUsage()).toMatchObject({ renderGroups: 1, savedOutputs: 1, imageCostUsd: null, driverTokens: { reportedTotal: 1234, sessionsMeasured: 1 } });

    // Sidecar metadata exists too.
    const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
    expect(existsSync(sidecar)).toBe(true);
    expect(JSON.parse(await readFile(sidecar, 'utf8'))).toMatchObject({
      inputProvenance: 'provider-inputs',
      initImageFilename: 'source.png', referenceImageFilenames: ['reference.png'],
    });
  });

  it('preserves the completed image and sidecar when receipt persistence fails', async () => {
    const sessionId = '44444444-4444-4444-8444-444444444444';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    await writeFile(join(codexDir, 'exec-output.png'), Buffer.from('fakepngbytes'));
    await mkdir(PATHS.data, { recursive: true });
    await writeFile(join(PATHS.data, 'image-render-usage'), 'blocked-directory');
    const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
    try {
      const completed = vi.fn();
      imageGenEvents.on('completed', completed);
      const job = await codex.generateImage({ prompt: 'a fox' });
      const child = spawnCalls[0].child;
      child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
      child.exitCode = 0;
      child.emit('close', 0, null);
      await vi.waitFor(() => expect(completed).toHaveBeenCalledTimes(1));
      expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(true);
      expect(JSON.parse(await readFile(join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`), 'utf8'))).toMatchObject({ codexSessionId: sessionId });
      expect(logged).toHaveBeenCalledWith(expect.stringContaining('Failed to record Codex image usage'));
    } finally { logged.mockRestore(); }
  });

  it('crops an off-aspect frame to the requested ratio and records it in the sidecar', async () => {
    const sessionId = '019dd59e-a8da-7bd2-a7d8-4ac6f46e7b99';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    // Codex answered a 16:9 request with a square close-up.
    const square = await sharp({ create: { width: 640, height: 640, channels: 3, background: { r: 200, g: 120, b: 40 } } })
      .composite([{ input: { create: { width: 200, height: 200, channels: 3, background: { r: 20, g: 40, b: 220 } } }, top: 100, left: 220 }])
      .png().toBuffer();
    await writeFile(join(codexDir, 'ig_square.png'), square);

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);
    const job = await codex.generateImage({ prompt: 'a singer close-up', width: 1600, height: 900 });
    const child = spawnCalls[0].child;
    child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
    child.exitCode = 0;
    child.emit('close', 0, null);
    const deadline = Date.now() + 3000;
    while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
      await new Promise((r) => setTimeout(r, 50));
    }
    imageGenEvents.off('completed', completedListener);

    expect(completedListener).toHaveBeenCalledTimes(1);
    const { width, height } = await sharp(join(FAKE_IMAGES_DIR, job.filename)).metadata();
    expect({ width, height }).toEqual({ width: 640, height: 360 });
    const sidecar = JSON.parse(await readFile(join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`), 'utf8'));
    expect(sidecar.aspectConformed).toEqual({ from: '640x640', to: '640x360' });
  });

  it('harvests the exec-named PNG emitted by newer Codex image tools', async () => {
    const sessionId = '33333333-3333-4333-8333-333333333333';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    const fakePngBytes = Buffer.from('new-codex-png');
    await writeFile(join(codexDir, 'exec-example-output.png'), fakePngBytes);

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);

    const job = await codex.generateImage({ prompt: 'an example landscape' });
    const child = spawnCalls[0].child;
    child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
    child.stdout.emit('data', Buffer.from('[Generated image](sandbox:/example/generated_images/session/exec-example-output.png)'));
    child.exitCode = 0;
    child.emit('close', 0, null);

    await vi.waitFor(() => expect(completedListener).toHaveBeenCalledTimes(1));
    expect(await readFile(join(FAKE_IMAGES_DIR, job.filename))).toEqual(fakePngBytes);
  });

  it('decodes image bytes from the Codex session JSONL when no generated_images file exists', async () => {
    const sessionId = '22222222-2222-4222-8222-222222222222';
    const sessionsDir = join(TEST_HOME, '.codex', 'sessions', '2026', '06', '22');
    await mkdir(sessionsDir, { recursive: true });
    const fakePngBytes = Buffer.from([
      0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
      0x00, 0x00, 0x00, 0x0d,
    ]);
    await writeFile(
      join(sessionsDir, `rollout-2026-06-22T00-19-45-${sessionId}.jsonl`),
      `${JSON.stringify({
        timestamp: '2026-06-22T00:22:57.040Z',
        type: 'event_msg',
        payload: {
          type: 'image_generation_end',
          call_id: 'ig_test',
          status: 'generating',
          result: fakePngBytes.toString('base64'),
        },
      })}\n`,
    );

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);

    const job = await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;
    child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
    child.exitCode = 0;
    child.emit('close', 0, null);

    const deadline = Date.now() + 3000;
    while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
      await new Promise((r) => setTimeout(r, 50));
    }

    expect(completedListener).toHaveBeenCalledTimes(1);
    const finalPath = join(FAKE_IMAGES_DIR, job.filename);
    expect(existsSync(finalPath)).toBe(true);
    const written = await readFile(finalPath);
    expect(Buffer.compare(written, fakePngBytes)).toBe(0);
  });

  it('emits a failed event when codex exits 0 but writes no image (likely auth/quota issue)', async () => {
    const sessionId = '00000000-0000-4000-8000-000000000000';
    // Create the session dir so the harvest path exists, but leave it
    // empty — that's the failure mode we surface to users.
    await mkdir(join(TEST_HOME, '.codex', 'generated_images', sessionId), { recursive: true });

    const failedListener = vi.fn();
    imageGenEvents.on('failed', failedListener);

    await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;
    child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
    child.exitCode = 0;
    child.emit('close', 0, null);

    await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1));
    expect(failedListener.mock.calls[0][0].error).toMatch(/no generated image/i);
  });

  it('captures the session id even when banner + long prompt echo arrive in a single >4KB stderr chunk', async () => {
    // Regression: with multi-KB comic-pipeline prompts, codex flushes the
    // entire banner *and* the echoed prompt in one stderr write. The old
    // captureSession() sliced the buffer to its tail before running the
    // regex, chopping the `session id:` line off the front and producing
    // a spurious "Codex returned no session id" failure even though the
    // banner was emitted correctly.
    const sessionId = '019e2513-c506-7de1-815e-c1f589229242';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    await writeFile(join(codexDir, 'ig_x.png'), Buffer.from('png'));

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);

    await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;

    const longPromptEcho = 'panel description '.repeat(400); // ~7KB
    const banner =
      'Reading additional input from stdin...\n' +
      'OpenAI Codex v0.130.0\n' +
      '--------\n' +
      'workdir: /tmp\n' +
      'model: gpt-5.5\n' +
      'provider: openai\n' +
      'approval: never\n' +
      'sandbox: workspace-write\n' +
      'reasoning effort: high\n' +
      'reasoning summaries: none\n' +
      `session id: ${sessionId}\n` +
      '--------\n' +
      'user\n' +
      `$imagegen ${longPromptEcho}\n`;
    expect(banner.length).toBeGreaterThan(4 * 1024);
    child.stderr.emit('data', Buffer.from(banner));
    child.exitCode = 0;
    child.emit('close', 0, null);

    const deadline = Date.now() + 3000;
    while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
      await new Promise((r) => setTimeout(r, 50));
    }
    expect(completedListener).toHaveBeenCalledTimes(1);
  });

  it('captures the session id when a stdout chunk interleaves the stderr banner', async () => {
    // Regression: the old code fed both stdout and stderr into the same
    // bannerBuf. A stdout chunk arriving between two stderr chunks of the
    // banner would split the `session id:` line with unrelated text and
    // break the regex match.
    const sessionId = '019e2513-aaaa-7bcd-bb00-c1f589229242';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    await writeFile(join(codexDir, 'ig_y.png'), Buffer.from('png'));

    const completedListener = vi.fn();
    imageGenEvents.on('completed', completedListener);

    await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;

    child.stderr.emit('data', Buffer.from('session id: 019e2513-aaaa-7bcd-'));
    child.stdout.emit('data', Buffer.from('progress noise\n'));
    child.stderr.emit('data', Buffer.from('bb00-c1f589229242\n'));
    child.exitCode = 0;
    child.emit('close', 0, null);

    const deadline = Date.now() + 3000;
    while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
      await new Promise((r) => setTimeout(r, 50));
    }
    expect(completedListener).toHaveBeenCalledTimes(1);
  });

  it('emits a failed event when no session id banner is parsed', async () => {
    const failedListener = vi.fn();
    imageGenEvents.on('failed', failedListener);

    await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;
    // Stdout/stderr deliberately empty — nothing to match SESSION_ID_RE.
    child.exitCode = 0;
    child.emit('close', 0, null);
    await flush();
    await new Promise((r) => setTimeout(r, 50));
    expect(failedListener).toHaveBeenCalledTimes(1);
    expect(failedListener.mock.calls[0][0].error).toMatch(/no session id/i);
  });

  it('recovers from a spawn error so subsequent generations can run', async () => {
    // Simulate ENOENT (codex binary not found) by emitting 'error' on the
    // child. Without the activeProcess-clear fix, the next generateImage
    // call would forever throw 409 IMAGE_GEN_BUSY because activeProcess
    // would still be set to the dead child.
    const failedListener = vi.fn();
    imageGenEvents.on('failed', failedListener);

    await codex.generateImage({ prompt: 'first', codexPath: '/nonexistent/codex' });
    const child = spawnCalls[0].child;
    child.emit('error', Object.assign(new Error('spawn /nonexistent/codex ENOENT'), { code: 'ENOENT' }));
    // The 'close' event also fires for spawn errors; emit it so the
    // idempotence guard is exercised.
    child.exitCode = 1;
    child.emit('close', 1, null);
    await flush();
    await new Promise((r) => setTimeout(r, 50));

    expect(failedListener).toHaveBeenCalled();
    // Critical: activeProcess must be cleared so a follow-up call works.
    const second = await codex.generateImage({ prompt: 'second' });
    expect(second.mode).toBe('codex');
    expect(spawnCalls.length).toBe(2);
    spawnCalls[1].child.exitCode = 1;
    spawnCalls[1].child.emit('close', 1, null);
    await flush();
  });

  // Simulate copyFile throwing — happens in the wild when data/images is
  // read-only, the disk is full, or the harvested PNG is unreadable.
  // Without the try/catch in the close handler, the async EventEmitter
  // listener would surface an unhandled rejection and leave the job stuck
  // in 'running'.
  // Skip on Windows: POSIX read-only chmod doesn't reliably block writes
  // there, and ESM `vi.spyOn(fs/promises, 'copyFile')` errors with
  // "Cannot redefine property: copyFile" because module namespaces aren't
  // configurable in ESM. macOS/Linux are the platforms PortOS actually
  // runs on; this regression-locks the fix where it matters.
  // Also skip as root: root ignores the 0o555 mode, so the copy never fails.
  const itPosix = process.platform === 'win32' || process.getuid?.() === 0 ? it.skip : it;
  itPosix('routes async errors in the close handler through finalizeJobFailure (no unhandled rejections)', async () => {
    const sessionId = '11111111-1111-4111-8111-111111111111';
    const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);
    await mkdir(codexDir, { recursive: true });
    await writeFile(join(codexDir, 'ig_a.png'), Buffer.from('x'));
    await mkdir(FAKE_IMAGES_DIR, { recursive: true });

    const { chmod } = await import('fs/promises');
    await chmod(FAKE_IMAGES_DIR, 0o555);

    const failedListener = vi.fn();
    imageGenEvents.on('failed', failedListener);

    let unhandled = null;
    const onUnhandled = (reason) => { unhandled = reason; };
    process.on('unhandledRejection', onUnhandled);

    try {
      await codex.generateImage({ prompt: 'a fox' });
      const child = spawnCalls[0].child;
      child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
      child.exitCode = 0;
      child.emit('close', 0, null);

      const deadline = Date.now() + 4000;
      while (Date.now() < deadline && failedListener.mock.calls.length === 0) {
        await new Promise((r) => setTimeout(r, 50));
      }

      expect(failedListener).toHaveBeenCalledTimes(1);
      expect(failedListener.mock.calls[0][0].error).toMatch(/post-exit handler failed/i);
      expect(unhandled).toBeNull();
    } finally {
      // Restore write perms so afterEach cleanup can rm the tree.
      await chmod(FAKE_IMAGES_DIR, 0o755).catch(() => {});
      process.off('unhandledRejection', onUnhandled);
    }
  }, 8000);

  it('emits a failed event when codex exits non-zero', async () => {
    const failedListener = vi.fn();
    imageGenEvents.on('failed', failedListener);

    await codex.generateImage({ prompt: 'a fox' });
    const child = spawnCalls[0].child;
    child.stderr.emit('data', Buffer.from('boom: out of quota\n'));
    child.exitCode = 1;
    child.emit('close', 1, null);
    await flush();
    await new Promise((r) => setTimeout(r, 50));
    expect(failedListener).toHaveBeenCalledTimes(1);
    expect(failedListener.mock.calls[0][0].error).toMatch(/Exit code 1|generation failed/i);
  });
});

describe('codex provider — internals', () => {
  it('SESSION_ID_RE matches the codex banner format', () => {
    const banner = `OpenAI Codex v0.125.0
workdir: /tmp/x
model: gpt-5.5
session id: 019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07
something else`;
    const m = banner.match(codex._internals.SESSION_ID_RE);
    expect(m).toBeTruthy();
    expect(m[1]).toBe('019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07');
  });

  it('codexImagesDir resolves under the user homedir', () => {
    const dir = codex._internals.codexImagesDir('abc');
    expect(dir.endsWith(join('.codex', 'generated_images', 'abc'))).toBe(true);
  });
});

describe('codex provider — noImageReason (no-image diagnostics)', () => {
  it('reports a success claim without guessing tool availability', () => {
    const msg = codex.noImageReason('codex\nGenerated with the built-in image tool using the imagegen skill.\ntokens used\n11484');
    expect(msg).toMatch(/no generated image file was found/i);
    expect(msg).not.toMatch(/unavailable|rate-limited|didn.t run/i);
    // the model's own words are surfaced…
    expect(msg).toContain('Generated with the built-in image tool');
    // …but codex's structural labels + token count are stripped out
    expect(msg).not.toMatch(/\b11484\b/);
    expect(msg).not.toMatch(/tokens used/i);
  });

  it('surfaces a content-decline message verbatim', () => {
    const msg = codex.noImageReason('codex\nI can’t create that image because it depicts explicit content.\n');
    expect(msg).toMatch(/did not produce an image/i);
    expect(msg).toContain('depicts explicit content');
    expect(msg).not.toMatch(/rate-limited/i);
  });

  it('falls back to session/settings guidance when codex said nothing usable', () => {
    expect(codex.noImageReason('')).toMatch(/Check the Codex session and Settings/i);
    expect(codex.noImageReason('codex\nuser\n----\ntokens used\n42')).toMatch(/Check the Codex session and Settings/i);
  });

  it('strips ANSI escape codes from the surfaced narration', () => {
    const ESC = String.fromCharCode(27);
    const msg = codex.noImageReason(`${ESC}[1mI can’t make that.${ESC}[0m`);
    expect(msg).toContain('I can’t make that.');
    expect(msg).not.toContain(ESC);
    expect(msg).not.toMatch(/\[\d+m/);
  });
});


it('settles admission rejection from the actual close event and clears the active slot', async () => {
  const job = await codex.generateImage({ prompt: 'admission failure' });
  const child = spawnCalls[0].child;
  const failed = new Promise(resolve => imageGenEvents.once('failed', resolve));
  admissionFault.error = new Error('injected publication admission refusal');
  try {
    child.emit('close', 0, null);
    expect((await failed).error).toContain('injected publication admission refusal');
    expect(codex.getActiveJob()).toBeNull();
    const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };
    expect(codex.attachSseClient(job.jobId, response)).toBe(true);
    expect(response.write.mock.calls[0][0]).toContain('injected publication admission refusal');
    await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
    response.req.emit('close');
  } finally { admissionFault.error = null; }
});

// #10749 — a launch that throws must settle through the job's own finalizer,
// not leave a phantom 'running' job, a never-terminating SSE stream and a
// cancel that cannot find a process.
describe('codex provider — launch refusal settlement', () => {
  const sseClient = () => ({ writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() });

  it.each([
    // Node validates argv synchronously and throws before any child exists.
    ['a real Node argument refusal', { codexPath: 'codex\0probe' }, () => spawn.mockImplementationOnce(realSpawn), /without null bytes/],
    ['a synthetic launch refusal', {}, () => spawn.mockImplementationOnce(() => { throw new Error('synthetic launch refusal'); }), /synthetic launch refusal/],
  ])('settles %s exactly once with a replayable terminal frame', async (_label, params, arrange, reason) => {
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
    const failed = vi.fn();
    imageGenEvents.on('failed', failed);
    arrange();
    const job = await codex.generateImage({ prompt: 'synthetic', ...params });

    expect(spawnCalls).toHaveLength(0);
    expect(failed).toHaveBeenCalledTimes(1);
    expect(failed.mock.calls[0][0]).toMatchObject({ mode: 'codex', generationId: job.jobId, error: expect.stringMatching(reason) });
    expect(codex.getActiveJob()).toBeNull();
    expect(codex.cancel(job.jobId)).toBe(false);
    const client = sseClient();
    expect(codex.attachSseClient(job.jobId, client)).toBe(true);
    expect(JSON.parse(client.write.mock.calls[0][0].replace(/^data: /, ''))).toMatchObject({ type: 'error', error: expect.stringMatching(reason) });
    client.req.emit('close');

    vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS);
    expect(codex.attachSseClient(job.jobId, sseClient())).toBe(false);
  });

  it('terminates a live child whose setup fails and settles once, only after it physically closes', async () => {
    spawn.mockImplementationOnce((bin, args, options) => {
      const child = makeFakeChild();
      child.stdout.on = () => { throw new Error('synthetic stream setup failure'); };
      spawnCalls.push({ bin, args, options, child });
      return child;
    });
    const failed = vi.fn();
    imageGenEvents.on('failed', failed);
    const job = await codex.generateImage({ prompt: 'synthetic' });
    const { child } = spawnCalls[0];
    child.pid = 4242;

    expect(child.kill).toHaveBeenCalledWith('SIGTERM');
    expect(existsSync(spawnCalls[0].options.cwd)).toBe(true);
    expect(failed).not.toHaveBeenCalled();
    expect(codex.getActiveJob()).toMatchObject({ generationId: job.jobId });

    // A live-child error is not exit; the close that follows settles exactly once.
    child.emit('error', new Error('signal delivery failed'));
    await flush();
    expect(failed).not.toHaveBeenCalled();
    child.exitCode = 0;
    child.emit('close', 0, null);
    child.emit('close', 0, null);
    await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));
    await flush();
    expect(failed).toHaveBeenCalledTimes(1);
    expect(failed.mock.calls[0][0].error).toMatch(/launch setup failed: synthetic stream setup failure/);
    await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
    expect(codex.getActiveJob()).toBeNull();
    expect(codex.cancel(job.jobId)).toBe(false);
  });
});

describe('codex provider — Windows shim lifecycle', () => {
  // An npm cmd-shim, so a launch whose argv cmd.exe cannot carry (the image
  // prompt always spans lines) bypasses cmd.exe for the shim's node target.
  const writeCodexShim = async () => {
    const cliDir = join(TEST_HOME, 'CLI shims');
    const script = join(cliDir, 'node_modules', '@openai', 'codex', 'bin', 'codex.js');
    await mkdir(join(cliDir, 'node_modules', '@openai', 'codex', 'bin'), { recursive: true });
    await writeFile(script, '');
    await writeFile(join(cliDir, 'node.exe'), '');
    const shim = join(cliDir, 'codex.cmd');
    await writeFile(shim, '@ECHO off\r\n"%dp0%\\node.exe"  "%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n');
    return { cliDir, shim, script, node: join(cliDir, 'node.exe') };
  };

  it.each(['bare', 'explicit'])('prepares the %s shim for both probes and image launches without losing arguments', async kind => {
    setPlatform('win32');
    const { cliDir, shim, script, node } = await writeCodexShim();
    vi.stubEnv('PATH', cliDir);
    const codexPath = kind === 'explicit' ? shim : undefined;

    const probe = codex.checkConnection({ codexPath });
    const probeCall = spawnCalls[0];
    expect(probeCall).toMatchObject({ bin: 'cmd.exe', args: ['/c', shim, '--version'], options: { shell: false } });
    probeCall.child.stdout.emit('data', Buffer.from('codex-cli 1.2.3'));
    probeCall.child.emit('close', 0);
    await expect(probe).resolves.toMatchObject({ connected: true });

    await mkdir(FAKE_IMAGES_DIR, { recursive: true });
    const image = join(FAKE_IMAGES_DIR, 'reference & sketch.png');
    await writeFile(image, 'synthetic image');
    const job = await codex.generateImage({
      codexPath, model: 'gpt-6.1-sol&example', effort: 'high',
      prompt: 'a fox & tree | sky > clouds', initImagePath: image,
    });
    const call = spawnCalls[1];
    expect(call.bin).toBe(node);
    expect(call.options.shell).toBe(false);
    expect(call.args.slice(0, 2)).toEqual([script, 'exec']);
    expect(call.args).toEqual(expect.arrayContaining([
      'model_reasoning_effort=high', '-i', image, '-m', 'gpt-6.1-sol&example', '--',
    ]));
    expect(call.args.at(-1)).toContain('a fox & tree | sky > clouds');
    expect(call.args.at(-1)).toMatch(/^\$imagegen /);
    call.child.exitCode = 1;
    call.child.emit('close', 1);
    await flush();
    expect(codex.cancel(job.jobId)).toBe(false);
  });

  it.each(['win32', 'linux'])('terminates only the selected %s job, then cancel-all terminates the remaining job', async platform => {
    setPlatform(platform);
    const { shim } = await writeCodexShim();
    const first = await codex.generateImage({ prompt: 'first', codexPath: shim });
    const second = await codex.generateImage({ prompt: 'second', codexPath: shim });
    const firstChild = spawnCalls[0].child;
    const secondChild = spawnCalls[1].child;
    firstChild.pid = 4242;
    secondChild.pid = 4243;

    expect(codex.cancel(first.jobId)).toBe(true);
    if (platform === 'win32') {
      expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4242'] });
      expect(firstChild.kill).not.toHaveBeenCalled();
    } else {
      expect(firstChild.kill).toHaveBeenCalledWith('SIGTERM');
    }
    expect(secondChild.killed).toBe(false);
    firstChild.exitCode = 1;
    firstChild.emit('close', 1);
    await flush();
    expect(codex.getActiveJob()).toMatchObject({ generationId: second.jobId });
    expect(codex.cancelAll()).toBe(true);
    if (platform === 'win32') {
      expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4243'] });
      expect(secondChild.kill).not.toHaveBeenCalled();
    } else {
      expect(secondChild.kill).toHaveBeenCalledWith('SIGTERM');
    }
    secondChild.exitCode = 1;
    secondChild.emit('close', 1);
    await flush();
    expect(codex.cancelAll()).toBe(false);
  });

  it.each(['win32', 'linux'])('uses the same platform termination path for the %s wall-clock limit', async platform => {
    setPlatform(platform);
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
    const { shim } = await writeCodexShim();
    const job = await codex.generateImage({ prompt: 'stalled synthetic render', codexPath: shim });
    const child = spawnCalls[0].child;
    child.pid = 4242;
    await vi.advanceTimersByTimeAsync(20 * 60 * 1000);
    if (platform === 'win32') {
      expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4242'] });
      await vi.advanceTimersByTimeAsync(5000);
      expect(child.kill).not.toHaveBeenCalled();
      expect(spawnCalls.filter(call => call.bin === 'taskkill')).toHaveLength(1);
    } else {
      expect(spawnCalls[0].bin).toBe(shim);
      expect(child.kill).toHaveBeenCalledWith('SIGTERM');
      await vi.advanceTimersByTimeAsync(4999);
      expect(child.kill).toHaveBeenCalledTimes(1);
      await vi.advanceTimersByTimeAsync(1);
      expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
    }
    child.exitCode = 1;
    child.emit('close', 1);
    await flush();
    expect(codex.cancel(job.jobId)).toBe(false);
    vi.clearAllTimers();
  });
});

describe('Codex cached defaults and isolated workspace', () => {
  const cacheModels = async slugs => {
    await mkdir(join(TEST_HOME, '.codex'), { recursive: true });
    await writeFile(join(TEST_HOME, '.codex', 'models_cache.json'), JSON.stringify({
      models: slugs.map(slug => ({ slug, visibility: 'list' })),
    }));
  };
  const finish = async call => {
    call.child.exitCode = 1;
    call.child.emit('close', 1, null);
    await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
  };

  it.each([
    [['gpt-6-luna', 'gpt-5.6-luna'], {}, 'gpt-6-luna'],
    [['gpt-5.6-terra', 'gpt-5.6-luna'], {}, 'gpt-5.6-luna'],
    [['gpt-5.6-terra'], { model: 'gpt-6-luna', modelIsShippedDefault: true }, 'gpt-5.6-terra'],
    [['gpt-5.6-luna'], { model: 'gpt-6-luna' }, 'gpt-6-luna'],
    [['gpt-5.6-luna'], { model: 'custom-explicit' }, 'custom-explicit'],
  ])('uses cached defaults without replacing explicit selection (%j, %j)', async (models, options, expected) => {
    await cacheModels(models);
    const job = await codex.generateImage({ prompt: 'synthetic', ...options });
    const call = spawnCalls[0];
    expect(job.model).toBe(expected);
    expect(call.args[call.args.indexOf('-m') + 1]).toBe(expected);
    await finish(call);
  });

  it('rejects a known-absent default without silently buying a more expensive tier', async () => {
    await cacheModels(['gpt-6.1-sol']);
    await expect(codex.generateImage({ prompt: 'synthetic' })).rejects.toThrow(/Select an available model explicitly/);
    expect(spawnCalls).toHaveLength(0);
  });

  it.each(['{broken', '{"models":[]}', '{"other":true}'])('treats an unusable cache as unknown: %s', async content => {
    await mkdir(join(TEST_HOME, '.codex'), { recursive: true });
    await writeFile(join(TEST_HOME, '.codex', 'models_cache.json'), content);
    expect((await codex.generateImage({ prompt: 'synthetic' })).model).toBe('gpt-6-luna');
    await finish(spawnCalls[0]);
  });

  it('preserves relative CLI and CODEX_HOME resolution when changing cwd', async () => {
    vi.stubEnv('CODEX_HOME', relative(process.cwd(), join(TEST_HOME, '.codex')));
    await codex.generateImage({ prompt: 'synthetic', codexPath: './bin/codex' });
    const call = spawnCalls[0];
    expect(call.bin).toBe(resolve('./bin/codex'));
    expect(call.options.env.CODEX_HOME).toBe(join(TEST_HOME, '.codex'));
    await finish(call);
  });

  it('withholds server secrets but keeps the Codex provider key', async () => {
    vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');
    vi.stubEnv('PGPASSWORD', 'db');
    vi.stubEnv('ANTHROPIC_API_KEY', 'other-provider');
    vi.stubEnv('OPENAI_API_KEY', 'codex-key');
    await codex.generateImage({ prompt: 'synthetic' });
    const { env } = spawnCalls[0].options;
    expect(env).not.toHaveProperty('PRIVACY_VAULT_KEY');
    expect(env).not.toHaveProperty('PGPASSWORD');
    expect(env).not.toHaveProperty('ANTHROPIC_API_KEY');
    expect(env.OPENAI_API_KEY).toBe('codex-key');
    await finish(spawnCalls[0]);
  });

  it('cleans scratch after a spawn error with no physical child', async () => {
    await codex.generateImage({ prompt: 'synthetic' });
    const call = spawnCalls[0];
    call.child.emit('error', new Error('spawn ENOENT'));
    await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
    expect(codex.getActiveJob()).toBeNull();
  });

  it('keeps scratch files until physical exit and never harvests shell drawings', async () => {
    const sessionId = '019e2513-c506-7de1-815e-c1f589229242';
    const sessions = join(TEST_HOME, '.codex', 'sessions');
    await mkdir(sessions, { recursive: true });
    await writeFile(join(sessions, `rollout-${sessionId}.jsonl`), JSON.stringify({
      type: 'response_item', payload: { type: 'function_call', name: 'exec_command', arguments: 'draw a picture' },
    }));
    const failed = vi.fn();
    imageGenEvents.on('failed', failed);
    const job = await codex.generateImage({ prompt: 'synthetic' });
    const call = spawnCalls[0];
    // The property #11734 actually bought: the child's cwd is a fresh per-render
    // directory under the OS temp root, NOT the server's own cwd (the PortOS
    // checkout), so a hand-drawing codex cannot write into the working tree.
    expect(basename(call.options.cwd).startsWith('portos-codex-image-')).toBe(true);
    // realpath both sides: on macOS tmpdir() is /var/... while the resolved
    // path is /private/var/..., so a raw prefix compare is platform-fragile.
    expect(realpathSync(call.options.cwd).startsWith(realpathSync(tmpdir()))).toBe(true);
    expect(call.options.cwd.startsWith(PATHS.installRoot)).toBe(false);
    expect(call.options.env.PWD).toBe(call.options.cwd);
    expect(call.args.at(-1)).toContain('Only the image_gen tool may produce this image');
    await writeFile(join(call.options.cwd, 'drawing.svg'), '<svg/>');
    await writeFile(join(call.options.cwd, 'drawing.png'), 'not a generated image');
    codex.cancel(job.jobId);
    expect(existsSync(call.options.cwd)).toBe(true);
    call.child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
    call.child.exitCode = 0;
    call.child.emit('close', 0, null);
    await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
    expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);
    expect(failed).toHaveBeenCalledTimes(1);
    expect(JSON.stringify(failed.mock.calls)).toContain('No image_gen call was observed');
    expect(JSON.stringify(failed.mock.calls)).toContain('shell activity was recorded');
    expect(JSON.stringify(failed.mock.calls)).toContain('does not establish whether the tool is available');
  });
});

it('cancels during preparation before starting a render', async () => {
  const { imageGenEvents: events } = await import('../imageGenEvents.js');
  const failed = vi.fn();
  const completed = vi.fn();
  events.on('failed', failed);
  events.on('completed', completed);
  const jobId = 'preamble-cancel-imageGen-codex';
  const pending = codex.generateImage({ prompt: 'a quiet gate', jobId });
  expect(codex.cancel(jobId)).toBe('pending');
  await pending;
  await vi.waitFor(() => expect(failed).toHaveBeenCalledWith(expect.objectContaining({ generationId: jobId, error: 'Canceled' })));
  expect(completed).not.toHaveBeenCalled();
  expect(spawnCalls).toHaveLength(0);
  expect(codex.cancel(jobId)).toBe(false);
});