Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

52.9 KB
Raw Blame
import {
  existsSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  writeFileSync
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { FastifyInstance } from 'fastify';
import { afterEach, describe, expect, it } from 'vitest';
import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';
import { buildServer } from '../../src/api/server.js';
import type { AgentRuntimeAdapter } from '../../src/creator/agent/runtime-adapter.js';
import type { CreatorExecutor } from '../../src/creator/executor.js';
import { createGatewayConfigStore } from '../../src/gateway/config-store.js';

let server: FastifyInstance | undefined;
let tempDir = '';
type TestResponse = { statusCode: number; json(): any };

afterEach(async () => {
  await server?.close();
  server = undefined;
  if (tempDir) rmSync(tempDir, {
    recursive: true,
    force: true,
    maxRetries: 30,
    retryDelay: 100
  });
  tempDir = '';
});

describe('creator api', () => {
  it('detects imported source subtitle language and persists it without changing the target', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', { projectId: 'project_detect_srt', templateId: 'video-translation', state: {
      sourceType: 'subtitle', sourceLanguage: 'en', targetLanguage: 'ja'
    } });
    const job = created.json().job;
    const imported = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'import-subtitle', expectedRevision: job.revision, input: {
        kind: 'source_subtitle', language: 'auto', fileName: 'unknown.en.srt',
        contentBase64: Buffer.from('1\n00:00:00,000 --> 00:00:04,000\nयह वीडियो 11Reader के साथ साझेदारी में बनाया गया है, और आगे मैं आपको इनके बारे में और बताऊंगा। एक पूर्णकालिक डॉक्टर के तौर पर, मेरी असली मुश्किलों में से एक है पढ़ने के लिए समय निकालना।\n').toString('base64')
      }
    });
    expect(imported.statusCode).toBe(200);
    const detected = imported.json().job;
    expect(detected.state).toMatchObject({ sourceLanguage: 'hi', targetLanguage: 'ja' });
    expect(detected.artifacts[0].metadata).toMatchObject({ language: 'hi', languageDetection: 'detected' });
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job.state.sourceLanguage).toBe('hi');
    const manual = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'update-settings', expectedRevision: detected.revision, input: { patch: { sourceLanguage: 'mr' } }
    });
    expect(manual.json().job.state).toMatchObject({ sourceLanguage: 'mr', targetLanguage: 'ja' });
  });

  it('keeps an uncertain import unresolved and requires a manual language before running', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', { projectId: 'project_short_srt', templateId: 'video-translation', state: {
      sourceType: 'subtitle', sourceLanguage: 'en'
    } });
    const job = created.json().job;
    const imported = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'import-subtitle', expectedRevision: job.revision, input: {
      kind: 'source_subtitle', language: 'auto', fileName: 'short.srt',
      contentBase64: Buffer.from('1\n00:00:00,000 --> 00:00:01,000\nHello\n').toString('base64')
    } });
    expect(imported.statusCode).toBe(200);
    const unresolved = imported.json().job;
    expect(unresolved.state.sourceLanguage).toBe('auto');
    expect(unresolved.artifacts[0].metadata).toMatchObject({ language: 'auto', languageDetection: 'uncertain' });
    const started = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: unresolved.revision, input: { stageId: 'subtitle' } });
    expect(started.statusCode).toBe(400);
    expect(started.json().error.code).toBe('creator_action_invalid');
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job.stages).toHaveLength(0);
  });

  it('translates a standalone SRT without video and stops after the subtitle stage', async () => {
    const calls: string[] = [];
    await setupServer({ creatorExecutors: [{ id: 'krillinai', async run(stage) {
      calls.push(stage.stageRun.stageId);
      expect(stage.job.state.sourceType).toBe('subtitle');
      expect(stage.inputArtifacts.map(artifact => artifact.kind)).toEqual(['source_subtitle']);
      expect(readFileSync(stage.inputArtifacts[0]!.path!, 'utf8')).toContain('00:00:02,250 --> 00:00:04,750');
      const path = join(stage.workdir, 'translated.srt');
      writeFileSync(path, '1\n00:00:02,250 --> 00:00:04,750\n你好\n');
      return { outputs: [{ kind: 'target_subtitle', status: 'completed', path }] };
    } }] });
    const created = await request('POST', '/creator/jobs', { projectId: 'project_srt', templateId: 'video-translation', state: {
      sourceType: 'subtitle', sourceUrl: '', sourceLanguage: 'en', targetLanguage: 'zh_cn',
      dubbing: true, composeVideo: true, videoFormat: 'all'
    } });
    expect(created.statusCode).toBe(201);
    const job = created.json().job;
    expect(job.state).toMatchObject({ composeVideo: false, dubbing: false });
    const missing = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: job.revision, input: { stageId: 'subtitle', workflow: true } });
    expect(missing.statusCode).toBe(400);
    const imported = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'import-subtitle', expectedRevision: job.revision, input: {
      kind: 'source_subtitle', language: 'en', fileName: 'source.srt',
      contentBase64: Buffer.from('1\n00:00:02,250 --> 00:00:04,750\nHello\n').toString('base64')
    } });
    expect(imported.statusCode).toBe(200);
    const started = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: imported.json().job.revision, input: { stageId: 'subtitle', workflow: true } });
    expect(started.statusCode).toBe(200);
    const completed = await waitForCreatorJob(job.id, job => job.status === 'completed');
    expect(calls).toEqual(['subtitle']);
    expect(completed.artifacts.map((artifact: { kind: string }) => artifact.kind)).toEqual(['source_subtitle', 'target_subtitle']);
    const target = completed.artifacts.find((artifact: { kind: string }) => artifact.kind === 'target_subtitle');
    const download = await request('GET', `/creator/jobs/${job.id}/artifacts/${target.id}/content`);
    expect(download.statusCode).toBe(200);
    const edited = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'edit-subtitle', expectedRevision: completed.revision, input: {
      artifactId: target.id, baseResultVersion: completed.state.resultVersion, preserveResultVersion: true,
      cues: [{ id: 1, start: '00:00:02,250', end: '00:00:04,750', text: '你好世界', sourceText: 'Hello' }]
    } });
    expect(edited.statusCode).toBe(200);
    const editedJob = edited.json().job;
    const editedTarget = editedJob.artifacts.find((artifact: { metadata: { editedFromArtifactId?: string } }) => artifact.metadata.editedFromArtifactId === target.id);
    expect(readFileSync(editedTarget.path, 'utf8')).toContain('00:00:02,250 --> 00:00:04,750\n你好世界');
    expect(editedJob.artifacts.some((artifact: { kind: string }) => artifact.kind === 'bilingual_subtitle')).toBe(true);
    expect(calls).toEqual(['subtitle']);
    for (const stageId of ['tts', 'render-horizontal', 'render-vertical', 'prepare-source-video']) {
      const blocked = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: editedJob.revision, input: { stageId } });
      expect(blocked.statusCode).toBe(400);
    }
  });
  it.each(['source_subtitle', 'target_subtitle'])('imports %s and runs downstream workflow with the persisted input', async kind => {
    const calls: string[] = [];
    await setupServer({ llmConfigured: kind === 'source_subtitle', creatorExecutors: [{
      id: 'krillinai', async run(stage) {
        calls.push(stage.stageRun.stageId);
        const path = join(stage.workdir, 'output.srt');
        writeFileSync(path, '1\n00:00:00,000 --> 00:00:01,000\nHello\n');
        if (stage.stageRun.stageId === 'subtitle') {
          expect(stage.inputArtifacts.some(a => a.kind === kind && a.metadata.source === 'local-upload')).toBe(true);
          return { outputs: ['source_video', 'target_subtitle', 'vertical_subtitle'].map(kind => ({ kind, status: 'completed' as const, path })) };
        }
        return { outputs: [{ kind: stage.stageRun.stageId === 'tts' ? 'dubbed_audio' : stage.stageRun.stageId === 'render-horizontal' ? 'horizontal_video' : 'vertical_video', status: 'completed', path }] };
      }
    }] });
    const created = await request('POST', '/creator/jobs', { projectId: 'project_import', templateId: 'video-translation', state: {
      sourceUrl: 'https://www.youtube.com/watch?v=import', dubbing: true, ttsProvider: 'edge-tts', composeVideo: true, videoFormat: 'all'
    } });
    const job = created.json().job;
    const payload = { action: 'import-subtitle', expectedRevision: 0, input: { kind, language: 'en', fileName: 'captions.srt', contentBase64: Buffer.from('1\n00:00:00,000 --> 00:00:01,000\nHello\n').toString('base64') } };
    const invalid = await request('POST', `/creator/jobs/${job.id}/actions`, {
      ...payload, input: { ...payload.input, contentBase64: Buffer.from([0xff, 0xfe, 0x41, 0x00]).toString('base64') }
    });
    expect(invalid.statusCode).toBe(400);
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job).toMatchObject({ revision: 0, artifacts: [] });
    const imported = await request('POST', `/creator/jobs/${job.id}/actions`, payload);
    expect(imported.statusCode).toBe(200);
    const artifact = imported.json().job.artifacts[0];
    expect(artifact).toMatchObject({ kind, metadata: { source: 'local-upload', language: 'en', cueCount: 1 } });
    expect(existsSync(artifact.path)).toBe(true);
    const started = await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: imported.json().job.revision, input: { stageId: 'subtitle', workflow: true } });
    expect(started.statusCode).toBe(200);
    await waitForCreatorJob(job.id, job => job.artifacts.some((a: { kind: string }) => a.kind === 'vertical_video'));
    expect(calls).toEqual(['subtitle', 'tts', 'render-horizontal', 'render-vertical']);
    const old = await request('GET', `/creator/jobs/${job.id}/artifacts/${artifact.id}/content`);
    expect(old.statusCode).toBe(200);
  });
  it('serves built-in stickman visual asset previews in development', async () => {
    tempDir = mkdtempSync(join(tmpdir(), 'creator-api-'));
    server = await buildServer({
      token: 'secret',
      dataDir: tempDir,
      codexHome: join(tempDir, 'codex-home')
    });

    const catalog = await request(
      'GET',
      '/creator/visual-assets?templateId=stickman-video'
    );
    expect(catalog.statusCode).toBe(200);
    expect(catalog.json().assets).toHaveLength(14);

    const preview = await server.inject({
      method: 'GET',
      url: '/creator/visual-assets/stickman.character.student/revisions/1/preview',
      headers: { authorization: 'Bearer secret' }
    });
    expect(preview.statusCode).toBe(200);
    expect(preview.headers['content-type']).toContain('image/png');
    expect(preview.rawPayload.byteLength).toBeGreaterThan(1_000);
  });

  it('uploads a persistent inline image for a WeChat article', async () => {
    await setupServer({});
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_article_image',
      templateId: 'wechat-article'
    });
    const job = created.json().job;
    const uploaded = await server!.inject({
      method: 'POST',
      url: `/creator/jobs/${job.id}/article-image?expectedRevision=${job.revision}&fileName=photo.png&mime=image%2Fpng&lastModified=123`,
      headers: {
        authorization: 'Bearer secret',
        'content-type': 'application/vnd.opencreator.creator-reference-image'
      },
      payload: png('article-inline-image')
    });

    expect(uploaded.statusCode).toBe(201);
    expect(uploaded.json()).toMatchObject({
      job: { state: { manualArticleImageArtifactIds: [expect.any(String)] } },
      artifact: {
        kind: 'article_image',
        metadata: { originalFileName: 'photo.png', source: 'local-upload' }
      }
    });
  });

  it('deletes an inactive creator job', async () => {
    await setupServer({});
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_delete',
      templateId: 'cover',
      creationKey: 'delete-kept-files',
      state: { prompt: '待删除封面' }
    });
    const job = created.json().job;
    const keptJobRoot = join(tempDir, 'creator', 'jobs', job.id);
    mkdirSync(keptJobRoot, { recursive: true });
    writeFileSync(join(keptJobRoot, 'generated.png'), 'kept');

    const deleted = await request('DELETE', `/creator/jobs/${job.id}`);
    expect(deleted.statusCode).toBe(204);
    expect(existsSync(keptJobRoot)).toBe(true);
    expect((await request('GET', `/creator/jobs/${job.id}`)).statusCode).toBe(404);
    expect((await request('DELETE', `/creator/jobs/${job.id}`)).statusCode).toBe(404);

    const createdWithFiles = await request('POST', '/creator/jobs', {
      projectId: 'project_delete_files',
      templateId: 'cover',
      creationKey: 'delete-with-files',
      state: { prompt: '连同文件删除的封面' }
    });
    const jobWithFiles = createdWithFiles.json().job;
    const deletedJobRoot = join(tempDir, 'creator', 'jobs', jobWithFiles.id);
    mkdirSync(deletedJobRoot, { recursive: true });
    writeFileSync(join(deletedJobRoot, 'generated.png'), 'deleted');

    const deletedWithFiles = await request(
      'DELETE',
      `/creator/jobs/${jobWithFiles.id}?deleteFiles=true`
    );
    expect(deletedWithFiles.statusCode).toBe(204);
    expect(existsSync(deletedJobRoot)).toBe(false);
    expect((await request('GET', `/creator/jobs/${jobWithFiles.id}`)).statusCode).toBe(404);
  });

  it.each(['failed', 'succeeded', 'running'] as const)('stops and resumes translation when its parallel download is %s', async downloadStatus => {
    let subtitleRuns = 0;
    let downloadRuns = 0;
    let releaseResume!: () => void;
    const resumeGate = new Promise<void>(resolve => { releaseResume = resolve; });
    const executor: CreatorExecutor = {
      id: 'krillinai',
      async run({ stageRun, signal }) {
        if (stageRun.stageId === 'subtitle') {
          subtitleRuns += 1;
          if (subtitleRuns === 1) {
            await new Promise<void>(resolve => {
              if (signal.aborted) resolve();
              else signal.addEventListener('abort', () => resolve(), { once: true });
            });
            return { outputs: [] };
          }
          await Promise.race([resumeGate, new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }))]);
          return {
            outputs: [
              { kind: 'source_video', status: 'completed', path: null },
              { kind: 'target_subtitle', status: 'completed', path: null }
            ]
          };
        }
        return {
          outputs: [{
            kind: 'horizontal_video',
            status: 'completed',
            path: null
          }]
        };
      }
    };
    await setupServer({ creatorExecutors: [executor, {
      id: 'download', async run({ signal }) {
        if (downloadStatus === 'failed') throw new Error('Source download unavailable');
        if (downloadStatus === 'running' && ++downloadRuns === 1) {
          await new Promise<void>(resolve => {
            if (signal.aborted) resolve();
            else signal.addEventListener('abort', () => resolve(), { once: true });
          });
        }
        return { outputs: [] };
      }
    }] });
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_job_control',
      templateId: 'video-translation',
      creationKey: 'job-control',
      state: {
        sourceType: 'url',
        sourceUrl: 'https://www.youtube.com/watch?v=job-control',
        targetLanguage: 'zh_cn',
        composeVideo: true,
        videoFormat: 'horizontal'
      }
    });
    const job = created.json().job;
    const started = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'run-stage',
      expectedRevision: job.revision,
      idempotencyKey: 'start-job-control-workflow',
      input: { stageId: 'subtitle', workflow: true }
    });
    expect(started.statusCode).toBe(200);

    const running = await waitForCreatorJob(job.id, candidate => (
      candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'subtitle' && stage.status === 'running')
      && candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'preview-source-video' && stage.status === downloadStatus)
    ));
    const canceledStageId = running.stages.find((stage: { stageId: string }) => stage.stageId === 'subtitle').id;
    const canceled = await request('POST', `/creator/jobs/${job.id}/cancel`);
    expect(canceled.statusCode).toBe(202);
    expect(canceled.json()).toMatchObject({
      control: 'canceling',
      stage: {
        id: canceledStageId,
        progress: { workflow: true, cancelRequested: true }
      }
    });

    const stopped = await waitForCreatorJob(job.id, candidate => (
      candidate.status === 'canceled'
      && candidate.stages.find((stage: { id: string }) => stage.id === canceledStageId)?.status === 'canceled'
      && candidate.stages.every((stage: { status: string }) => !['queued', 'running'].includes(stage.status))
    ));
    expect(stopped.artifacts).toEqual([]);
    const repeatedCancel = await request('POST', `/creator/jobs/${job.id}/cancel`);
    expect(repeatedCancel.statusCode).toBe(200);
    expect(repeatedCancel.json()).toMatchObject({
      control: 'canceled',
      stage: { id: canceledStageId, status: 'canceled' }
    });

    const resumeResponses = await Promise.all([
      request('POST', `/creator/jobs/${job.id}/resume`),
      request('POST', `/creator/jobs/${job.id}/resume`)
    ]);
    expect(resumeResponses.map(response => response.statusCode).sort()).toEqual([200, 202]);
    const resumed = resumeResponses.find(response => response.statusCode === 202)!;
    expect(resumeResponses[0].json().stage.id).toBe(resumeResponses[1].json().stage.id);
    expect(resumed.json()).toMatchObject({
      control: 'resumed',
      stage: {
        stageId: 'subtitle',
        progress: {
          workflow: true,
          resumedFromStageRunId: canceledStageId
        }
      }
    });

    releaseResume();
    const completed = await waitForCreatorJob(job.id, candidate => (
      candidate.status === 'completed'
      && candidate.stages.at(-1)?.stageId === 'render-horizontal'
      && candidate.stages.at(-1)?.status === 'succeeded'
    ));
    expect(completed.stages.filter((stage: { stageId: string }) => stage.stageId !== 'preview-source-video').map((stage: { stageId: string; status: string }) => (
      `${stage.stageId}:${stage.status}`
    ))).toEqual([
      'subtitle:canceled',
      'subtitle:succeeded',
      'render-horizontal:succeeded'
    ]);
    expect(completed.stages.find((stage: { id: string }) => stage.id === resumed.json().stage.id)).toMatchObject({
      progress: {
        workflow: true,
        resumedFromStageRunId: canceledStageId
      }
    });
    expect(subtitleRuns).toBe(2);
    expect((await request('POST', `/creator/jobs/${job.id}/resume`)).statusCode).toBe(409);
  });

  it('resumes only the canceled source download after subtitles have completed', async () => {
    let downloadRuns = 0;
    const translationStages: string[] = [];
    await setupServer({ creatorExecutors: [{ id: 'krillinai', async run({ stageRun }) {
      translationStages.push(stageRun.stageId);
      return { outputs: [{ kind: stageRun.stageId === 'subtitle' ? 'target_subtitle' : 'horizontal_video', status: 'completed', path: null }] };
    } }, { id: 'download', async run({ signal }) {
      if (++downloadRuns === 1) {
        await new Promise<void>(resolve => {
          if (signal.aborted) resolve();
          else signal.addEventListener('abort', () => resolve(), { once: true });
        });
        return { outputs: [] };
      }
      return { outputs: [{ kind: 'source_video', status: 'completed', path: null }] };
    } }] });
    const { job } = (await request('POST', '/creator/jobs', { projectId: 'project_download_resume', templateId: 'video-translation', state: {
      sourceType: 'url', sourceUrl: 'https://youtu.be/download-resume', composeVideo: true, videoFormat: 'horizontal'
    } })).json();
    await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: job.revision,
      idempotencyKey: 'start-download-resume', input: { stageId: 'subtitle', workflow: true } });
    const waiting = await waitForCreatorJob(job.id, candidate => candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'subtitle' && stage.status === 'succeeded')
      && candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'preview-source-video' && stage.status === 'running'));
    const download = waiting.stages.find((stage: { stageId: string }) => stage.stageId === 'preview-source-video');
    expect((await request('POST', `/creator/jobs/${job.id}/cancel`)).statusCode).toBe(202);
    await waitForCreatorJob(job.id, candidate => candidate.stages.find((stage: { id: string }) => stage.id === download.id)?.status === 'canceled');
    const resumed = await request('POST', `/creator/jobs/${job.id}/resume`);
    expect(resumed.statusCode).toBe(202);
    expect(resumed.json().stage).toMatchObject({ stageId: 'preview-source-video', progress: {
      backgroundSourceDownload: true, workflowParentStageRunId: download.progress.workflowParentStageRunId, resumedFromStageRunId: download.id
    } });
    await waitForCreatorJob(job.id, candidate => candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'render-horizontal' && stage.status === 'succeeded'));
    expect(translationStages).toEqual(['subtitle', 'render-horizontal']);
    expect(downloadRuns).toBe(2);
    expect((await request('POST', `/creator/jobs/${job.id}/resume`)).statusCode).toBe(409);
  });

  it('replays creator job creation after the response is lost', async () => {
    await setupServer();
    const requestBody = {
      projectId: 'project_creation_recovery',
      templateId: 'cover',
      creationKey: 'creator-create-recovery-1'
    };

    const first = await request('POST', '/creator/jobs', requestBody);
    const replayed = await request('POST', '/creator/jobs', requestBody);

    expect(first.statusCode).toBe(201);
    expect(replayed.statusCode).toBe(201);
    expect(replayed.json().job.id).toBe(first.json().job.id);
    const listed = await request(
      'GET',
      '/creator/jobs?projectId=project_creation_recovery'
    );
    expect(listed.json().jobs).toHaveLength(1);

    const conflicting = await request('POST', '/creator/jobs', {
      ...requestBody,
      templateId: 'video-translation'
    });
    expect(conflicting.statusCode).toBe(409);
    expect(conflicting.json()).toMatchObject({
      error: { code: 'creator_idempotency_key_reused' }
    });
  });

  it('restores signed-out gateway users to manual services while keeping presets available', async () => {
    await setupServer({ gatewayMode: true, llmConfigured: false });
    const account = await request('GET', '/gateway/account');
    expect(account.json()).toMatchObject({
      source: 'manual', authState: 'signed_out', activationState: 'inactive'
    });
    expect(await createGatewayConfigStore(tempDir).readConfiguration())
      .toMatchObject({ source: 'manual', bindingVersion: null });
    const activation = await request('POST', '/gateway/auth/activate');
    expect(activation.statusCode).toBe(401);
    expect(activation.json()).toMatchObject({
      error: { code: 'GATEWAY_AUTH_REQUIRED', details: { gatewayCode: 'auth_required' } }
    });

    const catalog = await request('GET', '/creator/presets?locale=zh-CN');
    expect(catalog.statusCode).toBe(200);
    const imagePreset = catalog.json().presets.find(
      (preset: { module: string }) => preset.module === 'image-generation'
    );
    expect(imagePreset).toMatchObject({
      title: expect.any(String),
      coverUrl: expect.stringMatching(/^\/creator-presets\/[a-f0-9]{64}\.(?:jpg|png|webp)$/)
    });
    const cover = await server!.inject({
      method: 'GET',
      url: imagePreset.coverUrl,
      headers: { authorization: 'Bearer secret' }
    });
    expect(cover.statusCode).toBe(200);
    expect(cover.headers['content-type']).toMatch(/^image\//);
    expect(cover.rawPayload.byteLength).toBeGreaterThan(1_000);

    const modelConfig = await request('GET', '/creator-services/config');
    expect(modelConfig.statusCode).toBe(200);
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_signed_out',
      preset: { module: imagePreset.module, id: imagePreset.id, version: imagePreset.version },
      locale: 'zh-CN',
      creationKey: 'signed-out-preset-creation'
    });
    expect(created.statusCode).toBe(201);
    expect((await request('GET', '/creator/jobs?projectId=project_signed_out')).json().jobs)
      .toHaveLength(1);
  });

  it('lists localized presets and creates a real preset job', async () => {
    await setupServer();
    const catalog = await request('GET', '/creator/presets?locale=en-US');
    expect(catalog.statusCode).toBe(200);
    expect(catalog.json()).toMatchObject({
      locale: 'en-US',
      catalogHash: expect.stringMatching(/^[a-f0-9]{64}$/)
    });
    const imagePreset = catalog.json().presets.find(
      (preset: { module: string }) => preset.module === 'image-generation'
    );
    expect(imagePreset).toMatchObject({
      module: 'image-generation',
      id: expect.any(String),
      version: expect.any(Number),
      title: expect.any(String),
      coverUrl: expect.stringMatching(/^\/creator-presets\/[a-f0-9]{64}\.(?:jpg|png|webp)$/),
      prompt: expect.any(String),
      tags: expect.any(Array),
      tagIds: expect.any(Array),
      highlights: expect.any(Array)
    });
    expect(imagePreset.tagIds).toHaveLength(imagePreset.tags.length);
    expect(imagePreset.details).toEqual(expect.arrayContaining([
      { label: 'Model', text: 'Codex native image generation', colors: [] }
    ]));
    const fullPreviewPreset = catalog.json().presets.find(
      (preset: { id: string }) => preset.id === 'y2k-streetwear-mobile-landing-page'
    );
    expect(fullPreviewPreset.previewUrl)
      .toMatch(/^\/creator-presets\/[a-f0-9]{64}\.webp$/);
    expect(fullPreviewPreset.previewUrl).not.toBe(fullPreviewPreset.coverUrl);
    expect(fullPreviewPreset.author).toEqual({
      name: '@cezanne_cupcake_haze12',
      url: 'https://higgsfield.ai/publications/0bbfc974-900c-4a1e-8561-3d9ada80177a'
    });
    const avatarPreset = catalog.json().presets.find(
      (preset: { id: string }) => preset.id === 'felt-country-miniature-world'
    );
    expect(avatarPreset.author).toEqual({
      name: '@volkan_iras',
      url: 'https://x.com/volkan_iras/status/2051403524966141980',
      avatarUrl: expect.stringMatching(/^\/creator-presets\/[a-f0-9]{64}\.webp$/)
    });
    const videoPreset = catalog.json().presets.find(
      (preset: { id: string }) => preset.id === 'aerial-pullback-rise-reveal'
    );
    expect(videoPreset.previewVideoUrl)
      .toMatch(/^\/creator-presets\/[a-f0-9]{64}\.mp4$/);
    expect(videoPreset.author).toEqual({
      name: 'Higgsfield.AI Team',
      url: 'https://higgsfield.ai/academy/how-to-use/turn-your-video-into-cinema-using-wan-camera-control'
    });
    const videoRange = await server!.inject({
      method: 'GET',
      url: videoPreset.previewVideoUrl,
      headers: {
        authorization: 'Bearer secret',
        range: 'bytes=0-11'
      }
    });
    expect(videoRange.statusCode).toBe(206);
    expect(videoRange.headers['content-type']).toContain('video/mp4');
    expect(videoRange.headers['content-range']).toMatch(/^bytes 0-11\/\d+$/);
    expect(videoRange.rawPayload).toHaveLength(12);

    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_preset_api',
      preset: {
        module: 'image-generation',
        id: imagePreset.id,
        version: imagePreset.version
      },
      locale: 'en-US',
      creationKey: 'api-preset-creation'
    });
    expect(created.statusCode).toBe(201);
    expect(created.json().job).toMatchObject({
      templateId: 'image-generation',
      templateVersion: 2,
      status: 'draft',
      presetOrigin: {
        module: 'image-generation',
        id: imagePreset.id,
        version: imagePreset.version,
        locale: 'en-US',
        title: imagePreset.title
      },
      state: {
        prompt: imagePreset.prompt,
        provider: 'codex-native'
      },
      stages: []
    });
  });

  it('rejects mixed blank and preset creator job requests without creating jobs', async () => {
    await setupServer();
    const invalidRequests = [{
      projectId: 'project_invalid_preset',
      preset: {
        module: 'image-generation',
        id: 'ecommerce-product',
        version: 1
      },
      locale: 'zh-CN',
      creationKey: 'mixed-state',
      state: {}
    }, {
      projectId: 'project_invalid_preset',
      preset: {
        module: 'image-generation',
        id: 'ecommerce-product',
        version: 1
      },
      locale: 'zh-CN',
      creationKey: 'mixed-template',
      templateId: 'image-generation'
    }, {
      projectId: 'project_invalid_preset',
      templateId: 'image-generation',
      locale: 'en-US',
      creationKey: 'blank-locale'
    }];

    for (const body of invalidRequests) {
      const response = await request('POST', '/creator/jobs', body);
      expect(response.statusCode).toBe(400);
      expect(response.json()).toMatchObject({
        error: { code: 'VALIDATION_FAILED' }
      });
    }

    const listed = await request(
      'GET',
      '/creator/jobs?projectId=project_invalid_preset'
    );
    expect(listed.json().jobs).toEqual([]);
  });

  it('creates, lists, reads and mutates creator jobs', async () => {
    tempDir = mkdtempSync(join(tmpdir(), 'creator-api-'));
    server = await buildServer({
      token: 'secret',
      dataDir: tempDir,
      codexHome: join(tempDir, 'codex-home')
    });

    const templates = await request('GET', '/creator/templates');
    expect(templates.statusCode).toBe(200);
    expect(templates.json().templates).toContainEqual(expect.objectContaining({
      id: 'video-translation',
      version: 1
    }));

    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_1',
      templateId: 'video-translation',
      creationKey: 'creator-api-mutation',
      state: { targetLanguage: 'en' }
    });
    expect(created.statusCode).toBe(201);
    const job = created.json().job;
    expect(job).toMatchObject({ revision: 0, state: { targetLanguage: 'en' } });

    const updated = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'update-settings',
      expectedRevision: 0,
      input: { patch: { targetLanguage: 'ja' } }
    });
    expect(updated.statusCode).toBe(200);
    expect(updated.json().job).toMatchObject({
      revision: 1,
      state: { targetLanguage: 'ja' }
    });

    const conflict = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'update-settings',
      expectedRevision: 0,
      input: { patch: { targetLanguage: 'fr' } }
    });
    expect(conflict.statusCode).toBe(409);
    expect(conflict.json()).toMatchObject({
      error: {
        code: 'creator_revision_conflict',
        details: { latestRevision: 1 }
      }
    });

    const listed = await request('GET', '/creator/jobs?projectId=project_1');
    expect(listed.json().jobs).toHaveLength(1);
    const allJobs = await request('GET', '/creator/jobs');
    expect(allJobs.json().jobs).toContainEqual(expect.objectContaining({ id: job.id }));

    const missingArtifact = await request('GET', `/creator/jobs/${job.id}/artifacts/missing/content`);
    expect(missingArtifact.statusCode).toBe(404);
    expect(missingArtifact.json()).toMatchObject({ error: { code: 'creator_artifact_not_found' } });
  });

  it('rejects unsupported video sources before creating a stage run', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_vt5',
      templateId: 'video-translation',
      creationKey: 'unsupported-video-source',
      state: {
        sourceType: 'url',
        sourceUrl: 'https://example.com/video/unsupported',
        targetLanguage: 'en'
      }
    });
    const job = created.json().job;

    const started = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'run-stage',
      expectedRevision: 0,
      input: { stageId: 'subtitle' }
    });
    expect(started.statusCode).toBe(422);
    expect(started.json()).toMatchObject({ error: { code: 'unsupported_source' } });

    const restored = await request('GET', `/creator/jobs/${job.id}`);
    expect(restored.json().job).toMatchObject({ revision: 0, status: 'draft', stages: [] });
  });

  it('streams a local source into the job before starting subtitles', async () => {
    const sourceBytes = Buffer.from('test-video-content');
    await setupServer({
      creatorSourceMediaProbe: async path => {
        expect(readFileSync(path)).toEqual(sourceBytes);
        return {
          duration: 12.5,
          width: 1280,
          height: 720,
          hasVideo: true,
          hasAudio: true
        };
      }
    });
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_local_source',
      templateId: 'video-translation',
      creationKey: 'local-video-source',
      state: {
        sourceType: 'file',
        targetLanguage: 'en'
      }
    });
    const job = created.json().job;
    const uploadUrl = `/creator/jobs/${job.id}/source-video?${new URLSearchParams({
      expectedRevision: '0',
      fileName: 'sample.webm',
      mime: 'video/webm',
      lastModified: '123'
    })}`;
    const uploaded = await server!.inject({
      method: 'POST',
      url: uploadUrl,
      headers: {
        authorization: 'Bearer secret',
        'content-type': 'application/vnd.opencreator.creator-source'
      },
      payload: sourceBytes
    });

    expect(uploaded.statusCode).toBe(201);
    expect(uploaded.json()).toMatchObject({
      deduplicated: false,
      job: {
        revision: 1,
        state: {
          sourceType: 'file',
          sourceFileName: 'sample.webm'
        }
      },
      artifact: {
        kind: 'source_video',
        status: 'completed',
        metadata: {
          fileName: 'sample.webm',
          mimeType: 'video/webm',
          size: sourceBytes.length,
          source: 'local-upload'
        }
      }
    });

    const duplicate = await server!.inject({
      method: 'POST',
      url: uploadUrl.replace('expectedRevision=0', 'expectedRevision=1'),
      headers: {
        authorization: 'Bearer secret',
        'content-type': 'application/vnd.opencreator.creator-source'
      },
      payload: sourceBytes
    });
    expect(duplicate.statusCode).toBe(200);
    expect(duplicate.json()).toMatchObject({ deduplicated: true, job: { revision: 1 } });

    const started = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'run-stage',
      expectedRevision: 1,
      input: { stageId: 'subtitle' }
    });
    expect(started.statusCode).toBe(400);
    expect(started.json()).toMatchObject({
      error: { preflight: { canStart: false } }
    });
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job.stages).toEqual([]);
  });

  it('starts subtitles without requiring TTS configuration up front', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_vt6',
      templateId: 'video-translation',
      creationKey: 'subtitle-before-tts',
      state: {
        sourceType: 'url',
        sourceUrl: 'https://www.youtube.com/watch?v=vt6',
        targetLanguage: 'en',
        dubbing: true
      }
    });
    const job = created.json().job;

    const started = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'run-stage',
      expectedRevision: 0,
      input: { stageId: 'subtitle' }
    });
    expect(started.statusCode).toBe(400);
    expect(started.json()).toMatchObject({
      error: { preflight: { canStart: false } }
    });
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job.stages).toEqual([]);
  });

  it('requires text translation configuration before starting subtitles', async () => {
    await setupServer({ llmConfigured: false });
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_llm',
      templateId: 'video-translation',
      creationKey: 'translation-llm-missing',
      state: {
        sourceType: 'url',
        sourceUrl: 'https://www.youtube.com/watch?v=llm',
        targetLanguage: 'en'
      }
    });
    const job = created.json().job;

    const preflight = await request('GET', `/creator/jobs/${job.id}/preflight?stageId=subtitle`);
    expect(preflight.statusCode).toBe(200);
    expect(preflight.json()).toMatchObject({
      canStart: false,
      blocked: expect.arrayContaining([expect.objectContaining({
        id: 'llm',
        repair: expect.objectContaining({
          deepLink: '#/settings?tab=ai-services&section=text'
        })
      })])
    });

    const started = await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'run-stage',
      expectedRevision: 0,
      input: { stageId: 'subtitle' }
    });

    expect(started.statusCode).toBe(400);
    expect(started.json()).toMatchObject({
      error: {
        code: 'creator_llm_config_missing',
        preflight: { canStart: false }
      }
    });
    expect((await request('GET', `/creator/jobs/${job.id}`)).json().job.stages).toEqual([]);
  });

  it('returns the authoritative Agent issue with its provider reason instead of a second HTTP error', async () => {
    await setupServer({ agentRuntime: {
      id: 'provider-failure', available: true,
      async runTurn() {
        throw Object.assign(new Error('The selected model is not supported by this account.'), {
          publicFacts: { kind: 'http-rejected', provider: 'codex',
            upstreamMessage: 'The selected model is not supported by this account.' }
        });
      }
    } });
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_agent_failure', templateId: 'video-download'
    });
    const job = created.json().job;
    const response = await request('POST', `/creator/jobs/${job.id}/agent-turns`, { message: 'hello' });
    expect(response.statusCode).toBe(502);
    expect(response.json()).toMatchObject({ error: {
      code: 'creator_agent_failed',
      issue: { code: 'creator_agent_failed', publicFacts: {
        provider: 'codex', upstreamMessage: 'The selected model is not supported by this account.'
      } }
    } });
    const current = (await request('GET', `/creator/jobs/${job.id}`)).json().job;
    expect(current.issues).toHaveLength(1);
    expect(current.issues[0].id).toBe(response.json().error.issue.id);
  });

  it('returns the persisted Agent timeline and resolves approvals by generation', async () => {
    let observedDecision = '';
    const agentRuntime: AgentRuntimeAdapter = {
      id: 'api-test',
      available: true,
      async runTurn(input) {
        input.onStarted?.({ pid: 301, generation: 8, reused: false });
        if (input.message === '需要审批') {
          observedDecision = await input.onApprovalRequest?.({
            id: 'request-api-approval',
            method: 'item/commandExecution/requestApproval',
            params: { itemId: 'item-api-approval', reason: '执行真实命令' }
          }) ?? '';
        }
        await input.onNotification?.({
          method: 'item/completed',
          params: {
            item: {
              id: `prompt-${input.runId}`,
              type: 'userMessage',
              content: [{
                type: 'inputText',
                text: '用户请求:测试\nOpenCreator Context Projection:{"private":true}'
              }]
            }
          }
        });
        await input.onNotification?.({
          method: 'item/completed',
          params: {
            item: {
              id: `item-${input.runId}`,
              type: 'agentMessage',
              text: '真实 Agent 回复'
            }
          }
        });
        return {
          content: '真实 Agent 回复',
          runtimeThreadId: 'runtime-thread-api',
          runtimeTurnId: `runtime-${input.runId}`,
          processGeneration: 8
        };
      }
    };
    await setupServer({ agentRuntime });
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_agent_api',
      templateId: 'video-translation',
      creationKey: 'creator-agent-api'
    });
    const job = created.json().job;

    const emptyTimeline = await request('GET', `/creator/jobs/${job.id}/agent-timeline`);
    expect(emptyTimeline.json()).toMatchObject({ session: null, turns: [], items: [] });

    const invalidSandbox = await request('POST', `/creator/jobs/${job.id}/agent-turns`, {
      message: '无效权限请求',
      sandbox: 'read-only'
    });
    expect(invalidSandbox.statusCode).toBe(400);
    expect(invalidSandbox.json()).toMatchObject({ error: { code: 'VALIDATION_FAILED' } });

    const first = await request('POST', `/creator/jobs/${job.id}/agent-turns`, {
      message: '开始处理',
      clientMessageId: 'client-api-1',
      sandbox: 'danger-full-access'
    });
    expect(first.statusCode).toBe(200);

    const approvalTurn = request('POST', `/creator/jobs/${job.id}/agent-turns`, {
      message: '需要审批',
      clientMessageId: 'client-api-2'
    });
    const approval = await waitForApiApproval(job.id);
    const approved = await request(
      'POST',
      `/creator/jobs/${job.id}/agent-approvals/${approval.id}`,
      { decision: 'approved', processGeneration: 8 }
    );
    expect(approved.statusCode).toBe(200);
    await approvalTurn;

    const timeline = await request('GET', `/creator/jobs/${job.id}/agent-history`);
    expect(timeline.json()).toMatchObject({
      session: { runtimeThreadId: 'runtime-thread-api', hostGeneration: 8 },
      approvals: [{ id: approval.id, status: 'approved' }]
    });
    expect(timeline.json().turns).toHaveLength(4);
    expect(timeline.json().turns.some((turn: { content?: string }) => turn.content === '真实 Agent 回复'))
      .toBe(true);
    expect(timeline.json().items).toEqual(expect.arrayContaining([
      expect.objectContaining({
        kind: 'assistant_message',
        text: expect.any(String)
      })
    ]));
    expect(JSON.stringify(timeline.json())).not.toContain('Context Projection');
    expect(JSON.stringify(timeline.json())).not.toContain('private');
    expect(observedDecision).toBe('approved');
  });

  it('replays stable Creator SSE events after a cursor', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_sse',
      templateId: 'video-translation',
      creationKey: 'creator-sse'
    });
    const job = created.json().job;
    await server!.listen({ host: '127.0.0.1', port: 0 });
    const address = server!.server.address();
    if (address === null || typeof address === 'string') throw new Error('Server address is unavailable');
    const origin = `http://127.0.0.1:${address.port}`;

    const initial = await readSseFrames(
      `${origin}/creator/jobs/${job.id}/events`,
      1
    );
    expect(initial[0]).toMatchObject({
      id: 'snapshot:0',
      event: 'snapshot_changed',
      data: { id: 'snapshot:0', revision: 0 }
    });

    await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'update-settings',
      expectedRevision: 0,
      idempotencyKey: 'sse-action-1',
      input: { patch: { targetLanguage: 'ja' } }
    });
    const reset = await readSseFrames(
      `${origin}/creator/jobs/${job.id}/events?cursor=${encodeURIComponent('snapshot:0')}`,
      1
    );
    expect(reset[0]).toMatchObject({
      id: 'reset:1',
      data: { payload: { reset: true, revision: 1 } }
    });

    const firstUpdated = await request('GET', `/creator/jobs/${job.id}`);
    const firstActivityId = firstUpdated.json().job.activities[0].id;
    await request('POST', `/creator/jobs/${job.id}/actions`, {
      action: 'update-settings',
      expectedRevision: 1,
      idempotencyKey: 'sse-action-2',
      input: { patch: { targetLanguage: 'fr' } }
    });
    const replayed = await readSseFrames(
      `${origin}/creator/jobs/${job.id}/events?cursor=${encodeURIComponent(`activity:${firstActivityId}`)}`,
      2
    );
    expect(replayed.map(frame => frame.id)).toContain('snapshot:2');
    expect(replayed.some(frame => frame.id.startsWith('activity:'))).toBe(true);
    expect(new Set(replayed.map(frame => frame.id)).size).toBe(replayed.length);
  });

  it('reports one sanitized client issue through response snapshot list stats and SSE', async () => {
    await setupServer();
    const created = await request('POST', '/creator/jobs', {
      projectId: 'project_issue_api',
      templateId: 'video-translation',
      creationKey: 'creator-issue-api'
    });
    const job = created.json().job;
    const reportBody = {
      clientIssueId: 'local:issue-api',
      code: 'creator_client_preview_failed',
      source: 'client',
      operation: 'creator.preview-artifact',
      fallbackMessage: 'Authorization: Bearer secret C:\\Users\\Mayn\\private.mp4'
    };
    const first = await request('POST', `/creator/jobs/${job.id}/issues/report`, reportBody);
    const repeated = await request('POST', `/creator/jobs/${job.id}/issues/report`, reportBody);

    expect(first.statusCode).toBe(201);
    expect(repeated.statusCode).toBe(201);
    expect(repeated.json().issue).toMatchObject({
      id: first.json().issue.id,
      occurrenceCount: 2,
      source: 'client',
      status: 'open'
    });
    expect(JSON.stringify(repeated.json())).not.toContain('secret');
    expect(JSON.stringify(repeated.json())).not.toContain('Mayn');

    const snapshot = await request('GET', `/creator/jobs/${job.id}`);
    const listed = await request('GET', `/creator/jobs/${job.id}/issues?limit=1`);
    expect(snapshot.json().job.issues).toEqual([
      expect.objectContaining({ id: first.json().issue.id })
    ]);
    expect(listed.json()).toMatchObject({
      issues: [expect.objectContaining({ id: first.json().issue.id })],
      events: [expect.objectContaining({ issueId: first.json().issue.id })],
      nextCursor: expect.any(String)
    });

    const occurredAt = Date.parse(first.json().issue.occurredAt);
    const from = new Date(occurredAt - 60_000).toISOString();
    const to = new Date(occurredAt + 60_000).toISOString();
    const stats = await request(
      'GET',
      `/creator/jobs/${job.id}/issues/stats?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`
    );
    expect(Object.keys(stats.json())).toEqual(['jobId', 'from', 'to', 'rows']);
    expect(stats.json().rows).toEqual([{
      code: 'creator_client_preview_failed',
      source: 'client',
      status: 'open',
      retryResult: 'none',
      count: 1
    }]);
    expect(Object.keys(stats.json().rows[0])).toEqual([
      'code', 'source', 'status', 'retryResult', 'count'
    ]);

    const forged = await request('POST', `/creator/jobs/${job.id}/issues/report`, {
      ...reportBody,
      repairActions: [{ kind: 'retry-operation', risk: 'paid' }]
    });
    const foreign = await request('POST', '/creator/jobs/missing-job/issues/report', reportBody);
    expect(forged.statusCode).toBe(400);
    expect(foreign.statusCode).toBe(404);

    await server!.listen({ host: '127.0.0.1', port: 0 });
    const address = server!.server.address();
    if (address === null || typeof address === 'string') throw new Error('Server address is unavailable');
    const frames = await readSseFrames(
      `http://127.0.0.1:${address.port}/creator/jobs/${job.id}/events?cursor=${encodeURIComponent('snapshot:0')}`,
      1
    );
    const issueFrame = frames.find(frame => frame.event === 'issue_changed');
    expect(issueFrame?.data).toMatchObject({
      payload: { issue: { id: first.json().issue.id, occurrenceCount: 2 } }
    });
  });
});

async function setupServer(options: {
  llmConfigured?: boolean;
  gatewayMode?: boolean;
  agentRuntime?: AgentRuntimeAdapter;
  creatorSourceMediaProbe?(path: string): Promise<{
    duration: number;
    width?: number;
    height?: number;
    hasVideo: boolean;
    hasAudio: boolean;
  }>;
  creatorExecutors?: CreatorExecutor[];
} = {}): Promise<void> {
  tempDir = mkdtempSync(join(tmpdir(), 'creator-api-'));
  if (options.gatewayMode) {
    await createGatewayConfigStore(tempDir).writeConfiguration({
      source: 'gateway', bindingVersion: null
    });
  }
  const config = createDefaultCreatorServicesConfig();
  config.llm.source = 'custom';
  if (options.llmConfigured !== false) {
    config.llm.baseUrl = 'https://api.openai.com/v1';
    config.llm.apiKey = 'test-llm-key';
  }
  server = await buildServer({
    token: 'secret',
    dataDir: tempDir,
    codexHome: join(tempDir, 'codex-home'),
    creatorAgentRuntime: options.agentRuntime,
    ...(options.creatorExecutors === undefined
      ? {}
      : { creatorExecutors: options.creatorExecutors }),
    ...(options.creatorSourceMediaProbe === undefined
      ? {}
      : { creatorSourceMediaProbe: options.creatorSourceMediaProbe }),
    creatorServicesConfigStore: {
      async read() { return structuredClone(config); },
      async write(next) { return structuredClone(next); },
      async reset() { return structuredClone(config); }
    },
    codexProviderCredentialStore: {
      async readApiKey() { return undefined; },
      async writeApiKey() {}
    }
  });
}

async function waitForCreatorJob(
  jobId: string,
  predicate: (job: any) => boolean
): Promise<any> {
  let lastJob: any;
  for (let attempt = 0; attempt < 100; attempt += 1) {
    const response = await request('GET', `/creator/jobs/${jobId}`);
    const job = response.json().job;
    lastJob = job;
    if (predicate(job)) return job;
    await new Promise(resolve => setTimeout(resolve, 10));
  }
  throw new Error(`Timed out waiting for Creator job ${jobId}: ${JSON.stringify({ status: lastJob?.status, stages: lastJob?.stages })}`);
}

async function waitForApiApproval(jobId: string) {
  for (let attempt = 0; attempt < 30; attempt += 1) {
    const timeline = await request('GET', `/creator/jobs/${jobId}/agent-timeline`);
    const approval = timeline.json().approvals?.[0];
    if (approval !== undefined) return approval;
    await new Promise(resolve => setTimeout(resolve, 0));
  }
  throw new Error('API approval was not persisted');
}

async function request(
  method: 'GET' | 'POST' | 'DELETE',
  url: string,
  payload?: string | object
): Promise<TestResponse> {
  return await server!.inject({
    method,
    url,
    headers: { authorization: 'Bearer secret' },
    ...(payload === undefined ? {} : { payload })
  }) as unknown as TestResponse;
}

function png(label: string): Buffer {
  return Buffer.concat([
    Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
    Buffer.from(label.padEnd(24, '.'))
  ]);
}

async function readSseFrames(url: string, expected: number): Promise<Array<{
  id: string;
  event: string;
  data: Record<string, unknown>;
}>> {
  const controller = new AbortController();
  const response = await fetch(url, {
    headers: { authorization: 'Bearer secret' },
    signal: controller.signal
  });
  const reader = response.body?.getReader();
  if (reader === undefined) throw new Error('SSE response has no body');
  const decoder = new TextDecoder();
  const frames: Array<{ id: string; event: string; data: Record<string, unknown> }> = [];
  let buffered = '';
  try {
    while (frames.length < expected) {
      const read = await Promise.race([
        reader.read(),
        new Promise<never>((_, reject) => setTimeout(
          () => reject(new Error('Timed out waiting for SSE replay')),
          2_000
        ))
      ]);
      if (read.done) break;
      buffered += decoder.decode(read.value, { stream: true });
      let boundary = buffered.indexOf('\n\n');
      while (boundary >= 0) {
        const frame = buffered.slice(0, boundary);
        buffered = buffered.slice(boundary + 2);
        const id = frame.split('\n').find(line => line.startsWith('id: '))?.slice(4);
        const event = frame.split('\n').find(line => line.startsWith('event: '))?.slice(7);
        const data = frame.split('\n').find(line => line.startsWith('data: '))?.slice(6);
        if (id !== undefined && event !== undefined && data !== undefined) {
          frames.push({ id, event, data: JSON.parse(data) as Record<string, unknown> });
        }
        boundary = buffered.indexOf('\n\n');
      }
    }
  } finally {
    controller.abort();
    await reader.cancel().catch(() => undefined);
  }
  return frames;
}