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.

37.6 KB
Raw Blame
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { CreatorAgentTimelineResponse, CreatorJob } from '@opencreator/protocol';
import { describe, expect, it, vi } from 'vitest';
import { LanguageProvider } from '../../i18n/LanguageProvider.js';
import { CreatorSessionProvider } from './creator-session-store.js';
import VideoTranslationAgentPanel from './VideoTranslationAgentPanel.js';
import { LanguageSwitchControls } from '../../test/LanguageSwitchControls.js';

describe('VideoTranslationAgentPanel', () => {
  it.each([30, null])('shows source-video download bytes and %s percent without requiring a component link', async percent => {
    const current = job();
    current.status = 'completed';
    current.stages.push({
      id: 'source-download', jobId: current.id, stageId: 'prepare-source-video', executor: 'download', status: 'running', dispatchStatus: 'claimed',
      claimOwner: 'scheduler', claimExpiresAt: null, attempt: 1, idempotencyKey: 'source-download', scopeKey: null, inputFingerprint: null,
      progress: { phase: 'downloading', percent, downloadedBytes: 6 * 1024 ** 2, totalBytes: percent === null ? null : 20 * 1024 ** 2,
        message: '原始下载器信息,不直接作为界面文案' },
      errorCode: null, errorMessage: null, startedAt: '2026-10-02T00:00:00.000Z', finishedAt: null
    });
    renderPanel({ initialJob: current, getAgentTimeline: vi.fn(async () => emptyTimeline()), languageSwitch: true });
    expect(await screen.findByText(/正在下载当前视频资源:6.0 MiB/)).toBeVisible();
    const progress = screen.getByRole('progressbar');
    if (percent === null) expect(progress).not.toHaveAttribute('aria-valuenow');
    else expect(progress).toHaveAttribute('aria-valuenow', String(percent));
    expect(screen.queryByRole('link', { name: '查看组件下载详情' })).not.toBeInTheDocument();
    expect(screen.queryByText('原始下载器信息,不直接作为界面文案')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'en-US' }));
    expect(screen.getByText(/Downloading the current video resource: 6.0 MiB/)).toBeVisible();
    fireEvent.click(screen.getByRole('button', { name: 'sv-SE' }));
    expect(screen.getByText(/Laddar ned den aktuella videoresursen: 6.0 MiB/)).toBeVisible();
  });

  it('keeps the overall percentage and labels the conversion phase separately', async () => {
    const current = job();
    current.status = 'running';
    current.stages.push({
      id: 'source-conversion', jobId: current.id, stageId: 'prepare-source-video', executor: 'download', status: 'running', dispatchStatus: 'claimed',
      claimOwner: 'scheduler', claimExpiresAt: null, attempt: 1, idempotencyKey: 'source-conversion', scopeKey: null, inputFingerprint: null,
      progress: { phase: 'normalizing_media', percent: 98.90059326924516, phasePercent: 90 },
      errorCode: null, errorMessage: null, startedAt: '2026-10-02T00:00:00.000Z', finishedAt: null
    });
    renderPanel({ initialJob: current, getAgentTimeline: vi.fn(async () => emptyTimeline()) });
    const progress = await screen.findByRole('progressbar');
    expect(progress).toHaveAttribute('aria-valuenow', '99');
    expect(screen.getByText('当前转换阶段 90%')).toBeVisible();
    expect(screen.getByText('正在转换原视频为本机兼容格式,已有字幕会保留。')).toBeVisible();
    expect(screen.queryByText(/98\.90059326924516/)).not.toBeInTheDocument();
  });

  it('明确显示长时间模型下载的原因、真实进度和自动继续提示', async () => {
    const current = job();
    current.status = 'running';
    current.stages.push({
      id: 'component-download', jobId: current.id, stageId: 'subtitle', executor: 'krillinai', status: 'running', dispatchStatus: 'claimed',
      claimOwner: 'scheduler', claimExpiresAt: null, attempt: 1, idempotencyKey: 'component-download', scopeKey: null, inputFingerprint: null,
      progress: { phase: 'downloading_dependencies', percent: 2, dependencyPercent: 25, downloadedBytes: 512 * 1024 ** 2, totalBytes: 2 * 1024 ** 3,
        message: '未找到可用的原始字幕,正在下载本地模型。模型文件较大,下载并校验完成后将自动继续,无需重新开始。' },
      errorCode: null, errorMessage: null, startedAt: '2026-10-01T00:00:00.000Z', finishedAt: null
    });
    const getAgentTimeline = vi.fn(async () => emptyTimeline());
    const runAgentTurn = vi.fn();
    renderPanel({ initialJob: current, getAgentTimeline, runAgentTurn, languageSwitch: true });
    expect(await screen.findByText('下载本地转录组件(尚未开始转录)')).toBeInTheDocument();
    expect(screen.getByText(/下载并校验完成后会自动继续/)).toBeInTheDocument();
    expect(screen.getByText(/512.0 MiB \/ 2.00 GiB/)).toBeInTheDocument();
    expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
    expect(screen.getByRole('link', { name: '查看组件下载详情' })).toHaveAttribute('href', expect.stringContaining('returnPath='));
    fireEvent.click(screen.getByRole('button', { name: 'en-US' }));
    expect(screen.getByText('Downloading local components (transcription has not started)')).toBeVisible();
    expect(screen.getByText(/the task continues automatically after download and verification/)).toBeVisible();
    fireEvent.click(screen.getByRole('button', { name: 'sv-SE' }));
    expect(screen.getByText('Laddar ned lokala komponenter (transkriptionen har inte startat)')).toBeVisible();
    expect(screen.getByText(/uppgiften fortsätter automatiskt efter nedladdning och verifiering/)).toBeVisible();
    expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
    expect(screen.getByRole('link', { name: 'Visa information om komponentnedladdningen' })).toHaveAttribute('href', expect.stringContaining('returnPath='));
    expect(getAgentTimeline).toHaveBeenCalledOnce();
    expect(runAgentTurn).not.toHaveBeenCalled();
  });
  it('只展示标准对话和协作事件,不泄露内部工具上下文', async () => {
    const { container } = renderPanel({
      getAgentTimeline: vi.fn(async () => timeline())
    });

    expect(await screen.findByRole('heading', { name: '设置建议', level: 3 })).toBeInTheDocument();
    expect(screen.getByText('先确认目标语言')).toBeInTheDocument();
    expect(screen.getByText('请检查当前设置')).toBeInTheDocument();
    expect(screen.getByText('更新了创作设置')).toBeInTheDocument();
    expect(screen.getByText('工作台')).toBeInTheDocument();
    expect(screen.queryByText(/OpenCreator Context Projection/)).not.toBeInTheDocument();
    expect(screen.queryByText(/internal prompt/)).not.toBeInTheDocument();
    expect(screen.queryByText('确认项目状态')).not.toBeInTheDocument();
    expect(screen.queryByText('执行记录')).not.toBeInTheDocument();
    expect(screen.queryByText('已经处理的工具确认')).not.toBeInTheDocument();
    expect(container.querySelector('.tool-agent-composer-icon-button')).toBeNull();
    expect(container.querySelectorAll('.tool-agent-composer-select')).toHaveLength(1);
    expect(container.querySelector('.tool-agent-composer-send')).not.toBeNull();
    expect(container.querySelector('.creator-collaboration-header .opencreator-mark')).not.toBeNull();
    expect(container.querySelector(
      '.creator-collaboration-message[data-role="assistant"] .opencreator-mark'
    )).not.toBeNull();
    expect(container.querySelector('.lucide-bot')).toBeNull();
  });

  it('合并连续的工作台设置更新,并忽略纯界面状态', async () => {
    renderPanel({
      initialJob: job(),
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    expect(await screen.findByText('更新了创作设置')).toBeInTheDocument();
    expect(screen.getAllByText('更新了创作设置')).toHaveLength(1);
    expect(screen.getByText('目标语言、双语字幕、配音')).toBeInTheDocument();
    expect(screen.getByText('2 次修改')).toBeInTheDocument();
    expect(screen.queryByText('当前步骤')).not.toBeInTheDocument();
    expect(screen.queryByText('V4')).not.toBeInTheDocument();
  });

  it('区分工作台快捷操作与真实 Agent 对话', async () => {
    const directAction = vi.fn();
    const runAgentTurn = vi.fn(async () => ({ turn: {} }));
    renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline()),
      directAction
    });

    fireEvent.click(screen.getByRole('button', { name: '打开翻译设置' }));
    expect(directAction).toHaveBeenCalledTimes(1);
    expect(runAgentTurn).not.toHaveBeenCalled();

    fireEvent.click(screen.getByRole('button', { name: '让 Agent 检查设置' }));
    await waitFor(() => expect(runAgentTurn).toHaveBeenCalledWith(
      'job_1',
      expect.objectContaining({
        message: '检查设置',
        clientMessageId: expect.any(String),
        sandbox: 'danger-full-access'
      })
    ));
  });

  it('默认使用完全访问权限,并把权限真实传给 Creator Agent', async () => {
    const runAgentTurn = vi.fn(async () => ({ turn: {} }));
    renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    expect(screen.getByRole('button', { name: /选择访问权限 完全访问权限/ })).toBeInTheDocument();

    fireEvent.change(screen.getByRole('textbox', { name: '告诉 Agent 你的要求' }), {
      target: { value: '合成视频' }
    });
    fireEvent.click(screen.getByRole('button', { name: '发送给 Agent' }));

    await waitFor(() => expect(runAgentTurn).toHaveBeenCalledWith(
      'job_1',
      expect.objectContaining({
        message: '合成视频',
        sandbox: 'danger-full-access'
      })
    ));
  });

  it('Agent 提交失败时保留输入,并在共享时间线显示安全诊断', async () => {
    const runAgentTurn = vi.fn(async () => {
      throw new Error('Creator Agent is not ready');
    });
    renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    const composer = screen.getByRole('textbox', { name: '告诉 Agent 你的要求' });
    fireEvent.change(composer, { target: { value: '合成横屏视频' } });
    fireEvent.click(screen.getByRole('button', { name: '发送给 Agent' }));

    expect(await screen.findByText(/Agent 未能完成诊断,请查看问题详情后重试。 错误码:CLIENT_OPERATION_FAILED。/)).toBeInTheDocument();
    expect(screen.queryByText('Creator Agent is not ready')).not.toBeInTheDocument();
    expect(composer).toHaveValue('合成横屏视频');
  });

  it('从真实 Creator Thread 状态恢复完全访问权限', async () => {
    const currentTimeline = timeline();
    currentTimeline.session!.sandbox = 'danger-full-access';
    renderPanel({
      getAgentTimeline: vi.fn(async () => currentTimeline)
    });

    expect(await screen.findByRole('button', {
      name: /选择访问权限 完全访问权限/
    })).toBeInTheDocument();
  });

  it('显示 Agent 对工作台的真实修改,并隐藏内部工具枚举', async () => {
    const currentJob = job();
    currentJob.activities.push({
      id: 'activity_render',
      jobId: currentJob.id,
      revision: 5,
      actor: 'agent',
      action: 'run-stage',
      summary: '启动阶段 render-horizontal',
      details: {},
      createdAt: '2026-08-21T00:00:06.000Z'
    });
    const currentTimeline = timeline();
    currentTimeline.turns.push(
      {
        ...currentTimeline.turns[0]!,
        id: 'turn_user_render',
        content: '合成视频',
        createdAt: '2026-08-21T00:00:04.000Z'
      },
      {
        ...currentTimeline.turns[1]!,
        id: 'turn_assistant_render',
        content: '视频已合成成功。\n\n- 当前 revision:`19`',
        createdAt: '2026-08-21T00:00:05.000Z',
        completedAt: '2026-08-21T00:00:07.000Z'
      }
    );
    currentTimeline.items.push(
      ...['context_1', 'context_2', 'context_3'].map((id, index) => ({
        ...currentTimeline.items[1]!,
        id,
        turnId: 'turn_assistant_render',
        runtimeItemId: id,
        sequence: index + 1
      })),
      {
        ...currentTimeline.items[1]!,
        id: 'codex_resources',
        turnId: 'turn_assistant_render',
        runtimeItemId: 'codex_resources',
        toolName: 'codex.list_mcp_resources',
        sequence: 4
      },
      ...['apply_1', 'apply_2'].map((id, index) => ({
        ...currentTimeline.items[1]!,
        id,
        turnId: 'turn_assistant_render',
        runtimeItemId: id,
        toolName: 'opencreator_tools.creator_apply_action',
        sequence: index + 5
      }))
    );

    const { container } = renderPanel({
      initialJob: currentJob,
      getAgentTimeline: vi.fn(async () => currentTimeline)
    });

    expect(await screen.findByText('开始生成横屏成片')).toBeInTheDocument();
    expect(container.querySelector('.creator-collaboration-activity[data-actor="agent"]')).not.toBeNull();
    expect(screen.queryByText('确认项目状态')).not.toBeInTheDocument();
    expect(screen.queryByText('执行记录')).not.toBeInTheDocument();
    expect(screen.queryByText('调用 Creator 工具')).not.toBeInTheDocument();
    expect(screen.queryByText(/revision 19/i)).not.toBeInTheDocument();
  });

  it('发送后立即清空输入框,并在请求完成前阻止重复提交', async () => {
    const pending = deferred<unknown>();
    const runAgentTurn = vi.fn(() => pending.promise);
    renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    const input = screen.getByRole('textbox', { name: '告诉 Agent 你的要求' });
    fireEvent.change(input, { target: { value: '查看下生成的字幕样式' } });
    fireEvent.click(screen.getByRole('button', { name: '发送给 Agent' }));

    expect(input).toHaveValue('');
    await waitFor(() => expect(runAgentTurn).toHaveBeenCalledTimes(1));

    fireEvent.change(input, { target: { value: '不要重复发送' } });
    const sendButton = screen.getByRole('button', { name: '发送给 Agent' });
    expect(sendButton).toBeDisabled();
    fireEvent.click(sendButton);
    expect(runAgentTurn).toHaveBeenCalledTimes(1);

    await act(async () => pending.resolve({ turn: {} }));
    await waitFor(() => expect(sendButton).not.toBeDisabled());
    expect(input).toHaveValue('不要重复发送');
  });

  it('发送失败时仅在输入框仍为空时恢复原消息', async () => {
    const runAgentTurn = vi.fn(async () => {
      throw new Error('Agent unavailable');
    });
    renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    const input = screen.getByRole('textbox', { name: '告诉 Agent 你的要求' });
    fireEvent.change(input, { target: { value: '查看字幕样式' } });
    fireEvent.click(screen.getByRole('button', { name: '发送给 Agent' }));

    expect(input).toHaveValue('');
    await waitFor(() => expect(input).toHaveValue('查看字幕样式'));
  });

  it('Codex 尚未输出内容时只显示一个真实工作指示器', async () => {
    const { container } = renderPanel({
      getAgentTimeline: vi.fn(async () => runningTimeline())
    });

    expect(await screen.findByText('请检查当前设置')).toBeInTheDocument();
    expect(screen.getByRole('status', { name: 'Agent 正在工作' })).toBeInTheDocument();
    expect(container.querySelectorAll('.creator-collaboration-working')).toHaveLength(1);
    expect(container.querySelector(
      '.creator-collaboration-message[data-source="agent"][data-role="assistant"]'
    )).toBeNull();
  });

  it('工具正在执行时不把工具状态伪装成 Codex 回复', async () => {
    const value = runningTimeline();
    value.items = [{
      ...timeline().items[1]!,
      turnId: value.turns[1]!.id,
      status: 'running'
    }];
    const { container } = renderPanel({ getAgentTimeline: vi.fn(async () => value) });

    expect(await screen.findByText('请检查当前设置')).toBeInTheDocument();
    expect(screen.queryByText('确认项目状态')).not.toBeInTheDocument();
    expect(screen.queryByText('执行记录')).not.toBeInTheDocument();
    expect(screen.getByRole('status', { name: 'Agent 正在工作' })).toBeInTheDocument();
    expect(container.querySelectorAll('.creator-collaboration-working')).toHaveLength(1);
    expect(container.querySelector(
      '.creator-collaboration-message[data-source="agent"][data-role="assistant"]'
    )).toBeNull();
  });

  it('优先展示 Codex 已流式输出的可见说明', async () => {
    const value = runningTimeline();
    value.items = [{
      ...timeline().items[0]!,
      turnId: value.turns[1]!.id,
      kind: 'assistant_message',
      role: 'assistant',
      status: 'running',
      text: '我先检查当前字幕和成片设置。',
      data: { phase: 'commentary' }
    }];

    renderPanel({ getAgentTimeline: vi.fn(async () => value) });

    expect(await screen.findByText('我先检查当前字幕和成片设置。')).toBeInTheDocument();
    expect(screen.getByText('Agent 回复')).toBeInTheDocument();
    expect(screen.getByRole('status', { name: 'Agent 正在工作' })).toBeInTheDocument();
  });

  it('等待审批时只展示真实审批请求,不生成固定回复', async () => {
    const value = runningTimeline();
    value.turns[1] = { ...value.turns[1]!, status: 'waiting_approval' };
    value.approvals = [{
      ...timeline().approvals[0]!,
      turnId: value.turns[1]!.id,
      status: 'pending',
      details: {
        _meta: {
          tool_params: {
            action: 'run-stage',
            input: { stageId: 'render-horizontal' }
          }
        }
      },
      resolvedAt: null
    }];
    const { container } = renderPanel({ getAgentTimeline: vi.fn(async () => value) });

    expect(await screen.findByRole('button', { name: '批准' })).toBeInTheDocument();
    expect(screen.queryByRole('status')).not.toBeInTheDocument();
    expect(container.querySelector(
      '.creator-collaboration-message[data-source="agent"][data-role="assistant"]'
    )).toBeNull();
  });

  it('系统运行信息跟随界面语言,同时保留用户和 Agent 的原始对话语言', async () => {
    const currentJob = job();
    currentJob.status = 'running';
    currentJob.revision = 8;
    currentJob.activities.push(
      {
        id: 'activity_needs_input',
        jobId: currentJob.id,
        revision: 5,
        actor: 'system',
        action: 'needs-input',
        summary: '请先完成文本翻译模型配置',
        details: { code: 'creator_llm_config_missing' },
        createdAt: '2026-08-21T00:00:04.000Z'
      },
      {
        id: 'activity_unknown_system',
        jobId: currentJob.id,
        revision: 6,
        actor: 'system',
        action: 'workflow-state-changed',
        summary: '后台恢复任务状态',
        details: {},
        createdAt: '2026-08-21T00:00:05.000Z'
      }
    );
    currentJob.stages.push(
      {
        id: 'stage_subtitle_localized',
        jobId: currentJob.id,
        stageId: 'subtitle',
        executor: 'krillinai',
        status: 'running',
        dispatchStatus: 'claimed',
        claimOwner: 'scheduler_1',
        claimExpiresAt: '2026-08-21T00:01:00.000Z',
        attempt: 1,
        idempotencyKey: 'subtitle_localized_1',
        scopeKey: null,
        inputFingerprint: null,
        progress: {
          phase: 'translating_subtitles',
          percent: 24,
          message: '正在翻译字幕'
        },
        errorCode: null,
        errorMessage: null,
        startedAt: '2026-08-21T00:00:06.000Z',
        finishedAt: null
      },
      {
        id: 'stage_tts_localized',
        jobId: currentJob.id,
        stageId: 'tts',
        executor: 'krillinai',
        status: 'failed',
        dispatchStatus: 'finished',
        claimOwner: null,
        claimExpiresAt: null,
        attempt: 1,
        idempotencyKey: 'tts_localized_1',
        scopeKey: null,
        inputFingerprint: null,
        progress: {
          phase: 'generating_voice',
          percent: 35,
          message: '正在生成配音'
        },
        errorCode: 'voice_provider_failed',
        errorMessage: '配音服务返回错误',
        startedAt: '2026-08-21T00:00:07.000Z',
        finishedAt: '2026-08-21T00:00:08.000Z'
      }
    );
    const currentTimeline = timeline();
    currentTimeline.approvals = [{
      ...currentTimeline.approvals[0]!,
      status: 'pending',
      title: '确认工具调用',
      summary: 'Agent 请求执行工具',
      resolvedAt: null
    }];

    renderPanel({
      language: 'en-US',
      initialJob: currentJob,
      getAgentTimeline: vi.fn(async () => currentTimeline)
    });

    expect(await screen.findByText('Confirm tool call')).toBeInTheDocument();
    expect(screen.getByText('Updated creative settings')).toBeInTheDocument();
    expect(screen.getByText('Target language, Bilingual subtitles, Dubbing'))
      .toBeInTheDocument();
    expect(screen.getByText('Configure the text model to continue')).toBeInTheDocument();
    expect(screen.getByText('System updated the task status')).toBeInTheDocument();
    expect(screen.getByText('Translating subtitles')).toBeInTheDocument();
    expect(screen.getByText('Failed')).toBeInTheDocument();
    expect(screen.getByText(
      'The Agent wants to use a tool to continue this task.'
    )).toBeInTheDocument();

    expect(screen.queryByText('请先完成文本翻译模型配置')).not.toBeInTheDocument();
    expect(screen.queryByText('后台恢复任务状态')).not.toBeInTheDocument();
    expect(screen.queryByText('正在翻译字幕')).not.toBeInTheDocument();
    expect(screen.queryByText('配音服务返回错误')).not.toBeInTheDocument();
    expect(screen.queryByText('确认工具调用')).not.toBeInTheDocument();
    expect(screen.queryByText('Agent 请求执行工具')).not.toBeInTheDocument();

    expect(screen.getByText('请检查当前设置')).toBeInTheDocument();
    expect(screen.getByRole('heading', { name: '设置建议', level: 3 }))
      .toBeInTheDocument();
    expect(screen.getByText('先确认目标语言')).toBeInTheDocument();
  });

  it('把工作台操作和 Runtime 真实进度归并为一张 Stage 卡', async () => {
    const runningJob = job();
    runningJob.status = 'running';
    runningJob.revision = 6;
    runningJob.activities.push({
      id: 'activity_run',
      jobId: runningJob.id,
      revision: 5,
      actor: 'user',
      action: 'run-stage',
      summary: '启动阶段 subtitle',
      details: {},
      createdAt: '2026-08-21T00:00:04.000Z'
    });
    runningJob.stages.push({
      id: 'stage_subtitle',
      jobId: runningJob.id,
      stageId: 'subtitle',
      executor: 'krillinai',
      status: 'running',
      dispatchStatus: 'claimed',
      claimOwner: 'scheduler_1',
      claimExpiresAt: '2026-08-21T00:01:00.000Z',
      attempt: 1,
      idempotencyKey: 'subtitle_1',
      scopeKey: null,
      inputFingerprint: null,
      progress: {
        krillinStatus: 'running',
        krillinEventPayload: {
          phase: 'translating_subtitles',
          percent: 52,
          message: '正在翻译字幕'
        }
      },
      errorCode: null,
      errorMessage: null,
      startedAt: '2026-08-21T00:00:05.000Z',
      finishedAt: null
    });

    const getAgentTimeline = vi.fn(async () => emptyTimeline());
    renderPanel({
      initialJob: runningJob,
      getAgentTimeline
    });

    expect(screen.getByText(/工作台 · 字幕翻译/)).toBeInTheDocument();
    expect(screen.getByText('翻译字幕')).toBeInTheDocument();
    expect(screen.getByText('52%')).toBeInTheDocument();
    expect(screen.getByRole('progressbar', { name: '字幕翻译进度' })).toHaveAttribute('aria-valuenow', '52');
    expect(screen.queryByRole('status', { name: 'Agent 正在工作' })).not.toBeInTheDocument();
    expect(document.querySelectorAll('.creator-collaboration-spin')).toHaveLength(1);
    expect(screen.queryByText('开始生成字幕')).not.toBeInTheDocument();
    expect(screen.queryByText('我已从工作台开始视频字幕翻译。')).not.toBeInTheDocument();
    await waitFor(() => expect(getAgentTimeline).toHaveBeenCalledTimes(1));
  });

  it('在阶段卡上提供终止和继续操作', async () => {
    const runningJob = job();
    runningJob.status = 'running';
    runningJob.stages.push({
      id: 'stage_control',
      jobId: runningJob.id,
      stageId: 'subtitle',
      executor: 'krillinai',
      status: 'running',
      dispatchStatus: 'claimed',
      claimOwner: 'scheduler_1',
      claimExpiresAt: '2026-08-28T06:01:00.000Z',
      attempt: 1,
      idempotencyKey: 'stage-control',
      scopeKey: null,
      inputFingerprint: null,
      progress: { percent: 25 },
      errorCode: null,
      errorMessage: null,
      startedAt: '2026-08-28T06:00:00.000Z',
      finishedAt: null
    });
    const onCancelTask = vi.fn();
    const view = render(
      <LanguageProvider initialPreference="zh-CN">
        <CreatorSessionProvider
          key="running-control"
          initialJob={runningJob}
          service={{
            applyAction: vi.fn(),
            runAgentTurn: vi.fn(),
            getAgentTimeline: vi.fn(async () => emptyTimeline())
          } as never}
        >
          <VideoTranslationAgentPanel
            stepLabel="翻译设置"
            contextSummary="英文到中文"
            onCancelTask={onCancelTask}
          />
        </CreatorSessionProvider>
      </LanguageProvider>
    );

    fireEvent.click(await screen.findByRole('button', { name: '终止字幕翻译' }));
    expect(onCancelTask).toHaveBeenCalledTimes(1);

    const canceledJob = {
      ...runningJob,
      status: 'canceled' as const,
      revision: runningJob.revision + 1,
      stages: [{
        ...runningJob.stages[0]!,
        status: 'canceled' as const,
        dispatchStatus: 'finished' as const,
        finishedAt: '2026-08-28T06:00:10.000Z'
      }]
    };
    const onResumeTask = vi.fn();
    view.rerender(
      <LanguageProvider initialPreference="zh-CN">
        <CreatorSessionProvider
          key="canceled-control"
          initialJob={canceledJob}
          service={{
            applyAction: vi.fn(),
            runAgentTurn: vi.fn(),
            getAgentTimeline: vi.fn(async () => emptyTimeline())
          } as never}
        >
          <VideoTranslationAgentPanel
            stepLabel="翻译设置"
            contextSummary="英文到中文"
            onResumeTask={onResumeTask}
          />
        </CreatorSessionProvider>
      </LanguageProvider>
    );

    fireEvent.click(await screen.findByRole('button', { name: '继续字幕翻译' }));
    expect(onResumeTask).toHaveBeenCalledTimes(1);
    expect(screen.getByText('已终止,可继续')).toBeInTheDocument();
  });

  it('任务失败后保留 Runtime 提供的最后进度', async () => {
    const failedJob = job();
    failedJob.status = 'failed';
    failedJob.stages.push({
      id: 'stage_subtitle_failed',
      jobId: failedJob.id,
      stageId: 'subtitle',
      executor: 'krillinai',
      status: 'failed',
      dispatchStatus: 'finished',
      claimOwner: null,
      claimExpiresAt: null,
      attempt: 1,
      idempotencyKey: 'subtitle_failed_1',
      scopeKey: null,
      inputFingerprint: null,
      progress: {
        percent: 67,
        phase: 'translating_subtitles',
        krillinEventPayload: {
          percent: 67,
          phase: 'translating_subtitles',
          message: '正在翻译字幕'
        }
      },
      errorCode: 'translation_failed',
      errorMessage: '翻译服务返回错误',
      startedAt: '2026-08-21T00:00:05.000Z',
      finishedAt: '2026-08-21T00:00:20.000Z'
    });

    const getAgentTimeline = vi.fn(async () => emptyTimeline());
    renderPanel({
      initialJob: failedJob,
      getAgentTimeline
    });

    expect(screen.getByText('执行失败')).toBeInTheDocument();
    expect(screen.queryByText('翻译服务返回错误')).not.toBeInTheDocument();
    expect(screen.getByText('67%')).toBeInTheDocument();
    expect(screen.getByRole('progressbar', { name: '字幕翻译进度' })).toHaveAttribute(
      'aria-valuetext',
      '失败前进度 67%'
    );
    expect(document.querySelectorAll('.creator-collaboration-spin')).toHaveLength(0);
    await waitFor(() => expect(getAgentTimeline).toHaveBeenCalledTimes(1));
  });

  it('请求刚发送且 Timeline 尚未返回时立即显示唯一工作指示器', async () => {
    const pending = deferred<unknown>();
    const runAgentTurn = vi.fn(() => pending.promise);
    const { container } = renderPanel({
      runAgentTurn,
      getAgentTimeline: vi.fn(async () => emptyTimeline())
    });

    fireEvent.change(screen.getByRole('textbox', { name: '告诉 Agent 你的要求' }), {
      target: { value: '检查任务失败原因' }
    });
    fireEvent.click(screen.getByRole('button', { name: '发送给 Agent' }));

    expect(await screen.findByRole('status', { name: 'Agent 正在工作' })).toBeInTheDocument();
    expect(container.querySelectorAll('.creator-collaboration-working')).toHaveLength(1);

    await act(async () => pending.resolve({ turn: {} }));
  });

  it('将同一 Codex Turn 收拢为一条最终回答', async () => {
    const value = timeline();
    value.turns[1] = {
      ...value.turns[1]!,
      content: '成片已经完成。'
    };
    value.items = [
      {
        ...value.items[0]!,
        id: 'assistant_commentary',
        turnId: value.turns[1]!.id,
        kind: 'assistant_message',
        role: 'assistant',
        text: '我先确认字幕和成片参数。',
        data: { phase: 'commentary' },
        status: 'completed',
        createdAt: '2026-08-21T00:00:03.000Z',
        updatedAt: '2026-08-21T00:00:03.500Z'
      },
      {
        ...value.items[0]!,
        id: 'assistant_final',
        turnId: value.turns[1]!.id,
        kind: 'assistant_message',
        role: 'assistant',
        text: '成片已经完成。',
        data: { phase: 'final_answer' },
        status: 'completed',
        createdAt: '2026-08-21T00:00:05.000Z',
        updatedAt: '2026-08-21T00:00:05.500Z'
      }
    ];

    const { container } = renderPanel({ getAgentTimeline: vi.fn(async () => value) });

    expect(await screen.findByText('成片已经完成。')).toBeInTheDocument();
    expect(screen.queryByText('我先确认字幕和成片参数。')).not.toBeInTheDocument();
    expect(screen.getAllByText('成片已经完成。')).toHaveLength(1);
    expect(container.querySelectorAll(
      '.creator-collaboration-message[data-role="assistant"]'
    )).toHaveLength(1);
  });

  it('兼容没有消息阶段标记的旧 Turn,只显示最后一条回复', async () => {
    const value = timeline();
    value.items = [
      {
        ...value.items[0]!,
        id: 'assistant_legacy_start',
        turnId: value.turns[1]!.id,
        kind: 'assistant_message',
        role: 'assistant',
        text: '我先启动横屏视频合成。',
        data: { type: 'agentMessage' },
        status: 'completed',
        sequence: 3,
        createdAt: '2026-08-21T00:00:03.000Z',
        updatedAt: '2026-08-21T00:00:03.500Z'
      },
      {
        ...value.items[0]!,
        id: 'assistant_legacy_latest',
        turnId: value.turns[1]!.id,
        kind: 'assistant_message',
        role: 'assistant',
        text: '横屏视频正在渲染。',
        data: { type: 'agentMessage' },
        status: 'completed',
        sequence: 8,
        createdAt: '2026-08-21T00:00:05.000Z',
        updatedAt: '2026-08-21T00:00:05.500Z'
      }
    ];

    const { container } = renderPanel({ getAgentTimeline: vi.fn(async () => value) });

    expect(await screen.findByText('横屏视频正在渲染。')).toBeInTheDocument();
    expect(screen.queryByText('我先启动横屏视频合成。')).not.toBeInTheDocument();
    expect(container.querySelectorAll(
      '.creator-collaboration-message[data-role="assistant"]'
    )).toHaveLength(1);
  });
});

function renderPanel(options: {
  language?: 'zh-CN' | 'en-US';
  languageSwitch?: boolean;
  initialJob?: CreatorJob;
  getAgentTimeline: ReturnType<typeof vi.fn>;
  runAgentTurn?: ReturnType<typeof vi.fn>;
  directAction?: ReturnType<typeof vi.fn>;
}) {
  const result = render(
    <LanguageProvider initialPreference={options.language ?? 'zh-CN'}>
      {options.languageSwitch ? <LanguageSwitchControls /> : null}
      <CreatorSessionProvider
        initialJob={options.initialJob ?? job()}
        service={{
          applyAction: vi.fn(),
          runAgentTurn: options.runAgentTurn ?? vi.fn(),
          getAgentTimeline: options.getAgentTimeline
        } as never}
      >
        <VideoTranslationAgentPanel
          stepLabel="翻译设置"
          contextSummary="中文到英文"
          quickActions={[
            {
              id: 'direct',
              label: '打开翻译设置',
              kind: 'action',
              onAction: options.directAction
            },
            {
              id: 'agent',
              label: '让 Agent 检查设置',
              kind: 'agent',
              prompt: '检查设置'
            }
          ]}
        />
      </CreatorSessionProvider>
    </LanguageProvider>
  );
  return result;
}

function timeline(): CreatorAgentTimelineResponse {
  return {
    session: {
      id: 'session_1',
      jobId: 'job_1',
      threadId: 'thread_1',
      runtimeThreadId: 'runtime_thread_1',
      status: 'active' as const,
      hostGeneration: 1,
      createdAt: '2026-08-21T00:00:00.000Z',
      updatedAt: '2026-08-21T00:00:03.000Z',
      interruptedAt: null,
      closedAt: null
    },
    turns: [
      {
        id: 'turn_user',
        jobId: 'job_1',
        sessionId: 'session_1',
        role: 'user' as const,
        content: '请检查当前设置',
        status: 'completed' as const,
        audit: [],
        createdAt: '2026-08-21T00:00:01.000Z'
      },
      {
        id: 'turn_assistant',
        jobId: 'job_1',
        sessionId: 'session_1',
        role: 'assistant' as const,
        content: '### 设置建议\n\n- 先确认目标语言',
        status: 'completed' as const,
        audit: [],
        createdAt: '2026-08-21T00:00:03.000Z'
      }
    ],
    items: [
      {
        id: 'reasoning_1',
        jobId: 'job_1',
        sessionId: 'session_1',
        turnId: 'turn_assistant',
        runtimeItemId: 'runtime_reasoning_1',
        kind: 'reasoning' as const,
        status: 'completed' as const,
        text: 'OpenCreator Context Projection: internal prompt',
        data: { private: true },
        sequence: 1,
        createdAt: '2026-08-21T00:00:02.000Z',
        updatedAt: '2026-08-21T00:00:02.000Z'
      },
      {
        id: 'tool_1',
        jobId: 'job_1',
        sessionId: 'session_1',
        turnId: 'turn_assistant',
        runtimeItemId: 'runtime_tool_1',
        kind: 'tool_call' as const,
        status: 'completed' as const,
        toolName: 'opencreator_tools.creator_get_context',
        data: {},
        sequence: 2,
        createdAt: '2026-08-21T00:00:02.000Z',
        updatedAt: '2026-08-21T00:00:02.000Z'
      }
    ],
    approvals: [{
      id: 'approval_1',
      jobId: 'job_1',
      sessionId: 'session_1',
      turnId: 'turn_assistant',
      itemId: 'tool_1',
      runtimeRequestId: 'runtime_approval_1',
      processGeneration: 1,
      kind: 'tool_call' as const,
      status: 'approved' as const,
      title: '已经处理的工具确认',
      summary: '历史审批不应长期占据对话区',
      details: {},
      requestedAt: '2026-08-21T00:00:02.000Z',
      expiresAt: '2026-08-21T00:05:02.000Z',
      resolvedAt: '2026-08-21T00:00:03.000Z',
      resolutionReason: null
    }],
    lastEventSequence: 2
  };
}

function emptyTimeline(): CreatorAgentTimelineResponse {
  return {
    session: null,
    turns: [],
    items: [],
    approvals: [],
    lastEventSequence: 0
  };
}

function runningTimeline(): CreatorAgentTimelineResponse {
  const value = timeline();
  return {
    ...value,
    turns: [
      value.turns[0]!,
      {
        ...value.turns[1]!,
        content: '',
        status: 'running' as const
      }
    ],
    items: [],
    approvals: []
  };
}

function deferred<T>() {
  let resolve!: (value: T | PromiseLike<T>) => void;
  let reject!: (reason?: unknown) => void;
  const promise = new Promise<T>((resolvePromise, rejectPromise) => {
    resolve = resolvePromise;
    reject = rejectPromise;
  });
  return { promise, resolve, reject };
}

function job(): CreatorJob {
  return {
    id: 'job_1',
    projectId: 'project_1',
    templateId: 'video-translation',
    templateVersion: 1,
    status: 'draft',
    revision: 4,
    presetOrigin: null,
    state: {},
    agentThreadId: null,
    stages: [],
    artifacts: [],
    providerRequests: [],
    activities: [
      {
        id: 'activity_1',
        jobId: 'job_1',
        revision: 1,
        actor: 'user',
        action: 'create-job',
        summary: '创建任务',
        details: {},
        createdAt: '2026-08-21T00:00:00.000Z'
      },
      {
        id: 'activity_2',
        jobId: 'job_1',
        revision: 2,
        actor: 'user',
        action: 'update-settings:draft',
        summary: '工作台设置已同步',
        details: { objectId: 'targetLanguage,bilingual' },
        createdAt: '2026-08-21T00:00:01.000Z'
      },
      {
        id: 'activity_3',
        jobId: 'job_1',
        revision: 3,
        actor: 'user',
        action: 'update-settings:draft',
        summary: '工作台设置已同步',
        details: { objectId: 'bilingual,dubbing' },
        createdAt: '2026-08-21T00:00:02.000Z'
      },
      {
        id: 'activity_4',
        jobId: 'job_1',
        revision: 4,
        actor: 'user',
        action: 'update-settings:draft',
        summary: '当前步骤',
        details: { objectId: 'workspacePhase,resultTab,currentStep' },
        createdAt: '2026-08-21T00:00:03.000Z'
      }
    ],
    createdAt: '2026-08-21T00:00:00.000Z',
    updatedAt: '2026-08-21T00:00:03.000Z'
  };
}