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.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
import type { LocalizeCopy } from '../../i18n/useLocalizedCopy.js';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
import {
ArrowDown,
ArrowUp,
BookOpen,
Check,
ChevronRight,
Clock3,
Copy,
FileText,
FilePenLine,
Globe2,
Image as ImageIcon,
LoaderCircle,
PackageCheck,
Pencil,
ShieldCheck,
ShieldX
} from 'lucide-react';
import {
forwardRef,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso';
import { MarkdownRenderer } from '../markdown/MarkdownRenderer.js';
import { copyToClipboard } from '../markdown/clipboard.js';
import { extractWorkspaceFilePaths, isWorkspaceFilePath } from '../markdown/markdown-inline.js';
import { ApprovalPanel } from '../../features/approvals/ApprovalPanel.js';
import { useAppLanguage } from '../../i18n/LanguageProvider.js';
import type { AppLanguage } from '../../i18n/language.js';
import type { TimelineItem } from './timeline-model.js';
type ProcessTimelineItem = Extract<
TimelineItem,
{ kind: 'reasoning_summary' | 'assistant_message' | 'run_status' | 'tool_step' | 'diagnostic' | 'done' }
>;
type VisibleProcessItem = Extract<
ProcessTimelineItem,
{ kind: 'reasoning_summary' | 'assistant_message' | 'tool_step' | 'diagnostic' | 'done' }
>;
type ProcessDisplayStep = {
key: string;
item: VisibleProcessItem;
title?: string;
liveActivity?: boolean;
activityRunning?: boolean;
milestoneActivity?: string;
milestoneCount?: number;
};
type ProcessBlock = {
type: 'process';
key: string;
runId?: string;
terminalStatus?: string;
approvedCommandExecution?: boolean;
items: ProcessTimelineItem[];
};
type ChangeBlock = {
type: 'changes';
key: string;
runId: string;
items: Array<Extract<TimelineItem, { kind: 'change_card' }>>;
};
type TimelineRenderItem = { type: 'item'; item: TimelineItem } | ProcessBlock | ChangeBlock;
const PROCESS_ELAPSED_LABEL_DELAY_MS = 10_000;
function isProcessTimelineItem(item: TimelineItem, finalAssistantMessageIds: ReadonlySet<string>): item is ProcessTimelineItem {
if (item.kind === 'assistant_message') {
return typeof item.runId === 'string' && item.runId.length > 0 && !finalAssistantMessageIds.has(item.id);
}
if (item.kind === 'diagnostic') return hasRunId(item);
return item.kind === 'reasoning_summary'
|| item.kind === 'run_status'
|| item.kind === 'tool_step'
|| item.kind === 'done';
}
function isInternalRuntimeDiagnostic(item: TimelineItem): boolean {
if (item.kind !== 'diagnostic' || item.severity !== 'warning') return false;
return /skill descriptions were shortened to fit the .*skills context budget/i.test(item.message);
}
function getTimelineTitle(l: LocalizeCopy, item: TimelineItem): string {
switch (item.kind) {
case 'user_message':
return l("你", "you");
case 'schedule_trigger':
return l("定时执行", "Scheduled execution");
case 'assistant_message':
return 'OpenCreator';
case 'change_card':
return l("文件变更", "File changes");
case 'approval':
return l("需要确认", "Need confirmation");
case 'reasoning_summary':
case 'tool_step':
case 'diagnostic':
case 'run_status':
case 'done':
return l("处理过程", "Processing");
default:
const _exhaustive: never = item;
return _exhaustive;
}
}
function getTimelineAvatar(l: LocalizeCopy, item: TimelineItem): string {
if (item.kind === 'user_message') return l("你", "you");
if (item.kind === 'schedule_trigger') return l("定", "Certainly");
if (item.kind === 'change_card') return 'Δ';
if (item.kind === 'assistant_message') return '·';
return '·';
}
function renderTimelineAvatar(l: LocalizeCopy, item: TimelineItem) {
if (item.kind === 'schedule_trigger') {
return <Clock3 aria-hidden="true" size={14} />;
}
return getTimelineAvatar(l, item);
}
function shouldRenderTimelineHeader(item: TimelineItem) {
return item.kind !== 'user_message'
&& item.kind !== 'assistant_message'
&& item.kind !== 'approval';
}
function isProcessComplete(process: ProcessBlock): boolean {
return process.terminalStatus !== undefined || process.items.some(item => item.kind === 'done');
}
function hasFailedOrCanceledDone(process: ProcessBlock): boolean {
return process.items.some(item => item.kind === 'done' && item.status !== 'succeeded');
}
function visibleProcessItems(process: ProcessBlock): VisibleProcessItem[] {
return process.items.filter((item): item is VisibleProcessItem => {
if (item.kind === 'done') return item.status !== 'succeeded';
return item.kind === 'reasoning_summary'
|| item.kind === 'assistant_message'
|| item.kind === 'tool_step'
|| item.kind === 'diagnostic';
});
}
function countVisibleProcessItems(process: ProcessBlock): number {
let count = 0;
for (const item of process.items) {
if (item.kind === 'done') {
if (item.status !== 'succeeded') count += 1;
continue;
}
if (
item.kind === 'reasoning_summary'
|| item.kind === 'assistant_message'
|| item.kind === 'tool_step'
|| item.kind === 'diagnostic'
) {
count += 1;
}
}
return count;
}
function hasVisibleProcessContent(process: ProcessBlock): boolean {
return countVisibleProcessItems(process) > 0;
}
function hasStartedRun(process: ProcessBlock): boolean {
return process.runId !== undefined
&& process.items.some(item => item.kind === 'run_status' && item.label !== 'queued');
}
function shouldRenderProcess(process: ProcessBlock): boolean {
if (process.items.every(item => item.kind === 'run_status' && item.label === 'queued')) {
return false;
}
return hasVisibleProcessContent(process) || !isProcessComplete(process) || hasStartedRun(process);
}
function getProcessDuration(process: ProcessBlock, language: AppLanguage): string | undefined {
const timestamps = process.items.flatMap(item => {
if (item.timestamp === undefined) return [];
const value = Date.parse(item.timestamp);
return Number.isFinite(value) ? [value] : [];
});
if (timestamps.length < 2 || !isProcessComplete(process)) return undefined;
return formatDuration(Math.max(...timestamps) - Math.min(...timestamps), language);
}
function getProcessStartedAt(process: ProcessBlock): number | undefined {
const timestamps = process.items.flatMap(item => {
if (item.timestamp === undefined) return [];
const value = Date.parse(item.timestamp);
return Number.isFinite(value) ? [value] : [];
});
return timestamps.length === 0 ? undefined : Math.min(...timestamps);
}
function formatDuration(durationMs: number, language: AppLanguage): string {
const totalSeconds = Math.max(1, Math.round(durationMs / 1000));
if (language !== 'zh-CN' && language !== 'zh-TW') {
if (totalSeconds < 60) return `${totalSeconds}s`;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes < 60) return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes === 0 ? `${hours}h` : `${hours}h ${remainingMinutes}m`;
}
if (totalSeconds < 60) return `${totalSeconds}秒`;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes < 60) return seconds === 0 ? `${minutes}${language === 'zh-TW' ? '分鐘' : '分钟'}` : `${minutes}分${seconds}秒`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
const hour = language === 'zh-TW' ? '小時' : '小时';
const minute = language === 'zh-TW' ? '分鐘' : '分钟';
return remainingMinutes === 0 ? `${hours}${hour}` : `${hours}${hour}${remainingMinutes}${minute}`;
}
function safeParseJson(content: string): unknown {
try {
return JSON.parse(content);
} catch {
return null;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function getPayloadType(item: ProcessTimelineItem): string | undefined {
if (!('content' in item) || typeof item.content !== 'string') return undefined;
const payload = safeParseJson(item.content);
if (!isRecord(payload)) return undefined;
const type = payload.type;
return typeof type === 'string' ? type : undefined;
}
function getToolCallId(item: ProcessTimelineItem): string | undefined {
if (item.kind !== 'tool_step') return undefined;
const payload = safeParseJson(item.content);
if (!isRecord(payload)) return undefined;
const toolCallId = payload.toolCallId;
return typeof toolCallId === 'string' && toolCallId.length > 0 ? toolCallId : undefined;
}
function getStringField(record: Record<string, unknown>, fieldNames: string[]): string | undefined {
for (const fieldName of fieldNames) {
const value = record[fieldName];
if (typeof value === 'string' && value.trim().length > 0) return value;
}
return undefined;
}
function getStringArgs(record: Record<string, unknown>): string[] {
const args = record.args;
if (!Array.isArray(args)) return [];
return args.filter((arg): arg is string => typeof arg === 'string' && arg.length > 0);
}
function formatCommandArg(arg: string): string {
if (arg.length === 0) return "''";
if (/^[A-Za-z0-9_./:=@%+-]+$/.test(arg)) return arg;
return `'${arg.replace(/'/g, "'\\''")}'`;
}
function formatCommandFromInput(input: Record<string, unknown>): string | undefined {
const command = getStringField(input, ['command', 'cmd']);
const args = getStringArgs(input);
const argsText = args.map(formatCommandArg).join(' ');
if (command !== undefined && argsText.length > 0) return `${command} ${argsText}`;
if (command !== undefined) return command;
if (argsText.length > 0) return argsText;
const raw = input.raw;
if (!isRecord(raw)) return undefined;
return formatCommandFromInput(raw);
}
function getToolCommand(item: Extract<ProcessTimelineItem, { kind: 'tool_step' }>): string | undefined {
const payload = safeParseJson(item.content);
if (!isRecord(payload) || payload.type !== 'tool_use' || !isRecord(payload.input)) return undefined;
return formatCommandFromInput(payload.input);
}
function getToolActivity(
toolName: string,
command?: string
): string {
const normalizedName = toolName.toLocaleLowerCase().split(/[.:/]/u).at(-1) ?? toolName;
if (
normalizedName === 'exec_command'
|| normalizedName === 'command_execution'
|| normalizedName === 'shell'
|| normalizedName === 'bash'
) {
return getCommandActivity(command);
}
if (
normalizedName.includes('apply_patch')
|| normalizedName.includes('edit')
|| normalizedName.includes('write')
) return '修改项目文件';
if (
normalizedName.includes('image')
|| normalizedName.includes('screenshot')
) return '查看图片';
if (
normalizedName.includes('browser')
|| normalizedName.includes('chrome')
|| normalizedName.includes('playwright')
) return '操作浏览器';
if (
normalizedName.includes('web')
|| normalizedName.includes('query')
) return '查询资料';
if (
normalizedName.includes('read')
|| normalizedName.includes('open')
|| normalizedName.includes('find')
|| normalizedName.includes('search')
) return '查看项目内容';
if (
normalizedName.includes('lark')
|| normalizedName.includes('docs')
) return '处理飞书文档';
return '执行开发操作';
}
function getCompletedActivityLabel(activity: string, count = 1): string | undefined {
const label = (() => {
switch (activity) {
case '查看项目内容':
return '已读取文件';
case '查看图片':
return '已查看图片';
case '操作浏览器':
return '已使用浏览器';
case '查询资料':
return '已查询资料';
case '处理飞书文档':
return '已处理飞书文档';
case '修改项目文件':
return '已更新文件';
case '运行测试':
return '已运行测试';
case '打包应用':
return '已打包应用';
case '构建应用':
return '已构建应用';
case '检查代码变更':
return '已检查代码变更';
case '更新代码':
return '已更新代码';
default:
return undefined;
}
})();
if (label === undefined || count === 1) return label;
return `${label}(${count} 次)`;
}
function getCommandActivity(command: string | undefined): string {
if (command === undefined) return '执行本地命令';
const normalized = command.trim().toLocaleLowerCase();
if (
/\b(?:vitest|jest|pytest|go test|cargo test)\b/u.test(normalized)
|| /\b(?:pnpm|npm|yarn)\b[^\n]*\btest\b/u.test(normalized)
) return '运行测试';
if (
/\b(?:electron-builder|package-release)\b/u.test(normalized)
|| /\b(?:pnpm|npm|yarn)\b[^\n]*\bpackage\b/u.test(normalized)
) return '打包应用';
if (
/\b(?:vite build|tsc|electron-builder)\b/u.test(normalized)
|| /\b(?:pnpm|npm|yarn)\b[^\n]*\bbuild\b/u.test(normalized)
) return '构建应用';
if (/^git\s+(?:status|diff|log|show)\b/u.test(normalized)) return '检查代码变更';
if (/^git\s+/u.test(normalized)) return '更新代码';
if (/^(?:rg|grep|sed|cat|ls|find|head|tail|wc|pwd)\b/u.test(normalized)) {
return '查看项目内容';
}
return '执行本地命令';
}
function formatTerminationReason(l: LocalizeCopy, reason: string | undefined): string {
switch (reason) {
case 'timeout':
return l('任务运行时间过长,已自动停止', 'The task exceeded its time limit and was stopped automatically');
case 'inactivity_timeout':
return l('任务长时间无响应,已自动停止', 'The task stopped responding and was stopped automatically');
case 'spawn_timeout':
return l('Codex 启动超时', 'Codex startup timed out');
case 'user_canceled':
return l('用户已取消', 'Canceled by user');
case 'daemon_restart':
return l('服务重启,任务已中断', 'The service restarted and interrupted the task');
case 'codex_exit_non_zero':
return l('Codex 执行失败', 'Codex execution failed');
case 'spawn_failed':
return l('Codex 启动失败', 'Codex failed to start');
case 'stream_error':
return l('Codex 输出异常', 'Codex output error');
case undefined:
return l('未知原因', 'Unknown reason');
default:
return reason;
}
}
function getProcessStepTitle(l: LocalizeCopy, item: ProcessTimelineItem): string {
switch (item.kind) {
case 'reasoning_summary':
case 'assistant_message':
return item.text;
case 'tool_step': {
return getPayloadType(item) === 'tool_result'
? l('操作已完成', 'Operation completed')
: localizeActivityLabel(l, `正在${getToolActivity(item.name, getToolCommand(item))}`);
}
case 'diagnostic':
return item.message;
case 'done':
return item.status === 'canceled'
? l(`运行已取消:${formatTerminationReason(l, item.terminationReason ?? 'user_canceled')}`, `Run canceled: ${formatTerminationReason(l, item.terminationReason ?? 'user_canceled')}`)
: item.status === 'failed'
? formatTerminationReason(l, item.terminationReason)
: '';
case 'run_status':
return '';
default:
const _exhaustive: never = item;
return _exhaustive;
}
}
// Translate generated activity labels after grouping; user-authored messages stay intact.
function localizeActivityLabel(l: LocalizeCopy, title: string): string {
const counted = /^(.*)((\d+) 次)$/.exec(title);
if (counted) {
const label = localizeActivityLabel(l, counted[1]!);
return l(`${label}(${counted[2]} 次)`, `${label} (${counted[2]} times)`);
}
switch (title) {
case '正在查看项目内容': return l(title, 'Reading project files');
case '正在查看图片': return l(title, 'Viewing images');
case '正在操作浏览器': return l(title, 'Using the browser');
case '正在查询资料': return l(title, 'Searching for information');
case '正在处理飞书文档': return l(title, 'Processing Feishu documents');
case '正在修改项目文件': return l(title, 'Updating project files');
case '正在运行测试': return l(title, 'Running tests');
case '正在打包应用': return l(title, 'Packaging the app');
case '正在构建应用': return l(title, 'Building the app');
case '正在检查代码变更': return l(title, 'Reviewing code changes');
case '正在更新代码': return l(title, 'Updating code');
case '正在执行本地命令': return l(title, 'Executing a local command');
case '正在执行开发操作': return l(title, 'Performing a development operation');
case '正在确认执行方案': return l(title, 'Planning the task');
case '正在检查网站可访问性': return l(title, 'Checking website availability');
case '正在读取任务资料': return l(title, 'Reading task information');
case '正在分析任务信息': return l(title, 'Analyzing task information');
case '正在执行任务': return l(title, 'Executing the task');
case '正在获取数据': return l(title, 'Fetching data');
case '已读取文件': return l(title, 'Files read');
case '已查看图片': return l(title, 'Images viewed');
case '已使用浏览器': return l(title, 'Browser used');
case '已查询资料': return l(title, 'Information retrieved');
case '已处理飞书文档': return l(title, 'Feishu documents processed');
case '已更新文件': return l(title, 'Files updated');
case '已运行测试': return l(title, 'Tests run');
case '已打包应用': return l(title, 'App packaged');
case '已构建应用': return l(title, 'App built');
case '已检查代码变更': return l(title, 'Code changes reviewed');
case '已更新代码': return l(title, 'Code updated');
case '已允许并执行本地命令': return l(title, 'Local command approved and executed');
case '已执行本地命令': return l(title, 'Local command executed');
case '已执行开发操作': return l(title, 'Development operation completed');
default: return title;
}
}
function getTransientProcessActivity(item: VisibleProcessItem): string | undefined {
if (item.kind !== 'reasoning_summary' && item.kind !== 'assistant_message') return undefined;
const text = item.text.trim();
if (text.length === 0 || text.length > 80 || text.includes('\n')) return undefined;
if (/^正在\S/.test(text)) return text;
if (/^planning\b/i.test(text)) return '正在确认执行方案';
if (/^inspect(?:ing)?\b.*\b(?:site|website)\b/i.test(text)) return '正在检查网站可访问性';
if (/^read(?:ing)?\b/i.test(text)) return '正在读取任务资料';
if (/^search(?:ing)?\b/i.test(text)) return '正在查询资料';
if (/^(?:check(?:ing)?|review(?:ing)?|analyz(?:ing)?)\b/i.test(text)) return '正在分析任务信息';
if (/^(?:run(?:ning)?|execut(?:ing)?)\b/i.test(text)) return '正在执行任务';
if (/^fetch(?:ing)?\b/i.test(text)) return '正在获取数据';
return undefined;
}
function buildVisibleProcessSteps(process: ProcessBlock): ProcessDisplayStep[] {
const completedToolCallIds = new Set<string>();
const toolUsesByCallId = new Map<string, Extract<ProcessTimelineItem, { kind: 'tool_step' }>>();
const hasTerminalFailure = process.items.some(item => (
item.kind === 'done' && item.status !== 'succeeded'
));
let latestTransientActivity: { index: number; item: VisibleProcessItem; title: string } | undefined;
for (const item of process.items) {
if (item.kind !== 'tool_step') continue;
const toolCallId = getToolCallId(item);
if (toolCallId === undefined) continue;
const payloadType = getPayloadType(item);
if (payloadType === 'tool_use') toolUsesByCallId.set(toolCallId, item);
if (payloadType === 'tool_result') completedToolCallIds.add(toolCallId);
}
const steps: ProcessDisplayStep[] = [];
for (const item of visibleProcessItems(process)) {
if (hasTerminalFailure && item.kind === 'diagnostic') continue;
if (item.kind !== 'tool_step') {
const transientActivity = getTransientProcessActivity(item);
if (transientActivity !== undefined) {
latestTransientActivity = {
index: process.items.indexOf(item),
item,
title: transientActivity
};
continue;
}
steps.push({ key: item.id, item });
continue;
}
if (getPayloadType(item) !== 'tool_result') continue;
const toolCallId = getToolCallId(item);
const toolUse = toolCallId === undefined ? undefined : toolUsesByCallId.get(toolCallId);
if (toolUse === undefined) continue;
const activity = getToolActivity(toolUse.name, getToolCommand(toolUse));
if (getProcessCompletedActivityLabel(process, activity) === undefined) continue;
const previous = steps.at(-1);
if (previous?.milestoneActivity === activity) {
previous.milestoneCount = (previous.milestoneCount ?? 1) + 1;
previous.title = getProcessCompletedActivityLabel(process, activity, previous.milestoneCount);
continue;
}
steps.push({
key: `milestone:${toolUse.id}`,
item: toolUse,
title: getProcessCompletedActivityLabel(process, activity),
milestoneActivity: activity,
milestoneCount: 1
});
}
if (isProcessComplete(process)) return steps;
let latestToolUse: Extract<ProcessTimelineItem, { kind: 'tool_step' }> | undefined;
let latestToolUseIndex = -1;
for (let index = process.items.length - 1; index >= 0; index -= 1) {
const item = process.items[index];
if (item?.kind !== 'tool_step' || getPayloadType(item) !== 'tool_use') continue;
latestToolUse = item;
latestToolUseIndex = index;
break;
}
if (
latestTransientActivity !== undefined
&& latestTransientActivity.index > latestToolUseIndex
) {
steps.push({
key: `live:${latestTransientActivity.item.id}`,
item: latestTransientActivity.item,
title: latestTransientActivity.title,
liveActivity: true,
activityRunning: true
});
return steps;
}
if (latestToolUse === undefined) return steps;
const toolCallId = getToolCallId(latestToolUse);
const activity = getToolActivity(latestToolUse.name, getToolCommand(latestToolUse));
const activityRunning = toolCallId === undefined || !completedToolCallIds.has(toolCallId);
if (!activityRunning && getProcessCompletedActivityLabel(process, activity) !== undefined) return steps;
steps.push({
key: `live:${latestToolUse.id}`,
item: latestToolUse,
title: `${activityRunning ? '正在' : '已'}${activity}`,
liveActivity: true,
activityRunning
});
return steps;
}
function getProcessCompletedActivityLabel(
process: ProcessBlock,
activity: string,
count = 1
): string | undefined {
if (activity === '执行本地命令' && process.approvedCommandExecution === true) {
return count === 1 ? '已允许并执行本地命令' : `已允许并执行本地命令(${count} 次)`;
}
return getCompletedActivityLabel(activity, count);
}
function hasRunId(item: ProcessTimelineItem): item is ProcessTimelineItem & { runId: string } {
return typeof item.runId === 'string' && item.runId.length > 0;
}
function getRunId(item: TimelineItem): string | undefined {
if (!('runId' in item)) return undefined;
return typeof item.runId === 'string' && item.runId.length > 0 ? item.runId : undefined;
}
function isTerminalTimelineRunStatus(status: string | undefined): boolean {
return status === 'succeeded' || status === 'failed' || status === 'canceled';
}
function collectTerminalRunStatuses(items: TimelineItem[]): Map<string, string> {
const statuses = new Map<string, string>();
for (const item of items) {
if (
item.kind === 'user_message'
&& item.runId !== undefined
&& isTerminalTimelineRunStatus(item.runStatus)
) {
statuses.set(item.runId, item.runStatus as string);
}
if (item.kind === 'done' && item.runId !== undefined) {
statuses.set(item.runId, item.status);
}
}
return statuses;
}
function collectFinalAssistantMessageIds(
items: TimelineItem[],
terminalRunStatuses: ReadonlyMap<string, string>
): Set<string> {
const runStates = new Map<string, { doneStatus?: string; lastAssistantMessageId?: string }>();
for (const item of items) {
const runId = getRunId(item);
if (runId === undefined) continue;
const state = runStates.get(runId) ?? {};
if (item.kind === 'assistant_message') state.lastAssistantMessageId = item.id;
if (item.kind === 'done') state.doneStatus = item.status;
runStates.set(runId, state);
}
const finalAssistantMessageIds = new Set<string>();
for (const state of runStates.values()) {
if (state.doneStatus === 'succeeded' && state.lastAssistantMessageId !== undefined) {
finalAssistantMessageIds.add(state.lastAssistantMessageId);
}
}
for (const [runId, status] of terminalRunStatuses) {
if (status !== 'succeeded') continue;
const lastAssistantMessageId = runStates.get(runId)?.lastAssistantMessageId;
if (lastAssistantMessageId !== undefined) finalAssistantMessageIds.add(lastAssistantMessageId);
}
return finalAssistantMessageIds;
}
function buildTimelineRenderItems(items: TimelineItem[]): TimelineRenderItem[] {
const renderItems: TimelineRenderItem[] = [];
const processByKey = new Map<string, ProcessBlock>();
let currentProcessKey: string | undefined;
const terminalRunStatuses = collectTerminalRunStatuses(items);
const finalAssistantMessageIds = collectFinalAssistantMessageIds(items, terminalRunStatuses);
const completedCommandRunIds = collectCompletedCommandRunIds(items);
const approvedCommandRunIds = new Set(items.flatMap(item => (
item.kind === 'approval'
&& item.approval.status === 'approved'
&& item.approval.kind === 'command_execution'
&& completedCommandRunIds.has(item.runId)
? [item.runId]
: []
)));
function getCurrentProcess(): ProcessBlock | undefined {
if (currentProcessKey === undefined) return undefined;
return processByKey.get(currentProcessKey);
}
function createProcess(key: string, runId?: string): ProcessBlock {
const process: ProcessBlock = {
type: 'process',
key,
runId,
terminalStatus: runId === undefined ? undefined : terminalRunStatuses.get(runId),
approvedCommandExecution: runId === undefined ? false : approvedCommandRunIds.has(runId),
items: []
};
processByKey.set(key, process);
renderItems.push(process);
return process;
}
function renameCurrentOrphanProcess(nextKey: string, runId: string): ProcessBlock | undefined {
const current = getCurrentProcess();
if (current === undefined || current.runId !== undefined || isProcessComplete(current)) return undefined;
processByKey.delete(current.key);
current.key = nextKey;
current.runId = runId;
current.approvedCommandExecution = approvedCommandRunIds.has(runId);
processByKey.set(nextKey, current);
currentProcessKey = nextKey;
return current;
}
for (const item of items) {
if (
item.kind === 'approval'
&& item.approval.status === 'approved'
&& item.approval.kind === 'command_execution'
&& approvedCommandRunIds.has(item.runId)
) continue;
const itemRunId = getRunId(item);
if (
item.kind === 'assistant_message'
&& itemRunId !== undefined
&& finalAssistantMessageIds.has(item.id)
&& !processByKey.has(`run:${itemRunId}`)
) {
createProcess(`run:${itemRunId}`, itemRunId);
}
if (!isProcessTimelineItem(item, finalAssistantMessageIds)) {
if (item.kind === 'change_card' && item.runId !== undefined) {
const previous = renderItems.at(-1);
if (previous?.type === 'changes' && previous.runId === item.runId) {
previous.items.push(item);
continue;
}
renderItems.push({
type: 'changes',
key: `changes:${item.runId}:${item.id}`,
runId: item.runId,
items: [item]
});
continue;
}
renderItems.push({ type: 'item', item });
continue;
}
let key: string;
let process: ProcessBlock | undefined;
if (hasRunId(item)) {
key = `run:${item.runId}`;
process = processByKey.get(key) ?? renameCurrentOrphanProcess(key, item.runId);
if (process === undefined) process = createProcess(key, item.runId);
} else {
const current = getCurrentProcess();
if (current !== undefined && !isProcessComplete(current)) {
key = current.key;
process = current;
} else {
key = `process:${item.id}`;
process = createProcess(key);
}
}
process.items.push(item);
currentProcessKey = item.kind === 'done' ? undefined : key;
}
return renderItems;
}
function collectCompletedCommandRunIds(items: TimelineItem[]): Set<string> {
const commandUsesByCallId = new Map<string, string>();
const completedRunIds = new Set<string>();
for (const item of items) {
if (item.kind !== 'tool_step') continue;
const toolCallId = getToolCallId(item);
const runId = getRunId(item);
if (toolCallId === undefined || runId === undefined) continue;
const callKey = `${runId}:${toolCallId}`;
const payloadType = getPayloadType(item);
if (payloadType === 'tool_use' && getToolActivity(item.name, getToolCommand(item)) === '执行本地命令') {
commandUsesByCallId.set(callKey, runId);
continue;
}
if (payloadType !== 'tool_result') continue;
const completedRunId = commandUsesByCallId.get(callKey);
if (completedRunId !== undefined) completedRunIds.add(completedRunId);
}
return completedRunIds;
}
function renderMessageContent(l: LocalizeCopy,
item: Extract<TimelineItem, { kind: 'user_message' | 'assistant_message' }>,
onOpenFile?: (path: string) => void,
onEditUserMessage?: (item: Extract<TimelineItem, { kind: 'user_message' }>) => void
) {
const canOpenWorkspaceFiles = item.kind === 'assistant_message' && onOpenFile !== undefined;
const artifacts = canOpenWorkspaceFiles
? extractWorkspaceFilePaths(item.text).filter(isDeliverableArtifact)
: [];
return (
<>
{item.kind === 'user_message' && (item.attachments?.length ?? 0) > 0 ? (
<div className="timeline-message-attachments">
{item.attachments?.map(attachment => {
const previewUrl = item.attachmentPreviewUrls?.[attachment.id];
return (
<figure key={attachment.id}>
{previewUrl ? <img src={previewUrl} alt={attachment.fileName} /> : null}
<figcaption>
<strong>{attachment.fileName}</strong>
<span>{formatAttachmentSize(attachment.size)}</span>
</figcaption>
</figure>
);
})}
</div>
) : null}
<MarkdownRenderer
text={item.text}
variant={item.kind === 'user_message' ? 'user' : 'assistant'}
linkifyWorkspaceFiles={canOpenWorkspaceFiles}
onLinkClick={canOpenWorkspaceFiles
? (href, event) => {
if (!isWorkspaceFilePath(href)) return;
event.preventDefault();
onOpenFile(href);
}
: undefined}
/>
{artifacts.length > 0 ? (
<div className="timeline-artifacts" aria-label={l("任务成果", "Mission results")}>
{artifacts.map(path => (
<button
key={path}
type="button"
className="timeline-artifact-card"
aria-label={l(`打开成果 ${path}`, `Open results ${path}`)}
onClick={() => onOpenFile?.(path)}
>
<FileText aria-hidden="true" size={17} />
<span className="timeline-artifact-copy">
<strong>{artifactFileName(path)}</strong>
<span>{artifactTypeLabel(l, path)}</span>
</span>
<span className="timeline-artifact-action">{l("打开", "Open")}</span>
</button>
))}
</div>
) : null}
</>
);
}
const DELIVERABLE_ARTIFACT_EXTENSIONS = new Set([
'csv', 'doc', 'docx', 'html', 'htm', 'md', 'markdown', 'pdf', 'ppt', 'pptx', 'xls', 'xlsx'
]);
function artifactExtension(path: string): string {
return path.split('.').at(-1)?.toLowerCase() ?? '';
}
function isDeliverableArtifact(path: string): boolean {
return DELIVERABLE_ARTIFACT_EXTENSIONS.has(artifactExtension(path));
}
function artifactFileName(path: string): string {
return path.split('/').at(-1) ?? path;
}
function artifactTypeLabel(l: LocalizeCopy, path: string): string {
switch (artifactExtension(path)) {
case 'html':
case 'htm':
return l("HTML 报告", "HTML report");
case 'pdf':
return l("PDF 文档", "PDF document");
case 'doc':
case 'docx':
return l("Word 文档", "Word document");
case 'xls':
case 'xlsx':
return l("Excel 表格", "Excel table");
case 'ppt':
case 'pptx':
return l("演示文稿", "presentation");
case 'csv':
return l("数据表", "data sheet");
default:
return l("文档", "document");
}
}
function renderResolvedApproval(l: LocalizeCopy, approval: Extract<TimelineItem, { kind: 'approval' }>['approval']) {
const approved = approval.status === 'approved';
const Icon = approved ? ShieldCheck : ShieldX;
return (
<div className="approval-resolution-row">
<Icon aria-hidden="true" size={14} />
<span>{formatApprovalResolution(approval)}</span>
</div>
);
}
function formatApprovalResolution(approval: Extract<TimelineItem, { kind: 'approval' }>['approval']): string {
const prefix = (() => {
switch (approval.status) {
case 'approved':
return '已允许';
case 'rejected':
return '已拒绝';
case 'expired':
return '权限申请已过期';
case 'canceled':
return '权限申请已取消';
case 'pending':
return '等待批准';
}
})();
if (approval.status === 'expired' || approval.status === 'canceled') return prefix;
if (approval.kind === 'permissions') {
const network = isRecord(approval.details.network) ? approval.details.network : undefined;
const host = typeof network?.host === 'string' ? network.host : undefined;
return host ? `${prefix}访问 ${host}` : `${prefix}获取权限`;
}
if (approval.kind === 'file_change') return `${prefix}修改文件`;
return `${prefix}执行命令`;
}
function MessageMeta(props: {
item: Extract<TimelineItem, { kind: 'user_message' | 'assistant_message' }>;
latestAssistant?: boolean;
onEdit?: (item: Extract<TimelineItem, { kind: 'user_message' }>) => void;
}) {
const l = useLocalizedCopy();
const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle');
const { language } = useAppLanguage();
const itemLabel = props.item.kind === 'assistant_message' ? l('回复', 'response') : l('消息', 'message');
const timestamp = props.item.timestamp ? (
<time dateTime={props.item.timestamp}>{formatMessageTime(props.item.timestamp, language)}</time>
) : null;
const copyButton = (
<button
type="button"
aria-label={
copyState === 'copied'
? l(`已复制${itemLabel}`, `Copied ${itemLabel}`)
: copyState === 'failed'
? l(`复制${itemLabel}失败`, `Failed to copy ${itemLabel}`)
: l(`复制${itemLabel}`, `Copy ${itemLabel}`)
}
title={copyState === 'copied' ? l("已复制", "Copied") : copyState === 'failed' ? l("复制失败", "Copy failed") : l("复制", "copy")}
onClick={async () => {
setCopyState(await copyToClipboard(props.item.text) ? 'copied' : 'failed');
}}
>
{copyState === 'copied' ? (
<Check size={14} aria-hidden="true" />
) : (
<Copy size={14} aria-hidden="true" />
)}
</button>
);
return (
<div className={`timeline-message-meta${props.latestAssistant ? ' is-latest-assistant' : ''}`}>
{props.item.kind === 'assistant_message' ? copyButton : timestamp}
{props.item.kind === 'assistant_message' ? timestamp : copyButton}
{props.item.kind === 'user_message' && props.onEdit ? (
<button
type="button"
aria-label={l("编辑消息", "Edit message")}
title={l("编辑", "Edit")}
onClick={() => {
if (props.item.kind === 'user_message') props.onEdit?.(props.item);
}}
>
<Pencil size={14} aria-hidden="true" />
</button>
) : null}
</div>
);
}
function formatMessageTime(value: string, language: AppLanguage): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(language, {
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
hour12: false
}).format(date);
}
function ScheduleTriggerContent(props: { item: Extract<TimelineItem, { kind: 'schedule_trigger' }> }) {
const { item } = props;
const { language } = useAppLanguage();
return (
<div className="timeline-schedule-trigger-content">
<time dateTime={item.triggeredAt}>{formatScheduleTriggerTime(item.triggeredAt, language)}</time>
<MarkdownRenderer text={item.prompt} variant="user" />
</div>
);
}
function formatScheduleTriggerTime(value: string, language: AppLanguage): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(language, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false
}).format(date);
}
function formatAttachmentSize(size: number): string {
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${Math.ceil(size / 1024)} KB`;
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}
function renderChangeCard(l: LocalizeCopy, item: Extract<TimelineItem, { kind: 'change_card' }>, onOpenFile?: (path: string) => void) {
const content = (
<>
<strong>{item.title}</strong>
<span>{item.path}</span>
<code>{item.delta}</code>
{onOpenFile ? <span className="change-card-action">{l("打开", "Open")}</span> : null}
</>
);
if (onOpenFile) {
return (
<button
type="button"
className="change-card-content change-card-button"
aria-label={l(`打开文件 ${item.path}`, `Open file ${item.path}`)}
onClick={() => onOpenFile(item.path)}
>
{content}
</button>
);
}
return (
<div className="change-card-content">
{content}
</div>
);
}
function renderChangeBlock(l: LocalizeCopy,
block: ChangeBlock,
onOpenFile?: (path: string) => void
) {
if (block.items.length === 1) {
return renderChangeCard(l, block.items[0]!, onOpenFile);
}
const paths = [...new Set(block.items.map(item => item.path))];
const visiblePaths = paths.slice(0, 3);
const hiddenCount = paths.length - visiblePaths.length;
return (
<div className="change-card-content change-card-group">
<strong>{l(`${block.items.length} 次连续文件变更`, `${block.items.length} consecutive file changes`)}</strong>
<span>{l(`${paths.length} 个文件`, `${paths.length} files`)}</span>
<div className="change-card-paths">
{visiblePaths.map(path => (
onOpenFile ? (
<button
key={path}
type="button"
className="change-card-path-button"
aria-label={l(`打开文件 ${path}`, `Open file ${path}`)}
onClick={() => onOpenFile(path)}
>
{path}
</button>
) : (
<code key={path}>{path}</code>
)
))}
{hiddenCount > 0 ? <span>{l(`另有 ${hiddenCount} 个文件`, `${hiddenCount} more files`)}</span> : null}
</div>
</div>
);
}
function renderTimelineItemContent(l: LocalizeCopy,
item: TimelineItem,
onOpenFile?: (path: string) => void,
onEditUserMessage?: (item: Extract<TimelineItem, { kind: 'user_message' }>) => void,
approvalState?: {
resolving?: boolean;
error?: string;
onApprove(id: string): void;
onReject(id: string): void;
}
) {
switch (item.kind) {
case 'user_message':
case 'assistant_message':
return renderMessageContent(l, item, onOpenFile, onEditUserMessage);
case 'schedule_trigger':
return <ScheduleTriggerContent item={item} />;
case 'change_card':
return renderChangeCard(l, item, onOpenFile);
case 'approval':
if (item.approval.status !== 'pending') return renderResolvedApproval(l, item.approval);
return approvalState === undefined ? null : (
<ApprovalPanel
approval={item.approval}
resolving={approvalState.resolving}
error={approvalState.error}
onApprove={approvalState.onApprove}
onReject={approvalState.onReject}
/>
);
case 'diagnostic':
return (
<div className="timeline-diagnostic-content">
<div className="process-step-row">
<span className={`process-step-severity ${item.severity}`}>{item.severity}</span>
<span className="process-step-title">{item.message}</span>
</div>
</div>
);
case 'reasoning_summary':
case 'tool_step':
case 'run_status':
case 'done':
return null;
default:
const _exhaustive: never = item;
return _exhaustive;
}
}
function renderProcessStep(l: LocalizeCopy, step: ProcessDisplayStep) {
const { item } = step;
if (step.liveActivity && (item.kind === 'reasoning_summary' || item.kind === 'assistant_message')) {
return (
<li
key={step.key}
className={`process-step process-step-${item.kind} is-live-activity`}
aria-live="polite"
>
<div className="process-step-row">
<LoaderCircle className="process-live-activity-icon is-running" aria-hidden="true" size={13} />
<div className="process-live-activity-text">
<MarkdownRenderer text={step.title ? localizeActivityLabel(l, step.title) : item.text} variant="process" />
</div>
</div>
</li>
);
}
if (!step.liveActivity && (item.kind === 'reasoning_summary' || item.kind === 'assistant_message')) {
return (
<li key={step.key} className={`process-step process-step-${item.kind}`}>
<div className="process-reasoning-text">
<MarkdownRenderer text={item.text} variant="process" />
</div>
</li>
);
}
return (
<li
key={step.key}
className={`process-step process-step-${item.kind}${step.liveActivity ? ' is-live-activity' : ''}`}
aria-live={step.liveActivity ? 'polite' : undefined}
>
<div className="process-step-row">
{step.liveActivity ? (
step.activityRunning ? (
<LoaderCircle className="process-live-activity-icon is-running" aria-hidden="true" size={13} />
) : (
<Check className="process-live-activity-icon" aria-hidden="true" size={13} />
)
) : null}
{step.milestoneActivity ? renderMilestoneIcon(step.milestoneActivity) : null}
{item.kind === 'diagnostic' ? <span className={`process-step-severity ${item.severity}`}>{item.severity}</span> : null}
<span className="process-step-title">
{step.title ? localizeActivityLabel(l, step.title) : getProcessStepTitle(l, item)}
</span>
</div>
</li>
);
}
function renderMilestoneIcon(activity: string) {
const props = { className: 'process-milestone-icon', 'aria-hidden': true, size: 14 } as const;
switch (activity) {
case '查看项目内容':
case '处理飞书文档':
return <BookOpen {...props} />;
case '查询资料':
case '操作浏览器':
return <Globe2 {...props} />;
case '查看图片':
return <ImageIcon {...props} />;
case '修改项目文件':
return <FilePenLine {...props} />;
case '运行测试':
case '构建应用':
case '打包应用':
return <PackageCheck {...props} />;
default:
return <Check {...props} />;
}
}
function ProcessBlockView(props: {
process: ProcessBlock;
expanded: boolean;
targeted?: boolean;
onExpandedChange(expanded: boolean): void;
}) {
const { process, expanded, onExpandedChange } = props;
const { language, t } = useAppLanguage();
const l = useLocalizedCopy();
const complete = isProcessComplete(process);
const duration = getProcessDuration(process, language);
const fallbackStartedAtRef = useRef({ key: process.key, value: Date.now() });
if (fallbackStartedAtRef.current.key !== process.key) {
fallbackStartedAtRef.current = { key: process.key, value: Date.now() };
}
const startedAt = getProcessStartedAt(process) ?? fallbackStartedAtRef.current.value;
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (complete) return;
setNow(Date.now());
const intervalId = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(intervalId);
}, [complete, process.key]);
const activeDurationMs = Math.max(0, now - startedAt);
const summaryLabel = complete
? duration === undefined ? t('timeline.process.completed') : t('timeline.process.elapsed', { duration })
: activeDurationMs >= PROCESS_ELAPSED_LABEL_DELAY_MS
? t('timeline.process.elapsed', { duration: formatDuration(activeDurationMs, language) })
: t('timeline.process.thinking');
const steps = expanded ? buildVisibleProcessSteps(process) : [];
return (
<article
className={`timeline-item timeline-process${complete ? ' is-complete' : ''}`}
data-search-target={props.targeted ? 'true' : undefined}
>
<details
open={expanded}
>
<summary
onClick={event => {
event.preventDefault();
onExpandedChange(!expanded);
}}
>
{!complete && activeDurationMs < PROCESS_ELAPSED_LABEL_DELAY_MS ? (
<LoaderCircle className="process-summary-spinner" aria-hidden="true" size={14} />
) : null}
<span className="process-summary-label">
{summaryLabel}
</span>
{complete ? (
<ChevronRight className="process-summary-chevron" aria-hidden="true" size={13} />
) : null}
</summary>
{expanded && steps.length > 0 ? (
<div className="process-detail">
<ol className="process-steps">{steps.map(step => renderProcessStep(l, step))}</ol>
</div>
) : null}
</details>
</article>
);
}
export type TimelineHandle = {
scrollBy(deltaY: number): boolean;
};
type TimelineProps = {
items: TimelineItem[];
targetItemId?: string;
targetRunId?: string;
targetApprovalId?: string;
hasMore?: boolean;
loadingOlder?: boolean;
onLoadOlder?(): Promise<void> | void;
onOpenFile?(path: string): void;
onEditUserMessage?(item: Extract<TimelineItem, { kind: 'user_message' }>): void;
resolvingApprovalIds?: ReadonlySet<string>;
approvalErrors?: Readonly<Record<string, string | undefined>>;
onApproveApproval?(id: string): void;
onRejectApproval?(id: string): void;
};
export const Timeline = forwardRef<TimelineHandle, TimelineProps>(function Timeline(props, ref) {
const l = useLocalizedCopy();
const virtuosoRef = useRef<VirtuosoHandle>(null);
const atBottomRef = useRef(true);
const userInteractedRef = useRef(false);
const previousItemIdsRef = useRef<string[]>([]);
const previousRenderItemCountRef = useRef(0);
const firstItemIndexRef = useRef(100_000);
const [atBottom, setAtBottom] = useState(true);
const [hasNewContent, setHasNewContent] = useState(false);
const [processExpansionOverrides, setProcessExpansionOverrides] = useState<Record<string, boolean>>({});
useImperativeHandle(ref, () => ({
scrollBy(deltaY) {
const virtuoso = virtuosoRef.current;
if (virtuoso === null) return false;
userInteractedRef.current = true;
virtuoso.scrollBy({ top: deltaY, behavior: 'auto' });
return true;
}
}), []);
const renderItems = useMemo(
() => buildTimelineRenderItems(props.items.filter(item => !isInternalRuntimeDiagnostic(item))).filter(item => {
if (item.type === 'process') return shouldRenderProcess(item);
if (
item.type === 'item'
&& item.item.kind === 'approval'
&& item.item.approval.status === 'pending'
) return false;
return !(
item.type === 'item'
&& item.item.kind === 'user_message'
&& (
item.item.runStatus === 'queued'
|| (item.item.runStatus === 'canceled' && item.item.wasQueued === true)
)
);
}),
[props.items]
);
const latestAssistantMessageId = useMemo(() => {
for (let index = renderItems.length - 1; index >= 0; index -= 1) {
const renderItem = renderItems[index];
if (
renderItem?.type === 'item'
&& renderItem.item.kind === 'assistant_message'
) {
return renderItem.item.id;
}
}
return undefined;
}, [renderItems]);
const targetRenderItemIndex = useMemo(
() => renderItems.findIndex(item => renderItemMatchesTarget(
item,
props.targetItemId,
props.targetRunId,
props.targetApprovalId
)),
[props.targetApprovalId, props.targetItemId, props.targetRunId, renderItems]
);
const itemIds = props.items.map(item => item.id);
const previousItemIds = previousItemIdsRef.current;
const previousRenderItemCount = previousRenderItemCountRef.current;
if (
previousItemIds.length > 0
&& itemIds.length > previousItemIds.length
&& hasSuffix(itemIds, previousItemIds)
) {
const prependedRenderItemCount = renderItems.length - previousRenderItemCount;
if (prependedRenderItemCount > 0) {
firstItemIndexRef.current -= prependedRenderItemCount;
}
} else if (
previousItemIds.length > 0
&& itemIds.length > 0
&& !hasPrefix(itemIds, previousItemIds)
) {
firstItemIndexRef.current = 100_000;
}
previousItemIdsRef.current = itemIds;
previousRenderItemCountRef.current = renderItems.length;
useEffect(() => {
const appended =
previousItemIds.length > 0
&& itemIds.length > previousItemIds.length
&& hasPrefix(itemIds, previousItemIds);
if (appended && !atBottomRef.current) setHasNewContent(true);
}, [itemIds, previousItemIds]);
useEffect(() => {
if (targetRenderItemIndex < 0) return;
virtuosoRef.current?.scrollToIndex({
index: targetRenderItemIndex,
align: 'center',
behavior: 'auto'
});
}, [
props.targetApprovalId,
props.targetItemId,
props.targetRunId,
targetRenderItemIndex
]);
function loadOlder() {
if (!props.hasMore || props.loadingOlder || props.onLoadOlder === undefined) return;
void props.onLoadOlder();
}
function scrollToLatest() {
if (renderItems.length === 0) return;
virtuosoRef.current?.scrollToIndex({
index: renderItems.length - 1,
align: 'end',
behavior: 'smooth'
});
setHasNewContent(false);
}
return (
<div className="timeline-list">
{props.items.length === 0 ? (
<div className="timeline-empty">
<strong>{l("暂无任务记录", "No task record yet")}</strong>
<span>{l("发送任务后,OpenCreator 会在这里展示处理过程和结果。", "After sending the task, OpenCreator will display the processing process and results here.")}</span>
</div>
) : (
<div
className="timeline-virtual-shell"
onWheel={() => {
userInteractedRef.current = true;
}}
onTouchMove={() => {
userInteractedRef.current = true;
}}
onKeyDown={() => {
userInteractedRef.current = true;
}}
>
<Virtuoso
ref={virtuosoRef}
className="timeline-virtuoso"
data={renderItems}
firstItemIndex={firstItemIndexRef.current}
defaultItemHeight={120}
initialTopMostItemIndex={{
index: targetRenderItemIndex < 0 ? 'LAST' : targetRenderItemIndex,
align: targetRenderItemIndex < 0 ? 'end' : 'center'
}}
computeItemKey={(_index, item) => getRenderItemKey(item)}
followOutput={isAtBottom => isAtBottom ? 'auto' : false}
atBottomStateChange={nextAtBottom => {
atBottomRef.current = nextAtBottom;
setAtBottom(nextAtBottom);
if (nextAtBottom) setHasNewContent(false);
}}
atTopStateChange={nextAtTop => {
if (nextAtTop && userInteractedRef.current) loadOlder();
}}
components={{
Header: () => (
<div className="timeline-load-older">
{props.hasMore ? (
<button
type="button"
className="inline-action"
disabled={props.loadingOlder}
onClick={loadOlder}
>
{props.loadingOlder ? (
<LoaderCircle className="spin" aria-hidden="true" size={14} />
) : (
<ArrowUp aria-hidden="true" size={14} />
)}
<span>{props.loadingOlder ? l("正在加载更早记录", "Loading older records") : l("加载更早记录", "Load older records")}</span>
</button>
) : null}
</div>
),
Footer: () => <div className="timeline-end-spacer" aria-hidden="true" />
}}
itemContent={(_index, renderItem) => (
<div className="timeline-virtual-item">
{renderTimelineRenderItem(l,
renderItem,
props.targetItemId,
props.targetRunId,
props.targetApprovalId,
props.onOpenFile,
props.onEditUserMessage,
props.resolvingApprovalIds,
props.approvalErrors,
props.onApproveApproval,
props.onRejectApproval,
latestAssistantMessageId,
renderItem.type === 'process'
? processExpansionOverrides[renderItem.key]
: undefined,
(processKey, expanded) => {
setProcessExpansionOverrides(current => ({
...current,
[processKey]: expanded
}));
}
)}
</div>
)}
/>
{!atBottom && hasNewContent ? (
<button
type="button"
className="timeline-new-content"
onClick={scrollToLatest}
>
<ArrowDown aria-hidden="true" size={15} />
<span>{l("有新内容", "There is new content")}</span>
</button>
) : null}
</div>
)}
</div>
);
});
function renderTimelineRenderItem(l: LocalizeCopy,
renderItem: TimelineRenderItem,
targetItemId?: string,
targetRunId?: string,
targetApprovalId?: string,
onOpenFile?: (path: string) => void,
onEditUserMessage?: (item: Extract<TimelineItem, { kind: 'user_message' }>) => void,
resolvingApprovalIds?: ReadonlySet<string>,
approvalErrors?: Readonly<Record<string, string | undefined>>,
onApproveApproval?: (id: string) => void,
onRejectApproval?: (id: string) => void,
latestAssistantMessageId?: string,
processExpansionOverride?: boolean,
onProcessExpandedChange?: (processKey: string, expanded: boolean) => void
) {
if (renderItem.type === 'process') {
const defaultExpanded = !isProcessComplete(renderItem) || hasFailedOrCanceledDone(renderItem);
return (
<ProcessBlockView
process={renderItem}
expanded={processExpansionOverride ?? defaultExpanded}
targeted={renderItemMatchesTarget(
renderItem,
targetItemId,
targetRunId,
targetApprovalId
)}
onExpandedChange={expanded => onProcessExpandedChange?.(renderItem.key, expanded)}
/>
);
}
if (renderItem.type === 'changes') {
return (
<article
className="timeline-item timeline-change_card"
data-search-target={renderItemMatchesTarget(
renderItem,
targetItemId,
targetRunId,
targetApprovalId
) ? 'true' : undefined}
>
<div className="timeline-bubble">{renderChangeBlock(l, renderItem, onOpenFile)}</div>
</article>
);
}
const item = renderItem.item;
return (
<article
className={`timeline-item timeline-${item.kind}${
item.kind === 'approval' && item.approval.status !== 'pending'
? ' timeline-approval-resolved'
: ''
}`}
data-search-target={renderItemMatchesTarget(
renderItem,
targetItemId,
targetRunId,
targetApprovalId
) ? 'true' : undefined}
>
{shouldRenderTimelineHeader(item) ? (
<div className="timeline-item-header">
<span className="timeline-avatar">{renderTimelineAvatar(l, item)}</span>
<span className="timeline-kind">{getTimelineTitle(l, item)}</span>
</div>
) : null}
<div className="timeline-bubble">
{renderTimelineItemContent(l,
item,
onOpenFile,
onEditUserMessage,
item.kind === 'approval'
&& onApproveApproval !== undefined
&& onRejectApproval !== undefined
? {
resolving: resolvingApprovalIds?.has(item.approval.id),
error: approvalErrors?.[item.approval.id],
onApprove: onApproveApproval,
onReject: onRejectApproval
}
: undefined
)}
</div>
{item.kind === 'user_message' || item.kind === 'assistant_message' ? (
<MessageMeta
item={item}
latestAssistant={
item.kind === 'assistant_message'
&& item.id === latestAssistantMessageId
}
onEdit={item.kind === 'user_message' ? onEditUserMessage : undefined}
/>
) : null}
</article>
);
}
function getRenderItemKey(item: TimelineRenderItem): string {
if (item.type === 'item') return `item:${item.item.id}`;
return item.key;
}
function renderItemContainsId(item: TimelineRenderItem, itemId: string): boolean {
if (item.type === 'item') return item.item.id === itemId;
return item.items.some(child => child.id === itemId);
}
function renderItemContainsRunId(item: TimelineRenderItem, runId: string): boolean {
if (item.type === 'item') return getRunId(item.item) === runId;
if (item.runId === runId) return true;
return item.items.some(child => getRunId(child) === runId);
}
function renderItemMatchesTarget(
item: TimelineRenderItem,
targetItemId?: string,
targetRunId?: string,
targetApprovalId?: string
): boolean {
if (targetItemId !== undefined && renderItemContainsId(item, targetItemId)) return true;
if (targetApprovalId !== undefined && renderItemContainsApprovalId(item, targetApprovalId)) {
return true;
}
return targetRunId !== undefined && renderItemContainsRunId(item, targetRunId);
}
function renderItemContainsApprovalId(
item: TimelineRenderItem,
approvalId: string
): boolean {
if (item.type !== 'item' || item.item.kind !== 'approval') return false;
return item.item.approval.id === approvalId;
}
function hasSuffix(values: string[], suffix: string[]): boolean {
const offset = values.length - suffix.length;
if (offset < 0) return false;
return suffix.every((value, index) => values[offset + index] === value);
}
function hasPrefix(values: string[], prefix: string[]): boolean {
if (values.length < prefix.length) return false;
return prefix.every((value, index) => values[index] === value);
}