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
fix: harden official model access and Creator workflows
Leggett829c211bc57e
diff --git a/apps/daemon/scripts/check-openrouter-media-contract.ts b/apps/daemon/scripts/check-openrouter-media-contract.tsnew file mode 100644index 00000000..5480b1aa--- /dev/null+++ b/apps/daemon/scripts/check-openrouter-media-contract.ts@@ -0,0 +1,83 @@+import assert from 'node:assert/strict';+import Fastify from 'fastify';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { gatewayVideoSizes } from '@opencreator/protocol';+import { createDirectTransport } from '../src/gateway/direct-transport.js';+import { mediaProfile, profileOperations, type MediaCatalogItem } from './openrouter-media-profiles.js';++const [schemaPath, catalogPath] = process.argv.slice(2);+if (!schemaPath || !catalogPath) throw new Error('Supply the official openapi.json and catalog.json paths');+type Schema = { properties?: Record<string, unknown>; [key: string]: unknown };+const contract = JSON.parse(await readFile(schemaPath, 'utf8')) as { components: { schemas: Record<string, Schema> } };+const catalog = JSON.parse(await readFile(catalogPath, 'utf8')) as Record<'image' | 'video', MediaCatalogItem[]>;+const schemas = contract.components.schemas;+const fields = {+ ImageGenerationRequest: ['model', 'prompt', 'n', 'stream', 'aspect_ratio', 'resolution', 'quality', 'output_format', 'input_references'],+ VideoGenerationRequest: ['model', 'prompt', 'duration', 'size', 'resolution', 'aspect_ratio', 'frame_images']+};+const requestSchemas = Object.fromEntries(Object.entries(fields).map(([name, properties]) => {+ const schema = schemas[name];+ assert(schema?.properties, `Official schema missing: ${name}`);+ // Validate the normalized fields this adapter owns, excluding unused provider passthrough.+ return [name, { ...schema, additionalProperties: false, properties: Object.fromEntries(properties.map(field => {+ assert(schema.properties![field], `Official request field missing: ${field}`);+ return [field, schema.properties![field]];+ })) }];+}));+const server = Fastify({ ajv: { customOptions: { strict: false, coerceTypes: false, removeAdditional: false, useDefaults: false } } });+server.addSchema({ $id: 'openrouter-media-contract', components: { schemas: { ...requestSchemas, ContentPartImage: schemas.ContentPartImage, FrameImage: schemas.FrameImage } } });+for (const [path, schema] of [['images', 'ImageGenerationRequest'], ['videos', 'VideoGenerationRequest']]) {+ server.post(`/${path}`, { schema: { body: { $ref: `openrouter-media-contract#/components/schemas/${schema}` } } }, async () => ({ valid: true }));+}+const root = await mkdtemp(join(tmpdir(), 'oc-openrouter-contract-'));+let checked = 0;+const fetcher: typeof fetch = async (url, options) => {+ const path = new URL(String(url)).pathname.replace('/api/v1', '');+ assert(['images', 'videos'].some(kind => String(url) === `https://openrouter.ai/api/v1/${kind}`));+ const result = await server.inject({ method: 'POST', url: path, payload: JSON.parse(String(options?.body)) });+ assert.equal(result.statusCode, 200, `Official schema rejected the emitted request: ${result.body}`);+ checked++;+ return Response.json(path === '/images'+ ? { created: 1, data: [{ b64_json: 'aW1hZ2U=', media_type: 'image/png' }] }+ : { id: 'gen-vid-1791880000-a1B2c3D4e5F6g7H8i9J0', status: 'pending', polling_url: '/api/v1/videos/gen-vid-1791880000-a1B2c3D4e5F6g7H8i9J0' });+};+const transport = createDirectTransport(root, fetcher);+try {+ assert.equal((await server.inject({ method: 'POST', url: '/images', payload: { model: 'test', prompt: 'test', response_format: 'b64_json' } })).statusCode, 400);+ assert.equal((await server.inject({ method: 'POST', url: '/videos', payload: { model: 'test', duration: '4' } })).statusCode, 400);+ for (const kind of ['image', 'video'] as const) for (const item of catalog[kind]) {+ const profile = mediaProfile(item, kind);+ const model = profile.model;+ if (!model) continue;+ for (const operation of profileOperations(profile)) {+ let resource: string;+ let body: unknown;+ let contentType = 'application/json';+ if (kind === 'image') {+ const options = model.imageOptions!;+ const fields = { model: model.id, prompt: 'A ceramic cup on a white table.', n: 1, size: '1024x1024', response_format: 'b64_json', aspect_ratio: options.aspectRatios?.[0], resolution: options.resolutions?.[0], quality: options.qualities?.[0] };+ resource = operation === 'image-edit' ? 'images/edits' : 'images/generations';+ body = fields;+ if (operation === 'image-edit') {+ const form = new FormData();+ for (const [name, value] of Object.entries(fields)) if (value !== undefined) form.append(name, String(value));+ form.append('image', new Blob(['test image'], { type: 'image/png' }), 'reference.png');+ const request = new Request('http://localhost', { method: 'POST', body: form });+ contentType = request.headers.get('content-type')!;+ body = Buffer.from(await request.arrayBuffer());+ }+ } else {+ resource = 'video/jobs';+ body = { model: model.id, prompt: 'A ceramic cup on a white table.', duration: model.durations![0], size: gatewayVideoSizes(model)[0], ...(operation === 'image-to-video' ? { image: 'data:image/png;base64,aW1hZ2U=' } : {}) };+ }+ await transport.request({ account: 'contract-check', key: 'no-real-credentials', resource, method: 'POST', body, contentType, identity: `${model.id}:${operation}`, fingerprint: `${model.id}:${operation}`, signal: AbortSignal.timeout(10_000), model });+ }+ }+ process.stdout.write(`${JSON.stringify({ source: 'https://openrouter.ai/openapi.json', schemaPath, checkedOperations: checked, paidSubmissions: 0 })}\n`);+} finally {+ await transport.close();+ await server.close();+ await rm(root, { recursive: true, force: true });+}diff --git a/apps/daemon/scripts/export-openrouter-audio-profiles.ts b/apps/daemon/scripts/export-openrouter-audio-profiles.tsnew file mode 100644index 00000000..6436656e--- /dev/null+++ b/apps/daemon/scripts/export-openrouter-audio-profiles.ts@@ -0,0 +1,26 @@+import { createHash } from 'node:crypto';+import { readFile, writeFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import { stringify } from '@iarna/toml';+import { verifiedAudioProfiles } from './openrouter-audio-profiles.js';++const [reportArgument, outputArgument] = process.argv.slice(2);+if (!reportArgument || !outputArgument) throw new Error('Expected a report JSON path and output TOML path');+const reportPath = resolve(reportArgument);+const report = JSON.parse(await readFile(reportPath, 'utf8')) as {+ verifiedAt?: string; updatedAt?: string; results: Record<string, unknown>[];+ chinese?: { speech?: Record<string, unknown>[]; transcription?: Record<string, unknown>[] }+};+const results = [...report.results, ...(report.chinese?.speech ?? []), ...(report.chinese?.transcription ?? [])];+for (const result of results.filter(result => result.status === 'passed')) {+ if (typeof result.outputPath !== 'string' || typeof result.sha256 !== 'string') throw new Error('Incomplete audio evidence');+ const content = await readFile(result.outputPath);+ if (createHash('sha256').update(content).digest('hex') !== result.sha256) throw new Error('Audio evidence hash mismatch');+}+const verifiedAt = report.verifiedAt ?? report.updatedAt;+if (!verifiedAt || !Number.isFinite(Date.parse(verifiedAt))) throw new Error('Missing audio verification date');+const profiles = verifiedAudioProfiles(results, reportPath, verifiedAt);+await writeFile(resolve(outputArgument), stringify({ openrouter: { verified_media_models: profiles } } as never), { mode: 0o600 });+process.stdout.write(`${JSON.stringify({ profiles: profiles.length, speech: profiles.filter(profile => profile.modality === 'speech').length,+ transcription: profiles.filter(profile => profile.modality === 'transcription').length,+ withRegionalEvidence: profiles.filter(profile => profile.verified_countries.length).length, paidSubmissions: 0 })}\n`);diff --git a/apps/daemon/scripts/inspect-openrouter-contract.ts b/apps/daemon/scripts/inspect-openrouter-contract.tsnew file mode 100644index 00000000..d66db129--- /dev/null+++ b/apps/daemon/scripts/inspect-openrouter-contract.ts@@ -0,0 +1,15 @@+import { mkdir, writeFile } from 'node:fs/promises';+import { resolve, join } from 'node:path';+import { createOfficialFetch } from '../src/gateway/official-fetch.js';++const root = resolve(process.argv[2] ?? '.state/openrouter-contract');+const source = 'https://openrouter.ai/openapi.json';+const response = await createOfficialFetch()(source, { signal: AbortSignal.timeout(45_000), redirect: 'error' });+if (!response.ok) throw new Error(`Official OpenAPI schema unavailable (${response.status})`);+const contract = await response.json() as { paths: Record<string, unknown>; components: { schemas: Record<string, unknown> } };+await mkdir(root, { recursive: true, mode: 0o700 });+await writeFile(join(root, 'openapi.json'), JSON.stringify(contract, null, 2), { mode: 0o600 });+for (const [name, schema] of Object.entries(contract.components.schemas)) {+ if (/image.*(request|response)|video.*(request|response|frame)/i.test(name)) process.stdout.write(`${JSON.stringify({ name, schema }, null, 2)}\n`);+}+process.stdout.write(`${JSON.stringify({ source, mediaPaths: Object.keys(contract.paths).filter(path => /^\/(images|videos)/.test(path)), savedContract: join(root, 'openapi.json') })}\n`);diff --git a/apps/daemon/scripts/inspect-openrouter-pcm.ts b/apps/daemon/scripts/inspect-openrouter-pcm.tsnew file mode 100644index 00000000..98463b18--- /dev/null+++ b/apps/daemon/scripts/inspect-openrouter-pcm.ts@@ -0,0 +1,27 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { createOfficialFetch } from '../src/gateway/official-fetch.js';++const root = resolve(process.argv[2]!);+await mkdir(root, { recursive: true, mode: 0o700 });+const chunks: Buffer[] = []; let size = 0;+for await (const chunk of process.stdin) {+ size += chunk.length; assert(size <= 16_384); chunks.push(Buffer.from(chunk));+}+const credential = JSON.parse(Buffer.concat(chunks).toString()) as { key: string; name: string; costBearer: string; accountRemainingUsd: number; productionReserveUsd: number; balanceCheckedAt: string };+assert(credential.key.startsWith('sk-or-') && credential.costBearer === 'platform' && credential.name.startsWith('OpenCreator platform audio verification'));+assert(Date.now() - Date.parse(credential.balanceCheckedAt) < 60_000 && credential.accountRemainingUsd >= 0.6 + credential.productionReserveUsd);+const upstream = createOfficialFetch();+const auth = { Authorization: `Bearer ${credential.key}` };+const keyInfo = await upstream('https://openrouter.ai/api/v1/key', { headers: auth, signal: AbortSignal.timeout(30_000), redirect: 'error' });+const { data: info } = await keyInfo.json();+assert(keyInfo.ok && !info.is_management_key && info.limit <= 0.6 && info.usage < 0.01);+const body = { model: 'heygen/heygen-voice-1-turbo', input: 'The red cup is on the table.', voice: 'f34178ba32584bfb98434bf6d07f1253', response_format: 'pcm' };+const response = await upstream('https://openrouter.ai/api/v1/audio/speech', { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json' }, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(120_000) });+const headers = Object.fromEntries([...response.headers].filter(([name]) => /^(content-type|x-generation-id|x-request-id)$/.test(name) || /sample|channel|audio.*rate|rate.*audio/.test(name)));+const content = Buffer.from(await response.arrayBuffer());+const result = { request: body, httpStatus: response.status, headers, bytes: content.length, headerNames: [...response.headers.keys()], error: response.ok ? undefined : content.toString().replaceAll(credential.key, '[redacted]'), outputPath: join(root, 'speech.pcm'), submissions: 1 };+if (response.ok) await writeFile(result.outputPath, content, { mode: 0o600 });+await writeFile(join(root, 'report.json'), JSON.stringify(result, null, 2), { mode: 0o600 });+process.stdout.write(`${JSON.stringify(result)}\n`);diff --git a/apps/daemon/scripts/openrouter-audio-profiles.ts b/apps/daemon/scripts/openrouter-audio-profiles.tsnew file mode 100644index 00000000..2aaef87e--- /dev/null+++ b/apps/daemon/scripts/openrouter-audio-profiles.ts@@ -0,0 +1,30 @@+import { gatewayDefaultVoiceId } from '@opencreator/protocol';+import { DIRECT_MEDIA_ADAPTER_VERSION } from '../src/gateway/direct-transport.js';++export function verifiedAudioProfiles(results: Record<string, unknown>[], evidence: string, verifiedAt: string) {+ const profiles = new Map<string, { id: string; modality: string; capabilities: string[]; voices: string[];+ adapter_version: number; verified_at: string; evidence: string; verified_countries: string[] }>();+ for (const result of results) {+ if (result.status !== 'passed' || result.restartReplay !== true || typeof result.model !== 'string'+ || typeof result.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(result.sha256)) continue;+ const modality = result.modality;+ const speech = modality === 'speech';+ if (!speech && !(modality === 'transcription' && result.subtitleCompatible === true && Number(result.validTimings) > 0)) continue;+ if (speech && (typeof result.voice !== 'string' || !result.voice || (result.format !== 'mp3'+ && !(result.format === 'wav' && result.model === 'heygen/heygen-voice-1-turbo')))) continue;+ const countries = Array.isArray(result.verifiedCountries) ? result.verifiedCountries.filter((country): country is string => typeof country === 'string' && /^[A-Z]{2}$/.test(country)) : [];+ const key = `${modality}:${result.model}`;+ const existing = profiles.get(key);+ const voice = speech ? result.voice as string : undefined;+ if (existing) {+ if (voice && voice !== gatewayDefaultVoiceId && !existing.voices.includes(voice)) existing.voices.push(voice);+ existing.verified_countries = existing.verified_countries.filter(country => countries.includes(country));+ continue;+ }+ profiles.set(key, { id: result.model, modality: modality as string, capabilities: speech+ ? [...(voice === gatewayDefaultVoiceId ? ['default_voice'] : []), ...(result.format === 'wav' ? ['pcm_speech'] : [])]+ : ['subtitle_timestamps'], voices: voice && voice !== gatewayDefaultVoiceId ? [voice] : [],+ adapter_version: DIRECT_MEDIA_ADAPTER_VERSION, verified_at: verifiedAt, evidence, verified_countries: countries });+ }+ return [...profiles.values()];+}diff --git a/apps/daemon/scripts/openrouter-media-profiles.ts b/apps/daemon/scripts/openrouter-media-profiles.tsnew file mode 100644index 00000000..9493ab83--- /dev/null+++ b/apps/daemon/scripts/openrouter-media-profiles.ts@@ -0,0 +1,163 @@+import type { GatewayModel } from '@opencreator/protocol';++export type MediaCatalogItem = {+ id: string;+ name?: string;+ architecture?: { input_modalities?: string[] };+ supported_parameters?: Record<string, { min?: number; max?: number; values?: string[] }>;+ supported_sizes?: string[] | null;+ supported_resolutions?: string[] | null;+ supported_aspect_ratios?: string[] | null;+ supported_durations?: number[] | null;+ supported_frame_images?: string[] | null;+ pricing_skus?: Record<string, string>;+};++export type MediaProfile = {+ id: string;+ modality: 'image' | 'video';+ model?: GatewayModel;+ unsupportedReason?: string;+};++const families: Array<{ modality: 'image' | 'video'; name: string; pattern: RegExp; preferred: string[] }> = [+ { modality: 'image', name: 'FLUX', pattern: /^black-forest-labs\/flux/, preferred: ['black-forest-labs/flux-3-image', 'black-forest-labs/flux.2-klein-4b'] },+ { modality: 'image', name: 'Seedream', pattern: /^bytedance-seed\/seedream-/, preferred: ['bytedance-seed/seedream-5-0-flash', 'bytedance-seed/seedream-4.5'] },+ { modality: 'image', name: 'Recraft', pattern: /^recraft\/recraft-/, preferred: ['recraft/recraft-v4.1-flash', 'recraft/recraft-v4'] },+ { modality: 'image', name: 'MAI Image', pattern: /^microsoft\/mai-image-/, preferred: ['microsoft/mai-image-2.6-flash', 'microsoft/mai-image-2.5'] },+ { modality: 'image', name: 'Qwen Image', pattern: /^qwen\/qwen-image-/, preferred: ['qwen/qwen-image-3'] },+ { modality: 'image', name: 'Krea', pattern: /^krea\/krea-/, preferred: ['krea/krea-2-medium-turbo', 'krea/krea-2-medium'] },+ { modality: 'image', name: 'Riverflow', pattern: /^sourceful\/riverflow-/, preferred: ['sourceful/riverflow-v2.5-fast', 'sourceful/riverflow-v2-fast'] },+ { modality: 'image', name: 'Grok Image', pattern: /^x-ai\/grok-imagine-image/, preferred: ['x-ai/grok-imagine-image-2.0'] },+ { modality: 'image', name: 'Gemini Image', pattern: /^google\/gemini-/, preferred: ['google/gemini-3.1-flash-image', 'google/gemini-2.5-flash-image'] },+ { modality: 'image', name: 'GPT Image', pattern: /^openai\/(gpt-image-|gpt-\d.*image)/, preferred: ['openai/gpt-image-1-mini', 'openai/gpt-image-2'] },+ { modality: 'image', name: 'HY Image', pattern: /^tencent\/hy-image-/, preferred: ['tencent/hy-image-v3.5-preview'] },+ { modality: 'image', name: 'Ming Image', pattern: /^inclusionai\/ming-image-/, preferred: ['inclusionai/ming-image-0.1-design'] },+ { modality: 'image', name: 'Muse Image', pattern: /^meta\/muse-image/, preferred: ['meta/muse-image'] },+ { modality: 'video', name: 'Grok Video', pattern: /^x-ai\/grok-imagine-video/, preferred: ['x-ai/grok-imagine-video-1.5-lite'] },+ { modality: 'video', name: 'Seedance', pattern: /^bytedance\/seedance-/, preferred: ['bytedance/seedance-2.0-fast', 'bytedance/seedance-1-5-pro'] },+ { modality: 'video', name: 'Kling', pattern: /^kwaivgi\/kling-/, preferred: ['kwaivgi/kling-v3.0-std'] },+ { modality: 'video', name: 'Wan', pattern: /^alibaba\/wan-/, preferred: ['alibaba/wan-2.6', 'alibaba/wan-3.0'] },+ { modality: 'video', name: 'HappyHorse', pattern: /^alibaba\/happyhorse-/, preferred: ['alibaba/happyhorse-1.1'] },+ { modality: 'video', name: 'Hailuo', pattern: /^minimax\/hailuo-/, preferred: ['minimax/hailuo-2.3'] },+ { modality: 'video', name: 'Veo', pattern: /^google\/veo-/, preferred: ['google/veo-3.1-lite'] },+ { modality: 'video', name: 'Runway', pattern: /^runway\/(gen-|aleph-)/, preferred: ['runway/gen-4.5'] },+ { modality: 'video', name: 'HeyGen', pattern: /^heygen\/(heygen-video-|avatar-)/, preferred: ['heygen/heygen-video-1'] },+ { modality: 'video', name: 'FLUX Video', pattern: /^black-forest-labs\/flux/, preferred: ['black-forest-labs/flux-3-video'] }+];++export function mediaFamily(profile: MediaProfile): string | undefined {+ return families.find(family => family.modality === profile.modality && family.pattern.test(profile.id))?.name;+}++export function familyRepresentatives(profiles: MediaProfile[]): MediaProfile[] {+ return families.flatMap(family => {+ const candidates = profiles.filter(profile => profile.model && profile.modality === family.modality && family.pattern.test(profile.id));+ const preferred = family.preferred.map(id => candidates.find(profile => profile.id === id)).find(Boolean);+ // Unknown/new families require an explicit selection; aliases never expand acceptance.+ const selected = preferred ?? candidates.sort((a, b) => a.id.localeCompare(b.id))[0];+ return selected ? [selected] : [];+ });+}++export function profileOperations(profile: MediaProfile): string[] {+ if (!profile.model) return [];+ return profile.modality === 'image'+ ? ['text-to-image', ...(profile.model.capabilities.includes('edit') ? ['image-edit'] : [])]+ : ['text-to-video', ...(profile.model.capabilities.includes('image_to_video') ? ['image-to-video'] : [])];+}++export function referenceDimensions(model: GatewayModel): { width: number; height: number } {+ const [a, b] = (model.sizes?.[0] ?? model.aspectRatios?.[0] ?? model.imageOptions?.aspectRatios?.[0] ?? '1:1').split(/[x:]/).map(Number);+ if (!a || !b) throw new Error('Invalid reference aspect ratio');+ return { width: Math.round(512 * a / Math.max(a, b)), height: Math.round(512 * b / Math.max(a, b)) };+}++export type VerificationFailureEvidence = { upstreamError?: { httpStatus?: number; upstreamCode?: string; upstreamMessage?: string } };+export function verificationBlockReason(evidence: VerificationFailureEvidence[]): 'funding' | 'provider-access' | undefined {+ if (evidence.some(({ upstreamError: e }) => e?.httpStatus === 402 || (e?.httpStatus === 403 && /^Key limit exceeded\b/i.test(e.upstreamMessage ?? '')))) return 'funding';+ if (evidence.some(({ upstreamError: e }) => e?.httpStatus === 403)) return 'provider-access';+ return undefined;+}++export function resolutionEdge(value: string): number {+ if (/^\d+(?:\.\d+)?k$/i.test(value)) return Number(value.slice(0, -1)) * 1024;+ return Number(value.replace(/p$/i, '')) || Infinity;+}++export function videoShapeMismatch(model: GatewayModel, width: number, height: number): string | undefined {+ if (model.sizes?.[0]) {+ const [expectedWidth, expectedHeight] = model.sizes[0].split('x').map(Number);+ return width === expectedWidth && height === expectedHeight ? undefined : 'The video does not match the verified pixel size';+ }+ const [a, b] = (model.aspectRatios?.[0] ?? '').split(':').map(Number);+ const edge = resolutionEdge(model.resolutions?.[0] ?? '');+ if (!a || !b || !Number.isFinite(edge) || Math.abs(width / height - a / b) > 0.02 || Math.abs(Math.min(width, height) - edge) > edge * 0.02) return 'The video does not match the verified resolution and aspect ratio';+ return undefined;+}++export function mediaProfile(item: MediaCatalogItem, modality: 'image' | 'video', videoShape?: string): MediaProfile {+ const profile: MediaProfile = { id: item.id, modality };+ const unsupported = (reason: string) => ({ ...profile, unsupportedReason: reason });+ if (modality === 'image') {+ const p = item.supported_parameters;+ if (!p) return unsupported('Missing image parameter metadata');+ if ((p.input_references?.min ?? 0) > 0) return unsupported('Reference-only models are outside the current official text-to-image catalog');+ const formats = p.output_format?.values ?? [];+ const format = ['png', 'jpeg', 'webp'].find(value => formats.includes(value));+ if (formats.length && !format) return unsupported('The image adapter requires raster output; this model only advertises other formats');+ const ratios = p.aspect_ratio?.values ?? [];+ const ratio = ratios.includes('1:1') ? '1:1' : ratios.find(value => /^\d+:\d+$/.test(value));+ if (ratios.length && !ratio) return unsupported('No fixed aspect ratio is available for verification');+ const resolutions = [...(p.resolution?.values ?? [])].sort((a, b) => resolutionEdge(a) - resolutionEdge(b));+ const resolution = resolutions.includes('1K') ? '1K' : resolutions[0];+ const qualities = p.quality?.values ?? [];+ const quality = ['low', 'medium', 'auto'].find(value => qualities.includes(value)) ?? qualities[0];+ const edits = item.architecture?.input_modalities?.includes('image') && (p.input_references?.max ?? 0) > 0;+ profile.model = { id: item.id, name: item.name, modality, capabilities: edits ? ['edit'] : [], imageOptions: {+ maxImages: 1, maxReferences: edits ? 1 : 0,+ aspectRatios: ratio ? [ratio] : [], resolutions: resolution ? [resolution] : [],+ qualities: quality ? [quality] : [], outputFormats: format ? [format] : []+ } };+ } else {+ const resolutions = [...(item.supported_resolutions ?? [])].sort((a, b) => resolutionEdge(a) - resolutionEdge(b));+ const durations = (item.supported_durations ?? []).filter(value => Number.isInteger(value) && value > 0);+ const ratios = item.supported_aspect_ratios ?? [];+ if (!resolutions.length || !durations.length) return unsupported('The current adapter requires explicit resolution and duration options; video editing, upscaling and avatar workflows need separate adapters');+ const resolution = resolutions[0]!;+ const ratio = ratios.includes('16:9') ? '16:9' : ratios.find(value => /^\d+:\d+$/.test(value));+ const sizes = [...(item.supported_sizes ?? [])].sort((a, b) => {+ const area = (value: string) => value.split('x').map(Number).reduce((x, y) => x * y, 1);+ return area(a) - area(b);+ });+ if (!sizes.length && !ratio) return unsupported('No fixed video size or aspect ratio is available');+ const selectedSize = sizes.find(value => {+ const [width, height] = value.split('x').map(Number);+ const [a, b] = (ratio ?? '16:9').split(':').map(Number);+ return width && height && a && b && Math.min(width, height) === resolutionEdge(resolution)+ && Math.abs(width / height - a / b) < 0.01;+ }) ?? sizes[0];+ profile.model = { id: item.id, name: item.name, modality,+ capabilities: item.supported_frame_images?.includes('first_frame') ? ['image_to_video'] : [],+ durations: [Math.min(...durations)],+ ...(selectedSize ? { sizes: [selectedSize] } : { resolutions: [resolution], aspectRatios: [ratio!] })+ };+ if (videoShape) {+ const [selectedResolution, selectedRatio, extra] = videoShape.split('@');+ if (extra || !selectedResolution || !selectedRatio || !resolutions.includes(selectedResolution) || !ratios.includes(selectedRatio)) throw new Error('The requested video shape is not declared by the model');+ delete profile.model.sizes;+ profile.model.resolutions = [selectedResolution];+ profile.model.aspectRatios = [selectedRatio];+ }+ }+ return profile;+}++// Each capability is admitted only when its own operation delivered a usable file.+export function passedProfile(model: GatewayModel, passedOperations: string[]): GatewayModel | undefined {+ const base = model.modality === 'image' ? 'text-to-image' : 'text-to-video';+ if (!passedOperations.includes(base)) return undefined;+ const reference = model.modality === 'image' ? 'image-edit' : 'image-to-video';+ const capabilities = passedOperations.includes(reference) ? [...model.capabilities] : [];+ return { ...model, capabilities, ...(model.imageOptions ? { imageOptions: { ...model.imageOptions, maxReferences: capabilities.includes('edit') ? 1 : 0 } } : {}) };+}diff --git a/apps/daemon/scripts/openrouter-verification-network.ts b/apps/daemon/scripts/openrouter-verification-network.tsnew file mode 100644index 00000000..655a65a3--- /dev/null+++ b/apps/daemon/scripts/openrouter-verification-network.ts@@ -0,0 +1,16 @@+import { createHash } from 'node:crypto';+import { isIP } from 'node:net';++export type VerificationNetwork = { country: string; exitHash: string };++export async function readVerificationNetwork(fetcher: typeof fetch): Promise<VerificationNetwork> {+ const response = await fetcher('https://openrouter.ai/cdn-cgi/trace', { redirect: 'error', signal: AbortSignal.timeout(8000) });+ const fields = new URLSearchParams((await response.text()).replace(/\r?\n/g, '&'));+ const ip = fields.get('ip') ?? ''; const country = fields.get('loc') ?? '';+ if (!response.ok || !isIP(ip) || !/^[A-Z]{2}$/.test(country)) throw new Error('Verification requires a known OpenRouter exit country');+ return { country, exitHash: createHash('sha256').update(JSON.stringify([ip, country])).digest('hex') };+}++export function verifiedCountries(before: VerificationNetwork, after?: VerificationNetwork): string[] {+ return before.country === after?.country && before.exitHash === after.exitHash ? [before.country] : [];+}diff --git a/apps/daemon/scripts/verify-openrouter-audio.ts b/apps/daemon/scripts/verify-openrouter-audio.tsnew file mode 100644index 00000000..74c9cc44--- /dev/null+++ b/apps/daemon/scripts/verify-openrouter-audio.ts@@ -0,0 +1,251 @@+import assert from 'node:assert/strict';+import Fastify from 'fastify';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { createHash } from 'node:crypto';+import { access, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { createDefaultCreatorServicesConfig, type GatewayModel } from '@opencreator/protocol';+import { createGatewayCreatorSource } from '../src/gateway/creator-service-source.js';+import { createDirectTransport } from '../src/gateway/direct-transport.js';+import { createOfficialFetch } from '../src/gateway/official-fetch.js';+import { createKrillinTtsService } from '../src/creator/krillin/tts-service.js';+import { readVerificationNetwork, verifiedCountries } from './openrouter-verification-network.js';+import { verifiedAudioProfiles } from './openrouter-audio-profiles.js';+import { stringify } from '@iarna/toml';++const args = process.argv.slice(2);+const option = (name: string) => args.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3);+const outputRoot = resolve(args.find(arg => !arg.startsWith('--')) ?? '.state/audio-verification');+const planOnly = args.includes('--plan');+const budgetUsd = Number(option('budget') ?? 0.25);+if (!Number.isFinite(budgetUsd) || budgetUsd <= 0 || budgetUsd > 1) throw new Error('Audio verification budget must be within USD 1');+const keyLimitUsd = Number(option('key-limit') ?? budgetUsd);+if (!Number.isFinite(keyLimitUsd) || keyLimitUsd < budgetUsd || keyLimitUsd > 1) throw new Error('Invalid audio test key limit');+await mkdir(outputRoot, { recursive: true, mode: 0o700 });+if (!planOnly && await access(join(outputRoot, 'report.json')).then(() => true, () => false)) throw new Error('Use a fresh report directory; never automatically resubmit a paid run');+const upstream = createOfficialFetch();+const exec = promisify(execFile);+type CatalogItem = { id: string; architecture: { output_modalities: string[] }; supported_voices?: string[] | null };+const catalog = JSON.parse(await readFile(option('catalog')!, 'utf8')) as { data: CatalogItem[] };+const representatives = [+ 'hexgrad/kokoro-82m', 'mistralai/voxtral-mini-tts-2603', 'elevenlabs/eleven-flash-v2.5',+ 'fish-audio/s2.1-pro', 'microsoft/mai-voice-2.1-flash', 'bytedance-seed/seed-audio-1-0',+ 'google/gemini-3.8-flash-lite-tts', 'qwen/qwen-audio-3.0-tts-flash', 'x-ai/grok-voice-tts-1.0',+ 'deepgram/aura-2', 'deepgram/flux-tts', 'minimax/speech-2.8-turbo',+ 'heygen/heygen-voice-1-turbo', 'canopylabs/orpheus-3b-0.1-ft', 'sesame/csm-1b',+ 'openai/whisper-large-v3-turbo', 'openai/gpt-4o-mini-transcribe', 'mistralai/voxtral-mini-transcribe',+ 'elevenlabs/scribe-v2', 'deepgram/nova-3', 'qwen/qwen3-asr-0.6b',+ 'nvidia/parakeet-tdt-0.6b-v3', 'nvidia/nemotron-3.5-asr-streaming-multilingual-0.6b',+ 'google/chirp-3', 'google/gemini-3.5-transcribe', 'microsoft/mai-transcribe-2',+ 'assemblyai/universal-3-5-pro', 'fish-audio/transcribe-1', 'meta/muse-voice-transcribe-1.0', 'x-ai/grok-stt-1.0'+];+const requestedModels = args.filter(arg => arg.startsWith('--model=')).map(arg => arg.slice('--model='.length));+const profiles = representatives.filter(id => !requestedModels.length || requestedModels.includes(id)).map<GatewayModel>(id => {+ const item = catalog.data.find(candidate => candidate.id === id);+ if (!item) throw new Error(`Representative absent from current catalog: ${id}`);+ const speech = item.architecture.output_modalities.includes('speech');+ assert(speech || item.architecture.output_modalities.includes('transcription'));+ const voices = item.supported_voices ?? [];+ if (option('voice') && !voices.includes(option('voice')!)) throw new Error('Voice absent from the current model catalog');+ const preferred = option('voice') ?? voices.find(voice => ['af_heart', 'en_paul_neutral'].includes(voice))+ ?? voices.find(voice => voice.startsWith('en-US-')) ?? voices[0];+ return { id, modality: speech ? 'speech' : 'transcription', capabilities: [...(speech && !voices.length ? ['default_voice'] : []), ...(id === 'heygen/heygen-voice-1-turbo' ? ['pcm_speech'] : [])], ...(preferred ? { voices: [preferred] } : {}) };+}).filter(profile => !option('modality') || profile.modality === option('modality'));+if (!profiles.length) throw new Error('No models selected');+const responseFormat = option('asr-format') ?? 'verbose_json';+if (!['json', 'verbose_json'].includes(responseFormat)) throw new Error('Invalid ASR response format');+const schema = JSON.parse(await readFile(option('schema')!, 'utf8'));+const contract = Fastify({ ajv: { customOptions: { strict: false, coerceTypes: false, removeAdditional: false, useDefaults: false } } });+const schemas = schema.components.schemas;+const speechFields = ['model', 'input', 'voice', 'response_format'];+const multipart = schema.paths['/audio/transcriptions'].post.requestBody.content['multipart/form-data'].schema;+contract.addSchema({ $id: 'openrouter-audio-contract', components: { schemas: {+ SpeechInput: schemas.SpeechInput, SpeechTurn: schemas.SpeechTurn,+ Speech: { ...schemas.SpeechRequest, additionalProperties: false, properties: Object.fromEntries(speechFields.map(field => [field, schemas.SpeechRequest.properties[field]])) },+ Multipart: { ...multipart, additionalProperties: false }+} } });+contract.post('/speech', { schema: { body: { $ref: 'openrouter-audio-contract#/components/schemas/Speech' } } }, async () => ({ valid: true }));+contract.post('/transcription', { schema: { body: { $ref: 'openrouter-audio-contract#/components/schemas/Multipart' } } }, async () => ({ valid: true }));+let contractChecks = 0;+async function validateRequest(resource: string, body: BodyInit, contentType: string) {+ let payload: Record<string, unknown>;+ if (resource === 'speech') payload = JSON.parse(String(body));+ else {+ const form = await new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': contentType }, body }).formData();+ payload = {};+ for (const [name, value] of form.entries()) {+ if (name.endsWith('[]')) {+ const values = (payload[name] ??= []) as unknown[];+ values.push(value);+ } else payload[name] = typeof value === 'string' ? value : value.name;+ }+ assert(form.get('file') instanceof Blob && (form.get('file') as Blob).size > 0);+ }+ const checked = await contract.inject({ method: 'POST', url: `/${resource}`, payload });+ assert.equal(checked.statusCode, 200, `Official schema rejected emitted request: ${checked.body}`);+ contractChecks++;+}+const text = option('text') ?? 'The red cup is on the table. Today is a sunny day.';+const language = option('language') ?? 'en';+for (const profile of profiles) {+ const response = await upstream(`https://openrouter.ai/${profile.id}/llms.txt`, { signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error(`Model API documentation unavailable: ${profile.id}`);+ const docs = await response.text();+ const endpoint = profile.modality === 'speech' ? '/audio/speech' : '/audio/transcriptions';+ if (!docs.includes(`POST https://openrouter.ai/api/v1${endpoint}`)) throw new Error(`Model documentation does not confirm the selected endpoint: ${profile.id}`);+ await writeFile(join(outputRoot, `${profile.id.replace('/', '__')}.md`), docs, { mode: 0o600 });+ if (profile.modality === 'speech') await validateRequest('speech', JSON.stringify({ model: profile.id, input: text, response_format: profile.capabilities.includes('pcm_speech') ? 'pcm' : 'mp3', ...(profile.voices?.[0] ? { voice: profile.voices[0] } : {}) }), 'application/json');+ else {+ const form = new FormData();+ form.set('model', profile.id); form.set('file', new Blob(['fixture'], { type: 'audio/wav' }), 'fixture.wav');+ form.set('language', language); form.set('response_format', responseFormat);+ if (responseFormat === 'verbose_json') form.set('timestamp_granularities[]', 'segment');+ const request = new Request('http://localhost', { method: 'POST', body: form });+ await validateRequest('transcription', new Uint8Array(await request.arrayBuffer()), request.headers.get('content-type')!);+ }+}+await writeFile(join(outputRoot, 'plan.json'), JSON.stringify({ text, language, responseFormat, profiles, contractChecks, budgetUsd, keyLimitUsd }, null, 2), { mode: 0o600 });+if (planOnly) { process.stdout.write(`${JSON.stringify({ profiles, contractChecks, paidSubmissions: 0 })}\n`); await contract.close(); process.exit(0); }+await exec(option('ffprobe') ?? 'ffprobe', ['-version']);+await exec(option('ffmpeg') ?? 'ffmpeg', ['-version']);+const chunks: Buffer[] = []; let credentialBytes = 0;+for await (const chunk of process.stdin) {+ credentialBytes += chunk.length; if (credentialBytes > 16_384) throw new Error('Credential input too large');+ chunks.push(Buffer.from(chunk));+}+const credential = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { key?: string; costBearer?: string; name?: string; accountRemainingUsd?: number; productionReserveUsd?: number; balanceCheckedAt?: string };+const key = credential.key;+const checkedAt = Date.parse(credential.balanceCheckedAt ?? '');+if (!key?.startsWith('sk-or-') || credential.costBearer !== 'platform' || !/^OpenCreator platform (?:media|audio) verification/.test(credential.name ?? '')+ || !Number.isFinite(checkedAt) || Date.now() - checkedAt > 60_000 || checkedAt > Date.now() + 5_000+ || !(credential.productionReserveUsd! >= 4) || !(credential.accountRemainingUsd! >= keyLimitUsd + credential.productionReserveUsd!)) throw new Error('Expected a limited platform test key and fresh owner-balance preflight');+async function keyInfo() {+ const response = await upstream('https://openrouter.ai/api/v1/key', { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error('Test key inspection failed');+ const { data } = await response.json() as { data: { limit?: number; usage?: number; is_management_key?: boolean } };+ if (data.is_management_key || !data.limit || data.limit > keyLimitUsd) throw new Error('Invalid test key budget');+ return { limitUsd: data.limit, usageUsd: data.usage ?? 0 };+}+let usage = await keyInfo();+const initialUsage = usage.usageUsd;+const results: Array<Record<string, unknown>> = [];+let fundingBlocked = false;+let reference = option('reference-audio');+const checkpoint = async () => {+ const verifiedAt = new Date().toISOString();+ const evidence = join(outputRoot, 'report.json');+ await writeFile(evidence, JSON.stringify({ updatedAt: verifiedAt, costBearer: 'platform', transport: 'official-fetch', contractChecks, budgetUsd, keyLimitUsd, usage: { ...usage, incrementalUsageUsd: usage.usageUsd - initialUsage }, fundingBlocked, text, language, responseFormat, results }, null, 2), { mode: 0o600 });+ await writeFile(join(outputRoot, 'verified-audio.toml'), stringify({ openrouter: { verified_media_models: verifiedAudioProfiles(results, evidence, verifiedAt) } } as never), { mode: 0o600 });+};+await checkpoint();+try {+ for (const model of profiles) {+ if (fundingBlocked) { results.push({ model: model.id, status: 'untested', reason: 'funding-blocked' }); await checkpoint(); continue; }+ const root = join(outputRoot, model.id.replace('/', '__'));+ const receiptsRoot = join(root, 'receipts');+ await mkdir(root, { recursive: true, mode: 0o700 });+ let submissions = 0;+ const networkBefore = await readVerificationNetwork(upstream);+ const upstreamMetadata: Record<string, unknown> = {};+ const fetcher: typeof fetch = async (url, options) => {+ if (options?.method === 'POST') {+ assert.equal(submissions, 0, 'Blocked duplicate paid submission');+ usage = await keyInfo();+ const reportedCostUsd = results.reduce((sum, result) => sum + (typeof result.reportedCostUsd === 'number' ? result.reportedCostUsd : 0), 0);+ if (Math.max(usage.usageUsd, initialUsage + reportedCostUsd) >= budgetUsd) { fundingBlocked = true; throw new Error('Test budget exhausted'); }+ const resource = String(url).endsWith('/audio/speech') ? 'speech' : 'transcription';+ await validateRequest(resource, options.body!, new Headers(options.headers).get('content-type')!);+ submissions++;+ }+ const response = await upstream(url, options);+ upstreamMetadata.httpStatus = response.status;+ for (const name of ['x-request-id', 'x-generation-id', 'content-type']) upstreamMetadata[name] = response.headers.get(name);+ if (response.status === 402) fundingBlocked = true;+ return response;+ };+ const manual = createDefaultCreatorServicesConfig();+ let origin: string | undefined;+ const source = createGatewayCreatorSource({ directRequestsRoot: receiptsRoot, fetcher,+ account: {+ peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'platform-audio-verification', email: 'platform-verification@invalid', verified: true }, bindingVersion: 'platform-audio-verification', models: [model], selectedModels: { [model.modality]: model.id }, activationError: null }),+ modelCredentials: async () => ({ accountId: 'platform-audio-verification', bindingVersion: 'platform-audio-verification', keyVersion: 'platform', modelKey: key!, baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models: [model], defaults: { [model.modality]: model.id } })+ }, manual: { read: async () => structuredClone(manual), write: async value => value, reset: async () => manual }, getLocalOrigin: () => origin });+ const server = Fastify();+ let result: Record<string, unknown> = { model: model.id, modality: model.modality, status: 'failed' };+ process.stderr.write(`${JSON.stringify({ model: model.id, phase: 'submitting' })}\n`);+ try {+ await source.register(server);+ origin = await server.listen({ host: '127.0.0.1', port: 0 });+ let content: Buffer;+ let requestId: string | undefined;+ let outputPath: string;+ if (model.modality === 'speech') {+ const service = createKrillinTtsService({ resourceRoot: root, workRoot: root, configStore: source.store });+ const synthesized = await service.synthesize({ text, model: model.id, format: 'wav', logicalId: `verify-audio:${model.id}`, onGatewayRequest: id => { requestId = id; } });+ content = synthesized.content;+ outputPath = join(root, `speech.${synthesized.format}`);+ await writeFile(outputPath, content, { mode: 0o600 });+ const { stdout } = await exec(option('ffprobe') ?? 'ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_name,sample_rate,channels:format=duration', '-of', 'json', outputPath]);+ const media = JSON.parse(stdout);+ assert(media.streams?.length === 1 && Number(media.format?.duration) > 0);+ assert.equal(synthesized.format, model.capabilities.includes('pcm_speech') ? 'wav' : 'mp3');+ const decoded = await exec(option('ffmpeg') ?? 'ffmpeg', ['-v', 'error', '-i', outputPath, '-f', 's16le', '-ac', '1', '-ar', '16000', 'pipe:1'], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 });+ const samples = decoded.stdout;+ let sum = 0; for (let offset = 0; offset + 1 < samples.length; offset += 2) sum += samples.readInt16LE(offset) ** 2;+ const rms = Math.sqrt(sum / (samples.length / 2));+ assert(samples.length > 1600 && rms > 10, 'Audio is silent or undecodable');+ result = { ...result, format: synthesized.format, voice: synthesized.voiceId, media, rms };+ if (!reference) {+ reference = join(outputRoot, 'reference.wav');+ await exec(option('ffmpeg') ?? 'ffmpeg', ['-v', 'error', '-i', outputPath, '-ar', '16000', '-ac', '1', reference]);+ }+ } else {+ assert(reference, 'No successful TTS fixture available; supply --reference-audio');+ const config = await source.store.read();+ const form = new FormData();+ form.set('model', model.id); form.set('file', new Blob([new Uint8Array(await readFile(reference))], { type: 'audio/wav' }), 'fixture.wav');+ form.set('language', language); form.set('response_format', responseFormat);+ if (responseFormat === 'verbose_json') form.set('timestamp_granularities[]', 'segment');+ const response = await fetch(`${origin}/internal/krillin-llm/gateway/v1/audio/transcriptions`, { method: 'POST', headers: { Authorization: `Bearer ${config.transcription.openai.apiKey}`, 'Idempotency-Key': `verify-audio:${model.id}` }, body: form, signal: AbortSignal.timeout(120_000) });+ const payload = await response.json();+ if (!response.ok) throw new Error(`Official ASR route failed: HTTP ${response.status}`);+ content = Buffer.from(JSON.stringify(payload));+ requestId = response.headers.get('x-request-id') ?? undefined;+ outputPath = join(root, 'transcript.json');+ await writeFile(outputPath, content, { mode: 0o600 });+ result = { ...result, outputPath, text: payload.text, reportedCostUsd: payload.usage?.cost, deliveryVerified: true };+ assert(typeof payload.text === 'string' && payload.text.trim(), 'No transcription text');+ const normalize = (value: string) => value.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');+ assert.equal(normalize(payload.text), normalize(text), 'Transcription does not match the known spoken fixture');+ const timings = [...(payload.words ?? []).map((word: { word: string; start: number; end: number }) => ({ ...word, text: word.word })), ...(payload.segments ?? [])];+ const validTimings = timings.filter(item => typeof item.text === 'string' && item.text.trim() && Number.isFinite(item.start) && Number.isFinite(item.end) && item.start >= 0 && item.end > item.start);+ result = { ...result, text: payload.text, validTimings: validTimings.length, reportedCostUsd: payload.usage?.cost, subtitleCompatible: validTimings.length > 0 };+ if (responseFormat === 'verbose_json') assert(validTimings.length > 0, 'Transcription text returned without valid subtitle timestamps');+ }+ assert(requestId && submissions === 1, 'Expected one recoverable paid submission');+ const restarted = createDirectTransport(receiptsRoot, fetcher);+ try {+ const replay = await restarted.request({ account: 'platform-audio-verification', key: key!, method: 'GET', resource: `requests/${requestId}/result`, body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal: AbortSignal.timeout(10_000) });+ const replayBytes = Buffer.from(await replay.arrayBuffer());+ const matched = model.modality === 'speech' ? content.equals(replayBytes) : JSON.stringify(JSON.parse(content.toString())) === JSON.stringify(JSON.parse(replayBytes.toString()));+ assert(matched && submissions === 1, 'Restart replay failed or caused a second paid call');+ } finally { await restarted.close(); }+ const networkAfter = await readVerificationNetwork(upstream).catch(() => undefined);+ result = { ...result, status: 'passed', outputPath, requestId, sha256: createHash('sha256').update(content).digest('hex'), restartReplay: true,+ verifiedCountries: verifiedCountries(networkBefore, networkAfter), networkBefore, networkAfter, verifiedAt: new Date().toISOString() };+ } catch (error) {+ result.error = (error instanceof Error ? error.message : String(error)).replaceAll(key!, '[redacted]');+ if ([402, 403].includes(Number(upstreamMetadata.httpStatus))) result.status = 'blocked';+ } finally { await source.revoke(); await server.close(); }+ const receipts = await readdir(receiptsRoot).catch(() => [] as string[]);+ const evidence = await Promise.all(receipts.map(async file => {+ const { content: _content, ...receipt } = JSON.parse(await readFile(join(receiptsRoot, file), 'utf8'));+ return receipt;+ }));+ usage = await keyInfo();+ result = { ...result, submissions, upstreamMetadata, evidence };+ results.push(result); await checkpoint();+ process.stdout.write(`${JSON.stringify(result)}\n`);+ }+} finally { await checkpoint(); await contract.close(); }diff --git a/apps/daemon/scripts/verify-openrouter-images.ts b/apps/daemon/scripts/verify-openrouter-images.tsnew file mode 100644index 00000000..954e6056--- /dev/null+++ b/apps/daemon/scripts/verify-openrouter-images.ts@@ -0,0 +1,111 @@+import Fastify from 'fastify';+import sharp from 'sharp';+import { createHash } from 'node:crypto';+import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { stringify } from '@iarna/toml';+import { createDefaultCreatorServicesConfig, type GatewayModel } from '@opencreator/protocol';+import { createGatewayCreatorSource } from '../src/gateway/creator-service-source.js';+import { createDirectTransport, DIRECT_MEDIA_ADAPTER_VERSION } from '../src/gateway/direct-transport.js';+import { generateImageContents } from '../src/image-generation/provider.js';+import { readPrivateJsonFile } from '../src/config/private-json-file.js';+import { createOfficialFetch } from '../src/gateway/official-fetch.js';+import { readVerificationNetwork, verifiedCountries } from './openrouter-verification-network.js';++// The key is supplied through stdin so it never enters shell arguments or acceptance reports.+const chunks: Buffer[] = [];+for await (const chunk of process.stdin) {+ chunks.push(Buffer.from(chunk));+ if (Buffer.concat(chunks).length > 16_384) throw new Error('Invalid platform credential input');+}+if (chunks.length === 0) throw new Error('Supply a dedicated platform verification credential through stdin');+const credential = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { key?: string; costBearer?: string; name?: string };+const key = credential.key;+if (!key || !key.startsWith('sk-or-') || credential.costBearer !== 'platform' || !credential.name?.startsWith('OpenCreator platform media verification')) throw new Error('An independently provisioned platform verification key is required');+const outputRoot = resolve(process.argv[2] ?? '.state/media-verification');+await mkdir(outputRoot, { recursive: true, mode: 0o700 });+const keyInfo = async () => {+ const response = await fetch('https://openrouter.ai/api/v1/key', { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error('Platform verification key could not be inspected');+ const { data } = await response.json() as { data: { label?: string; limit?: number; usage?: number; is_management_key?: boolean } };+ if (data.is_management_key || typeof data.limit !== 'number' || data.limit <= 0 || data.limit > 0.15) throw new Error('Use a dedicated platform verification key with a maximum USD 0.15 limit');+ return { limitUsd: data.limit, usageUsd: data.usage ?? 0 };+};+const initialUsage = await keyInfo();+const results: Array<Record<string, unknown>> = [];+const approvals: Array<Record<string, unknown>> = [];++for (const id of ['black-forest-labs/flux-3-image', 'black-forest-labs/flux.2-klein-4b']) {+ const modelRoot = join(outputRoot, id.split('/').at(-1)!);+ const receiptsRoot = join(modelRoot, 'receipts');+ await mkdir(modelRoot, { recursive: true, mode: 0o700 });+ const response = await fetch(`https://openrouter.ai/api/v1/images/models/${id}/endpoints`, { signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error(`Endpoint metadata unavailable for ${id}`);+ const metadata = await response.json() as { endpoints?: Array<{ supported_parameters?: Record<string, { max?: number; values?: string[] }> }> };+ const parameters = metadata.endpoints?.[0]?.supported_parameters;+ if (!parameters?.aspect_ratio?.values?.includes('1:1')) throw new Error(`A square verification profile is unavailable for ${id}`);+ const model: GatewayModel = { id, modality: 'image', capabilities: [], imageOptions: {+ maxImages: 1, maxReferences: 0, aspectRatios: ['1:1'],+ ...(parameters.resolution?.values?.includes('1K') ? { resolutions: ['1K'] } : {}),+ ...(parameters.output_format?.values?.includes('png') ? { outputFormats: ['png'] } : {})+ } };+ let submissions = 0;+ const officialFetch = createOfficialFetch();+ const networkBefore = await readVerificationNetwork(officialFetch);+ const fetcher: typeof fetch = async (url, options) => {+ if (String(url) === 'https://openrouter.ai/api/v1/images' && options?.method === 'POST') submissions++;+ return officialFetch(url, options);+ };+ const manual = createDefaultCreatorServicesConfig();+ const source = createGatewayCreatorSource({ directRequestsRoot: receiptsRoot, fetcher,+ account: {+ peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'platform-verification', email: 'platform-verification@invalid', verified: true }, bindingVersion: 'platform-verification', models: [model], selectedModels: { image: id }, activationError: null }),+ modelCredentials: async () => ({ accountId: 'platform-verification', bindingVersion: 'platform-verification', keyVersion: 'platform', modelKey: key, baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models: [model], defaults: { image: id } })+ },+ manual: { read: async () => structuredClone(manual), write: async value => value, reset: async () => manual },+ getLocalOrigin: () => origin+ });+ const server = Fastify();+ let origin: string | undefined;+ try {+ await source.register(server);+ origin = await server.listen({ host: '127.0.0.1', port: 0 });+ const config = await source.store.read();+ let requestId: string | undefined;+ process.stderr.write(`${JSON.stringify({ model: id, phase: 'submitting_platform_verification' })}\n`);+ const generated = await generateImageContents({ provider: 'openai', prompt: 'A red ceramic cup on a white table, simple product photograph.', size: '1024x1024', quality: 'medium', count: 1, aspectRatio: '1:1', ...(model.imageOptions?.resolutions?.length ? { resolution: '1K' } : {}) }, config,+ { logicalId: `verify:${id}`, onGatewayRequest: id => { requestId = id; } });+ const content = generated.contents[0]?.content;+ if (!content || !requestId || submissions !== 1) throw new Error('Generation did not return exactly one recoverable image');+ const image = await sharp(content).metadata();+ if (!image.width || !image.height || image.width !== image.height) throw new Error('The generated image failed square-profile validation');+ const imagePath = join(modelRoot, `image.${image.format === 'jpeg' ? 'jpg' : image.format}`);+ await writeFile(imagePath, content, { mode: 0o600 });+ if (!content.equals(await readFile(imagePath))) throw new Error('The generated image could not be saved correctly');+ const restarted = createDirectTransport(receiptsRoot, fetcher);+ const replay = await restarted.request({ account: 'platform-verification', key, method: 'GET', resource: `requests/${requestId}/result`, body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal: AbortSignal.timeout(30_000) });+ const replayData = await replay.json() as { data?: Array<{ b64_json?: string }> };+ if (!content.equals(Buffer.from(replayData.data?.[0]?.b64_json ?? '', 'base64')) || submissions !== 1) throw new Error('Restart recovery did not replay the original image');+ const receipt = await readPrivateJsonFile(join(receiptsRoot, `${requestId}.json`)) as Record<string, unknown>;+ results.push({ model: id, status: 'passed', width: image.width, height: image.height, format: image.format, submissions, restartReplay: true, sha256: createHash('sha256').update(content).digest('hex'), requestId, upstreamRequestId: receipt.upstreamRequestId, upstreamGenerationId: receipt.upstreamGenerationId, reportedCostUsd: receipt.reportedCostUsd });+ const networkAfter = await readVerificationNetwork(officialFetch).catch(() => undefined);+ const countries = verifiedCountries(networkBefore, networkAfter);+ results.at(-1)!.verifiedCountries = countries;+ approvals.push({ id, modality: 'image', capabilities: [], adapter_version: DIRECT_MEDIA_ADAPTER_VERSION, verified_at: new Date().toISOString(), evidence: join(outputRoot, 'report.json'), verified_countries: countries, image_options: { max_images: 1, max_references: 0, aspect_ratios: ['1:1'], resolutions: model.imageOptions?.resolutions ?? [], output_formats: model.imageOptions?.outputFormats ?? [] } });+ } catch (error) {+ const receipts = await readdir(receiptsRoot).catch(() => []);+ const evidence = await Promise.all(receipts.filter(name => name.endsWith('.json')).map(async name => {+ const receipt = await readPrivateJsonFile(join(receiptsRoot, name)) as Record<string, unknown>;+ return { requestId: name.replace(/\.json$/, ''), state: receipt.state, upstreamError: receipt.upstreamError, upstreamRequestId: receipt.upstreamRequestId, upstreamGenerationId: receipt.upstreamGenerationId, reportedCostUsd: typeof receipt.reportedCostUsd === 'number' ? receipt.reportedCostUsd : undefined };+ }));+ results.push({ model: id, status: 'failed', submissions, reportedCostUsd: evidence.reduce((sum, receipt) => sum + (receipt.reportedCostUsd ?? 0), 0), error: error instanceof Error ? error.message.replaceAll(key, '[redacted]') : 'Verification failed', evidence });+ } finally { await source.revoke(); await server.close(); }+}+const finalUsage = await keyInfo();+const incrementalUsageUsd = finalUsage.usageUsd - initialUsage.usageUsd;+const upstreamReportedCostUsd = results.reduce((sum, result) => sum + (typeof result.reportedCostUsd === 'number' ? result.reportedCostUsd : 0), 0);+const report = { adapterVersion: DIRECT_MEDIA_ADAPTER_VERSION, networkTransport: 'official-fetch', verifiedAt: new Date().toISOString(), costBearer: 'platform', usage: { ...finalUsage, incrementalUsageUsd, upstreamReportedCostUsd, usageUpdatePending: incrementalUsageUsd + 1e-9 < upstreamReportedCostUsd }, results };+await writeFile(join(outputRoot, 'report.json'), `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 });+await writeFile(join(outputRoot, 'verified-media.toml'), stringify({ openrouter: { verified_media_models: approvals } } as never), { mode: 0o600 });+process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);+if (results.some(result => result.status !== 'passed')) process.exitCode = 1;diff --git a/apps/daemon/scripts/verify-openrouter-media.ts b/apps/daemon/scripts/verify-openrouter-media.tsnew file mode 100644index 00000000..348a5f80--- /dev/null+++ b/apps/daemon/scripts/verify-openrouter-media.ts@@ -0,0 +1,287 @@+import Fastify from 'fastify';+import sharp from 'sharp';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { createHash } from 'node:crypto';+import { access, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';+import { setTimeout as delay } from 'node:timers/promises';+import { join, resolve } from 'node:path';+import { stringify } from '@iarna/toml';+import { createDefaultCreatorServicesConfig, gatewayVideoSizes, type VideoGenerationSize } from '@opencreator/protocol';+import { createGatewayCreatorSource } from '../src/gateway/creator-service-source.js';+import { createDirectTransport, DIRECT_MEDIA_ADAPTER_VERSION } from '../src/gateway/direct-transport.js';+import { generateImageContents } from '../src/image-generation/provider.js';+import { createVideoGenerationService } from '../src/video-generation/service.js';+import { validateMediaFile } from '../src/creator/validators/media.js';+import { readPrivateJsonFile } from '../src/config/private-json-file.js';+import { createOfficialFetch } from '../src/gateway/official-fetch.js';+import { readVerificationNetwork, verifiedCountries } from './openrouter-verification-network.js';+import { familyRepresentatives, mediaFamily, mediaProfile, passedProfile, profileOperations, referenceDimensions, videoShapeMismatch, verificationBlockReason, type MediaCatalogItem, type MediaProfile, type VerificationFailureEvidence } from './openrouter-media-profiles.js';++const args = process.argv.slice(2);+const option = (name: string) => args.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3);+const outputRoot = resolve(args.find(arg => !arg.startsWith('--')) ?? '.state/media-verification');+const budgetUsd = Number(option('budget') ?? 3);+if (!Number.isFinite(budgetUsd) || budgetUsd <= 0 || budgetUsd > 30) throw new Error('Verification budget must be greater than zero and no more than USD 30');+const modality = option('modality') ?? 'all';+if (!['all', 'image', 'video'].includes(modality)) throw new Error('Invalid verification modality');+const concurrency = Number(option('concurrency') ?? 1);+if (concurrency !== 1) throw new Error('Family verification is sequential to stop spending immediately on a funding block');+const planOnly = args.includes('--plan');+const evidenceOnly = args.includes('--evidence-only');+const referenceTests = args.includes('--reference-tests');+const retryFailed = args.includes('--retry-failed');+const exec = promisify(execFile);+const upstream = createOfficialFetch();+await mkdir(outputRoot, { recursive: true, mode: 0o700 });+if (!planOnly && await access(join(outputRoot, 'report.json')).then(() => true, () => false)) throw new Error('Use a fresh report directory; existing paid runs must never be resubmitted');+const catalogs: Record<string, MediaCatalogItem[]> = {};+if (option('video-shape') && !option('model')) throw new Error('A video shape override requires an explicit model');+if (option('catalog')) Object.assign(catalogs, JSON.parse(await readFile(resolve(option('catalog')!), 'utf8')));+else for (const kind of ['image', 'video'] as const) {+ const response = await upstream(`https://openrouter.ai/api/v1/${kind}s/models`, { signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error(`The ${kind} model catalog is unavailable`);+ const { data } = await response.json() as { data?: MediaCatalogItem[] };+ if (!Array.isArray(data) || data.some(item => typeof item.id !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._:-]+$/.test(item.id))) throw new Error('Invalid model catalog');+ catalogs[kind] = data;+}+const inventory = Object.entries(catalogs).flatMap(([kind, items]) => items+ .filter(item => !option('model') || item.id === option('model'))+ .map(item => mediaProfile(item, kind as 'image' | 'video', kind === 'video' ? option('video-shape') : undefined)))+ .filter(profile => modality === 'all' || profile.modality === modality);+const profiles = option('model') ? inventory : familyRepresentatives(inventory);+if (!profiles.length) throw new Error('No models matched the verification selection');+const unsupported = inventory.filter(profile => !profile.model).map(({ id, unsupportedReason }) => ({ id, reason: unsupportedReason }));+const unclassified = inventory.filter(profile => profile.model && !mediaFamily(profile)).map(profile => profile.id);+const families = profiles.map(profile => ({ modality: profile.modality, family: mediaFamily(profile) ?? 'explicit selection', representative: profile.id, operations: profileOperations(profile) }));+await writeFile(join(outputRoot, 'catalog.json'), `${JSON.stringify(catalogs, null, 2)}\n`, { mode: 0o600 });+await writeFile(join(outputRoot, 'plan.json'), `${JSON.stringify({ discoveredAt: new Date().toISOString(), selection: 'family-representatives', referenceTests, budgetUsd, families, unsupported, unclassified, profiles }, null, 2)}\n`, { mode: 0o600 });+if (planOnly) {+ process.stdout.write(`${JSON.stringify({ families, eligible: profiles.filter(profile => profile.model).length, unsupported, unclassified, budgetUsd })}\n`);+ process.exit(0);+}++const ffprobe = option('ffprobe') ?? 'ffprobe';+const ffmpeg = option('ffmpeg') ?? 'ffmpeg';+if (!evidenceOnly && profiles.some(profile => profile.model?.modality === 'video')) {+ await exec(ffprobe, ['-version'], { timeout: 10_000 });+ await exec(ffmpeg, ['-version'], { timeout: 10_000 });+}+const referencePath = option('reference-image');+if (!referencePath && !evidenceOnly) throw new Error('Supply --reference-image=/path/to/a/test-image for edit and image-to-video verification');+const reference = referencePath ? await readFile(referencePath) : undefined;++// Credentials travel through stdin and never enter shell arguments or report artifacts.+const chunks: Buffer[] = [];+let credentialBytes = 0;+if (!evidenceOnly) for await (const chunk of process.stdin) {+ credentialBytes += chunk.length;+ if (credentialBytes > 16_384) throw new Error('Invalid platform credential input');+ chunks.push(Buffer.from(chunk));+}+const credential = evidenceOnly ? {} : JSON.parse(Buffer.concat(chunks).toString('utf8')) as { key?: string; costBearer?: string; name?: string; accountRemainingUsd?: number; productionReserveUsd?: number; balanceCheckedAt?: string };+const key = credential.key;+if (!evidenceOnly) {+ if (!key?.startsWith('sk-or-') || credential.costBearer !== 'platform' || !credential.name?.startsWith('OpenCreator platform media verification')) throw new Error('Use a dedicated platform verification key');+ const checkedAt = Date.parse(credential.balanceCheckedAt ?? '');+ if (!Number.isFinite(checkedAt) || Date.now() - checkedAt > 60_000 || checkedAt > Date.now() + 5_000+ || typeof credential.accountRemainingUsd !== 'number' || !Number.isFinite(credential.accountRemainingUsd)+ || typeof credential.productionReserveUsd !== 'number' || credential.productionReserveUsd < 5+ || credential.accountRemainingUsd < budgetUsd + credential.productionReserveUsd) throw new Error('Provisioner must confirm fresh owner balance covering the test budget plus at least USD 5 production reserve');+}+async function keyInfo() {+ const response = await upstream('https://openrouter.ai/api/v1/key', { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(30_000), redirect: 'error' });+ if (!response.ok) throw new Error('Verification key inspection failed');+ const { data } = await response.json() as { data: { limit?: number; usage?: number; is_management_key?: boolean } };+ if (data.is_management_key || typeof data.limit !== 'number' || data.limit <= 0 || data.limit > budgetUsd) throw new Error('The platform verification key must have a cumulative limit within the verification budget');+ return { limitUsd: data.limit, usageUsd: data.usage ?? 0 };+}+const initialUsage = evidenceOnly ? { limitUsd: 0, usageUsd: 0 } : await keyInfo();+type OperationResult = { operation: string; status: 'passed' | 'failed' | 'blocked' | 'untested'; submissions: number; reportedCostUsd?: number; blockReason?: string; evidence?: VerificationFailureEvidence[]; reusedFrom?: string; [key: string]: unknown };+type ModelResult = { model: string; modality: string; status: 'pending' | 'passed' | 'partial' | 'failed' | 'blocked' | 'untested' | 'unsupported'; reason?: string; operations: OperationResult[] };+const results: ModelResult[] = profiles.map(profile => ({ model: profile.id, modality: profile.modality, status: profile.model ? 'pending' : 'unsupported', reason: profile.unsupportedReason, operations: [] }));+const approvals: Array<Record<string, unknown>> = [];+let reportWrites = Promise.resolve();+let observedUsage = initialUsage;+let fundingBlocked = false;+const priorReports = await Promise.all(args.filter(arg => arg.startsWith('--reuse-report=')).map(async arg => {+ const path = resolve(arg.slice('--reuse-report='.length));+ const report = JSON.parse(await readFile(path, 'utf8')) as { adapterVersion: number; networkTransport: string; results: ModelResult[] };+ const plan = JSON.parse(await readFile(join(resolve(path, '..'), 'plan.json'), 'utf8')) as { profiles: MediaProfile[] };+ if (report.adapterVersion !== DIRECT_MEDIA_ADAPTER_VERSION || report.networkTransport !== 'official-fetch') throw new Error('Reuse requires matching adapter version and official transport');+ return { path, report, plan };+}));+async function previousOperation(profile: MediaProfile, operation: string): Promise<OperationResult | undefined> {+ for (const { path, report, plan } of priorReports) {+ if (JSON.stringify(plan.profiles.find(item => item.id === profile.id)?.model) !== JSON.stringify(profile.model)) continue;+ const prior = report.results.find(result => result.model === profile.id)?.operations.find(result => result.operation === operation);+ if (!prior) continue;+ if (prior.status === 'passed') {+ if (prior.restartReplay !== true || typeof prior.outputPath !== 'string' || typeof prior.sha256 !== 'string') throw new Error('Incomplete previous acceptance evidence');+ const content = await readFile(prior.outputPath);+ if (createHash('sha256').update(content).digest('hex') !== prior.sha256) throw new Error('Previous media evidence hash mismatch');+ if (profile.modality === 'video') {+ if (typeof prior.width !== 'number' || typeof prior.height !== 'number') throw new Error('Previous video dimensions are missing');+ const mismatch = videoShapeMismatch(profile.model!, prior.width, prior.height);+ if (mismatch) return { ...prior, status: 'failed', error: mismatch, submissions: 0, reusedFrom: path };+ }+ return { ...prior, submissions: 0, reusedFrom: path };+ }+ const blockReason = verificationBlockReason(prior.evidence ?? []);+ const unknownOutcome = (prior.evidence as Array<{ state?: string }> | undefined)?.some(item => ['submitting', 'waiting_upstream', 'outcome_unknown'].includes(item.state ?? ''));+ if (blockReason === 'provider-access' || unknownOutcome || evidenceOnly || (!retryFailed && blockReason !== 'funding')) return { ...prior, status: blockReason || unknownOutcome ? 'blocked' : 'failed', blockReason: unknownOutcome ? 'unknown-outcome' : blockReason, submissions: 0, reusedFrom: path };+ }+ return undefined;+}+function checkpoint() {+ reportWrites = reportWrites.then(async () => {+ const reportedCostUsd = results.flatMap(result => result.operations).reduce((sum, operation) => sum + (operation.reusedFrom ? 0 : operation.reportedCostUsd ?? 0), 0);+ const report = { adapterVersion: DIRECT_MEDIA_ADAPTER_VERSION, networkTransport: 'official-fetch', updatedAt: new Date().toISOString(), selection: 'family-representatives', families, unsupported, unclassified, fundingBlocked, costBearer: 'platform', referenceSha256: reference ? createHash('sha256').update(reference).digest('hex') : undefined, catalogCounts: Object.fromEntries(Object.entries(catalogs).map(([kind, items]) => [kind, items.length])), usage: { ...observedUsage, incrementalUsageUsd: observedUsage.usageUsd - initialUsage.usageUsd, upstreamReportedCostUsd: reportedCostUsd, usageUpdatePending: observedUsage.usageUsd - initialUsage.usageUsd + 1e-9 < reportedCostUsd }, results };+ await writeFile(join(outputRoot, 'report.json'), `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 });+ await writeFile(join(outputRoot, 'verified-media.toml'), stringify({ openrouter: { verified_media_models: approvals } } as never), { mode: 0o600 });+ });+ return reportWrites;+}+await checkpoint();++async function verifyOperation(profile: MediaProfile, operation: string): Promise<OperationResult> {+ const model = profile.model!;+ const firstFrame = await sharp(reference!).resize(referenceDimensions(model).width, referenceDimensions(model).height, { fit: 'contain', background: 'white' }).png().toBuffer();+ const root = join(outputRoot, profile.modality, profile.id.replace('/', '__'), operation);+ const receiptsRoot = join(root, 'receipts');+ await mkdir(root, { recursive: true, mode: 0o700 });+ const networkBefore = await readVerificationNetwork(upstream);+ let submissions = 0;+ const fetcher: typeof fetch = async (url, options) => {+ if (options?.method === 'POST' && /^https:\/\/openrouter\.ai\/api\/v1\/(images|videos)$/.test(String(url))) {+ if (submissions >= 1) throw new Error('The verifier blocked a second paid submission');+ if (fundingBlocked) throw new Error('No new submissions after a funding block');+ const usage = await keyInfo();+ observedUsage = usage;+ const reported = results.flatMap(result => result.operations).reduce((sum, result) => sum + (result.reusedFrom ? 0 : result.reportedCostUsd ?? 0), 0);+ if (Math.max(usage.usageUsd, initialUsage.usageUsd + reported) >= Math.min(usage.limitUsd, budgetUsd)) { fundingBlocked = true; throw new Error('The verification budget is exhausted'); }+ submissions++;+ }+ return upstream(url, options);+ };+ const manual = createDefaultCreatorServicesConfig();+ let origin: string | undefined;+ const source = createGatewayCreatorSource({ directRequestsRoot: receiptsRoot, fetcher,+ account: {+ peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'platform-verification', email: 'platform-verification@invalid', verified: true }, bindingVersion: 'platform-verification', models: [model], selectedModels: { [model.modality]: model.id }, activationError: null }),+ modelCredentials: async () => ({ accountId: 'platform-verification', bindingVersion: 'platform-verification', keyVersion: 'platform', modelKey: key!, baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models: [model], defaults: { [model.modality]: model.id } })+ },+ manual: { read: async () => structuredClone(manual), write: async value => value, reset: async () => manual },+ getLocalOrigin: () => origin+ });+ const server = Fastify();+ let requestId: string | undefined;+ let observedMedia: Record<string, unknown> | undefined;+ let deliveryVerified = false;+ let parameterError: string | undefined;+ const logicalId = `verify:${profile.id}:${operation}`;+ process.stderr.write(`${JSON.stringify({ model: profile.id, operation, phase: 'submitting' })}\n`);+ try {+ await source.register(server);+ origin = await server.listen({ host: '127.0.0.1', port: 0 });+ let content: Buffer;+ let media: Record<string, unknown>;+ const restarted = createDirectTransport(receiptsRoot, fetcher);+ if (model.modality === 'image') {+ const config = await source.store.read();+ const options = model.imageOptions!;+ const generated = await generateImageContents({ provider: 'openai', prompt: operation === 'image-edit' ? 'Change the ceramic cup to blue. Keep the white table and composition.' : 'A red ceramic cup on a white table, simple product photograph.', size: '1024x1024', quality: 'medium', count: 1, aspectRatio: options.aspectRatios?.[0], resolution: options.resolutions?.[0], officialQuality: options.qualities?.[0] }, config, { logicalId, onGatewayRequest: id => { requestId = id; }, ...(operation === 'image-edit' ? { referenceImage: { content: firstFrame, mime: 'image/png' as const } } : {}) });+ content = generated.contents[0]?.content!;+ if (generated.contents.length !== 1 || !content?.length || !requestId || submissions !== 1) throw new Error('The image was not delivered with one recoverable submission');+ const image = await sharp(content).metadata();+ await sharp(content).raw().toBuffer();+ if (!image.width || !image.height || !['png', 'jpeg', 'webp'].includes(image.format ?? '')) throw new Error('The generated raster image could not be decoded');+ if (options.aspectRatios?.[0]) {+ const [a, b] = options.aspectRatios[0].split(':').map(Number);+ if (Math.abs(image.width / image.height - a! / b!) > 0.02) parameterError = 'The image does not match the verified aspect ratio';+ }+ const outputPath = join(root, `image.${image.format === 'jpeg' ? 'jpg' : image.format}`);+ observedMedia = { width: image.width, height: image.height, format: image.format, outputPath };+ await writeFile(outputPath, content, { mode: 0o600 });+ if (!content.equals(await readFile(outputPath))) throw new Error('Image saving failed');+ const replay = await restarted.request({ account: 'platform-verification', key: key!, method: 'GET', resource: `requests/${requestId}/result`, body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal: AbortSignal.timeout(30_000) });+ const replayData = await replay.json() as { data?: Array<{ b64_json?: string }> };+ if (!content.equals(Buffer.from(replayData.data?.[0]?.b64_json ?? '', 'base64'))) throw new Error('Image restart replay failed');+ media = observedMedia;+ } else {+ const createService = () => createVideoGenerationService({ dataDir: root, configStore: source.store, gatewaySource: source });+ const size = gatewayVideoSizes(model)[0]! as VideoGenerationSize;+ const duration = model.durations![0]!;+ let task = await createService().create({ provider: 'seedance', model: model.id, prompt: operation === 'image-to-video' ? 'The camera slowly moves around the ceramic cup on the white table.' : 'A red ceramic cup on a white table. The camera slowly moves around the cup.', size, duration, ...(operation === 'image-to-video' ? { referenceImage: { mime: 'image/png' as const, data: firstFrame.toString('base64') } } : {}) }, { logicalId, onGatewayRequest: id => { requestId = id; } });+ const service = createService();+ const deadline = Date.now() + 20 * 60_000;+ while (!['completed', 'failed'].includes(task.status)) {+ if (Date.now() >= deadline) throw new Error('Video generation did not finish within the verification deadline; do not resubmit');+ await delay(5_000);+ task = await service.refresh(task.id, { signal: AbortSignal.timeout(120_000), onGatewayRequest: id => { requestId = id; } });+ }+ if (task.status !== 'completed' || !requestId || submissions !== 1) throw new Error('Video generation failed or did not produce a recoverable result');+ content = (await service.read(task.id)).content;+ const outputPath = join(root, 'video.mp4');+ await service.copyTo(task.id, outputPath);+ if (!content.equals(await readFile(outputPath))) throw new Error('Video saving failed');+ const probe = await validateMediaFile(outputPath, ffprobe);+ observedMedia = { ...probe, outputPath, resultId: task.id };+ if (!probe.hasVideo || !probe.width || !probe.height || Math.abs(probe.duration - duration) > 0.75) throw new Error('The generated video does not match the requested duration');+ parameterError = videoShapeMismatch(model, probe.width, probe.height);+ await exec(ffmpeg, ['-v', 'error', '-xerror', '-i', outputPath, '-map', '0:v:0', '-f', 'null', '-'], { timeout: 120_000, maxBuffer: 1024 * 1024 });+ await exec(ffmpeg, ['-v', 'error', '-ss', String(probe.duration / 2), '-i', outputPath, '-frames:v', '1', join(root, 'poster.jpg')], { timeout: 30_000 });+ const replay = await restarted.request({ account: 'platform-verification', key: key!, method: 'GET', resource: `requests/${requestId}`, body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal: AbortSignal.timeout(30_000) });+ if ((await replay.json() as { state?: string }).state !== 'succeeded') throw new Error('Video restart lookup failed');+ const downloaded = await restarted.request({ account: 'platform-verification', key: key!, method: 'GET', resource: `requests/${requestId}/result`, body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal: AbortSignal.timeout(120_000) });+ if (!content.equals(Buffer.from(await downloaded.arrayBuffer()))) throw new Error('Video restart download failed');+ media = observedMedia;+ }+ if (submissions !== 1) throw new Error('Recovery triggered another paid submission');+ deliveryVerified = true;+ if (parameterError) throw new Error(parameterError);+ const receipt = await readPrivateJsonFile(join(receiptsRoot, `${requestId}.json`)) as Record<string, unknown>;+ const networkAfter = await readVerificationNetwork(upstream).catch(() => undefined);+ return { operation, status: 'passed', submissions, ...media!, restartReplay: true, sha256: createHash('sha256').update(content!).digest('hex'), requestId, upstreamRequestId: receipt.upstreamRequestId, upstreamGenerationId: receipt.upstreamGenerationId, reportedCostUsd: typeof receipt.reportedCostUsd === 'number' ? receipt.reportedCostUsd : undefined,+ verifiedCountries: verifiedCountries(networkBefore, networkAfter), networkBefore, networkAfter };+ } catch (error) {+ const files = await readdir(receiptsRoot).catch(() => []);+ const evidence = await Promise.all(files.filter(name => name.endsWith('.json')).map(async name => {+ const receipt = await readPrivateJsonFile(join(receiptsRoot, name)) as Record<string, unknown> & VerificationFailureEvidence;+ return { requestId: name.replace(/\.json$/, ''), state: receipt.state, model: receipt.model, upstreamError: receipt.upstreamError, upstreamRequestId: receipt.upstreamRequestId, upstreamGenerationId: receipt.upstreamGenerationId, reportedCostUsd: typeof receipt.reportedCostUsd === 'number' ? receipt.reportedCostUsd : undefined };+ }));+ const blockReason = verificationBlockReason(evidence) ?? (fundingBlocked ? 'funding' : undefined);+ if (blockReason === 'funding') fundingBlocked = true;+ return { operation, status: blockReason ? 'blocked' : 'failed', blockReason, submissions, ...observedMedia, deliveryVerified, parametersMatched: parameterError ? false : undefined, reportedCostUsd: evidence.reduce((sum, receipt) => sum + (receipt.reportedCostUsd ?? 0), 0), error: error instanceof Error ? error.message.replaceAll(key!, '[redacted]') : 'Verification failed', evidence };+ } finally { await source.revoke(); await server.close(); }+}++// Cover each family's base generation before spending on reference operations.+for (const phase of ['generation', 'references']) {+ for (const [index, profile] of profiles.entries()) {+ if (!profile.model) continue;+ const result = results[index]!;+ const operations = profileOperations(profile);+ for (const operation of operations.filter((_, i) => phase === 'generation' ? i === 0 : i > 0)) {+ const prior = await previousOperation(profile, operation);+ const referenceUnselected = phase === 'references' && (!referenceTests || result.operations[0]?.status !== 'passed');+ const current = prior ?? (evidenceOnly || referenceUnselected ? { operation, status: 'untested' as const, submissions: 0 } : fundingBlocked ? { operation, status: 'blocked' as const, blockReason: 'funding', submissions: 0 } : await verifyOperation(profile, operation));+ result.operations.push(current);+ await checkpoint();+ }+ const passed = result.operations.filter(operation => operation.status === 'passed').map(operation => operation.operation);+ const admitted = passedProfile(profile.model, passed);+ result.status = passed.length === operations.length ? 'passed' : passed.length ? 'partial' : result.operations.some(op => op.status === 'failed') ? 'failed' : result.operations.some(op => op.status === 'blocked') ? 'blocked' : 'untested';+ const previousApproval = approvals.findIndex(item => item.id === profile.id);+ if (previousApproval >= 0) approvals.splice(previousApproval, 1);+ const regionalProfiles = result.operations.filter(operation => operation.status === 'passed').map(operation => Array.isArray(operation.verifiedCountries) ? operation.verifiedCountries as string[] : []);+ const countries = regionalProfiles[0]?.filter(country => regionalProfiles.every(profile => profile.includes(country))) ?? [];+ if (admitted) approvals.push({ id: admitted.id, modality: admitted.modality, capabilities: admitted.capabilities, adapter_version: DIRECT_MEDIA_ADAPTER_VERSION, verified_at: new Date().toISOString(), evidence: join(outputRoot, 'report.json'), verified_countries: countries, ...(admitted.imageOptions ? { image_options: { max_images: 1, max_references: admitted.imageOptions.maxReferences, aspect_ratios: admitted.imageOptions.aspectRatios, resolutions: admitted.imageOptions.resolutions, qualities: admitted.imageOptions.qualities, output_formats: admitted.imageOptions.outputFormats } } : { durations: admitted.durations, sizes: admitted.sizes ?? [], resolutions: admitted.resolutions ?? [], aspect_ratios: admitted.aspectRatios ?? [] }) });+ process.stderr.write(`${JSON.stringify({ model: profile.id, status: result.status, operations: result.operations.map(({ operation, status }) => ({ operation, status })) })}\n`);+ await checkpoint();+ }+}+if (!evidenceOnly) try { observedUsage = await keyInfo(); } catch { process.stderr.write('Final key usage is unavailable; confirm usage when disabling the platform key.\n'); }+await checkpoint();+process.stdout.write(`${JSON.stringify({ report: join(outputRoot, 'report.json'), counts: Object.fromEntries(['passed', 'partial', 'failed', 'blocked', 'untested', 'unsupported', 'pending'].map(status => [status, results.filter(result => result.status === status).length])), admittedModels: approvals.length, observedUsage })}\n`);+if (results.some(result => result.status !== 'passed')) process.exitCode = 1;diff --git a/apps/daemon/src/agent-tools/creator-tools.ts b/apps/daemon/src/agent-tools/creator-tools.tsindex 8c19c6bc..74e3bd4d 100644--- a/apps/daemon/src/agent-tools/creator-tools.ts+++ b/apps/daemon/src/agent-tools/creator-tools.ts@@ -35,7 +35,7 @@ export type CreatorToolOperations = {timedOut: boolean;context: AgentContextEnvelope;}>;- applyAction(jobId: string, request: CreatorCommandRequest): CreatorCommandDispatchResult;+ applyAction(jobId: string, request: CreatorCommandRequest): CreatorCommandDispatchResult | Promise<CreatorCommandDispatchResult>;};export function createCreatorToolOperations(input: {@@ -97,7 +97,8 @@ export function createCreatorToolOperations(input: {},applyAction(jobId, request) {requireJob(input.service, jobId);- return input.dispatcher.dispatch(jobId, request, 'agent');+ return request.action === 'resolve-provider-request' && request.input.decision === 'query'+ ? input.dispatcher.dispatchAsync(jobId, request, 'agent') : input.dispatcher.dispatch(jobId, request, 'agent');}};}diff --git a/apps/daemon/src/agent-tools/internal-routes.ts b/apps/daemon/src/agent-tools/internal-routes.tsindex 5222ba68..aad63591 100644--- a/apps/daemon/src/agent-tools/internal-routes.ts+++ b/apps/daemon/src/agent-tools/internal-routes.ts@@ -189,7 +189,7 @@ export async function registerAgentToolRoutes(return reply.code(400).send(apiError('VALIDATION_FAILED', 'actor, jobId and projectId are bound by the capability token'));}try {- return input.creator!.applyAction(grant.jobId, {+ return await input.creator!.applyAction(grant.jobId, {action: readRequiredString(body.action, 'action'),expectedRevision: readRequiredInteger(body.expectedRevision, 'expectedRevision'),idempotencyKey: readRequiredString(body.idempotencyKey, 'idempotencyKey'),diff --git a/apps/daemon/src/api/routes.creator-services.ts b/apps/daemon/src/api/routes.creator-services.tsindex 5297b2a2..efc84fe6 100644--- a/apps/daemon/src/api/routes.creator-services.ts+++ b/apps/daemon/src/api/routes.creator-services.ts@@ -74,7 +74,7 @@ export async function registerCreatorServicesRoutes(reply.header('Cache-Control', 'no-store');return readCodexImageStatus ? await readCodexImageStatus() : {authentication: 'none', ready: false, executionMode: null,- message: '当前 Runtime 未配置 Codex 生图能力检查,请更新或检查 Runtime'+ message: 'Codex image capability checks are not configured. Update or check the Runtime.'} satisfies CodexImageStatus;});@@ -126,7 +126,7 @@ export async function registerCreatorServicesRoutes('VALIDATION_FAILED',firstIssue === undefined? 'Creator services configuration is invalid'- : `字段 ${firstIssue.field || 'config'} 无效:${firstIssue.message}`,+ : `Invalid field ${firstIssue.field || 'config'}: ${firstIssue.message}`,{ fields: issues }));}diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.tsindex 73aea870..a00828df 100644--- a/apps/daemon/src/api/routes.creator.ts+++ b/apps/daemon/src/api/routes.creator.ts@@ -997,7 +997,7 @@ export async function registerCreatorRoutes(}}const expectedRevision = readInteger(body.expectedRevision, 'expectedRevision');- const result = options.dispatcher.dispatch(id, {+ const result = await options.dispatcher.dispatchAsync(id, {idempotencyKey: typeof body.idempotencyKey === 'string'? body.idempotencyKey: fallbackIdempotencyKey(id, action, expectedRevision, actionInput),@@ -1556,11 +1556,11 @@ function errorCodeForIssue(error: unknown): string {}function fallbackForIssueSource(source: IssueSource): string {- if (source === 'upload') return '上传未完成,请检查文件后重试。';- if (source === 'preflight') return '执行条件未满足,请按提示修正后重试。';- if (source === 'provider') return '外部服务调用失败,请检查配置或稍后重试。';- if (source === 'agent') return 'Agent 操作未完成,可以在此询问原因。';- return '操作未完成,可以重试或询问 Agent。';+ if (source === 'upload') return 'The upload did not complete. Check the file and try again.';+ if (source === 'preflight') return 'Prerequisites are not met. Resolve the reported issues and try again.';+ if (source === 'provider') return 'The external service request failed. Check the configuration or try again later.';+ if (source === 'agent') return 'The Agent operation did not complete. Ask the Agent for details.';+ return 'The operation did not complete. Try again or ask the Agent.';}function requireCreatorJob(service: CreatorService, jobId: string): CreatorJob {diff --git a/apps/daemon/src/api/routes.gateway-account.ts b/apps/daemon/src/api/routes.gateway-account.tsindex 22a09486..060ee638 100644--- a/apps/daemon/src/api/routes.gateway-account.ts+++ b/apps/daemon/src/api/routes.gateway-account.ts@@ -12,7 +12,7 @@ export async function registerGatewayAccountRoutes(server: FastifyInstance, servconst code = cloud.status === 401 ? 'GATEWAY_AUTH_REQUIRED' : cloud.code === 'account_disabled' ? 'GATEWAY_ACCOUNT_DISABLED': cloud.status === 402 ? 'GATEWAY_CREDITS_INSUFFICIENT' : cloud.status === 409 ? 'GATEWAY_REQUEST_CONFLICT': cloud.code === 'services_not_ready' ? 'GATEWAY_SERVICES_NOT_READY' : 'GATEWAY_UNAVAILABLE';- return reply.code(cloud.status).send(apiError(code, code === 'GATEWAY_REQUEST_CONFLICT' ? '请等待当前任务结束后再切换账户或服务来源' : cloud.message, { gatewayCode: cloud.code }));+ return reply.code(cloud.status).send(apiError(code, code === 'GATEWAY_REQUEST_CONFLICT' ? 'Wait for the active task to finish before switching accounts or service sources.' : cloud.message, { gatewayCode: cloud.code }));}}server.get('/gateway/account', (_r, reply) => respond(() => service.readState(), reply));diff --git a/apps/daemon/src/api/routes.platform-connections.ts b/apps/daemon/src/api/routes.platform-connections.tsindex 50a941f8..a0cc0a95 100644--- a/apps/daemon/src/api/routes.platform-connections.ts+++ b/apps/daemon/src/api/routes.platform-connections.ts@@ -15,7 +15,7 @@ export async function registerPlatformConnectionRoutes(server: FastifyInstance,server.post<{ Body: { profileId?: unknown } }>(`${path}/connect`, (request, reply) => {const profileId = request.body?.profileId;if (profileId !== undefined && (typeof profileId !== 'string' || !/^[a-f0-9]{24}$/.test(profileId))) {- return reply.code(400).send(apiError('VALIDATION_FAILED', '请选择有效的浏览器账号。'));+ return reply.code(400).send(apiError('VALIDATION_FAILED', 'Select a valid browser profile.'));}return connection.connect(profileId as string | undefined);});@@ -23,10 +23,10 @@ export async function registerPlatformConnectionRoutes(server: FastifyInstance,server.delete(path, () => connection.disconnect());server.post<{ Body: { cookies?: unknown } }>(`${path}/import`, async (request, reply) => {if (typeof request.body?.cookies !== 'string' || Buffer.byteLength(request.body.cookies) > 1024 * 1024) {- return reply.code(400).send(apiError('VALIDATION_FAILED', '请选择有效的 Cookie 文件。'));+ return reply.code(400).send(apiError('VALIDATION_FAILED', 'Select a valid cookie file.'));}try { return await connection.importCookies(request.body.cookies); }- catch { return reply.code(400).send(apiError('VALIDATION_FAILED', `文件中没有有效的${platform === 'youtube' ? 'YouTube' : '抖音'}会话,请检查文件或重新连接。`)); }+ catch { return reply.code(400).send(apiError('VALIDATION_FAILED', `The file contains no valid ${platform === 'youtube' ? 'YouTube' : 'Douyin'} session. Check the file or reconnect.`)); }});}}diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.tsindex 13dcebb5..f4e9d85c 100644--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@ -567,7 +567,8 @@ export async function buildServer(input: BuildServerInput) {officialBindings = createGatewayRuntimeBindings({codexHome: home, baseUrl: bootstrap.baseUrl, model: model.id, direct: bootstrap.transport === 'openrouter-direct',readProxy: readCommonProxy,- beginUse: async () => { const use = await gatewayAccount.beginModelUse(); return { key: use.credentials.modelKey, keyVersion: use.credentials.keyVersion, release: use.release }; },+ beginUse: async () => { const use = await gatewayAccount.beginModelUse(); return { key: use.credentials.modelKey, keyVersion: use.credentials.keyVersion, release: use.release, models: use.credentials.models,+ onModelFailure: (id, modality, facts) => gatewayAccount.reportModelFailure(use.credentials, id, modality, facts) }; },recoverKey: async keyVersion => { const updated = await gatewayAccount.recoverModelCredentials(keyVersion); return { key: updated.modelKey, keyVersion: updated.keyVersion }; },readCredentials: async () => ({ accountId: bootstrap.account.id, modelKey: bootstrap.modelKey, keyVersion: bootstrap.keyVersion }),closeRuntime: async () => { await Promise.all([...officialManagers.values()].map(manager => manager.close())); }@@ -1156,6 +1157,7 @@ export async function buildServer(input: BuildServerInput) {service: creatorService,repository: creatorRepository,receipts: creatorAgentRepository,+ queryProviderRequest: request => gatewayCreatorSource!.queryProviderRequest(request),onQueuedStage: () => creatorStageScheduler?.wake(),onCommitted(result) {const activity = result.job.activities.find(candidate => (@@ -1678,7 +1680,7 @@ function readCodexBinaryReadiness(runtimeRoot: string | undefined): CodexRuntimereturn {status: 'invalid',errorCode: 'codex_runtime_hash_mismatch',- message: 'Codex Runtime manifest 未提供二进制 SHA-256'+ message: 'The Codex Runtime manifest is missing the executable SHA-256'};}return {diff --git a/apps/daemon/src/codex/local-provider.ts b/apps/daemon/src/codex/local-provider.tsindex 3d1f49c0..cd7599be 100644--- a/apps/daemon/src/codex/local-provider.ts+++ b/apps/daemon/src/codex/local-provider.ts@@ -45,7 +45,7 @@ export async function readLocalCodexImageConfiguration(input: {const tokens = readRecord(auth?.tokens);if (auth?.auth_mode !== 'apikey' && (auth?.auth_mode === 'chatgpt' || readString(tokens?.access_token))) {if (!readString(tokens?.access_token)) {- throw new LocalCodexProviderError('本机 Codex 的 ChatGPT 登录凭据不完整,请在本机 Codex 中重新登录');+ throw new LocalCodexProviderError('Local Codex ChatGPT credentials are incomplete. Sign in again in local Codex.');}return { authentication: 'chatgpt' };}@@ -76,11 +76,11 @@ export async function readLocalCodexProvider(input: {const apiKey = providerToken || envToken || authToken;if (!baseUrl) {- throw new LocalCodexProviderError('本机 Codex 未配置可用于生图的 Base URL');+ throw new LocalCodexProviderError('Local Codex has no Base URL configured for image generation');}if (!apiKey) {throw new LocalCodexProviderError(- '本机 Codex 未配置图像接口可用的 API Key,请检查本机 Codex 配置'+ 'Local Codex has no API key for image generation. Check its configuration.');}return {@@ -96,9 +96,9 @@ async function readToml(path: string, optional = false): Promise<Record<string,} catch (error) {if (isNotFound(error)) {if (optional) return {};- throw new LocalCodexProviderError('未找到本机 Codex 配置');+ throw new LocalCodexProviderError('Local Codex configuration not found');}- throw new LocalCodexProviderError('无法读取本机 Codex 配置');+ throw new LocalCodexProviderError('Could not read local Codex configuration');}}@@ -110,7 +110,7 @@ async function readJson(path: string, strict = false): Promise<Record<string, unreturn record;} catch (error) {if (isNotFound(error)) return undefined;- if (strict) throw new LocalCodexProviderError('无法读取本机 Codex 登录凭据,请在本机 Codex 中重新登录或配置 API Key');+ if (strict) throw new LocalCodexProviderError('Could not read local Codex credentials. Sign in again or configure an API key.');return undefined;}}diff --git a/apps/daemon/src/codex/provider-config.ts b/apps/daemon/src/codex/provider-config.tsindex 926d6f86..877269d9 100644--- a/apps/daemon/src/codex/provider-config.ts+++ b/apps/daemon/src/codex/provider-config.ts@@ -80,12 +80,12 @@ export function createCodexProviderConfigService(input: {if (loginApiKey === undefined && current.authentication === 'none') {throw new CodexProviderConfigValidationError(- '请填写 API Key'+ 'Enter an API key');}if (normalized.baseUrl.length > 0 && loginApiKey === undefined) {throw new CodexProviderConfigValidationError(- '自定义 Base URL 需要 API Key 登录'+ 'A custom Base URL requires API key authentication');}@@ -220,21 +220,21 @@ function normalizeUpdateRequest(request: CodexProviderConfigUpdateRequest): {const model = request.model.trim();const apiKey = request.apiKey?.trim();if (model.length === 0) {- throw new CodexProviderConfigValidationError('Model 不能为空');+ throw new CodexProviderConfigValidationError('Model cannot be empty');}if (baseUrl.length > 0) {let parsed: URL;try {parsed = new URL(baseUrl);} catch {- throw new CodexProviderConfigValidationError('Base URL 必须是有效的 HTTP 或 HTTPS 地址');+ throw new CodexProviderConfigValidationError('Base URL must be a valid HTTP or HTTPS URL');}if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {- throw new CodexProviderConfigValidationError('Base URL 必须是有效的 HTTP 或 HTTPS 地址');+ throw new CodexProviderConfigValidationError('Base URL must be a valid HTTP or HTTPS URL');}}if (request.apiKey !== undefined && apiKey?.length === 0) {- throw new CodexProviderConfigValidationError('API Key 不能为空');+ throw new CodexProviderConfigValidationError('API key cannot be empty');}return {baseUrl,diff --git a/apps/daemon/src/codex/runtime-readiness.ts b/apps/daemon/src/codex/runtime-readiness.tsindex 28856bb3..2cd17120 100644--- a/apps/daemon/src/codex/runtime-readiness.ts+++ b/apps/daemon/src/codex/runtime-readiness.ts@@ -254,7 +254,7 @@ function requestFailure(error: unknown, area: string): {protocolFailure ? 'invalid' : 'unavailable',undefined,protocolFailure ? 'codex_runtime_protocol_incompatible' : undefined,- `Codex ${area} 检查失败:${message}`+ `Codex ${area} check failed: ${message}`),protocolFailure};diff --git a/apps/daemon/src/codex/sessions/app-server-provider.ts b/apps/daemon/src/codex/sessions/app-server-provider.tsindex 81c33cd6..d001c0c7 100644--- a/apps/daemon/src/codex/sessions/app-server-provider.ts+++ b/apps/daemon/src/codex/sessions/app-server-provider.ts@@ -174,7 +174,7 @@ export function createCodexSessionProvider(codexThreadId: result.thread.id,title: result.thread.name?.trim()|| result.thread.preview?.trim()- || '未命名对话',+ || 'Untitled conversation',cwd: result.thread.cwd,itemType: 'title' as const,createdAt,diff --git a/apps/daemon/src/codex/sessions/indexer.ts b/apps/daemon/src/codex/sessions/indexer.tsindex 4b7385a9..f1f40fb9 100644--- a/apps/daemon/src/codex/sessions/indexer.ts+++ b/apps/daemon/src/codex/sessions/indexer.ts@@ -322,7 +322,7 @@ function toIndexedSession(codexThreadId: state.codexThreadId,sourcePath,kind,- title: state.title ?? '未命名对话',+ title: state.title ?? 'Untitled conversation',cwd: state.cwd ?? null,createdAt: state.createdAt ?? state.updatedAt ?? fallbackTimestamp,updatedAt: state.updatedAt ?? fallbackTimestampdiff --git a/apps/daemon/src/codex/sessions/parser.ts b/apps/daemon/src/codex/sessions/parser.tsindex c01e465b..e35144da 100644--- a/apps/daemon/src/codex/sessions/parser.ts+++ b/apps/daemon/src/codex/sessions/parser.ts@@ -67,7 +67,7 @@ export function parseCodexSessionLine(input: {state.title === undefined&& userMessage !== undefined) {- state.title = createConversationTitle(scheduleTrigger?.prompt ?? userMessage, '未命名对话');+ state.title = createConversationTitle(scheduleTrigger?.prompt ?? userMessage, 'Untitled conversation');}if (entry.type === 'event_msg' && payload?.type === 'user_message') {diff --git a/apps/daemon/src/codex/sessions/scanner.ts b/apps/daemon/src/codex/sessions/scanner.tsindex ec73e690..91ef30d6 100644--- a/apps/daemon/src/codex/sessions/scanner.ts+++ b/apps/daemon/src/codex/sessions/scanner.ts@@ -110,7 +110,7 @@ function readCodexSession(path: string): { kind: 'user'; summary: CodexSessionSukind: 'user',summary: {codexThreadId: state.codexThreadId,- title: state.title ?? '未命名对话',+ title: state.title ?? 'Untitled conversation',cwd: state.cwd,createdAt,updatedAt,diff --git a/apps/daemon/src/codex/status.ts b/apps/daemon/src/codex/status.tsindex 7be8276e..ad805bb1 100644--- a/apps/daemon/src/codex/status.ts+++ b/apps/daemon/src/codex/status.ts@@ -17,8 +17,8 @@ export function buildCodexStatusResponse(): CodexStatusResponse {const diagnostics = input.availabilityProbe?.status === 'failed'? [- `Codex 后台可用性验证失败:${- input.availabilityProbe.message ?? input.availabilityProbe.errorCode ?? '未知错误'+ `Codex background availability verification failed: ${+ input.availabilityProbe.message ?? input.availabilityProbe.errorCode ?? 'Unknown error'}`]: [];diff --git a/apps/daemon/src/creator/agent/agent-service.ts b/apps/daemon/src/creator/agent/agent-service.tsindex 0398d20e..1db66d4c 100644--- a/apps/daemon/src/creator/agent/agent-service.ts+++ b/apps/daemon/src/creator/agent/agent-service.ts@@ -215,7 +215,7 @@ export function createCreatorAgentService(input: {}}}- const dispatched = input.dispatcher.dispatch(jobId, {+ const dispatched = await input.dispatcher.dispatchAsync(jobId, {...runtimeResult.action,idempotencyKey: `${assistantTurn.id}:action:${conflictAttempt}`}, 'agent');@@ -294,7 +294,7 @@ export function createCreatorAgentService(input: {code,source: 'agent',operation: 'creator.agent-turn',- fallbackMessage: 'Agent 未能完成本次诊断,请查看问题详情后重试。',+ fallbackMessage: 'The Agent could not complete the diagnosis. Review the issue details and try again.',publicFacts: publicFactsFromFailure(error),technicalDetail: error.message,repairActions: [{ kind: 'focus-agent' }]@@ -508,7 +508,7 @@ export function createCreatorAgentService(input: {kind: approvalKind(event.request.method),status: 'pending',title: approvalTitle(event.request.method),- summary: typeof params.reason === 'string' ? params.reason : 'Creator Agent 请求执行操作',+ summary: typeof params.reason === 'string' ? params.reason : 'Creator Agent requested an operation',details: JSON.parse(JSON.stringify(params)),requestedAt,expiresAt: new Date(Date.parse(requestedAt) + 15 * 60_000).toISOString()@@ -765,10 +765,10 @@ function approvalKind(method: AppServerRequest['method']): CreatorAgentApproval[}function approvalTitle(method: AppServerRequest['method']): string {- if (method === 'item/commandExecution/requestApproval') return '确认命令执行';- if (method === 'item/fileChange/requestApproval') return '确认文件修改';- if (method === 'item/permissions/requestApproval') return '确认权限请求';- return '确认工具调用';+ if (method === 'item/commandExecution/requestApproval') return 'Approve command execution';+ if (method === 'item/fileChange/requestApproval') return 'Approve file changes';+ if (method === 'item/permissions/requestApproval') return 'Approve permission request';+ return 'Approve tool call';}function isAutoApprovedCreatorReadRequest(request: AppServerRequest): boolean {diff --git a/apps/daemon/src/creator/command-dispatcher.ts b/apps/daemon/src/creator/command-dispatcher.tsindex dc21b3f3..63f2078e 100644--- a/apps/daemon/src/creator/command-dispatcher.ts+++ b/apps/daemon/src/creator/command-dispatcher.ts@@ -6,7 +6,8 @@ import type {CreatorCommandReceipt,CreatorCommandRequest,CreatorJob,- CreatorJson+ CreatorJson,+ CreatorProviderRequest} from '@opencreator/protocol';import type { CreatorAgentRepository } from './agent/repository.js';import type { CreatorRepository } from './repository.js';@@ -38,6 +39,7 @@ export function createCreatorCommandDispatcher(input: {receipts: CreatorAgentRepository;onQueuedStage?(): void;onCommitted?(result: CreatorCommandDispatchResult): void;+ queryProviderRequest?(request: CreatorProviderRequest): Promise<void>;}) {function dispatch(jobId: string,@@ -66,6 +68,23 @@ export function createCreatorCommandDispatcher(input: {return dispatchCommand(jobId, request, 'system', identity);}+ async function dispatchAsync(jobId: string, request: CreatorCommandRequest, actor: CreatorActor): Promise<CreatorCommandDispatchResult> {+ if (request.action !== 'resolve-provider-request' || request.input.decision !== 'query' || input.receipts.getReceiptByKey(jobId, request.idempotencyKey)) return dispatch(jobId, request, actor);+ const job = input.service.getJob(jobId);+ if (!job) throw new CreatorCommandError('creator_job_not_found', 'Creator job not found');+ if (job.revision !== request.expectedRevision) throw new CreatorCommandError('creator_revision_conflict', 'Creator job revision changed', job.revision);+ const action = input.service.templates.get(job.templateId, job.templateVersion).actions.find(action => action.id === request.action);+ if (!action) throw new CreatorCommandError('creator_action_not_allowed', 'Creator action is not allowed');+ action.inputSchema.parse(request.input);+ const receipt = job.providerRequests.find(entry => entry.id === request.input.ledgerId);+ if (!receipt) throw new CreatorCommandError('creator_provider_request_not_found', 'Creator provider request was not found');+ if (['registered', 'submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(receipt.status)) {+ if (!input.queryProviderRequest) throw new CreatorCommandError('creator_provider_query_unavailable', 'Provider request lookup is unavailable');+ await input.queryProviderRequest(receipt);+ }+ return dispatchCommand(jobId, request, actor, undefined, true);+ }+function dispatchCommand(jobId: string,request: CreatorCommandRequest,@@ -75,8 +94,12 @@ export function createCreatorCommandDispatcher(input: {inputFingerprint?: string | null;parentStageRunId?: string;resumedFromStageRunId?: string;- }+ },+ queriedProvider = false): CreatorCommandDispatchResult {+ if (request.action === 'resolve-provider-request' && request.input.decision === 'query' && !queriedProvider && !input.receipts.getReceiptByKey(jobId, request.idempotencyKey)) {+ throw new CreatorCommandError('creator_provider_query_required', 'Use asynchronous dispatch to query a provider request');+ }const normalized = {action: request.action,expectedRevision: request.expectedRevision,@@ -123,7 +146,7 @@ export function createCreatorCommandDispatcher(input: {let response = actionResponse;let stageRunId: string | null = null;if (request.action === 'run-stage'- || (request.action === 'retry-stage' && actionResponse.job.templateId === 'image-generation')) {+ || (request.action === 'retry-stage' && ['image-generation', 'video-generation'].includes(actionResponse.job.templateId))) {const stageId = readStageId(request.input.stageId);const template = input.service.templates.get(actionResponse.job.templateId,@@ -136,6 +159,13 @@ export function createCreatorCommandDispatcher(input: {'Creator stage was not found');}+ const previousMediaStage = request.action === 'retry-stage' && ['image-generation', 'video-generation'].includes(actionResponse.job.templateId)+ ? [...actionResponse.job.stages].reverse().find(previous => previous.stageId === stageId+ && previous.scopeKey === (typeof request.input.scopeKey === 'string' ? request.input.scopeKey : null)+ && ['failed', 'interrupted', 'canceled'].includes(previous.status)) : undefined;+ const rejectedVideo = previousMediaStage && actionResponse.job.templateId === 'video-generation'+ && (previousMediaStage.errorCode === 'creator_video_generation_failed' || actionResponse.job.providerRequests.some(receipt => receipt.stageRunId === previousMediaStage.id && receipt.provider === 'opencreator-gateway-video' && receipt.status === 'failed'));+ const resumedMediaStage = rejectedVideo ? undefined : previousMediaStage;const stageRun = input.repository.createStageRun({jobId,stageId,@@ -153,6 +183,7 @@ export function createCreatorCommandDispatcher(input: {: {}),progress: {commandIdempotencyKey: request.idempotencyKey,+ ...(resumedMediaStage ? { resumedFromStageRunId: resumedMediaStage.id } : {}),...(workflowIdentity !== undefined || request.input.workflow === true? { workflow: true }: {}),@@ -227,7 +258,7 @@ export function createCreatorCommandDispatcher(input: {}}- return { dispatch, dispatchWorkflow };+ return { dispatch, dispatchAsync, dispatchWorkflow };}function scopedStageIdentity(diff --git a/apps/daemon/src/creator/image/executor.ts b/apps/daemon/src/creator/image/executor.tsindex 33f909bd..f022c76e 100644--- a/apps/daemon/src/creator/image/executor.ts+++ b/apps/daemon/src/creator/image/executor.ts@@ -91,7 +91,7 @@ export function createImageExecutor(input: {}if (stage.job.templateId === 'image-generation' && referenceImage === undefined&& imagePromptRequiresReference(request.prompt)) {- const message = '当前提示词需要参考图,但任务没有可用的参考图片。请先上传图片,或移除提示词中对上传图片或原图的要求。';+ const message = 'This prompt requires a reference image, but none is available. Upload an image or remove references to an uploaded or original image from the prompt.';throw new CreatorExecutorError('creator_stage_input_missing', message, {}, {kind: 'validation', upstreamCode: 'IMAGE_REFERENCE_MISSING', upstreamMessage: message});diff --git a/apps/daemon/src/creator/issues.ts b/apps/daemon/src/creator/issues.tsindex 9b9c7bf0..3e41f762 100644--- a/apps/daemon/src/creator/issues.ts+++ b/apps/daemon/src/creator/issues.ts@@ -225,11 +225,11 @@ function categoryForSource(source: IssueSource): IssueCategory {}function fallbackForCategory(category: IssueCategory): string {- if (category === 'configuration') return '配置不完整,请检查相关设置。';- if (category === 'permission') return '当前操作没有所需权限。';- if (category === 'network') return '连接失败,请检查网络或服务状态。';- if (category === 'output-validation') return '输出未通过检查,请修正后重试。';- return '操作未完成,请重试。';+ if (category === 'configuration') return 'Configuration is incomplete. Check the relevant settings.';+ if (category === 'permission') return 'This operation requires additional permissions.';+ if (category === 'network') return 'Connection failed. Check the network or service status.';+ if (category === 'output-validation') return 'Output validation failed. Correct the output and try again.';+ return 'The operation did not complete. Try again.';}function sanitizeIdentifier(value: string, fallback: string, max = 160): string {diff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex 06e82bba..6b40936d 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -108,8 +108,8 @@ export function createKrillinExecutor(input: {) {deferredFailure = error;const message = error.code === 'platform_caption_invalid'- ? '平台字幕解析失败,已自动切换到语音转录'- : '未找到可用的平台字幕,已自动切换到语音转录';+ ? 'Platform subtitle parsing failed. Switched to speech transcription.'+ : 'No usable platform subtitles were found. Switched to speech transcription.';captionFallbackProgress = {captionSource: 'whisper',captionFallbackCode: error.code,diff --git a/apps/daemon/src/creator/krillin/dependency-loader.ts b/apps/daemon/src/creator/krillin/dependency-loader.tsindex 0d3a3746..855daed6 100644--- a/apps/daemon/src/creator/krillin/dependency-loader.ts+++ b/apps/daemon/src/creator/krillin/dependency-loader.ts@@ -168,7 +168,7 @@ export function createKrillinDependencyLoader(input: {}reportProgress({phase: 'downloading_dependencies',- message: '当前本地转录组件尚未安装,正在自动下载。模型文件较大,可能需要较长时间;下载并校验完成后将自动继续,无需重新开始。',+ message: 'Local transcription components are being downloaded automatically. Large model files may take time. Transcription will continue after download and verification.',krillinMode: 'cli',providerStatus: 'preparing',dependency: 'whispercpp',@@ -186,7 +186,7 @@ export function createKrillinDependencyLoader(input: {onPhase(phase) {reportProgress({phase: 'downloading_dependencies',- message: `正在准备 Whisper.cpp ${phase === 'cli' ? '转录引擎' : model + ' 模型'};下载并校验完成后将自动继续`,+ message: `Preparing Whisper.cpp ${phase === 'cli' ? 'transcription engine' : model + ' model'}. The task will resume after download and verification.`,krillinMode: 'cli',providerStatus: 'preparing',dependency: 'whispercpp',@@ -211,7 +211,7 @@ export function createKrillinDependencyLoader(input: {}throw new CreatorExecutorError('creator_dependency_prepare_failed',- `Whisper.cpp 依赖加载失败:${errorMessage(cause)}`+ `Could not load Whisper.cpp dependencies: ${errorMessage(cause)}`);}return;@@ -231,7 +231,7 @@ export function createKrillinDependencyLoader(input: {}reportProgress({phase: 'downloading_dependencies',- message: '当前本地转录组件尚未安装,正在自动下载。模型文件较大,可能需要较长时间;下载并校验完成后将自动继续,无需重新开始。',+ message: 'Local transcription components are being downloaded automatically. Large model files may take time. Transcription will continue after download and verification.',krillinMode: 'cli',providerStatus: 'preparing',dependency: 'whisperkit',@@ -246,7 +246,7 @@ export function createKrillinDependencyLoader(input: {onPhase(phase) {reportProgress({phase: 'downloading_dependencies',- message: `正在准备 WhisperKit ${phase === 'cli' ? '转录引擎' : 'large-v2 模型'};下载并校验完成后将自动继续`,+ message: `Preparing WhisperKit ${phase === 'cli' ? 'transcription engine' : 'large-v2 model'}. The task will resume after download and verification.`,krillinMode: 'cli',providerStatus: 'preparing',dependency: 'whisperkit',@@ -269,7 +269,7 @@ export function createKrillinDependencyLoader(input: {}throw new CreatorExecutorError('creator_dependency_prepare_failed',- `WhisperKit 依赖加载失败:${errorMessage(cause)}`+ `Could not load WhisperKit dependencies: ${errorMessage(cause)}`);}}@@ -309,7 +309,7 @@ function componentDownloadProgress(dependency: string, model: string, progress:phase: `${progress.state}_dependencies`, percent: 2, dependency, dependencyModel: model, dependencyItem: progress.item,dependencyPercent: percent, downloadedBytes: progress.downloadedBytes ?? 0, totalBytes: progress.totalBytes ?? null,bytesPerSecond: progress.bytesPerSecond ?? null, remainingSeconds: progress.remainingSeconds ?? null,- message: `正在${progress.state === 'verifying' ? '校验' : progress.state === 'extracting' ? '解压安装' : '下载'} ${progress.item}。${progress.statusMessage ?? ''}模型较大,准备完成后会自动继续转录,无需重新开始。`+ message: `${progress.state === 'verifying' ? 'Verifying' : progress.state === 'extracting' ? 'Extracting and installing' : 'Downloading'} ${progress.item}. ${progress.statusMessage ?? ''}The model is large. Transcription will resume automatically when ready.`};}@@ -782,7 +782,7 @@ export async function configuredOrDownloadedFile(input: {lastBytes = downloadedBytes;lastTime = now;input.onProgress?.({ state: 'downloading', item: input.name, downloadedBytes, totalBytes, bytesPerSecond,- statusMessage: retrying ? '下载连接暂时失败,正在自动重试。' : now - lastDataAt > 10_000 ? '下载暂无新数据,正在等待服务器响应;任务仍在运行。' : downloadedBytes === 0 ? '正在连接下载服务器,尚未开始传输。' : undefined,+ statusMessage: retrying ? 'The download connection failed temporarily. Retrying automatically. ' : now - lastDataAt > 10_000 ? 'Waiting for more data from the download server. The task is still running. ' : downloadedBytes === 0 ? 'Connecting to the download server. Transfer has not started yet. ' : undefined,remainingSeconds: totalBytes !== null && bytesPerSecond > 0 ? Math.max(0, totalBytes - downloadedBytes) / bytesPerSecond : null });} finally { polling = false; }};diff --git a/apps/daemon/src/creator/krillin/local-components.ts b/apps/daemon/src/creator/krillin/local-components.tsindex b4f19044..f5dcb51c 100644--- a/apps/daemon/src/creator/krillin/local-components.ts+++ b/apps/daemon/src/creator/krillin/local-components.ts@@ -67,7 +67,7 @@ export function manageLocalComponents(input: {for (const listener of listeners) listener(progress);};publish({ phase: preceding.length > 0 ? 'downloading_dependencies' : 'verifying_dependencies', percent: 2, dependency: provider, dependencyModel: model,- message: preceding.length > 0 ? '正在等待本地转录引擎的共享组件准备完成,随后会自动准备当前模型并继续转录,无需重新开始。' : '正在检查本地转录引擎和模型是否已安装;缺失时会自动下载,准备完成后会自动继续转录。'+ message: preceding.length > 0 ? 'Waiting for shared transcription components. The selected model will be prepared next, and transcription will resume automatically.' : 'Checking the local transcription engine and model. Missing components will be downloaded, and transcription will resume automatically.'});current.promise = Promise.all(preceding).then(() => input.loader.ensure({config: structuredClone(request.config),@@ -76,7 +76,7 @@ export function manageLocalComponents(input: {})).then(() => {states.set(key, { state: 'ready', model, error: null, percent: 100 });inspectedAt = 0;- const progress: Progress = { phase: 'dependencies_ready', percent: 5, message: '本地转录组件已准备完成,正在开始语音转录', dependency: provider, dependencyModel: model };+ const progress: Progress = { phase: 'dependencies_ready', percent: 5, message: 'Local transcription components are ready. Starting transcription.', dependency: provider, dependencyModel: model };for (const listener of listeners) listener(progress);}).catch(error => {states.set(key, { ...states.get(key), state: 'failed', error: error instanceof Error ? error.message : String(error) });diff --git a/apps/daemon/src/creator/krillin/tts-service.ts b/apps/daemon/src/creator/krillin/tts-service.tsindex 3614f6d1..3b0ed43e 100644--- a/apps/daemon/src/creator/krillin/tts-service.ts+++ b/apps/daemon/src/creator/krillin/tts-service.ts@@ -157,9 +157,9 @@ export function createKrillinTtsService(input: {const gateway = gatewayCreatorBinding(config);if (gateway) {const selected = gateway.catalog?.find(candidate => candidate.modality === 'speech' && candidate.id === (model || gateway.models.speech));- if (model && model !== gateway.models.speech && !selected) throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择官方语音模型', 400);+ if (model && model !== gateway.models.speech && !selected) throw new KrillinTtsServiceError('VALIDATION_FAILED', 'Select an official speech model', 400);const defaultVoice = selected?.capabilities.includes('default_voice') ?? gateway.capabilities?.speech?.includes('default_voice');- return { provider: 'openai', model: selected?.id ?? gateway.models.speech ?? '', voices: (defaultVoice ? [gatewayDefaultVoiceId] : selected?.voices ?? gateway.speechVoices ?? []).map(id => ({ id, name: id === gatewayDefaultVoiceId ? '默认音色' : id, provider: 'openai' as const, kind: 'builtin' as const })) };+ return { provider: 'openai', model: selected?.id ?? gateway.models.speech ?? '', voices: (defaultVoice ? [gatewayDefaultVoiceId] : selected?.voices ?? gateway.speechVoices ?? []).map(id => ({ id, name: id === gatewayDefaultVoiceId ? 'Default voice' : id, provider: 'openai' as const, kind: 'builtin' as const })) };}if (provider === 'edge-tts') {return { provider, model: '', voices: [] };@@ -203,7 +203,7 @@ export function createKrillinTtsService(input: {const configured = await input.configStore.read();const gateway = gatewayCreatorBinding(configured);const selected = gateway?.catalog?.find(candidate => candidate.modality === 'speech' && candidate.id === (request.model || gateway.models.speech));- if (gateway && request.model && request.model !== gateway.models.speech && (gateway.stageRunId || !selected)) throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择当前任务的官方语音模型', 400);+ if (gateway && request.model && request.model !== gateway.models.speech && (gateway.stageRunId || !selected)) throw new KrillinTtsServiceError('VALIDATION_FAILED', 'Select an official speech model for this task', 400);const provider = gateway ? 'openai' : request.provider ?? configured.tts.provider;if (provider === 'edge-tts') {throw new KrillinTtsServiceError(@@ -218,14 +218,14 @@ export function createKrillinTtsService(input: {const voiceId = request.voiceId?.trim() || (defaultVoice ? gatewayDefaultVoiceId : selected?.voices?.[0] || prepared.providerConfig.defaultVoiceId);const allowedVoices = defaultVoice ? [gatewayDefaultVoiceId] : selected?.voices ?? gateway?.speechVoices;if (allowedVoices && !allowedVoices.includes(voiceId)) {- throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择当前模型支持的音色', 400);+ throw new KrillinTtsServiceError('VALIDATION_FAILED', 'Select a voice supported by this model', 400);}if (!voiceId) {throw new KrillinTtsServiceError('VALIDATION_FAILED', 'A voice must be selected', 400);}const format = request.format ?? 'wav';const speed = request.speed ?? 1;- if (gateway && (speed !== 1 || request.instructions)) throw new KrillinTtsServiceError('unsupported_capability', '当前官方语音路由未验证此生成参数', 400);+ if (gateway && (speed !== 1 || request.instructions)) throw new KrillinTtsServiceError('unsupported_capability', 'This generation parameter is not verified for the official speech route', 400);if (!Number.isFinite(speed) || speed < 0.5 || speed > 2) {throw new KrillinTtsServiceError('VALIDATION_FAILED',diff --git a/apps/daemon/src/creator/output-validation.ts b/apps/daemon/src/creator/output-validation.tsindex 5c78be4b..3024e48e 100644--- a/apps/daemon/src/creator/output-validation.ts+++ b/apps/daemon/src/creator/output-validation.ts@@ -44,7 +44,7 @@ async function validateCompletedOutputFiles(findings.push({code: 'creator_output_file_empty',severity: 'blocking',- message: '生成的输出文件为空,请重新执行当前步骤。',+ message: 'The output file is empty. Run this step again.',evidence: { artifactKind: output.kind }});continue;@@ -57,7 +57,7 @@ async function validateCompletedOutputFiles(findings.push({code: 'creator_output_file_unreadable',severity: 'blocking',- message: '生成的输出文件无法读取,请重新执行当前步骤。',+ message: 'The output file is unreadable. Run this step again.',evidence: { artifactKind: output.kind }});}@@ -82,7 +82,7 @@ export const validateTranslationOutputLanguage: CreatorStageOutputValidator = asreturn [{code: 'creator_translation_output_invalid',severity: 'blocking',- message: '翻译字幕文件无法解析,请重新生成。',+ message: 'Could not parse the translated subtitle file. Generate it again.',evidence: { artifactKind: 'target_subtitle' }}];}@@ -103,7 +103,7 @@ export const validateTranslationOutputLanguage: CreatorStageOutputValidator = asreturn [{code: 'creator_translation_output_language_mismatch',severity: 'blocking',- message: '目标语言为中文,但翻译结果仍主要是英文,请重新生成。',+ message: 'The target language is Chinese, but the translation is mostly English. Generate it again.',evidence: compactEvidence({targetLanguage,sampleCharacters: metrics.meaningfulCharacters,diff --git a/apps/daemon/src/creator/preflight.ts b/apps/daemon/src/creator/preflight.tsindex 16c0789e..3a37f5d8 100644--- a/apps/daemon/src/creator/preflight.ts+++ b/apps/daemon/src/creator/preflight.ts@@ -82,22 +82,22 @@ export function createCreatorPreflight(input: {const value = { ...item, executionMode: item.executionMode ?? mode };if (status === 'ready') ready.push(value);else if (status === 'warning') warning.push(value);- else blocked.push({ ...value, repair: repair ?? { label: '打开设置', deepLink: '#/settings?tab=diagnostics' } });+ else blocked.push({ ...value, repair: repair ?? { label: 'Open settings', deepLink: '#/settings?tab=diagnostics' } });};if (executorIds.size > 0 && !executorIds.has(stage.executor)) {add('blocked', {id: 'executor',- title: '执行器不可用',- message: `当前 Runtime 未加载 ${stage.executor} 执行器。`,+ title: 'Executor unavailable',+ message: `The Runtime has not loaded the ${stage.executor} executor.`,executionMode: mode- }, { label: '打开诊断', deepLink: '#/settings?tab=diagnostics' });+ }, { label: 'Open diagnostics', deepLink: '#/settings?tab=diagnostics' });} else {- add('ready', { id: 'executor', title: '执行器', message: `${stage.executor} 已加载`, executionMode: mode });+ add('ready', { id: 'executor', title: 'Executor', message: `${stage.executor} loaded`, executionMode: mode });}try { input.assertServiceSource?.(job.id); } catch {- add('blocked', { id: 'service-source', title: '任务服务来源不匹配', message: '请恢复原任务账户和服务来源后继续。', executionMode: 'remote' }, { label: '打开账户设置', deepLink: '#/settings?tab=ai-services' });+ add('blocked', { id: 'service-source', title: 'Task service source mismatch', message: 'Restore the original task account and service source before continuing.', executionMode: 'remote' }, { label: 'Open account settings', deepLink: '#/settings?tab=ai-services' });return { templateId: job.templateId, templateVersion: job.templateVersion, stageId: stage.id, executionMode: mode, canStart: false, ready, warning, blocked, checkedAt: new Date().toISOString() };}const config = await input.configStore.read();@@ -107,33 +107,33 @@ export function createCreatorPreflight(input: {if (options.inputResultVersion !== undefined && inputSnapshot === undefined) {add('blocked', {id: 'input-result-version',- title: '结果版本不存在',- message: `找不到结果版本 ${options.inputResultVersion},无法安全复用历史输入。`,+ title: 'Result version not found',+ message: `Result version ${options.inputResultVersion} was not found. Saved inputs cannot be reused safely.`,executionMode: 'local'- }, { label: '打开诊断', deepLink: '#/settings?tab=diagnostics' });+ }, { label: 'Open diagnostics', deepLink: '#/settings?tab=diagnostics' });}const inputState = inputSnapshot?.state ?? job.state;if (stage.resultVersionPolicy === 'attach' && inputSnapshot === undefined) {- add('blocked', { id: 'input-result-version', title: '请先选择项目版本', message: '准备预览视频需要明确的已保存项目版本。', executionMode: 'local' });+ add('blocked', { id: 'input-result-version', title: 'Select a project version', message: 'Select a saved project version before preparing the preview video.', executionMode: 'local' });}if (job.templateId === 'video-translation' && (stage.id === 'subtitle' || stage.id === 'prepare-source-video' || stage.id === 'preview-source-video')) {try {await validateBilibiliSource({ ...job, state: inputState }, input.videoMetadataService);} catch (error) {add('blocked', {- id: 'bilibili-part', title: '请确认 B 站分集',- message: error instanceof Error ? error.message : '无法确认 B 站分集,请重新选择视频来源。',+ id: 'bilibili-part', title: 'Confirm the Bilibili video part',+ message: error instanceof Error ? error.message : 'Could not confirm the Bilibili video part. Select the video source again.',executionMode: 'remote'- }, { label: '选择视频分集', deepLink: `#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}` });+ }, { label: 'Select a video part', deepLink: `#/workbench?tool=video-translation&jobId=${encodeURIComponent(job.id)}` });}}if (inputState.sourceType === 'file' && stage.executor === 'krillinai' && typeof inputState.sourceArtifactId !== 'string') {add('blocked', {id: 'input-file',- title: '输入文件缺失',- message: '请选择要处理的本地视频文件。',+ title: 'Input file missing',+ message: 'Select a local video file to process.',executionMode: 'local'- }, { label: '选择输入文件', deepLink: '#/settings?tab=diagnostics' });+ }, { label: 'Select an input file', deepLink: '#/settings?tab=diagnostics' });}const resolvedInputs = resolveCreatorStageInputs(job,@@ -147,10 +147,10 @@ export function createCreatorPreflight(input: {&& !resolvedInputs.artifacts.some(artifact => artifact.kind === 'reference_image'&& artifact.status === 'completed' && artifact.path !== null)) {add('blocked', {- id: 'reference-image-required', title: '缺少参考图',- message: '当前提示词需要基于已有图片生成,请先上传参考图;如需纯文字生图,请移除对上传图片或原图的要求。',+ id: 'reference-image-required', title: 'Reference image missing',+ message: 'This prompt requires an existing image. Upload a reference image, or remove the image requirements for text-only generation.',executionMode: 'local'- }, { label: '上传参考图', deepLink: `#/workbench?tool=image-generation&jobId=${encodeURIComponent(job.id)}` });+ }, { label: 'Upload a reference image', deepLink: `#/workbench?tool=image-generation&jobId=${encodeURIComponent(job.id)}` });}await checkInputs(stage, resolvedInputs.artifacts, resolvedInputs.missing, add);await checkRuntimeDependencies(job, stage, config, add);@@ -177,14 +177,14 @@ export function createCreatorPreflight(input: {try {await mkdir(input.jobsRoot, { recursive: true });await access(input.jobsRoot, constants.W_OK);- add('ready', { id: 'managed-directory', title: '受管目录', message: '任务目录可写。', executionMode: 'local' });+ add('ready', { id: 'managed-directory', title: 'Managed directory', message: 'The task directory is writable.', executionMode: 'local' });} catch {add('blocked', {id: 'managed-directory',- title: '受管目录不可写',- message: 'OpenCreator 无法写入任务目录,无法安全保存 Artifact。',+ title: 'Managed directory is not writable',+ message: 'OpenCreator cannot write to the task directory or save artifacts safely.',executionMode: 'local'- }, { label: '打开诊断', deepLink: '#/settings?tab=diagnostics' });+ }, { label: 'Open diagnostics', deepLink: '#/settings?tab=diagnostics' });}}@@ -204,10 +204,10 @@ export function createCreatorPreflight(input: {} catch (error) {add('blocked', {id: 'krillin-runtime',- title: 'KrillinAI Runtime 不可用',- message: error instanceof Error ? error.message : 'KrillinAI Runtime 校验失败。',+ title: 'KrillinAI Runtime unavailable',+ message: error instanceof Error ? error.message : 'KrillinAI Runtime verification failed.',executionMode: 'local'- }, { label: '打开运行组件设置', deepLink: '#/settings?tab=local-components' });+ }, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components' });return;}}@@ -219,14 +219,14 @@ export function createCreatorPreflight(input: {const label = id === 'ffmpeg' ? 'FFmpeg' : 'ffprobe';if (path === undefined) add('blocked', {id,- title: `${label} 不可用`,- message: `当前 Runtime 未找到 ${label},该阶段无法执行。`,+ title: `${label} unavailable`,+ message: `The Runtime could not find ${label}. This stage cannot run.`,executionMode: 'local'- }, { label: '打开运行组件设置', deepLink: '#/settings?tab=local-components' });- else add('ready', { id, title: label, message: `${label} 已就绪。`, executionMode: 'local' });+ }, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components' });+ else add('ready', { id, title: label, message: `${label} is ready.`, executionMode: 'local' });}if (stage.executor === 'stickman-delivery' && input.ffmpegPath === undefined) {- add('warning', { id: 'ffmpeg', title: 'FFmpeg 不可用', message: '交付校验将跳过视频帧采样。', executionMode: 'local' });+ add('warning', { id: 'ffmpeg', title: 'FFmpeg unavailable', message: 'Delivery checks will skip video frame sampling.', executionMode: 'local' });}if (stage.executor === 'stickman-remotion') {try {@@ -234,21 +234,21 @@ export function createCreatorPreflight(input: {const component = await input.remotionComponent.status();if (!component.available) throw new Error(component.error ?? 'remotion_component_unavailable');add(component.state === 'ready' ? 'ready' : 'warning', {- id: 'stickman-runtime', title: 'Remotion 渲染组件',- message: component.state === 'ready' ? 'Remotion 渲染组件已就绪。' : '执行渲染时将按需准备 Remotion 组件,完成后自动继续。', executionMode: 'local'+ id: 'stickman-runtime', title: 'Remotion rendering component',+ message: component.state === 'ready' ? 'The Remotion rendering component is ready.' : 'Remotion will be prepared on demand. Rendering will continue automatically when ready.', executionMode: 'local'});} else {if (input.stickmanRuntimeRoot === undefined) throw new Error('stickman_runtime_unavailable');readStickmanRemotionRuntime(input.stickmanRuntimeRoot);- add('ready', { id: 'stickman-runtime', title: 'Stickman 渲染运行时', message: 'Remotion 运行资源校验通过。', executionMode: 'local' });+ add('ready', { id: 'stickman-runtime', title: 'Stickman rendering Runtime', message: 'Remotion Runtime assets passed verification.', executionMode: 'local' });}} catch (error) {add('blocked', {id: 'stickman-runtime',- title: 'Stickman 渲染运行时不可用',- message: error instanceof Error ? error.message : 'Remotion 运行资源校验失败。',+ title: 'Stickman rendering Runtime unavailable',+ message: error instanceof Error ? error.message : 'Remotion Runtime asset verification failed.',executionMode: 'local'- }, { label: '打开运行组件设置', deepLink: '#/settings?tab=local-components&component=remotion' });+ }, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components&component=remotion' });}}}@@ -257,35 +257,35 @@ export function createCreatorPreflight(input: {try { runtime = input.getYtDlpRuntime?.(); } catch { runtime = undefined; }if (runtime === undefined) add('blocked', {id: 'yt-dlp',- title: 'yt-dlp 不可用',- message: '当前 Runtime 未找到 yt-dlp,无法处理远程媒体。',+ title: 'yt-dlp unavailable',+ message: 'yt-dlp was not found. Remote media cannot be processed.',executionMode: 'local'- }, { label: '打开运行组件设置', deepLink: '#/settings?tab=local-components' });- else add('ready', { id: 'yt-dlp', title: 'yt-dlp', message: `已就绪(${runtime.version})。`, executionMode: 'local' });+ }, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components' });+ else add('ready', { id: 'yt-dlp', title: 'yt-dlp', message: `Ready (${runtime.version}).`, executionMode: 'local' });}if (input.validateRuntimeAssets !== false && stage.executor === 'krillinai') {try {preflightKrillinDependencies(input.resourceRoot, config, {cachePath: input.runtimeVerificationCachePath});- add('ready', { id: 'krillin-runtime', title: 'KrillinAI Runtime', message: '运行资源校验通过。', executionMode: 'local' });+ add('ready', { id: 'krillin-runtime', title: 'KrillinAI Runtime', message: 'Runtime assets passed verification.', executionMode: 'local' });} catch (error) {add('blocked', {id: 'krillin-runtime',- title: 'KrillinAI Runtime 不完整',- message: error instanceof Error ? error.message : 'KrillinAI 运行资源校验失败。',+ title: 'KrillinAI Runtime incomplete',+ message: error instanceof Error ? error.message : 'KrillinAI Runtime asset verification failed.',executionMode: 'local'- }, { label: '打开运行组件设置', deepLink: '#/settings?tab=local-components' });+ }, { label: 'Open local component settings', deepLink: '#/settings?tab=local-components' });}}if (stage.executor === 'krillinai' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false) && ['whisper.cpp', 'whisperkit', 'faster-whisper'].includes(config.transcription.provider)) {const provider = input.readCapabilities().transcription.providers.find(candidate => candidate.provider === config.transcription.provider);if (provider?.available !== true) add('blocked', {id: 'transcription-capability',- title: '语音识别能力不可用',- message: `${config.transcription.provider} 在当前 Runtime 不可用。`,+ title: 'Speech recognition unavailable',+ message: `${config.transcription.provider} is unavailable in this Runtime.`,executionMode: 'local'- }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=transcription' });+ }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=transcription' });}}}@@ -341,21 +341,21 @@ async function checkProviderConfig(if (config.llm.source === 'codex' && stage.executor === 'krillinai' && config.llm.apiKey.trim()) {add('ready', {id: 'llm',- title: '文本模型',- message: `本机 Codex / ${config.llm.model || 'Runtime'} 已启用。`,+ title: 'Text model',+ message: `Local Codex / ${config.llm.model || 'Runtime'} is enabled.`,executionMode: 'local'});} else {- checkOpenAi(config.llm, 'llm', '文本模型', '#/settings?tab=ai-services§ion=text', add);+ checkOpenAi(config.llm, 'llm', 'Text model', '#/settings?tab=ai-services§ion=text', add);}}if (needs.has('tts')) {const gateway = gatewayCreatorBinding(config);if (gateway && (stage.executor === 'smart-dubbing' || (typeof job.state.speed === 'number' && job.state.speed !== 1))) {- add('blocked', { id: 'tts-style-capability', title: '配音参数不受支持', message: '当前官方语音模型未提供已验证的样式或语速控制,请选择其他配音服务。', executionMode: 'remote' }, { label: '打开配音设置', deepLink: '#/settings?tab=ai-services§ion=tts' });+ add('blocked', { id: 'tts-style-capability', title: 'Unsupported speech settings', message: 'Style and speed controls are not verified for this official speech model. Select another TTS service.', executionMode: 'remote' }, { label: 'Open speech settings', deepLink: '#/settings?tab=ai-services§ion=tts' });}const provider = readTtsProvider(job, config);- if (provider === 'edge-tts') add('ready', { id: 'tts', title: '配音服务', message: 'Edge TTS 不需要 API Key。', executionMode: 'remote' });+ if (provider === 'edge-tts') add('ready', { id: 'tts', title: 'Speech service', message: 'Edge TTS does not require an API key.', executionMode: 'remote' });else checkTts(config, provider, add);}if (needs.has('image')) {@@ -371,21 +371,21 @@ async function checkProviderConfig(let status: CodexImageStatus | undefined;try { status = await readCodexImageStatus?.(); } catch { status = undefined; }add(status?.ready ? 'ready' : 'blocked', {- id: 'image-provider', title: '本机 Codex 生图',- message: status?.message ?? '无法检查 Codex 生图认证和 Runtime 能力,请检查本机 Codex 登录和配置。',+ id: 'image-provider', title: 'Local Codex image generation',+ message: status?.message ?? 'Could not check Codex image authentication and Runtime capabilities. Check local Codex sign-in and configuration.',executionMode: status?.executionMode === 'api' ? 'remote' : 'local'- }, { label: '检查生图设置', deepLink: '#/settings?tab=ai-services§ion=image' });+ }, { label: 'Check image settings', deepLink: '#/settings?tab=ai-services§ion=image' });} else if (imageProviderConfigured(config, provider)) {add('ready', {id: 'image-provider',- title: '图像服务',- message: `${provider} / ${settings.model} 已配置。`,+ title: 'Image service',+ message: `${provider} / ${settings.model} is configured.`,executionMode: settings.executionMode});} else {add('blocked', {- id: 'image-provider', title: '图像服务配置不完整', message: `请配置 ${provider} 的 Base URL、模型和凭据。`, executionMode: settings.executionMode- }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=image' });+ id: 'image-provider', title: 'Image service configuration incomplete', message: `Configure the Base URL, model, and credentials for ${provider}.`, executionMode: settings.executionMode+ }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=image' });}const hasReference = stage.executor === 'stickman-image'|| (stage.inputArtifacts.some(item => item.kind === 'reference_image')@@ -400,42 +400,42 @@ async function checkProviderConfig(const spec = stickmanShotSpecSchema.parse(JSON.parse(await readFile(shotSpec.path, 'utf8')));multiple ||= spec.shots.some(shouldUsePreviousShotReference);} catch {- add('blocked', { id: 'shot-spec-invalid', title: '分镜数据不可用', message: '无法检查分镜的参考图要求,请重新生成分镜。', executionMode: 'local' });+ add('blocked', { id: 'shot-spec-invalid', title: 'Storyboard data unavailable', message: 'Could not check storyboard reference requirements. Generate the storyboard again.', executionMode: 'local' });}}- if (multiple) add('blocked', { id: 'reference-image-count', title: '参考图数量不支持', message: '当前官方图像服务仅验证了 1 张参考图,此任务需要多张参考图。', executionMode: 'remote' });+ if (multiple) add('blocked', { id: 'reference-image-count', title: 'Unsupported number of reference images', message: 'The official image service is verified for one reference image. This task needs multiple references.', executionMode: 'remote' });}if (hasReference && !supportsReference) add('blocked', {- id: 'reference-image-capability', title: '参考图能力不匹配', message: `${provider} 不支持当前阶段的参考图编辑。`, executionMode: 'remote'- }, { label: '选择支持参考图的服务', deepLink: '#/settings?tab=ai-services§ion=image' });+ id: 'reference-image-capability', title: 'Reference image capability mismatch', message: `${provider} does not support reference image editing for this stage.`, executionMode: 'remote'+ }, { label: 'Select a service that supports reference images', deepLink: '#/settings?tab=ai-services§ion=image' });}if (needs.has('video')) {const gateway = gatewayCreatorBinding(config);if (gateway) {- add(gateway.models.video ? 'ready' : 'blocked', { id: 'video-provider', title: '官方视频服务', message: gateway.models.video ? `${gateway.models.video} 已配置。` : '当前官方服务没有可用的视频模型', executionMode: 'remote' });- if (job.artifacts.some(artifact => artifact.kind === 'reference_image' && artifact.status === 'completed') && !gateway.capabilities?.video?.includes('image_to_video')) add('blocked', { id:'reference-image-capability',title:'参考图能力不匹配',message:'当前官方视频模型不支持参考图。',executionMode:'remote' });+ add(gateway.models.video ? 'ready' : 'blocked', { id: 'video-provider', title: 'Official video service', message: gateway.models.video ? `${gateway.models.video} is configured.` : 'The official service has no available video model', executionMode: 'remote' });+ if (job.artifacts.some(artifact => artifact.kind === 'reference_image' && artifact.status === 'completed') && !gateway.capabilities?.video?.includes('image_to_video')) add('blocked', { id:'reference-image-capability',title:'Reference image capability mismatch',message:'The official video model does not support reference images.',executionMode:'remote' });} else {const provider = readVideoProvider(job, config);const settings = config.video[provider];const hasKey = providerCredentials(settings, provider);if (!hasKey || !settings.model.trim() || !settings.baseUrl.trim()) add('blocked', {- id: 'video-provider', title: '视频服务配置不完整', message: `请配置 ${provider} 的 Base URL、模型和凭据。`, executionMode: 'remote'- }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=video' });- else add('ready', { id: 'video-provider', title: '视频服务', message: `${provider} / ${settings.model} 已配置。`, executionMode: 'remote' });+ id: 'video-provider', title: 'Video service configuration incomplete', message: `Configure the Base URL, model, and credentials for ${provider}.`, executionMode: 'remote'+ }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=video' });+ else add('ready', { id: 'video-provider', title: 'Video service', message: `${provider} / ${settings.model} is configured.`, executionMode: 'remote' });}}if (stage.executor === 'krillinai' && stage.id === 'subtitle' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false)) {const provider = capabilities.transcription.providers.find(candidate => candidate.provider === config.transcription.provider);if (provider?.available !== true) return;if (config.transcription.provider === 'openai' && !config.transcription.openai.apiKey.trim()) {- checkOpenAi(config.transcription.openai, 'transcription', '语音识别', '#/settings?tab=ai-services§ion=transcription', add);+ checkOpenAi(config.transcription.openai, 'transcription', 'Speech recognition', '#/settings?tab=ai-services§ion=transcription', add);} else if (config.transcription.provider === 'aliyun' && (!config.transcription.aliyun.speech.accessKeyId.trim() || !config.transcription.aliyun.speech.accessKeySecret.trim() || !config.transcription.aliyun.speech.appKey.trim())) {- add('blocked', { id: 'transcription-config', title: '语音识别凭据缺失', message: '请补全阿里云语音识别凭据。', executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=transcription' });+ add('blocked', { id: 'transcription-config', title: 'Speech recognition credentials missing', message: 'Complete the Aliyun speech recognition credentials.', executionMode: 'remote' }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=transcription' });} else if (config.transcription.provider === 'funasr' && (!config.transcription.funasr.baseUrl.trim() || !config.transcription.funasr.model.trim())) {- add('blocked', { id: 'transcription-config', title: '语音识别配置缺失', message: '请补全 FunASR Base URL 和模型。', executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=transcription' });+ add('blocked', { id: 'transcription-config', title: 'Speech recognition configuration missing', message: 'Complete the FunASR Base URL and model.', executionMode: 'remote' }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=transcription' });} else if (config.transcription.provider === 'volcengine' && (!config.transcription.volcengine.appId.trim() || !config.transcription.volcengine.accessToken.trim())) {- add('blocked', { id: 'transcription-config', title: '语音识别凭据缺失', message: '请补全火山引擎 App ID 和 Access Token。', executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=transcription' });- } else add('ready', { id: 'transcription-config', title: '语音识别', message: `${config.transcription.provider} 已配置。`, executionMode: provider.kind === 'local' ? 'local' : 'remote' });+ add('blocked', { id: 'transcription-config', title: 'Speech recognition credentials missing', message: 'Complete the Volcengine App ID and access token.', executionMode: 'remote' }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=transcription' });+ } else add('ready', { id: 'transcription-config', title: 'Speech recognition', message: `${config.transcription.provider} is configured.`, executionMode: provider.kind === 'local' ? 'local' : 'remote' });}}@@ -446,8 +446,8 @@ function checkOpenAi(deepLink: string,add: Parameters<typeof checkProviderConfig>[5]) {- if (!value.baseUrl.trim() || !value.model.trim() || !value.apiKey.trim()) add('blocked', { id, title: `${title}配置不完整`, message: `请补全 ${title} 的 Base URL、模型和 API Key。`, executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink });- else add('ready', { id, title, message: `${value.model} 已配置。`, executionMode: 'remote' });+ if (!value.baseUrl.trim() || !value.model.trim() || !value.apiKey.trim()) add('blocked', { id, title: `${title} configuration incomplete`, message: `Complete the Base URL, model, and API key for ${title}.`, executionMode: 'remote' }, { label: 'Open AI service settings', deepLink });+ else add('ready', { id, title, message: `${value.model} is configured.`, executionMode: 'remote' });}function checkTts(config: CreatorServicesConfig, provider: Exclude<CreatorServicesConfig['tts']['provider'], 'edge-tts'>, add: Parameters<typeof checkProviderConfig>[5]) {@@ -455,8 +455,8 @@ function checkTts(config: CreatorServicesConfig, provider: Exclude<CreatorServic? Boolean(config.tts.volcengine.appId.trim() && config.tts.volcengine.accessToken.trim()): Boolean(config.tts[provider].apiKey.trim());const value = config.tts[provider];- if (!value.baseUrl.trim() || !value.model.trim() || !credentialsReady) add('blocked', { id: 'tts', title: '配音服务配置不完整', message: `请补全 ${provider} 的 Base URL、模型和凭据。`, executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=tts' });- else add('ready', { id: 'tts', title: '配音服务', message: `${provider} / ${value.model} 已配置。`, executionMode: 'remote' });+ if (!value.baseUrl.trim() || !value.model.trim() || !credentialsReady) add('blocked', { id: 'tts', title: 'Speech service configuration incomplete', message: `Complete the Base URL, model, and credentials for ${provider}.`, executionMode: 'remote' }, { label: 'Open AI service settings', deepLink: '#/settings?tab=ai-services§ion=tts' });+ else add('ready', { id: 'tts', title: 'Speech service', message: `${provider} / ${value.model} is configured.`, executionMode: 'remote' });}async function checkInputs(@@ -466,18 +466,18 @@ async function checkInputs(add: Parameters<typeof checkProviderConfig>[5]): Promise<void> {for (const kind of missing) {- add('blocked', { id: `input-artifact:${kind}`, title: '前置产物缺失', message: `请先生成 ${kind},再启动 ${stage.id}。`, executionMode: 'local' }, { label: '返回上一步', deepLink: '#/settings?tab=diagnostics' });+ add('blocked', { id: `input-artifact:${kind}`, title: 'Required input missing', message: `Generate ${kind} before starting ${stage.id}.`, executionMode: 'local' }, { label: 'Return to the previous step', deepLink: '#/settings?tab=diagnostics' });}for (const artifact of artifacts) {if (artifact.path === null) {- add('blocked', { id: 'input-file', title: '输入文件不可用', message: '所选输入文件不存在或不可读。', executionMode: 'local' }, { label: '重新选择输入文件', deepLink: '#/settings?tab=diagnostics' });+ add('blocked', { id: 'input-file', title: 'Input file unavailable', message: 'The selected input file is missing or unreadable.', executionMode: 'local' }, { label: 'Select the input file again', deepLink: '#/settings?tab=diagnostics' });continue;}try {await access(artifact.path, constants.R_OK);- add('ready', { id: `input-file:${artifact.id}`, title: '输入文件', message: '输入文件存在且可读。', executionMode: 'local' });+ add('ready', { id: `input-file:${artifact.id}`, title: 'Input file', message: 'The input file exists and is readable.', executionMode: 'local' });} catch {- add('blocked', { id: 'input-file', title: '输入文件不可读', message: '所选输入文件不存在或不可读。', executionMode: 'local' }, { label: '重新选择输入文件', deepLink: '#/settings?tab=diagnostics' });+ add('blocked', { id: 'input-file', title: 'Input file unreadable', message: 'The selected input file is missing or unreadable.', executionMode: 'local' }, { label: 'Select the input file again', deepLink: '#/settings?tab=diagnostics' });}}}diff --git a/apps/daemon/src/creator/provider-requests.ts b/apps/daemon/src/creator/provider-requests.tsindex 868705cb..da7305bd 100644--- a/apps/daemon/src/creator/provider-requests.ts+++ b/apps/daemon/src/creator/provider-requests.ts@@ -170,7 +170,7 @@ export class CreatorProviderRequestLedger {if (result.status === 'waiting_remote') {return this.transition(id,- ['submitting', 'waiting_remote', 'unknown_remote_acceptance'],+ ['registered', 'submitting', 'waiting_remote', 'unknown_remote_acceptance'],'waiting_remote',{ remoteTaskId: result.remoteTaskId });@@ -178,7 +178,7 @@ export class CreatorProviderRequestLedger {if (result.status === 'succeeded') {const request = this.transition(id,- ['submitting', 'waiting_remote', 'unknown_remote_acceptance'],+ ['registered', 'submitting', 'waiting_remote', 'unknown_remote_acceptance'],'succeeded',{...(result.remoteTaskId === undefined ? {} : { remoteTaskId: result.remoteTaskId }),@@ -190,7 +190,7 @@ export class CreatorProviderRequestLedger {}const request = this.transition(id,- ['submitting', 'waiting_remote', 'unknown_remote_acceptance'],+ ['registered', 'submitting', 'waiting_remote', 'unknown_remote_acceptance'],'failed',result.remoteTaskId === undefined ? {} : { remoteTaskId: result.remoteTaskId });@@ -294,8 +294,8 @@ export class CreatorProviderRequestLedger {stageRunId: request.stageRunId,scopeKey: request.scopeKey ?? undefined,fallbackMessage: unknownRemoteAcceptance- ? '外部服务是否已接收请求尚不明确,请先查询状态或确认后再继续。'- : '外部服务调用失败,可以重试或询问 Agent。',+ ? 'It is unclear whether the external service accepted the request. Check its status or confirm before continuing.'+ : 'The external service request failed. Try again or ask the Agent.',publicFacts: factsForProvider(error, request.provider),...(error instanceof Error ? { technicalDetail: sanitizeIssueDetail(error.message) } : {}),retryable: !unknownRemoteAcceptance,diff --git a/apps/daemon/src/creator/repository.ts b/apps/daemon/src/creator/repository.tsindex ec22b07c..1912de00 100644--- a/apps/daemon/src/creator/repository.ts+++ b/apps/daemon/src/creator/repository.ts@@ -1381,10 +1381,10 @@ function deriveLegacyStageIssues(: 'issue.execution',summaryParams: {},fallbackMessage: outputFailure- ? '翻译结果未通过目标语言检查,请修正后重试。'+ ? 'The translation failed target language validation. Correct it and try again.': providerFailure- ? '外部服务调用失败,请先确认请求状态后再继续。'- : '创作步骤执行失败,可以重试或询问 Agent。',+ ? 'The external service request failed. Confirm its status before continuing.'+ : 'The creator step failed. Try again or ask the Agent.',retryable,repairActions,fingerprint: digest,diff --git a/apps/daemon/src/creator/service.ts b/apps/daemon/src/creator/service.tsindex f29ebffa..40c437e5 100644--- a/apps/daemon/src/creator/service.ts+++ b/apps/daemon/src/creator/service.ts@@ -240,7 +240,7 @@ export function createCreatorService(input: {revision: 0,actor: 'user',action: 'create-job',- summary: '创建创作任务',+ summary: 'Created creator task',details: input.activityDetails});return repository.getJob(job.id)!;@@ -362,7 +362,7 @@ export function createCreatorService(input: {revision,actor: 'user',action: 'register-source-video',- summary: '上传本地视频',+ summary: 'Uploaded local video',details: {objectId: input.fileName,affectedArtifactIds: [artifact.id]@@ -466,7 +466,7 @@ export function createCreatorService(input: {revision,actor: 'user',action: 'import-source-video',- summary: '从项目文件导入视频',+ summary: 'Imported video from project files',details: {objectId: fileName,sourceJobId: input.sourceJobId,@@ -555,16 +555,16 @@ export function createCreatorService(input: {}) as Record<string, CreatorJson>});const referenceImageLabel = current.templateId === 'cover'- ? '封面参考图'+ ? 'thumbnail reference image': current.templateId === 'video-generation'- ? '视频生成参考图'- : '图像生成参考图';+ ? 'video reference image'+ : 'image generation reference image';repository.insertActivity({jobId,revision,actor: 'user',action: 'register-reference-image',- summary: `${duplicate === undefined ? '上传' : '重新选择'}${referenceImageLabel}`,+ summary: `${duplicate === undefined ? 'Uploaded' : 'Reselected'} ${referenceImageLabel}`,details: {objectId: input.fileName,affectedArtifactIds: [artifact.id]@@ -651,7 +651,7 @@ export function createCreatorService(input: {revision,actor: 'user',action: 'register-article-image',- summary: duplicate === undefined ? '上传文章配图' : '重新插入文章配图',+ summary: duplicate === undefined ? 'Uploaded article image' : 'Reinserted article image',details: {objectId: input.fileName,affectedArtifactIds: [artifact.id]@@ -742,7 +742,7 @@ export function createCreatorService(input: {revision,actor: 'user',action: 'register-source-document',- summary: duplicate === undefined ? '上传内容灵感' : '重新选择内容灵感',+ summary: duplicate === undefined ? 'Uploaded inspiration source' : 'Reselected inspiration source',details: {objectId: input.fileName,affectedArtifactIds: [artifact.id]@@ -946,7 +946,7 @@ export function createCreatorService(input: {[kind === 'source_subtitle' ? 'sourceLanguage' : 'targetLanguage']: language };nextState = { ...nextState, ...appendCreatorResultSnapshot({ job: current, version: resultVersion,changedArtifacts: [artifact], artifactRefsPatch, staleArtifactIds: affectedArtifactIds,- action: request.action, description: '导入本地字幕', state: nextState }) };+ action: request.action, description: 'Imported local subtitles', state: nextState }) };affectedArtifactIds.push(artifact.id);nextStatus = 'draft';} else if (request.action === 'edit-subtitle') {@@ -1115,8 +1115,8 @@ export function createCreatorService(input: {)),action: request.action,description: source.kind === 'target_subtitle'- ? '保存横屏字幕修改'- : '保存竖屏字幕修改',+ ? 'Saved horizontal subtitle changes'+ : 'Saved vertical subtitle changes',state: nextState})};@@ -1137,7 +1137,7 @@ export function createCreatorService(input: {changedArtifacts: [],artifactRefsPatch: videoTranslationArtifactRefsPatch(nextState),action: request.action,- description: '保存版本设置',+ description: 'Saved version settings',state: nextState})};@@ -1148,8 +1148,8 @@ export function createCreatorService(input: {if (stage === undefined) {throw new CreatorServiceError('creator_stage_not_found', 'Creator stage was not found');}- if (current.templateId === 'image-generation' && providerRequestLedger.unresolvedForStage({ jobId, stageId, scopeKey: typeof parsedInput.scopeKey === 'string' ? parsedInput.scopeKey : null }).length > 0) {- throw new CreatorServiceError('creator_provider_resolution_required', 'Resolve the previous paid image request before starting another generation');+ if (['image-generation', 'video-generation'].includes(current.templateId) && providerRequestLedger.unresolvedForStage({ jobId, stageId, scopeKey: typeof parsedInput.scopeKey === 'string' ? parsedInput.scopeKey : null }).length > 0) {+ throw new CreatorServiceError('creator_provider_resolution_required', 'Resolve the previous paid media request before starting another generation');}for (const field of ['baseResultVersion', 'inputResultVersion', 'targetResultVersion'] as const) {readResultVersion(current, parsedInput[field], field);@@ -1215,7 +1215,8 @@ export function createCreatorService(input: {});}} else if (decision === 'query') {- nextStatus = 'needs_input';+ nextStatus = ledger.status === 'failed' ? 'failed' : 'needs_input';+ if (ledger.status === 'succeeded' || ledger.status === 'failed') delete nextState.needsInput;} else {throw new CreatorServiceError('creator_action_invalid',@@ -1505,15 +1506,15 @@ function dependentArtifacts(artifacts: CreatorArtifact[], sourceId: string): Cre}function summarizeAction(action: string, input: Record<string, CreatorJson>): string {- if (action === 'select-result-version') return `选择项目结果 V${String(input.version)}`;- if (action === 'import-subtitle') return '导入本地字幕并保留旧版本';- if (action === 'edit-subtitle') return '更新字幕并保留下游旧版本';- if (action === 'commit-version') return '保存项目版本设置';- if (action === 'run-stage') return `启动阶段 ${String(input.stageId ?? '')}`.trim();- if (action === 'retry-stage') return `重试阶段 ${String(input.stageId ?? '')}`.trim();- if (action === 'resolve-provider-request') return '处置计费服务请求';- if (action === 'undo-action') return '撤销上一次创作修改';- return '更新创作设置';+ if (action === 'select-result-version') return `Selected project result V${String(input.version)}`;+ if (action === 'import-subtitle') return 'Imported local subtitles and retained previous versions';+ if (action === 'edit-subtitle') return 'Updated subtitles and retained previous downstream versions';+ if (action === 'commit-version') return 'Saved project version settings';+ if (action === 'run-stage') return `Started stage ${String(input.stageId ?? '')}`.trim();+ if (action === 'retry-stage') return `Retried stage ${String(input.stageId ?? '')}`.trim();+ if (action === 'resolve-provider-request') return 'Resolved a billed service request';+ if (action === 'undo-action') return 'Undid the previous creator change';+ return 'Updated creator settings';}diff --git a/apps/daemon/src/creator/short-video-script/executor.ts b/apps/daemon/src/creator/short-video-script/executor.tsindex 7624faab..42932378 100644--- a/apps/daemon/src/creator/short-video-script/executor.ts+++ b/apps/daemon/src/creator/short-video-script/executor.ts@@ -118,7 +118,7 @@ export function createShortVideoScriptExecutor(input: {if (Math.abs(actualDurationSeconds - request.targetDurationSeconds) > toleranceSeconds) {throw new CreatorExecutorError('creator_llm_upstream_error',- `脚本总时长 ${actualDurationSeconds} 秒偏离目标 ${request.targetDurationSeconds} 秒,允许误差为 ±${toleranceSeconds} 秒,请重新生成。`+ `The script duration of ${actualDurationSeconds} seconds is outside the ${request.targetDurationSeconds}-second target tolerance of ${toleranceSeconds} seconds. Generate it again.`);}const markdown = formatScript(script, request);diff --git a/apps/daemon/src/creator/smart-dubbing/executor.ts b/apps/daemon/src/creator/smart-dubbing/executor.tsindex e783b412..4a395ca3 100644--- a/apps/daemon/src/creator/smart-dubbing/executor.ts+++ b/apps/daemon/src/creator/smart-dubbing/executor.ts@@ -26,7 +26,7 @@ export function createSmartDubbingExecutor(input: {stage.reportProgress({ phase: 'validating', percent: 5 });const request = readRequest(stage.job.state);const official = input.isOfficial?.() === true;- if (official && (request.style !== 'natural' || request.speed !== 1)) throw new CreatorExecutorError('unsupported_capability', '当前官方语音模型只支持自然表达和默认语速');+ if (official && (request.style !== 'natural' || request.speed !== 1)) throw new CreatorExecutorError('unsupported_capability', 'The official speech model supports only natural delivery and default speed');if (stage.signal.aborted) {throw new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled');}diff --git a/apps/daemon/src/creator/stage-runner.ts b/apps/daemon/src/creator/stage-runner.tsindex 6303fc85..f4e2087c 100644--- a/apps/daemon/src/creator/stage-runner.ts+++ b/apps/daemon/src/creator/stage-runner.ts@@ -154,7 +154,7 @@ export function createCreatorStageRunner(input: {stageId,stageRunId: stageRun!.id,scopeKey: stageRun!.scopeKey ?? undefined,- fallbackMessage: '缺少执行当前步骤所需的输入,请补充后重试。',+ fallbackMessage: 'Required input for this step is missing. Add it and try again.',repairActions: [{ kind: 'select-input', inputField: 'source' }, { kind: 'focus-agent' }]});}@@ -442,15 +442,15 @@ export function createCreatorStageRunner(input: {fallbackMessage: outputValidation? failureMessage: configurationInput !== null- ? '缺少执行当前步骤所需的服务配置,请检查相关服务设置。'+ ? 'Required service configuration is missing for this step. Check the relevant service settings.': unknownProviderAcceptance- ? '外部服务是否已接收请求尚不明确,请先查询状态或确认后再继续。'+ ? 'It is unclear whether the external service accepted the request. Check its status or confirm before continuing.': error instanceof CreatorExecutorError&& error.publicFacts?.provider === 'yt-dlp'? failureMessage: providerFailure- ? '外部服务调用失败,可以重试或询问 Agent。'- : '创作步骤执行失败,可以重试或询问 Agent。',+ ? 'The external service request failed. Try again or ask the Agent.'+ : 'The creator step failed. Try again or ask the Agent.',technicalDetail: failureMessage,publicFacts: configurationInput !== null? { ...stageFailureFacts(error, failureCode), kind: 'configuration' }@@ -788,28 +788,28 @@ function errorCode(error: unknown): string {function resultSnapshotDescription(stageId: string, templateId: string): string {if (templateId === 'wechat-article') {- if (stageId === 'sources') return '解析内容灵感';- if (stageId === 'topics') return '生成候选选题';- if (stageId === 'outline') return '生成文章大纲';- if (stageId === 'article') return '撰写公众号文章';- if (stageId === 'images') return '生成文章配图';+ if (stageId === 'sources') return 'Parsed inspiration sources';+ if (stageId === 'topics') return 'Generated topic candidates';+ if (stageId === 'outline') return 'Generated article outline';+ if (stageId === 'article') return 'Wrote WeChat article';+ if (stageId === 'images') return 'Generated article images';}if (templateId === 'auto-clip') {- if (stageId === 'analyze') return '识别视频高光片段';- if (stageId === 'render') return '导出视频切片';+ if (stageId === 'analyze') return 'Identified video highlights';+ if (stageId === 'render') return 'Exported video clips';}- if (stageId === 'subtitle') return '生成字幕';- if (stageId === 'tts') return '生成配音';- if (stageId === 'render-horizontal') return '合成横屏视频';- if (stageId === 'render-vertical') return '合成竖屏视频';+ if (stageId === 'subtitle') return 'Generated subtitles';+ if (stageId === 'tts') return 'Generated dubbing';+ if (stageId === 'render-horizontal') return 'Rendered horizontal video';+ if (stageId === 'render-vertical') return 'Rendered vertical video';if (stageId === 'generate') {- if (templateId === 'cover') return '生成封面';- if (templateId === 'video-generation') return '生成视频';- if (templateId === 'xiaohongshu-post') return '生成小红书帖子';- if (templateId === 'short-video-script') return '生成短视频脚本';- return '生成图片';+ if (templateId === 'cover') return 'Generated thumbnail';+ if (templateId === 'video-generation') return 'Generated video';+ if (templateId === 'xiaohongshu-post') return 'Generated Xiaohongshu post';+ if (templateId === 'short-video-script') return 'Generated short video script';+ return 'Generated image';}- return `完成 ${stageId}`;+ return `Completed ${stageId}`;}function nextStageResultVersion(job: CreatorJob, stageId: string): number {diff --git a/apps/daemon/src/creator/stickman/action-handler.ts b/apps/daemon/src/creator/stickman/action-handler.tsindex 01a72968..a6853f08 100644--- a/apps/daemon/src/creator/stickman/action-handler.ts+++ b/apps/daemon/src/creator/stickman/action-handler.ts@@ -271,7 +271,7 @@ export function handleStickmanAction(input: {if (visualDescription === undefined && motion === undefined) {throw new CreatorServiceError('creator_action_input_invalid',- '画面描述或运镜至少需要修改一项'+ 'Change the visual description or camera motion');}const shots = shotSpec.shots.map((shot, index) => index === targetIndex@@ -401,7 +401,7 @@ function requireNoPendingImageProviderRequest(job: CreatorJob): void {if (pending) {throw new CreatorServiceError('creator_provider_resolution_required',- '必须先确认状态未明的画面生成请求,才能继续批量生成'+ 'Resolve the unknown visual generation request before continuing batch generation');}}@@ -431,7 +431,7 @@ function normalizeEditedScript(if (overlongSegment !== undefined) {throw new CreatorServiceError('creator_script_segment_duration_invalid',- `${overlongSegment.id} 的预计配音时长超过 5 秒,请按完整语义拆成多个旁白单元`+ `The estimated speech duration of ${overlongSegment.id} exceeds 5 seconds. Split it into complete narration units.`);}const totalNarrationUnits = segments.reduce((total, segment) => total + segment.narrationUnits, 0);@@ -441,7 +441,7 @@ function normalizeEditedScript() {throw new CreatorServiceError('creator_script_duration_budget_invalid',- `旁白长度必须保持在 ${value.narrationBudget.minUnits}-${value.narrationBudget.maxUnits} ${unit === 'words' ? '词' : '字符'}内`+ `Narration must contain ${value.narrationBudget.minUnits}-${value.narrationBudget.maxUnits} ${unit === 'words' ? 'words' : 'characters'}.`);}return stickmanScriptManifestSchema.parse({diff --git a/apps/daemon/src/creator/stickman/audio-executor.ts b/apps/daemon/src/creator/stickman/audio-executor.tsindex eb2e37aa..457faec2 100644--- a/apps/daemon/src/creator/stickman/audio-executor.ts+++ b/apps/daemon/src/creator/stickman/audio-executor.ts@@ -298,7 +298,7 @@ function resolveTtsSelection(stage: CreatorExecutorInput, config: CreatorServiceif (provider === undefined) {throw new CreatorExecutorError('creator_tts_config_missing',- '请先在 AI 服务的配音服务中配置可用的配音 Provider'+ 'Configure an available TTS provider in AI Services first');}if (provider === 'edge-tts') {@@ -320,7 +320,7 @@ function resolveTtsSelection(stage: CreatorExecutorInput, config: CreatorServiceif (!voiceId) {throw new CreatorExecutorError('creator_tts_config_missing',- '请先在 AI 服务的配音服务中选择默认音色'+ 'Select a default voice in AI Services first');}return { provider, model, voiceId };diff --git a/apps/daemon/src/creator/stickman/content-executor.ts b/apps/daemon/src/creator/stickman/content-executor.tsindex 09d20b1f..1c3e9d98 100644--- a/apps/daemon/src/creator/stickman/content-executor.ts+++ b/apps/daemon/src/creator/stickman/content-executor.ts@@ -258,7 +258,7 @@ async function script(stage: CreatorExecutorInput, complete: CompleteJson) {progress: {phase: 'completed',percent: 100,- message: '脚本已生成,等待审核',+ message: 'The script is ready for review',completed: 1,failed: 0,total: 1@@ -269,7 +269,7 @@ async function script(stage: CreatorExecutorInput, complete: CompleteJson) {stage.reportProgress({phase: 'writing',percent: 40 + attempt * 25,- message: `脚本第 ${attempt + 1} 次生成未通过完整性校验,正在整稿重生成`,+ message: `Script attempt ${attempt + 1} failed completeness checks. Regenerating the full script.`,completed: 0,failed: 1,total: 1@@ -278,7 +278,7 @@ async function script(stage: CreatorExecutorInput, complete: CompleteJson) {throw new CreatorExecutorError('creator_script_validation_failed',- `脚本在 3 次整稿生成后仍未通过校验:${formatScriptFailures(failures)}`+ `The script failed validation after 3 complete attempts: ${formatScriptFailures(failures)}`);}@@ -374,22 +374,22 @@ function finalizeShotScript(const narration = raw.narration.trim();if (!/[。!?!?;;.]\s*["'”’))\]]?$/u.test(narration)) {- failures.push(`${id} 的旁白不是完整句子`);+ failures.push(`Narration for ${id} is not a complete sentence`);}if (claimIds.some(claimId => !retained.has(claimId))) {- failures.push(`${id} 引用了未保留或不存在的 Claim`);+ failures.push(`${id} references a discarded or missing claim`);}const supportedSpans = new Set(claimIds.flatMap(claimId => [...(claimSpans.get(claimId) ?? [])]));if (sourceSpanIds.some(sourceSpanId => !supportedSpans.has(sourceSpanId))) {- failures.push(`${id} 的来源片段不受其 Claim 支持`);+ failures.push(`The source spans for ${id} are not supported by its claims`);}claimIds.forEach(claimId => coveredClaims.add(claimId));const normalized = normalizeScriptText(narration);if (normalizedNarrations.has(normalized)) {- failures.push(`${id} 与 ${normalizedNarrations.get(normalized)} 的旁白重复`);+ failures.push(`${id} duplicates the narration of ${normalizedNarrations.get(normalized)}`);} else {normalizedNarrations.set(normalized, id);}@@ -398,7 +398,7 @@ function finalizeShotScript(narrationUnits / plan.narrationBudget.unitsPerMinute * 60);if (estimatedDurationSeconds > MAX_ESTIMATED_SCRIPT_SEGMENT_SECONDS) {- failures.push(`${id} 的预计配音时长 ${estimatedDurationSeconds} 秒超过 ${MAX_ESTIMATED_SCRIPT_SEGMENT_SECONDS} 秒,请按完整语义重新拆成多个旁白单元`);+ failures.push(`The estimated speech duration of ${id} (${estimatedDurationSeconds} seconds) exceeds ${MAX_ESTIMATED_SCRIPT_SEGMENT_SECONDS} seconds. Split it into complete narration units.`);}return {id,@@ -413,7 +413,7 @@ function finalizeShotScript(const missingClaims = plan.retainedClaimIds.filter(claimId => !coveredClaims.has(claimId));if (missingClaims.length > 0) {- failures.push(`保留 Claim 未被脚本覆盖:${missingClaims.join('、')}`);+ failures.push(`Retained claims not covered by the script: ${missingClaims.join(', ')}`);}const totalNarrationUnits = segments.reduce((total, segment) => (total + segment.narrationUnits@@ -423,8 +423,8 @@ function finalizeShotScript(|| totalNarrationUnits > plan.narrationBudget.maxUnits) {failures.push(- `旁白总${plan.narrationBudget.unit === 'characters' ? '字符' : '词'}数 ${totalNarrationUnits} `- + `不在预算 ${plan.narrationBudget.minUnits}-${plan.narrationBudget.maxUnits} 内`+ `The narration contains ${totalNarrationUnits} ${plan.narrationBudget.unit === 'characters' ? 'characters' : 'words'}, `+ + `outside the ${plan.narrationBudget.minUnits}-${plan.narrationBudget.maxUnits} budget`);}if (failures.length > 0) return { failures: [...new Set(failures)] };@@ -460,9 +460,9 @@ function assertContentPlanClaims(throw new CreatorExecutorError('creator_content_plan_claim_partition_invalid',[- missing.length > 0 ? `未处理 Claim:${missing.join('、')}` : '',- unknown.length > 0 ? `未知 Claim:${unknown.join('、')}` : ''- ].filter(Boolean).join(';') || '内容计划的 Claim 取舍无效'+ missing.length > 0 ? `Unprocessed claims: ${missing.join(', ')}` : '',+ unknown.length > 0 ? `Unknown claims: ${unknown.join(', ')}` : ''+ ].filter(Boolean).join('; ') || 'Invalid claim selection in the content plan');}}@@ -516,8 +516,8 @@ async function storyboard(stage: CreatorExecutorInput, complete: CompleteJson) {phase: attempt < 2 ? 'planning' : 'failed',percent: 40 + attempt * 25,message: attempt < 2- ? `分镜第 ${attempt + 1} 次生成未通过语义契约,正在整稿重生成`- : '分镜连续 3 次生成未通过校验,已停止,请重试',+ ? `Storyboard attempt ${attempt + 1} failed semantic validation. Regenerating the full storyboard.`+ : 'The storyboard failed validation 3 times. Generation stopped. Try again.',completed: 0,failed: 1,total: 1@@ -526,7 +526,7 @@ async function storyboard(stage: CreatorExecutorInput, complete: CompleteJson) {if (value === undefined) {throw new CreatorExecutorError('creator_storyboard_validation_failed',- `分镜在 3 次整稿生成后仍未通过校验:${formatScriptFailures(failures)}`+ `The storyboard failed validation after 3 complete attempts: ${formatScriptFailures(failures)}`);}const shotSpec = await writeJsonArtifact(stage, 'shot-spec.json', value);@@ -597,11 +597,11 @@ function finalizeStoryboard(input: {const actualIds = parsed.data.shots.map(shot => shot.sourceSegmentId);const failures: string[] = [];if (JSON.stringify(actualIds) !== JSON.stringify(expectedIds)) {- failures.push('分镜必须按顺序完整覆盖每个旁白单元,且每个单元只能出现一次');+ failures.push('The storyboard must cover every narration unit exactly once and in order');}for (const shot of parsed.data.shots) {if (requestsVisibleText(shot.visualDescription)) {- failures.push(`${shot.sourceSegmentId} 的画面描述要求生成可见文字`);+ failures.push(`The visual description for ${shot.sourceSegmentId} requests visible text`);}}if (failures.length > 0) return { failures };@@ -918,7 +918,7 @@ function buildSourceSpans(if (content.length === 0) {throw new CreatorExecutorError('creator_source_content_missing',- '来源内容为空,无法生成来源片段'+ 'The source content is empty. Source segments cannot be generated.');}const sentences = (content.match(/[^。!?!?;;\n]+[。!?!?;;]?/gu) ?? [content])@@ -958,7 +958,7 @@ function assertSourceReferences(if (invalidIds.length > 0) {throw new CreatorExecutorError(errorCode,- `内容引用了不存在的来源片段:${invalidIds.join('、')}`+ `The content references missing source spans: ${invalidIds.join(', ')}`);}}diff --git a/apps/daemon/src/creator/stickman/image-executor.ts b/apps/daemon/src/creator/stickman/image-executor.tsindex bb125cd8..b8573c08 100644--- a/apps/daemon/src/creator/stickman/image-executor.ts+++ b/apps/daemon/src/creator/stickman/image-executor.ts@@ -259,7 +259,7 @@ export function createStickmanImageExecutor(input: {const quality = readQuality(stage.job.state.quality);if (gateway) {if (!gateway.capabilities?.image?.includes('edit') || referenceImages.length > 1) {- throw new CreatorExecutorError('creator_stickman_image_provider_unsupported', '当前官方图像服务仅支持 1 张参考图,无法执行此镜头');+ throw new CreatorExecutorError('creator_stickman_image_provider_unsupported', 'The official image service supports one reference image. This shot cannot be generated.');}} else assertReferenceImageSupport(provider, referenceImages.length);const model = imageSettings.model;diff --git a/apps/daemon/src/creator/stickman/remotion-component.ts b/apps/daemon/src/creator/stickman/remotion-component.tsindex 8292b491..3c0386f3 100644--- a/apps/daemon/src/creator/stickman/remotion-component.ts+++ b/apps/daemon/src/creator/stickman/remotion-component.ts@@ -97,7 +97,7 @@ export function createRemotionComponentManager(input: {state = update.state;const percent = update.totalBytes ? Math.min(100, (update.downloadedBytes ?? 0) / update.totalBytes * 100) : null;publish({ phase: 'preparing_dependencies', percent: percent === null ? 1 : percent * 0.05,- message: '正在准备 Remotion 渲染组件,完成后将自动继续渲染。',+ message: 'Preparing the Remotion rendering component. Rendering will continue automatically when ready.',dependency: 'remotion', dependencyItem: update.item, dependencyPercent: percent,downloadedBytes: update.downloadedBytes ?? 0, totalBytes: update.totalBytes ?? value.bytes,bytesPerSecond: update.bytesPerSecond ?? null, remainingSeconds: update.remainingSeconds ?? null });@@ -105,7 +105,7 @@ export function createRemotionComponentManager(input: {});if ((await stat(archive)).size !== value.bytes) throw new Error('remotion_component_archive_size_mismatch');state = 'extracting';- publish({ phase: 'preparing_dependencies', percent: 4, message: '正在安装并校验 Remotion 渲染组件。', dependency: 'remotion' });+ publish({ phase: 'preparing_dependencies', percent: 4, message: 'Installing and verifying the Remotion rendering component.', dependency: 'remotion' });const listing = await runTar(['-tvzf', archive], staging, signal);if (listing.split('\n').filter(Boolean).some(line => !/^[-d]/.test(line) || / -> | link to /.test(line))) throw new Error('remotion_component_archive_links_not_allowed');const names = await runTar(['-tzf', archive], staging, signal);@@ -139,10 +139,10 @@ export function createRemotionComponentManager(input: {controller = new AbortController();state = 'verifying';error = null;- publish({ phase: 'preparing_dependencies', percent: 1, dependency: 'remotion', message: '正在检查 Remotion 渲染组件,缺失时将按需下载。' });+ publish({ phase: 'preparing_dependencies', percent: 1, dependency: 'remotion', message: 'Checking the Remotion rendering component. Missing files will download on demand.' });pending = install().then(runtime => {state = 'ready';- publish({ phase: 'dependencies_ready', percent: 5, dependency: 'remotion', message: 'Remotion 渲染组件已就绪,正在开始渲染。' });+ publish({ phase: 'dependencies_ready', percent: 5, dependency: 'remotion', message: 'The Remotion rendering component is ready. Starting rendering.' });return runtime;}).catch(cause => {state = 'failed';diff --git a/apps/daemon/src/creator/stickman/remotion-executor.ts b/apps/daemon/src/creator/stickman/remotion-executor.tsindex e3f20cd4..00f4c8a7 100644--- a/apps/daemon/src/creator/stickman/remotion-executor.ts+++ b/apps/daemon/src/creator/stickman/remotion-executor.ts@@ -62,7 +62,7 @@ export function createStickmanRemotionExecutor(input: {const workerEntrypoint = input.workerEntrypoint?? resolveDefaultWorkerEntrypoint();try {- stage.reportProgress({ phase: 'rendering', percent: 5, message: '正在渲染火柴人动画。' });+ stage.reportProgress({ phase: 'rendering', percent: 5, message: 'Rendering stickman animation.' });await runWorker(workerEntrypoint, requestPath, resultPath, stage.signal);const result = JSON.parse(await readFile(resultPath, 'utf8')) as {ok?: boolean;diff --git a/apps/daemon/src/creator/templates/cover-actions.ts b/apps/daemon/src/creator/templates/cover-actions.tsindex c0c86924..01ea2e96 100644--- a/apps/daemon/src/creator/templates/cover-actions.ts+++ b/apps/daemon/src/creator/templates/cover-actions.ts@@ -28,7 +28,7 @@ export function createCoverWorkflow(input: {if (!config.llm.apiKey.trim()) {setConfigurationNeeded(input.creator, job.id, {code: 'creator_llm_config_missing',- message: '请先完成文本模型配置,以分析视频内容',+ message: 'Configure a text model before analyzing video content',section: 'text',resumeStageId: stageId});@@ -57,7 +57,7 @@ export function createCoverWorkflow(input: {if (!hasImageCredentials(config, provider)) {setConfigurationNeeded(input.creator, job.id, {code: 'creator_image_config_missing',- message: '请先完成当前图像生成服务配置',+ message: 'Configure the current image generation service first',section: 'image',resumeStageId: stageId});@@ -72,7 +72,7 @@ export function createCoverWorkflow(input: {) {setConfigurationNeeded(input.creator, job.id, {code: 'unsupported_capability',- message: '当前图像服务不支持参考图,请切换到 OpenAI 或 Gemini',+ message: 'The image service does not support references. Switch to OpenAI or Gemini.',section: 'image',resumeStageId: stageId});@@ -299,7 +299,7 @@ function setReferenceNeeded(}creator.setNeedsInput(jobId, {code: 'creator_cover_reference_missing',- message: '无法获取 YouTube 原封面,请重新分析视频来源',+ message: 'Could not retrieve the YouTube thumbnail. Analyze the video source again.',resumeStageId: 'analyze-source',workflow: true});diff --git a/apps/daemon/src/creator/templates/stickman-video-actions.ts b/apps/daemon/src/creator/templates/stickman-video-actions.tsindex 9e6b8b35..a6718e27 100644--- a/apps/daemon/src/creator/templates/stickman-video-actions.ts+++ b/apps/daemon/src/creator/templates/stickman-video-actions.ts@@ -89,7 +89,7 @@ export function createStickmanVideoWorkflow(input: {if (unresolved.length > 0) {throw new CreatorServiceError('creator_provider_resolution_required',- '必须先处置状态未知的 Provider 请求,才能重新执行该阶段'+ 'Resolve the unknown provider request before running this stage again');}const interrupted = [...job.stages].reverse().find(stage => (@@ -100,7 +100,7 @@ export function createStickmanVideoWorkflow(input: {if (interrupted !== undefined && hasRemoteSideEffect(interrupted, job.providerRequests)) {throw new CreatorServiceError('creator_provider_resolution_required',- '该阶段存在尚未确认的远端任务,不能自动重试'+ 'This stage has an unconfirmed remote task and cannot retry automatically');}requireApprovedInputs(job, stageId);@@ -114,7 +114,7 @@ export function createStickmanVideoWorkflow(input: {if (current !== undefined) {throw new CreatorServiceError('creator_job_not_resumable',- '该阶段的精确输出已经完成,无需再次执行'+ 'The exact output for this stage is already complete. No rerun is needed.');}}@@ -522,14 +522,14 @@ function requireApprovedInputs(job: CreatorJob, stageId: string): void {stageAtOrAfter(stageId, 'narration')&& (script === undefined || job.state.approvedScriptArtifactId !== script.id)) {- throw new CreatorServiceError('creator_review_required', '必须先审核当前脚本');+ throw new CreatorServiceError('creator_review_required', 'Review the current script first');}const storyboard = latestCompleted(job, 'shot_spec');if (stageAtOrAfter(stageId, 'style-assets')&& storyboard === undefined) {- throw new CreatorServiceError('creator_stage_input_missing', '必须先生成当前分镜');+ throw new CreatorServiceError('creator_stage_input_missing', 'Generate the current storyboard first');}}@@ -537,13 +537,13 @@ function requireWorkflowTarget(job: CreatorJob, stageId: string): void {if (stageAtOrAfter(stageId, 'timeline') && !workflowTargetAtLeast(job, 'delivery_ready')) {throw new CreatorServiceError('creator_workflow_gate_required',- '必须先确认当前分镜画面,才能开始动画合成'+ 'Confirm the current storyboard visuals before composing the animation');}if (stageAtOrAfter(stageId, 'storyboard') && !workflowTargetAtLeast(job, 'visuals_ready')) {throw new CreatorServiceError('creator_workflow_gate_required',- '必须先完成配音与节奏阶段,才能开始生成分镜画面'+ 'Complete the voice and timing stage before generating storyboard visuals');}}@@ -646,7 +646,7 @@ function setReviewGate(&& currentGate.artifactId === artifactId) return;const messages = {- 'approve-script': '请审核脚本后继续'+ 'approve-script': 'Review the script before continuing'} as const;creator.setNeedsInput(job.id, {code: 'creator_review_required',@@ -673,8 +673,8 @@ function setProviderRecoveryGate(creator.setNeedsInput(job.id, {code: 'creator_provider_resolution_required',message: request === undefined- ? '检测到未完成的远端任务,请确认状态后继续'- : `Provider 请求 ${request.id} 的远端接受状态需要用户处置`,+ ? 'An incomplete remote task was found. Confirm its status before continuing.'+ : `The remote acceptance status of provider request ${request.id} needs your attention`,resumeStageId: stage.stageId,workflow: true});diff --git a/apps/daemon/src/creator/templates/video-generation.ts b/apps/daemon/src/creator/templates/video-generation.tsindex 2711829e..ade3f7a4 100644--- a/apps/daemon/src/creator/templates/video-generation.ts+++ b/apps/daemon/src/creator/templates/video-generation.ts@@ -37,6 +37,8 @@ export function createVideoGenerationTemplate(): CreatorTemplateDefinition {actions: [{ id: 'update-settings', inputSchema: record, allowedStages: ['generate'] },{ id: 'run-stage', inputSchema: record, allowedStages: ['generate'] },+ { id: 'retry-stage', inputSchema: record, allowedStages: ['generate'] },+ { id: 'resolve-provider-request', inputSchema: record, allowedStages: ['generate'] },{ id: 'undo-action', inputSchema: record, allowedStages: ['generate'] }],outputs: [{ kind: 'generated_video', required: true }],diff --git a/apps/daemon/src/creator/templates/video-translation-actions.ts b/apps/daemon/src/creator/templates/video-translation-actions.tsindex 054ee73b..516cf17f 100644--- a/apps/daemon/src/creator/templates/video-translation-actions.ts+++ b/apps/daemon/src/creator/templates/video-translation-actions.ts@@ -35,7 +35,7 @@ export function createVideoTranslationWorkflow(input: {) {setConfigurationNeeded(input.creator, job.id, {code: 'creator_llm_config_missing',- message: '请先完成文本翻译模型配置',+ message: 'Configure the text translation model first',section: 'text'});throw new VideoTranslationWorkflowError(@@ -50,7 +50,7 @@ export function createVideoTranslationWorkflow(input: {if (!hasTtsCredentials(config, job)) {setConfigurationNeeded(input.creator, job.id, {code: 'creator_tts_config_missing',- message: '请先完成目标语言配音服务配置',+ message: 'Configure the target-language TTS service first',section: 'tts'});throw new VideoTranslationWorkflowError(@@ -136,24 +136,24 @@ export async function validateBilibiliSource(job: CreatorJob, service?: VideoMetif (host !== 'bilibili.com' && !host.endsWith('.bilibili.com')) return;const source = parseBilibiliVideoSource(job.state.sourceUrl);if (source === null) {- throw new VideoTranslationWorkflowError('creator_source_invalid_part', 'B 站链接无效,请检查视频地址和分 P 参数(p 必须为正整数)');+ throw new VideoTranslationWorkflowError('creator_source_invalid_part', 'Invalid Bilibili URL. Check the video address and part parameter (p must be a positive integer).');}try {if (service === undefined) throw new Error('Video metadata service unavailable');const metadata = await service.get(source.url);if ((metadata.parts?.length ?? 0) > 1 && source.partIndex === undefined) {- throw new VideoTranslationWorkflowError('creator_source_part_required', `该视频包含 ${metadata.parts!.length} 个分 P,请先在视频来源中选择要翻译的分集`);+ throw new VideoTranslationWorkflowError('creator_source_part_required', `This video has ${metadata.parts!.length} parts. Select the part to translate in the video source settings.`);}if (source.partIndex !== undefined && metadata.parts !== undefined&& !metadata.parts.some(part => part.index === source.partIndex)) {- throw new VideoTranslationWorkflowError('creator_source_invalid_part', '指定的分 P 不存在,请重新选择视频分集');+ throw new VideoTranslationWorkflowError('creator_source_invalid_part', 'The requested video part does not exist. Select another part.');}} catch (error) {if (error instanceof VideoTranslationWorkflowError) throw error;if (error instanceof VideoMetadataError && error.code === 'INVALID_PART') {throw new VideoTranslationWorkflowError('creator_source_invalid_part', error.message);}- throw new VideoTranslationWorkflowError('creator_source_metadata_unavailable', '无法读取 B 站分集信息,请重试;未启动下载或翻译');+ throw new VideoTranslationWorkflowError('creator_source_metadata_unavailable', 'Could not read Bilibili video parts. Try again. Download and translation have not started.');}}diff --git a/apps/daemon/src/creator/video/executor.ts b/apps/daemon/src/creator/video/executor.tsindex ea79d9c7..081df18f 100644--- a/apps/daemon/src/creator/video/executor.ts+++ b/apps/daemon/src/creator/video/executor.ts@@ -215,7 +215,11 @@ export function createVideoExecutor(input: {}};} catch (error) {- if (providerRequest && input.ledger && ['submitting', 'waiting_remote'].includes(providerRequest.status)) input.ledger.markUnknownRemoteAcceptance(providerRequest.id);+ if (providerRequest && input.ledger && ['submitting', 'waiting_remote'].includes(providerRequest.status)) {+ const status = error instanceof VideoGenerationError ? error.publicFacts?.httpStatus ?? error.statusCode : undefined;+ if (providerRequest.remoteTaskId === null && status !== undefined && [400, 401, 402, 403, 404, 422, 429].includes(status)) input.ledger.markFailed(providerRequest.id, error);+ else input.ledger.markUnknownRemoteAcceptance(providerRequest.id);+ }throw creatorVideoError(error);}}@@ -284,10 +288,11 @@ function readResumedResultId(stage: CreatorExecutorInput): string | undefined {: [...stage.job.stages].reverse().find(candidate => (candidate.id !== stage.stageRun.id&& candidate.stageId === stage.stageRun.stageId+ && candidate.scopeKey === stage.stageRun.scopeKey&& candidate.status === 'failed'- && candidate.errorCode === 'creator_video_upstream_error'- && typeof candidate.progress.videoGenerationResultId === 'string'));+ if (typeof resumedFrom !== 'string' && (previous?.errorCode !== 'creator_video_upstream_error'+ || stage.job.providerRequests.some(request => request.stageRunId === previous.id && request.provider === 'opencreator-gateway-video' && request.status === 'failed'))) return undefined;const resultId = previous?.progress.videoGenerationResultId;return typeof resultId === 'string' && resultId.length > 0 ? resultId : undefined;}diff --git a/apps/daemon/src/events/normalizer.ts b/apps/daemon/src/events/normalizer.tsindex 399c52ed..9b75ca7e 100644--- a/apps/daemon/src/events/normalizer.ts+++ b/apps/daemon/src/events/normalizer.ts@@ -419,8 +419,8 @@ export function normalizeAppServerEvent(input: NormalizeInput): AgentEventEnvelocode: 'CODEX_STREAM_RETRYING',severity: 'warning',message: reconnectProgress === undefined- ? 'Codex 响应连接中断,正在自动重连'- : `Codex 响应连接中断,正在自动重连(${reconnectProgress})`,+ ? 'The Codex response connection was interrupted. Reconnecting automatically.'+ : `The Codex response connection was interrupted. Reconnecting automatically (${reconnectProgress}).`,details: { raw: params }}};diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.tsindex 4b438b44..d7fe4a76 100644--- a/apps/daemon/src/gateway/account-service.ts+++ b/apps/daemon/src/gateway/account-service.ts@@ -1,4 +1,4 @@-import type { GatewayAccountState, GatewayBalanceSnapshot, GatewayBalanceState, ServiceSource } from '@opencreator/protocol';+import type { GatewayAccountState, GatewayBalanceSnapshot, GatewayBalanceState, GatewayModel, PublicErrorFacts, ServiceSource } from '@opencreator/protocol';import { z } from 'zod';import { createGatewayConfigStore, type GatewayCredentials } from './config-store.js';import { accountSchema, bootstrapSchema, cachedModelUsePolicy, catalogSchema, probeCredentialsSchema, GatewayError, type GatewayBootstrap, type GatewayClient, type GatewayDeviceGrant, type GatewayProbeCredentials } from './client.js';@@ -51,7 +51,7 @@ export function createGatewayAccountService(input: {let runtimeCloseWork: Promise<void> | undefined;const saveConfiguration = () => store.writeConfiguration({ source: state.source, bindingVersion: state.bindingVersion, selectedModels });function serialize<T>(work: () => Promise<T>): Promise<T> { const result = mutation.then(work); mutation = result.then(() => undefined, () => undefined); return result; }- function fail(error: unknown) { state.activationState = 'blocked'; state.activationError = { code: error instanceof GatewayError ? error.code : 'services_not_ready', message: '官方服务尚未就绪,请重试' }; }+ function fail(error: unknown) { state.activationState = 'blocked'; state.activationError = { code: error instanceof GatewayError ? error.code : 'services_not_ready', message: 'The official service is not ready. Try again.' }; }function assertIdle() { if (localUses > 0 || input.hasActiveTasks()) throw new GatewayError('active_tasks', 409); }function assertSignedIn() { if (!credentials || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401); return credentials; }function usesCachedModelKey() { return credentials?.modelUsePolicy === cachedModelUsePolicy && credentials.transport === 'openrouter-direct' && credentials.keyRotation === false; }@@ -83,6 +83,35 @@ export function createGatewayAccountService(input: {const eligible = withModelCatalog(bootstrap, officialModelPolicy(bootstrap.models));return input.modelAccess && eligible.transport === 'openrouter-direct' ? input.modelAccess.prepare(eligible) : eligible;}+ async function applyVisibleCatalog(next: GatewayBootstrap) {+ if (!credentials) return;+ if (JSON.stringify(state.models) !== JSON.stringify(next.models) || JSON.stringify(state.selectedModels) !== JSON.stringify(next.defaults)) {+ credentials = { ...credentials, defaults: next.defaults };+ selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels }; state.models = next.models;+ await store.writeCredentials(credentials); await saveConfiguration();+ }+ }+ async function refreshVisibleCatalog() {+ if (!input.modelAccess || closing || accessPaused || credentials?.modelAccessError || credentials?.transport !== 'openrouter-direct' || state.authState !== 'signed_in') return;+ const original = bootstrapSchema.parse(credentials); const expected = generation;+ await visibleBootstrap(original);+ if (closing || accessPaused || generation !== expected || state.authState !== 'signed_in') return;+ await serialize(async () => {+ if (generation === expected && state.authState === 'signed_in' && credentials?.account?.id === original.account.id && credentials.keyVersion === original.keyVersion) await applyVisibleCatalog(input.modelAccess!.filter(bootstrapSchema.parse(credentials)));+ });+ }+ async function reportModelFailure(scope: { accountId: string; keyVersion: string; accessContext?: string; models?: GatewayModel[] }, id: string, modality: GatewayModel['modality'], facts: PublicErrorFacts) {+ if (closing || accessPaused || state.authState !== 'signed_in') return;+ await serialize(async () => {+ if (!input.modelAccess || state.authState !== 'signed_in' || credentials?.transport !== 'openrouter-direct'+ || credentials.account?.id !== scope.accountId || credentials.keyVersion !== scope.keyVersion) return;+ const bootstrap = bootstrapSchema.parse(credentials);+ const model = bootstrap.models.find(candidate => candidate.id === id && candidate.modality === modality);+ const submitted = scope.models?.find(candidate => candidate.id === id && candidate.modality === modality);+ if (scope.models && JSON.stringify(submitted) !== JSON.stringify(model)) return;+ if (model && await input.modelAccess.recordFailure(scope.accessContext ?? '', model, facts)) await applyVisibleCatalog(input.modelAccess.filter(bootstrap));+ });+ }function needsAccessibleRuntime() {return credentials?.transport === 'openrouter-direct' && !credentials.modelAccessError && state.authState === 'signed_in'&& state.source === 'gateway' && !closing && !accessPaused && (state.activationState === 'ready' || accessBlocked)@@ -112,11 +141,7 @@ export function createGatewayAccountService(input: {if (controller.signal.aborted || closing || generation !== expected || state.authState !== 'signed_in'|| credentials?.account?.id !== original.account.id || credentials.keyVersion !== original.keyVersion) return;const next = input.modelAccess!.filter(withModelCatalog(bootstrapSchema.parse(credentials), officialModelPolicy(credentials.models ?? [])));- if (JSON.stringify(state.models) !== JSON.stringify(next.models) || JSON.stringify(state.selectedModels) !== JSON.stringify(next.defaults)) {- credentials = { ...credentials, defaults: next.defaults };- selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels }; state.models = next.models;- await store.writeCredentials(credentials); await saveConfiguration();- }+ await applyVisibleCatalog(next);await synchronizeAccessibleRuntime();});});@@ -277,6 +302,7 @@ export function createGatewayAccountService(input: {function refreshState(): Promise<void> {stateRefreshWork ??= (async () => {await readProfile(); await readCatalog();+ await refreshVisibleCatalog();if (needsAccessibleRuntime()) await serialize(synchronizeAccessibleRuntime);scheduleModelAccess();})().finally(() => { stateRefreshWork = undefined; });@@ -331,7 +357,7 @@ export function createGatewayAccountService(input: {}async function performAuthorizationPoll(current: NonNullable<typeof attempt>) {const id = current.attemptId;- if (current.expiresAt <= Date.now()) { await cancelAuthorization(); state.activationError = { code: 'device_expired', message: '登录授权已过期,请重新登录' }; return; }+ if (current.expiresAt <= Date.now()) { await cancelAuthorization(); state.activationError = { code: 'device_expired', message: 'Sign-in authorization expired. Sign in again.' }; return; }try {const tokens = await input.client.pollDevice(id, current.deviceSecret);if (generation !== current.generation || attempt !== current) { await input.client.logout(tokens.accessToken).catch(() => undefined); return; }@@ -361,17 +387,18 @@ export function createGatewayAccountService(input: {fail(error); await cancelAuthorization();}}- async function readModelCredentials(): Promise<{ accountId: string; modelKey: string; keyVersion: string; bindingVersion: string; baseUrl: string; transport?: GatewayBootstrap['transport']; models: GatewayBootstrap['models']; defaults: Record<string, string> }> {+ async function readModelCredentials(recovery = false): Promise<{ accountId: string; modelKey: string; keyVersion: string; bindingVersion: string; baseUrl: string; transport?: GatewayBootstrap['transport']; models: GatewayBootstrap['models']; defaults: Record<string, string>; accessContext?: string }> {await initialize();if (!usesCachedModelKey()) await refresh();- return currentModelCredentials();+ await refreshVisibleCatalog();+ return currentModelCredentials(recovery);}- function currentModelCredentials() {+ function currentModelCredentials(recovery = false): Awaited<ReturnType<typeof readModelCredentials>> {if (closing || accessPaused) throw new GatewayError('auth_required', 401);const value = assertSignedIn();if (value.modelAccessError) throw new GatewayError(value.modelAccessError, value.modelAccessError === 'auth_required' ? 401 : 403);- if (state.source !== 'gateway' || state.activationState !== 'ready' || !value.account || !value.modelKey || !value.keyVersion || !value.bindingVersion || !value.baseUrl || !value.models || !value.defaults) throw new GatewayError('services_not_ready');- return { accountId: value.account.id, modelKey: value.modelKey, keyVersion: value.keyVersion, bindingVersion: value.bindingVersion, baseUrl: value.baseUrl, transport: value.transport, models: structuredClone(state.models), defaults: { ...value.defaults } };+ if (state.source !== 'gateway' || (!recovery && state.activationState !== 'ready') || !value.account || !value.modelKey || !value.keyVersion || !value.bindingVersion || !value.baseUrl || !value.models || !value.defaults) throw new GatewayError('services_not_ready');+ return { accountId: value.account.id, modelKey: value.modelKey, keyVersion: value.keyVersion, bindingVersion: value.bindingVersion, baseUrl: value.baseUrl, transport: value.transport, models: structuredClone(state.models), defaults: { ...value.defaults }, accessContext: input.modelAccess?.context() };}const modelCredentials = () => readModelCredentials();async function probeCredentials(): Promise<GatewayProbeCredentials> {@@ -455,8 +482,8 @@ export function createGatewayAccountService(input: {}await saveConfiguration();}- async function acquireModelUse() {- const snapshot = await readModelCredentials();+ async function acquireModelUse(recovery = false) {+ const snapshot = await readModelCredentials(recovery);const cached = usesCachedModelKey();localUses++;let released = false;@@ -475,17 +502,17 @@ export function createGatewayAccountService(input: {version = await reportUsage();}if (version && version !== credentials?.keyVersion) await synchronizeBinding();- return { credentials: await readModelCredentials(), release };+ return { credentials: await readModelCredentials(recovery), release };} catch (error) { await release(); throw error; }}- const beginModelUse = () => acquireModelUse();+ const beginModelUse = (options?: { recovery: boolean }) => acquireModelUse(options?.recovery);async function recoverModelCredentials(keyVersion: string) {await initialize();if (!usesCachedModelKey()) throw new GatewayError('model_auth_required', 401);- if (currentModelCredentials().keyVersion !== keyVersion) return currentModelCredentials();+ if (currentModelCredentials(true).keyVersion !== keyVersion) return currentModelCredentials(true);await refresh();await synchronizeBinding();- return currentModelCredentials();+ return currentModelCredentials(true);}async function logout() {await initialize();@@ -517,7 +544,7 @@ export function createGatewayAccountService(input: {return {initialize, startBackgroundRestore,peekState() { return structuredClone(state); },- startAuthorization, cancelAuthorization, pollAuthorization, checkAuthorization, refresh, logout, modelCredentials, beginModelUse, recoverModelCredentials, probeCredentials, readBalance, billing,+ startAuthorization, cancelAuthorization, pollAuthorization, checkAuthorization, refresh, logout, modelCredentials, beginModelUse, recoverModelCredentials, probeCredentials, readBalance, billing, reportModelFailure,readPlans() { return input.client.request('/api/v1/plans', ''); },async readAvatar(accountId: string) {await initialize(); await refresh();@@ -545,7 +572,7 @@ export function createGatewayAccountService(input: {});},async selectModel(modality: import('@opencreator/protocol').GatewayModel['modality'], model: string) {- await initialize(); await serialize(async () => {+ await initialize(); await refreshVisibleCatalog(); await serialize(async () => {assertIdle(); const current = assertSignedIn(); const expected = generation;if (state.source !== 'gateway' || state.activationState !== 'ready' || !current.defaults || !state.models.some(candidate => candidate.modality === modality && candidate.id === model && (modality !== 'text' || candidate.capabilities.includes('responses')))) throw new GatewayError('invalid_model', 400);if (input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);diff --git a/apps/daemon/src/gateway/client.ts b/apps/daemon/src/gateway/client.tsindex dcfd7196..4fd66ede 100644--- a/apps/daemon/src/gateway/client.ts+++ b/apps/daemon/src/gateway/client.ts@@ -10,6 +10,10 @@ const modelSchema = z.object({durations: z.array(z.number().int().positive()).optional(),resolutions: z.array(z.string().min(1)).optional(),aspectRatios: z.array(z.string().min(1)).optional(),+ verification: z.object({+ adapterVersion: z.number().int().positive(), verifiedAt: z.string().datetime(),+ countries: z.array(z.string().regex(/^[A-Z]{2}$/))+ }).optional(),imageOptions: z.object({aspectRatios: z.array(z.string()).optional(), resolutions: z.array(z.string()).optional(),qualities: z.array(z.string()).optional(), outputFormats: z.array(z.string()).optional(),@@ -49,7 +53,7 @@ export type GatewayClient = {cancelPendingRequests?(): void;};export class GatewayError extends Error {- constructor(readonly code: string, readonly status = 503) { super('OpenCreator 网关请求未完成'); }+ constructor(readonly code: string, readonly status = 503) { super('The OpenCreator gateway request did not complete'); }}export function validateGatewayOrigin(origin: string) {const u = new URL(origin);diff --git a/apps/daemon/src/gateway/creator-service-source.ts b/apps/daemon/src/gateway/creator-service-source.tsindex daafdc80..46bea373 100644--- a/apps/daemon/src/gateway/creator-service-source.ts+++ b/apps/daemon/src/gateway/creator-service-source.ts@@ -8,8 +8,8 @@ import { KRILLIN_LLM_ROUTE_PREFIX } from '../creator/krillin/codex-llm-gateway.jimport type { GatewayAccountService } from './account-service.js';import { GatewayError } from './client.js';import type { CreatorServiceBinding } from '../creator/repository.js';-import type { CreatorProviderRequestLedger } from '../creator/provider-requests.js';-import { createDirectTransport } from './direct-transport.js';+import type { CreatorProviderRequestLedger, CreatorProviderLookupResult } from '../creator/provider-requests.js';+import { createDirectTransport, directRequestId } from './direct-transport.js';import { createOfficialFetch } from './official-fetch.js';export type GatewayCreatorBinding = { accountId: string; bindingVersion: string; baseUrl: string; apiKey: string; models: Record<string, string>; catalog?: GatewayModel[]; capabilities?: Record<string, string[]>; speechVoices?: string[]; logicalId?: string; stageRunId?: string };@@ -17,7 +17,7 @@ const bindings = new WeakMap<CreatorServicesConfig, GatewayCreatorBinding>();export function gatewayCreatorBinding(config: CreatorServicesConfig) { return bindings.get(config); }export function createGatewayCreatorSource(input: {- account: Pick<GatewayAccountService, 'peekState' | 'modelCredentials'> & Partial<Pick<GatewayAccountService, 'beginModelUse' | 'recoverModelCredentials'>>;+ account: Pick<GatewayAccountService, 'peekState' | 'modelCredentials'> & Partial<Pick<GatewayAccountService, 'beginModelUse' | 'recoverModelCredentials' | 'reportModelFailure'>>;manual: CreatorServicesConfigStore;getLocalOrigin(): string | undefined;fetcher?: typeof fetch;@@ -54,9 +54,9 @@ export function createGatewayCreatorSource(input: {}return { source: 'gateway', accountId: state.account.id, bindingVersion: state.bindingVersion, models, capabilities: caps };}- function assertSnapshot(value: CreatorServiceBinding) {+ function assertSnapshot(value: CreatorServiceBinding, recovery = false) {const state = input.account.peekState();- if (value.source === 'gateway' && (state.authState !== 'signed_in' || state.activationState !== 'ready')) throw new GatewayError('services_not_ready');+ if (value.source === 'gateway' && (state.authState !== 'signed_in' || (!recovery && state.activationState !== 'ready'))) throw new GatewayError('services_not_ready');if (value.source !== state.source || (value.source === 'gateway' && value.accountId !== state.account?.id)) throw new GatewayError('task_source_mismatch', 409);}function assertJob(jobId: string) { if (input.readJobBinding) assertSnapshot(input.readJobBinding(jobId)); }@@ -97,6 +97,43 @@ export function createGatewayCreatorSource(input: {};return {store, binding, snapshot, assertJob,+ async queryProviderRequest(request: CreatorProviderRequest) {+ if (input.readJobBinding) assertSnapshot(input.readJobBinding(request.jobId), true);+ if (!input.ledger || !request.gateway || !request.provider.startsWith('opencreator-gateway-')) throw new GatewayError('capability_unsupported', 400);+ const use = await input.account.beginModelUse?.({ recovery: true });+ try {+ const credentials = use?.credentials ?? await input.account.modelCredentials();+ if (credentials.accountId !== request.gateway.accountId) throw new GatewayError('task_source_mismatch', 409);+ const requestId = request.remoteTaskId ?? (credentials.transport === 'openrouter-direct'+ ? directRequestId(credentials.accountId, request.requestKey) : undefined);+ if (!requestId) throw new GatewayError('request_outcome_unknown', 409);+ const signal = AbortSignal.timeout(30_000);+ let lookupResult: Promise<CreatorProviderLookupResult> | undefined;+ const lookup = async (): Promise<CreatorProviderLookupResult> => {+ let response: Response;+ try {+ response = credentials.transport === 'openrouter-direct' && direct+ ? await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource: `requests/${requestId}`, method: 'GET', body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal,+ onModelFailure: async (id, modality, facts) => { await input.account.reportModelFailure?.(credentials, id, modality, facts); } })+ : await (input.fetcher ?? fetch)(`${credentials.baseUrl}/requests/${encodeURIComponent(requestId)}`, { method: 'GET', headers: { Authorization: `Bearer ${credentials.modelKey}` }, redirect: 'error', signal });+ } catch (error) { if (error instanceof GatewayError && error.code === 'request_not_found') return { status: 'not_found' }; throw error; }+ if (response.status === 404) return { status: 'not_found' };+ if (!response.ok) throw new GatewayError('gateway_unavailable');+ const result = await response.json() as { requestId?: string; state?: string };+ if (result.requestId !== requestId) throw new GatewayError('invalid_gateway_response');+ if (result.state === 'succeeded') return { status: 'succeeded', remoteTaskId: requestId };+ if (result.state === 'failed' || result.state === 'canceled') return { status: 'failed', remoteTaskId: requestId };+ if (result.state === 'outcome_unknown') return { status: 'not_found' };+ if (!['submitting', 'waiting_upstream'].includes(result.state ?? '')) throw new GatewayError('invalid_gateway_response');+ return { status: 'waiting_remote', remoteTaskId: requestId };+ };+ const provider = { lookupByRequestKey: true, lookup: () => lookupResult ??= lookup() };+ await input.ledger.recover(request.id, provider);+ for (const related of input.ledger.findByRemoteTaskId(request.jobId, requestId)) {+ if (related.id !== request.id && related.gateway?.accountId === credentials.accountId && related.provider.startsWith('opencreator-gateway-')) await input.ledger.recover(related.id, provider);+ }+ } finally { await use?.release(); }+ },async runForJob<T>(jobId: string, stageRunId: string, work: () => Promise<T>): Promise<T> {let original = input.readJobBinding?.(jobId) ?? snapshot();assertSnapshot(original);@@ -108,7 +145,12 @@ export function createGatewayCreatorSource(input: {const catalog = input.account.peekState().models;for (const [modality, id] of Object.entries(choices)) {const selected = catalog.find(candidate => candidate.modality === modality && candidate.id === id && (modality !== 'text' || candidate.capabilities.includes('responses')));- if (!selected) throw new GatewayError('invalid_model', 400);+ if (!selected) {+ const resumed = typeof input.readStageRun?.(stageRunId)?.progress.resumedFromStageRunId === 'string';+ if (!resumed || !['image', 'video'].includes(modality) || typeof id !== 'string') throw new GatewayError('invalid_model', 400);+ original.models[modality] = id;+ continue;+ }original.models[modality] = selected.id; original.capabilities[modality] = [...selected.capabilities];}}@@ -179,7 +221,7 @@ export function createGatewayCreatorSource(input: {heartbeat = setInterval(() => { if (!reply.raw.destroyed && !reply.raw.writableEnded) reply.raw.write(': keep-alive\n\n'); }, 10_000);heartbeat.unref();}- const use = await input.account.beginModelUse?.(); releaseUse = use?.release;+ const use = await input.account.beginModelUse?.({ recovery: request.method === 'GET' }); releaseUse = use?.release;signal.throwIfAborted();const credentials = use?.credentials ?? await input.account.modelCredentials();signal.throwIfAborted();@@ -202,7 +244,8 @@ export function createGatewayCreatorSource(input: {await input.ledger!.recover(receipt!.id, { lookupByRequestKey: false, async lookup({ remoteTaskId }) {if (!remoteTaskId) return { status: 'not_found' };const response = credentials.transport === 'openrouter-direct' && direct- ? await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource: `requests/${remoteTaskId}`, method: 'GET', body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal })+ ? await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource: `requests/${remoteTaskId}`, method: 'GET', body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal,+ onModelFailure: async (id, modality, facts) => { await input.account.reportModelFailure?.(credentials, id, modality, facts); } }): await (input.fetcher ?? fetch)(`${credentials.baseUrl}/requests/${encodeURIComponent(remoteTaskId)}`, { method: 'GET', headers: { Authorization: `Bearer ${credentials.modelKey}` }, redirect: 'error', signal });if (!response.ok) throw new GatewayError('gateway_unavailable');const result = await response.json() as { requestId?: string; state?: string };@@ -219,15 +262,20 @@ export function createGatewayCreatorSource(input: {if (credentials.transport === 'openrouter-direct') {if (!direct) throw new GatewayError('services_not_ready');let modelMetadata: GatewayModel | undefined;+ let cachedResponse: Response | undefined;if (request.method === 'POST') {const modality = resource.startsWith('images/') ? 'image' : resource === 'audio/speech' ? 'speech' : resource === 'audio/transcriptions' ? 'transcription' : resource.startsWith('video') ? 'video' : 'text';const model = Buffer.isBuffer(request.body)? (await new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': headers['Content-Type']! }, body: new Uint8Array(request.body) }).formData()).get('model'): (request.body as { model?: unknown })?.model;modelMetadata = credentials.models.find(candidate => candidate.modality === modality && candidate.id === model);- if (!modelMetadata) throw new GatewayError('invalid_model', 400);+ if (!modelMetadata) {+ if (modality === 'image' || modality === 'video') cachedResponse = await direct.replay(credentials.accountId, headers['Idempotency-Key']!, digest ?? '');+ if (!cachedResponse) throw new GatewayError('invalid_model', 400);+ }}- response = await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource, method: request.method, body: request.body, contentType: headers['Content-Type']!, identity: headers['Idempotency-Key'] ?? '', fingerprint: digest ?? '', signal, model: modelMetadata, asyncImage: request.headers.prefer === 'respond-async' });+ response = cachedResponse ?? await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource, method: request.method, body: request.body, contentType: headers['Content-Type']!, identity: headers['Idempotency-Key'] ?? '', fingerprint: digest ?? '', signal, model: modelMetadata, asyncImage: request.headers.prefer === 'respond-async',+ onModelFailure: async (id, modality, facts) => { await input.account.reportModelFailure?.(credentials, id, modality, facts); } });} else response = await (input.fetcher ?? fetch)(`${credentials.baseUrl}/${resource}`, { method: request.method, headers, body, redirect: 'error', signal });signal.throwIfAborted();const id = response.headers.get('x-request-id');diff --git a/apps/daemon/src/gateway/direct-runtime.ts b/apps/daemon/src/gateway/direct-runtime.tsindex 87734e9a..cdcc43fe 100644--- a/apps/daemon/src/gateway/direct-runtime.ts+++ b/apps/daemon/src/gateway/direct-runtime.ts@@ -2,11 +2,15 @@ import { createServer } from 'node:http';import { randomBytes } from 'node:crypto';import { Readable } from 'node:stream';import { pipeline } from 'node:stream/promises';-import { statelessResponses } from './direct-transport.js';+import { errorFacts, statelessResponses, type OfficialModelFailureReporter } from './direct-transport.js';import { officialEventStream } from './official-stream.js';import { GatewayError } from './client.js';+import type { GatewayModel } from '@opencreator/protocol';+import { creatorServiceFailureFacts } from '../creator-services/upstream-fetch.js';-export async function createDirectRuntime(key: string, fetcher: typeof fetch = fetch, beginUse?: () => Promise<{ key: string; keyVersion?: string; release(): Promise<void> }>, recoverKey?: (keyVersion: string) => Promise<{ key: string; keyVersion: string }>) {+export type DirectRuntimeUse = { key: string; keyVersion?: string; release(): Promise<void>; models?: GatewayModel[]; onModelFailure?: OfficialModelFailureReporter };++export async function createDirectRuntime(key: string, fetcher: typeof fetch = fetch, beginUse?: () => Promise<DirectRuntimeUse>, recoverKey?: (keyVersion: string) => Promise<{ key: string; keyVersion: string }>) {const token = `oclocal_${randomBytes(32).toString('base64url')}`;const active = new Set<AbortController>();const handlers = new Set<Promise<void>>();@@ -22,12 +26,16 @@ export async function createDirectRuntime(key: string, fetcher: typeof fetch = ffor await (const chunk of req) { size += chunk.length; if (size > 64 * 1024 * 1024) throw new Error('Request too large'); chunks.push(Buffer.from(chunk)); }const body = statelessResponses(JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>);const use = await beginUse?.(); release = use?.release;+ if (use?.models && !use.models.some(model => model.modality === 'text' && model.id === body.model && model.capabilities.includes('responses'))) {+ res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { code: 'invalid_model', message: 'The selected model is unavailable' } })); return;+ }const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(180_000)]);const submit = (modelKey: string) => {signal.throwIfAborted();return fetcher('https://openrouter.ai/api/v1/responses', { method: 'POST', redirect: 'error', signal, headers: { Authorization: `Bearer ${modelKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });};- let response = await submit(use?.key ?? key);+ let modelKey = use?.key ?? key;+ let response = await submit(modelKey);if (response.status === 401 && use?.keyVersion && recoverKey) {await response.body?.cancel();let updated: { key: string; keyVersion: string };@@ -36,18 +44,21 @@ export async function createDirectRuntime(key: string, fetcher: typeof fetch = fsignal.throwIfAborted();throw error instanceof GatewayError && [401, 403].includes(error.status) ? error : new GatewayError('model_auth_required', 401);}- if (updated.keyVersion !== use.keyVersion) response = await submit(updated.key);+ if (updated.keyVersion !== use.keyVersion) { modelKey = updated.key; response = await submit(modelKey); }}if (!response.ok || !response.body) {- await response.body?.cancel();- res.writeHead([401, 402].includes(response.status) ? response.status : 503, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: response.status === 401 ? '官方模型凭据已失效,请重新连接账号' : response.status === 402 ? '积分不足' : '官方模型服务暂不可用' } })); return;+ const facts = await errorFacts(response, modelKey, signal);+ if (typeof body.model === 'string') { try { await use?.onModelFailure?.(body.model, 'text', facts); } catch {} }+ res.writeHead([401, 402].includes(response.status) ? response.status : 503, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: response.status === 401 ? 'The official model credentials expired. Sign in again.' : response.status === 402 ? 'Insufficient credits' : 'The official model service is unavailable' } })); return;}res.writeHead(200, { 'Content-Type': response.headers.get('content-type') ?? 'text/event-stream', 'Cache-Control': 'no-store' });- const bodyStream = response.headers.get('content-type')?.includes('text/event-stream') ? officialEventStream(response.body) : response.body;+ const bodyStream = response.headers.get('content-type')?.includes('text/event-stream') ? officialEventStream(response.body, async error => {+ if (typeof body.model === 'string') await use?.onModelFailure?.(body.model, 'text', creatorServiceFailureFacts(error));+ }) : response.body;await pipeline(Readable.fromWeb(bodyStream as import('node:stream/web').ReadableStream), res);} catch (error) {const status = error instanceof GatewayError && [401, 403].includes(error.status) ? error.status : 503;- if (!res.headersSent) res.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: status === 401 ? '官方模型凭据已失效,请重新连接账号' : status === 403 ? '官方模型服务暂不可用,请检查账号状态' : '官方模型服务暂不可用' } }));+ if (!res.headersSent) res.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: status === 401 ? 'The official model credentials expired. Sign in again.' : status === 403 ? 'The official model service is unavailable. Check your account status.' : 'The official model service is unavailable' } }));else res.destroy();} finally {try { await release?.(); }diff --git a/apps/daemon/src/gateway/direct-transport.ts b/apps/daemon/src/gateway/direct-transport.tsindex ad90ed18..bc471cd3 100644--- a/apps/daemon/src/gateway/direct-transport.ts+++ b/apps/daemon/src/gateway/direct-transport.ts@@ -1,14 +1,66 @@import { createHash } from 'node:crypto';-import { gatewayDefaultVoiceId, gatewayVideoSizeParameters, type GatewayModel } from '@opencreator/protocol';+import { gatewayDefaultVoiceId, gatewayVideoSizeParameters, safePublicRequestId, type GatewayModel, type PublicErrorFacts } from '@opencreator/protocol';import { join } from 'node:path';import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';import { GatewayError } from './client.js';import { officialEventStream } from './official-stream.js';+import { creatorServiceFailureFacts } from '../creator-services/upstream-fetch.js';+import { publicFactsFromFailure } from '../creator/public-error-facts.js';-type Receipt = { account: string; fingerprint: string; state: 'submitting' | 'waiting_upstream' | 'succeeded' | 'failed' | 'outcome_unknown'; remoteId?: string; status?: number; mime?: string; content?: string; errorCode?: string; errorStatus?: number };+type Receipt = { account: string; fingerprint: string; state: 'submitting' | 'waiting_upstream' | 'succeeded' | 'failed' | 'outcome_unknown'; remoteId?: string; status?: number; mime?: string; content?: string; errorCode?: string; errorStatus?: number;+ model?: string; operation?: string; createdAt?: string; updatedAt?: string; upstreamRequestId?: string; upstreamGenerationId?: string; reportedCostUsd?: number; receivedBytes?: number; upstreamError?: PublicErrorFacts };const base = 'https://openrouter.ai/api/v1';+export const DIRECT_MEDIA_ADAPTER_VERSION = 2;export const DIRECT_IMAGE_TIMEOUT_MS = 10 * 60_000;+export function directRequestId(account: string, identity: string) {+ return 'ocdir_' + createHash('sha256').update(JSON.stringify([account, identity])).digest('hex').slice(0, 48);+}++class DirectUpstreamError extends GatewayError {+ constructor(code: string, status: number, readonly facts: PublicErrorFacts) { super(code, status); }+}++export type OfficialModelFailureReporter = (id: string, modality: GatewayModel['modality'], facts: PublicErrorFacts) => Promise<void>;++export async function errorFacts(response: Response, key: string, signal?: AbortSignal): Promise<PublicErrorFacts> {+ const reader = response.body?.getReader();+ const chunks: Uint8Array[] = []; let size = 0;+ let payload: unknown;+ try {+ if (reader) for (;;) {+ const chunk = await (signal ? abortable(reader.read(), signal) : reader.read());+ if (chunk.done) break;+ size += chunk.value.length;+ if (size > 16_384) break;+ chunks.push(chunk.value);+ }+ if (size <= 16_384) payload = JSON.parse(Buffer.concat(chunks).toString('utf8').replaceAll(key, '[redacted]'));+ } catch {} finally { void reader?.cancel().catch(() => undefined); }+ return creatorServiceFailureFacts(payload, undefined, { httpStatus: response.status, requestId: response.headers.get('x-request-id') ?? undefined });+}++function recordUpstreamMetadata(record: Receipt, value: unknown) {+ if (!value || typeof value !== 'object') return;+ const metadata = value as { id?: unknown; generation_id?: unknown; request_id?: unknown; usage?: { cost?: unknown } };+ const generationId = [metadata.generation_id, metadata.id].find(id => typeof id === 'string' && /^gen-[A-Za-z0-9_-]{1,180}$/.test(id));+ if (typeof generationId === 'string') record.upstreamGenerationId = generationId;+ if (typeof metadata.request_id === 'string') record.upstreamRequestId ??= safePublicRequestId(metadata.request_id);+ const cost = metadata.usage?.cost;+ if (typeof cost === 'number' && Number.isFinite(cost) && cost >= 0) record.reportedCostUsd = cost;+}++function recordVideoStatus(record: Receipt, value: unknown, key: string) {+ const remote = value as { status?: unknown } | null;+ if (!remote || typeof remote.status !== 'string' || !['pending', 'in_progress', 'completed', 'failed', 'cancelled', 'expired'].includes(remote.status)) throw new GatewayError('invalid_gateway_response');+ record.state = remote.status === 'completed' ? 'succeeded' : ['failed', 'cancelled', 'expired'].includes(remote.status) ? 'failed' : 'waiting_upstream';+ recordUpstreamMetadata(record, remote);+ if (record.state === 'failed') {+ record.errorCode = 'official_service_unavailable';+ record.upstreamError = creatorServiceFailureFacts(JSON.parse(JSON.stringify(remote).replaceAll(key, '[redacted]')));+ }+}+function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {signal.throwIfAborted();return new Promise((resolve, reject) => {@@ -26,6 +78,20 @@ function completeImageResponse(content: Buffer): boolean {} catch { return false; }}+function pcmWave(content: Buffer, contentType: string): Buffer {+ const rate = Number(/(?:^|;)\s*rate=(\d+)\s*(?:;|$)/i.exec(contentType)?.[1]);+ const channels = Number(/(?:^|;)\s*channels=(\d+)\s*(?:;|$)/i.exec(contentType)?.[1]);+ if (!Number.isInteger(rate) || rate < 8_000 || rate > 192_000 || !Number.isInteger(channels) || channels < 1 || channels > 8+ || !content.length || content.length % (channels * 2) !== 0) throw new GatewayError('invalid_gateway_response');+ // OpenRouter PCM is signed 16-bit little-endian; rate and channels come from its response.+ const header = Buffer.alloc(44);+ header.write('RIFF', 0); header.writeUInt32LE(content.length + 36, 4); header.write('WAVEfmt ', 8);+ header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(channels, 22);+ header.writeUInt32LE(rate, 24); header.writeUInt32LE(rate * channels * 2, 28);+ header.writeUInt16LE(channels * 2, 32); header.writeUInt16LE(16, 34); header.write('data', 36); header.writeUInt32LE(content.length, 40);+ return Buffer.concat([header, content]);+}+function completeEventStream(content: Buffer, resource?: string): boolean {let completed = false;for (const frame of content.toString('utf8').replace(/\r\n/g, '\n').split('\n\n').slice(0, -1)) {@@ -51,7 +117,7 @@ function pixelAspectRatio(size: unknown) {return `${width / divisor}:${height / divisor}`;}-export function statelessResponses(body: Record<string, unknown>) {+export function statelessResponses(body: Record<string, unknown>): Record<string, unknown> {if (body.previous_response_id) throw new GatewayError('capability_unsupported', 400);const { previous_response_id: _previous, store: _store, ...rest } = body;return { ...rest, store: false };@@ -72,7 +138,7 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetc}return record;};- const write = (id: string, record: Receipt) => writePrivateJsonFile(path(id), record);+ const write = (id: string, record: Receipt) => writePrivateJsonFile(path(id), { ...record, updatedAt: new Date().toISOString() });const response = (id: string, record: Receipt) => new Response(Buffer.from(record.content ?? '', 'base64'), { status: record.status ?? 200, headers: { 'Content-Type': record.mime ?? 'application/json', 'X-Request-ID': id } });const accepted = (id: string) => Response.json({ requestId: id, state: 'waiting_upstream' }, { status: 202, headers: { 'X-Request-ID': id } });async function call(resource: string, options: RequestInit, key: string, account: string) {@@ -85,7 +151,8 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetcthrow error;}};- let result = await submit(key);+ let modelKey = key;+ let result = await submit(modelKey);if (result.status === 401 && recoverKey) {await result.body?.cancel();const recovery = recoverKey(account, key);@@ -95,29 +162,38 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetcoptions.signal?.throwIfAborted();throw error instanceof GatewayError && [401, 403].includes(error.status) ? error : new GatewayError('model_auth_required', 401);}- if (updated && updated !== key) result = await submit(updated);+ if (updated && updated !== key) { modelKey = updated; result = await submit(modelKey); }}if (!result.ok) {- let limitExceeded = false;- if (result.status === 403) {- try {- const payload = await abortable(result.json() as Promise<{ error?: { message?: unknown } }>, options.signal!);- limitExceeded = typeof payload.error?.message === 'string' && /^Key limit exceeded\b/i.test(payload.error.message);- } catch {}- } else void result.body?.cancel().catch(() => undefined);- throw new GatewayError(result.status === 401 ? 'model_auth_required' : result.status === 402 || limitExceeded ? 'credits_insufficient' : 'official_service_unavailable', result.status >= 400 && result.status < 500 ? result.status : 503);+ const facts = await errorFacts(result, modelKey, options.signal ?? undefined);+ const limitExceeded = result.status === 403 && /^Key limit exceeded\b/i.test(facts.upstreamMessage ?? '');+ throw new DirectUpstreamError(result.status === 401 ? 'model_auth_required' : result.status === 402 || limitExceeded ? 'credits_insufficient' : 'official_service_unavailable', result.status >= 400 && result.status < 500 ? result.status : 503, facts);}return result;}return {isBusy() { return workers.size > 0; },+ async replay(account: string, identity: string, fingerprint: string): Promise<Response | undefined> {+ const id = directRequestId(account, identity);+ const saved = await read(id);+ if (!saved) return undefined;+ if (saved.account !== account || saved.fingerprint !== fingerprint) throw new GatewayError('operation_conflict', 409);+ if (saved.state === 'succeeded' && !saved.remoteId) return response(id, saved);+ if (saved.remoteId) return Response.json({ requestId: id, state: saved.state }, { status: 202, headers: { 'X-Request-ID': id } });+ if (saved.state === 'failed') return undefined;+ if (pending.has(id)) return accepted(id);+ throw new GatewayError('request_outcome_unknown', 409);+ },async close() {const work = [...workers.keys()].map(id => pending.get(id));for (const controller of workers.values()) controller.abort();await Promise.allSettled(work);},- async request(input: { account: string; key: string; resource: string; method: string; body: unknown; contentType: string; identity: string; fingerprint: string; signal: AbortSignal; model?: GatewayModel; asyncImage?: boolean }): Promise<Response> {+ async request(input: { account: string; key: string; resource: string; method: string; body: unknown; contentType: string; identity: string; fingerprint: string; signal: AbortSignal; model?: GatewayModel; asyncImage?: boolean; onModelFailure?: OfficialModelFailureReporter }): Promise<Response> {const { account, key, resource } = input;+ const notify = async (id: string | undefined, modality: GatewayModel['modality'], facts: PublicErrorFacts | undefined) => {+ if (id && facts) { try { await input.onModelFailure?.(id, modality, facts); } catch {} }+ };const asyncImage = input.asyncImage === true && /^images\/(generations|edits)$/.test(resource) && input.method === 'POST';const controller = asyncImage ? new AbortController() : undefined;const signal = controller ? AbortSignal.any([controller.signal, AbortSignal.timeout(DIRECT_IMAGE_TIMEOUT_MS)]) : input.signal;@@ -133,15 +209,18 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetcif (record.state !== 'succeeded') throw new GatewayError('request_outcome_unknown', 409);return call(`videos/${encodeURIComponent(record.remoteId)}/content?index=0`, { method: 'GET', signal }, key, account);}- const remote = await (await call(`videos/${encodeURIComponent(record.remoteId)}`, { method: 'GET', signal }, key, account)).json() as { status?: string };- record.state = remote.status === 'completed' ? 'succeeded' : ['failed', 'cancelled', 'expired'].includes(remote.status ?? '') ? 'failed' : 'waiting_upstream';+ let remote: unknown;+ try { remote = await (await call(`videos/${encodeURIComponent(record.remoteId)}`, { method: 'GET', signal }, key, account)).json(); }+ catch (error) { if (error instanceof DirectUpstreamError) await notify(record.model, 'video', error.facts); throw error; }+ recordVideoStatus(record, remote, key);await write(id, record);+ if (record.state === 'failed') await notify(record.model, 'video', record.upstreamError);}if (lookup[2]) { if (record.state !== 'succeeded') throw new GatewayError('request_outcome_unknown', 409); return response(id, record); }return Response.json({ requestId: id, state: record.state, ...(record.errorCode ? { error: { code: record.errorCode, status: record.errorStatus } } : {}) }, { headers: { 'X-Request-ID': id } });}if (input.method !== 'POST') throw new GatewayError('capability_unsupported', 404);- const id = 'ocdir_' + createHash('sha256').update(JSON.stringify([account, input.identity])).digest('hex').slice(0, 48);+ const id = directRequestId(account, input.identity);const existing = pending.get(id);if (existing) {if (fingerprints.get(id) !== input.fingerprint) throw new GatewayError('operation_conflict', 409);@@ -171,45 +250,67 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetc}if (resource === 'images/generations') endpoint = 'images';if (endpoint === 'images') {- const { response_format: _format, size, quality, aspect_ratio, resolution, ...fields } = body as Record<string, unknown>;+ const { response_format: _format, size, quality, aspect_ratio, resolution, output_format, stream, ...fields } = body as Record<string, unknown>;const options = input.model?.imageOptions;- const aspectRatio = aspect_ratio || pixelAspectRatio(size);+ const aspectRatio = aspect_ratio || (options && !options.aspectRatios?.length ? undefined : pixelAspectRatio(size));const valid = (value: unknown, allowed?: string[]) => value === undefined || value === '' || (typeof value === 'string' && !!allowed?.includes(value));- if (options && (!valid(aspect_ratio, options.aspectRatios) || !valid(resolution, options.resolutions) || !valid(quality, options.qualities)- || (Number(fields.n ?? 1) > options.maxImages) || (Array.isArray(fields.input_references) && fields.input_references.length > options.maxReferences))) throw new GatewayError('capability_unsupported', 400);- const selectedRatio = options?.aspectRatios?.length && !options.aspectRatios.includes(String(aspectRatio)) ? options.aspectRatios[0] : aspectRatio;- const outputFormat = ['png', 'jpeg', 'webp'].find(format => !options?.outputFormats?.length || options.outputFormats.includes(format));- if (!outputFormat) throw new GatewayError('capability_unsupported', 400);- body = { ...fields, ...(selectedRatio ? { aspect_ratio: selectedRatio } : {}), ...(resolution ? { resolution } : {}), ...(quality ? { quality } : {}), output_format: outputFormat };+ const count = fields.n ?? 1;+ if (typeof count !== 'number' || !Number.isInteger(count) || count < 1 || count > 10+ || (stream !== undefined && stream !== false)+ || typeof fields.model !== 'string' || !fields.model || typeof fields.prompt !== 'string' || !fields.prompt.trim()+ || (fields.input_references !== undefined && (!Array.isArray(fields.input_references) || fields.input_references.length > 16+ || fields.input_references.some(ref => !ref || ref.type !== 'image_url' || typeof ref.image_url?.url !== 'string' || !ref.image_url.url)))) throw new GatewayError('capability_unsupported', 400);+ if (options && (!valid(aspectRatio, options.aspectRatios) || !valid(resolution, options.resolutions) || !valid(quality, options.qualities) || !valid(output_format, options.outputFormats)+ || count > options.maxImages || (Array.isArray(fields.input_references) && fields.input_references.length > options.maxReferences))) throw new GatewayError('capability_unsupported', 400);+ if (input.model && Array.isArray(fields.input_references) && fields.input_references.length && !input.model.capabilities.includes('edit')) throw new GatewayError('capability_unsupported', 400);+ if (resource === 'images/edits' && (!Array.isArray(fields.input_references) || !fields.input_references.length)) throw new GatewayError('capability_unsupported', 400);+ const outputFormat = output_format || ['png', 'jpeg', 'webp'].find(format => options?.outputFormats?.includes(format));+ body = { ...fields, stream: false, ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}), ...(resolution ? { resolution } : {}), ...(quality ? { quality } : {}), ...(outputFormat ? { output_format: outputFormat } : {}) };}if (resource === 'audio/speech') {const { voice, ...fields } = body as Record<string, unknown>;+ const format = input.model?.capabilities.includes('pcm_speech') ? 'pcm' : 'mp3';+ if (input.model?.verification && (typeof fields.input !== 'string' || !fields.input.trim()+ || (fields.speed !== undefined && fields.speed !== 1) || fields.instructions !== undefined+ || (!input.model.capabilities.includes('default_voice') && (typeof voice !== 'string' || !input.model.voices?.includes(voice))))) throw new GatewayError('capability_unsupported', 400);if (input.model?.capabilities.includes('default_voice')) {if (voice && voice !== gatewayDefaultVoiceId) throw new GatewayError('capability_unsupported', 400);- body = { ...fields, response_format: 'mp3' };- } else body = { ...fields, voice, response_format: 'mp3' };+ body = { ...fields, response_format: format };+ } else body = { ...fields, voice, response_format: format };}if (resource === 'video/jobs' || resource === 'videos/tasks') {const value = body as { model: string; prompt: string; duration?: number; size?: string; image?: string };const sizeParams = input.model ? gatewayVideoSizeParameters(input.model, value.size ?? '') : value.size ? { size: value.size } : {};- if (!sizeParams || (input.model?.durations && !input.model.durations.includes(value.duration!))) throw new GatewayError('capability_unsupported', 400);+ if (!sizeParams || typeof value.model !== 'string' || !value.model || typeof value.prompt !== 'string' || !value.prompt.trim()+ || (value.duration !== undefined && (!Number.isInteger(value.duration) || value.duration < 1))+ || (input.model?.durations && !input.model.durations.includes(value.duration!))) throw new GatewayError('capability_unsupported', 400);+ if (value.image !== undefined && (typeof value.image !== 'string' || !value.image)) throw new GatewayError('capability_unsupported', 400);+ if (value.image && input.model && !input.model.capabilities.includes('image_to_video')) throw new GatewayError('capability_unsupported', 400);body = { model: value.model, prompt: value.prompt, duration: value.duration, ...sizeParams, ...(value.image ? { frame_images: [{ type: 'image_url', image_url: { url: value.image }, frame_type: 'first_frame' }] } : {}) };endpoint = 'videos';}- const record: Receipt = { account, fingerprint: input.fingerprint, state: asyncImage ? 'waiting_upstream' : 'submitting' };+ const record: Receipt = { account, fingerprint: input.fingerprint, state: asyncImage ? 'waiting_upstream' : 'submitting', operation: resource, model: input.model?.id ?? (body && typeof body === 'object' && 'model' in body && typeof body.model === 'string' ? body.model : undefined), createdAt: new Date().toISOString() };await write(id, record);registered();try {const remote = await call(endpoint, { method: 'POST', signal, headers: { 'Content-Type': contentType }, body: Buffer.isBuffer(body) ? new Uint8Array(body) : JSON.stringify(body) }, key, account);+ record.upstreamRequestId = safePublicRequestId(remote.headers.get('x-request-id') ?? undefined);+ recordUpstreamMetadata(record, { generation_id: remote.headers.get('x-generation-id') });+ record.status = remote.status;+ await write(id, record);if (endpoint === 'videos') {const value = await remote.json() as { id?: string };if (!value.id || !/^[A-Za-z0-9_-]{1,200}$/.test(value.id)) throw new GatewayError('invalid_gateway_response');- record.remoteId = value.id; record.state = 'waiting_upstream'; await write(id, record);+ // Keep the remote ID even if the submit response needs reconciliation.+ record.remoteId = value.id;+ recordVideoStatus(record, value, key);+ await write(id, record);+ if (record.state === 'failed') await notify(record.model, 'video', record.upstreamError);return Response.json({ requestId: id, state: record.state }, { status: 202, headers: { 'X-Request-ID': id } });}record.status = remote.status; record.mime = remote.headers.get('content-type') ?? 'application/json';await write(id, record);- const reader = (record.mime.includes('text/event-stream') && remote.body ? officialEventStream(remote.body) : remote.body)?.getReader(); if (!reader) throw new GatewayError('invalid_gateway_response');+ const reader = (record.mime.includes('text/event-stream') && remote.body ? officialEventStream(remote.body, error => notify(record.model, 'text', creatorServiceFailureFacts(error))) : remote.body)?.getReader(); if (!reader) throw new GatewayError('invalid_gateway_response');const chunks: Uint8Array[] = []; let size = 0;if (!record.mime.includes('text/event-stream')) {try {@@ -220,9 +321,33 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetc// Buffered image JSON can be complete before the upstream closes its HTTP stream.if (endpoint === 'images' && Buffer.from(item.value).toString('utf8').trimEnd().endsWith('}') && completeImageResponse(Buffer.concat(chunks))) break;}- } finally { void reader.cancel().catch(() => undefined); }- if (endpoint === 'images' && !completeImageResponse(Buffer.concat(chunks))) throw new GatewayError('invalid_gateway_response');- record.content = Buffer.concat(chunks).toString('base64'); record.state = 'succeeded'; await write(id, record);+ } catch (error) {+ if (endpoint === 'images') record.content = Buffer.from(Buffer.concat(chunks).toString('utf8').replaceAll(key, '[redacted]')).toString('base64');+ throw error;+ } finally { record.receivedBytes = size; void reader.cancel().catch(() => undefined); }+ let content: Buffer = Buffer.concat(chunks);+ if (endpoint === 'audio/speech' && /^audio\/pcm(?:;|$)/i.test(record.mime)) {+ content = pcmWave(content, record.mime); record.mime = 'audio/wav';+ }+ record.content = content.toString('base64');+ if (endpoint === 'audio/transcriptions') {+ try { recordUpstreamMetadata(record, JSON.parse(content.toString('utf8'))); } catch {}+ if (input.model?.capabilities.includes('subtitle_timestamps')) {+ const value = JSON.parse(content.toString('utf8')) as { text?: unknown; words?: Array<{ word?: unknown; start?: unknown; end?: unknown }>; segments?: Array<{ text?: unknown; start?: unknown; end?: unknown }> };+ const timings = [...(Array.isArray(value.words) ? value.words.map(word => ({ ...word, text: word.word })) : []), ...(Array.isArray(value.segments) ? value.segments : [])];+ if (typeof value.text !== 'string' || !value.text.trim() || !timings.some(item => typeof item?.text === 'string' && item.text.trim()+ && typeof item.start === 'number' && Number.isFinite(item.start) && item.start >= 0 && typeof item.end === 'number' && Number.isFinite(item.end) && item.end > item.start)) throw new GatewayError('invalid_gateway_response');+ }+ }+ if (endpoint === 'images') {+ try { recordUpstreamMetadata(record, JSON.parse(content.toString('utf8'))); } catch {}+ if (!completeImageResponse(content)) {+ record.content = Buffer.from(content.toString('utf8').replaceAll(key, '[redacted]')).toString('base64');+ record.upstreamError = { kind: 'invalid-response', httpStatus: remote.status, upstreamCode: 'invalid_image_response' };+ throw new GatewayError('invalid_gateway_response');+ }+ }+ record.state = 'succeeded'; await write(id, record);return response(id, record);}let settlement = Promise.resolve();@@ -270,7 +395,11 @@ export function createDirectTransport(root: string, fetcher: typeof fetch = fetc} catch (error) {record.state = error instanceof GatewayError && [400, 401, 402, 403, 404, 422, 429].includes(error.status) ? 'failed' : 'outcome_unknown';if (error instanceof GatewayError) { record.errorCode = error.code; record.errorStatus = error.status; }- await write(id, record); throw error;+ if (error instanceof DirectUpstreamError) { record.upstreamError = error.facts; record.upstreamRequestId ??= error.facts.requestId; }+ else record.upstreamError ??= publicFactsFromFailure(error, undefined, { timedOut: signal.aborted && signal.reason instanceof DOMException && signal.reason.name === 'TimeoutError' });+ await write(id, record);+ if (error instanceof DirectUpstreamError) await notify(record.model, input.model?.modality ?? 'text', error.facts);+ throw error;}})();pending.set(id, work);diff --git a/apps/daemon/src/gateway/model-access.ts b/apps/daemon/src/gateway/model-access.tsindex 3208a9bc..52430914 100644--- a/apps/daemon/src/gateway/model-access.ts+++ b/apps/daemon/src/gateway/model-access.ts@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';import { isIP } from 'node:net';import { join } from 'node:path';import { z } from 'zod';-import type { GatewayModel } from '@opencreator/protocol';+import type { GatewayModel, PublicErrorFacts } from '@opencreator/protocol';import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';import { probeCredentialsSchema, type GatewayBootstrap, type GatewayProbeCredentials } from './client.js';@@ -10,12 +10,18 @@ const allowedTTL = 24 * 60 * 60_000;const blockedTTL = 60 * 60_000;const retryTTL = 5 * 60_000;const entrySchema = z.object({- status: z.enum(['allowed', 'blocked', 'unknown']),- nextCheck: z.number(), representative: z.string(), alternate: z.boolean().optional()+ status: z.enum(['allowed', 'blocked', 'unknown']), profile: z.string(),+ nextCheck: z.number(), validUntil: z.number()+});+const cacheSchema = z.object({+ version: z.literal(2), base: z.string(), network: z.string(), country: z.string(),+ models: z.record(entrySchema), catalogIDs: z.array(z.string()), catalogExpiresAt: z.number()});-const cacheSchema = z.object({ version: z.literal(1), base: z.string(), network: z.string(), groups: z.record(entrySchema) });type AccessCache = z.infer<typeof cacheSchema>;const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');+const modelKey = (model: Pick<GatewayModel, 'id' | 'modality'>) => `${model.modality}:${model.id}`;+const profileKey = ({ name: _name, ...model }: GatewayModel) => digest(model);+const emptyCache = (base = ''): AccessCache => ({ version: 2, base, network: '', country: '', models: {}, catalogIDs: [], catalogExpiresAt: 0 });export function modelAccessGroup(model: GatewayModel): string | undefined {const [vendor, slug] = model.id.replace(/^~/, '').split('/');@@ -40,61 +46,109 @@ export function withModelCatalog(bootstrap: GatewayBootstrap, models: GatewayModreturn { ...bootstrap, models, defaults };}-const preferred: Record<string, string[]> = {- openai: ['openai/gpt-4.1-mini', 'openai/gpt-6-sol', 'openai/gpt-4o-mini'],- 'google-gemini': ['google/gemini-2.5-flash-lite', 'google/gemini-2.5-flash'],- deepseek: ['deepseek/deepseek-v3.2', 'deepseek/deepseek-chat'],- qwen: ['qwen/qwen3-coder', 'qwen/qwen3-max'],- 'openai-oss': ['openai/gpt-oss-20b', 'openai/gpt-oss-120b'],- 'google-gemma': ['google/gemma-3-12b-it', 'google/gemma-3-27b-it']-};+// Only model access failures affect admission. Quota, content policy and outages do not.+export function isModelAccessFailure(facts: PublicErrorFacts): boolean {+ const status = facts.httpStatus ?? Number(facts.upstreamCode);+ const message = facts.upstreamMessage ?? '';+ if (/key limit|balance|credits|quota|rate limit|moderation|content policy|safety filter/i.test(message)) return false;+ const regionOrTerms = /provider terms of service|(?:country|region|location).{0,80}(?:not supported|restricted|not allowed|unavailable|prohibited)|(?:not available|unavailable|unsupported|restricted).{0,80}(?:country|region|location)/i.test(message);+ if (facts.kind === 'provider-failed' && !Number.isFinite(status) && regionOrTerms) return true;+ if (![400, 403, 404].includes(status)) return false;+ return regionOrTerms || /no (?:available )?endpoints found|(?:model|provider).{0,80}(?:permission denied|not allowed|not found|not available|unavailable)|(?:permission denied|not allowed).{0,80}(?:model|provider)|does not support response_format/i.test(message);+}export function createOfficialModelAccess(input: {dataDir: string; fetcher: typeof fetch; readProxy(): Promise<string>;readProbeCredentials(): Promise<GatewayProbeCredentials>;}) {const path = join(input.dataDir, 'config', 'gateway-model-access.json');- let cache: AccessCache = { version: 1, base: '', network: '', groups: {} };+ let cache = emptyCache();let loaded: Promise<void> | undefined;let saving = Promise.resolve();- let networkCheckedAt = 0;- async function prepare(bootstrap: GatewayBootstrap) {+ let metadataWork: Promise<void> | undefined;+ let metadataCheckedAt = 0;+ let identityValid = false;+ const context = () => identityValid && cache.network ? digest([cache.base, cache.network]) : '';+ function save() {+ const snapshot = structuredClone(cache);+ saving = saving.catch(() => undefined).then(() => writePrivateJsonFile(path, snapshot));+ return saving;+ }+ async function prepare(bootstrap: GatewayBootstrap, signal?: AbortSignal) {loaded ??= (async () => {try {const parsed = cacheSchema.safeParse(await readPrivateJsonFile(path));if (parsed.success) cache = parsed.data;- } catch { /* A broken availability cache must not prevent sign-in. */ }+ } catch { /* A broken cache must not prevent sign-in. */ }})();await loaded;+ if (signal?.aborted) return filter(bootstrap);const base = digest([bootstrap.account.id, bootstrap.keyVersion, await input.readProxy()]);- if (cache.base !== base) {- cache = { version: 1, base, network: '', groups: {} };- networkCheckedAt = 0;+ if (cache.base !== base) { cache = emptyCache(base); identityValid = false; metadataCheckedAt = 0; }+ if (metadataWork) await metadataWork;+ if (Date.now() - metadataCheckedAt >= 60_000 || metadataCheckedAt === 0) {+ metadataCheckedAt = Date.now();+ const expectedBase = cache.base;+ const work = (async () => {+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000);+ identityValid = false;+ try {+ const response = await input.fetcher('https://openrouter.ai/cdn-cgi/trace', { redirect: 'error', signal: requestSignal });+ const fields = new URLSearchParams((await response.text()).replace(/\r?\n/g, '&'));+ const ip = fields.get('ip') ?? ''; const country = fields.get('loc') ?? '';+ if (!response.ok || !isIP(ip) || !/^[A-Z]{2}$/.test(country)) throw new Error('Unknown network');+ if (cache.base !== expectedBase || signal?.aborted) return;+ const network = digest([ip, country]);+ if (cache.network !== network) cache = { ...emptyCache(expectedBase), network, country };+ identityValid = true;+ cache.catalogExpiresAt = 0;+ const ids: string[] = [];+ let offset = 0;+ for (let page = 0; page < 10; page++) {+ const response = await input.fetcher(`https://openrouter.ai/api/v1/models/user?output_modalities=all&limit=1000&offset=${offset}`, {+ redirect: 'error', signal: requestSignal, headers: { Authorization: `Bearer ${bootstrap.modelKey}` }+ });+ if (!response.ok) throw new Error('Unknown account catalog');+ const value = z.object({ data: z.array(z.object({ id: z.string().min(1) })), links: z.object({ next: z.string().nullable().optional() }).optional() }).parse(await response.json());+ ids.push(...value.data.map(model => model.id));+ if (!value.links?.next) break;+ const next = new URL(value.links.next, 'https://openrouter.ai');+ const nextOffset = Number(next.searchParams.get('offset'));+ if (next.origin !== 'https://openrouter.ai' || next.pathname !== '/api/v1/models/user' || !Number.isInteger(nextOffset) || nextOffset <= offset || page === 9 || !value.data.length) throw new Error('Invalid account catalog pagination');+ offset = nextOffset;+ }+ if (cache.base !== expectedBase || signal?.aborted) return;+ cache.catalogIDs = ids; cache.catalogExpiresAt = Date.now() + retryTTL;+ await save();+ } catch {+ if (cache.base === expectedBase && !signal?.aborted) await save();+ }+ })();+ metadataWork = work;+ try { await work; } finally { if (metadataWork === work) metadataWork = undefined; }}return filter(bootstrap);}function filter(bootstrap: GatewayBootstrap) {- const eligible = officialModelPolicy(bootstrap.models);- const status = (model: GatewayModel) => cache.groups[modelAccessGroup(model) ?? '']?.status;- const text = eligible.filter(model => model.modality === 'text' && model.capabilities.includes('responses'));- const selected = text.find(model => model.id === bootstrap.defaults.text);- const fallback = (selected && status(selected) !== 'blocked' ? selected : undefined)- ?? text.find(model => status(model) === 'allowed')- ?? text.find(model => status(model) !== 'blocked');- const fallbackGroup = fallback && modelAccessGroup(fallback);- return withModelCatalog(bootstrap, eligible.filter(model => {- const group = modelAccessGroup(model);- if (group === undefined) return true;- if (cache.groups[group]?.status === 'blocked') return false;- return model.modality !== 'text' || cache.groups[group]?.status === 'allowed' || group === fallbackGroup;+ const ids = new Set(cache.catalogExpiresAt > Date.now() ? cache.catalogIDs : []);+ return withModelCatalog(bootstrap, officialModelPolicy(bootstrap.models).filter(model => {+ if (!identityValid || !ids.has(model.id)) return false;+ const entry = cache.models[modelKey(model)];+ const current = entry?.profile === profileKey(model) ? entry : undefined;+ if (current?.status === 'blocked') return false;+ if (model.modality === 'text') return model.capabilities.includes('responses') && current?.status === 'allowed' && current.validUntil > Date.now();+ const verified = model.verification;+ return verified?.adapterVersion === 2 && verified.countries.includes(cache.country)+ && (model.modality !== 'transcription' || model.capabilities.includes('subtitle_timestamps'));}));}- function save() {- const snapshot = structuredClone(cache);- saving = saving.catch(() => undefined).then(() => writePrivateJsonFile(path, snapshot));- return saving;+ async function recordFailure(expectedContext: string, model: GatewayModel, facts: PublicErrorFacts) {+ if (!expectedContext || expectedContext !== context() || !isModelAccessFailure(facts)) return false;+ cache.models[modelKey(model)] = { status: 'blocked', profile: profileKey(model), nextCheck: Date.now() + blockedTTL, validUntil: 0 };+ await save();+ return true;}- async function check(model: GatewayModel, key: string, signal: AbortSignal): Promise<{ status: 'allowed' | 'blocked' | 'unknown'; alternate?: boolean }> {+ async function check(model: GatewayModel, key: string, signal: AbortSignal): Promise<'allowed' | 'blocked' | 'unknown'> {try {const response = await input.fetcher('https://openrouter.ai/api/v1/responses', {method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(8000)]),@@ -105,70 +159,49 @@ export function createOfficialModelAccess(input: {});const value = await response.json() as { status?: string; error?: { message?: unknown }; output?: Array<{ type?: string; name?: string; arguments?: string }> };const message = typeof value.error?.message === 'string' ? value.error.message : '';- if (response.status === 403 && /provider terms of service|(?:country|region|location).{0,80}(?:not supported|restricted|not allowed|unavailable|prohibited)|(?:not available|unavailable|unsupported|restricted).{0,80}(?:country|region|location)/i.test(message)) return { status: 'blocked' };- if (!response.ok) return { status: 'unknown', alternate: response.status === 400 || response.status === 404 };+ if (isModelAccessFailure({ kind: 'http-rejected', httpStatus: response.status, upstreamMessage: message })) return 'blocked';+ if (!response.ok) return 'unknown';const call = value.output?.find(item => item.type === 'function_call' && item.name === 'oc_access_check');- return value.status === 'completed' && call && JSON.parse(call.arguments ?? '{}').ready === true ? { status: 'allowed' } : { status: 'unknown', alternate: true };- } catch { return { status: 'unknown' }; }+ return value.status === 'completed' && call && JSON.parse(call.arguments ?? '{}').ready === true ? 'allowed' : 'unknown';+ } catch { return 'unknown'; }}async function refresh(bootstrap: GatewayBootstrap, signal: AbortSignal, onChange: () => Promise<void>) {- await prepare(bootstrap);+ await prepare(bootstrap, signal);if (signal.aborted) return;- if (Date.now() - networkCheckedAt > 60_000) {- networkCheckedAt = Date.now();- try {- const response = await input.fetcher('https://openrouter.ai/cdn-cgi/trace', { redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(4000)]) });- const fields = new URLSearchParams((await response.text()).replace(/\r?\n/g, '&'));- const ip = fields.get('ip') ?? ''; const country = fields.get('loc') ?? '';- if (response.ok && isIP(ip) && /^[A-Z]{2}$/.test(country)) {- const network = digest([ip, country]);- if (cache.network !== network) {- cache = { ...cache, network, groups: {} };- await save(); await onChange();- }- }- } catch { /* Keep prior results when the network identity endpoint is unavailable. */ }- }- const groups = new Map<string, GatewayModel[]>();- for (const model of officialModelPolicy(bootstrap.models)) {- const group = modelAccessGroup(model);- if (model.modality !== 'text' || !model.capabilities.includes('responses') || !group) continue;- groups.set(group, [...(groups.get(group) ?? []), model]);- }+ await onChange();+ if (!context() || cache.catalogExpiresAt <= Date.now()) return;+ const ids = new Set(cache.catalogIDs);const priority = ['openai', 'google-gemini', 'deepseek', 'qwen', 'openai-oss', 'google-gemma'];- const pending = [...groups].filter(([group]) => (cache.groups[group]?.nextCheck ?? 0) <= Date.now())- .sort(([a], [b]) => {- const rank = (group: string) => priority.includes(group) ? priority.indexOf(group) : priority.length;- return rank(a) - rank(b);- }).slice(0, 12);- const expectedBase = cache.base;+ const rank = (model: GatewayModel) => {+ if (model.id === bootstrap.defaults.text) return -1;+ const index = priority.indexOf(modelAccessGroup(model) ?? '');+ return index < 0 ? priority.length : index;+ };+ const pending = officialModelPolicy(bootstrap.models).filter(model => {+ const entry = cache.models[modelKey(model)];+ return model.modality === 'text' && model.capabilities.includes('responses') && ids.has(model.id)+ && (entry?.profile !== profileKey(model) || entry.nextCheck <= Date.now());+ }).sort((a, b) => rank(a) - rank(b)).slice(0, 12);+ const expectedContext = context();if (!pending.length || signal.aborted) return;const credentials = probeCredentialsSchema.parse(await input.readProbeCredentials());- if (credentials.costBearer !== 'platform' || credentials.modelKey === bootstrap.modelKey- || Date.parse(credentials.expiresAt) <= Date.now() || signal.aborted || cache.base !== expectedBase) return;+ if (credentials.modelKey === bootstrap.modelKey || Date.parse(credentials.expiresAt) <= Date.now() || signal.aborted || context() !== expectedContext) return;const deadline = Date.now() + 20_000;async function worker() {- while (pending.length && !signal.aborted && Date.now() < deadline && cache.base === expectedBase) {- const [group, models] = pending.shift()!;- const previous = cache.groups[group];- const choices = [...models].sort((a, b) => {- const rank = (id: string) => { const index = preferred[group]?.indexOf(id) ?? -1; return index < 0 ? 100 : index; };- return rank(a.id) - rank(b.id);- });- const representative = (previous?.alternate ? choices.find(model => model.id !== previous.representative) : undefined) ?? choices[0]!;- const result = await check(representative, credentials.modelKey, signal);- if (signal.aborted || cache.base !== expectedBase) return;- cache.groups[group] = {- status: result.status === 'unknown' ? previous?.status ?? 'unknown' : result.status,- representative: representative.id, alternate: result.alternate,- nextCheck: Date.now() + (result.status === 'allowed' ? allowedTTL : result.status === 'blocked' ? blockedTTL : retryTTL)- };+ while (pending.length && !signal.aborted && Date.now() < deadline && context() === expectedContext) {+ const model = pending.shift()!;+ const key = modelKey(model); const previous = cache.models[key];+ const result = await check(model, credentials.modelKey, signal);+ if (signal.aborted || context() !== expectedContext || cache.models[key] !== previous) continue;+ cache.models[key] = { status: result, profile: profileKey(model),+ validUntil: result === 'allowed' ? Date.now() + allowedTTL : 0,+ nextCheck: Date.now() + (result === 'allowed' ? allowedTTL : result === 'blocked' ? blockedTTL : retryTTL) };await save(); await onChange();}}await Promise.all([worker(), worker()]);}- return { prepare, filter, refresh };+ return { prepare, filter, refresh, context, recordFailure };}export type OfficialModelAccess = ReturnType<typeof createOfficialModelAccess>;diff --git a/apps/daemon/src/gateway/official-stream.ts b/apps/daemon/src/gateway/official-stream.tsindex 838925be..5475263b 100644--- a/apps/daemon/src/gateway/official-stream.ts+++ b/apps/daemon/src/gateway/official-stream.ts@@ -1,26 +1,31 @@// Preserve model output while replacing upstream operational errors with product-facing text.-export function officialEventStream(stream: ReadableStream<Uint8Array>) {+export function officialEventStream(stream: ReadableStream<Uint8Array>, onError?: (error: unknown) => void | Promise<void>) {const decoder = new TextDecoder(); const encoder = new TextEncoder(); let buffered = '';- function sanitize(frame: string) {- return frame.split('\n').map(line => {- if (!line.startsWith('data:')) return line;+ async function sanitize(frame: string) {+ const lines: string[] = [];+ for (let line of frame.split('\n')) {+ if (!line.startsWith('data:')) { lines.push(line); continue; }try {const value = JSON.parse(line.slice(5)) as { type?: string; message?: string; error?: unknown; response?: { error?: unknown; status?: string } };- if (value.type === 'error') return `data: ${JSON.stringify({ type: 'error', error: { code: 'official_service_unavailable', message: '官方模型服务暂不可用' } })}`;- if (value.error) value.error = { code: 'official_service_unavailable', message: '官方模型服务暂不可用' };- if (value.response?.error) value.response.error = { code: 'official_service_unavailable', message: '官方模型服务暂不可用' };- return `data: ${JSON.stringify(value)}`;- } catch { return line; }- }).join('\n');+ const error = value.error ?? value.response?.error ?? (value.type === 'error' ? value : undefined);+ if (error) { try { await onError?.(error); } catch {} }+ if (value.type === 'error') { lines.push(`data: ${JSON.stringify({ type: 'error', error: { code: 'official_service_unavailable', message: 'The official model service is unavailable' } })}`); continue; }+ if (value.error) value.error = { code: 'official_service_unavailable', message: 'The official model service is unavailable' };+ if (value.response?.error) value.response.error = { code: 'official_service_unavailable', message: 'The official model service is unavailable' };+ line = `data: ${JSON.stringify(value)}`;+ } catch {}+ lines.push(line);+ }+ return lines.join('\n');}return stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({- transform(chunk, controller) {+ async transform(chunk, controller) {buffered += decoder.decode(chunk, { stream: true });buffered = buffered.replace(/\r\n/g, '\n');let boundary: number;- while ((boundary = buffered.indexOf('\n\n')) >= 0) { controller.enqueue(encoder.encode(sanitize(buffered.slice(0, boundary)) + '\n\n')); buffered = buffered.slice(boundary + 2); }+ while ((boundary = buffered.indexOf('\n\n')) >= 0) { controller.enqueue(encoder.encode(await sanitize(buffered.slice(0, boundary)) + '\n\n')); buffered = buffered.slice(boundary + 2); }if (buffered.length > 1024 * 1024) throw new Error('Official event exceeds the supported size');},- flush(controller) { buffered += decoder.decode(); if (buffered) controller.enqueue(encoder.encode(sanitize(buffered))); }+ async flush(controller) { buffered += decoder.decode(); if (buffered) controller.enqueue(encoder.encode(await sanitize(buffered))); }}));}diff --git a/apps/daemon/src/gateway/runtime-bindings.ts b/apps/daemon/src/gateway/runtime-bindings.tsindex 539f2da1..b1365ad6 100644--- a/apps/daemon/src/gateway/runtime-bindings.ts+++ b/apps/daemon/src/gateway/runtime-bindings.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { chmodSync, existsSync, lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { isAbsolute, join } from 'node:path';-import { createDirectRuntime } from './direct-runtime.js';+import { createDirectRuntime, type DirectRuntimeUse } from './direct-runtime.js';import { createOfficialFetch } from './official-fetch.js';export type GatewayRuntimeBindingsInput = {@@ -13,7 +13,7 @@ export type GatewayRuntimeBindingsInput = {parentEnvironment?: NodeJS.ProcessEnv;direct?: boolean;readProxy?(): Promise<string>;- beginUse?(): Promise<{ key: string; keyVersion?: string; release(): Promise<void> }>;+ beginUse?(): Promise<DirectRuntimeUse>;recoverKey?(keyVersion: string): Promise<{ key: string; keyVersion: string }>;};diff --git a/apps/daemon/src/image-generation/codex-native.ts b/apps/daemon/src/image-generation/codex-native.tsindex 7f8ff71b..9e2148b2 100644--- a/apps/daemon/src/image-generation/codex-native.ts+++ b/apps/daemon/src/image-generation/codex-native.ts@@ -32,7 +32,7 @@ export async function generateCodexNativeImage(input: {onProgress?(progress: NativeImageProgress): void;}): Promise<GeneratedImageContent> {input.signal.throwIfAborted();- if (!input.runtime.codexBin) throw new CodexNativeImageError('当前 Runtime 缺少 Codex 可执行程序', 'configuration');+ if (!input.runtime.codexBin) throw new CodexNativeImageError('The Codex executable is missing from this Runtime', 'configuration');const workdir = await mkdtemp(join(tmpdir(), 'opencreator-codex-image-'));const outputDir = join(workdir, 'output');let process: CodexExecProcess | undefined;@@ -50,13 +50,13 @@ export async function generateCodexNativeImage(input: {await mkdir(outputDir, { mode: 0o700 });const imagePaths: string[] = [];for (const [index, image] of input.referenceImages.entries()) {- if (!image.content.length || image.content.length > MAX_IMAGE_BYTES) throw new Error('参考图片超过大小限制或内容为空');+ if (!image.content.length || image.content.length > MAX_IMAGE_BYTES) throw new Error('The reference image is empty or exceeds the size limit');const path = join(workdir, `reference-${index}.${image.mime === 'image/jpeg' ? 'jpg' : image.mime === 'image/webp' ? 'webp' : 'png'}`);await writeFile(path, image.content, { mode: 0o600 });imagePaths.push(path);}input.signal.throwIfAborted();- report('preparing_native_image', '正在准备 ChatGPT 登录态生图;将使用 Codex 原生工具,不会调用图片 API Key 接口。');+ report('preparing_native_image', 'Preparing image generation with ChatGPT sign-in and the native Codex tool.');const startedAt = Date.now();process = (input.runtime.startExec ?? startCodexExec)({codexBin: input.runtime.codexBin,@@ -80,7 +80,7 @@ export async function generateCodexNativeImage(input: {try { event = JSON.parse(line); } catch { return; }if (!isRecord(event)) return;if (event.type === 'thread.started' && typeof event.thread_id === 'string') threadId = event.thread_id;- if (event.type === 'turn.started') report('generating_image', '正在通过 ChatGPT 登录态生成图片,请稍候。');+ if (event.type === 'turn.started') report('generating_image', 'Generating images with ChatGPT sign-in. Please wait.');if (event.type === 'turn.failed' || event.type === 'error') {const error = isRecord(event.error) ? event.error : event;if (typeof error.message === 'string') streamError = nativeFailure(error.message);@@ -91,13 +91,13 @@ export async function generateCodexNativeImage(input: {lastAgentMessage = item.text.slice(0, 4_000);}if (item && (item.type === 'image_generation' || item.type === 'imageGeneration')) {- report('generating_image', 'Codex 原生生图工具正在处理图片,请稍候。');+ report('generating_image', 'The native Codex image tool is processing the image. Please wait.');const path = item.saved_path ?? item.savedPath;if (typeof path === 'string') savedPath = path;if (item.status === 'failed' || item.failure) {const error = isRecord(item.failure) ? item.failure : item;failure = nativeFailure(typeof error.message === 'string' ? error.message- : typeof error.type === 'string' ? error.type : 'Codex 原生生图工具执行失败');+ : typeof error.type === 'string' ? error.type : 'The native Codex image tool failed');} else if (item.status === 'completed') failure = undefined;}}@@ -108,17 +108,17 @@ export async function generateCodexNativeImage(input: {input.signal.throwIfAborted();if (error instanceof CodexExecError) {if (['timeout', 'inactivity_timeout', 'spawn_timeout'].includes(error.terminationReason)) {- throw new CodexNativeImageError('Codex 原生生图超时,请稍后重试', 'timeout');+ throw new CodexNativeImageError('Codex native image generation timed out. Try again later.', 'timeout');}throw nativeFailure(error.stderr || error.message);}- throw new CodexNativeImageError('无法启动或执行 Codex 原生生图,请检查 Runtime', 'unavailable');+ throw new CodexNativeImageError('Could not start or run Codex native image generation. Check the Runtime.', 'unavailable');});input.signal.throwIfAborted();if (result.terminationReason !== 'completed' || result.exitCode !== 0 || turnFailed || failure) {throw failure ?? streamError ?? nativeFailure(result.stderr || lastAgentMessage);}- report('collecting_outputs', 'Codex 执行已结束,正在检查是否生成有效图片并保存产物。');+ report('collecting_outputs', 'Codex finished. Checking generated images and saving outputs.');const roots = [await realpath(workdir)];const references = new Set(await Promise.all(imagePaths.map(path => realpath(path))));if (threadId && /^[A-Za-z0-9_-]+$/.test(threadId)) {@@ -131,20 +131,20 @@ export async function generateCodexNativeImage(input: {: [savedPath];const images: GeneratedImageContent[] = [];for (const candidate of candidates) {- if (!isAbsolute(candidate) || candidate.includes('\0')) throw new Error('Codex 返回的图片路径无效');+ if (!isAbsolute(candidate) || candidate.includes('\0')) throw new Error('Codex returned an invalid image path');const path = await realpath(candidate);if (references.has(path)) continue;- if (!roots.some(root => inside(root, path))) throw new Error('Codex 图片产物不属于当前生图任务,已拒绝读取');+ if (!roots.some(root => inside(root, path))) throw new Error('The Codex image output does not belong to this task. Reading it was denied.');const info = await stat(path);- if (!info.isFile() || info.size <= 0 || info.size > MAX_IMAGE_BYTES) throw new Error('Codex 图片产物大小无效');+ if (!info.isFile() || info.size <= 0 || info.size > MAX_IMAGE_BYTES) throw new Error('The Codex image output has an invalid size');if (info.mtimeMs < startedAt - 1000) {- if (savedPath !== undefined) throw new Error('Codex 返回了已有图片,未产生新的生图结果');+ if (savedPath !== undefined) throw new Error('Codex returned an existing image without generating a new output');continue;}const content = await readFile(path);- if (content.length > MAX_IMAGE_BYTES) throw new Error('Codex 图片产物超过大小限制');+ if (content.length > MAX_IMAGE_BYTES) throw new Error('The Codex image output exceeds the size limit');const mime = imageMime(content);- if (!mime) throw new Error('Codex 图片产物不是受支持的 PNG、JPEG 或 WebP 图片');+ if (!mime) throw new Error('The Codex image output is not a supported PNG, JPEG, or WebP image');images.push({ content, mime });}if (images.length !== 1) {@@ -152,9 +152,9 @@ export async function generateCodexNativeImage(input: {if (diagnostic.publicFacts.kind === 'provider-failed' && result.stderr) diagnostic = nativeFailure(result.stderr);// exec --json can omit image tool events and exit successfully after a tool refusal.if (images.length === 0 && diagnostic.publicFacts.kind !== 'provider-failed') throw diagnostic;- const message = `Codex 没有返回唯一的新图片产物(${images.length} 张),不能将文字回复视为生图成功`;+ const message = `Codex returned ${images.length} new images instead of exactly one. A text reply cannot be treated as a generated image.`;throw new CodexNativeImageError(message, 'invalid-response',- `${message}。${lastAgentMessage ? `Codex 最后回复:${lastAgentMessage}` : 'Codex 未返回图片或更具体的失败说明,请重试;持续失败时检查本机 Codex 登录、网络和原生生图能力。'}`,+ `${message} ${lastAgentMessage ? `Last Codex reply: ${lastAgentMessage}` : 'Codex returned no image or specific failure reason. Try again. If it keeps failing, check local Codex sign-in, the network, and native image capabilities.'}`,'IMAGE_OUTPUT_MISSING');}return images[0]!;@@ -162,7 +162,7 @@ export async function generateCodexNativeImage(input: {input.signal.throwIfAborted();if (error instanceof CodexNativeImageError) throw error;if (error instanceof Error) throw new CodexNativeImageError(- safePublicErrorMessage(error.message) ?? 'Codex 图片产物检查失败', 'invalid-response'+ safePublicErrorMessage(error.message) ?? 'Could not validate the Codex image output', 'invalid-response');throw error;} finally {@@ -173,33 +173,33 @@ export async function generateCodexNativeImage(input: {function nativeFailure(message: string): CodexNativeImageError {if (/requested the last \d+ conversation images, but only 0 were available|no (?:available |uploaded |attached |reference )*(?:images?|photos?|pictures?)|(?:没有|缺少|未上传|未提供|找不到|不可用)[^。\n]{0,30}(?:人物照片|参考图|上传[^。\n]{0,10}(?:图片|照片))|(?:参考图|人物照片)[^。\n]{0,15}(?:缺失|未上传|不可用)/i.test(message)) {- return new CodexNativeImageError('Codex 无法获取所需的参考图,请先上传图片后重试。', 'validation', message, 'IMAGE_REFERENCE_MISSING');+ return new CodexNativeImageError('Codex cannot access the required reference image. Upload it and try again.', 'validation', message, 'IMAGE_REFERENCE_MISSING');}if (/unauthorized|\b401\b|token.*expired|refresh.*token|not.*logged|authentication|login|sign.?in/i.test(message)) {- return new CodexNativeImageError('本机 Codex 的 ChatGPT 登录已失效或无法验证,请在本机 Codex 中重新登录后重试', 'unauthorized', message);+ return new CodexNativeImageError('Local Codex ChatGPT sign-in expired or could not be verified. Sign in again and retry.', 'unauthorized', message);}if (/usage.?limit|rate.?limit|quota|\b429\b|limit.?exceeded/i.test(message)) {- return new CodexNativeImageError('ChatGPT 生图额度或请求频率受限,请稍后重试', 'rate-limited', message);+ return new CodexNativeImageError('ChatGPT image quota or request rate is limited. Try again later.', 'rate-limited', message);}if (/unsupported|not.*support|not.*available|\b403\b|access.*denied/i.test(message)) {- return new CodexNativeImageError('当前 ChatGPT 账号或 Codex Runtime 无法使用原生生图,请检查账号权限或更新 Runtime', 'unsupported', message);+ return new CodexNativeImageError('This ChatGPT account or Codex Runtime cannot use native image generation. Check account permissions or update the Runtime.', 'unsupported', message);}if (/policy|moderation|safety|content_filter/i.test(message)) {- return new CodexNativeImageError('图片请求被安全策略拒绝,请调整描述后重试', 'http-rejected', message);+ return new CodexNativeImageError('The image request was denied by the safety policy. Adjust the description and retry.', 'http-rejected', message);}if (/timed?\s*out|timeout/i.test(message)) {- return new CodexNativeImageError('Codex 原生生图请求超时,请稍后重试', 'timeout', message);+ return new CodexNativeImageError('The Codex native image request timed out. Try again later.', 'timeout', message);}if (/ENOTFOUND|EAI_AGAIN/i.test(message)) {- return new CodexNativeImageError('Codex 生图服务域名解析失败,请检查网络后重试', 'dns', message);+ return new CodexNativeImageError('Codex image service DNS lookup failed. Check the network and retry.', 'dns', message);}if (/ECONNREFUSED/i.test(message)) {- return new CodexNativeImageError('Codex 生图服务连接被拒绝,请检查网络或代理', 'connection-refused', message);+ return new CodexNativeImageError('The Codex image service connection was refused. Check the network or proxy.', 'connection-refused', message);}if (/ECONNRESET|connection.*reset/i.test(message)) {- return new CodexNativeImageError('Codex 生图服务连接中断,请检查网络后重试', 'connection-reset', message);+ return new CodexNativeImageError('The Codex image service connection was interrupted. Check the network and retry.', 'connection-reset', message);}- return new CodexNativeImageError('Codex 原生生图失败,请查看服务说明后重试', 'provider-failed', message);+ return new CodexNativeImageError('Codex native image generation failed. Review the provider message and retry.', 'provider-failed', message);}async function imageFiles(root: string, depth = 0): Promise<string[]> {@@ -209,7 +209,7 @@ async function imageFiles(root: string, depth = 0): Promise<string[]> {const path = join(root, entry.name);if (entry.isDirectory() && depth < 3) files.push(...await imageFiles(path, depth + 1));else if (entry.isFile() && /\.(png|jpe?g|webp)$/i.test(entry.name)) files.push(path);- if (files.length > 32) throw new Error('Codex 当前任务返回了过多图片产物');+ if (files.length > 32) throw new Error('Codex returned too many image outputs for this task');}return files;}diff --git a/apps/daemon/src/image-generation/codex-runtime.ts b/apps/daemon/src/image-generation/codex-runtime.tsindex fd4a764d..e45445a5 100644--- a/apps/daemon/src/image-generation/codex-runtime.ts+++ b/apps/daemon/src/image-generation/codex-runtime.ts@@ -11,30 +11,30 @@ export async function readCodexImageConfiguration(runtime: CodexNativeImageRuntiexport async function inspectCodexImageRuntime(runtime: CodexNativeImageRuntime | undefined): Promise<CodexImageStatus> {let authentication: CodexImageStatus['authentication'] = 'none';try {- if (!runtime) throw new Error('当前 Runtime 未配置本机 Codex 生图,请检查 Runtime 配置');+ if (!runtime) throw new Error('Local Codex image generation is not configured. Check Runtime settings.');const configuration = await readCodexImageConfiguration(runtime);authentication = configuration.authentication;if (configuration.authentication === 'api_key') return {authentication, ready: true, executionMode: 'api', model: configuration.provider.model,- message: '已检测到 Codex API 配置;将沿用当前接口生图,接口和模型需支持图片生成。'+ message: 'Codex API configuration was found. Image generation will use this API; both the API and model must support it.'};- if (!runtime.codexBin) throw new Error('当前 Runtime 缺少 Codex 可执行程序,无法使用 ChatGPT 登录态生图');+ if (!runtime.codexBin) throw new Error('The Codex executable is missing. Image generation with ChatGPT sign-in is unavailable.');const capability = runtime.checkNativeCapability? await runtime.checkNativeCapability(): await probeNativeImageCapability(runtime.codexBin, runtime.codexHome);- if (!capability.supported) throw new Error(`当前 Codex Runtime ${capability.version ?? ''} 不支持原生生图,请更新 Runtime`);+ if (!capability.supported) throw new Error(`Codex Runtime ${capability.version ?? ''} does not support native image generation. Update the Runtime.`);return { authentication, ready: true, executionMode: 'native', version: capability.version,- message: '已检测到本地 ChatGPT 登录凭据和原生生图工具;将通过 Codex 生成图片,无需额外配置图片 API Key。'+ message: 'Local ChatGPT credentials and native image tools were found. Codex will generate images without an additional image API key.'};} catch (error) {- return { authentication, ready: false, executionMode: null, message: error instanceof Error ? error.message : '无法检查 Codex 生图能力' };+ return { authentication, ready: false, executionMode: null, message: error instanceof Error ? error.message : 'Could not check Codex image capabilities' };}}async function probeNativeImageCapability(codexBin: string, codexHome: string): Promise<{ supported: boolean; version?: string }> {const run = (args: string[]) => new Promise<string>((resolve, reject) => {execFile(codexBin, args, { timeout: 8_000, maxBuffer: 1024 * 1024, encoding: 'utf8', env: { ...process.env, CODEX_HOME: codexHome } }, (error, stdout) => {- if (error) reject(new Error('无法启动 Codex Runtime 或读取原生生图能力,请检查可执行程序'));+ if (error) reject(new Error('Could not start Codex or read native image capabilities. Check the executable.'));else resolve(stdout);});});diff --git a/apps/daemon/src/image-generation/provider.ts b/apps/daemon/src/image-generation/provider.tsindex 952c480c..3ddfc82e 100644--- a/apps/daemon/src/image-generation/provider.ts+++ b/apps/daemon/src/image-generation/provider.ts@@ -94,7 +94,7 @@ export async function generateImageContents(const gateway = gatewayCreatorBinding(config);const capabilities = gateway ? { supportsReferenceImage: gateway.capabilities?.image?.includes('edit') === true, maxReferenceImages: gateway.capabilities?.image?.includes('edit') ? 1 : 0 } : imageGenerationCapabilities(request.provider);const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(new DOMException(gateway ? '图片生成等待超时,请先查询请求状态,避免重复扣费' : '图片生成超时,请重试', 'TimeoutError')), gateway ? DIRECT_IMAGE_TIMEOUT_MS + 30_000 : REQUEST_TIMEOUT_MS);+ const timeout = setTimeout(() => controller.abort(new DOMException(gateway ? 'Image generation timed out. Check the request status before retrying to avoid duplicate charges.' : 'Image generation timed out. Try again.', 'TimeoutError')), gateway ? DIRECT_IMAGE_TIMEOUT_MS + 30_000 : REQUEST_TIMEOUT_MS);const abort = () => controller.abort(options.signal?.reason);timeout.unref();if (options.signal?.aborted) abort();@@ -129,10 +129,10 @@ export async function generateImageContents(const configuration = await readCodexImageConfiguration(options.codexNative);if (configuration.authentication === 'chatgpt') {nativeExecution = true;- options.onProgress?.({ phase: 'preparing_native_image', message: '正在检查 ChatGPT 登录态和 Codex 原生生图能力…' });+ options.onProgress?.({ phase: 'preparing_native_image', message: 'Checking ChatGPT sign-in and Codex native image capabilities...' });const status = await inspectCodexImageRuntime(options.codexNative);if (!status.ready) throw new ImageGenerationProviderError('config_missing', status.message);- if (status.executionMode !== 'native') throw new ImageGenerationProviderError('config_missing', 'Codex 认证模式已变化,请刷新状态后重试');+ if (status.executionMode !== 'native') throw new ImageGenerationProviderError('config_missing', 'Codex authentication mode changed. Refresh status and try again.');const image = await generateCodexNativeImage({runtime: options.codexNative,request,@@ -184,7 +184,7 @@ export async function generateImageContents(if (error instanceof ImageGenerationProviderError) throw error;if (options.signal?.aborted) throw error;if (controller.signal.reason instanceof DOMException && controller.signal.reason.name === 'TimeoutError') {- const message = gateway ? '图片生成等待超时,请先查询请求状态,避免重复扣费' : '图片生成超时,请稍后重试';+ const message = gateway ? 'Image generation timed out. Check the request status before retrying to avoid duplicate charges.' : 'Image generation timed out. Try again later.';throw new ImageGenerationProviderError('upstream_error', message,{ kind: 'timeout', provider: request.provider, upstreamMessage: message }, { cause: error });}@@ -263,7 +263,7 @@ async function generateOpenAiImages(if (official && response.status === 202) {const accepted = await response.json() as { requestId?: string };if (!accepted.requestId || accepted.requestId !== gatewayRequest || !/^ocdir_[a-f0-9]{48}$/.test(accepted.requestId)) {- throw new ImageGenerationProviderError('upstream_error', '图片生成请求回执无效');+ throw new ImageGenerationProviderError('upstream_error', 'Invalid image generation receipt');}const statusUrl = openAiCompatibleEndpoint(provider.baseUrl, `requests/${accepted.requestId}`);for (;;) {@@ -271,23 +271,23 @@ async function generateOpenAiImages(const status = await fetchCreatorService({ endpoint: statusUrl, method: 'GET', headers: { Authorization: `Bearer ${provider.apiKey}` }, proxy: config.proxy.trim(), signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]), maxResponseBytes: 16_384, fetchImpl });if (!status.ok) {void status.body?.cancel().catch(() => undefined);- throw new ImageGenerationProviderError('upstream_error', '暂时无法查询图片生成结果,请保留任务,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ throw new ImageGenerationProviderError('upstream_error', 'Could not query the image result. Keep the task to avoid duplicate charges.', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });}const receipt = await status.json() as { state?: string; error?: { code?: string; status?: number } };if (receipt.state === 'succeeded') {response = await fetchCreatorService({ endpoint: appendEndpointPath(statusUrl, 'result'), method: 'GET', headers: { Authorization: `Bearer ${provider.apiKey}` }, proxy: config.proxy.trim(), signal, maxResponseBytes: MAX_RESPONSE_BYTES, fetchImpl });if (!response.ok) {void response.body?.cancel().catch(() => undefined);- throw new ImageGenerationProviderError('upstream_error', '图片结果暂时无法下载,请保留任务,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ throw new ImageGenerationProviderError('upstream_error', 'The image result cannot be downloaded yet. Keep the task to avoid duplicate charges.', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });}break;}if (receipt.state === 'failed') {- response = Response.json({ error: { code: receipt.error?.code ?? 'official_service_unavailable', message: receipt.error?.code === 'credits_insufficient' ? '积分不足,请补充积分后再试' : '图片生成请求被拒绝' } }, { status: receipt.error?.status ?? 503 });+ response = Response.json({ error: { code: receipt.error?.code ?? 'official_service_unavailable', message: receipt.error?.code === 'credits_insufficient' ? 'Insufficient credits. Add credits and try again.' : 'The image generation request was rejected' } }, { status: receipt.error?.status ?? 503 });break;}- if (receipt.state === 'outcome_unknown') throw new ImageGenerationProviderError('upstream_error', '图片生成结果尚未确认,请先查询请求状态,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });- if (!['submitting', 'waiting_upstream'].includes(receipt.state ?? '')) throw new ImageGenerationProviderError('upstream_error', '图片生成请求状态无效');+ if (receipt.state === 'outcome_unknown') throw new ImageGenerationProviderError('upstream_error', 'The image result is unconfirmed. Check request status first to avoid duplicate charges.', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ if (!['submitting', 'waiting_upstream'].includes(receipt.state ?? '')) throw new ImageGenerationProviderError('upstream_error', 'Invalid image generation request status');await delay(1_000, undefined, { signal });}}diff --git a/apps/daemon/src/main.ts b/apps/daemon/src/main.tsindex d264b604..a66dc0ea 100644--- a/apps/daemon/src/main.ts+++ b/apps/daemon/src/main.ts@@ -126,7 +126,7 @@ async function main(): Promise<void> {if (!versionProbe.ready) {emitBootstrapError({code: 'CODEX_VERSION_CHECK_FAILED',- message: 'Codex CLI 无法正常启动,请重新安装或选择其他 Codex 可执行文件',+ message: 'Codex CLI could not start. Reinstall it or select another Codex executable.',details: {codexBin,version: versionProbe.version,@@ -405,9 +405,9 @@ function probeErrorMessage(input: {}): string {if (input.stderrSummary !== undefined) return input.stderrSummary;if (input.exitCode !== null && input.exitCode !== 0) {- return `Codex CLI 退出码为 ${input.exitCode}`;+ return `Codex CLI exited with code ${input.exitCode}`;}- return `Codex CLI 未返回有效回复(${input.terminationReason})`;+ return `Codex CLI returned no valid response (${input.terminationReason})`;}async function runAvailabilityProbe(input: {@@ -461,7 +461,7 @@ async function runAvailabilityProbe(input: {errorCode,message});- console.warn(`Codex 后台可用性验证失败 [${errorCode}]:${message}`);+ console.warn(`Codex background availability check failed [${errorCode}]: ${message}`);}function isRecord(value: unknown): value is Record<string, unknown> {diff --git a/apps/daemon/src/notifications/service.ts b/apps/daemon/src/notifications/service.tsindex c650f2e3..120d364f 100644--- a/apps/daemon/src/notifications/service.ts+++ b/apps/daemon/src/notifications/service.ts@@ -87,7 +87,7 @@ export function createNotificationService(input: {enqueueRunTerminal(runId) {const row = getScheduleRun.get(runId) as ScheduleRunNotificationRow | undefined;if (row === undefined) return undefined;- const title = safeText(row.schedule_name, TITLE_LIMIT, '已安排任务');+ const title = safeText(row.schedule_name, TITLE_LIMIT, 'Scheduled task');const notification = terminalCopy(row, title);return repository.enqueue({id: idFactory(),@@ -106,13 +106,13 @@ export function createNotificationService(input: {| ScheduleApprovalNotificationRow| undefined;if (row === undefined) return undefined;- const title = safeText(row.schedule_name, TITLE_LIMIT, '已安排任务');+ const title = safeText(row.schedule_name, TITLE_LIMIT, 'Scheduled task');return repository.enqueue({id: idFactory(),dedupeKey: `approval:${row.approval_id}:pending`,kind: 'schedule_waiting_approval',- title: `${title}等待审批`,- body: safeText(row.summary, BODY_LIMIT, '需要你的审批。'),+ title: `${title}: awaiting approval`,+ body: safeText(row.summary, BODY_LIMIT, 'Your approval is required.'),threadId: row.thread_id,runId: row.run_id,approvalId: row.approval_id,@@ -152,20 +152,20 @@ function terminalCopy(return {kind: 'schedule_succeeded',title,- body: resultSummary(row.result_event_payload_json) ?? '任务已完成。'+ body: resultSummary(row.result_event_payload_json) ?? 'The task is complete.'};}if (row.public_status === 'canceled') {return {kind: 'schedule_canceled',- title: `${title}已取消`,- body: '本次任务已取消。'+ title: `${title}: canceled`,+ body: 'This task was canceled.'};}return {kind: 'schedule_failed',- title: `${title}失败`,- body: '任务未完成,请打开会话查看详情。'+ title: `${title}: failed`,+ body: 'The task did not complete. Open its conversation for details.'};}diff --git a/apps/daemon/src/platform-connections/browser-close.ts b/apps/daemon/src/platform-connections/browser-close.tsindex bcca6eb1..1d817278 100644--- a/apps/daemon/src/platform-connections/browser-close.ts+++ b/apps/daemon/src/platform-connections/browser-close.ts@@ -1,10 +1,12 @@import { join } from 'node:path';import { spawnCreatorProcess } from '../creator/process-tree.js';-export class BrowserCloseError extends Error {+import { PublicPlatformConnectionError } from './errors.js';++export class BrowserCloseError extends PublicPlatformConnectionError {constructor(browser: 'chrome' | 'edge') {const name = browser === 'chrome' ? 'Chrome' : 'Edge';- super(`无法读取 ${name} 登录窗口。请关闭刚才打开的 YouTube 登录窗口后重新连接;其他浏览器窗口可以保持打开。`);+ super(`Could not read the ${name} sign-in window. Close the YouTube sign-in window and reconnect. Other browser windows can stay open.`);}}@@ -116,7 +118,7 @@ $pids = @(Get-CimInstance Win32_Process -Filter "Name = '${processName}'" | Wher`, signal);if (!Array.isArray(result?.pids) || result.pids.some(pid => !Number.isSafeInteger(pid) || pid <= 0)) {signal.throwIfAborted();- throw new Error('无法确认 YouTube 登录窗口,请重试连接。');+ throw new PublicPlatformConnectionError('Could not verify the YouTube sign-in window. Connect again.');}return result.pids as number[];}diff --git a/apps/daemon/src/platform-connections/browser-login.ts b/apps/daemon/src/platform-connections/browser-login.tsindex 217f1b10..ce0e615e 100644--- a/apps/daemon/src/platform-connections/browser-login.ts+++ b/apps/daemon/src/platform-connections/browser-login.ts@@ -13,8 +13,10 @@ export type BrowserLoginSession = {dispose(): Promise<void>;};-export class LoginBrowserCloseError extends Error {- constructor() { super('请关闭刚才打开的 YouTube 登录窗口,再点击“完成登录”。其他 Chrome 窗口可以保持打开。'); }+import { PublicPlatformConnectionError } from './errors.js';++export class LoginBrowserCloseError extends PublicPlatformConnectionError {+ constructor() { super('Close the YouTube sign-in window, then click "Finish sign-in". Other Chrome windows can stay open.'); }}export function windowsYouTubeBrowserArgs(directory: string, url = 'https://accounts.google.com/ServiceLogin?service=youtube&continue=https%3A%2F%2Fwww.youtube.com%2F'): string[] {@@ -33,7 +35,7 @@ export async function openWindowsYouTubeLogin(input: { root: string; signal: Aboconst browser = spawn(executable, windowsYouTubeBrowserArgs(directory, input.url), { stdio: 'ignore', windowsHide: true });await new Promise<void>((resolve, reject) => {browser.once('spawn', resolve);- browser.once('error', () => reject(new Error('无法打开 Chrome 登录窗口,请重试连接。')));+ browser.once('error', () => reject(new PublicPlatformConnectionError('Could not open the Chrome sign-in window. Connect again.')));});const pids = existing.length ? existing : [browser.pid!];const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe');@@ -64,5 +66,5 @@ async function findChrome(): Promise<string> {const executable = join(root, 'Google/Chrome/Application/chrome.exe');if ((await stat(executable).catch(() => undefined))?.isFile()) return executable;}- throw new Error('未找到 Chrome,请安装 Chrome 后重新连接 YouTube。');+ throw new PublicPlatformConnectionError('Chrome was not found. Install Chrome and reconnect YouTube.');}diff --git a/apps/daemon/src/platform-connections/browser.ts b/apps/daemon/src/platform-connections/browser.tsindex e6a973af..3b35f4af 100644--- a/apps/daemon/src/platform-connections/browser.ts+++ b/apps/daemon/src/platform-connections/browser.ts@@ -5,6 +5,7 @@ import { join } from 'node:path';import { spawnCreatorProcess } from '../creator/process-tree.js';import type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';import { BrowserCloseError } from './browser-close.js';+import { PublicPlatformConnectionError } from './errors.js';import type { ConnectionPlatform } from '@opencreator/protocol';import { filterPlatformCookies, hasPlatformSession, type PlatformCookie } from './cookies.js';@@ -88,7 +89,7 @@ export async function readBrowserPlatformCookies(input: {}): Promise<PlatformCookie[]> {const { runtime, profile, signal } = input;const platform = input.platform ?? 'youtube';- if (!runtime?.script) throw new Error('浏览器连接需要内置 yt-dlp 组件,请更新本地组件后重试。');+ if (!runtime?.script) throw new PublicPlatformConnectionError('Browser connection requires the bundled yt-dlp component. Update local components and try again.');signal.throwIfAborted();const output = await new Promise<string>((resolve, reject) => {const child = spawnCreatorProcess(runtime.executable, ['-I', '-B', '-c', READ_BROWSER_COOKIES,@@ -99,21 +100,21 @@ export async function readBrowserPlatformCookies(input: {let length = 0;child.stdout?.on('data', (chunk: Buffer) => {length += chunk.length;- if (length > 1024 * 1024) { child.kill(); reject(new Error('浏览器 Cookie 读取失败,请重试。')); return; }+ if (length > 1024 * 1024) { child.kill(); reject(new PublicPlatformConnectionError('Could not read browser cookies. Try again.')); return; }chunks.push(chunk);});child.stderr?.on('data', () => undefined);- child.once('error', () => reject(new Error('无法读取浏览器 Cookie,请检查本地组件。')));+ child.once('error', () => reject(new PublicPlatformConnectionError('Could not read browser cookies. Check local components.')));child.once('close', code => {- if (signal.aborted) reject(new Error('连接已取消。'));+ if (signal.aborted) reject(new PublicPlatformConnectionError('Connection canceled.'));else if (code !== 0) {if (process.platform === 'win32') {let failure: string | undefined;try { failure = JSON.parse(Buffer.concat(chunks).toString('utf8')).failure; } catch { /* 输出不完整时使用通用错误。 */ }reject(failure === 'browser-locked' ? new BrowserCloseError(profile.browser): failure === 'decryption-failed' ? windowsDecryptionError()- : new Error('无法读取 YouTube 登录态,请重新连接并完成登录。'));- } else reject(new Error('无法读取 Chrome / Edge 的 Cookie。请允许钥匙串访问;若浏览器加密或文件锁阻止读取,可导入 Cookie 文件。'));+ : new PublicPlatformConnectionError('Could not read the YouTube session. Reconnect and finish signing in.'));+ } else reject(new PublicPlatformConnectionError('Could not read Chrome or Edge cookies. Allow Keychain access. If browser encryption or file locks prevent access, import a cookie file.'));}else resolve(Buffer.concat(chunks).toString('utf8'));});@@ -124,12 +125,12 @@ export async function readBrowserPlatformCookies(input: {throw windowsDecryptionError();}if (result.decryptionFailed && cookies.length === 0) {- throw new Error('浏览器 Cookie 解密失败,请允许 macOS 钥匙串访问后重新连接;当前浏览器的加密方式也可能不受 yt-dlp 支持。');+ throw new PublicPlatformConnectionError('Browser cookie decryption failed. Allow macOS Keychain access and reconnect. This browser\'s encryption may also be unsupported by yt-dlp.');}return cookies;}function windowsDecryptionError(): Error {- return new Error('无法解密 YouTube 登录态,请断开后重新连接并登录。');+ return new PublicPlatformConnectionError('Could not decrypt the YouTube session. Disconnect, reconnect, and sign in again.');}export const readBrowserYouTubeCookies = readBrowserPlatformCookies;diff --git a/apps/daemon/src/platform-connections/errors.ts b/apps/daemon/src/platform-connections/errors.tsnew file mode 100644index 00000000..ae01e069--- /dev/null+++ b/apps/daemon/src/platform-connections/errors.ts@@ -0,0 +1 @@+export class PublicPlatformConnectionError extends Error {}diff --git a/apps/daemon/src/platform-connections/service.ts b/apps/daemon/src/platform-connections/service.tsindex 28ee715b..f6678103 100644--- a/apps/daemon/src/platform-connections/service.ts+++ b/apps/daemon/src/platform-connections/service.ts@@ -6,6 +6,7 @@ import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-jsoimport type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';import { listBrowserProfiles, readBrowserPlatformCookies, type BrowserProfile } from './browser.js';import { LoginBrowserCloseError, openWindowsYouTubeLogin, type BrowserLoginSession } from './browser-login.js';+import { PublicPlatformConnectionError } from './errors.js';import { filterPlatformCookies, hasPlatformSession, parsePlatformCookies,serializePlatformCookies, type PlatformCookie } from './cookies.js';@@ -65,7 +66,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionif (await this.hasAuthentication()) { await this.refreshState(); return this.publicState(); }const attempt: ConnectionAttempt = { controller: new AbortController(), work: Promise.resolve() };this.attempt = attempt;- this.state = { platform: this.platform, status: 'connecting', message: '正在打开 YouTube 登录窗口' };+ this.state = { platform: this.platform, status: 'connecting', message: 'Opening the YouTube sign-in window' };attempt.work = this.finishConnection(attempt);return this.publicState();}@@ -73,8 +74,8 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionconst profile = profileId ? profiles.find(p => p.id === profileId) : profiles[0];if (!profile) {this.state = { platform: this.platform, status: 'error', message: this.platform === 'youtube'- ? '未找到可用的浏览器账号,请先在 Chrome 或 Edge 中登录 YouTube。'- : '未找到可用的浏览器账号,请先在 Chrome 或 Edge 中打开抖音并完成网页验证。' };+ ? 'No browser profile was found. Sign in to YouTube in Chrome or Edge first.'+ : 'No browser profile was found. Open Douyin in Chrome or Edge and complete website verification first.' };return this.publicState();}const attempt = { controller: new AbortController(), work: Promise.resolve() };@@ -88,7 +89,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionreturn this.serialize(async () => {if (this.attempt?.completeLogin) {this.attempt.completeLogin();- this.state = { platform: this.platform, status: 'connecting', browser: 'chrome', message: '正在保存 YouTube 登录态' };+ this.state = { platform: this.platform, status: 'connecting', browser: 'chrome', message: 'Saving the YouTube session' };}return this.publicState();});@@ -112,8 +113,8 @@ export class PlatformConnectionService<P extends ConnectionPlatform = ConnectionimportCookies(source: string): Promise<ConnectionState<P>> {return this.serialize(async () => {const cookies = parsePlatformCookies(source, this.platform);- if (!hasPlatformSession(cookies, this.platform)) throw new Error(this.platform === 'youtube'- ? 'Cookie 文件中没有有效的 YouTube 登录态。' : 'Cookie 文件中没有有效的抖音会话。');+ if (!hasPlatformSession(cookies, this.platform)) throw new PublicPlatformConnectionError(this.platform === 'youtube'+ ? 'The cookie file contains no valid YouTube session.' : 'The cookie file contains no valid Douyin session.');await this.stopConnection();await writePrivateJsonFile(this.credentialFile, { version: 1, cookies, connectedAt: new Date().toISOString() } satisfies Credential);await this.refreshState();@@ -161,7 +162,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionif (managed) {login = await (this.input.openLoginBrowser ?? openWindowsYouTubeLogin)({ root: this.input.root, signal: attempt.controller.signal });profile = login.profile;- let message = '请在打开的 Chrome 窗口中登录 YouTube';+ let message = 'Sign in to YouTube in the Chrome window';let actionRequired: 'complete-login' | 'close-login-browser' = 'complete-login';let watchExit = true;while (!browserClosed) {@@ -169,7 +170,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionawait this.waitForLoginCompletion(attempt, login, watchExit);watchExit = false;attempt.controller.signal.throwIfAborted();- this.state = { platform: this.platform, status: 'connecting', browser: 'chrome', profileId: profile.id, message: '正在保存 YouTube 登录态' };+ this.state = { platform: this.platform, status: 'connecting', browser: 'chrome', profileId: profile.id, message: 'Saving the YouTube session' };try { await login.close(attempt.controller.signal); browserClosed = true; }catch (error) {if (!(error instanceof LoginBrowserCloseError)) throw error;@@ -178,17 +179,17 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connection}}attempt.controller.signal.throwIfAborted();- if (!profile) throw new Error('未找到可用的浏览器账号,请重新连接。');+ if (!profile) throw new PublicPlatformConnectionError('No browser profile was found. Connect again.');const cookies = filterPlatformCookies(await (this.input.readBrowserCookies ?? readBrowserPlatformCookies)({profile, runtime: this.input.getRuntime(), signal: attempt.controller.signal,...(this.platform === 'douyin' ? { platform: 'douyin' as const } : {})}), this.platform);attempt.controller.signal.throwIfAborted();- if (!hasPlatformSession(cookies, this.platform)) throw new Error(managed- ? '尚未完成 YouTube 登录,请重新连接并在登录窗口中完成登录。'+ if (!hasPlatformSession(cookies, this.platform)) throw new PublicPlatformConnectionError(managed+ ? 'YouTube sign-in is incomplete. Reconnect and finish signing in in the sign-in window.': this.platform === 'youtube'- ? '此浏览器账号尚未登录 YouTube,或登录已过期。请在该账号中登录后重新连接。'- : '此浏览器账号没有有效的抖音会话,请先打开抖音视频并完成网页验证后重新连接。');+ ? 'This browser profile is signed out of YouTube or its session expired. Sign in with this profile and reconnect.'+ : 'This browser profile has no valid Douyin session. Open the video, complete website verification, and reconnect.');const connectedAt = new Date().toISOString();await writePrivateJsonFile(this.credentialFile, {version: 1, cookies, connectedAt, browser: profile.browser, profileId: profile.id@@ -196,7 +197,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connectionthis.state = { platform: this.platform, status: 'connected', connectedAt, browser: profile.browser, profileId: profile.id };} catch (error) {this.state = { platform: this.platform, status: 'error', browser: profile?.browser, profileId: profile?.id,- message: attempt.controller.signal.aborted ? '连接已取消或超时,请重新连接。' : publicConnectionError(error) };+ message: attempt.controller.signal.aborted ? 'The connection was canceled or timed out. Connect again.' : publicConnectionError(error) };} finally {clearTimeout(timeout);if (login) {@@ -255,5 +256,7 @@ export class PlatformConnectionService<P extends ConnectionPlatform = Connection}function publicConnectionError(error: unknown): string {const message = error instanceof Error ? error.message : '';- return /^[\u4e00-\u9fff]/.test(message) ? message : '读取浏览器登录态失败,请重试或选择其他浏览器账号。';+ return error instanceof PublicPlatformConnectionError || /^[\u4e00-\u9fff]/.test(message)+ ? message+ : 'Could not read the browser session. Try again or select another browser profile.';}diff --git a/apps/daemon/src/projects/manager.ts b/apps/daemon/src/projects/manager.tsindex c9617918..be11df4c 100644--- a/apps/daemon/src/projects/manager.ts+++ b/apps/daemon/src/projects/manager.ts@@ -62,14 +62,14 @@ export function createProjectManager(input: CreateProjectManagerInput): ProjectMif (!existsSync(cwd)) {throw new ProjectManagerError('PROJECT_DIRECTORY_UNAVAILABLE',- '无法创建项目目录'+ 'Could not create the project directory');}}}throw new ProjectManagerError('PROJECT_DIRECTORY_CONFLICT',- '无法生成唯一项目目录'+ 'Could not create a unique project directory');};@@ -80,7 +80,7 @@ export function createProjectManager(input: CreateProjectManagerInput): ProjectM} catch {throw new ProjectManagerError('PROJECT_DIRECTORY_UNAVAILABLE',- 'OpenCreator 默认项目目录不可用'+ 'The OpenCreator default project directory is unavailable');}@@ -94,7 +94,7 @@ export function createProjectManager(input: CreateProjectManagerInput): ProjectMif (!existsSync(cwd)) {throw new ProjectManagerError('PROJECT_DIRECTORY_UNAVAILABLE',- '无法创建默认项目目录'+ 'Could not create the default project directory');}}@@ -105,7 +105,7 @@ export function createProjectManager(input: CreateProjectManagerInput): ProjectMif (existing !== undefined) return mapProjectRow(existing);try {- return createProjectRecord({ cwd: directory.cwd, name: '默认项目' });+ return createProjectRecord({ cwd: directory.cwd, name: 'Default project' });} catch (error) {if (createdDirectory) {try {@@ -127,7 +127,7 @@ export function createProjectManager(input: CreateProjectManagerInput): ProjectM} catch {throw new ProjectManagerError('PROJECT_DIRECTORY_UNAVAILABLE',- 'OpenCreator 默认项目目录不可用'+ 'The OpenCreator default project directory is unavailable');}@@ -415,7 +415,7 @@ function normalizeProjectPath(value: string, homeDir: string): string {}function normalizeProjectName(value: string | undefined, cwd: string): string {- const name = value?.trim() || basename(cwd) || '项目';+ const name = value?.trim() || basename(cwd) || 'Project';if (name.length === 0) throw new Error('Project name is required');return name;}@@ -423,10 +423,10 @@ function normalizeProjectName(value: string | undefined, cwd: string): string {function normalizeManagedProjectName(value: string): string {const name = value.trim();if (name.length === 0) {- throw new ProjectManagerError('PROJECT_NAME_INVALID', '项目名称不能为空');+ throw new ProjectManagerError('PROJECT_NAME_INVALID', 'Project name cannot be empty');}if (name.length > 80) {- throw new ProjectManagerError('PROJECT_NAME_INVALID', '项目名称不能超过 80 个字符');+ throw new ProjectManagerError('PROJECT_NAME_INVALID', 'Project name cannot exceed 80 characters');}if (name === '.'@@ -437,7 +437,7 @@ function normalizeManagedProjectName(value: string): string {) {throw new ProjectManagerError('PROJECT_NAME_INVALID',- '项目名称不能包含路径分隔符'+ 'Project name cannot contain path separators');}return name;diff --git a/apps/daemon/src/runs/manager.ts b/apps/daemon/src/runs/manager.tsindex 5c30a9f5..c267ceb7 100644--- a/apps/daemon/src/runs/manager.ts+++ b/apps/daemon/src/runs/manager.ts@@ -884,7 +884,7 @@ export function createRunManager(options: RunManagerOptions): RunManager {id,++seq,'THREAD_CODEX_SESSION_ROTATED',- '执行上下文已重新连接',+ 'Execution context reconnected',publish,{reason: rotation.reason,@@ -913,7 +913,7 @@ export function createRunManager(options: RunManagerOptions): RunManager {id,++seq,'THREAD_ROTATION_CONTEXT_UNAVAILABLE',- '会话摘要暂不可用,已使用本次公开任务输入重新连接',+ 'Conversation summary unavailable. Reconnected using the current public task input.',publish,{ error: redactText(error instanceof Error ? error.message : String(error)) }).catch(() => undefined);@@ -2067,14 +2067,14 @@ function buildApprovalRequest(input: {? 'file_change' as const: 'permissions' as const;const title = isScheduleCreate- ? '允许创建定时任务'+ ? 'Allow scheduled task creation': isMcpElicitation- ? '允许调用 MCP 工具'+ ? 'Allow MCP tool call': kind === 'command_execution'- ? host === undefined ? '允许执行命令' : '允许网络访问'+ ? host === undefined ? 'Allow command execution' : 'Allow network access': kind === 'file_change'- ? '允许修改文件'- : '允许扩大权限';+ ? 'Allow file changes'+ : 'Allow additional permissions';const summary = host !== undefined? `${protocol ?? 'network'}://${host}${port === undefined ? '' : `:${port}`}`: scheduleName ?? toolName ?? serverName ?? command ?? grantRoot ?? reason ?? title;diff --git a/apps/daemon/src/search/service.ts b/apps/daemon/src/search/service.tsindex 2eff94cf..5ab47ae9 100644--- a/apps/daemon/src/search/service.ts+++ b/apps/daemon/src/search/service.ts@@ -194,7 +194,7 @@ function mapSearchRow(row: SearchRow, query: string): ConversationSearchResult {threadId: row.thread_id,projectId: row.project_id,codexThreadId: row.codex_thread_id,- title: createConversationTitle(row.session_title, '未命名对话'),+ title: createConversationTitle(row.session_title, 'Untitled conversation'),cwd: row.session_cwd,...(row.item_id === TITLE_ITEM_ID ? {} : { itemId: row.item_id }),itemType: row.item_type,diff --git a/apps/daemon/src/tasks/service.ts b/apps/daemon/src/tasks/service.tsindex 95372d8a..e9851c2e 100644--- a/apps/daemon/src/tasks/service.ts+++ b/apps/daemon/src/tasks/service.ts@@ -331,21 +331,21 @@ function classifyFailure() {return {kind: 'project_directory',- summary: '项目目录不存在或无法访问,请编辑项目后重试。'+ summary: 'The project directory is missing or inaccessible. Edit the project and try again.'};}switch (row.termination_reason) {case 'timeout':- return { kind: 'other', summary: '任务运行时间过长,已自动停止。' };+ return { kind: 'other', summary: 'The task exceeded its time limit and was stopped automatically.' };case 'inactivity_timeout':- return { kind: 'other', summary: '任务长时间没有响应,已自动停止。' };+ return { kind: 'other', summary: 'The task stopped responding and was stopped automatically.' };case 'daemon_restart':- return { kind: 'other', summary: '本地服务重启中断了本次任务,可以稍后重试。' };+ return { kind: 'other', summary: 'A Runtime restart interrupted this task. Try again later.' };case 'spawn_failed':- return { kind: 'other', summary: '任务无法启动,请检查项目和运行配置。' };+ return { kind: 'other', summary: 'The task could not start. Check the project and Runtime configuration.' };default:- return { kind: 'other', summary: '任务未完成,请打开会话查看详情。' };+ return { kind: 'other', summary: 'The task did not complete. Open its conversation for details.' };}}diff --git a/apps/daemon/src/threads/conversation-title.ts b/apps/daemon/src/threads/conversation-title.tsindex 272b4bc2..282c49cb 100644--- a/apps/daemon/src/threads/conversation-title.ts+++ b/apps/daemon/src/threads/conversation-title.ts@@ -1,5 +1,5 @@-const DEFAULT_TITLE = '新对话';-const ATTACHMENT_TITLE = '查看附件';+const DEFAULT_TITLE = 'New conversation';+const ATTACHMENT_TITLE = 'View attachments';const MAX_TITLE_WIDTH = 30;const REQUEST_MARKERS = [@@ -21,7 +21,7 @@ export function createConversationTitle(input: string, fallback = DEFAULT_TITLE)const command = /<command>\s*([\s\S]*?)\s*<\/command>/i.exec(extracted)?.[1];if (command !== undefined) {- return limitTitle(`执行 ${normalizeWhitespace(command)}`, fallback);+ return limitTitle(`Run ${normalizeWhitespace(command)}`, fallback);}const withoutSkill = extracted@@ -94,7 +94,7 @@ function extractRequest(input: string): string | undefined {markerEnd < 0&& source.startsWith('你是 OpenCreator 的计划任务配置助手')) {- return '创建计划任务';+ return 'Create scheduled task';}if (source.startsWith('# Files mentioned by the user:')) {diff --git a/apps/daemon/src/video-generation/service.ts b/apps/daemon/src/video-generation/service.tsindex 46aae8f7..151cc6ad 100644--- a/apps/daemon/src/video-generation/service.ts+++ b/apps/daemon/src/video-generation/service.ts@@ -124,18 +124,21 @@ export function createVideoGenerationService(input: {headers: { Authorization: `Bearer ${binding.apiKey}`, 'Content-Type': 'application/json', ...(logicalId ? { 'Idempotency-Key': logicalId } : {}) },...(params ? { body: JSON.stringify(params) } : {})});- if (!response.ok) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频请求未完成,请查询原任务', response.status);+ if (!response.ok) {+ const failure = await creatorServiceErrorInfo(response, 'Official video', 'opencreator-gateway-video');+ throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', failure.message, response.status, failure.publicFacts);+ }return response;}async function refreshGateway(stored: StoredVideoGeneration, options: VideoGenerationOperationOptions) {const source = await input.gatewaySource?.binding();- if (!source || source.accountId !== stored.gateway?.accountId) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', '请登录原任务账户后查询视频', 403);+ if (!source || source.accountId !== stored.gateway?.accountId) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', 'Sign in with the original task account to check the video', 403);if (stored.result.status === 'completed' || stored.result.status === 'failed') return stored.result;const response = stored.upstreamId? await gatewayCall(source, `requests/${encodeURIComponent(stored.upstreamId)}`, options): await gatewayCall(source, 'video/jobs', options, stored.gateway.params, stored.gateway.logicalId);const payload = await response.json() as { requestId?: string; state?: string };- if (!payload.requestId || !/^[A-Za-z0-9_-]{12,128}$/.test(payload.requestId)) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频回执无效', 502);+ if (!payload.requestId || !/^[A-Za-z0-9_-]{12,128}$/.test(payload.requestId)) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', 'Invalid official video receipt', 502);stored.upstreamId = payload.requestId;options.onGatewayRequest?.(payload.requestId);const completed = payload.state === 'succeeded';@@ -145,10 +148,10 @@ export function createVideoGenerationService(input: {options.onDownloadStart?.();const response = await gatewayCall(source, `requests/${encodeURIComponent(stored.upstreamId)}/result`, options);const reader = response.body?.getReader(); const chunks: Buffer[] = []; let size = 0;- if (!reader) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频结果为空', 502);- for (;;) { const chunk = await reader.read(); if (chunk.done) break; size += chunk.value.length; if (size > MAX_VIDEO_BYTES) { await reader.cancel(); throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '视频结果过大', 502); } chunks.push(Buffer.from(chunk.value)); }+ if (!reader) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', 'The official video result is empty', 502);+ for (;;) { const chunk = await reader.read(); if (chunk.done) break; size += chunk.value.length; if (size > MAX_VIDEO_BYTES) { await reader.cancel(); throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', 'The video result is too large', 502); } chunks.push(Buffer.from(chunk.value)); }const content = Buffer.concat(chunks);- if (!content.length) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频结果为空', 502);+ if (!content.length) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', 'The official video result is empty', 502);await writeFile(videoPath(stored.result.id), content, { mode: 0o600 });stored.result = { ...stored.result, status: 'completed', progress: 100, progressKnown: true, fileName: `OpenCreator-video-${stored.result.id}.mp4`, mime: 'video/mp4', size: content.length };await writeStored(stored);@@ -223,10 +226,10 @@ export function createVideoGenerationService(input: {const gateway = await input.gatewaySource?.binding();validateRequest(request, gateway === undefined);if (gateway) {- if (!gateway.models.video || (request.referenceImage && !gateway.capabilities?.video?.includes('image_to_video'))) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', '当前官方路由未提供此视频能力', 400);- if (request.model && request.model !== gateway.models.video) throw new VideoGenerationError('VALIDATION_FAILED', '请选择当前任务的官方视频模型', 400);+ if (!gateway.models.video || (request.referenceImage && !gateway.capabilities?.video?.includes('image_to_video'))) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', 'The official route does not provide this video capability', 400);+ if (request.model && request.model !== gateway.models.video) throw new VideoGenerationError('VALIDATION_FAILED', 'Select an official video model for this task', 400);const model = gateway.catalog?.find(candidate => candidate.modality === 'video' && candidate.id === gateway.models.video);- if (!model || !gatewayVideoSizes(model).includes(request.size) || !model.durations?.includes(request.duration)) throw new VideoGenerationError('VALIDATION_FAILED', '当前官方视频模型不支持所选尺寸或时长', 400);+ if (!model || !gatewayVideoSizes(model).includes(request.size) || !model.durations?.includes(request.duration)) throw new VideoGenerationError('VALIDATION_FAILED', 'The official video model does not support this size or duration', 400);const id = createId(); validateResultId(id);const logicalId = gateway.logicalId ?? options.logicalId ?? id;options.onGatewayBinding?.({accountId:gateway.accountId,bindingVersion:gateway.bindingVersion,logicalId});diff --git a/apps/daemon/src/video-metadata/service.ts b/apps/daemon/src/video-metadata/service.tsindex 80242142..6f5e02e3 100644--- a/apps/daemon/src/video-metadata/service.ts+++ b/apps/daemon/src/video-metadata/service.ts@@ -39,7 +39,7 @@ export function createVideoMetadataService(input: {const { previewUrl: _previewUrl, ...metadata } = await resolveOnlineVideoMetadata({ url: normalized, platform,runtime: input.getYtDlpRuntime!(normalized)!, proxy: await resolveProxy(input.getProxy) });return metadata;- } catch { throw new VideoMetadataError('UPSTREAM_ERROR', 'YouTube 视频信息暂不可用,请检查网络或平台连接后重试'); }+ } catch { throw new VideoMetadataError('UPSTREAM_ERROR', 'YouTube metadata is unavailable. Check the network or platform connection and retry.'); }});}if (platform !== null && platform !== 'youtube' && platform !== 'bilibili') {@@ -181,7 +181,7 @@ function parseVideoSource(value: string): ParsedVideoSource {if (hostname === 'bilibili.com' || hostname.endsWith('.bilibili.com')) {const bilibili = parseBilibiliVideoSource(value);if (bilibili === null) {- throw new VideoMetadataError('UNSUPPORTED_SOURCE', 'B 站链接无效,请检查视频地址和分 P 参数(p 必须为正整数)');+ throw new VideoMetadataError('UNSUPPORTED_SOURCE', 'Invalid Bilibili URL. Check the video address and part parameter (p must be a positive integer).');}return { platform: 'bilibili', videoId: bilibili.videoId, ...(bilibili.partIndex === undefined ? {} : { partIndex: bilibili.partIndex }) };}@@ -232,12 +232,12 @@ function parseMetadataPayload(source: ParsedVideoSource, payload: unknown): Videconst thumbnailUrl = boundedText(payload.data.pic, 2048);const parts = Array.isArray(payload.data.pages) ? payload.data.pages.map(parseBilibiliPart) : undefined;if (parts?.length === 0) {- throw new VideoMetadataError('UPSTREAM_ERROR', '无法读取 B 站视频分集信息,请重试');+ throw new VideoMetadataError('UPSTREAM_ERROR', 'Could not read Bilibili video parts. Try again.');}const partIndex = source.partIndex ?? (parts?.length === 1 ? parts[0]?.index : undefined);const selectedPart = parts?.find(part => part.index === partIndex);if (source.partIndex !== undefined && (parts === undefined ? source.partIndex !== 1 : selectedPart === undefined)) {- throw new VideoMetadataError('INVALID_PART', `分 P ${source.partIndex} 不存在,请重新选择视频分集`);+ throw new VideoMetadataError('INVALID_PART', `Video part ${source.partIndex} does not exist. Select a video part again.`);}const dimension = selectedPart ?? (parts !== undefined && parts.length > 1 ? undefined : payload.data.dimension);const dimensions = parseDimensions(dimension);@@ -254,7 +254,7 @@ function parseMetadataPayload(source: ParsedVideoSource, payload: unknown): Videfunction parseBilibiliPart(value: unknown): VideoSourcePart {if (!isRecord(value) || typeof value.page !== 'number' || !Number.isSafeInteger(value.page) || value.page < 1) {- throw new VideoMetadataError('UPSTREAM_ERROR', '无法读取 B 站视频分集信息,请重试');+ throw new VideoMetadataError('UPSTREAM_ERROR', 'Could not read Bilibili video parts. Try again.');}const cid = typeof value.cid === 'number' && Number.isSafeInteger(value.cid) && value.cid > 0 ? value.cid : undefined;const durationSeconds = typeof value.duration === 'number' && value.duration >= 0 ? value.duration : undefined;diff --git a/apps/daemon/test/integration/approval-runtime.test.ts b/apps/daemon/test/integration/approval-runtime.test.tsindex 0b2855b9..9abdff12 100644--- a/apps/daemon/test/integration/approval-runtime.test.ts+++ b/apps/daemon/test/integration/approval-runtime.test.ts@@ -137,7 +137,7 @@ describe('approval runtime integration', () => {threadId: fixture.thread.id,kind: 'permissions',status: 'pending',- title: '允许创建定时任务',+ title: 'Allow scheduled task creation',summary: '武汉天气每5分钟简报',details: {serverName: 'opencreator_schedule',@@ -281,7 +281,7 @@ describe('approval runtime integration', () => {type: 'diagnostic',payload: expect.objectContaining({code: 'THREAD_CODEX_SESSION_ROTATED',- message: '执行上下文已重新连接'+ message: 'Execution context reconnected'})})]));diff --git a/apps/daemon/test/integration/direct-credential-recovery.test.ts b/apps/daemon/test/integration/direct-credential-recovery.test.tsindex 44d6abc9..8a7f903b 100644--- a/apps/daemon/test/integration/direct-credential-recovery.test.ts+++ b/apps/daemon/test/integration/direct-credential-recovery.test.ts@@ -20,7 +20,7 @@ async function fixture(fetcher: typeof fetch, recover = vi.fn(async (_account: s}it.each(['chat/completions', 'images/generations', 'video/jobs'])('%s 明确拒绝认证后只重试一次,同一请求复用结果', async resource => {- const fetcher = vi.fn<typeof fetch>().mockResolvedValueOnce(Response.json({}, { status: 401 })).mockImplementation(async () => Response.json(resource.startsWith('images') ? { data: [{ b64_json: 'aW1hZ2U=' }] } : resource === 'video/jobs' ? { id: 'video-upstream' } : { choices: [{ message: { content: 'translated' } }] }));+ const fetcher = vi.fn<typeof fetch>().mockResolvedValueOnce(Response.json({}, { status: 401 })).mockImplementation(async () => Response.json(resource.startsWith('images') ? { data: [{ b64_json: 'aW1hZ2U=' }] } : resource === 'video/jobs' ? { id: 'video-upstream', status: 'pending' } : { choices: [{ message: { content: 'translated' } }] }));const f = await fixture(fetcher);const asyncImage = resource.startsWith('images');const first = await f.request(resource, asyncImage);diff --git a/apps/daemon/test/integration/direct-services.test.ts b/apps/daemon/test/integration/direct-services.test.tsindex 3f111c07..59f6e9a3 100644--- a/apps/daemon/test/integration/direct-services.test.ts+++ b/apps/daemon/test/integration/direct-services.test.ts@@ -31,7 +31,7 @@ it('redacts provider errors from fragmented events while preserving model text',const text = await new Response(officialEventStream(source)).text();expect(text).toContain('hello'); expect(text).not.toContain('OpenRouter'); expect(text).toContain('official_service_unavailable');});-async function fixture(ledger?: CreatorProviderRequestLedger) {+async function fixture(ledger?: CreatorProviderRequestLedger, options: Partial<Parameters<typeof createGatewayCreatorSource>[0]> = {}) {const root = await mkdtemp(join(tmpdir(), 'oc-direct-')); cleanup.push(() => rm(root, { recursive: true, force: true }));const manual = createDefaultCreatorServicesConfig(); manual.llm = { source: 'custom', baseUrl: 'https://personal.test/v1', apiKey: 'personal-key', model: 'personal-model', jsonMode: true };const models: GatewayModel[] = [@@ -42,6 +42,7 @@ async function fixture(ledger?: CreatorProviderRequestLedger) {{ id: 'vendor/transcription', modality: 'transcription' as const, capabilities: [] }];const defaults = Object.fromEntries(models.map(model => [model.modality, model.id]));+ const reportModelFailure = vi.fn(async () => undefined);const state = { source: 'gateway' as 'gateway' | 'manual', authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: 'a:1', models, selectedModels: defaults, activationError: null };const fetcher = vi.fn(async (url: URL | RequestInfo, options?: RequestInit) => {if (String(url).endsWith('/videos')) return Response.json({ id: 'video_upstream', status: 'pending' });@@ -52,15 +53,15 @@ async function fixture(ledger?: CreatorProviderRequestLedger) {if (String(url).endsWith('/images')) return Response.json({ data: [{ b64_json: 'aW1hZ2U=' }] });return Response.json({ choices: [{ message: { content: 'text result' } }] });}) as typeof fetch;- const account: Pick<GatewayAccountService, 'peekState' | 'modelCredentials'> & Partial<Pick<GatewayAccountService, 'beginModelUse'>> = {- peekState: () => state, modelCredentials: async () => ({ accountId: 'a', bindingVersion: 'a:1', keyVersion: '1', modelKey: 'private-user-key', baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models, defaults })+ const account: Pick<GatewayAccountService, 'peekState' | 'modelCredentials'> & Partial<Pick<GatewayAccountService, 'beginModelUse' | 'reportModelFailure'>> = {+ reportModelFailure, peekState: () => state, modelCredentials: async () => ({ accountId: 'a', bindingVersion: 'a:1', keyVersion: '1', modelKey: 'private-user-key', baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models, defaults })};- const source = createGatewayCreatorSource({ directRequestsRoot: join(root, 'receipts'), ledger, account,+ const source = createGatewayCreatorSource({ ...options, directRequestsRoot: join(root, 'receipts'), ledger, account,manual: { read: async () => structuredClone(manual), write: async config => config, reset: async () => manual }, getLocalOrigin: () => 'http://127.0.0.1:39999', fetcher});const server = Fastify(); cleanup.push(() => server.close()); cleanup.push(() => source.revoke());await source.register(server); await registerCreatorServicesRoutes(server, source.store);- return { server, source, fetcher, state, manual, root, account };+ return { server, source, fetcher, state, manual, root, account, reportModelFailure };}it.each(['account', 'headers', 'first-token'])('opens the translation stream before slow %s preparation and reuses the completed result', async delayed => {const f = await fixture();@@ -135,6 +136,19 @@ it('reports rejected streaming translations without exposing upstream details',expect(response.body).not.toMatch(/OpenRouter|private-user-key|private failure/);await vi.waitFor(() => expect(f.source.isBusy()).toBe(false));});+it.each([+ ['images/generations', 'image'], ['audio/speech', 'speech'], ['audio/transcriptions', 'transcription'], ['video/jobs', 'video']+])('forwards exact model failure feedback from the real Creator route %s', async (resource, modality) => {+ const f = await fixture();+ const config = await f.source.store.read();+ vi.mocked(f.fetcher).mockImplementation(async () => Response.json({ error: { message: 'Model unavailable in this country private-user-key' } }, { status: 403 }));+ const response = await f.server.inject({ method: 'POST', url: `/internal/krillin-llm/gateway/v1/${resource}`, headers: { Authorization: `Bearer ${config.llm.apiKey}` },+ payload: { model: `vendor/${modality}`, prompt: 'test', input: 'test', voice: 'tested_voice', size: '1280x720', duration: 5 } });+ expect(response.statusCode).toBe(403);+ expect(response.body).not.toContain('private-user-key');+ expect(f.reportModelFailure).toHaveBeenCalledWith(expect.objectContaining({ accountId: 'a', keyVersion: '1' }), `vendor/${modality}`, modality,+ expect.objectContaining({ httpStatus: 403, upstreamMessage: 'Model unavailable in this country [redacted]' }));+});it('reconciles a streamed chat result without creating an unknown-acceptance issue', async () => {const root = await mkdtemp(join(tmpdir(), 'oc-direct-chat-ledger-'));const db = openRuntimeDatabase(join(root, 'runtime.sqlite'));@@ -175,7 +189,8 @@ it('sends multimodal requests directly, translates image edits, and replays a paexpect((await submit('chat/completions', { model: 'vendor/text', messages: [{ role: 'user', content: 'hello' }] })).statusCode).toBe(200);expect((await submit('images/generations', { model: 'vendor/image', prompt: 'image', n: 1, size: '1536x1024', response_format: 'b64_json' })).statusCode).toBe(200);const imageBody = JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body));- expect(imageBody).toMatchObject({ aspect_ratio: '3:2', output_format: 'png' });+ expect(imageBody).toMatchObject({ aspect_ratio: '3:2' });+ expect(imageBody).not.toHaveProperty('output_format');expect(imageBody).not.toHaveProperty('size'); expect(imageBody).not.toHaveProperty('response_format');expect((await submit('audio/speech', { model: 'vendor/speech', input: 'hello', voice: 'alloy', response_format: 'wav' })).headers['content-type']).toBe('audio/mpeg');expect(JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body)).response_format).toBe('mp3');@@ -227,9 +242,20 @@ it('uses the selected official speech model voice catalog and rejects incompatibawait expect(service.synthesize({ text: 'Hello', voiceId: 'alloy' })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });expect(synthesize).toHaveBeenCalledOnce();});+it('delivers a playable WAV for an official PCM-only speech model', async () => {+ const f = await fixture();+ f.state.models.find(model => model.modality === 'speech')!.capabilities = ['pcm_speech'];+ vi.mocked(f.fetcher).mockImplementation(async () => new Response(Buffer.from([0, 1, 0, 2]), { headers: { 'content-type': 'audio/pcm;rate=44100;channels=1' } }));+ const config = await f.source.store.read();+ const response = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/audio/speech', headers: { Authorization: `Bearer ${config.tts.openai.apiKey}`, 'Idempotency-Key': 'pcm' }, payload: { model: 'vendor/speech', input: 'Hello', voice: 'tested_voice' } });+ expect(response.statusCode).toBe(200);+ expect(response.headers['content-type']).toBe('audio/wav');+ expect(response.rawPayload.toString('ascii', 0, 4)).toBe('RIFF');+ expect(JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body))).toMatchObject({ response_format: 'pcm' });+});it.each(['cancelled', 'expired', 'failed'])('terminates video jobs with upstream status %s', async status => {const root = await mkdtemp(join(tmpdir(), 'oc-direct-video-')); cleanup.push(() => rm(root, { recursive: true, force: true }));- const fetcher = vi.fn(async (url: URL | RequestInfo) => Response.json(String(url).endsWith('/videos') ? { id: 'remote-video' } : { status }));+ const fetcher = vi.fn(async (url: URL | RequestInfo) => Response.json(String(url).endsWith('/videos') ? { id: 'remote-video', status: 'pending' } : { status }));const transport = createDirectTransport(root, fetcher);const input = { account: 'a', key: 'private', resource: 'video/jobs', method: 'POST', body: { model: 'video', prompt: 'test' }, contentType: 'application/json', identity: 'video', fingerprint: 'video', signal: AbortSignal.timeout(3000) };const { requestId } = await (await transport.request(input)).json();@@ -253,14 +279,14 @@ it('uses image model parameters and raster formats, and rejects invalid optionsconst model: GatewayModel = { id: 'image', modality: 'image', capabilities: [], imageOptions: { aspectRatios: ['16:9'], resolutions: ['2K'], qualities: [], outputFormats: ['jpeg'], maxImages: 1, maxReferences: 0 } };const input = { account: 'a', key: 'test', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'test', n: 1, size: '1024x1024', aspect_ratio: '16:9', resolution: '2K' }, contentType: 'application/json', identity: 'image', fingerprint: 'image', signal: AbortSignal.timeout(3_000), model };await transport.request(input);- expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'image', prompt: 'test', n: 1, aspect_ratio: '16:9', resolution: '2K', output_format: 'jpeg' });+ expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'image', prompt: 'test', n: 1, stream: false, aspect_ratio: '16:9', resolution: '2K', output_format: 'jpeg' });await expect(transport.request({ ...input, identity: 'invalid', fingerprint: 'invalid', body: { ...input.body, quality: 'high' } })).rejects.toMatchObject({ code: 'capability_unsupported' });expect(fetcher).toHaveBeenCalledOnce();});it('passes normalized resolution and ratio when the video catalog has no pixel sizes', async () => {const root = await mkdtemp(join(tmpdir(), 'oc-video-options-')); cleanup.push(() => rm(root, { recursive: true, force: true }));- const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ id: 'remote' }));+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ id: 'remote', status: 'pending' }));const model: GatewayModel = { id: 'video', modality: 'video', capabilities: [], resolutions: ['1080p'], aspectRatios: ['1:1'], durations: [12] };await createDirectTransport(root, fetcher).request({ account: 'a', key: 'test', resource: 'video/jobs', method: 'POST', body: { model: 'video', prompt: 'test', size: '1080p@1:1', duration: 12 }, contentType: 'application/json', identity: 'video', fingerprint: 'video', signal: AbortSignal.timeout(3_000), model });expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'video', prompt: 'test', resolution: '1080p', aspect_ratio: '1:1', duration: 12 });@@ -381,3 +407,60 @@ it('uses a local Runtime capability and stateless Responses with safe upstream eexpect(JSON.parse(String(fetcher.mock.lastCall?.[1]?.body))).toMatchObject({ store: false });expect((await fetch(`${runtime.baseUrl}/responses`, { method: 'POST', body: '{}' })).status).toBe(401);});++it('queries a saved paid image receipt and resolves related ledgers without resubmitting', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-query-paid-image-'));+ const db = openRuntimeDatabase(join(root, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const ledger = new CreatorProviderRequestLedger(repository);+ const f = await fixture(ledger);+ const job = repository.createJob({ projectId: 'project', templateId: 'image-generation', templateVersion: 2, status: 'failed', state: {} });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'failed' });+ try {+ const config = await f.source.store.read();+ const response = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/images/generations', headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Idempotency-Key': 'query-paid-image' }, payload: { model: 'vendor/image', prompt: 'test' } });+ expect(response.statusCode).toBe(200);+ const requestId = String(response.headers['x-request-id']);+ const register = (provider: string) => {+ const receipt = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, provider, requestKey: 'query-paid-image', request: {}, gateway: { accountId: 'a', bindingVersion: 'a:1', logicalId: 'query-paid-image' } });+ ledger.markSubmitting(receipt.id); ledger.markWaitingRemote(receipt.id, requestId);+ return ledger.markUnknownRemoteAcceptance(receipt.id);+ };+ const outer = register('opencreator-gateway-image');+ register('opencreator-gateway-images/generations');+ await f.source.queryProviderRequest(outer);+ expect(repository.listProviderRequests(job.id).map(receipt => receipt.status)).toEqual(['succeeded', 'succeeded']);+ expect(f.fetcher).toHaveBeenCalledOnce();+ await expect(f.source.queryProviderRequest({ ...outer, gateway: { ...outer.gateway!, accountId: 'different-account' } })).rejects.toMatchObject({ code: 'task_source_mismatch' });+ expect(f.fetcher).toHaveBeenCalledOnce();+ } finally { await f.source.revoke(); db.close(); await rm(root, { recursive: true, force: true }); }+});++it('replays an existing image after model quarantine and rejects new requests to that model', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-quarantined-media-'));+ const db = openRuntimeDatabase(join(root, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'image-generation', templateVersion: 2, status: 'failed', state: { officialModels: { image: 'vendor/image' } } });+ const original = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'failed' });+ const resumed = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'running', progress: { resumedFromStageRunId: original.id } });+ const f = await fixture(undefined, { readJobState: id => repository.getJob(id)?.state, readStageRun: repository.getStageRun,+ readJobBinding: () => ({ source: 'gateway', accountId: 'a', bindingVersion: 'a:1', models: { image: 'vendor/image', text: 'vendor/text' }, capabilities: { image: ['edit'] } }) });+ const origin = await f.server.listen({ host: '127.0.0.1', port: 0 });+ const image = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aC1sAAAAASUVORK5CYII=', 'base64');+ vi.mocked(f.fetcher).mockImplementation(async () => Response.json({ data: [{ b64_json: image.toString('base64') }] }));+ const generate = async () => {+ const config = await f.source.store.read(); config.image.openai.baseUrl = `${origin}/internal/krillin-llm/gateway/v1`;+ return generateImageContents({ provider: 'openai', prompt: 'test', size: '1024x1024', quality: 'medium', count: 1 }, config, { logicalId: 'quarantined-paid-image' });+ };+ try {+ await f.source.runForJob(job.id, original.id, generate);+ f.state.models.splice(f.state.models.findIndex(model => model.modality === 'image'), 1);+ expect((await f.source.runForJob(job.id, resumed.id, generate)).contents[0]!.content).toEqual(image);+ expect(f.fetcher).toHaveBeenCalledOnce();+ await expect(f.source.runForJob(job.id, original.id, generate)).rejects.toMatchObject({ code: 'invalid_model' });+ const config = await f.source.store.read();+ const response = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/images/generations', headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Idempotency-Key': 'new-quarantined-image' }, payload: { model: 'vendor/image', prompt: 'test' } });+ expect(response.statusCode).toBe(400);+ expect(f.fetcher).toHaveBeenCalledOnce();+ } finally { await f.source.revoke(); db.close(); await rm(root, { recursive: true, force: true }); }+});diff --git a/apps/daemon/test/integration/douyin-connection.test.ts b/apps/daemon/test/integration/douyin-connection.test.tsindex 7c2252a6..ce7af7bf 100644--- a/apps/daemon/test/integration/douyin-connection.test.ts+++ b/apps/daemon/test/integration/douyin-connection.test.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import Fastify from 'fastify';import { afterEach, expect, it, vi } from 'vitest';import { PlatformConnectionService } from '../../src/platform-connections/service.js';+import { PublicPlatformConnectionError } from '../../src/platform-connections/errors.js';import { filterPlatformCookies, hasPlatformSession, parsePlatformCookies, serializePlatformCookies } from '../../src/platform-connections/cookies.js';import { readBrowserPlatformCookies, type BrowserProfile } from '../../src/platform-connections/browser.js';import { registerPlatformConnectionRoutes } from '../../src/api/routes.platform-connections.js';@@ -60,6 +61,15 @@ it('connects without requiring a logged-in account and returns no credentials inif (process.platform !== 'win32') expect((await stat(join(root, 'credentials.json'))).mode & 0o777).toBe(0o600);});+it.each([+ [new PublicPlatformConnectionError('Allow macOS Keychain access and reconnect.'), 'Allow macOS Keychain access and reconnect.'],+ [new Error('Could not read /private/profile/Cookies with token=private'), 'Could not read the browser session. Try again or select another browser profile.']+])('preserves public connection guidance and filters internal errors: %s', async (error, message) => {+ const { service } = await setup(async () => { throw error; });+ await service.connect(profile.id);+ await vi.waitFor(async () => expect(await service.getState()).toMatchObject({ status: 'error', message }));+});+it('isolates concurrent task files and platform credentials and removes snapshots after failure', async () => {const { root, service } = await setup();const { service: youtube } = await setup(undefined, 'youtube');diff --git a/apps/daemon/test/integration/notification-api.test.ts b/apps/daemon/test/integration/notification-api.test.tsindex ec4cce6d..f839f218 100644--- a/apps/daemon/test/integration/notification-api.test.ts+++ b/apps/daemon/test/integration/notification-api.test.ts@@ -195,7 +195,7 @@ describe('notification outbox api', () => {expect(page.notifications).toEqual([expect.objectContaining({kind: 'schedule_waiting_approval',- title: '发布日报等待审批',+ title: '发布日报: awaiting approval',body: expect.stringContaining('写入发布目录'),threadId: schedule.threadId,runId: 'run_approval',diff --git a/apps/daemon/test/integration/project-api.test.ts b/apps/daemon/test/integration/project-api.test.tsindex a9b0e752..e026c701 100644--- a/apps/daemon/test/integration/project-api.test.ts+++ b/apps/daemon/test/integration/project-api.test.ts@@ -34,7 +34,7 @@ describe('project API', () => {expect(first.statusCode).toBe(200);expect(first.json().project).toMatchObject({- name: '默认项目',+ name: 'Default project',cwd: join(tempDir, 'OpenCreator', 'Default Project'),directoryState: 'available'});diff --git a/apps/daemon/test/integration/run-manager.test.ts b/apps/daemon/test/integration/run-manager.test.tsindex d730d0f1..b18d931e 100644--- a/apps/daemon/test/integration/run-manager.test.ts+++ b/apps/daemon/test/integration/run-manager.test.ts@@ -1624,7 +1624,7 @@ describe('run manager', () => {expect(rotationDiagnostics).toHaveLength(1);expect(rotationDiagnostics[0]).toMatchObject({payload: {- message: '执行上下文已重新连接',+ message: 'Execution context reconnected',details: {reason: 'resume_failed',previousCodexThreadId: 'codex-thread-old',diff --git a/apps/daemon/test/integration/video-metadata-api.test.ts b/apps/daemon/test/integration/video-metadata-api.test.tsindex f623597a..10b4bb80 100644--- a/apps/daemon/test/integration/video-metadata-api.test.ts+++ b/apps/daemon/test/integration/video-metadata-api.test.ts@@ -183,7 +183,7 @@ describe('video metadata API', () => {const url = 'https://www.bilibili.com/video/BV18E421w7bf?p=3';const response = await server.inject({ method: 'GET', url: `/video-metadata?${new URLSearchParams({ url })}` });expect(response.statusCode).toBe(400);- expect(response.json().error.message).toContain('分 P 3 不存在');+ expect(response.json().error.message).toContain('Video part 3 does not exist');});it('registers production metadata and prevents a multipart task from bypassing selection', async () => {diff --git a/apps/daemon/test/integration/youtube-connection.test.ts b/apps/daemon/test/integration/youtube-connection.test.tsindex ba7b9044..fa40d15a 100644--- a/apps/daemon/test/integration/youtube-connection.test.ts+++ b/apps/daemon/test/integration/youtube-connection.test.ts@@ -93,7 +93,7 @@ it.each(['cancel', 'timeout'] as const)('Windows 等待登录期间 %s 不保存await service.connect();await vi.waitFor(async () => expect((await service.getState()).actionRequired).toBe('complete-login'));if (mode === 'cancel') expect((await service.cancel()).status).toBe('disconnected');- else await vi.waitFor(async () => expect(await service.getState()).toMatchObject({ status: 'error', message: '连接已取消或超时,请重新连接。' }));+ else await vi.waitFor(async () => expect(await service.getState()).toMatchObject({ status: 'error', message: 'The connection was canceled or timed out. Connect again.' }));expect(read).not.toHaveBeenCalled();expect(login.session.close).toHaveBeenCalledTimes(1);expect(login.session.dispose).toHaveBeenCalledTimes(1);@@ -106,7 +106,7 @@ it('Windows 未登录不假成功,启动失败也不写入凭据', async () =>await service.connect();await vi.waitFor(async () => expect((await service.getState()).actionRequired).toBe('complete-login'));await service.completeLogin();- await vi.waitFor(async () => expect(await service.getState()).toMatchObject({ status: 'error', message: expect.stringContaining('尚未完成') }));+ await vi.waitFor(async () => expect(await service.getState()).toMatchObject({ status: 'error', message: expect.stringContaining('incomplete') }));await expect(access(join(root, 'credentials.json'))).rejects.toThrow();login.openLoginBrowser.mockRejectedValueOnce(new Error('无法打开 Chrome 登录窗口,请重试连接。'));await service.connect();diff --git a/apps/daemon/test/smoke/real-codex-smoke.test.ts b/apps/daemon/test/smoke/real-codex-smoke.test.tsindex 3e6a4716..89cd1ad4 100644--- a/apps/daemon/test/smoke/real-codex-smoke.test.ts+++ b/apps/daemon/test/smoke/real-codex-smoke.test.ts@@ -525,7 +525,7 @@ describe.runIf(runRealCodex)('real codex smoke', () => {expect(secondRun.codexThreadId).not.toBe(firstRun.codexThreadId);expect(second.events.body).toContain(ROTATION_SECOND_MARKER);expect(second.events.body).toContain('THREAD_CODEX_SESSION_ROTATED');- expect(second.events.body).toContain('执行上下文已重新连接');+ expect(second.events.body).toContain('Execution context reconnected');} finally {await server.close();rmSync(dataDir, { recursive: true, force: true });diff --git a/apps/daemon/test/unit/codex-local-provider.test.ts b/apps/daemon/test/unit/codex-local-provider.test.tsindex e1559b61..674654e4 100644--- a/apps/daemon/test/unit/codex-local-provider.test.ts+++ b/apps/daemon/test/unit/codex-local-provider.test.ts@@ -42,7 +42,7 @@ describe('local Codex provider', () => {it('does not silently route corrupted authentication to a configured API provider', async () => {root = await codexHome(['openai_base_url = "https://api.example.test/v1"']);await writeFile(join(root, 'auth.json'), '{corrupt');- await expect(readLocalCodexImageConfiguration({ codexHome: root })).rejects.toThrow('无法读取本机 Codex 登录凭据');+ await expect(readLocalCodexImageConfiguration({ codexHome: root })).rejects.toThrow('Could not read local Codex credentials');});it.each(['chatgpt', undefined])('recognizes OAuth credentials without treating them as API keys (%s)', async authMode => {@@ -56,7 +56,7 @@ describe('local Codex provider', () => {it('does not fall back to an old key when the selected ChatGPT login is incomplete', async () => {root = await codexHome(['openai_base_url = "https://api.example.test/v1"']);await writeFile(join(root, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt', OPENAI_API_KEY: 'old-secret' }));- await expect(readLocalCodexImageConfiguration({ codexHome: root })).rejects.toThrow('重新登录');+ await expect(readLocalCodexImageConfiguration({ codexHome: root })).rejects.toThrow('Sign in again');});it('reads the selected provider base URL and bearer token', async () => {diff --git a/apps/daemon/test/unit/codex-native-image.test.ts b/apps/daemon/test/unit/codex-native-image.test.tsindex 16fca0cf..d233bbdc 100644--- a/apps/daemon/test/unit/codex-native-image.test.ts+++ b/apps/daemon/test/unit/codex-native-image.test.ts@@ -54,7 +54,7 @@ describe('ChatGPT native image execution', () => {const error = await generateImageContents(request, createDefaultCreatorServicesConfig(), { codexNative: runtime(mode) }).catch(error => error);expect(error).toMatchObject({ code: 'upstream_error', publicFacts: {kind: 'validation', provider: 'codex-native', upstreamCode: 'IMAGE_REFERENCE_MISSING',- upstreamMessage: expect.stringContaining('参考图')+ upstreamMessage: expect.stringContaining('reference image')} });expect(JSON.stringify(error.publicFacts)).not.toContain('private-oauth-secret');});@@ -72,26 +72,26 @@ describe('ChatGPT native image execution', () => {return base.startExec(input).result;}) };});- await expect(generateCodexNativeImage({ runtime: { ...base, startExec }, request, referenceImages: [{ content: reference, mime: 'image/png' }], signal: new AbortController().signal })).rejects.toThrow('唯一的新图片');+ await expect(generateCodexNativeImage({ runtime: { ...base, startExec }, request, referenceImages: [{ content: reference, mime: 'image/png' }], signal: new AbortController().signal })).rejects.toThrow('instead of exactly one');await expect(readFile(join(workspace, 'reference-0.png'))).rejects.toMatchObject({ code: 'ENOENT' });});it('only discovers artifacts for the current thread and isolates concurrent requests', async () => {const [first, second] = await Promise.all(['thread-first', 'thread-second'].map(thread => generateCodexNativeImage({ runtime: runtime('home', thread), request, referenceImages: [], signal: new AbortController().signal })));expect(first!.content).toEqual(second!.content);- await expect(generateCodexNativeImage({ runtime: runtime('other-thread'), request, referenceImages: [], signal: new AbortController().signal })).rejects.toThrow('唯一的新图片');+ await expect(generateCodexNativeImage({ runtime: runtime('other-thread'), request, referenceImages: [], signal: new AbortController().signal })).rejects.toThrow('instead of exactly one');});it('rejects a thread directory symlink pointing to another thread', async () => {const generated = join(home, 'generated_images');await mkdir(join(generated, 'different-thread'), { recursive: true });await symlink(join(generated, 'different-thread'), join(generated, 'image-test-thread'));- await expect(generateCodexNativeImage({ runtime: runtime('home'), request, referenceImages: [], signal: new AbortController().signal })).rejects.toThrow('唯一的新图片');+ await expect(generateCodexNativeImage({ runtime: runtime('home'), request, referenceImages: [], signal: new AbortController().signal })).rejects.toThrow('instead of exactly one');});it.each([- ['text-only', '唯一的新图片'], ['old', '已有图片'], ['outside', '不属于当前生图任务'],- ['symlink', '不属于当前生图任务'], ['invalid', '不是受支持'], ['failure', '重新登录'], ['quota', '额度']+ ['text-only', 'instead of exactly one'], ['old', 'existing image'], ['outside', 'does not belong to this task'],+ ['symlink', 'does not belong to this task'], ['invalid', 'not a supported'], ['failure', 'Sign in again'], ['quota', 'quota']])('rejects unsafe or unsuccessful results (%s)', async (mode, message) => {await expect(generateCodexNativeImage({ runtime: runtime(mode), request, referenceImages: [], signal: new AbortController().signal })).rejects.toThrow(message);});@@ -112,7 +112,7 @@ describe('ChatGPT native image execution', () => {await expect(generateCodexNativeImage({runtime: { ...base, startExec: () => ({ cancel() {}, result: Promise.reject(new CodexExecError({ message: 'timeout token=private-oauth-secret', terminationReason: 'timeout', stdoutLines: [], stderr: '' })) }) },request, referenceImages: [], signal: new AbortController().signal- })).rejects.toThrow('原生生图超时');+ })).rejects.toThrow('native image generation timed out');});});@@ -143,14 +143,14 @@ describe('Codex authentication dispatch and readiness', () => {it('does not fall back to HTTP after a native failure', async () => {const fetchImpl = vi.fn();const task = generateImageContents(request, createDefaultCreatorServicesConfig(), { codexNative: runtime('failure'), fetchImpl });- await expect(task).rejects.toMatchObject({ code: 'upstream_error', message: expect.stringContaining('重新登录') });+ await expect(task).rejects.toMatchObject({ code: 'upstream_error', message: expect.stringContaining('Sign in again') });expect(fetchImpl).not.toHaveBeenCalled();});it('blocks native execution when Runtime capability is missing', async () => {const startExec = vi.fn(runtime().startExec);const codexNative = { ...runtime(), startExec, checkNativeCapability: async () => ({ supported: false, version: 'old-runtime' }) };- await expect(generateImageContents(request, createDefaultCreatorServicesConfig(), { codexNative })).rejects.toMatchObject({ code: 'config_missing', message: expect.stringContaining('不支持原生生图') });+ await expect(generateImageContents(request, createDefaultCreatorServicesConfig(), { codexNative })).rejects.toMatchObject({ code: 'config_missing', message: expect.stringContaining('does not support native image generation') });expect(startExec).not.toHaveBeenCalled();await expect(inspectCodexImageRuntime(codexNative)).resolves.toMatchObject({ authentication: 'chatgpt', ready: false, executionMode: null });});@@ -168,6 +168,6 @@ describe('Codex authentication dispatch and readiness', () => {});it('blocks ChatGPT mode without a Codex executable', async () => {- await expect(inspectCodexImageRuntime({ codexHome: home })).resolves.toMatchObject({ authentication: 'chatgpt', ready: false, message: expect.stringContaining('缺少 Codex') });+ await expect(inspectCodexImageRuntime({ codexHome: home })).resolves.toMatchObject({ authentication: 'chatgpt', ready: false, message: expect.stringContaining('Codex executable is missing') });});});diff --git a/apps/daemon/test/unit/codex-provider-config.test.ts b/apps/daemon/test/unit/codex-provider-config.test.tsindex e1dd229d..ebc2a62d 100644--- a/apps/daemon/test/unit/codex-provider-config.test.ts+++ b/apps/daemon/test/unit/codex-provider-config.test.ts@@ -295,7 +295,7 @@ describe('Codex provider configuration', () => {await expect(service.update({baseUrl: 'https://api.deepseek.com',model: 'deepseek-chat'- })).rejects.toThrow('自定义 Base URL 需要 API Key 登录');+ })).rejects.toThrow('A custom Base URL requires API key authentication');expect(client.restart).not.toHaveBeenCalled();});diff --git a/apps/daemon/test/unit/codex-sessions-scanner.test.ts b/apps/daemon/test/unit/codex-sessions-scanner.test.tsindex 5ecfb1bc..bbc0d872 100644--- a/apps/daemon/test/unit/codex-sessions-scanner.test.ts+++ b/apps/daemon/test/unit/codex-sessions-scanner.test.ts@@ -217,7 +217,7 @@ describe('codex sessions scanner', () => {expect(sessions).toEqual([expect.objectContaining({codexThreadId: 'large-session',- title: '未命名对话',+ title: 'Untitled conversation',updatedAt: modifiedAt.toISOString()})]);diff --git a/apps/daemon/test/unit/codex-status.test.ts b/apps/daemon/test/unit/codex-status.test.tsindex 6db2ee80..384049a6 100644--- a/apps/daemon/test/unit/codex-status.test.ts+++ b/apps/daemon/test/unit/codex-status.test.ts@@ -109,7 +109,7 @@ describe('codex status response builder', () => {errorCode: 'CODEX_PROBE_EXIT_NON_ZERO'});expect(response.diagnostics).toEqual([- 'Codex 后台可用性验证失败:尚未登录'+ 'Codex background availability verification failed: 尚未登录']);});});diff --git a/apps/daemon/test/unit/conversation-title.test.ts b/apps/daemon/test/unit/conversation-title.test.tsindex a9e3870a..9ff52fdf 100644--- a/apps/daemon/test/unit/conversation-title.test.ts+++ b/apps/daemon/test/unit/conversation-title.test.ts@@ -22,7 +22,7 @@ describe('createConversationTitle', () => {it('uses a concise compatibility title for truncated legacy assistant prompts', () => {expect(createConversationTitle('你是 OpenCreator 的计划任务配置助手。 不要调用工具,不要修改文件,只根据用户描述生成一个计划任务草稿。 用户所在时区:Asia/Shanghai 只输出一…'- )).toBe('创建计划任务');+ )).toBe('Create scheduled task');});it('removes attachment metadata and uses the user request', () => {@@ -44,8 +44,8 @@ describe('createConversationTitle', () => {it('uses a short fallback for attachment-only and blank requests', () => {expect(createConversationTitle('# Files mentioned by the user:\n\n## image.png: /tmp/image.png'))- .toBe('查看附件');- expect(createConversationTitle(' ')).toBe('新对话');+ .toBe('View attachments');+ expect(createConversationTitle(' ')).toBe('New conversation');});it('limits long titles by visual width', () => {diff --git a/apps/daemon/test/unit/creator-command-dispatcher.test.ts b/apps/daemon/test/unit/creator-command-dispatcher.test.tsindex 8570bd5d..aa3c034a 100644--- a/apps/daemon/test/unit/creator-command-dispatcher.test.ts+++ b/apps/daemon/test/unit/creator-command-dispatcher.test.ts@@ -11,6 +11,7 @@ import { createCreatorRepository } from '../../src/creator/repository.js';import { createCreatorService } from '../../src/creator/service.js';import { createDefaultCreatorTemplateRegistry } from '../../src/creator/templates/registry.js';import { openRuntimeDatabase } from '../../src/storage/database.js';+import { CreatorProviderRequestLedger } from '../../src/creator/provider-requests.js';let tempDir = '';@@ -20,6 +21,72 @@ afterEach(() => {});describe('creator command dispatcher', () => {+ it('queues video retries once and retains the original media request identity', () => {+ const fixture = setup();+ try {+ const job = fixture.service.createJob({ projectId: 'project', templateId: 'video-generation', state: { prompt: 'test' } });+ const original = fixture.repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'failed' });+ const wake = vi.fn();+ const dispatcher = createCreatorCommandDispatcher({ service: fixture.service, repository: fixture.repository, receipts: fixture.receipts, onQueuedStage: wake });+ const command = { action: 'retry-stage', expectedRevision: job.revision, idempotencyKey: 'retry-video', input: { stageId: 'generate' } };+ const first = dispatcher.dispatch(job.id, command, 'user');+ const replay = dispatcher.dispatch(job.id, command, 'user');+ expect(first.commandReceipt.stageRunId).toBe(replay.commandReceipt.stageRunId);+ expect(first.job.stages.find(stage => stage.id === first.commandReceipt.stageRunId)).toMatchObject({ status: 'queued', progress: { resumedFromStageRunId: original.id } });+ expect(fixture.repository.getJob(job.id)!.stages).toHaveLength(2);+ expect(wake).toHaveBeenCalledOnce();+ } finally { fixture.db.close(); }+ });++ it('gives a definitively failed video a new attempt instead of replaying its failure', () => {+ const fixture = setup();+ try {+ const job = fixture.service.createJob({ projectId: 'project', templateId: 'video-generation', state: { prompt: 'test' } });+ const original = fixture.repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'failed' });+ const ledger = new CreatorProviderRequestLedger(fixture.repository);+ const receipt = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: original.id, provider: 'opencreator-gateway-video', requestKey: 'rejected-video', request: {} });+ ledger.markSubmitting(receipt.id); ledger.markFailed(receipt.id);+ const dispatcher = createCreatorCommandDispatcher({ service: fixture.service, repository: fixture.repository, receipts: fixture.receipts });+ const result = dispatcher.dispatch(job.id, { action: 'retry-stage', expectedRevision: job.revision, idempotencyKey: 'retry-rejected-video', input: { stageId: 'generate' } }, 'user');+ expect(result.job.stages.find(stage => stage.id === result.commandReceipt.stageRunId)?.progress).not.toHaveProperty('resumedFromStageRunId');+ } finally { fixture.db.close(); }+ });++ it('performs request lookup before committing a query and replays it without querying again', async () => {+ const fixture = setup();+ try {+ const job = fixture.service.createJob({ projectId: 'project', templateId: 'image-generation', state: { prompt: 'test' } });+ const stage = fixture.repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'failed' });+ const ledger = new CreatorProviderRequestLedger(fixture.repository);+ const receipt = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, provider: 'image', requestKey: 'paid', request: {} });+ ledger.markSubmitting(receipt.id); ledger.markUnknownRemoteAcceptance(receipt.id);+ const query = vi.fn(async () => { await ledger.recover(receipt.id, { lookupByRequestKey: true, lookup: async () => ({ status: 'failed' }) }); });+ const dispatcher = createCreatorCommandDispatcher({ service: fixture.service, repository: fixture.repository, receipts: fixture.receipts, queryProviderRequest: query });+ const command = { action: 'resolve-provider-request', expectedRevision: job.revision, idempotencyKey: 'query-paid', input: { ledgerId: receipt.id, decision: 'query' } };+ await expect(dispatcher.dispatchAsync(job.id, { ...command, expectedRevision: 99 }, 'user')).rejects.toMatchObject({ code: 'creator_revision_conflict' });+ expect(query).not.toHaveBeenCalled();+ expect(() => dispatcher.dispatch(job.id, command, 'user')).toThrow('asynchronous dispatch');+ const first = await dispatcher.dispatchAsync(job.id, command, 'user');+ expect(first.job).toMatchObject({ status: 'failed', providerRequests: [{ status: 'failed' }] });+ expect((await dispatcher.dispatchAsync(job.id, command, 'user')).commandReceipt.status).toBe('replayed');+ expect(query).toHaveBeenCalledOnce();+ } finally { fixture.db.close(); }+ });++ it('keeps unknown media requests blocked after an inconclusive query', async () => {+ const fixture = setup();+ try {+ const job = fixture.service.createJob({ projectId: 'project', templateId: 'video-generation', state: { prompt: 'test' } });+ const stage = fixture.repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'failed' });+ const ledger = new CreatorProviderRequestLedger(fixture.repository);+ const receipt = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, provider: 'video', requestKey: 'paid', request: {} });+ ledger.markSubmitting(receipt.id); ledger.markUnknownRemoteAcceptance(receipt.id);+ const dispatcher = createCreatorCommandDispatcher({ service: fixture.service, repository: fixture.repository, receipts: fixture.receipts, queryProviderRequest: async () => {} });+ const result = await dispatcher.dispatchAsync(job.id, { action: 'resolve-provider-request', expectedRevision: job.revision, idempotencyKey: 'query', input: { ledgerId: receipt.id, decision: 'query' } }, 'user');+ for (const action of ['run-stage', 'retry-stage']) expect(() => dispatcher.dispatch(job.id, { action, expectedRevision: result.job.revision, idempotencyKey: action, input: { stageId: 'generate' } }, 'user')).toThrow('request');+ expect(result.job.providerRequests[0]!.status).toBe('unknown_remote_acceptance');+ } finally { fixture.db.close(); }+ });it('imports subtitle versions through user and agent commands and invalidates only dependencies', () => {const fixture = setup();try {diff --git a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.tsindex 27a010dc..e80e018a 100644--- a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts+++ b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts@@ -111,7 +111,7 @@ describe('KrillinAI configured transcription dependency', () => {expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({phase: 'fallback_to_transcription', providerStatus: 'running',captionSource: 'whisper', captionFallbackCode: code,- message: expect.stringContaining('已自动切换到语音转录')+ message: expect.stringContaining('Switched to speech transcription.')}));expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({phase: 'transcribing_audio', percent: 55, captionFallbackCode: code, captionSource: 'whisper'@@ -161,7 +161,7 @@ describe('KrillinAI configured transcription dependency', () => {expect(stage.reportProgress).not.toHaveBeenCalledWith(expect.objectContaining({ providerStatus: 'failed' }));expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({phase: 'downloading_dependencies', captionFallbackCode: 'platform_caption_invalid',- message: expect.stringContaining('平台字幕解析失败,已自动切换到语音转录')+ message: expect.stringContaining('Platform subtitle parsing failed. Switched to speech transcription.')}));});diff --git a/apps/daemon/test/unit/creator-local-components.test.ts b/apps/daemon/test/unit/creator-local-components.test.tsindex faef3c14..99a99928 100644--- a/apps/daemon/test/unit/creator-local-components.test.ts+++ b/apps/daemon/test/unit/creator-local-components.test.ts@@ -100,7 +100,7 @@ describe('shared local transcription components', () => {test.finish();await task;expect(test.install).toHaveBeenCalledOnce();- expect(listener).toHaveBeenCalledWith(expect.objectContaining({ phase: 'dependencies_ready', message: expect.stringContaining('开始语音转录') }));+ expect(listener).toHaveBeenCalledWith(expect.objectContaining({ phase: 'dependencies_ready', message: expect.stringContaining('Starting transcription') }));expect((await test.loader.status(test.config)).components.find(component => component.id === 'whisperkit')).toMatchObject({ state: 'ready', version: '1.1.0' });test.loader.close();});diff --git a/apps/daemon/test/unit/creator-preflight.test.ts b/apps/daemon/test/unit/creator-preflight.test.tsindex 64d09edd..5700f9ad 100644--- a/apps/daemon/test/unit/creator-preflight.test.ts+++ b/apps/daemon/test/unit/creator-preflight.test.ts@@ -31,7 +31,7 @@ describe('creator preflight', () => {const job = fakeJob('stickman-video', { provider: 'gemini' });job.artifacts = ['character_reference', 'style_reference'].map((kind, i) => ({ id: `ref-${i}`, jobId: job.id, kind, version: 1, scopeKey: null, inputFingerprint: null, sourceArtifactIds: [], path: join(root, `${i}.png`), status: 'completed', metadata: {}, sha256: 'hash', producerStageRunId: null, createdAt: job.createdAt, updatedAt: job.updatedAt }));const result = await createCreatorPreflight({ configStore: source.store, readCapabilities: () => createKrillinCreatorServicesCapabilities('darwin', 'arm64'), resourceRoot: root, jobsRoot: join(root, 'jobs'), validateRuntimeAssets: false }).check(job, createStickmanVideoTemplate().stages.find(stage => stage.executor === 'stickman-image')!);- expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'reference-image-count', message: expect.stringContaining('1 张') }));+ expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'reference-image-count', message: expect.stringContaining('one reference image') }));});it.each(['reference', 'speech-style'])('blocks unverified official %s before executing', async feature => {root = await mkdtemp(join(tmpdir(), 'creator-official-capability-'));@@ -57,7 +57,7 @@ describe('creator preflight', () => {const job = fakeJob('image-generation', { provider, prompt: '以上传的人物照片为唯一主体,生成复古海报', referenceImageArtifactId: 'missing-artifact' });const result = await check.check(job, createImageGenerationTemplate().stages[0]!);expect(result.canStart).toBe(false);- expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'reference-image-required', message: expect.stringContaining('上传参考图') }));+ expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'reference-image-required', message: expect.stringContaining('Upload a reference image') }));expect(new CreatorPreflightError(result)).toMatchObject({ code: 'creator_stage_input_missing', publicFacts: { kind: 'validation', upstreamCode: 'IMAGE_REFERENCE_MISSING' } });});it('allows rendering to prepare an installable Remotion component without downloading during preflight', async () => {@@ -72,7 +72,7 @@ describe('creator preflight', () => {}).check(fakeJob('stickman-video', {}), stage);expect(status).toHaveBeenCalledOnce();expect(result.blocked.map(item => item.id)).not.toContain('stickman-runtime');- expect(result.warning).toContainEqual(expect.objectContaining({ id: 'stickman-runtime', message: expect.stringContaining('按需准备') }));+ expect(result.warning).toContainEqual(expect.objectContaining({ id: 'stickman-runtime', message: expect.stringContaining('prepared on demand') }));});it('prepares preview from the saved Bilibili source without translation or Whisper credentials', async () => {@@ -115,7 +115,7 @@ describe('creator preflight', () => {}).check(job, createVideoTranslationTemplate().stages.find(stage => stage.id === 'subtitle')!);if (part === undefined) {expect(result.canStart).toBe(false);- expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'bilibili-part', message: expect.stringContaining('选择要翻译的分集') }));+ expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'bilibili-part', message: expect.stringContaining('Select the part to translate') }));} else {expect(result.blocked.map(item => item.id)).not.toContain('bilibili-part');}diff --git a/apps/daemon/test/unit/creator-provider-requests.test.ts b/apps/daemon/test/unit/creator-provider-requests.test.tsindex a06743c1..678f4f22 100644--- a/apps/daemon/test/unit/creator-provider-requests.test.ts+++ b/apps/daemon/test/unit/creator-provider-requests.test.ts@@ -47,6 +47,15 @@ function setup(path = join(tempDir, 'runtime.sqlite')) {}describe('creator provider request ledger', () => {+ it.each(['succeeded', 'failed', 'waiting_remote'] as const)('reconciles a registered request with authoritative lookup evidence (%s)', async status => {+ tempDir = mkdtempSync(join(tmpdir(), 'creator-registered-recovery-'));+ const { db, job, stage, ledger } = setup();+ try {+ const request = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, provider: 'image', requestKey: 'recover-registered', request: {} });+ const recovered = await ledger.recover(request.id, { lookupByRequestKey: true, lookup: async () => ({ status, remoteTaskId: 'original-remote' }) });+ expect(recovered).toMatchObject({ status, remoteTaskId: 'original-remote' });+ } finally { db.close(); }+ });it('closes the matching unknown-receipt issue only after all requests in its scope are recovered', async () => {tempDir = mkdtempSync(join(tmpdir(), 'creator-provider-stream-recovery-'));const { db, repository, job, stage } = setup();diff --git a/apps/daemon/test/unit/creator-video-executor.test.ts b/apps/daemon/test/unit/creator-video-executor.test.tsindex 9f368e9e..dff6a518 100644--- a/apps/daemon/test/unit/creator-video-executor.test.ts+++ b/apps/daemon/test/unit/creator-video-executor.test.ts@@ -26,6 +26,44 @@ afterEach(async () => {});describe('creator video executor', () => {+ it('submits a fresh video after the previous saved attempt was definitively rejected', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-video-retry-rejected-'));+ const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));+ try {+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'video-generation', templateVersion: 1, status: 'running', state: stageInput({}, []).job.state });+ const previous = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'failed', progress: { videoGenerationResultId: 'rejected-video-result' } });+ repository.updateStageRun({ id: previous.id, status: 'failed', errorCode: 'creator_video_upstream_error', errorMessage: 'Rejected' });+ const current = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'running' });+ const ledger = new CreatorProviderRequestLedger(repository);+ const receipt = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: previous.id, provider: 'opencreator-gateway-video', requestKey: previous.id, request: {} });+ ledger.markSubmitting(receipt.id); ledger.markFailed(receipt.id);+ const service = videoService({});+ const stage = stageInput({}, []); stage.job = repository.getJob(job.id)!; stage.stageRun = current;+ await createVideoExecutor({ ledger, service, probeVideo: async () => ({ duration: 5, width: 1280, height: 720, hasVideo: true, hasAudio: false }) }).run(stage);+ expect(service.create).toHaveBeenCalledOnce();+ expect(service.get).not.toHaveBeenCalled();+ } finally { db.close(); }+ });+ it.each([400, 402, 422, 429])('finalizes a rejected video submission instead of blocking it as unknown (%s)', async status => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-video-rejection-'));+ const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));+ try {+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'video-generation', templateVersion: 1, status: 'running', state: {} });+ const stageRun = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'running' });+ const stage = stageInput({}, []); stage.job.id = job.id; stage.stageRun.id = stageRun.id;+ const ledger = new CreatorProviderRequestLedger(repository);+ const service = videoService({ create: vi.fn(async (_request, options) => {+ options!.onGatewayBinding!({ accountId: 'a', bindingVersion: 'a:1', logicalId: stageRun.id });+ throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', 'Rejected', 502, { kind: 'http-rejected', httpStatus: status });+ }) });+ const executor = createVideoExecutor({ ledger, service, probeVideo: vi.fn() });+ await expect(executor.run(stage)).rejects.toMatchObject({ code: 'creator_video_upstream_error' });+ expect(repository.getJob(job.id)!.providerRequests).toMatchObject([{ status: 'failed' }]);+ expect(ledger.unresolvedForStage({ jobId: job.id, stageId: 'generate' })).toEqual([]);+ } finally { db.close(); }+ });it('recovers exactly the original video ledger entry among multiple pending requests', async () => {tempDir = await mkdtemp(join(tmpdir(), 'creator-video-recover-ledger-'));const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));diff --git a/apps/daemon/test/unit/creator-video-translation-workflow.test.ts b/apps/daemon/test/unit/creator-video-translation-workflow.test.tsindex 8665c02a..82b3d1cc 100644--- a/apps/daemon/test/unit/creator-video-translation-workflow.test.ts+++ b/apps/daemon/test/unit/creator-video-translation-workflow.test.ts@@ -51,7 +51,7 @@ describe('video translation workflow', () => {videoMetadataService: { get: async () => { throw new Error('network unavailable'); } } });try {await expect(workflow.validateStage(fixture.service.getJob(fixture.jobId)!, 'subtitle'))- .rejects.toMatchObject({ code: 'creator_source_metadata_unavailable', message: expect.stringContaining('未启动下载或翻译') });+ .rejects.toMatchObject({ code: 'creator_source_metadata_unavailable', message: expect.stringContaining('Download and translation have not started') });expect(fixture.service.getJob(fixture.jobId)!.stages).toHaveLength(0);} finally { fixture.db.close(); }});diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.tsindex 612465a8..613df997 100644--- a/apps/daemon/test/unit/gateway-account-service.test.ts+++ b/apps/daemon/test/unit/gateway-account-service.test.ts@@ -534,13 +534,14 @@ it('checks on foreground return without bypassing polling intervals or slow-down} finally { clock.mockRestore(); await f.service.close(); }});-it('silently filters official families without blocking model selection or changing the raw candidate catalog', async () => {+it('admits exact verified models and preserves the raw candidate catalog', async () => {let finishProbe!: () => void;const waiting = new Promise<void>(resolve => { finishProbe = resolve; });const requests: string[] = [];const f = await setup(undefined, undefined, undefined, undefined, (root, readProbeCredentials) => createOfficialModelAccess({dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ if (String(url).includes('/models/user?')) return Response.json({ data: raw.models });expect(new Headers(options?.headers).get('authorization')).toBe('Bearer platform-probe-key');const model = JSON.parse(String(options?.body)).model; requests.push(model);await waiting;@@ -559,14 +560,23 @@ it('silently filters official families without blocking model selection or chang});const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);await expect.poll(() => requests.length).toBeGreaterThan(0);- expect(f.service.peekState().activationState).toBe('ready');- await f.service.selectModel('text', 'deepseek/deepseek-r1');+ expect(f.service.peekState().activationState).toBe('blocked');+ await expect(f.service.selectModel('text', 'deepseek/deepseek-r1')).rejects.toMatchObject({ code: 'invalid_model' });finishProbe();await expect.poll(() => f.service.peekState().models.some(model => model.id === 'qwen/qwen3-coder')).toBe(true);+ await f.service.selectModel('text', 'deepseek/deepseek-r1');expect(f.service.peekState().models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'deepseek/deepseek-r1', 'qwen/qwen3-coder']);expect(f.service.peekState().selectedModels?.text).toBe('deepseek/deepseek-r1');await expect(f.service.selectModel('text', 'openai/gpt-6-sol')).rejects.toMatchObject({ code: 'invalid_model' });expect((await f.service.modelCredentials()).models).toEqual(f.service.peekState().models);+ const scope = await f.service.modelCredentials();+ const facts = { kind: 'http-rejected' as const, httpStatus: 403, upstreamMessage: 'Model unavailable in this country' };+ await f.service.reportModelFailure({ ...scope, accountId: 'stale-account' }, 'qwen/qwen3-coder', 'text', facts);+ expect(f.service.peekState().models).toHaveLength(3);+ await f.service.reportModelFailure(scope, 'deepseek/deepseek-r1', 'text', facts);+ expect(f.service.peekState().models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'qwen/qwen3-coder']);+ expect((await f.service.readState()).selectedModels?.text).toBe('deepseek/deepseek-v3.2');+ await expect(f.service.selectModel('text', 'deepseek/deepseek-r1')).rejects.toMatchObject({ code: 'invalid_model' });expect((await createGatewayConfigStore(f.root).readCredentials())?.models).toHaveLength(6);expect(usage.some(value => value.busy)).toBe(false);await f.service.close();@@ -580,6 +590,7 @@ it('defers a blocked default replacement until idle and recovers after every famconst f = await setup(undefined, undefined, undefined, () => active, (root, readProbeCredentials) => createOfficialModelAccess({dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ if (String(url).includes('/models/user?')) return Response.json({ data: raw.models });await waiting;const model = JSON.parse(String(options?.body)).model;return !recover && (model.startsWith('openai/') || denyFallback)@@ -596,7 +607,7 @@ it('defers a blocked default replacement until idle and recovers after every famconst grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);active = true; finishProbe();await expect.poll(() => f.service.peekState().selectedModels?.text).toBe('deepseek/deepseek-v3.2');- expect(f.activate).toHaveBeenCalledOnce();+ expect(f.activate).not.toHaveBeenCalled();active = false;expect(await f.service.readState()).toMatchObject({ activationState: 'ready', selectedModels: { text: 'deepseek/deepseek-v3.2' } });expect(f.activate).toHaveBeenLastCalledWith(expect.objectContaining({ defaults: { text: 'deepseek/deepseek-v3.2' } }));@@ -606,12 +617,19 @@ it('defers a blocked default replacement until idle and recovers after every famawait f.service.readState();await expect.poll(() => f.service.peekState().activationState).toBe('blocked');await expect(f.service.modelCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });+ await expect.poll(async () => {+ const cache = JSON.parse(await readFile(join(f.root, 'config/gateway-model-access.json'), 'utf8')) as { models: Record<string, { status: string; nextCheck: number }> };+ return Object.values(cache.models).length === 2 && Object.values(cache.models).every(entry => entry.status === 'blocked' && entry.nextCheck > Date.now());+ }).toBe(true);+ const recoveryUse = await f.service.beginModelUse({ recovery: true });+ expect(recoveryUse.credentials.models).toEqual([]);+ await recoveryUse.release();recover = true; clock.mockReturnValue(start + 25 * 60 * 60_000 + 2);await f.service.readState();- await expect.poll(() => f.service.peekState().activationState).toBe('ready');+ await expect.poll(async () => (await f.service.readState()).activationState).toBe('ready');expect(f.service.peekState().bindingVersion).toBe(raw.bindingVersion);expect((await f.service.modelCredentials()).defaults.text).toBeTruthy();- expect(f.activate).toHaveBeenCalledTimes(3);+ expect(f.activate).toHaveBeenCalledTimes(2);} finally { clock.mockRestore(); await f.service.close(); }});@@ -620,6 +638,7 @@ it('aborts an in-flight availability check on logout without applying a late resconst f = await setup(undefined, undefined, undefined, undefined, (root, readProbeCredentials) => createOfficialModelAccess({dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ if (String(url).includes('/models/user?')) return Response.json({ data: raw.models });started = true;return new Promise<Response>(resolve => options!.signal!.addEventListener('abort', () => {aborted = true;@@ -636,7 +655,7 @@ it('aborts an in-flight availability check on logout without applying a late resexpect(aborted).toBe(true);expect(f.service.peekState()).toMatchObject({ authState: 'signed_out', activationState: 'inactive', models: [] });expect(await createGatewayConfigStore(f.root).readCredentials()).toBeUndefined();- expect(f.activate).toHaveBeenCalledOnce();+ expect(f.activate).not.toHaveBeenCalled();await f.service.close();});diff --git a/apps/daemon/test/unit/gateway-direct-audio.test.ts b/apps/daemon/test/unit/gateway-direct-audio.test.tsnew file mode 100644index 00000000..3737f1bf--- /dev/null+++ b/apps/daemon/test/unit/gateway-direct-audio.test.ts@@ -0,0 +1,67 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it, vi } from 'vitest';+import { createDirectTransport } from '../../src/gateway/direct-transport.js';+import { readPrivateJsonFile } from '../../src/config/private-json-file.js';++const roots: string[] = [];+afterEach(async () => { for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); });+async function fixture(contentType = 'audio/pcm;rate=44100;channels=1') {+ const root = await mkdtemp(join(tmpdir(), 'oc-audio-')); roots.push(root);+ const pcm = Buffer.from([0, 1, 0, 2]);+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => new Response(pcm, { headers: { 'content-type': contentType, 'x-generation-id': 'gen-tts-audio-test' } }));+ const transport = createDirectTransport(root, fetcher);+ const input = { account: 'audio', key: 'private-test-key', resource: 'audio/speech', method: 'POST', body: { model: 'pcm-model', input: 'Hello', voice: 'voice', response_format: 'wav' }, contentType: 'application/json', identity: 'request', fingerprint: 'fingerprint', signal: AbortSignal.timeout(3_000), model: { id: 'pcm-model', modality: 'speech' as const, capabilities: ['pcm_speech'] } };+ return { root, pcm, fetcher, transport, input };+}++it('wraps documented PCM metadata in a playable WAV and replays without another synthesis', async () => {+ const f = await fixture();+ const response = await f.transport.request(f.input);+ const wav = Buffer.from(await response.arrayBuffer());+ expect(JSON.parse(String(f.fetcher.mock.calls[0]?.[1]?.body))).toMatchObject({ response_format: 'pcm' });+ expect(response.headers.get('content-type')).toBe('audio/wav');+ expect(wav.toString('ascii', 0, 4)).toBe('RIFF');+ expect(wav.toString('ascii', 8, 16)).toBe('WAVEfmt ');+ expect(wav.readUInt16LE(22)).toBe(1); expect(wav.readUInt32LE(24)).toBe(44100);+ expect(wav.readUInt16LE(34)).toBe(16); expect(wav.readUInt32LE(40)).toBe(f.pcm.length);+ expect(wav.subarray(44)).toEqual(f.pcm);+ const id = response.headers.get('x-request-id')!;+ expect(await readPrivateJsonFile(join(f.root, `${id}.json`))).toMatchObject({ state: 'succeeded', mime: 'audio/wav', upstreamGenerationId: 'gen-tts-audio-test' });+ const replay = await createDirectTransport(f.root, f.fetcher).request(f.input);+ expect(Buffer.from(await replay.arrayBuffer())).toEqual(wav);+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it.each(['audio/pcm', 'audio/pcm;rate=44100', 'audio/pcm;rate=999999;channels=1', 'audio/pcm;rate=44100;channels=3'])('rejects unusable PCM metadata without guessing a playback rate: %s', async mime => {+ const f = await fixture(mime);+ await expect(f.transport.request(f.input)).rejects.toMatchObject({ code: 'invalid_gateway_response' });+ await expect(createDirectTransport(f.root, f.fetcher).request(f.input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('retains real transcription generation identity and reported cost without changing the payload', async () => {+ const f = await fixture();+ const payload = { text: 'Hello', usage: { cost: 0.00015 }, segments: [{ start: 0, end: 1, text: 'Hello' }] };+ f.fetcher.mockImplementation(async () => Response.json(payload, { headers: { 'x-generation-id': 'gen-stt-audio-test' } }));+ const response = await f.transport.request({ ...f.input, resource: 'audio/transcriptions', model: { id: 'asr', modality: 'transcription', capabilities: [] }, body: { model: 'asr', input: 'fixture' } });+ expect(await response.json()).toEqual(payload);+ expect(await readPrivateJsonFile(join(f.root, `${response.headers.get('x-request-id')}.json`))).toMatchObject({ upstreamGenerationId: 'gen-stt-audio-test', reportedCostUsd: 0.00015, state: 'succeeded' });+});++it('does not mark a subtitle transcription successful when timestamps are missing', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ text: 'Hello' }));+ const input = { ...f.input, resource: 'audio/transcriptions', model: { id: 'asr', modality: 'transcription' as const, capabilities: ['subtitle_timestamps'] }, body: { model: 'asr', input: 'fixture' } };+ await expect(f.transport.request(input)).rejects.toMatchObject({ code: 'invalid_gateway_response' });+ await expect(createDirectTransport(f.root, f.fetcher).request(input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('rejects an unverified speech voice before a paid call', async () => {+ const f = await fixture();+ const model = { ...f.input.model, voices: ['tested'], verification: { adapterVersion: 2, verifiedAt: '2026-10-14T00:00:00Z', countries: ['JP'] } };+ await expect(f.transport.request({ ...f.input, model })).rejects.toMatchObject({ code: 'capability_unsupported' });+ expect(f.fetcher).not.toHaveBeenCalled();+});diff --git a/apps/daemon/test/unit/gateway-direct-media.test.ts b/apps/daemon/test/unit/gateway-direct-media.test.tsnew file mode 100644index 00000000..9afb8658--- /dev/null+++ b/apps/daemon/test/unit/gateway-direct-media.test.ts@@ -0,0 +1,165 @@+import { mkdtemp, readdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it, vi } from 'vitest';+import type { GatewayModel } from '@opencreator/protocol';+import { createDirectTransport } from '../../src/gateway/direct-transport.js';+import { readPrivateJsonFile } from '../../src/config/private-json-file.js';++const roots: string[] = [];+afterEach(async () => { for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); });+async function fixture() {+ const root = await mkdtemp(join(tmpdir(), 'oc-media-')); roots.push(root);+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ id: 'gen-image-test', usage: { cost: 0.014 }, data: [{ b64_json: 'aW1hZ2U=' }] }, { headers: { 'x-request-id': 'upstream-request-test' } }));+ const transport = createDirectTransport(root, fetcher);+ const model: GatewayModel = { id: 'flux-3', modality: 'image', capabilities: [], imageOptions: { maxImages: 1, maxReferences: 0, aspectRatios: ['1:1'], resolutions: ['1K'] } };+ const input = { account: 'account', key: 'private-test-key', resource: 'images/generations', method: 'POST', body: { model: model.id, prompt: 'test', n: 1 }, contentType: 'application/json', identity: 'request', fingerprint: 'fingerprint', signal: AbortSignal.timeout(3_000), model };+ return { root, fetcher, transport, model, input };+}++it('reports an asynchronous image rejection after acceptance without making another submission', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ error: { message: 'Model unavailable in this country' } }, { status: 403 }));+ const onModelFailure = vi.fn(async () => undefined);+ const response = await f.transport.request({ ...f.input, asyncImage: true, onModelFailure });+ expect(response.status).toBe(202);+ await expect.poll(() => onModelFailure.mock.calls.length).toBe(1);+ expect(onModelFailure).toHaveBeenCalledWith(f.model.id, 'image', expect.objectContaining({ httpStatus: 403 }));+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('reports access failures from video polling with the saved exact model identity', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async url => Response.json(String(url).endsWith('/videos')+ ? { id: 'remote-video', status: 'pending' }+ : { id: 'remote-video', status: 'failed', error: { code: 403, message: 'Model unavailable in this country' } }));+ const model: GatewayModel = { id: 'vendor/video', modality: 'video', capabilities: [], sizes: ['1280x720'], durations: [5] };+ const onModelFailure = vi.fn(async () => undefined);+ const submitted = await f.transport.request({ ...f.input, resource: 'video/jobs', model, body: { model: model.id, prompt: 'test', size: '1280x720', duration: 5 }, onModelFailure });+ const { requestId } = await submitted.json();+ await f.transport.request({ ...f.input, resource: `requests/${requestId}`, method: 'GET', onModelFailure });+ expect(onModelFailure).toHaveBeenCalledWith(model.id, 'video', expect.objectContaining({ upstreamCode: '403' }));+ expect(f.fetcher.mock.calls.filter(([, options]) => options?.method === 'POST')).toHaveLength(1);+});++it('omits undeclared output_format and uses declared formats for Klein', async () => {+ const f = await fixture();+ await f.transport.request(f.input);+ expect(JSON.parse(String(f.fetcher.mock.lastCall?.[1]?.body))).not.toHaveProperty('output_format');+ f.model.imageOptions!.outputFormats = ['jpeg'];+ await f.transport.request({ ...f.input, identity: 'klein' });+ expect(JSON.parse(String(f.fetcher.mock.lastCall?.[1]?.body))).toMatchObject({ output_format: 'jpeg' });+});++it.each([+ { output_format: 'png' }, { aspect_ratio: '16:9' }, { size: '1536x1024' }, { resolution: '4K' },+ { n: 2 }, { n: 0 }, { n: 1.5 }, { n: '1' }, { n: 11 }, { quality: 'high' }, { stream: true },+ { prompt: '' }, { prompt: null }, { input_references: 'invalid' }, { input_references: [{}] },+ { input_references: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,aW1hZ2U=' } }] }+])('rejects an unsupported image profile before spending: %j', async params => {+ const f = await fixture();+ await expect(f.transport.request({ ...f.input, body: { ...f.input.body, ...params } })).rejects.toMatchObject({ code: 'capability_unsupported', status: 400 });+ expect(f.fetcher).not.toHaveBeenCalled();+ expect(await readdir(f.root)).toEqual([]);+});++it.each(['pending', 'in_progress', 'completed', 'failed', 'cancelled', 'expired'])('honors the documented video submit status %s and uses the authenticated content endpoint', async status => {+ const f = await fixture();+ f.fetcher.mockImplementation(async url => String(url).includes('/content?index=0') ? new Response('video') : Response.json({ id: 'remote-video', status, error: 'provider failed: private-test-key', usage: { cost: 0.02 }, polling_url: 'https://untrusted.invalid/job' }));+ const model: GatewayModel = { id: 'video', modality: 'video', capabilities: ['image_to_video'], resolutions: ['480p'], aspectRatios: ['16:9'], durations: [1] };+ const response = await f.transport.request({ ...f.input, resource: 'video/jobs', model, body: { model: 'video', prompt: 'test', size: '480p@16:9', duration: 1, image: 'data:image/png;base64,aW1hZ2U=' } });+ expect(JSON.parse(String(f.fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'video', prompt: 'test', duration: 1, resolution: '480p', aspect_ratio: '16:9', frame_images: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,aW1hZ2U=' }, frame_type: 'first_frame' }] });+ const state = status === 'completed' ? 'succeeded' : ['failed', 'cancelled', 'expired'].includes(status) ? 'failed' : 'waiting_upstream';+ expect(await response.clone().json()).toMatchObject({ state });+ const { requestId } = await response.json();+ const receipt = await readPrivateJsonFile(join(f.root, `${requestId}.json`));+ expect(receipt).toMatchObject({ state, reportedCostUsd: 0.02 });+ expect(JSON.stringify(receipt)).not.toContain('private-test-key');+ if (state === 'failed') expect(receipt).toMatchObject({ upstreamError: { upstreamMessage: 'provider failed: [redacted]' } });+ if (state === 'succeeded') {+ await f.transport.request({ ...f.input, method: 'GET', resource: `requests/${requestId}/result` });+ expect(f.fetcher.mock.lastCall?.[0]).toBe('https://openrouter.ai/api/v1/videos/remote-video/content?index=0');+ expect(f.fetcher.mock.lastCall?.[1]?.headers).toMatchObject({ Authorization: 'Bearer private-test-key' });+ }+});++it('preserves an accepted video ID when a malformed submit status needs read-only reconciliation', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ id: 'remote-video' }));+ const input = { ...f.input, resource: 'video/jobs', model: undefined, body: { model: 'video', prompt: 'test' } };+ await expect(f.transport.request(input)).rejects.toMatchObject({ code: 'invalid_gateway_response' });+ const replay = await createDirectTransport(f.root, f.fetcher).request(input);+ expect(await replay.json()).toMatchObject({ state: 'outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('keeps model, upstream identifiers and reported cost with a replayable result', async () => {+ const f = await fixture();+ const response = await f.transport.request(f.input);+ const requestId = response.headers.get('x-request-id')!;+ expect(await readPrivateJsonFile(join(f.root, `${requestId}.json`))).toMatchObject({+ account: 'account', model: 'flux-3', operation: 'images/generations', state: 'succeeded',+ upstreamRequestId: 'upstream-request-test', upstreamGenerationId: 'gen-image-test', reportedCostUsd: 0.014,+ createdAt: expect.any(String), updatedAt: expect.any(String)+ });+ await createDirectTransport(f.root, f.fetcher).request(f.input);+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('retains bounded, redacted rejection evidence privately without exposing it in the receipt API', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ error: { code: 'unsupported_parameter', message: 'output_format is unsupported; api_key=private-test-key', metadata: { raw: 'should not be retained' } } }, { status: 400, headers: { 'x-request-id': 'failed-upstream-request' } }));+ await expect(f.transport.request(f.input)).rejects.toMatchObject({ status: 400 });+ const [name] = await readdir(f.root);+ const receipt = await readPrivateJsonFile(join(f.root, name!));+ expect(receipt).toMatchObject({ state: 'failed', upstreamRequestId: 'failed-upstream-request', upstreamError: { httpStatus: 400, upstreamCode: 'unsupported_parameter', upstreamMessage: expect.stringContaining('output_format') } });+ expect(JSON.stringify(receipt)).not.toContain('private-test-key');+ expect(JSON.stringify(receipt)).not.toContain('should not be retained');+ const status = await f.transport.request({ ...f.input, method: 'GET', resource: `requests/${name!.replace(/\.json$/, '')}` });+ expect(await status.text()).not.toContain('unsupported_parameter');+});++it('keeps server errors and interruptions unknown so they cannot trigger an automatic duplicate', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ error: { message: 'Upstream disconnected' } }, { status: 502 }));+ await expect(f.transport.request(f.input)).rejects.toMatchObject({ status: 503 });+ await expect(createDirectTransport(f.root, f.fetcher).request(f.input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('retains malformed HTTP 200 image responses and generation IDs for reconciliation', async () => {+ const f = await fixture();+ f.fetcher.mockImplementation(async () => Response.json({ id: 'gen-bad-image', usage: { cost: 0.014 }, data: [] }));+ await expect(f.transport.request(f.input)).rejects.toMatchObject({ code: 'invalid_gateway_response' });+ const [name] = await readdir(f.root);+ const receipt = await readPrivateJsonFile(join(f.root, name!)) as { content: string };+ expect(receipt).toMatchObject({ state: 'outcome_unknown', upstreamGenerationId: 'gen-bad-image', reportedCostUsd: 0.014, upstreamError: { upstreamCode: 'invalid_image_response' } });+ expect(JSON.parse(Buffer.from(receipt.content, 'base64').toString('utf8'))).toMatchObject({ id: 'gen-bad-image', data: [] });+ await expect(createDirectTransport(f.root, f.fetcher).request(f.input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('retains partial image response bytes and connection failure facts without retrying', async () => {+ const f = await fixture();+ const partial = '{"data":[';+ f.fetcher.mockImplementation(async () => {+ let sent = false;+ return new Response(new ReadableStream<Uint8Array>({ pull(controller) {+ if (!sent) { sent = true; controller.enqueue(new TextEncoder().encode(partial)); }+ else controller.error(new Error('Connection interrupted', { cause: { code: 'ECONNRESET' } }));+ } }), { headers: { 'Content-Type': 'application/json' } });+ });+ await expect(f.transport.request(f.input)).rejects.toThrow('Connection interrupted');+ const [name] = await readdir(f.root);+ const receipt = await readPrivateJsonFile(join(f.root, name!)) as { content: string };+ expect(receipt).toMatchObject({ state: 'outcome_unknown', status: 200, receivedBytes: partial.length, upstreamError: { kind: 'connection-reset', upstreamCode: 'ECONNRESET' } });+ expect(Buffer.from(receipt.content, 'base64').toString('utf8')).toBe(partial);+ await expect(createDirectTransport(f.root, f.fetcher).request(f.input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it('blocks an unverified image-to-video operation before submitting', async () => {+ const f = await fixture();+ await expect(f.transport.request({ ...f.input, resource: 'video/jobs', model: { id: 'video', modality: 'video', capabilities: [], sizes: ['1280x720'], durations: [5] }, body: { model: 'video', prompt: 'test', size: '1280x720', duration: 5, image: 'data:image/png;base64,aW1hZ2U=' } })).rejects.toMatchObject({ code: 'capability_unsupported' });+ expect(f.fetcher).not.toHaveBeenCalled();+});diff --git a/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.ts b/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.tsindex 5ad43903..301f89e0 100644--- a/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.ts+++ b/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.ts@@ -84,3 +84,23 @@ it('Runtime 关闭期间迟到的认证恢复不会再次提交', async () => {expect(fetcher).toHaveBeenCalledOnce();} finally { resume(); await runtime.close(); await request; }});+it('rejects a hidden model before inference and reports both HTTP and streamed access failures', async () => {+ const onModelFailure = vi.fn(async () => undefined);+ const fetcher = vi.fn(async () => Response.json({ error: { code: 403, message: 'Model unavailable in this country' } }, { status: 403 }));+ const runtime = await createDirectRuntime('user-key', fetcher, async () => ({+ key: 'user-key', release: async () => undefined, onModelFailure,+ models: [{ id: 'vendor/allowed', modality: 'text', capabilities: ['responses'] }]+ }));+ const submit = (model: string) => fetch(`${runtime.baseUrl}/responses`, { method: 'POST', headers: { Authorization: `Bearer ${runtime.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model, input: 'test', stream: true }) });+ try {+ expect((await submit('vendor/hidden')).status).toBe(400);+ expect(fetcher).not.toHaveBeenCalled();+ const failure = await submit('vendor/allowed'); await failure.text();+ expect(onModelFailure).toHaveBeenLastCalledWith('vendor/allowed', 'text', expect.objectContaining({ httpStatus: 403, upstreamMessage: 'Model unavailable in this country' }));+ fetcher.mockImplementation(async () => new Response('data: {"type":"response.failed","response":{"error":{"code":403,"message":"Model unavailable in this country"}}}\n\n', { headers: { 'content-type': 'text/event-stream' } }));+ const streamed = await submit('vendor/allowed');+ expect(await streamed.text()).not.toContain('this country');+ expect(onModelFailure).toHaveBeenLastCalledWith('vendor/allowed', 'text', expect.objectContaining({ upstreamCode: '403', upstreamMessage: 'Model unavailable in this country' }));+ expect(onModelFailure).toHaveBeenCalledTimes(2);+ } finally { await runtime.close(); }+});diff --git a/apps/daemon/test/unit/gateway-model-access.test.ts b/apps/daemon/test/unit/gateway-model-access.test.tsindex 10937292..8861f17f 100644--- a/apps/daemon/test/unit/gateway-model-access.test.ts+++ b/apps/daemon/test/unit/gateway-model-access.test.ts@@ -1,10 +1,10 @@-import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { mkdtemp, readFile, rm, writeFile, mkdir } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, expect, it, vi } from 'vitest';import type { GatewayModel } from '@opencreator/protocol';import type { GatewayBootstrap } from '../../src/gateway/client.js';-import { createOfficialModelAccess, modelAccessGroup, officialModelPolicy } from '../../src/gateway/model-access.js';+import { createOfficialModelAccess, isModelAccessFailure, modelAccessGroup, officialModelPolicy } from '../../src/gateway/model-access.js';const roots: string[] = [];afterEach(async () => { vi.restoreAllMocks(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });@@ -18,10 +18,15 @@ const success = () => Response.json({ status: 'completed', output: [{ type: 'funconst denied = () => Response.json({ error: { message: 'The request is prohibited due to a violation of provider Terms Of Service.' } }, { status: 403 });async function fixture(models: GatewayModel[], reply: (id: string) => Response | Promise<Response> = success) {const root = await mkdtemp(join(tmpdir(), 'oc-model-access-')); roots.push(root);- let proxy = 'http://127.0.0.1:7897'; let ip = '203.0.113.1';+ let proxy = 'http://127.0.0.1:7897'; let ip = '203.0.113.1'; let country = 'JP';+ let catalogIDs = models.map(model => model.id);const calls: string[] = [];const fetcher = vi.fn<typeof fetch>(async (target, options) => {- if (String(target).endsWith('/cdn-cgi/trace')) return new Response(`ip=${ip}\nloc=JP\n`);+ if (String(target).endsWith('/cdn-cgi/trace')) return new Response(`ip=${ip}\nloc=${country}\n`);+ if (String(target).includes('/models/user?')) {+ expect(new Headers(options?.headers).get('authorization')).toBe('Bearer private-model-key');+ return Response.json({ data: catalogIDs.map(id => ({ id })) });+ }const body = JSON.parse(String(options?.body)); calls.push(body.model);expect(body).toMatchObject({ store: false, stream: false, max_output_tokens: 512 });expect(new Headers(options?.headers).get('authorization')).toBe('Bearer platform-probe-key');@@ -34,7 +39,7 @@ async function fixture(models: GatewayModel[], reply: (id: string) => Response |const input = { dataDir: root, fetcher, readProxy: async () => proxy, readProbeCredentials };const access = createOfficialModelAccess(input); const value = bootstrap(models);const run = (target = value) => access.refresh(target, new AbortController().signal, async () => undefined);- return { root, input, access, value, run, calls, fetcher, readProbeCredentials, setIP(value: string) { ip = value; }, setProxy(value: string) { proxy = value; } };+ return { root, input, access, value, run, calls, fetcher, readProbeCredentials, setIP(value: string) { ip = value; }, setProxy(value: string) { proxy = value; }, setCountry(value: string) { country = value; }, setCatalogIDs(ids: string[]) { catalogIDs = ids; } };}it('keeps hosted GPT and Gemini separate from open weight models and removes unsupported catalog entries', () => {@@ -46,22 +51,93 @@ it('keeps hosted GPT and Gemini separate from open weight models and removes unsexpect(officialModelPolicy(['anthropic/claude-sonnet-4.6', '~anthropic/claude-opus-4.6', 'openai/gpt-4.1:batch', 'openrouter/auto', 'deepseek/deepseek-v3.2'].map(text)).map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);});-it('checks one representative per family and filters all explicitly denied family members', async () => {+it('requires exact media verification in the current country and subtitle-compatible ASR', async () => {+ const verification = { adapterVersion: 2, verifiedAt: '2026-10-14T00:00:00Z', countries: ['JP'] };+ const media: GatewayModel[] = [+ { id: 'openai/image-ok', modality: 'image', capabilities: [], verification },+ { id: 'openai/video-ok', modality: 'video', capabilities: [], verification },+ { id: 'openai/tts-ok', modality: 'speech', capabilities: [], verification },+ { id: 'openai/asr-ok', modality: 'transcription', capabilities: ['subtitle_timestamps'], verification },+ { id: 'openai/asr-json-only', modality: 'transcription', capabilities: [], verification },+ { id: 'openai/image-untested', modality: 'image', capabilities: [] },+ { id: 'openai/image-other-country', modality: 'image', capabilities: [], verification: { ...verification, countries: ['US'] } }+ ];+ const f = await fixture([text('openai/text-denied'), ...media], denied);+ await f.run();+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(media.slice(0, 4).map(model => model.id));+ expect(f.calls).toEqual(['openai/text-denied']);+ expect(f.access.filter(f.value).defaults).not.toHaveProperty('text');+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_001);+ f.setCountry('US'); await f.run();+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['openai/image-other-country']);+ clock.mockRestore();+});++it('intersects verification with the actual customer key catalog and removes stale defaults', async () => {+ const f = await fixture([text('vendor/one'), text('vendor/two')]);+ await f.run();+ f.setCatalogIDs(['vendor/two']);+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_001);+ await f.run();+ expect(f.access.filter(f.value)).toMatchObject({ models: [text('vendor/two')], defaults: { text: 'vendor/two' } });+});++it('quarantines only the exact failed model and ignores stale-network feedback', async () => {+ const f = await fixture([text('vendor/one'), text('vendor/two')]);+ await f.run();+ const before = f.access.context();+ const facts = { kind: 'http-rejected' as const, httpStatus: 403, upstreamMessage: 'Model unavailable in this country' };+ expect(await f.access.recordFailure(before, f.value.models[0]!, facts)).toBe(true);+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['vendor/two']);+ f.setIP('203.0.113.2'); vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_001); await f.run();+ expect(await f.access.recordFailure(before, f.value.models[1]!, facts)).toBe(false);+ expect(f.access.filter(f.value).models).toHaveLength(2);+});++it('rejects old family caches and invalidates proof when the exact model profile changes', async () => {+ const f = await fixture([text('vendor/one')]);+ await mkdir(join(f.root, 'config'), { recursive: true });+ await writeFile(join(f.root, 'config/gateway-model-access.json'), JSON.stringify({ version: 1, base: '', network: '', groups: { vendor: { status: 'allowed', representative: 'vendor/one', nextCheck: Date.now() + 3600000 } } }));+ expect((await f.access.prepare(f.value)).models).toEqual([]);+ await f.run();+ const changed = { ...f.value, models: [{ ...f.value.models[0]!, capabilities: ['responses', 'changed-contract'] }] };+ expect(f.access.filter(changed).models).toEqual([]);+ await f.run(changed);+ expect(f.access.filter(changed).models).toHaveLength(1);+});++it.each([+ [402, 'Insufficient credits', false], [403, 'Key limit exceeded', false],+ [403, 'Content policy violation', false], [403, 'Forbidden', false],+ [429, 'Rate limit exceeded', false], [503, 'Provider unavailable', false],+ [403, 'Model unavailable in this country', true], [403, 'Permission denied for this model', true],+ [404, 'No endpoints found for this model', true],+ [400, 'The selected model does not support response_format "verbose_json"', true]+])('classifies HTTP %s %s without conflating access and request failures', (httpStatus, upstreamMessage, expected) => {+ expect(isModelAccessFailure({ kind: 'http-rejected', httpStatus: httpStatus as number, upstreamMessage: upstreamMessage as string })).toBe(expected);+});++it('recognizes explicit geographic failure from an accepted video job without an HTTP error status', () => {+ expect(isModelAccessFailure({ kind: 'provider-failed', upstreamCode: 'provider_error', upstreamMessage: 'Model unavailable in this country' })).toBe(true);+ expect(isModelAccessFailure({ kind: 'provider-failed', upstreamCode: 'provider_error', upstreamMessage: 'Temporarily unavailable' })).toBe(false);+});++it('checks each text model and never infers sibling or media availability from a representative', async () => {const image: GatewayModel = { id: 'openai/gpt-image-1', modality: 'image', capabilities: [] };const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-6-sol'), text('openai/gpt-4.1-mini'), image, text('google/gemini-2.5-flash'), text('google/gemini-2.5-flash-lite'), text('openai/gpt-oss-20b'), text('google/gemma-3-12b-it'), text('anthropic/claude-sonnet-4.6')], id => /gpt-4.1-mini|gemini/.test(id) ? denied() : success());- expect((await f.access.prepare(f.value)).models.filter(model => model.modality === 'text').map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+ expect((await f.access.prepare(f.value)).models).toEqual([]);await f.run();- expect(f.calls).toHaveLength(5);+ expect(f.calls).toHaveLength(7);expect(f.calls).toContain('openai/gpt-4.1-mini');- expect(f.calls).not.toContain('openai/gpt-6-sol');+ expect(f.calls).toContain('openai/gpt-6-sol');expect(f.calls).toContain('google/gemini-2.5-flash-lite');expect(f.calls).not.toContain(image.id);- expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'openai/gpt-oss-20b', 'google/gemma-3-12b-it']);+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'openai/gpt-6-sol', 'openai/gpt-oss-20b', 'google/gemma-3-12b-it']);const saved = await readFile(join(f.root, 'config/gateway-model-access.json'), 'utf8');expect(saved).not.toMatch(/private-model-key|203\.0\.113|a@test/);});-it('preserves the selected family while another family finishes its check first', async () => {+it('keeps an unchecked selected model hidden while a verified fallback finishes first', async () => {let finishSelected!: () => void;const waiting = new Promise<void>(resolve => { finishSelected = resolve; });const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], async id => {@@ -69,23 +145,23 @@ it('preserves the selected family while another family finishes its check first'return success();});const work = f.run();- await expect.poll(() => f.access.filter(f.value).models.length).toBe(2);- expect(f.access.filter(f.value).defaults.text).toBe('deepseek/deepseek-v3.2');+ await expect.poll(() => f.access.filter(f.value).models.length).toBe(1);+ expect(f.access.filter(f.value).defaults.text).toBe('openai/gpt-4.1-mini');finishSelected(); await work;expect(f.access.filter(f.value).defaults.text).toBe('deepseek/deepseek-v3.2');});-it.each([429, 503, 403])('retains a previously accessible family for a transient or unrelated HTTP %s failure', async status => {+it.each([429, 503, 403])('does not treat an expired success plus HTTP %s as new availability proof', async status => {let failure = false;const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], () => failure? Response.json({ error: { message: status === 403 ? 'Key limit exceeded' : 'Temporarily unavailable' } }, { status }) : success());const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());await f.run(); failure = true; clock.mockReturnValue(Date.now() + 24 * 60 * 60_000 + 1);await f.run();- expect(f.access.filter(f.value).models).toHaveLength(2);+ expect(f.access.filter(f.value).models).toHaveLength(0);});-it('keeps success across a network exception without caching a secret error message', async () => {+it('hides expired success after a network exception without caching a secret error message', async () => {let failed = false;const f = await fixture([text('deepseek/deepseek-v3.2'), text('qwen/qwen3-coder')], () => {if (failed) throw new Error('private-model-key');@@ -93,11 +169,11 @@ it('keeps success across a network exception without caching a secret error mess});const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());await f.run(); failed = true; clock.mockReturnValue(Date.now() + 24 * 60 * 60_000 + 1); await f.run();- expect(f.access.filter(f.value).models).toHaveLength(2);+ expect(f.access.filter(f.value).models).toHaveLength(0);expect(await readFile(join(f.root, 'config/gateway-model-access.json'), 'utf8')).not.toContain('private-model-key');});-it('preserves cached results when the network identity endpoint is unavailable', async () => {+it('hides cached results when the current network identity cannot be established', async () => {const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], id => id.startsWith('openai/') ? denied() : success());const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());await f.run(); const count = f.calls.length;@@ -105,7 +181,7 @@ it('preserves cached results when the network identity endpoint is unavailable',f.fetcher.mockRejectedValueOnce(new Error('trace unavailable'));await f.run();expect(f.calls).toHaveLength(count);- expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+ expect(f.access.filter(f.value).models).toEqual([]);});it('reuses persisted results and retries a blocked family after one hour', async () => {@@ -125,21 +201,21 @@ it('invalidates results for account, key, proxy and exit changes', async () => {const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());await f.run();const key = { ...f.value, keyVersion: 'key-v2' };- expect((await f.access.prepare(key)).models).toHaveLength(1); await f.run(key);+ expect((await f.access.prepare(key)).models).toHaveLength(0); await f.run(key);const account = { ...key, account: { ...key.account, id: 'account-b' } };- expect((await f.access.prepare(account)).models).toHaveLength(1); await f.run(account);- f.setProxy('http://127.0.0.1:8888'); expect((await f.access.prepare(account)).models).toHaveLength(1); await f.run(account);+ expect((await f.access.prepare(account)).models).toHaveLength(0); await f.run(account);+ f.setProxy('http://127.0.0.1:8888'); expect((await f.access.prepare(account)).models).toHaveLength(0); await f.run(account);f.setIP('203.0.113.2'); clock.mockReturnValue(Date.now() + 60_001); await f.run(account);expect(f.calls).toHaveLength(10);});-it('tries another representative after a model-specific parameter or missing-model error', async () => {+it('does not promote a missing sibling when another exact model succeeds', async () => {const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini'), text('openai/gpt-6-sol')], id => id === 'openai/gpt-4.1-mini'? Response.json({ error: { message: 'Model is unavailable' } }, { status: 404 }) : success());const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());await f.run(); clock.mockReturnValue(Date.now() + 5 * 60_000 + 1); await f.run();expect(f.calls.filter(id => id.startsWith('openai/'))).toEqual(['openai/gpt-4.1-mini', 'openai/gpt-6-sol']);- expect(f.access.filter(f.value).models).toHaveLength(3);+ expect(f.access.filter(f.value).models).toHaveLength(2);});it('bounds each background pass and stops starting probes after cancellation', async () => {diff --git a/apps/daemon/test/unit/openrouter-audio-profiles.test.ts b/apps/daemon/test/unit/openrouter-audio-profiles.test.tsnew file mode 100644index 00000000..67af7158--- /dev/null+++ b/apps/daemon/test/unit/openrouter-audio-profiles.test.ts@@ -0,0 +1,42 @@+import { expect, it, vi } from 'vitest';+import { verifiedAudioProfiles } from '../../scripts/openrouter-audio-profiles.js';+import { readVerificationNetwork, verifiedCountries } from '../../scripts/openrouter-verification-network.js';++const passed = { status: 'passed', restartReplay: true, sha256: 'a'.repeat(64), verifiedCountries: ['JP'] };+const exportProfiles = (results: Record<string, unknown>[]) => verifiedAudioProfiles(results, 'report.json', '2026-10-14T00:00:00Z');++it('admits only tested voices and ASR models with subtitle timings', () => {+ const speech = { ...passed, model: 'vendor/tts', modality: 'speech', voice: 'tested', format: 'mp3' };+ const asr = { ...passed, model: 'vendor/asr', modality: 'transcription', subtitleCompatible: true, validTimings: 2 };+ const profiles = exportProfiles([speech, { ...speech, voice: 'another-tested' }, asr,+ { ...asr, model: 'vendor/json', subtitleCompatible: false }, { ...asr, model: 'vendor/warning', status: 'quality-warning' },+ { ...speech, model: 'vendor/untested', restartReplay: false }]);+ expect(profiles).toHaveLength(2);+ expect(profiles[0]).toMatchObject({ voices: ['tested', 'another-tested'], verified_countries: ['JP'] });+ expect(profiles[1]?.capabilities).toEqual(['subtitle_timestamps']);+});++it('does not fabricate regional evidence from old reports or inherit another voice country', () => {+ const speech = { ...passed, model: 'vendor/tts', modality: 'speech', voice: 'tested', format: 'mp3' };+ expect(exportProfiles([{ ...speech, verifiedCountries: undefined }])[0]?.verified_countries).toEqual([]);+ expect(exportProfiles([speech, { ...speech, voice: 'other', verifiedCountries: ['US'] }])[0]?.verified_countries).toEqual([]);+});++it('certifies PCM only for the exact repaired HeyGen model and omits the default voice sentinel', () => {+ const speech = { ...passed, model: 'heygen/heygen-voice-1-turbo', modality: 'speech', voice: 'tested', format: 'wav' };+ const profiles = exportProfiles([speech, { ...speech, model: 'heygen/untested-sibling' }, { ...speech, model: 'vendor/default', voice: '__default__', format: 'mp3' }]);+ expect(profiles).toHaveLength(2);+ expect(profiles[0]?.capabilities).toEqual(['pcm_speech']);+ expect(profiles[1]).toMatchObject({ voices: [], capabilities: ['default_voice'] });+});++it('records the real exit without retaining its IP and rejects unknown or changed exits', async () => {+ const fetcher = vi.fn(async () => new Response('ip=203.0.113.1\nloc=JP\n'));+ const before = await readVerificationNetwork(fetcher);+ expect(JSON.stringify(before)).not.toContain('203.0.113');+ expect(verifiedCountries(before, before)).toEqual(['JP']);+ expect(verifiedCountries(before, { ...before, exitHash: 'different' })).toEqual([]);+ expect(verifiedCountries(before)).toEqual([]);+ fetcher.mockImplementation(async () => new Response('loc=JP\n'));+ await expect(readVerificationNetwork(fetcher)).rejects.toThrow('known OpenRouter exit country');+});diff --git a/apps/daemon/test/unit/openrouter-media-profiles.test.ts b/apps/daemon/test/unit/openrouter-media-profiles.test.tsnew file mode 100644index 00000000..6c41eae0--- /dev/null+++ b/apps/daemon/test/unit/openrouter-media-profiles.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest';+import { familyRepresentatives, mediaFamily, mediaProfile, passedProfile, referenceDimensions, videoShapeMismatch, verificationBlockReason } from '../../scripts/openrouter-media-profiles.js';++describe('OpenRouter media verification profiles', () => {+ it('omits undeclared options and does not mistake metadata for edit acceptance', () => {+ const { model } = mediaProfile({ id: 'vendor/image', architecture: { input_modalities: ['text', 'image'] }, supported_parameters: { aspect_ratio: { values: ['1:1'] }, input_references: { max: 5 } } }, 'image');+ expect(model?.imageOptions).toMatchObject({ outputFormats: [], resolutions: [], qualities: [], maxReferences: 1 });+ expect(passedProfile(model!, ['text-to-image'])).toMatchObject({ capabilities: [], imageOptions: { maxReferences: 0 } });+ expect(passedProfile(model!, ['text-to-image', 'image-edit'])).toMatchObject({ capabilities: ['edit'], imageOptions: { maxReferences: 1 } });+ });+ it('supports JPEG-only models and selects an advertised resolution without assuming 1K', () => {+ expect(mediaProfile({ id: 'vendor/jpeg', supported_parameters: { resolution: { values: ['4K', '2K'] }, output_format: { values: ['jpeg'] } } }, 'image').model?.imageOptions).toMatchObject({ resolutions: ['2K'], outputFormats: ['jpeg'], aspectRatios: [] });+ });+ it('reports reference-only and vector-only models as unsupported', () => {+ expect(mediaProfile({ id: 'vendor/style', supported_parameters: { input_references: { min: 1 } } }, 'image').unsupportedReason).toMatch(/Reference-only/);+ expect(mediaProfile({ id: 'vendor/vector', supported_parameters: { output_format: { values: ['svg'] } } }, 'image').unsupportedReason).toMatch(/raster/);+ });+ it('chooses the minimum video duration and a matching low-resolution landscape size', () => {+ const { model } = mediaProfile({ id: 'vendor/video', supported_resolutions: ['1080p', '480p', '720p'], supported_durations: [10, 4, 8], supported_aspect_ratios: ['1:1', '16:9'], supported_sizes: ['1920x1080', '480x480', '854x480'], supported_frame_images: ['first_frame'] }, 'video');+ expect(model).toMatchObject({ durations: [4], sizes: ['854x480'], capabilities: ['image_to_video'] });+ expect(passedProfile(model!, ['text-to-video'])).toMatchObject({ capabilities: [] });+ expect(passedProfile(model!, ['image-to-video'])).toBeUndefined();+ });+ it('handles videos without pixel sizes and excludes specialized video workflows', () => {+ expect(mediaProfile({ id: 'vendor/video', supported_resolutions: ['720p'], supported_durations: [5], supported_aspect_ratios: ['16:9'] }, 'video').model).toMatchObject({ resolutions: ['720p'], aspectRatios: ['16:9'], durations: [5] });+ expect(mediaProfile({ id: 'vendor/upscale' }, 'video').unsupportedReason).toMatch(/separate adapters/);+ });+ it('selects one supported representative per family independent of catalog order', () => {+ const profiles = ['black-forest-labs/flux.2-max', 'black-forest-labs/flux-3-image', 'black-forest-labs/flux.2-klein-4b', 'alibaba/wan-2.6', 'alibaba/happyhorse-1.1', 'new-vendor/new-video'].map(id => mediaProfile({ id, supported_parameters: {}, supported_resolutions: ['480p'], supported_aspect_ratios: ['16:9'], supported_durations: [1] }, id.startsWith('black-forest-labs') ? 'image' : 'video'));+ expect(familyRepresentatives(profiles).map(p => p.id)).toEqual(['black-forest-labs/flux-3-image', 'alibaba/wan-2.6', 'alibaba/happyhorse-1.1']);+ expect(familyRepresentatives(profiles.reverse()).map(p => p.id)).toEqual(['black-forest-labs/flux-3-image', 'alibaba/wan-2.6', 'alibaba/happyhorse-1.1']);+ expect(mediaFamily(profiles[0]!)).toBeUndefined();+ });+ it('preserves the selected video proportions in first-frame verification input', () => {+ expect(referenceDimensions({ id: 'video', modality: 'video', capabilities: [], aspectRatios: ['16:9'] })).toEqual({ width: 512, height: 288 });+ expect(referenceDimensions({ id: 'video', modality: 'video', capabilities: [], sizes: ['720x1280'] })).toEqual({ width: 288, height: 512 });+ });+ it('allows a targeted normalized video profile only when the catalog declares it', () => {+ const item = { id: 'video/model', supported_resolutions: ['480p', '720p'], supported_aspect_ratios: ['16:9'], supported_sizes: ['1280x720'], supported_durations: [4] };+ const { model } = mediaProfile(item, 'video', '720p@16:9');+ expect(model).toMatchObject({ resolutions: ['720p'], aspectRatios: ['16:9'] });+ expect(model?.sizes).toBeUndefined();+ expect(() => mediaProfile(item, 'video', '1080p@16:9')).toThrow(/not declared/);+ expect(() => mediaProfile(item, 'video', '720p@9:16')).toThrow(/not declared/);+ });+ it('separates funding and provider-access blocks from model failures', () => {+ expect(verificationBlockReason([{ upstreamError: { httpStatus: 402 } }])).toBe('funding');+ expect(verificationBlockReason([{ upstreamError: { httpStatus: 403, upstreamMessage: 'Key limit exceeded' } }])).toBe('funding');+ expect(verificationBlockReason([{ upstreamError: { httpStatus: 403, upstreamMessage: 'The request is prohibited' } }])).toBe('provider-access');+ expect(verificationBlockReason([{ upstreamError: { httpStatus: 400 } }])).toBeUndefined();+ });+ it('does not mistake a different resolution or a square first-frame output for the requested profile', () => {+ const model = { id: 'video/model', modality: 'video' as const, capabilities: [], resolutions: ['720p'], aspectRatios: ['16:9'] };+ expect(videoShapeMismatch(model, 1280, 720)).toBeUndefined();+ expect(videoShapeMismatch(model, 1920, 1080)).toMatch(/resolution/);+ expect(videoShapeMismatch(model, 720, 720)).toMatch(/aspect ratio/);+ expect(videoShapeMismatch({ ...model, resolutions: ['480p'] }, 848, 480)).toBeUndefined();+ expect(videoShapeMismatch({ ...model, sizes: ['854x480'] }, 864, 496)).toMatch(/pixel size/);+ });+});diff --git a/apps/daemon/test/unit/project-manager.test.ts b/apps/daemon/test/unit/project-manager.test.tsindex dbcbaa23..b6137960 100644--- a/apps/daemon/test/unit/project-manager.test.ts+++ b/apps/daemon/test/unit/project-manager.test.ts@@ -34,7 +34,7 @@ describe('project manager', () => {expect(first).toMatchObject({id: 'project_default_1',- name: '默认项目',+ name: 'Default project',cwd: join(managedProjectRoot, 'Default Project'),directoryState: 'available'});diff --git a/apps/daemon/test/unit/task-service.test.ts b/apps/daemon/test/unit/task-service.test.tsindex fea1b6ff..defbf251 100644--- a/apps/daemon/test/unit/task-service.test.ts+++ b/apps/daemon/test/unit/task-service.test.ts@@ -213,7 +213,7 @@ describe('task service', () => {id: 'run_directory_3',scheduleId: 'sch_missing_project',failureKind: 'project_directory',- failureSummary: '项目目录不存在或无法访问,请编辑项目后重试。',+ failureSummary: 'The project directory is missing or inaccessible. Edit the project and try again.',consecutiveFailureCount: 3,suggestPause: true});diff --git a/apps/desktop/e2e/creator-packaged-app.spec.ts b/apps/desktop/e2e/creator-packaged-app.spec.tsindex 79f20deb..a053eec1 100644--- a/apps/desktop/e2e/creator-packaged-app.spec.ts+++ b/apps/desktop/e2e/creator-packaged-app.spec.ts@@ -251,7 +251,7 @@ test('打包 App 的浅色窗口按钮区域与设置侧栏连续且保留标题expect(await fixture.app.page.evaluate(() => (typeof window.opencreatorDesktop?.setWindowColorMode))).toBe('function');- await expect(fixture.app.page.getByRole('group', { name: '窗口控制' }).getByRole('button')).toHaveCount(3);+ await expect(fixture.app.page.getByRole('group', { name: 'Window controls' }).getByRole('button')).toHaveCount(3);for (const action of ['close', 'minimize', 'zoom']) {const background = await fixture.app.page.locator(`.desktop-window-control-${action}`).evaluate(element =>getComputedStyle(element).backgroundColor@@ -268,9 +268,9 @@ test('打包 App 的浅色窗口按钮区域与设置侧栏连续且保留标题const title = document.querySelector('.creator-tools-page-header h1')!.getBoundingClientRect();return Math.round((brand.top + brand.bottom - title.top - title.bottom) / 2);})).toBeLessThanOrEqual(3);- await fixture.app.page.getByRole('button', { name: '缩放窗口' }).click();+ await fixture.app.page.getByRole('button', { name: 'Zoom window' }).click();await expect.poll(() => fixture.app.page.evaluate(() => window.innerWidth)).toBeGreaterThan(980);- await fixture.app.page.getByRole('button', { name: '缩放窗口' }).click();+ await fixture.app.page.getByRole('button', { name: 'Zoom window' }).click();await expect.poll(() => fixture.app.page.evaluate(() => window.innerWidth)).toBe(980);await fixture.app.page.getByRole('button', { name: '我的项目', exact: true }).click();await expect(fixture.app.page.getByRole('heading', { name: '我的项目' })).toBeVisible();diff --git a/apps/desktop/e2e/desktop.spec.ts b/apps/desktop/e2e/desktop.spec.tsindex 9db4a743..c29b47d3 100644--- a/apps/desktop/e2e/desktop.spec.ts+++ b/apps/desktop/e2e/desktop.spec.ts@@ -224,7 +224,7 @@ test('@package-smoke 授权回调唤起个人中心,模型初始化期间立if (-not [OpenCreatorE2EWindow]::IsIconic($windowHandle)) { throw 'Desktop native window did not minimize'; }`], { timeout: 10_000 });} else {- await fixture.page.getByRole('button', { name: '最小化窗口', exact: true }).click();+ await fixture.page.getByRole('button', { name: 'Minimize window', exact: true }).click();}approved = true;const checks: string[] = [];@@ -1154,7 +1154,7 @@ test('后台 Probe 失败时仍进入 Dashboard 并暴露诊断状态', async ()status: payload.availabilityProbe?.status,errorCode: payload.availabilityProbe?.errorCode,hasDiagnostic: payload.diagnostics?.some(message =>- message.includes('Codex 后台可用性验证失败')+ message.includes('Codex background availability verification failed')) ?? false};}), { timeout: 15_000 }).toEqual({@@ -1172,7 +1172,7 @@ test('Dashboard 握手超时后显示本地错误页并可无 Probe 重载', asyconst fixture = await launchPackagedDesktop('workspace-failure');try {await expect(fixture.page.locator('#status-title')).toHaveText(- 'Dashboard 加载失败',+ 'Dashboard failed to load',{ timeout: 30_000 });await expect(fixture.page.locator('#reload-workspace')).toBeVisible();@@ -1353,12 +1353,12 @@ test('@package-smoke 关闭后隐藏保留本地服务,重新打开后可以await fixture.page.evaluate(async () => {await window.opencreatorDesktop?.updateDesktopPreferences({ closeBehavior: 'hide' });});- await fixture.page.getByRole('button', { name: '关闭窗口', exact: true }).click();+ await fixture.page.getByRole('button', { name: 'Close window', exact: true }).click();expect(fixture.process.exitCode).toBeNull();expect((await runtimeRequest(fixture.page, 'GET', '/healthz')).status).toBe(200);await launchSecondInstance(fixture);- await expect(fixture.page.getByRole('button', { name: '关闭窗口', exact: true })).toBeVisible();+ await expect(fixture.page.getByRole('button', { name: 'Close window', exact: true })).toBeVisible();await requestPackagedAppQuit(fixture);expect(await waitForProcessExit(fixture.process, 3_000)).toBe(true);expect(fixture.process.exitCode).toBe(0);@@ -1493,7 +1493,7 @@ test('@package-smoke 设置关闭后退出时,关闭按钮结束实际 App', aawait fixture.page.evaluate(async () => {await window.opencreatorDesktop?.updateDesktopPreferences({ closeBehavior: 'quit' });});- await fixture.page.getByRole('button', { name: '关闭窗口', exact: true }).click();+ await fixture.page.getByRole('button', { name: 'Close window', exact: true }).click();expect(await waitForProcessExit(fixture.process, 3_000)).toBe(true);expect(fixture.process.exitCode).toBe(0);} finally {diff --git a/apps/desktop/src/bootstrap/index.html b/apps/desktop/src/bootstrap/index.htmlindex 911f6440..29e56722 100644--- a/apps/desktop/src/bootstrap/index.html+++ b/apps/desktop/src/bootstrap/index.html@@ -1,5 +1,5 @@<!doctype html>-<html lang="zh-CN">+<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />@@ -7,10 +7,10 @@<link rel="stylesheet" href="./style.css" /></head><body>- <div class="desktop-window-controls" role="group" aria-label="窗口控制" hidden>- <button type="button" data-action="close" aria-label="关闭窗口" title="关闭窗口"><span aria-hidden="true">×</span></button>- <button type="button" data-action="minimize" aria-label="最小化窗口" title="最小化窗口"><span aria-hidden="true">−</span></button>- <button type="button" data-action="zoom" aria-label="缩放窗口" title="缩放窗口"><span aria-hidden="true">+</span></button>+ <div class="desktop-window-controls" role="group" aria-label="Window controls" hidden>+ <button type="button" data-action="close" aria-label="Close window" title="Close window"><span aria-hidden="true">×</span></button>+ <button type="button" data-action="minimize" aria-label="Minimize window" title="Minimize window"><span aria-hidden="true">−</span></button>+ <button type="button" data-action="zoom" aria-label="Zoom window" title="Zoom window"><span aria-hidden="true">+</span></button></div><main class="bootstrap-shell"><section class="bootstrap-panel" aria-live="polite">@@ -18,30 +18,30 @@<div class="status-mark" id="status-mark" aria-hidden="true"><span></span></div>- <h1 id="status-title">正在准备 OpenCreator</h1>- <p id="status-detail">正在检查本机运行环境</p>+ <h1 id="status-title">Preparing OpenCreator</h1>+ <p id="status-detail">Checking the local environment</p><p class="elapsed" id="elapsed" hidden></p><div class="failure-actions" id="failure-actions" hidden>- <button class="primary" id="retry" type="button">重新检测</button>- <button id="select-codex" type="button">选择 Codex 或 ChatGPT</button>- <button id="diagnostics" type="button">导出诊断</button>- <button class="quiet" id="quit" type="button">退出</button>+ <button class="primary" id="retry" type="button">Retry</button>+ <button id="select-codex" type="button">Select Codex or ChatGPT</button>+ <button id="diagnostics" type="button">Export diagnostics</button>+ <button class="quiet" id="quit" type="button">Quit</button></div><div class="failure-actions" id="workspace-actions" hidden>- <button class="primary" id="reload-workspace" type="button">重新加载 Dashboard</button>- <button id="restart-runtime" type="button">重启 Runtime</button>- <button id="workspace-diagnostics" type="button">导出诊断</button>- <button class="quiet" id="workspace-quit" type="button">退出</button>+ <button class="primary" id="reload-workspace" type="button">Reload Dashboard</button>+ <button id="restart-runtime" type="button">Restart Runtime</button>+ <button id="workspace-diagnostics" type="button">Export diagnostics</button>+ <button class="quiet" id="workspace-quit" type="button">Quit</button></div><details id="technical-details" hidden>- <summary>技术信息</summary>+ <summary>Technical details</summary><dl><div><dt>Codex</dt><dd id="codex-path">-</dd></div><div><dt>CODEX_HOME</dt><dd id="codex-home">-</dd></div>- <div><dt>错误代码</dt><dd id="error-code">-</dd></div>+ <div><dt>Error code</dt><dd id="error-code">-</dd></div></dl><pre id="error-message"></pre></details>diff --git a/apps/desktop/src/bootstrap/main.ts b/apps/desktop/src/bootstrap/main.tsindex 86bbdc0f..0be3eb21 100644--- a/apps/desktop/src/bootstrap/main.ts+++ b/apps/desktop/src/bootstrap/main.ts@@ -68,14 +68,14 @@ const selectCodex = element('select-codex');let currentState: BootstrapState | undefined;const labels: Record<BootstrapState['phase'], [string, string]> = {- idle: ['正在准备 OpenCreator', '正在初始化桌面环境'],- resolving_codex: ['正在查找本机 Codex', '正在读取终端环境和已保存路径'],- starting_daemon: ['正在启动本地运行服务', '正在创建独立的 OpenCreator Runtime'],- probing_codex: ['正在验证 Codex 是否可用', '正在检查本机 Codex 进程'],- starting_runtime: ['正在打开 OpenCreator', '正在加载本地数据和 Codex 能力信息'],- ready: ['正在打开 OpenCreator', '本地运行环境已就绪'],- workspace_failed: ['Dashboard 加载失败', '本地 Runtime 仍在运行,可以直接重载 Dashboard 或重启 Runtime'],- failed: ['Codex CLI 暂时无法完成调用', 'OpenCreator 没有收到有效响应,请检查诊断后重试']+ idle: ['Preparing OpenCreator', 'Initializing the desktop environment'],+ resolving_codex: ['Locating Codex', 'Reading the shell environment and saved paths'],+ starting_daemon: ['Starting the local Runtime', 'Creating an isolated OpenCreator Runtime'],+ probing_codex: ['Checking Codex availability', 'Checking the local Codex process'],+ starting_runtime: ['Opening OpenCreator', 'Loading local data and Codex capabilities'],+ ready: ['Opening OpenCreator', 'The local Runtime is ready'],+ workspace_failed: ['Dashboard failed to load', 'The local Runtime is still running. Reload the Dashboard or restart the Runtime.'],+ failed: ['Codex CLI is unavailable', 'OpenCreator did not receive a valid response. Check diagnostics and try again.']};api.subscribeBootstrapState(render);@@ -102,7 +102,7 @@ window.setInterval(() => {}const seconds = Math.max(0, Math.floor((Date.now() - Date.parse(currentState.startedAt)) / 1000));elapsed.hidden = seconds < 3;- elapsed.textContent = `已等待 ${seconds} 秒`;+ elapsed.textContent = `Waiting for ${seconds}s`;}, 500);function render(state: BootstrapState): void {@@ -129,17 +129,17 @@ function render(state: BootstrapState): void {function failureLabel(state: BootstrapState): [string, string] {if (state.error?.code === 'CODEX_NOT_FOUND') {return [- '未找到本机 Codex CLI',- '请确认终端中可以运行 codex,或直接选择 ChatGPT/Codex 应用'+ 'Codex CLI not found',+ 'Make sure codex runs in your terminal, or select the ChatGPT or Codex app.'];}if (state.error?.code === 'CODEX_PATH_INVALID') {- return ['所选 Codex 路径不可用', state.error.message];+ return ['The selected Codex path is unavailable', state.error.message];}if (state.error?.code === 'RUNTIME_DATA_IN_USE') {return [- 'OpenCreator 本地服务已在运行',- '当前运行环境正在使用同一数据目录,请关闭另一个同版本窗口后重试'+ 'OpenCreator Runtime is already running',+ 'Another instance is using the same data directory. Close the other window for this version and try again.'];}return labels.failed;diff --git a/apps/desktop/src/main/bootstrap-controller.ts b/apps/desktop/src/main/bootstrap-controller.tsindex 3e9bf378..6e9f6022 100644--- a/apps/desktop/src/main/bootstrap-controller.ts+++ b/apps/desktop/src/main/bootstrap-controller.ts@@ -124,7 +124,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>phase: 'failed',error: {code: 'CODEX_PATH_INVALID',- message: '请选择 ChatGPT.app、Codex.app,或可执行的 codex 文件'+ message: 'Select ChatGPT.app, Codex.app, or a codex executable'}});return;@@ -146,7 +146,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>this.stopping = false;if (this.resolvedEnvironment === undefined) {await this.start();- if (this.state.phase === 'failed') throw new Error(this.state.error?.message ?? '本地服务启动失败');+ if (this.state.phase === 'failed') throw new Error(this.state.error?.message ?? 'Failed to start the local Runtime');return;}await this.recoverRuntime('manual');@@ -256,7 +256,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>phase: 'failed',error: {code: 'CODEX_NOT_FOUND',- message: '未能自动找到 Codex CLI。请确认终端中可以运行 codex,或手动选择 Codex 路径',+ message: 'Codex CLI could not be located automatically. Make sure codex runs in your terminal, or select its path manually.',...(resolutionDiagnostics === undefined? {}: { details: { ...resolutionDiagnostics } })@@ -378,7 +378,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>if (controller.signal.aborted || this.stopping) return;this.updateState({phase: 'failed',- error: { code: 'DAEMON_RESTART_EXHAUSTED', message: '本地服务多次恢复失败,请在连接提示或设置 → 诊断中重启本地服务。' }+ error: { code: 'DAEMON_RESTART_EXHAUSTED', message: 'Runtime recovery failed repeatedly. Restart the local Runtime from the connection notice or Settings > Diagnostics.' }});}diff --git a/apps/desktop/src/main/codex-resolver.ts b/apps/desktop/src/main/codex-resolver.tsindex 03ee9d12..3a629f79 100644--- a/apps/desktop/src/main/codex-resolver.ts+++ b/apps/desktop/src/main/codex-resolver.ts@@ -145,13 +145,13 @@ function resolveBundled(input: {diagnostics: CodexResolutionDiagnostics;}): ResolvedCodexEnvironment {if (input.runtimeRoot === undefined) {- throw failure('codex_runtime_missing', '未提供 OpenCreator 内置 Codex Runtime 路径', input.diagnostics);+ throw failure('codex_runtime_missing', 'The bundled OpenCreator Codex Runtime path was not provided', input.diagnostics);}const runtimeRoot = resolve(input.runtimeRoot);const manifestPath = join(runtimeRoot, 'manifest.json');Object.assign(input.diagnostics, { runtimeRoot, manifestPath });if (!existsSync(manifestPath)) {- throw failure('codex_runtime_missing', `内置 Codex Runtime 清单不存在:${manifestPath}`, input.diagnostics);+ throw failure('codex_runtime_missing', `The bundled Codex Runtime manifest is missing: ${manifestPath}`, input.diagnostics);}const manifestSource = readFileSync(manifestPath, 'utf8');const manifest = JSON.parse(manifestSource) as Record<string, unknown>;@@ -163,7 +163,7 @@ function resolveBundled(input: {) {throw failure('codex_runtime_version_mismatch',- `内置 Codex Runtime 与当前 OpenCreator 不兼容(需要 ${BUNDLED_VERSION})`,+ `The bundled Codex Runtime is incompatible with OpenCreator (requires ${BUNDLED_VERSION})`,input.diagnostics);}@@ -171,11 +171,11 @@ function resolveBundled(input: {const relativePath = readString(binary.relativePath);const expectedHash = readString(binary.sha256);if (relativePath === undefined || expectedHash === undefined) {- throw failure('codex_runtime_hash_mismatch', '内置 Codex Runtime 主程序清单无效', input.diagnostics);+ throw failure('codex_runtime_hash_mismatch', 'The bundled Codex Runtime executable manifest is invalid', input.diagnostics);}const codexBin = safeRuntimePath(runtimeRoot, relativePath, input.diagnostics);if (!existsSync(codexBin) || lstatSync(codexBin).isSymbolicLink() || !statSync(codexBin).isFile()) {- throw failure('codex_runtime_missing', `内置 Codex 主程序不存在:${codexBin}`, input.diagnostics);+ throw failure('codex_runtime_missing', `The bundled Codex executable is missing: ${codexBin}`, input.diagnostics);}const verification = verifyFileIntegrityWithCache({cachePath: join(input.userDataDir, 'runtime-verification', 'codex.json'),@@ -188,7 +188,7 @@ function resolveBundled(input: {}]});if (!verification.verified) {- throw failure('codex_runtime_hash_mismatch', '内置 Codex 主程序哈希校验失败', input.diagnostics);+ throw failure('codex_runtime_hash_mismatch', 'The bundled Codex executable failed hash verification', input.diagnostics);}const codexHome = join(input.userDataDir, 'runtime', 'codex');mkdirSync(codexHome, { recursive: true });@@ -220,11 +220,11 @@ function resolveExternal(input: {diagnostics: CodexResolutionDiagnostics;}): ResolvedCodexEnvironment {if (input.codexBin === undefined) {- throw failure('codex_runtime_missing', '外部 Codex 模式需要显式选择主程序', input.diagnostics);+ throw failure('codex_runtime_missing', 'Select an executable to use external Codex mode', input.diagnostics);}const codexBin = validateManualCodexPath(input.codexBin, { platform: input.platform });if (codexBin === undefined) {- throw failure('codex_runtime_missing', '选择的外部 Codex 主程序无效', input.diagnostics);+ throw failure('codex_runtime_missing', 'The selected external Codex executable is invalid', input.diagnostics);}const codexHome = join(input.userDataDir, 'runtime', 'external-codex');mkdirSync(codexHome, { recursive: true });@@ -234,7 +234,7 @@ function resolveExternal(input: {if (version !== BUNDLED_VERSION) {throw failure('codex_runtime_version_mismatch',- `外部 Codex 版本不兼容:${version ?? '未知'},需要 ${BUNDLED_VERSION}`,+ `The external Codex version is incompatible: ${version ?? 'unknown'}; requires ${BUNDLED_VERSION}`,input.diagnostics);}@@ -273,7 +273,7 @@ function safeRuntimePath(const path = resolve(root, candidate);const relativePath = relative(root, path);if (relativePath.startsWith('..') || resolve(root, relativePath) !== path) {- throw failure('codex_runtime_hash_mismatch', '内置 Codex Runtime 路径越界', diagnostics);+ throw failure('codex_runtime_hash_mismatch', 'The bundled Codex Runtime path is outside its root directory', diagnostics);}return path;}diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.tsindex 61fa99f6..0981c6b1 100644--- a/apps/desktop/src/main/daemon-manager.ts+++ b/apps/desktop/src/main/daemon-manager.ts@@ -247,7 +247,7 @@ export class DaemonManager extends EventEmitter<DaemonManagerEvents> {const timeoutMs = input.startupTimeoutMs ?? DEFAULT_DAEMON_START_TIMEOUT_MS;fail(new DaemonStartError('DAEMON_START_FAILED',- `本地运行服务在 ${timeoutMs}ms 内未能就绪`,+ `The local Runtime did not become ready within ${timeoutMs}ms`,diagnosticOutputDetails({ stdoutTail, stderrTail })));child.kill();@@ -285,7 +285,7 @@ export class DaemonManager extends EventEmitter<DaemonManagerEvents> {if (!await settlesWithin(exited, 1_000)) {throw new DaemonStartError('DAEMON_STOP_FAILED',- '旧的本地运行服务未确认退出,已取消启动替代进程'+ 'The previous Runtime has not been confirmed stopped. Starting a replacement process was canceled.');}}@@ -516,8 +516,8 @@ export function createDaemonExitError(?? summarizeDaemonFailure(output.stdoutTail);return new DaemonStartError('DAEMON_START_FAILED',- `本地运行服务在就绪前退出(代码 ${String(code)})${- summary === undefined ? '' : `:${summary}`+ `The local Runtime exited before becoming ready (code ${String(code)})${+ summary === undefined ? '' : `: ${summary}`}`,{exitCode: code,diff --git a/apps/desktop/src/main/diagnostics.ts b/apps/desktop/src/main/diagnostics.tsindex 7d170c16..8d2bc672 100644--- a/apps/desktop/src/main/diagnostics.ts+++ b/apps/desktop/src/main/diagnostics.ts@@ -33,12 +33,12 @@ export async function exportDesktopDiagnostics(input: {};const now = dependencies.now();const result = await dependencies.showSaveDialog({- title: '导出 OpenCreator 诊断',+ title: 'Export OpenCreator diagnostics',defaultPath: `opencreator-diagnostics-${now.toISOString().slice(0, 10)}.json`,filters: [{ name: 'JSON', extensions: ['json'] }]});if (result.canceled || result.filePath === undefined) {- return { ok: false, code: 'FAILED', message: '已取消导出' };+ return { ok: false, code: 'FAILED', message: 'Export canceled' };}const desktopLogTail = await readDesktopLogTail(join(input.logDir, 'desktop-main.log'),diff --git a/apps/desktop/src/main/main.ts b/apps/desktop/src/main/main.tsindex ec65d367..83f3ced1 100644--- a/apps/desktop/src/main/main.ts+++ b/apps/desktop/src/main/main.ts@@ -383,26 +383,26 @@ function registerIpcHandlers(input: {});handle(desktopIpc.selectCodex, input.development, async () => {const result = await dialog.showOpenDialog({- title: '选择 Codex 或 ChatGPT',- message: '可直接选择 ChatGPT.app、Codex.app,或 codex 可执行文件',- buttonLabel: '使用所选项目',+ title: 'Select Codex or ChatGPT',+ message: 'Select ChatGPT.app, Codex.app, or the codex executable',+ buttonLabel: 'Use selection',properties: ['openFile']});const path = result.filePaths[0];if (result.canceled || path === undefined) {- return failed('已取消选择');+ return failed('Selection canceled');}await input.bootstrap.selectCodexPath(path);return input.bootstrap.currentState.phase === 'ready'? ok()- : failed(input.bootstrap.currentState.error?.message ?? 'Codex 检测失败');+ : failed(input.bootstrap.currentState.error?.message ?? 'Codex detection failed');});handle(desktopIpc.selectProjectDirectory, input.development, async (_event, purpose: unknown) => {const labels = purpose === 'default-project-root'- ? { title: '选择默认项目位置', buttonLabel: '使用此位置' }+ ? { title: 'Select the default project location', buttonLabel: 'Use this location' }: purpose === 'output-root'- ? { title: '选择完成产物位置', buttonLabel: '使用此位置' }- : { title: '添加项目文件夹', buttonLabel: '添加项目' };+ ? { title: 'Select the output location', buttonLabel: 'Use this location' }+ : { title: 'Add a project folder', buttonLabel: 'Add project' };const result = await dialog.showOpenDialog({...labels,properties: ['openDirectory']@@ -415,7 +415,7 @@ function registerIpcHandlers(input: {await input.bootstrap.restartRuntime();return input.bootstrap.currentState.phase === 'ready'? ok()- : failed(input.bootstrap.currentState.error?.message ?? '本地运行服务重启失败');+ : failed(input.bootstrap.currentState.error?.message ?? 'Failed to restart the local Runtime');} catch (error) {return failed(error instanceof Error ? error.message : String(error));}@@ -424,7 +424,7 @@ function registerIpcHandlers(input: {await input.reloadWorkspace();return input.bootstrap.currentState.phase === 'ready'? ok()- : failed(input.bootstrap.currentState.error?.message ?? 'Dashboard 加载失败');+ : failed(input.bootstrap.currentState.error?.message ?? 'Dashboard failed to load');});handle(desktopIpc.readPreferences, input.development, () => ({closeBehavior: input.settings.read().closeBehavior,@@ -476,7 +476,7 @@ function registerIpcHandlers(input: {await openExternal(url);});handle(desktopIpc.revealPath, input.development, async (_event, path: unknown) => {- if (typeof path !== 'string') return failed('路径必须是字符串');+ if (typeof path !== 'string') return failed('Path must be a string');return await revealPath(path);});handle(desktopIpc.notify, input.development, (_event, message: unknown) => {@@ -486,7 +486,7 @@ function registerIpcHandlers(input: {});handle(desktopIpc.configureNotifications, input.development, (_event, configuration: unknown) => {if (!isRecord(configuration) || typeof configuration.enabled !== 'boolean') {- return failed('通知配置无效');+ return failed('Invalid notification configuration');}input.notifications.configure(configuration.enabled);return ok();diff --git a/apps/desktop/src/main/native-actions.ts b/apps/desktop/src/main/native-actions.tsindex fddd0d38..b7ceb0af 100644--- a/apps/desktop/src/main/native-actions.ts+++ b/apps/desktop/src/main/native-actions.ts@@ -10,7 +10,7 @@ export async function openExternal(url: string): Promise<void> {export async function revealPath(path: string): Promise<DesktopHostResult> {if (!existsSync(path)) {- return { ok: false, code: 'FAILED', message: '路径不存在' };+ return { ok: false, code: 'FAILED', message: 'Path does not exist' };}shell.showItemInFolder(path);return { ok: true };diff --git a/apps/desktop/src/main/tray-manager.ts b/apps/desktop/src/main/tray-manager.tsindex 10c56a43..3e0082c3 100644--- a/apps/desktop/src/main/tray-manager.ts+++ b/apps/desktop/src/main/tray-manager.ts@@ -23,12 +23,12 @@ export class TrayManager {const tray = new Tray(icon);tray.setToolTip('OpenCreator');tray.setContextMenu(Menu.buildFromTemplate([- { label: '打开 OpenCreator', click: input.open },+ { label: 'Open OpenCreator', click: input.open },{ type: 'separator' },- { label: '新建任务', click: () => input.navigate('#/') },- { label: '查看运行中任务', click: () => input.navigate('#/tasks') },+ { label: 'New task', click: () => input.navigate('#/') },+ { label: 'View running tasks', click: () => input.navigate('#/tasks') },{ type: 'separator' },- { label: '退出 OpenCreator', click: input.quit }+ { label: 'Quit OpenCreator', click: input.quit }]));tray.on('click', input.open);this.tray = tray;diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.tsindex 3c5271cd..86a516b3 100644--- a/apps/desktop/src/main/updater.ts+++ b/apps/desktop/src/main/updater.ts@@ -124,10 +124,10 @@ export function startUpdater(input: {try {const choice = await showMessageBox({type: 'info',- title: 'OpenCreator 更新',- message: `发现 OpenCreator ${info.version}`,- detail: '可以在后台下载更新,当前任务不会被中断。',- buttons: ['下载更新', '稍后'],+ title: 'OpenCreator update',+ message: `OpenCreator ${info.version} is available`,+ detail: 'The update can download in the background without interrupting your current tasks.',+ buttons: ['Download update', 'Later'],defaultId: 0,cancelId: 1});@@ -148,10 +148,10 @@ export function startUpdater(input: {try {const choice = await showMessageBox({type: 'info',- title: '更新已下载',- message: `OpenCreator ${info.version} 已准备好`,- detail: '退出并安装会关闭当前本地运行服务,请确认没有需要继续运行的任务。',- buttons: ['退出并安装', '稍后'],+ title: 'Update downloaded',+ message: `OpenCreator ${info.version} is ready to install`,+ detail: 'Quitting to install will stop the local Runtime. Make sure no tasks need to keep running.',+ buttons: ['Quit and install', 'Later'],defaultId: 1,cancelId: 1});diff --git a/apps/web/e2e/fixtures/runtime.ts b/apps/web/e2e/fixtures/runtime.tsindex 6a863ec5..9c9de7cb 100644--- a/apps/web/e2e/fixtures/runtime.ts+++ b/apps/web/e2e/fixtures/runtime.ts@@ -332,7 +332,7 @@ export const test = base.extend<TestFixtures>({legacyProjects: options.legacyProjects});await page.goto(`${origin}/#/thread/${encodeURIComponent(selectedThreadId)}`);- await expect(page.getByRole('status', { name: '本地运行内核正常' })).toBeVisible();+ await expect(page.getByRole('status', { name: 'The local Runtime is ready' })).toBeVisible();if (await page.evaluate(() => localStorage.getItem('opencreator.agent-setup-confirmed.v1') === null)) {const setup = page.getByRole('region', { name: '开始使用 Agent' });await expect(setup).toBeVisible();diff --git a/apps/web/e2e/gateway-account.spec.ts b/apps/web/e2e/gateway-account.spec.tsindex d2c7c680..fa9b5620 100644--- a/apps/web/e2e/gateway-account.spec.ts+++ b/apps/web/e2e/gateway-account.spec.ts@@ -34,10 +34,10 @@ test('独立订阅页面支持游客选套餐、登录后继续购买并返回});await runtime.openApp(page);const navigation = page.getByRole('navigation', { name: 'OpenCreator', exact: true });- const openNavigation = page.getByRole('button', { name: '打开导航', exact: true });+ const openNavigation = page.getByRole('button', { name: 'Open navigation', exact: true });if (await openNavigation.isVisible()) await openNavigation.click();await navigation.getByRole('button', { name: '账户', exact: true }).click();- if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator 导航', { exact: true })).toHaveCSS('visibility', 'hidden');+ if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator navigation', { exact: true })).toHaveCSS('visibility', 'hidden');const center = page.getByRole('main', { name: '账户', exact: true });await expect(center.getByRole('button', { name: '登录 / 注册' })).toBeVisible();await expect(center.getByRole('heading', { name: '订阅套餐', exact: true })).toHaveCount(0);@@ -137,10 +137,10 @@ test('浏览器完成真实网关设备授权,缺少模型配置时保留登await expect.poll(async () => (await runtime.api<{ authState: string }>('GET', '/gateway/account')).authState).toBe('signed_in');await expect(setup).not.toBeVisible();const navigation = page.getByRole('navigation', { name: 'OpenCreator', exact: true });- const openNavigation = page.getByRole('button', { name: '打开导航', exact: true });+ const openNavigation = page.getByRole('button', { name: 'Open navigation', exact: true });if (await openNavigation.isVisible()) await openNavigation.click();await navigation.getByRole('button', { name: '账户', exact: true }).click();- if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator 导航', { exact: true })).toHaveCSS('visibility', 'hidden');+ if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator navigation', { exact: true })).toHaveCSS('visibility', 'hidden');await expect(page).toHaveURL(/#\/account$/);await expect(navigation.getByRole('button', { name: '账户', exact: true })).toHaveAttribute('aria-current', 'page');await expect(navigation.getByRole('button', { name: '模版', exact: true })).not.toHaveAttribute('aria-current', 'page');diff --git a/apps/web/e2e/project-session-ownership.spec.ts b/apps/web/e2e/project-session-ownership.spec.tsindex 509e62e3..53e05d9b 100644--- a/apps/web/e2e/project-session-ownership.spec.ts+++ b/apps/web/e2e/project-session-ownership.spec.ts@@ -145,7 +145,7 @@ test('OpenCreator owns projects and mapped sessions across reloads', async ({ pa});await page.reload();- await expect(page.getByRole('status', { name: '本地运行内核正常' })).toBeVisible();+ await expect(page.getByRole('status', { name: 'The local Runtime is ready' })).toBeVisible();await expect(page.getByRole('heading', { name: '普通会话' })).toBeVisible();await expect(page.getByText(prompt)).toBeVisible();await expect(page.getByText('刷新后仍从 Codex 会话恢复的回答')).toBeVisible();diff --git a/apps/web/e2e/scheduled-task-performance.spec.ts b/apps/web/e2e/scheduled-task-performance.spec.tsindex 699309c2..c0f062d8 100644--- a/apps/web/e2e/scheduled-task-performance.spec.ts+++ b/apps/web/e2e/scheduled-task-performance.spec.ts@@ -78,7 +78,7 @@ test('100 个任务只加载摘要,并按需加载单个任务会话历史', aexpectLoadRequestBudget(initialRequests, taskThreadIds);await page.reload();- await expect(page.getByRole('status', { name: '本地运行内核正常' })).toBeVisible();+ await expect(page.getByRole('status', { name: 'The local Runtime is ready' })).toBeVisible();const refreshSample = await readPerformanceSample(page);const refreshRequests = requests.splice(0);expectLoadRequestBudget(refreshRequests, taskThreadIds);diff --git a/apps/web/e2e/scheduled-task-thread.spec.ts b/apps/web/e2e/scheduled-task-thread.spec.tsindex 20848640..82a1f8be 100644--- a/apps/web/e2e/scheduled-task-thread.spec.ts+++ b/apps/web/e2e/scheduled-task-thread.spec.ts@@ -83,7 +83,7 @@ test('运行中刷新后恢复活动 Run 和 SSE', async ({ page, runtime }) =>await page.getByRole('button', { name: '立即运行任务' }).click();await expect(page.getByRole('status', { name: '任务状态' })).toContainText('运行中');await page.reload();- await expect(page.getByRole('status', { name: '本地运行内核正常' })).toBeVisible();+ await expect(page.getByRole('status', { name: 'The local Runtime is ready' })).toBeVisible();await expect(page.getByRole('heading', { name: schedule.name })).toBeVisible();await expect(page.getByText('刷新后恢复的任务结果')).toBeVisible();await expectNoHorizontalOverflow(page);diff --git a/apps/web/e2e/web-desktop-parity.spec.ts b/apps/web/e2e/web-desktop-parity.spec.tsindex 171fae88..81b5f202 100644--- a/apps/web/e2e/web-desktop-parity.spec.ts+++ b/apps/web/e2e/web-desktop-parity.spec.ts@@ -65,11 +65,11 @@ test('首页和项目页按需加载管理、登录与插件资源且 Browser/Deexpect(resources.some(url => /ProjectManagementDialog|\/packages\/skill-market\//.test(url))).toBe(false);resources.length = 0;await page.reload();- await expect(page.getByRole('status', { name: '本地运行内核正常' })).toBeVisible();+ await expect(page.getByRole('status', { name: 'The local Runtime is ready' })).toBeVisible();await expect(page.locator('.startup-agent-setup')).toHaveCount(0);expect(resources).toHaveLength(0);await page.getByRole('button', { name: '我的项目', exact: true }).click();- const workspace = page.getByRole('region', { name: 'OpenCreator 工作区' });+ const workspace = page.getByRole('region', { name: 'OpenCreator workspace' });const heading = workspace.getByRole('heading', { name: '我的项目', exact: true });await expect(heading).toBeVisible();expect(resources).toHaveLength(0);@@ -1115,7 +1115,7 @@ test('通用界面设置在 Browser/Desktop Bridge 下读取并写入相同 Runtawait page.goto(`${runtime.origin}/#/settings`);const settings = page- .getByRole('region', { name: 'OpenCreator 工作区' })+ .getByRole('region', { name: 'OpenCreator workspace' }).getByRole('main');const lightButton = settings.getByRole('button', { name: '浅色' });const permission = settings.getByRole('combobox', { name: '默认权限' });@@ -1599,7 +1599,7 @@ test('本地 Whisper 在 Browser/Desktop Bridge 下遵守相同 Runtime 能力await runtime.openApp(page);await page.goto(`${runtime.origin}/#/settings?tab=ai-services§ion=transcription`);const settings = page- .getByRole('region', { name: 'OpenCreator 工作区' })+ .getByRole('region', { name: 'OpenCreator workspace' }).getByRole('main');const localMode = settings.getByRole('button', { name: '本地 Whisper' });if (localProvider) {@@ -2042,7 +2042,7 @@ test('第三方组件设置在 Browser/Desktop Bridge 下保持相同状态、await page.goto(`${runtime.origin}/#/settings?tab=local-components`);const settings = page- .getByRole('region', { name: 'OpenCreator 工作区' })+ .getByRole('region', { name: 'OpenCreator workspace' }).getByRole('main');const component = settings.locator('.runtime-component-item').filter({has: page.getByRole('heading', { name: 'yt-dlp nightly' })diff --git a/apps/web/src/app/App.test.tsx b/apps/web/src/app/App.test.tsxindex d261ad7a..6154545b 100644--- a/apps/web/src/app/App.test.tsx+++ b/apps/web/src/app/App.test.tsx@@ -153,7 +153,7 @@ describe('App', () => {render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);expect(await screen.findByRole('heading', { name: 'OpenCreator' })).toBeInTheDocument();- expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('OpenCreator navigation')).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: '稍后配置,进入本地模式' }));expect(await screen.findByText('Agent 尚未配置,暂时无法发送任务。')).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '配置 Agent' }));@@ -179,7 +179,7 @@ describe('App', () => {render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);await waitFor(() => {expect(screen.queryByText('正在检查 Agent 配置…')).not.toBeInTheDocument();- expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument();+ expect(screen.getByLabelText('OpenCreator navigation')).toBeInTheDocument();});expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();}@@ -215,7 +215,7 @@ describe('App', () => {expect(screen.queryByLabelText('Base URL')).not.toBeInTheDocument();expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: '登录 OpenCreator' }));- await waitFor(() => expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument());+ await waitFor(() => expect(screen.getByLabelText('OpenCreator navigation')).toBeInTheDocument());expect(screen.queryByRole('region', { name: '开始使用 Agent' })).not.toBeInTheDocument();expect(screen.queryByText('Agent 尚未配置,暂时无法发送任务。')).not.toBeInTheDocument();if (activationState === 'ready') {@@ -262,13 +262,13 @@ describe('App', () => {render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);await user.click(await screen.findByRole('button', { name: '本地模式' }));expect(await screen.findByText('已找到本机 Codex')).toBeInTheDocument();- expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('OpenCreator navigation')).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: '使用本机 Codex,继续' }));await waitFor(() => expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument());cleanup();render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);- await waitFor(() => expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument());+ await waitFor(() => expect(screen.getByLabelText('OpenCreator navigation')).toBeInTheDocument());expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();cleanup();@@ -300,7 +300,7 @@ describe('App', () => {diagnostics: []})).toEqual(expect.arrayContaining([expect.objectContaining({ category: 'skill', insertText: '$brainstorming ' }),- expect.objectContaining({ category: 'mcp', insertText: '使用 MCP:github ' })+ expect.objectContaining({ category: 'mcp', insertText: 'Use MCP: github ' })]));});@@ -309,7 +309,7 @@ describe('App', () => {Date.parse('2026-07-21T07:00:30.000Z'));- expect(formatRelativeTime('2026-07-21 07:00:00')).toBe('刚刚');+ expect(formatRelativeTime('2026-07-21 07:00:00')).toBe('Just now');now.mockRestore();});@@ -532,7 +532,7 @@ describe('App', () => {expect(await screen.findByRole('heading', { name: '我的项目' })).toBeInTheDocument();expect(screen.getByRole('button', { name: '我的项目' })).toHaveAttribute('aria-current', 'page');- expect(screen.queryByLabelText('项目和对话')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Projects and conversations')).not.toBeInTheDocument();});it('returns to My Projects after opening a creator project from the project list', async () => {@@ -714,12 +714,12 @@ describe('App', () => {/>);- expect(await screen.findByRole('heading', { name: '任务中心' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Task center' })).toBeInTheDocument();expect(window.location.hash).toBe('#/tasks');await user.click(await within(screen.getByRole('list')).findByRole('button', { name: /后台整理任务/ }));- expect(await screen.findByRole('heading', { name: '运行详情' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Run details' })).toBeInTheDocument();expect(screen.getByText('run_task')).toBeInTheDocument();expect(window.location.hash).toBe('#/thread/thread_task');});@@ -808,7 +808,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('heading', { name: '任务中心' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Task center' })).toBeInTheDocument();await user.click(await within(await screen.findByRole('list')).findByRole('button', {name: /每日总结/}));@@ -818,7 +818,7 @@ describe('App', () => {});expect(document.querySelector('[data-search-target="true"]')).toContainElement(approvalRegion);- expect(screen.queryByRole('heading', { name: '运行详情' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Run details' })).not.toBeInTheDocument();expect(window.location.hash).toBe('#/thread/thread_approval_task?runId=run_approval_task&approvalId=approval_task');@@ -829,7 +829,7 @@ describe('App', () => {render(<App fileService={createFileService()} />);- expect(await screen.findByRole('button', { name: '关闭文件工作区' })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: 'Close file workspace' })).toBeInTheDocument();expect(window.location.hash).toBe('#/files?path=docs%2Fatoms.md');});@@ -837,14 +837,14 @@ describe('App', () => {const user = userEvent.setup();render(<App />);- const navigation = await screen.findByLabelText('OpenCreator 导航');- await user.click(screen.getByRole('button', { name: '打开导航' }));+ const navigation = await screen.findByLabelText('OpenCreator navigation');+ await user.click(screen.getByRole('button', { name: 'Open navigation' }));expect(navigation).toHaveAttribute('data-mobile-open', 'true');await user.click(screen.getByRole('button', { name: '工作台' }));expect(navigation).toHaveAttribute('data-mobile-open', 'false');- await user.click(screen.getByRole('button', { name: '打开导航' }));+ await user.click(screen.getByRole('button', { name: 'Open navigation' }));expect(navigation).toHaveAttribute('data-mobile-open', 'true');act(() => window.dispatchEvent(new PopStateEvent('popstate')));@@ -868,16 +868,16 @@ describe('App', () => {render(<App />);- await user.click(await screen.findByRole('button', { name: '打开导航' }));+ await user.click(await screen.findByRole('button', { name: 'Open navigation' }));expect(pushState).toHaveBeenCalledWith(expect.objectContaining({ opencreatorMobileNavigation: true }),'');- await user.click(screen.getByRole('button', { name: '关闭导航' }));+ await user.click(screen.getByRole('button', { name: 'Close navigation' }));expect(back).toHaveBeenCalledTimes(1);- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-mobile-open', 'false');+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-mobile-open', 'false');});it('replaces the temporary mobile drawer entry when navigating from the drawer', async () => {@@ -896,13 +896,13 @@ describe('App', () => {render(<App />);- await user.click(await screen.findByRole('button', { name: '打开导航' }));+ await user.click(await screen.findByRole('button', { name: 'Open navigation' }));await user.click(screen.getByRole('button', { name: '工作台' }));await waitFor(() => expect(window.location.hash).toBe('#/dashboard'));expect(back).not.toHaveBeenCalled();expect(window.history.state?.opencreatorMobileNavigation).not.toBe(true);- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-mobile-open', 'false');+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-mobile-open', 'false');});afterEach(() => {@@ -969,7 +969,7 @@ describe('App', () => {await user.click(screen.getByRole('button', { name: /^视频翻译/ }));expect(await screen.findByRole('heading', { name: '视频翻译配音' })).toBeInTheDocument();- expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('OpenCreator navigation')).not.toBeInTheDocument();const agentInput = screen.getByRole('textbox', { name: '告诉 Agent 你的要求' });expect(agentInput).toHaveAttribute('placeholder',@@ -979,7 +979,7 @@ describe('App', () => {await user.click(within(screen.getByRole('region', { name: '视频翻译操作区' })).getByRole('button', { name: '返回' }));- expect(await screen.findByLabelText('OpenCreator 导航')).toBeInTheDocument();+ expect(await screen.findByLabelText('OpenCreator navigation')).toBeInTheDocument();await waitFor(() => expect(window.location.hash).toBe('#/workbench'));});@@ -1289,7 +1289,7 @@ describe('App', () => {expect(shell?.style.getPropertyValue('--opencreator-titlebar-height')).toBe('38px');expect(shell?.style.getPropertyValue('--opencreator-traffic-light-inset')).toBe('76px');expect(document.querySelector('.desktop-titlebar-drag-region')).toBeInTheDocument();- expect(screen.queryByRole('group', { name: '窗口控制' })).not.toBeInTheDocument();+ expect(screen.queryByRole('group', { name: 'Window controls' })).not.toBeInTheDocument();expect(document.querySelector('.opencreator-main-titlebar')).not.toBeInTheDocument();});@@ -1307,10 +1307,10 @@ describe('App', () => {render(<App fileService={createFileService()} hostBridge={hostBridge} />);await screen.findByRole('button', { name: '工作台' });- const controls = screen.getByRole('group', { name: '窗口控制' });- await user.click(within(controls).getByRole('button', { name: '缩放窗口' }));- await user.click(within(controls).getByRole('button', { name: '最小化窗口' }));- await user.click(within(controls).getByRole('button', { name: '关闭窗口' }));+ const controls = screen.getByRole('group', { name: 'Window controls' });+ await user.click(within(controls).getByRole('button', { name: 'Zoom window' }));+ await user.click(within(controls).getByRole('button', { name: 'Minimize window' }));+ await user.click(within(controls).getByRole('button', { name: 'Close window' }));expect(controlWindow.mock.calls).toEqual([['zoom'], ['minimize'], ['close']]);});@@ -1358,7 +1358,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /hello/ }));const mainTitlebar = document.querySelector<HTMLElement>('.opencreator-main-titlebar');@@ -1367,10 +1367,10 @@ describe('App', () => {expect(document.querySelector('.conversation-page > .conversation-header')).not.toBeInTheDocument();expect(screen.getAllByRole('heading', { name: 'hello' })).toHaveLength(1);- await user.click(within(mainTitlebar!).getByRole('button', { name: '文件' }));+ await user.click(within(mainTitlebar!).getByRole('button', { name: 'Files' }));- expect(await screen.findByLabelText('会话和文件工作区')).toBeInTheDocument();- expect(within(mainTitlebar!).getByRole('button', { name: '文件' }))+ expect(await screen.findByLabelText('Conversation and file workspace')).toBeInTheDocument();+ expect(within(mainTitlebar!).getByRole('button', { name: 'Files' })).toHaveAttribute('aria-pressed', 'true');});@@ -1563,7 +1563,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /浏览器会话标题/ }));const conversationPage = document.querySelector<HTMLElement>('.conversation-page');@@ -1685,19 +1685,19 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '定时任务' }));expect(await screen.findByRole('heading', { name: '每日总结' })).toBeInTheDocument();expect(screen.queryByRole('heading', { name: 'OpenCreator:已安排' })).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '查看上次运行' }));+ await user.click(screen.getByRole('button', { name: 'View last run' }));expect(await screen.findByRole('heading', { name: '每日总结' })).toBeInTheDocument();expect(window.location.hash).toBe('#/thread/thread-schedule-1?runId=run_schedule');- expect(screen.queryByRole('heading', { name: '运行详情' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Run details' })).not.toBeInTheDocument();expect(screen.getByRole('textbox', { name: '输入任务' })).toBeInTheDocument();- expect(screen.getByText('定时执行')).toBeInTheDocument();+ expect(screen.getByText('Scheduled run')).toBeInTheDocument();expect(screen.getByText('生成每日项目摘要')).toBeInTheDocument();});@@ -1764,20 +1764,20 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();- expect(screen.queryByLabelText('任务管理')).not.toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();+ expect(screen.queryByLabelText('Task management')).not.toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /^每日总结/ }));- expect(await screen.findByLabelText('任务管理')).toBeInTheDocument();+ expect(await screen.findByLabelText('Task management')).toBeInTheDocument();expect(document.querySelector('.opencreator-main-titlebar')).toHaveTextContent('每日总结');expect(document.querySelector('.conversation-task-strip--standalone'))- .toContainElement(screen.getByLabelText('任务管理'));+ .toContainElement(screen.getByLabelText('Task management'));expect(document.querySelector('.conversation-page > .conversation-header')).not.toBeInTheDocument();expect(screen.queryByText('需要帮你做点什么')).not.toBeInTheDocument();- expect(screen.getByRole('button', { name: '立即运行任务' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: '暂停任务' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: '编辑任务' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Run task now' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Pause task' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Edit task' })).toBeInTheDocument();});it.each([@@ -1802,7 +1802,7 @@ describe('App', () => {skipped: false,queued: true},- expectedMessage: '本次运行已排队,会在当前任务结束后执行'+ expectedMessage: 'This run is queued and will start after the active task finishes.'},{label: 'skips',@@ -1812,7 +1812,7 @@ describe('App', () => {skipped: true,queued: false},- expectedMessage: '已有任务在运行,本次已跳过'+ expectedMessage: 'A task is already running. This run was skipped.'}])('$label a schedule from its task thread', async ({ response, expectedMessage }) => {const user = userEvent.setup();@@ -1872,7 +1872,7 @@ describe('App', () => {);await user.click(await screen.findByRole('button', { name: '定时任务' }));- await user.click(await screen.findByRole('button', { name: '立即运行每日总结' }));+ await user.click(await screen.findByRole('button', { name: 'Run now 每日总结' }));expect(window.location.hash).toBe('#/thread/thread-schedule-1');runNow.resolve(jsonResponse(response));@@ -1951,12 +1951,12 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '定时任务' }));- expect(await screen.findByRole('heading', { name: '定时任务' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Scheduled tasks' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: /^创建$/ }));- expect(screen.getByRole('dialog', { name: '创建定时任务' })).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: /^Create$/ }));+ expect(screen.getByRole('dialog', { name: 'Create scheduled task' })).toBeInTheDocument();expect(screen.queryByRole('menu')).not.toBeInTheDocument();expect(screen.queryByText('使用 OpenCreator 创建')).not.toBeInTheDocument();expect(findPostCall(fetchCalls, '/threads')).toBeUndefined();@@ -2061,17 +2061,17 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '定时任务' }));- await user.click(await screen.findByRole('button', { name: /^创建$/ }));- expect(screen.getByRole('dialog', { name: '创建定时任务' })).toBeInTheDocument();- expect(screen.getByLabelText('定时任务标题')).toBeInTheDocument();- expect(screen.getByLabelText('任务内容')).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: /^Create$/ }));+ expect(screen.getByRole('dialog', { name: 'Create scheduled task' })).toBeInTheDocument();+ expect(screen.getByLabelText('Scheduled task title')).toBeInTheDocument();+ expect(screen.getByLabelText('Task instructions')).toBeInTheDocument();expect(findPostCall(fetchCalls, '/threads')).toBeUndefined();expect(findPostCall(fetchCalls, '/runs')).toBeUndefined();expect(findPostCall(fetchCalls, '/schedules')).toBeUndefined();expect(scheduleListCalls).toBeGreaterThanOrEqual(1);- expect(screen.queryByLabelText('任务管理')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Task management')).not.toBeInTheDocument();});it('keeps the current project selected while editing a new schedule', async () => {@@ -2139,19 +2139,19 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await waitFor(() => {expect(screen.getByRole('button', { name: 'customer-agent' })).toHaveAttribute('data-current-project', 'true');});await user.click(screen.getByRole('button', { name: '定时任务' }));- await user.click(await screen.findByRole('button', { name: /^创建$/ }));- expect(screen.getByRole('dialog', { name: '创建定时任务' })).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: /^Create$/ }));+ expect(screen.getByRole('dialog', { name: 'Create scheduled task' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'customer-agent' })).toHaveAttribute('data-current-project', 'true');- expect(screen.getByRole('heading', { name: '请选择访问权限' })).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Select access permissions' })).toBeInTheDocument();expect(findPostCall(fetchCalls, '/threads')).toBeUndefined();- expect(within(screen.getByLabelText('customer-agent 对话')).queryByText('任务草稿'))+ expect(within(screen.getByLabelText('customer-agent conversations')).queryByText('Task draft')).not.toBeInTheDocument();});@@ -2239,12 +2239,12 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '定时任务' }));- await user.click(await screen.findByRole('button', { name: /^创建$/ }));- expect(screen.getByRole('dialog', { name: '创建定时任务' })).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: /^Create$/ }));+ expect(screen.getByRole('dialog', { name: 'Create scheduled task' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: '每日文稿' })).toBeInTheDocument();- expect(screen.queryByLabelText('任务管理')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Task management')).not.toBeInTheDocument();expect(scheduleListCalls).toBeGreaterThanOrEqual(2);});@@ -2304,7 +2304,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(runRequests).toEqual([]);await user.click(await screen.findByRole('button', { name: /会话 A/ }));@@ -2312,7 +2312,7 @@ describe('App', () => {expect(await screen.findByRole('button', { name: '停止任务' })).toBeInTheDocument();expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled();expect(screen.queryByRole('button', { name: '排队发送' })).not.toBeInTheDocument();- expect(screen.getByLabelText('正在运行')).toBeInTheDocument();+ expect(screen.getByLabelText('Running')).toBeInTheDocument();expect(runRequests).toEqual(['thread_a']);await user.click(await screen.findByRole('button', { name: /会话 B/ }));@@ -2401,7 +2401,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /队列会话/ }));const textbox = screen.getByRole('textbox', { name: '输入任务' });@@ -2500,7 +2500,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /会话 A/ }));await waitFor(() => {expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled();@@ -2519,7 +2519,7 @@ describe('App', () => {});expect(activeSubscription?.signal?.aborted).toBe(false);expect(screen.queryByText('切换前的实时进度')).not.toBeInTheDocument();- expect(screen.getByRole('button', { name: /会话 A.*正在运行/ })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /会话 A.*Running/ })).toBeInTheDocument();await act(async () => {activeSubscription?.onEvent(@@ -2547,7 +2547,7 @@ describe('App', () => {});await waitFor(() => {- expect(screen.getByRole('button', { name: /会话 A/ })).not.toHaveAccessibleName(/正在运行/);+ expect(screen.getByRole('button', { name: /会话 A/ })).not.toHaveAccessibleName(/Running/);});expect(screen.queryByText('后台完成后的内容')).not.toBeInTheDocument();@@ -2617,7 +2617,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /会话 A/ }));await user.click(await screen.findByRole('button', { name: '停止任务' }));await user.click(screen.getByRole('button', { name: /会话 B/ }));@@ -2689,7 +2689,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /会话 A/ }));await user.click(await screen.findByRole('button', { name: '停止任务' }));@@ -2850,7 +2850,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /断线恢复会话/ }));await waitFor(() => expect(subscriptions).toHaveLength(2), { timeout: 2_000 });@@ -2913,7 +2913,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /会话 A/ }));await waitFor(() => {expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled();@@ -3022,7 +3022,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), '/');expect(await screen.findByRole('listbox', { name: '能力菜单' })).toBeInTheDocument();@@ -3105,9 +3105,9 @@ describe('App', () => {/>);- expect(await screen.findByLabelText('OpenCreator 导航')).toBeInTheDocument();+ expect(await screen.findByLabelText('OpenCreator navigation')).toBeInTheDocument();expect(screen.queryByText('登录即可享受云端协作')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '登录' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Sign in to' })).not.toBeInTheDocument();});@@ -3184,7 +3184,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await waitFor(() => expect(skillRequests).toBe(1));navigateToTestRoute('#/plugins');@@ -3297,7 +3297,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), '/');expect(await screen.findByRole('option', { name: /frontend-slides/ })).toBeInTheDocument();expect(screen.queryByRole('option', { name: /github/ })).not.toBeInTheDocument();@@ -3306,10 +3306,10 @@ describe('App', () => {navigateToTestRoute('#/plugins');await waitFor(() => expect(screen.getAllByTestId('skill-market-card')).toHaveLength(12));await showSkillMarketCard(user, 'frontend-slides');- const marketIssue = await findIssueByDescription('无法加载技能市场,请重试。');+ const marketIssue = await findIssueByDescription('Could not load the skill marketplace. Try again.');expect(marketIssue).not.toHaveTextContent(/诊断编号:OC-/);const card = getSkillMarketCard('frontend-slides');- expect(within(card).queryByText('版本未知')).not.toBeInTheDocument();+ expect(within(card).queryByText('Unknown version')).not.toBeInTheDocument();expect(within(card).getByRole('button', { name: '使用' })).toBeEnabled();expect(within(card).queryByRole('button', { name: '更新' })).not.toBeInTheDocument();});@@ -3346,11 +3346,11 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await waitFor(() => expect(screen.getAllByTestId('skill-market-card')).toHaveLength(12));await showSkillMarketCard(user, 'frontend-slides');- const marketIssue = await findIssueByDescription('无法加载技能市场,请重试。');+ const marketIssue = await findIssueByDescription('Could not load the skill marketplace. Try again.');expect(marketIssue).not.toHaveTextContent(/诊断编号:OC-/);const action = within(getSkillMarketCard('frontend-slides')).getByRole('button', {name: '状态未知'@@ -3397,7 +3397,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');await waitFor(() => expect(within(getSkillMarketCard('frontend-slides')).getByRole('button', { name: '使用' })).toBeEnabled());@@ -3409,17 +3409,17 @@ describe('App', () => {await user.click(within(dialog).getByRole('button', { name: '使用' }));await user.click(screen.getByRole('button', { name: '在 content-design' }));- const useIssue = await findIssueByDescription('无法使用该技能,请重试。');- expect(useIssue).toHaveTextContent('无法使用该技能,请重试。');+ const useIssue = await findIssueByDescription('Could not use this skill. Try again.');+ expect(useIssue).toHaveTextContent('Could not use this skill. Try again.');expect(useIssue).not.toHaveTextContent(/诊断编号:OC-/);- expect(screen.queryByText(/创建对话失败/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Create对话失败/)).not.toBeInTheDocument();await user.click(within(getSkillMarketCard('frontend-slides')).getByRole('button', {name: /打开 .*详情/}));const retryDialog = screen.getByRole('dialog');- expect(within(retryDialog).queryByText(/创建对话失败/)).not.toBeInTheDocument();+ expect(within(retryDialog).queryByText(/Create对话失败/)).not.toBeInTheDocument();await user.click(within(retryDialog).getByRole('button', { name: '使用' }));await user.click(screen.getByRole('button', { name: '在 content-design' }));await waitFor(() => {@@ -3472,7 +3472,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');await waitFor(() => expect(within(getSkillMarketCard('frontend-slides')).getByRole('button', { name: '使用' })).toBeEnabled());@@ -3578,7 +3578,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');await waitFor(() => expect(within(getSkillMarketCard('frontend-slides')).getByRole('button', { name: '安装' })).toBeEnabled());@@ -3659,7 +3659,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await waitFor(() => expect(skillRequests).toBe(1));navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');@@ -3717,15 +3717,15 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');await user.click(await within(getSkillMarketCard('frontend-slides')).findByRole('button', { name: '安装' }));- expect(await findIssueByDescription('无法加载技能市场,请重试。')).not.toHaveTextContent(/诊断编号:OC-/);- expect(within(getSkillMarketCard('frontend-slides')).queryByText('版本未知')).not.toBeInTheDocument();+ expect(await findIssueByDescription('Could not load the skill marketplace. Try again.')).not.toHaveTextContent(/诊断编号:OC-/);+ expect(within(getSkillMarketCard('frontend-slides')).queryByText('Unknown version')).not.toBeInTheDocument();expect(within(getSkillMarketCard('frontend-slides')).getByRole('button', { name: '使用' })).toBeEnabled();- expect(screen.queryByText('安装失败,请重试')).not.toBeInTheDocument();+ expect(screen.queryByText('Installation failed. Try again.')).not.toBeInTheDocument();});it('applies refreshed records and disables actions when update skills refresh fails', async () => {@@ -3781,17 +3781,17 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();navigateToTestRoute('#/plugins');await showSkillMarketCard(user, 'frontend-slides');await user.click(await within(getSkillMarketCard('frontend-slides')).findByRole('button', { name: '更新' }));- expect(await findIssueByDescription('无法加载技能市场,请重试。')).not.toHaveTextContent(/诊断编号:OC-/);+ expect(await findIssueByDescription('Could not load the skill marketplace. Try again.')).not.toHaveTextContent(/诊断编号:OC-/);const action = within(getSkillMarketCard('frontend-slides')).getByRole('button', {name: '状态未知'});expect(action).toBeDisabled();- expect(screen.queryByText('更新失败,请重试')).not.toBeInTheDocument();+ expect(screen.queryByText('Update failed. Try again.')).not.toBeInTheDocument();});it('starts a real runtime run, records SSE events without redundant process detail, and shows Codex info in settings', async () => {@@ -3867,7 +3867,7 @@ describe('App', () => {</StrictMode>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(screen.queryByText('codex-cli test')).not.toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);@@ -3878,7 +3878,7 @@ describe('App', () => {expect(await screen.findByText(/^(?:已完成|已处理 .+)$/)).toBeInTheDocument();expect(screen.queryByText('queued')).not.toBeInTheDocument();expect(screen.queryByText('running')).not.toBeInTheDocument();- expect(screen.queryByText('排队中')).not.toBeInTheDocument();+ expect(screen.queryByText('Queued')).not.toBeInTheDocument();expect(screen.queryByText('处理中')).not.toBeInTheDocument();await user.click(screen.getByText(/^(?:已完成|已处理 .+)$/));@@ -3997,13 +3997,13 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));- expect(await screen.findByText('允许 OpenCreator 执行这条命令?')).toBeInTheDocument();+ expect(await screen.findByText('Allow OpenCreator to run this command?')).toBeInTheDocument();expect(document.querySelector('.composer-approval-overlay')).toBeInTheDocument();- await user.click(screen.getByText('查看操作详情'));+ await user.click(screen.getByText('View operation details'));expect(screen.getByText('rm -rf build')).toBeInTheDocument();const timelineScroller = screen.getByTestId('virtuoso-scroller');const composerWrap = document.querySelector<HTMLElement>('.composer-wrap');@@ -4022,11 +4022,11 @@ describe('App', () => {fireEvent.wheel(composerInput, { deltaY: 80 });expect(timelineScroller.scrollTop).toBe(160);- await user.click(screen.getByRole('button', { name: '允许一次' }));+ await user.click(screen.getByRole('button', { name: 'Allow once' }));await waitFor(() => {expect(screen.queryByText('rm -rf build')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '允许一次' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Allow once' })).not.toBeInTheDocument();});expect(fetchCalls.some(call => (call.url.endsWith('/approvals/approval_1/approve')@@ -4082,7 +4082,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -4096,7 +4096,7 @@ describe('App', () => {await user.click(screen.getByText(/^(?:已完成|已处理 .+)$/));- expect(screen.queryByText('运行详情')).not.toBeInTheDocument();+ expect(screen.queryByText('Run details')).not.toBeInTheDocument();expect(screen.queryByText('queued')).not.toBeInTheDocument();expect(screen.queryByText('running')).not.toBeInTheDocument();expect(screen.queryByText('finalizing')).not.toBeInTheDocument();@@ -4154,7 +4154,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -4224,7 +4224,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -4266,7 +4266,7 @@ describe('App', () => {await Promise.resolve();});- expect(await screen.findByText('运行已取消:用户已取消')).toBeInTheDocument();+ expect(await screen.findByText('Run canceled: Canceled by user')).toBeInTheDocument();expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled();expect(screen.queryByRole('button', { name: '停止任务' })).not.toBeInTheDocument();});@@ -4351,7 +4351,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -4362,9 +4362,9 @@ describe('App', () => {await user.click(screen.getByText(/^(?:已完成|已处理 .+)$/));expect(screen.getByText('我会先确认当前目录,再读取必要文件。')).toBeInTheDocument();- expect(screen.queryByText('正在查看项目内容')).not.toBeInTheDocument();+ expect(screen.queryByText('Running: Read project files')).not.toBeInTheDocument();expect(screen.queryByText('pwd')).not.toBeInTheDocument();- expect(screen.getByText('已读取文件')).toBeInTheDocument();+ expect(screen.getByText('Read files')).toBeInTheDocument();expect(screen.queryByText('工具完成 call_1')).not.toBeInTheDocument();expect(screen.getByText('当前目录是 /repo,检查已完成。')).toBeInTheDocument();expect(container.querySelectorAll('.timeline-assistant_message')).toHaveLength(1);@@ -4421,9 +4421,9 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '整理本周项目进展 4天' }));+ await user.click(screen.getByRole('button', { name: '整理本周项目进展 4d ago' }));expect(await screen.findByRole('heading', { name: '整理本周项目进展' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);@@ -4432,9 +4432,9 @@ describe('App', () => {expect(await findTimelineUserMessage(prompt)).toBeInTheDocument();expect(await screen.findByText('周报已整理。')).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '在 content-design 中新建会话' }));+ await user.click(screen.getByRole('button', { name: 'New conversation in content-design' }));- expect(screen.queryByRole('heading', { name: '新对话' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'New conversation' })).not.toBeInTheDocument();expect(screen.getByText('需要帮你做点什么')).toBeInTheDocument();expect(screen.queryByRole('button', { name: /选择项目 / })).not.toBeInTheDocument();expect(screen.queryByText(prompt)).not.toBeInTheDocument();@@ -4540,7 +4540,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: '默认项目' })).toHaveAttribute('data-current-project', 'true');await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);@@ -4593,7 +4593,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(screen.getByRole('button', { name: /Playground 历史会话/ })).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'playground' })).not.toBeInTheDocument();@@ -4653,7 +4653,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', {name: new RegExp(`^${hostKind} 归档会话 `)}));@@ -4661,9 +4661,9 @@ describe('App', () => {const conversation = screen.getByRole('group', {name: `${hostKind} 归档会话`});- await user.click(within(conversation).getByRole('button', { name: '归档' }));- const archiveDialog = screen.getByRole('alertdialog', { name: '归档对话' });- await user.click(within(archiveDialog).getByRole('button', { name: '归档' }));+ await user.click(within(conversation).getByRole('button', { name: 'Archive' }));+ const archiveDialog = screen.getByRole('alertdialog', { name: 'Archive conversation' });+ await user.click(within(archiveDialog).getByRole('button', { name: 'Archive' }));await waitFor(() => {expect(screen.queryByRole('button', {@@ -4710,9 +4710,9 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: 'legacy-project' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '管理项目' }));+ await user.click(screen.getByRole('button', { name: 'Manage projects' }));await user.click(await screen.findByRole('button', { name: '使用现有文件夹' }));expect(hostBridge.selectProjectDirectory).toHaveBeenCalledTimes(1);await waitFor(() => {@@ -4726,9 +4726,9 @@ describe('App', () => {expect(findPostCall(fetchCalls, '/projects')).toBeDefined();expect(window.localStorage.getItem(PROJECTS_STORAGE_KEY)).toBe(legacyProjects);- await user.click(screen.getByRole('button', { name: '项目操作 官网资料' }));- await user.click(screen.getByRole('menuitem', { name: '移除项目 官网资料' }));- await user.click(screen.getByRole('button', { name: '移除项目' }));+ await user.click(screen.getByRole('button', { name: 'Project actions 官网资料' }));+ await user.click(screen.getByRole('menuitem', { name: 'Remove project 官网资料' }));+ await user.click(screen.getByRole('button', { name: 'Remove project' }));await waitFor(() => {expect(screen.queryByRole('button', { name: '官网资料' })).not.toBeInTheDocument();@@ -4769,10 +4769,10 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();- await user.click(await screen.findByRole('button', { name: '创建项目' }));+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: 'Create project' }));- expect(screen.queryByRole('dialog', { name: '创建项目' })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Create project' })).not.toBeInTheDocument();expect(await screen.findByRole('button', { name: '项目' })).toBeInTheDocument();const createCall = findPostCall(fetchCalls, '/projects/managed');@@ -4814,7 +4814,7 @@ describe('App', () => {expect(await screen.findByRole('heading', { name: '我的项目' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '新建项目' }));expect(screen.getByRole('menu', { name: '项目类型' })).toBeInTheDocument();- expect(screen.queryByRole('dialog', { name: '创建项目' })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Create project' })).not.toBeInTheDocument();await user.click(screen.getByRole('menuitem', { name: /图像生成/ }));expect(await screen.findByRole(@@ -4859,21 +4859,21 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();const dropRoot = document.querySelector<HTMLElement>('[data-project-drop-root="true"]');if (dropRoot === null) throw new Error('Expected project drop root');const folder = new File([], 'dropped-project');const dataTransfer = createDirectoryDataTransfer(folder);fireEvent.dragEnter(dropRoot, { dataTransfer });- expect(screen.getByText('松开以添加项目文件夹')).toBeInTheDocument();+ expect(screen.getByText('Drop to add a project folder')).toBeInTheDocument();fireEvent.drop(dropRoot, { dataTransfer });expect(hostBridge.resolveDroppedFilePath).toHaveBeenCalledWith(folder);expect(await screen.findByRole('button', { name: 'dropped-project' })).toBeInTheDocument();expect(findPostCall(fetchCalls, '/projects')).toBeDefined();- expect(screen.queryByText('松开以添加项目文件夹')).not.toBeInTheDocument();+ expect(screen.queryByText('Drop to add a project folder')).not.toBeInTheDocument();});it('opens only one project directory picker while the previous request is pending', async () => {@@ -4910,8 +4910,8 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '管理项目' }));+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Manage projects' }));await user.click(await screen.findByRole('button', { name: '使用现有文件夹' }));await user.click(screen.getByRole('button', { name: '使用现有文件夹' }));@@ -4957,9 +4957,9 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();- await user.click(await screen.findByRole('button', { name: '创建项目' }));- expect(screen.queryByRole('dialog', { name: '创建项目' })).not.toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: 'Create project' }));+ expect(screen.queryByRole('dialog', { name: 'Create project' })).not.toBeInTheDocument();await waitFor(() => {expect(fetchCalls.map(call => [call.url, call.init?.method])).toContainEqual([@@ -4972,7 +4972,7 @@ describe('App', () => {expect(await screen.findByRole('button', { name: '项目' })).toHaveAttribute('data-current-project', 'true');- await user.click(screen.getByRole('button', { name: '管理项目' }));+ await user.click(screen.getByRole('button', { name: 'Manage projects' }));await user.click(await screen.findByRole('button', { name: '使用现有文件夹' }));expect(hostBridge.selectProjectDirectory).toHaveBeenCalledTimes(1);@@ -5031,7 +5031,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: /Playground 历史会话/ })).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'thread_RwiAbzbZ8p' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: 'thread_1Qm6X_K0eo' })).not.toBeInTheDocument();@@ -5113,7 +5113,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -5121,9 +5121,9 @@ describe('App', () => {expect(await findTimelineUserMessage(prompt)).toBeInTheDocument();expect(await screen.findByText('周报已整理。')).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '在 secondary 中新建会话' }));+ await user.click(screen.getByRole('button', { name: 'New conversation in secondary' }));- expect(screen.queryByRole('heading', { name: '新对话' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'New conversation' })).not.toBeInTheDocument();expect(screen.getByText('需要帮你做点什么')).toBeInTheDocument();expect(Array.from(document.querySelectorAll('.timeline-user_message')).some(message => message.textContent?.includes(prompt)@@ -5239,13 +5239,13 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), '旧任务');await user.click(screen.getByRole('button', { name: '发送' }));await waitFor(() => expect(subscriptionSequence).toBe(1));- await user.click(screen.getByRole('button', { name: '在 secondary 中新建会话' }));+ await user.click(screen.getByRole('button', { name: 'New conversation in secondary' }));await user.type(screen.getByRole('textbox', { name: '输入任务' }), '新任务');await user.click(screen.getByRole('button', { name: '发送' }));await waitFor(() => expect(subscriptionSequence).toBe(2));@@ -5340,7 +5340,7 @@ describe('App', () => {const firstRender = render(<App {...appProps} />);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: 'bili' }));await user.click(await screen.findByRole('button', { name: /bili 历史/ }));expect(await findTimelineUserMessage('刷新后仍然打开这条对话')).toBeInTheDocument();@@ -5463,9 +5463,9 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: /真实 Codex 历史会话/ })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: '整理本周项目进展 4天' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: '整理本周项目进展 4d ago' })).not.toBeInTheDocument();});it('loads task summaries without preloading task history or listing task threads as conversations', async () => {@@ -5535,13 +5535,13 @@ describe('App', () => {/>);- const conversationList = await screen.findByLabelText('content-design 对话');- const taskList = await screen.findByLabelText('任务会话');+ const conversationList = await screen.findByLabelText('content-design conversations');+ const taskList = await screen.findByLabelText('Task conversations');expect(within(conversationList).getByRole('button', { name: /普通会话/ })).toBeInTheDocument();- expect(within(taskList).getByRole('button', { name: /任务草稿.*草稿/ }))+ expect(within(taskList).getByRole('button', { name: /任务草稿.*Draft/ })).toHaveClass('sidebar-task-row');- expect(within(conversationList).queryByText('任务草稿'))+ expect(within(conversationList).queryByText('Task draft')).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: /任务线程旧标题/ })).not.toBeInTheDocument();await waitFor(() => {@@ -5646,8 +5646,8 @@ describe('App', () => {/>);- const conversationList = await screen.findByLabelText('content-design 对话');- const taskList = await screen.findByLabelText('任务会话');+ const conversationList = await screen.findByLabelText('content-design conversations');+ const taskList = await screen.findByLabelText('Task conversations');await user.click(within(conversationList).getByRole('button', { name: /普通会话/ }));expect(await screen.findByText('旧会话内容')).toBeInTheDocument();@@ -5729,7 +5729,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /真实 Codex 历史会话/ }));expect(await findTimelineUserMessage('分析这个 skill 是干什么的')).toBeInTheDocument();@@ -5741,7 +5741,7 @@ describe('App', () => {expect(screen.getByText('先读取 skill 说明。')).toBeInTheDocument();expect(screen.getByText('这个 skill 用于分析选品资料。')).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '编辑消息' }));+ await user.click(screen.getByRole('button', { name: 'Edit message' }));expect(screen.getByRole('textbox', { name: '输入任务' })).toHaveValue('分析这个 skill 是干什么的');@@ -5830,7 +5830,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /分页历史会话/ }));expect(await screen.findByText('最新一页内容')).toBeInTheDocument();@@ -5840,7 +5840,7 @@ describe('App', () => {'http://127.0.0.1:60764/threads/thread_paged_history/history?limit=50']);- await user.click(screen.getByRole('button', { name: '加载更早记录' }));+ await user.click(screen.getByRole('button', { name: 'Load earlier history' }));expect(await findTimelineUserMessage('更早的一页内容')).toBeInTheDocument();expect(document.querySelectorAll('.timeline-user_message')).toHaveLength(2);@@ -5961,13 +5961,13 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /无 Turn ID 的分页会话/ }));await user.click(await screen.findByText(/^(?:已完成|已处理 .+)$/));expect(screen.getByText('当前任务的处理过程')).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '加载更早记录' }));+ await user.click(screen.getByRole('button', { name: 'Load earlier history' }));expect(await findTimelineUserMessage('更早的任务')).toBeInTheDocument();expect(screen.getByText('当前任务的处理过程')).toBeInTheDocument();@@ -6030,7 +6030,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /刚生成的内容/ }));expect(await findTimelineUserMessage('帮我生成视频脚本')).toBeInTheDocument();@@ -6128,7 +6128,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(await screen.findByRole('searchbox', { name: '搜索会话' }), 'App.tsx');const result = await screen.findByTestId('search-result-title');await user.click(within(result).getByRole('button'));@@ -6200,7 +6200,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();const conversationButton = await screen.findByRole('button', { name: /当前打开的历史/ });await user.click(conversationButton);@@ -6287,7 +6287,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /content-design 历史/ }));expect(await findTimelineUserMessage('上一条会话内容保持可见')).toBeInTheDocument();@@ -6415,20 +6415,20 @@ describe('App', () => {);await user.click(await screen.findByRole('button', { name: /真实文件会话/ }));- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));- expect(await screen.findByLabelText('会话和文件工作区')).toBeInTheDocument();- expect(screen.getByRole('button', { name: '文件' })).toHaveAttribute('aria-pressed', 'true');+ expect(await screen.findByLabelText('Conversation and file workspace')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Files' })).toHaveAttribute('aria-pressed', 'true');expect(screen.getByRole('heading', { name: '真实文件会话' })).toBeInTheDocument();expect(await screen.findByRole('heading', { name: 'Workspace' })).toBeInTheDocument();- expect(screen.queryByText('打开文件')).not.toBeInTheDocument();+ expect(screen.queryByText('Open file')).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: '返回对话' })).not.toBeInTheDocument();- expect(screen.queryByText('暂无预览内容')).not.toBeInTheDocument();+ expect(screen.queryByText('No preview available')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));- expect(screen.queryByLabelText('会话和文件工作区')).not.toBeInTheDocument();- expect(screen.getByRole('button', { name: '文件' })).toHaveAttribute('aria-pressed', 'false');+ expect(screen.queryByLabelText('Conversation and file workspace')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Files' })).toHaveAttribute('aria-pressed', 'false');});it('点击聊天回复中的成果卡片会直接打开对应文件', async () => {@@ -6567,12 +6567,12 @@ describe('App', () => {);await user.click(await screen.findByRole('button', { name: /真实文件会话/ }));- await user.click(await screen.findByRole('button', { name: `打开成果 ${absoluteChangedPath}` }));+ await user.click(await screen.findByRole('button', { name: `Open output ${absoluteChangedPath}` }));- expect(await screen.findByLabelText('会话和文件工作区')).toBeInTheDocument();- expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML 预览')).toBeInTheDocument();- expect(screen.queryByText('选择一个文件')).not.toBeInTheDocument();- expect(screen.queryByText('已编辑 docs/atoms.md')).not.toBeInTheDocument();+ expect(await screen.findByLabelText('Conversation and file workspace')).toBeInTheDocument();+ expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML preview')).toBeInTheDocument();+ expect(screen.queryByText('Select a file')).not.toBeInTheDocument();+ expect(screen.queryByText('Edited docs/atoms.md')).not.toBeInTheDocument();expect(fetchCalls.some(call => (call.url.includes('/workspace/files/meta?')@@ -6690,16 +6690,16 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();- const navigation = screen.getByLabelText('OpenCreator 导航');+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();+ const navigation = screen.getByLabelText('OpenCreator navigation');expect(navigation).toHaveAttribute('data-collapsed', 'false');await user.click(await screen.findByRole('button', { name: /真实文件会话/ }));- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));await screen.findByRole('heading', { name: 'Workspace' });expect(navigation).toHaveAttribute('data-collapsed', 'true');expect(screen.getByRole('button', { name: '侧栏已自动收起' })).toBeInTheDocument();- const layout = screen.getByLabelText('会话和文件工作区');+ const layout = screen.getByLabelText('Conversation and file workspace');vi.spyOn(layout, 'getBoundingClientRect').mockReturnValue({x: 0,y: 0,@@ -6712,7 +6712,7 @@ describe('App', () => {toJSON: () => undefined});- const separator = screen.getByRole('separator', { name: '调整会话和文件区域宽度' });+ const separator = screen.getByRole('separator', { name: 'Resize the conversation and file areas' });fireEvent.mouseDown(separator, { button: 0, clientX: 420 });expect(document.querySelector('.pane-resize-shield')).not.toBeNull();fireEvent.mouseMove(window, { clientX: 520 });@@ -6727,7 +6727,7 @@ describe('App', () => {expect(layout).toHaveStyle({ '--conversation-pane-width': '914px' });- await user.click(screen.getByRole('button', { name: '关闭文件工作区' }));+ await user.click(screen.getByRole('button', { name: 'Close file workspace' }));expect(navigation).toHaveAttribute('data-collapsed', 'false');});@@ -6854,22 +6854,22 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /文件会话 A/ }));- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));expect(await screen.findByRole('heading', { name: 'A.md' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: /文件会话 B/ }));- expect(screen.getByLabelText('会话和文件工作区')).toBeInTheDocument();+ expect(screen.getByLabelText('Conversation and file workspace')).toBeInTheDocument();expect(await screen.findByRole('heading', { name: 'B.md' })).toBeInTheDocument();await user.click(screen.getByRole('button', { name: /空文件会话/ }));await waitFor(() => {- expect(screen.queryByLabelText('会话和文件工作区')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Conversation and file workspace')).not.toBeInTheDocument();});await user.click(screen.getByRole('button', { name: /文件会话 A/ }));- expect(screen.queryByLabelText('会话和文件工作区')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Conversation and file workspace')).not.toBeInTheDocument();});@@ -6993,14 +6993,14 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /只读文件会话/ }));- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));- expect(await screen.findByText('当前会话为只读模式,不能保存文件')).toBeInTheDocument();+ expect(await screen.findByText('This conversation is read-only. Files cannot be saved.')).toBeInTheDocument();expect(await screen.findByRole('heading', { name: 'Workspace' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '编辑' }));- expect(await screen.findByRole('textbox', { name: 'README.md 编辑器' })).toHaveAttribute('aria-readonly', 'true');+ await user.click(screen.getByRole('button', { name: 'Edit' }));+ expect(await screen.findByRole('textbox', { name: 'README.md editor' })).toHaveAttribute('aria-readonly', 'true');await user.click(screen.getByRole('button', { name: '选择访问权限 请求批准' }));await user.click(screen.getByRole('menuitemradio', { name: /完全访问/ }));@@ -7009,10 +7009,10 @@ describe('App', () => {await waitFor(() => {expect(findPatchCall(fetchCalls, '/threads/thread_files')).toBeDefined();});- expect(screen.queryByText('当前会话为只读模式,不能保存文件')).not.toBeInTheDocument();+ expect(screen.queryByText('This conversation is read-only. Files cannot be saved.')).not.toBeInTheDocument();expect(await screen.findByRole('heading', { name: 'Workspace' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '编辑' }));- expect(await screen.findByRole('textbox', { name: 'README.md 编辑器' })).toHaveAttribute('aria-readonly', 'false');+ await user.click(screen.getByRole('button', { name: 'Edit' }));+ expect(await screen.findByRole('textbox', { name: 'README.md editor' })).toHaveAttribute('aria-readonly', 'false');});it('不显示无用途的详情按钮,点击文件进入真实文件工作区', async () => {@@ -7114,21 +7114,21 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /真实文件会话/ }));- expect(screen.queryByRole('button', { name: '详情' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'details' })).not.toBeInTheDocument();expect(screen.queryByRole('heading', { name: 'README.md' })).not.toBeInTheDocument();- expect(screen.queryByText('已编辑 docs/atoms.md')).not.toBeInTheDocument();+ expect(screen.queryByText('Edited docs/atoms.md')).not.toBeInTheDocument();expect(screen.queryByText('+903 -0')).not.toBeInTheDocument();- expect(screen.queryByText('暂无预览内容')).not.toBeInTheDocument();- expect(screen.queryByText('打开文件')).not.toBeInTheDocument();+ expect(screen.queryByText('No preview available')).not.toBeInTheDocument();+ expect(screen.queryByText('Open file')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '文件' }));- expect(screen.getByLabelText('会话和文件工作区')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Files' }));+ expect(screen.getByLabelText('Conversation and file workspace')).toBeInTheDocument();expect(screen.getByRole('heading', { name: '真实文件会话' })).toBeInTheDocument();expect(await screen.findByRole('heading', { name: 'Workspace' })).toBeInTheDocument();- expect(screen.queryByText('打开文件')).not.toBeInTheDocument();+ expect(screen.queryByText('Open file')).not.toBeInTheDocument();});it('loads migrated projects from Runtime and never renders local home', async () => {@@ -7186,7 +7186,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: 'content-design' })).toHaveAttribute('data-current-project', 'true');expect(screen.queryByRole('button', { name: '本机目录' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: 'opencreator-agent' })).not.toBeInTheDocument();@@ -7231,7 +7231,7 @@ describe('App', () => {expect(screen.getByRole('button', { name: '选择模型 Cached GPT' })).toBeInTheDocument();- expect(await screen.findByRole('status', { name: '本地运行内核正常' }))+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();modelResponse.resolve(jsonResponse(liveCatalog));@@ -7273,14 +7273,14 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' }))+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();const modelButton = await screen.findByRole('button', {name: '选择模型 Cached GPT'});await user.click(modelButton);- expect(await screen.findByText('模型目录刷新失败,当前使用本地缓存'))+ expect(await screen.findByText('Could not refresh the model catalog. Using the local cache.')).toBeInTheDocument();expect(screen.queryByText('暂无可用模型')).not.toBeInTheDocument();});@@ -7322,7 +7322,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' }))+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', {name: '选择模型 默认模型'@@ -7380,7 +7380,7 @@ describe('App', () => {expect(composer).toBeDisabled();await waitFor(() => expect(composer).toBeEnabled(), { timeout: 4_000 });expect(threadListCalls).toBe(2);- expect(screen.getByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(screen.getByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: '重试连接' })).not.toBeInTheDocument();});@@ -7413,7 +7413,7 @@ describe('App', () => {render(<App fileService={createFileService()} hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);await waitFor(() => expect(migrationCalls).toBe(1));- await screen.findByRole('status', { name: '本地运行内核正常' }, { timeout: 4_000 });+ await screen.findByRole('status', { name: 'The local Runtime is ready' }, { timeout: 4_000 });expect(migrationCalls).toBe(2);expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled();});@@ -7490,7 +7490,7 @@ describe('App', () => {};render(<App fileService={createFileService()} hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);- await screen.findByRole('status', { name: '本地运行内核正常' });+ await screen.findByRole('status', { name: 'The local Runtime is ready' });const conversation = await screen.findByRole('button', { name: /保留的会话/ });fireEvent.click(conversation);const composer = await screen.findByRole('textbox', { name: '输入任务' });@@ -7504,7 +7504,7 @@ describe('App', () => {await waitFor(() => expect(failedHealthChecks).toBeGreaterThan(0));available = true;- await waitFor(() => expect(screen.getByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument(), {+ await waitFor(() => expect(screen.getByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument(), {timeout: 4_000});expect(screen.getByRole('textbox', { name: '输入任务' })).toHaveValue('恢复后继续这段草稿');@@ -7544,7 +7544,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' }))+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(await screen.findByRole('button', { name: '选择模型 GPT-5.5' })).toBeInTheDocument();@@ -7651,7 +7651,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.type(screen.getByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));@@ -7742,7 +7742,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: /Profile/ })).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: '选择访问权限 请求批准' }));@@ -7827,7 +7827,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /已有会话/ }));await user.click(await screen.findByRole('button', {name: '选择模型 GPT-5.6 Sol'@@ -7858,7 +7858,7 @@ describe('App', () => {await user.click(screen.getByRole('button', { name: '返回应用' }));- expect(screen.queryByRole('heading', { name: '新对话' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'New conversation' })).not.toBeInTheDocument();expect(screen.queryByText('需要帮你做点什么')).not.toBeInTheDocument();expect(await screen.findByText('精选模板')).toBeInTheDocument();expect(window.location.hash).toBe('#/new');@@ -7905,7 +7905,7 @@ describe('App', () => {render(<App fileService={createFileService()} />);- expect(screen.queryByRole('heading', { name: '新对话' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'New conversation' })).not.toBeInTheDocument();expect(screen.queryByTestId('conversation-lightfall-background')).not.toBeInTheDocument();expect(document.querySelector('.conversation-page')).not.toHaveAttribute('data-background-mode');expect(document.querySelector('.conversation-page')).not.toHaveAttribute('data-dynamic-background');@@ -8026,7 +8026,7 @@ describe('App', () => {};const firstRender = render(<App {...appProps} />);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: 'secondary' }));expect(screen.getByRole('button', { name: '选择访问权限 完全访问权限' })).toBeInTheDocument();@@ -8203,7 +8203,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /运行中的权限会话/ }));const permissionButton = await screen.findByRole('button', {@@ -8267,7 +8267,7 @@ describe('App', () => {/>);- expect(await screen.findByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument();+ expect(await screen.findByRole('status', { name: 'The local Runtime is ready' })).toBeInTheDocument();await user.click(await screen.findByRole('button', { name: /权限切换竞争/ }));await user.click(await screen.findByRole('button', {name: '选择访问权限 请求批准'@@ -8275,8 +8275,8 @@ describe('App', () => {await user.click(screen.getByRole('menuitemradio', { name: /完全访问权限/ }));await user.click(screen.getByRole('button', { name: '开启' }));- const permissionIssue = await findIssueByDescription('会话配置未更新,请重试。');- expect(permissionIssue).toHaveTextContent('会话配置未更新,请重试。');+ const permissionIssue = await findIssueByDescription('Conversation settings were not updated. Try again.');+ expect(permissionIssue).toHaveTextContent('Conversation settings were not updated. Try again.');expect(permissionIssue).not.toHaveTextContent(/诊断编号:OC-/);expect(permissionIssue).not.toHaveTextContent('Thread has active run');expect(screen.getByRole('button', { name: '选择访问权限 请求批准' }))@@ -8424,14 +8424,14 @@ describe('App', () => {await user.click(screen.getByRole('button', { name: '设置' }));await user.click(await screen.findByRole('button', { name: '记忆' }));expect(await screen.findByText('提交前运行全部测试')).toBeInTheDocument();- expect(screen.getByText('版本 1')).toBeInTheDocument();+ expect(screen.getByText('Version 1')).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '返回应用' }));const prompt = '以后默认运行全量测试';await user.type(await screen.findByRole('textbox', { name: '输入任务' }), prompt);await user.click(screen.getByRole('button', { name: '发送' }));- expect(await screen.findByRole('region', { name: '记忆建议' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '忽略记忆建议' }));+ expect(await screen.findByRole('region', { name: 'Memory suggestion' })).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Dismiss memory suggestion' }));expect(fetchCalls.some(call => (call.url.endsWith('/memories') && call.init?.method === 'POST'))).toBe(false);diff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsxindex d7679626..7098bf78 100644--- a/apps/web/src/app/AppController.tsx+++ b/apps/web/src/app/AppController.tsx@@ -424,15 +424,15 @@ export function AppController(props: AppControllerProps) {const appIssueSignalsRef = useRef<Record<string, string | undefined>>({});useEffect(() => {const signals = [- ['app.load-files', treeLoadError, '无法加载文件列表,请重试。'],- ['app.project-operation', projectLoadError, '项目操作未完成,请查看诊断后重试。'],- ['app.thread-operation', threadLoadError, '会话操作未完成,请查看诊断后重试。'],- ['app.load-thread-history', threadHistoryLoadError, '无法加载会话历史,请重试。'],- ['app.update-thread-config', threadConfigUpdateError, '会话配置未更新,请重试。'],- ['app.load-skill-market', skillMarketLoadError, '无法加载技能市场,请重试。'],- ['app.mutate-skill-market', skillMarketOperation?.error, '技能安装或更新未完成,请重试。'],- ['app.use-skill', skillMarketUseError?.error, '无法使用该技能,请重试。'],- ['app.sync-default-permission', defaultPermissionSyncError, '默认权限同步失败,重新打开相关会话后会重试。']+ ['app.load-files', treeLoadError, 'Could not load the file list. Try again.'],+ ['app.project-operation', projectLoadError, 'The project operation did not complete. Check diagnostics and try again.'],+ ['app.thread-operation', threadLoadError, 'The conversation operation did not complete. Check diagnostics and try again.'],+ ['app.load-thread-history', threadHistoryLoadError, 'Could not load conversation history. Try again.'],+ ['app.update-thread-config', threadConfigUpdateError, 'Conversation settings were not updated. Try again.'],+ ['app.load-skill-market', skillMarketLoadError, 'Could not load the skill marketplace. Try again.'],+ ['app.mutate-skill-market', skillMarketOperation?.error, 'Skill installation or update did not complete. Try again.'],+ ['app.use-skill', skillMarketUseError?.error, 'Could not use this skill. Try again.'],+ ['app.sync-default-permission', defaultPermissionSyncError, 'Default permission synchronization failed. Reopen the conversation to retry.']] as const;for (const [operationId, error, fallback] of signals) {if (appIssueSignalsRef.current[operationId] === error) continue;@@ -1282,10 +1282,10 @@ export function AppController(props: AppControllerProps) {?? codexModelsRef.current;if (fallbackModels !== undefined && fallbackModels.models.length > 0) {setCodexModels(fallbackModels);- setCodexModelsNotice('模型目录刷新失败,当前使用本地缓存');+ setCodexModelsNotice('Could not refresh the model catalog. Using the local cache.');} else {setCodexModels(undefined);- setCodexModelsLoadError('无法加载模型列表');+ setCodexModelsLoadError('Could not load the model list');}}})@@ -1310,7 +1310,7 @@ export function AppController(props: AppControllerProps) {}}).catch(() => {- if (!canceled) setTreeLoadError('无法加载项目文件');+ if (!canceled) setTreeLoadError('Could not load project files');});return () => {@@ -1383,7 +1383,7 @@ export function AppController(props: AppControllerProps) {if (canceled) return;initialProjectError = getRuntimeErrorMessage(error,- '无法自动创建默认项目,请手动添加项目'+ 'Could not create the default project. Add a project manually.');}}@@ -1433,11 +1433,11 @@ export function AppController(props: AppControllerProps) {dispatch({ type: 'new_conversation' });return;}- setThreadLoadError('无法恢复上次打开的历史会话');+ setThreadLoadError('Could not restore the last conversation');}} catch {if (canceled) return;- setProjectLoadError('无法迁移或加载项目,请稍后重试');+ setProjectLoadError('Could not migrate or load projects. Try again later.');setThreadLoadError(undefined);} finally {if (!canceled) {@@ -1520,7 +1520,7 @@ export function AppController(props: AppControllerProps) {}).catch(error => {if (!canceled) {- setCreatorJobsError(getRuntimeErrorMessage(error, '无法加载最近项目'));+ setCreatorJobsError(getRuntimeErrorMessage(error, 'Could not load recent projects'));}}).finally(() => {@@ -1619,14 +1619,14 @@ export function AppController(props: AppControllerProps) {setRuntimeThreads(previous => upsertThread(previous, response.thread));setDefaultPermissionSyncError(defaultPermissionSyncFailuresRef.current.size > 0- ? '部分普通会话的全局权限同步失败,重新打开会话后会重试'+ ? 'Global permission synchronization failed for some conversations. Reopen them to retry.': undefined);}).catch(() => {if (!mountedRef.current) return;defaultPermissionSyncFailuresRef.current.add(thread.id);- setDefaultPermissionSyncError('部分普通会话的全局权限同步失败,重新打开会话后会重试');+ setDefaultPermissionSyncError('Global permission synchronization failed for some conversations. Reopen them to retry.');});}}, [@@ -1695,7 +1695,7 @@ export function AppController(props: AppControllerProps) {if (mcpResult?.status === 'fulfilled') setCodexMcp(mcpResult.value);else setCodexMcp(undefined);if (skillsResult?.status === 'rejected' || mcpResult?.status === 'rejected') {- setCapabilitiesLoadError('本机能力检测失败');+ setCapabilitiesLoadError('Could not detect local capabilities');}}).finally(() => {@@ -1813,8 +1813,8 @@ export function AppController(props: AppControllerProps) {if (recordsResult?.status === 'fulfilled') setSkillMarketInstallRecords(recordsResult.value.records);else setSkillMarketInstallRecords(undefined);const marketErrors: string[] = [];- if (skillsResult?.status === 'rejected') marketErrors.push('技能状态加载失败');- if (recordsResult?.status === 'rejected') marketErrors.push('安装记录加载失败');+ if (skillsResult?.status === 'rejected') marketErrors.push('Could not load skill status');+ if (recordsResult?.status === 'rejected') marketErrors.push('Could not load installation history');setSkillMarketLoadError(marketErrors.length > 0 ? marketErrors.join(';') : undefined);}).finally(() => {@@ -2082,7 +2082,7 @@ export function AppController(props: AppControllerProps) {return;}- setLoadErrorByPath(previous => ({ ...previous, [path]: '无法加载文件' }));+ setLoadErrorByPath(previous => ({ ...previous, [path]: 'Could not load the file' }));if (selectedFilePathRef.current === path) {setLoadingFilePath('');}@@ -2243,11 +2243,11 @@ export function AppController(props: AppControllerProps) {appIssues.captureOperationFailure(`app.approval:${id}`,error,- '审批操作未完成,请查看诊断后重试。'+ 'The approval operation did not complete. Check diagnostics and try again.');setApprovalErrors(previous => ({...previous,- [id]: '审批操作未完成,请重试。'+ [id]: 'The approval operation did not complete. Try again.'}));} finally {setResolvingApprovalIds(previous => {@@ -2328,7 +2328,7 @@ export function AppController(props: AppControllerProps) {.catch(cause => appIssues.captureOperationFailure('app.save-color-mode',cause,- '外观设置未同步到本地 Runtime,请重试。'+ 'Appearance settings were not synchronized with the local Runtime. Try again.'));}@@ -2341,7 +2341,7 @@ export function AppController(props: AppControllerProps) {.catch(cause => appIssues.captureOperationFailure('app.save-accent-color',cause,- '强调色设置未同步到本地 Runtime,请重试。'+ 'Accent color settings were not synchronized with the local Runtime. Try again.'));}@@ -2360,7 +2360,7 @@ export function AppController(props: AppControllerProps) {.catch(cause => appIssues.captureOperationFailure('app.save-accent-color',cause,- '强调色设置未同步到本地 Runtime,请重试。'+ 'Accent color settings were not synchronized with the local Runtime. Try again.'));}@@ -2440,7 +2440,7 @@ export function AppController(props: AppControllerProps) {kind: 'diagnostic',id: createTimelineId('runtime_not_connected'),severity: 'error',- message: '本地运行内核尚未连接,无法发送任务。',+ message: 'The local Runtime is disconnected. Tasks cannot be sent.',content: getConnectionStatusLabel(connectionState),source: 'runtime'}@@ -2552,7 +2552,7 @@ export function AppController(props: AppControllerProps) {if (path === null) return;await registerProjectDirectory(path);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '添加项目失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not add the project. Try again.'));} finally {projectDirectoryDialogInFlightRef.current = false;}@@ -2588,7 +2588,7 @@ export function AppController(props: AppControllerProps) {setCreateProjectError(undefined);return true;} catch (error) {- const message = getRuntimeErrorMessage(error, '新建项目失败,请重试');+ const message = getRuntimeErrorMessage(error, 'Could not create the project. Try again.');setProjectLoadError(message);setCreateProjectError(message);return false;@@ -2622,7 +2622,7 @@ export function AppController(props: AppControllerProps) {setProjectLoadError(undefined);return;}- throw new Error('项目已存在,但无法在项目列表中找到');+ throw new Error('The project already exists but could not be found in the project list');}}@@ -2662,13 +2662,13 @@ export function AppController(props: AppControllerProps) {const path = hostBridge.resolveDroppedFilePath(file);if (path === null) {- setProjectLoadError('无法读取拖入的项目文件夹路径');+ setProjectLoadError('Could not read the dropped project folder path');return;}try {await registerProjectDirectory(path);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '拖入项目失败,请确认选择的是文件夹'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not add the dropped project. Make sure it is a folder.'));}}@@ -2690,7 +2690,7 @@ export function AppController(props: AppControllerProps) {}setProjectLoadError(undefined);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '移除项目失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not remove the project. Try again.'));}}@@ -2703,7 +2703,7 @@ export function AppController(props: AppControllerProps) {if (mountedRef.current) setUnassignedThreads(response.threads);} catch (error) {if (mountedRef.current) {- setProjectLoadError(getRuntimeErrorMessage(error, '无法加载待归属会话'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not load unassigned conversations'));}}}@@ -2731,7 +2731,7 @@ export function AppController(props: AppControllerProps) {setProjects(current => upsertProject(current, response.project));setProjectLoadError(undefined);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '更新项目失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not update the project. Try again.'));} finally {setProjectMutationBusy(false);}@@ -2745,7 +2745,7 @@ export function AppController(props: AppControllerProps) {await refreshProjectsFromRuntime();setProjectLoadError(undefined);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '恢复项目失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not restore the project. Try again.'));} finally {setProjectMutationBusy(false);}@@ -2761,7 +2761,7 @@ export function AppController(props: AppControllerProps) {setProjects(current => upsertProject(current, response.project));setProjectLoadError(undefined);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '更换项目目录失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not change the project directory. Try again.'));} finally {setProjectMutationBusy(false);}@@ -2776,7 +2776,7 @@ export function AppController(props: AppControllerProps) {setUnassignedThreads(current => current.filter(thread => thread.id !== threadId));setProjectLoadError(undefined);} catch (error) {- setProjectLoadError(getRuntimeErrorMessage(error, '认领会话失败,请重试'));+ setProjectLoadError(getRuntimeErrorMessage(error, 'Could not assign the conversation. Try again.'));} finally {setProjectMutationBusy(false);}@@ -2793,7 +2793,7 @@ export function AppController(props: AppControllerProps) {}setThreadLoadError(undefined);} catch (error) {- setThreadLoadError(getRuntimeErrorMessage(error, '删除任务草稿失败,请重试'));+ setThreadLoadError(getRuntimeErrorMessage(error, 'Could not delete the task draft. Try again.'));}}@@ -2845,8 +2845,8 @@ export function AppController(props: AppControllerProps) {} catch (error) {setThreadLoadError(error instanceof ApiClientError && error.code === 'THREAD_HAS_ACTIVE_RUN'- ? '任务运行期间不能归档会话,请等待当前任务结束'- : getRuntimeErrorMessage(error, '归档会话失败,请重试')+ ? 'Wait for the active task to finish before archiving this conversation.'+ : getRuntimeErrorMessage(error, 'Could not archive the conversation. Try again.'));}}@@ -2858,7 +2858,7 @@ export function AppController(props: AppControllerProps) {setRuntimeThreads(current => upsertThread(current, response.thread));setThreadLoadError(undefined);} catch (error) {- setThreadLoadError(getRuntimeErrorMessage(error, '重命名会话失败,请重试'));+ setThreadLoadError(getRuntimeErrorMessage(error, 'Could not rename the conversation. Try again.'));throw error;}}@@ -2870,7 +2870,7 @@ export function AppController(props: AppControllerProps) {setRuntimeThreads(current => upsertThread(current, response.thread));setThreadLoadError(undefined);} catch (error) {- setThreadLoadError(getRuntimeErrorMessage(error, pinned ? '置顶会话失败,请重试' : '取消置顶失败,请重试'));+ setThreadLoadError(getRuntimeErrorMessage(error, pinned ? 'Could not pin the conversation. Try again.' : 'Could not unpin the conversation. Try again.'));throw error;}}@@ -2888,8 +2888,8 @@ export function AppController(props: AppControllerProps) {} catch (error) {setThreadLoadError(error instanceof ApiClientError && error.code === 'THREAD_HAS_ACTIVE_RUN'- ? '任务运行期间不能删除会话,请等待当前任务结束'- : getRuntimeErrorMessage(error, '删除会话失败,请重试')+ ? 'Wait for the active task to finish before deleting this conversation.'+ : getRuntimeErrorMessage(error, 'Could not delete the conversation. Try again.'));throw error;}@@ -3062,7 +3062,7 @@ export function AppController(props: AppControllerProps) {thread = response.thread;setRuntimeThreads(previous => upsertThread(previous, response.thread));} catch {- if (mountedRef.current) setThreadLoadError('无法打开搜索结果对应的会话');+ if (mountedRef.current) setThreadLoadError('Could not open the conversation for this search result');return;}}@@ -3103,7 +3103,7 @@ export function AppController(props: AppControllerProps) {return true;}if (currentRunBusy) {- setThreadConfigUpdateError('任务运行期间不能修改访问权限,请等待当前任务结束');+ setThreadConfigUpdateError('Wait for the active task to finish before changing access permissions.');return false;}@@ -3113,7 +3113,7 @@ export function AppController(props: AppControllerProps) {return true;}if (threadService === null) {- setThreadConfigUpdateError('本地服务暂不可用,无法更新会话访问权限');+ setThreadConfigUpdateError('The local Runtime is unavailable. Conversation permissions cannot be updated.');return false;}@@ -3127,8 +3127,8 @@ export function AppController(props: AppControllerProps) {if (mountedRef.current) {setThreadConfigUpdateError(error instanceof ApiClientError && error.code === 'THREAD_HAS_ACTIVE_RUN'- ? '任务运行期间不能修改访问权限,请等待当前任务结束'- : '无法更新会话访问权限'+ ? 'Wait for the active task to finish before changing access permissions.'+ : 'Could not update conversation permissions');}return false;@@ -3195,13 +3195,13 @@ export function AppController(props: AppControllerProps) {setCodexSkills(skillsResult.value);} else {setCodexSkills(undefined);- refreshErrors.push('技能状态刷新失败');+ refreshErrors.push('Could not refresh skill status');}if (recordsResult.status === 'fulfilled') {setSkillMarketInstallRecords(recordsResult.value.records);} else {setSkillMarketInstallRecords(undefined);- refreshErrors.push('安装记录刷新失败');+ refreshErrors.push('Could not refresh installation history');}setSkillMarketLoadError(refreshErrors.length > 0 ? refreshErrors.join(';') : undefined);}@@ -3225,7 +3225,7 @@ export function AppController(props: AppControllerProps) {setSkillMarketOperation({skillId,kind: 'install',- error: getRuntimeErrorMessage(error, '安装失败,请重试')+ error: getRuntimeErrorMessage(error, 'Installation failed. Try again.')});}} finally {@@ -3254,7 +3254,7 @@ export function AppController(props: AppControllerProps) {setSkillMarketOperation({skillId,kind: 'update',- error: getRuntimeErrorMessage(error, '更新失败,请重试')+ error: getRuntimeErrorMessage(error, 'Update failed. Try again.')});}} finally {@@ -3267,7 +3267,7 @@ export function AppController(props: AppControllerProps) {async function useMarketSkill(skillId: string, projectId: string) {setSkillMarketUseError(undefined);const isSkillCreator = skillId === 'skill-creator';- let title = '创建技能';+ let title = 'Create skill';if (!isSkillCreator) {try {const [{ skillMarketCatalog }, { getSkillMarketDisplayTitle }] = await Promise.all([@@ -3276,12 +3276,12 @@ export function AppController(props: AppControllerProps) {]);const entry = skillMarketCatalog.find(candidate => candidate.id === skillId);if (entry === undefined) {- setSkillMarketUseError({ skillId, error: '未找到这个技能' });+ setSkillMarketUseError({ skillId, error: 'Skill not found' });return;}title = getSkillMarketDisplayTitle(entry);} catch {- setSkillMarketUseError({ skillId, error: '技能列表加载失败,请重试' });+ setSkillMarketUseError({ skillId, error: 'Could not load the skill list. Try again.' });return;}}@@ -3305,12 +3305,12 @@ export function AppController(props: AppControllerProps) {input.onError(undefined);const activeThreadService = threadService;if (activeThreadService === null) {- input.onError('本地服务暂不可用,无法创建对话');+ input.onError('The local Runtime is unavailable. Conversations cannot be created.');return;}const project = findProjectById(projects, input.projectId);if (project === undefined) {- input.onError('未找到所选项目');+ input.onError('Selected project not found');return;}const config = defaultComposerRunConfig(@@ -3350,7 +3350,7 @@ export function AppController(props: AppControllerProps) {});} catch (error) {if (isCurrentThreadRuntime(generation, activeThreadService)) {- input.onError(getRuntimeErrorMessage(error, '创建对话失败,请重试'));+ input.onError(getRuntimeErrorMessage(error, 'Could not create the conversation. Try again.'));}} finally {if (isCurrentThreadRuntime(generation, activeThreadService)) {@@ -3366,7 +3366,7 @@ export function AppController(props: AppControllerProps) {const activeSkillMarketService = skillMarketService;if (selectDirectory === undefined) return;if (activeRuntimeClient === null || activeCapabilityService === null || activeSkillMarketService === null) {- setSkillMarketLoadError('本地服务暂不可用,无法上传技能');+ setSkillMarketLoadError('The local Runtime is unavailable. Skills cannot be uploaded.');return;}@@ -3385,7 +3385,7 @@ export function AppController(props: AppControllerProps) {);} catch (error) {if (mountedRef.current) {- setSkillMarketLoadError(getRuntimeErrorMessage(error, '上传技能失败,请重试'));+ setSkillMarketLoadError(getRuntimeErrorMessage(error, 'Could not upload the skill. Try again.'));}}}@@ -3491,7 +3491,7 @@ export function AppController(props: AppControllerProps) {}if (attachments.length > 0) {const draftId = attachments[0]!.attachment.draftId;- if (draftId === undefined) throw new Error('附件缺少草稿归属,无法发送');+ if (draftId === undefined) throw new Error('The attachment has no associated draft and cannot be sent');runInput.draftId = draftId;runInput.attachmentIds = attachments.map(item => item.attachment.id);}@@ -3574,7 +3574,7 @@ export function AppController(props: AppControllerProps) {async function requestRunCancellation(runId: string) {let cancellationError: unknown;try {- if (runService === null) throw new Error('本地运行内核已断开,无法停止任务');+ if (runService === null) throw new Error('The local Runtime is disconnected. The task cannot be stopped.');await runService.cancelRun(runId);} catch (error) {cancellationError = error;@@ -3600,7 +3600,7 @@ export function AppController(props: AppControllerProps) {runId,state: 'failed'});- const message = getRuntimeErrorMessage(cancellationError, '停止任务失败,请重试');+ const message = getRuntimeErrorMessage(cancellationError, 'Could not stop the task. Try again.');const item: TimelineItem = {kind: 'diagnostic',id: createTimelineId('cancel_error'),@@ -3630,11 +3630,11 @@ export function AppController(props: AppControllerProps) {async function steerQueuedRun(runId: string) {const threadId = runRegistryRef.current.runsById[runId]?.threadId;try {- if (runService === null) throw new Error('本地运行内核已断开,无法调整等待任务');+ if (runService === null) throw new Error('The local Runtime is disconnected. Queued tasks cannot be changed.');await runService.steerRun(runId);if (threadId !== undefined) await refreshThreadRunState(threadId);} catch (error) {- const message = getRuntimeErrorMessage(error, '调整等待任务失败,请重试');+ const message = getRuntimeErrorMessage(error, 'Could not change the queued task. Try again.');const item: TimelineItem = {kind: 'diagnostic',id: createTimelineId('steer_error'),@@ -3915,7 +3915,7 @@ export function AppController(props: AppControllerProps) {}async function saveMemorySuggestion(input: CreateMemoryRequest) {- if (memoryService === null) throw new Error('记忆服务暂不可用');+ if (memoryService === null) throw new Error('The memory service is unavailable');await memoryService.createMemory(input);}@@ -3932,7 +3932,7 @@ export function AppController(props: AppControllerProps) {thread = response.thread;setRuntimeThreads(previous => upsertThread(previous, response.thread));} catch {- if (mountedRef.current) setThreadLoadError('无法打开任务对应的会话');+ if (mountedRef.current) setThreadLoadError('Could not open the conversation for this task');return false;}}@@ -3992,7 +3992,7 @@ export function AppController(props: AppControllerProps) {state.activeView === 'conversation'&& state.selectedThreadId === schedule.threadId;const opened = alreadyOpen || await openScheduleTask(schedule.threadId);- if (!opened) throw new Error('无法打开任务对应的会话');+ if (!opened) throw new Error('Could not open the conversation for this task');if (alreadyOpen) {setTimelineRunTarget(undefined);setTimelineApprovalTarget(undefined);@@ -4001,7 +4001,7 @@ export function AppController(props: AppControllerProps) {try {if (scheduleService === null) {- throw new Error('本地服务暂不可用,无法立即运行任务');+ throw new Error('The local Runtime is unavailable. The task cannot run now.');}const response = await scheduleService.runNow(schedule.id);handleScheduleChanged(response.schedule);@@ -4019,9 +4019,9 @@ export function AppController(props: AppControllerProps) {}const message = response.queued- ? '本次运行已排队,会在当前任务结束后执行'+ ? 'This run is queued and will start after the active task finishes.': response.skipped- ? '已有任务在运行,本次已跳过'+ ? 'A task is already running. This run was skipped.': undefined;if (message !== undefined) {appendTimelineItemsForThread(schedule.threadId, [@@ -4034,7 +4034,7 @@ export function AppController(props: AppControllerProps) {]);}} catch (error) {- const message = getRuntimeErrorMessage(error, '无法立即运行任务');+ const message = getRuntimeErrorMessage(error, 'Could not run the task now');appendTimelineItemsForThread(schedule.threadId, [{kind: 'diagnostic',@@ -4071,7 +4071,7 @@ export function AppController(props: AppControllerProps) {thread = response.thread;setRuntimeThreads(previous => upsertThread(previous, response.thread));} catch {- setThreadLoadError('无法打开任务对应的会话');+ setThreadLoadError('Could not open the conversation for this task');return;}}@@ -4180,7 +4180,7 @@ export function AppController(props: AppControllerProps) {}} catch {if (mountedRef.current) {- setSaveErrorByPath(previous => ({ ...previous, [saveSnapshot.path]: '保存到本地草稿失败' }));+ setSaveErrorByPath(previous => ({ ...previous, [saveSnapshot.path]: 'Could not save the local draft' }));}} finally {if (mountedRef.current) {@@ -4406,7 +4406,7 @@ export function AppController(props: AppControllerProps) {imageInputUnsupportedReason={imageInputSupported? undefined- : '当前 Codex 版本不支持图片输入,请更新 Codex'+ : 'This Codex version does not support image input. Update Codex.'}draftRequest={pendingComposerDraft !== undefined && pendingComposerDraft.threadId === state.selectedThreadId@@ -4438,7 +4438,7 @@ export function AppController(props: AppControllerProps) {onCancelQueuedRun={(runId) => void cancelQueuedRun(runId)}onSteerQueuedRun={(runId) => void steerQueuedRun(runId)}onUploadAttachment={async file => {- if (attachmentService === null) throw new Error('附件服务暂不可用');+ if (attachmentService === null) throw new Error('The attachment service is unavailable');const response = await attachmentService.upload({file,draftId: composerAttachmentDraftId@@ -4584,7 +4584,7 @@ export function AppController(props: AppControllerProps) {const conversationWorkspace = fileWorkspaceOpen ? (<sectionclassName="conversation-file-layout"- aria-label="会话和文件工作区"+ aria-label="Conversation and file workspace"ref={conversationFileLayoutRef}style={conversationFileLayoutStyle}>@@ -4592,7 +4592,7 @@ export function AppController(props: AppControllerProps) {<divclassName="pane-resize-handle conversation-file-resize-handle"role="separator"- aria-label="调整会话和文件区域宽度"+ aria-label="Resize the conversation and file areas"aria-orientation="vertical"aria-valuenow={conversationPaneWidth}tabIndex={0}@@ -4734,7 +4734,7 @@ export function AppController(props: AppControllerProps) {navigateToRoute({ view: 'schedules', scheduleId });}}onPauseSchedule={async scheduleId => {- if (scheduleService === null) throw new Error('本地运行内核未连接');+ if (scheduleService === null) throw new Error('The local Runtime is disconnected');const updated = await scheduleService.updateSchedule(scheduleId, { enabled: false });handleScheduleChanged(updated);}}@@ -4786,7 +4786,7 @@ export function AppController(props: AppControllerProps) {appIssues.captureOperationFailure('app.save-desktop-close-behavior',cause,- '窗口关闭行为未保存,请重试。'+ 'Window close preferences were not saved. Try again.');});}}@@ -4806,7 +4806,7 @@ export function AppController(props: AppControllerProps) {appIssues.captureOperationFailure('app.save-desktop-telemetry',cause,- '诊断数据偏好未保存,请重试。'+ 'Diagnostics preferences were not saved. Try again.');});}}@@ -4912,7 +4912,7 @@ export function AppController(props: AppControllerProps) {aria-label={connectionState.status === 'connected' && runtimeWorkspaceReady? getConnectionStatusLabel(connectionState)- : '正在加载本地运行内核'+ : 'Loading the local Runtime'}aria-live="polite"/>@@ -5020,7 +5020,7 @@ export function AppController(props: AppControllerProps) {{projectDropActive ? (<div className="project-drop-overlay" role="status" aria-live="polite"><FolderInput aria-hidden="true" size={30} />- <strong>松开以添加项目文件夹</strong>+ <strong>Drop to add a project folder</strong></div>) : null}{projectManagementOpen ? (@@ -5082,7 +5082,7 @@ export function AppController(props: AppControllerProps) {return (<DetailPanelmode="run"- title="运行详情"+ title="Run details"subtitle={state.selectedRunId}content={<RunDetailPanel@@ -5101,7 +5101,7 @@ export function AppController(props: AppControllerProps) {return (<DetailPanelmode="change"- title="已编辑 docs/atoms.md"+ title="Edited docs/atoms.md"subtitle="+903 -0"content="docs/atoms.md"onClose={() => dispatch({ type: 'close_detail' })}@@ -5113,8 +5113,8 @@ export function AppController(props: AppControllerProps) {const fileTitle = selectedFilePath.split('/').at(-1) ?? selectedFilePath;const fileContent = loadingSelectedFile- ? '正在加载文件...'- : loadError ?? saveError ?? (selectedDraftContent.length > 0 ? selectedDraftContent : '暂无预览内容');+ ? 'Loading file...'+ : loadError ?? saveError ?? (selectedDraftContent.length > 0 ? selectedDraftContent : 'No preview available');return (<DetailPanel@@ -5321,14 +5321,14 @@ function routeForConversation(selectedThreadId?: string): AppRoute {function PageLoading() {return (- <section className="page-loading" role="status" aria-label="正在加载页面">- <span>正在加载页面...</span>+ <section className="page-loading" role="status" aria-label="Loading page">+ <span>Loading page...</span></section>);}function getConnectionStatusLabel(connectionState: ConnectionState) {- if (connectionState.status === 'connected') return '本地运行内核正常';+ if (connectionState.status === 'connected') return 'The local Runtime is ready';return connectionState.message;}@@ -5420,11 +5420,11 @@ function PlaceholderView(props: { label: string }) {function getPlaceholderLabel(activeView: 'schedules' | 'plugins' | 'files') {switch (activeView) {case 'schedules':- return '已安排';+ return 'Scheduled';case 'plugins':- return '插件';+ return 'Plugins';case 'files':- return '文件';+ return 'Files';}}@@ -5487,7 +5487,7 @@ function buildMemoryProjectOptions(const options = new Map<string, string>();for (const thread of threads) {if (thread.purpose !== 'conversation' || thread.projectId === null) continue;- const label = findProjectById(projects, thread.projectId)?.name ?? '未知项目';+ const label = findProjectById(projects, thread.projectId)?.name ?? 'Unknown project';options.set(thread.projectId, label);}return Array.from(options, ([key, label]) => ({ key, label }));@@ -5557,11 +5557,11 @@ export function formatRelativeTime(iso: string): string {const hour = 60 * minute;const day = 24 * hour;- if (diffMs < minute) return '刚刚';- if (diffMs < hour) return `${Math.floor(diffMs / minute)}分钟`;- if (diffMs < day) return `${Math.floor(diffMs / hour)}小时`;- if (diffMs < 7 * day) return `${Math.floor(diffMs / day)}天`;- return `${Math.floor(diffMs / (7 * day))}周`;+ if (diffMs < minute) return 'Just now';+ if (diffMs < hour) return `${Math.floor(diffMs / minute)}m ago`;+ if (diffMs < day) return `${Math.floor(diffMs / hour)}h ago`;+ if (diffMs < 7 * day) return `${Math.floor(diffMs / day)}d ago`;+ return `${Math.floor(diffMs / (7 * day))}w ago`;}function getRuntimeErrorMessage(error: unknown, fallback: string): string {@@ -5576,7 +5576,7 @@ function buildThreadRequest(): Extract<CreateThreadRequest, { projectId: string }> {const request: Extract<CreateThreadRequest, { projectId: string }> = {projectId: project.id,- title: prompt.trim() || '新对话',+ title: prompt.trim() || 'New conversation',profile: config.profile,sandbox: toRuntimeSandbox(config.permission)};@@ -5695,8 +5695,8 @@ export function buildComposerSlashCommands(id: `mcp:${server.name}`,category: 'mcp' as const,label: server.name,- description: `${server.transport} · 已配置`,- insertText: `使用 MCP:${server.name} `+ description: `${server.transport} · Configured`,+ insertText: `Use MCP: ${server.name} `}));return [...skillCommands, ...mcpCommands];}@@ -5874,8 +5874,8 @@ function mapHistoryItemToTimelineItem(item: ThreadHistoryItem, fallbackRunId?: s...base,kind: 'change_card',title: formatHistoryFileChangeTitle(item.changes),- path: item.changes.find(change => change.path.length > 0)?.path ?? '文件变更',- delta: `${item.changes.length} 项变更`,+ path: item.changes.find(change => change.path.length > 0)?.path ?? 'File changes',+ delta: `${item.changes.length} changes`,source: 'runtime'};case 'done':@@ -5896,7 +5896,7 @@ function mapHistoryItemToTimelineItem(item: ThreadHistoryItem, fallbackRunId?: sfunction formatHistoryFileChangeTitle(changes: Array<{ kind: 'add' | 'modify' | 'delete' | 'unknown' }>): string {- if (changes.length === 0) return '文件变更';+ if (changes.length === 0) return 'File changes';const counts = new Map<'add' | 'modify' | 'delete' | 'unknown', number>();for (const change of changes) counts.set(change.kind, (counts.get(change.kind) ?? 0) + 1);@@ -5905,10 +5905,10 @@ function formatHistoryFileChangeTitle(.map(kind => {const count = counts.get(kind) ?? 0;if (count === 0) return undefined;- if (kind === 'add') return `新增 ${count} 个文件`;- if (kind === 'modify') return `修改 ${count} 个文件`;- if (kind === 'delete') return `删除 ${count} 个文件`;- return `变更 ${count} 个文件`;+ if (kind === 'add') return `Added ${count} files`;+ if (kind === 'modify') return `Modified ${count} files`;+ if (kind === 'delete') return `Deleted ${count} files`;+ return `Changed ${count} files`;}).filter((part): part is string => part !== undefined).join(',');diff --git a/apps/web/src/app/use-runtime-dependencies.ts b/apps/web/src/app/use-runtime-dependencies.tsindex 74fe911c..6c655af5 100644--- a/apps/web/src/app/use-runtime-dependencies.ts+++ b/apps/web/src/app/use-runtime-dependencies.ts@@ -104,7 +104,7 @@ export function useRuntimeDependencies(input: {pageIssues.captureOperationFailure(operationId,caught,- '无法读取或检查运行组件,请确认本地 Runtime 已连接后重试。',+ 'Could not read or check Runtime components. Connect the local Runtime and try again.',{ retryable: true });}@@ -140,7 +140,7 @@ export function useRuntimeDependencies(input: {pageIssues.captureOperationFailure('runtime.check-yt-dlp',caught,- '检查运行组件更新失败,请稍后重试。',+ 'Could not check Runtime component updates. Try again later.',{ retryable: true });throw caught;@@ -163,7 +163,7 @@ export function useRuntimeDependencies(input: {pageIssues.captureOperationFailure('runtime.update-yt-dlp',caught,- '运行组件更新失败,请检查网络和磁盘空间后重试。',+ 'Runtime component update failed. Check the network and disk space before retrying.',{ retryable: true });throw caught;diff --git a/apps/web/src/components/editor/FileEditor.test.tsx b/apps/web/src/components/editor/FileEditor.test.tsxindex 30f82724..963be930 100644--- a/apps/web/src/components/editor/FileEditor.test.tsx+++ b/apps/web/src/components/editor/FileEditor.test.tsx@@ -18,8 +18,8 @@ describe('FileEditor', () => {/>);- const saveButton = screen.getByRole('button', { name: '保存到本地草稿' });- expect(screen.queryByRole('button', { name: '保存' })).not.toBeInTheDocument();+ const saveButton = screen.getByRole('button', { name: 'Save to local draft' });+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();await user.click(saveButton);@@ -41,7 +41,7 @@ describe('FileEditor', () => {/>);- const saveButton = screen.getByRole('button', { name: '保存到本地草稿' });+ const saveButton = screen.getByRole('button', { name: 'Save to local draft' });expect(saveButton).toBeDisabled();await user.click(saveButton);@@ -62,7 +62,7 @@ describe('FileEditor', () => {);expect(screen.getByText('无法加载文件')).toBeInTheDocument();- expect(screen.getByRole('textbox', { name: 'docs/design/creator-dashboard.md 编辑器' })).toHaveValue(+ expect(screen.getByRole('textbox', { name: 'docs/design/creator-dashboard.md editor' })).toHaveValue('# Dashboard\nunsaved edit');});@@ -96,7 +96,7 @@ describe('FileEditor', () => {/>);- expect(screen.getByRole('textbox', { name: 'README.md 编辑器' })).toHaveValue('# OpenCreator\n\n**raw**');+ expect(screen.getByRole('textbox', { name: 'README.md editor' })).toHaveValue('# OpenCreator\n\n**raw**');expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();});});diff --git a/apps/web/src/components/editor/FileEditor.tsx b/apps/web/src/components/editor/FileEditor.tsxindex 3f5fb473..a2064bdd 100644--- a/apps/web/src/components/editor/FileEditor.tsx+++ b/apps/web/src/components/editor/FileEditor.tsx@@ -18,7 +18,7 @@ export function FileEditor(props: FileEditorProps) {<div className="file-editor-title"><strong>{props.path}</strong><span className={`save-state${props.dirty ? ' dirty' : ''}`}>- {props.dirty ? '未保存' : '已保存到本地草稿'}+ {props.dirty ? 'Unsaved' : 'Saved to local draft'}</span>{errors.length === 0 ? null : (<div className="file-editor-errors" role="status">@@ -29,14 +29,14 @@ export function FileEditor(props: FileEditorProps) {)}</div><button className="editor-save-button" type="button" disabled={props.saving} onClick={props.onSave}>- 保存到本地草稿+ Save to local draft</button></div><div className="file-editor-body"><div className="editor-card"><textareaclassName="code-textarea"- aria-label={`${props.path} 编辑器`}+ aria-label={`${props.path} editor`}value={props.content}onChange={event => props.onChange(event.currentTarget.value)}spellCheck={false}diff --git a/apps/web/src/components/editor/FileTree.test.tsx b/apps/web/src/components/editor/FileTree.test.tsxindex a050c6be..5a2cdd3e 100644--- a/apps/web/src/components/editor/FileTree.test.tsx+++ b/apps/web/src/components/editor/FileTree.test.tsx@@ -20,7 +20,7 @@ describe('FileTree', () => {/>);- expect(screen.getByRole('navigation', { name: '项目文件' })).toBeInTheDocument();+ expect(screen.getByRole('navigation', { name: 'Project files' })).toBeInTheDocument();expect(screen.getByText('docs')).not.toHaveAttribute('role', 'treeitem');expect(screen.queryByRole('tree')).not.toBeInTheDocument();expect(screen.queryByRole('treeitem')).not.toBeInTheDocument();diff --git a/apps/web/src/components/editor/FileTree.tsx b/apps/web/src/components/editor/FileTree.tsxindex a4633983..b32d8d77 100644--- a/apps/web/src/components/editor/FileTree.tsx+++ b/apps/web/src/components/editor/FileTree.tsx@@ -17,9 +17,9 @@ const languageLabels: Partial<Record<NonNullable<FileTreeNode['language']>, striexport function FileTree(props: FileTreeProps) {return (- <nav className="tree-list" aria-label="项目文件">+ <nav className="tree-list" aria-label="Project files">{props.nodes.length === 0 ? (- <p className="empty-state compact">暂无项目文件</p>+ <p className="empty-state compact">No project files</p>) : (<ul>{props.nodes.map(node => (diff --git a/apps/web/src/components/layout/AppLayout.test.tsx b/apps/web/src/components/layout/AppLayout.test.tsxindex 5c90c992..aba3769d 100644--- a/apps/web/src/components/layout/AppLayout.test.tsx+++ b/apps/web/src/components/layout/AppLayout.test.tsx@@ -15,9 +15,9 @@ describe('AppLayout', () => {/>);- expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument();- expect(screen.getByLabelText('OpenCreator 工作区')).toBeInTheDocument();- expect(screen.getByLabelText('详情')).toBeInTheDocument();+ expect(screen.getByLabelText('OpenCreator navigation')).toBeInTheDocument();+ expect(screen.getByLabelText('OpenCreator workspace')).toBeInTheDocument();+ expect(screen.getByLabelText('details')).toBeInTheDocument();expect(screen.getByRole('main')).toHaveClass('opencreator-shell', 'has-detail');});@@ -31,9 +31,9 @@ describe('AppLayout', () => {/>);- expect(screen.getByLabelText('OpenCreator 导航')).toHaveClass('opencreator-sidebar-pane');- expect(screen.getByLabelText('OpenCreator 工作区')).toHaveClass('opencreator-main-pane');- expect(screen.queryByLabelText('详情')).not.toBeInTheDocument();+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveClass('opencreator-sidebar-pane');+ expect(screen.getByLabelText('OpenCreator workspace')).toHaveClass('opencreator-main-pane');+ expect(screen.queryByLabelText('details')).not.toBeInTheDocument();expect(screen.getByRole('main')).toHaveClass('opencreator-shell');expect(screen.getByRole('main')).not.toHaveClass('has-detail');});@@ -47,7 +47,7 @@ describe('AppLayout', () => {/>);- const mainPane = screen.getByLabelText('OpenCreator 工作区');+ const mainPane = screen.getByLabelText('OpenCreator workspace');expect(mainPane).toHaveAttribute('data-has-main-header', 'true');expect(mainPane.querySelector('.opencreator-main-titlebar')).toHaveTextContent('会话标题');expect(mainPane.querySelector('.opencreator-main-content')).toHaveTextContent('工作区');@@ -61,7 +61,7 @@ describe('AppLayout', () => {/>);- const mainPane = screen.getByLabelText('OpenCreator 工作区');+ const mainPane = screen.getByLabelText('OpenCreator workspace');expect(mainPane).not.toHaveAttribute('data-has-main-header');expect(mainPane.querySelector('.opencreator-main-titlebar')).not.toBeInTheDocument();});@@ -76,7 +76,7 @@ describe('AppLayout', () => {);expect(screen.getByRole('main')).toHaveClass('opencreator-shell', 'sidebar-collapsed');- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-collapsed', 'true');+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-collapsed', 'true');});it('removes navigation and expands the main workspace in immersive mode', () => {@@ -89,9 +89,9 @@ describe('AppLayout', () => {);expect(screen.getByRole('main')).toHaveClass('opencreator-shell', 'is-immersive');- expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '打开导航' })).not.toBeInTheDocument();- expect(screen.getByLabelText('OpenCreator 工作区')).toHaveTextContent('沉浸工作区');+ expect(screen.queryByLabelText('OpenCreator navigation')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Open navigation' })).not.toBeInTheDocument();+ expect(screen.getByLabelText('OpenCreator workspace')).toHaveTextContent('沉浸工作区');});it('opens the mobile navigation as a focus-managed drawer and restores focus after closing', async () => {@@ -99,21 +99,21 @@ describe('AppLayout', () => {render(<MobileLayoutHarness />);- const trigger = screen.getByRole('button', { name: '打开导航' });+ const trigger = screen.getByRole('button', { name: 'Open navigation' });await user.click(trigger);- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-mobile-open', 'true');- expect(screen.getByRole('button', { name: '关闭导航' })).toHaveFocus();+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-mobile-open', 'true');+ expect(screen.getByRole('button', { name: 'Close navigation' })).toHaveFocus();await user.keyboard('{Escape}');- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-mobile-open', 'false');+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-mobile-open', 'false');await waitFor(() => expect(trigger).toHaveFocus());await user.click(trigger);- await user.click(screen.getByRole('button', { name: '关闭导航遮罩' }));+ await user.click(screen.getByRole('button', { name: 'Close navigation overlay' }));- expect(screen.getByLabelText('OpenCreator 导航')).toHaveAttribute('data-mobile-open', 'false');+ expect(screen.getByLabelText('OpenCreator navigation')).toHaveAttribute('data-mobile-open', 'false');});});diff --git a/apps/web/src/components/layout/AppLayout.tsx b/apps/web/src/components/layout/AppLayout.tsxindex e3ff4dc9..503b1f53 100644--- a/apps/web/src/components/layout/AppLayout.tsx+++ b/apps/web/src/components/layout/AppLayout.tsx@@ -65,7 +65,7 @@ export function AppLayout(props: {<main className={shellClassName}>{mobileSidebarOpen ? (<button- aria-label="关闭导航遮罩"+ aria-label="Close navigation overlay"className="mobile-navigation-backdrop"onClick={props.onCloseMobileSidebar}type="button"@@ -73,16 +73,16 @@ export function AppLayout(props: {) : null}{props.immersive ? null : <asideclassName="opencreator-sidebar-pane"- aria-label="OpenCreator 导航"+ aria-label="OpenCreator navigation"data-collapsed={props.sidebarCollapsed ? 'true' : 'false'}data-mobile-open={mobileSidebarOpen ? 'true' : 'false'}ref={sidebarRef}><button- aria-label="关闭导航"+ aria-label="Close navigation"className="mobile-navigation-close"onClick={props.onCloseMobileSidebar}- title="关闭导航"+ title="Close navigation"type="button"><X aria-hidden="true" size={18} />@@ -91,7 +91,7 @@ export function AppLayout(props: {</aside>}<sectionclassName="opencreator-main-pane"- aria-label="OpenCreator 工作区"+ aria-label="OpenCreator workspace"data-has-main-header={props.mainHeader === undefined ? undefined : 'true'}>{props.mainHeader === undefined ? null : (@@ -100,11 +100,11 @@ export function AppLayout(props: {{props.immersive ? null : <div className="mobile-navigation-toolbar"><buttonaria-expanded={mobileSidebarOpen}- aria-label="打开导航"+ aria-label="Open navigation"className="mobile-navigation-trigger"onClick={props.onOpenMobileSidebar}ref={mobileTriggerRef}- title="打开导航"+ title="Open navigation"type="button"><Menu aria-hidden="true" size={20} />@@ -113,7 +113,7 @@ export function AppLayout(props: {<div className="opencreator-main-content">{props.main}</div></section>{props.detailOpen ? (- <aside className="opencreator-detail-pane" aria-label="详情">+ <aside className="opencreator-detail-pane" aria-label="details">{props.detail}</aside>) : null}diff --git a/apps/web/src/components/layout/DesktopWindowControls.tsx b/apps/web/src/components/layout/DesktopWindowControls.tsxindex 678efeec..8289f8df 100644--- a/apps/web/src/components/layout/DesktopWindowControls.tsx+++ b/apps/web/src/components/layout/DesktopWindowControls.tsx@@ -6,13 +6,13 @@ export function DesktopWindowControls(props: {onAction(action: WindowAction): Promise<void>;}) {const actions = [- { action: 'close', label: '关闭窗口', Icon: X },- { action: 'minimize', label: '最小化窗口', Icon: Minus },- { action: 'zoom', label: '缩放窗口', Icon: Maximize2 }+ { action: 'close', label: 'Close window', Icon: X },+ { action: 'minimize', label: 'Minimize window', Icon: Minus },+ { action: 'zoom', label: 'Zoom window', Icon: Maximize2 }] as const;return (- <div className="desktop-window-controls" role="group" aria-label="窗口控制">+ <div className="desktop-window-controls" role="group" aria-label="Window controls">{actions.map(({ action, label, Icon }) => (<buttonkey={action}diff --git a/apps/web/src/components/markdown/MarkdownCodeBlock.tsx b/apps/web/src/components/markdown/MarkdownCodeBlock.tsxindex 5c7a5f8b..f4525b10 100644--- a/apps/web/src/components/markdown/MarkdownCodeBlock.tsx+++ b/apps/web/src/components/markdown/MarkdownCodeBlock.tsx@@ -39,7 +39,7 @@ export function MarkdownCodeBlock(props: {}, 1600);}- const copyLabel = copyState === 'copied' ? '已复制' : copyState === 'failed' ? '复制失败' : '复制';+ const copyLabel = copyState === 'copied' ? 'Copied' : copyState === 'failed' ? 'Copy failed' : 'Copy';const CopyIcon = copyState === 'copied' ? Check : copyState === 'failed' ? AlertCircle : Copy;const linkifyTextFiles = props.linkifyWorkspaceFiles === true&& props.onLinkClick !== undefined@@ -57,7 +57,7 @@ export function MarkdownCodeBlock(props: {<buttontype="button"className="md-code-action md-code-action-icon"- aria-label={collapsed ? '展开代码' : '收起代码'}+ aria-label={collapsed ? 'Expand code' : 'Collapse code'}aria-expanded={!collapsed}onClick={() => setCollapsed(value => !value)}>diff --git a/apps/web/src/components/markdown/MarkdownRenderer.test.tsx b/apps/web/src/components/markdown/MarkdownRenderer.test.tsxindex 0556526a..998c3606 100644--- a/apps/web/src/components/markdown/MarkdownRenderer.test.tsx+++ b/apps/web/src/components/markdown/MarkdownRenderer.test.tsx@@ -74,10 +74,10 @@ describe('MarkdownRenderer', () => {expect(screen.getByText('const value = 1;')).toBeInTheDocument();expect(document.querySelector('.md-code-highlighted')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '复制' }));+ await user.click(screen.getByRole('button', { name: 'Copy' }));expect(writeText).toHaveBeenCalledWith('const value = 1;');- expect(screen.getByRole('button', { name: '已复制' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Copied' })).toBeInTheDocument();});it('collapses long code at a complete line boundary and expands all content', async () => {@@ -100,10 +100,10 @@ describe('MarkdownRenderer', () => {'…',].join('\n'));- await user.click(screen.getByRole('button', { name: '展开代码' }));+ await user.click(screen.getByRole('button', { name: 'Expand code' }));expect(code?.textContent).toBe(body);- expect(screen.getByRole('button', { name: '收起代码' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: 'Collapse code' })).toHaveAttribute('aria-expanded','true');@@ -118,9 +118,9 @@ describe('MarkdownRenderer', () => {render(<MarkdownRenderer variant="assistant" text={'```txt\nhello\n```'} />);- await user.click(screen.getByRole('button', { name: '复制' }));+ await user.click(screen.getByRole('button', { name: 'Copy' }));- expect(screen.getByRole('button', { name: '复制失败' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Copy failed' })).toBeInTheDocument();});it('does not render unsafe links as anchors', () => {@@ -209,7 +209,7 @@ describe('MarkdownRenderer', () => {expect(skill).toBeInTheDocument();expect(skill).toHaveAttribute('title',- '技能:zhiyu-brainstorm'+ 'Skill: zhiyu-brainstorm');expect(screen.getByText(/分析需求,再继续执行/)).toBeInTheDocument();});diff --git a/apps/web/src/components/markdown/MarkdownRenderer.tsx b/apps/web/src/components/markdown/MarkdownRenderer.tsxindex 7403e63f..66235ded 100644--- a/apps/web/src/components/markdown/MarkdownRenderer.tsx+++ b/apps/web/src/components/markdown/MarkdownRenderer.tsx@@ -35,7 +35,7 @@ function renderTaskListItem(item: string, key: number, options: MarkdownRendererconst checked = task[1]?.toLowerCase() === 'x';return (<li key={key} className="md-task-item" data-checked={checked ? 'true' : undefined}>- <input className="md-task-check" type="checkbox" checked={checked} readOnly aria-label={checked ? '已完成' : '未完成'} />+ <input className="md-task-check" type="checkbox" checked={checked} readOnly aria-label={checked ? 'Completed' : 'Incomplete'} /><span>{renderInlineMarkdown(task[2] ?? '', options)}</span></li>);diff --git a/apps/web/src/components/markdown/markdown-inline.tsx b/apps/web/src/components/markdown/markdown-inline.tsxindex 348913f1..3e8c3f0e 100644--- a/apps/web/src/components/markdown/markdown-inline.tsx+++ b/apps/web/src/components/markdown/markdown-inline.tsx@@ -175,7 +175,7 @@ function pushTextWithLinks(<spankey={`${baseKey}-${key++}`}className="md-skill-reference"- title={`技能:${reference.slice(1)}`}+ title={`Skill: ${reference.slice(1)}`}><Blocks aria-hidden="true" size={14} strokeWidth={1.8} /><span>{formatSkillName(reference)}</span>@@ -273,7 +273,7 @@ export function renderInlineMarkdown(const src = options.resolveImageSrc?.(match[3]);output.push(src? <img key={key++} className="md-image" src={src} alt={alt ?? ''} />- : <Fragment key={key++}>{alt ? `${alt} [图片]` : '[图片]'}</Fragment>);+ : <Fragment key={key++}>{alt ? `${alt} [Image]` : '[Image]'}</Fragment>);} else if (match[4] && match[5]) {output.push(renderLink(match[5], match[4], key++, {allowRelative,diff --git a/apps/web/src/components/timeline/Timeline.test.tsx b/apps/web/src/components/timeline/Timeline.test.tsxindex c6150d09..385395c2 100644--- a/apps/web/src/components/timeline/Timeline.test.tsx+++ b/apps/web/src/components/timeline/Timeline.test.tsx@@ -27,7 +27,7 @@ describe('Timeline', () => {/>);- expect(screen.getByText('定时执行')).toBeInTheDocument();+ expect(screen.getByText('Scheduled run')).toBeInTheDocument();expect(screen.getByText('生成每日项目摘要')).toBeInTheDocument();expect(screen.getByText(/2026/)).toBeInTheDocument();expect(screen.queryByText(/立即完成本次任务/)).not.toBeInTheDocument();@@ -68,7 +68,7 @@ describe('Timeline', () => {);expect(container.querySelector('.timeline-approval-overlay')).not.toBeInTheDocument();- expect(screen.queryByText('允许 OpenCreator 执行这条命令?')).not.toBeInTheDocument();+ expect(screen.queryByText('Allow OpenCreator to run this command?')).not.toBeInTheDocument();expect(container.querySelector('.timeline-approval')).not.toBeInTheDocument();expect(screen.getByTestId('virtuoso-scroller').scrollTop).toBe(0);});@@ -106,10 +106,10 @@ describe('Timeline', () => {expect(screen.queryByText('已处理的审批')).not.toBeInTheDocument();expect(screen.queryByText('不应继续显示')).not.toBeInTheDocument();const expected = {- approved: '已允许执行命令',- rejected: '已拒绝执行命令',- expired: '权限申请已过期',- canceled: '权限申请已取消'+ approved: 'Allowed: run command',+ rejected: 'Denied: run command',+ expired: 'Permission request expired',+ canceled: 'Permission request canceled'}[status];expect(screen.getByText(expected)).toBeInTheDocument();expect(container.querySelector('.timeline-approval-resolved')).toBeInTheDocument();@@ -144,7 +144,7 @@ describe('Timeline', () => {/>);- expect(screen.getByText('已允许访问 apps.apple.com')).toBeInTheDocument();+ expect(screen.getByText('Allowed: access apps.apple.com')).toBeInTheDocument();});it('renders image metadata and a local preview with the user message', () => {@@ -215,11 +215,11 @@ describe('Timeline', () => {expect(bubble).not.toContainElement(meta);expect(meta?.querySelector('time')).toHaveAttribute('datetime', item.timestamp);- await user.click(screen.getByRole('button', { name: '复制消息' }));+ await user.click(screen.getByRole('button', { name: 'Copy Message' }));expect(writeText).toHaveBeenCalledWith('重新整理这段需求');- expect(await screen.findByRole('button', { name: '已复制消息' })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: 'Copied Message' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '编辑消息' }));+ await user.click(screen.getByRole('button', { name: 'Edit message' }));expect(onEditUserMessage).toHaveBeenCalledWith(item);});@@ -267,14 +267,14 @@ describe('Timeline', () => {);const latestReplyMeta = replies[1]?.querySelector('.timeline-message-meta');expect(latestReplyMeta?.children[0]).toBe(- screen.getAllByRole('button', { name: '复制回复' })[1]+ screen.getAllByRole('button', { name: 'Copy Reply' })[1]);expect(latestReplyMeta?.children[1]).toBe(latestReplyMeta?.querySelector('time'));- expect(screen.queryByRole('button', { name: '编辑消息' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Edit message' })).not.toBeInTheDocument();- await user.click(screen.getAllByRole('button', { name: '复制回复' })[1]!);+ await user.click(screen.getAllByRole('button', { name: 'Copy Reply' })[1]!);expect(writeText).toHaveBeenCalledWith('最新回复');- expect(await screen.findByRole('button', { name: '已复制回复' })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: 'Copied Reply' })).toBeInTheDocument();});it('marks the virtual item that contains a search target', () => {@@ -484,7 +484,7 @@ describe('Timeline', () => {expect(screen.queryByText('运行 running')).not.toBeInTheDocument();expect(screen.queryByText('running')).not.toBeInTheDocument();expect(screen.queryByText('queued')).not.toBeInTheDocument();- expect(screen.queryByText('排队中')).not.toBeInTheDocument();+ expect(screen.queryByText('Queued')).not.toBeInTheDocument();expect(screen.queryByText('处理中')).not.toBeInTheDocument();expect(screen.queryByText('我会先确认日志里有没有失败信息。')).not.toBeInTheDocument();@@ -492,12 +492,12 @@ describe('Timeline', () => {expect(screen.getByText('我会先确认日志里有没有失败信息。')).toBeInTheDocument();expect(screen.getByText('然后根据结果给出结论。')).toBeInTheDocument();- expect(screen.queryByText('正在运行测试')).not.toBeInTheDocument();+ expect(screen.queryByText('Running: Run tests')).not.toBeInTheDocument();expect(screen.queryByText('pnpm test')).not.toBeInTheDocument();expect(screen.queryByText('{"type":"tool_use","toolCallId":"call_1","name":"exec_command","input":{"command":"pnpm test"}}')).not.toBeInTheDocument();- expect(screen.getByText('已运行测试')).toBeInTheDocument();+ expect(screen.getByText('Ran tests')).toBeInTheDocument();expect(screen.queryByText('工具完成 call_1')).not.toBeInTheDocument();expect(screen.queryByText('{"type":"tool_result","toolCallId":"call_1","output":"test output","exitCode":0,"isError":false}')@@ -547,7 +547,7 @@ describe('Timeline', () => {expect(screen.getByText('正在思考')).toBeInTheDocument();expect(screen.queryByText(/等待 OpenCreator 返回过程/)).not.toBeInTheDocument();expect(screen.queryByText(/当前动态/)).not.toBeInTheDocument();- expect(screen.queryByText('运行详情')).not.toBeInTheDocument();+ expect(screen.queryByText('Run details')).not.toBeInTheDocument();expect(container.querySelector('.process-detail')).not.toBeInTheDocument();expect(screen.queryByText('处理中')).not.toBeInTheDocument();});@@ -742,13 +742,13 @@ describe('Timeline', () => {await user.click(screen.getByRole('link', { name: '放假.md' }));await user.click(screen.getByRole('link', { name: 'docs/report.pdf' }));- await user.click(screen.getByRole('button', { name: '打开成果 docs/report.pdf' }));+ await user.click(screen.getByRole('button', { name: 'Open output docs/report.pdf' }));expect(onOpenFile).toHaveBeenNthCalledWith(1, '放假.md');expect(onOpenFile).toHaveBeenNthCalledWith(2, 'docs/report.pdf');expect(onOpenFile).toHaveBeenNthCalledWith(3, 'docs/report.pdf');- expect(screen.getByText('PDF 文档')).toBeInTheDocument();- expect(screen.getByLabelText('任务成果')).toBeInTheDocument();+ expect(screen.getByText('PDF document')).toBeInTheDocument();+ expect(screen.getByLabelText('Task outputs')).toBeInTheDocument();});it('keeps user messages conservative while still rendering code and safe links', () => {@@ -910,7 +910,7 @@ describe('Timeline', () => {expect(screen.queryByText('正在思考')).not.toBeInTheDocument();await user.click(screen.getByText('已完成'));- expect(screen.queryByText('运行详情')).not.toBeInTheDocument();+ expect(screen.queryByText('Run details')).not.toBeInTheDocument();expect(screen.queryByText('本次没有可展示的中间过程。')).not.toBeInTheDocument();expect(container.querySelector('.process-detail')).not.toBeInTheDocument();expect(screen.queryByText('queued')).not.toBeInTheDocument();@@ -943,15 +943,15 @@ describe('Timeline', () => {expect(container.querySelector('.timeline-process')).toBeInTheDocument();expect(container.querySelector('.timeline-process details')).toHaveAttribute('open');expect(screen.getByText('已完成')).toBeInTheDocument();- expect(screen.getByText('任务运行时间过长,已自动停止')).toBeInTheDocument();- expect(screen.queryByText('运行详情')).not.toBeInTheDocument();+ expect(screen.getByText('The task exceeded its time limit and was stopped automatically')).toBeInTheDocument();+ expect(screen.queryByText('Run details')).not.toBeInTheDocument();});it('renders readable timeout failure labels', () => {const reasons = [- ['timeout', '任务运行时间过长,已自动停止'],- ['inactivity_timeout', '任务长时间无响应,已自动停止'],- ['spawn_timeout', 'Codex 启动超时']+ ['timeout', 'The task exceeded its time limit and was stopped automatically'],+ ['inactivity_timeout', 'The task stopped responding and was stopped automatically'],+ ['spawn_timeout', 'Codex startup timed out']] as const;for (const [terminationReason, label] of reasons) {@@ -1002,7 +1002,7 @@ describe('Timeline', () => {/>);- expect(screen.getByText('任务长时间无响应,已自动停止')).toBeInTheDocument();+ expect(screen.getByText('The task stopped responding and was stopped automatically')).toBeInTheDocument();expect(screen.queryByText('Codex app-server inactivity timeout after 600000ms')).not.toBeInTheDocument();expect(screen.queryByText('failed')).not.toBeInTheDocument();expect(screen.queryByText(/terminationReason/u)).not.toBeInTheDocument();@@ -1025,7 +1025,7 @@ describe('Timeline', () => {/>);- expect(screen.queryByText('操作已完成')).not.toBeInTheDocument();+ expect(screen.queryByText('Operation completed')).not.toBeInTheDocument();expect(screen.queryByText('工具完成 call_missing')).not.toBeInTheDocument();});@@ -1048,7 +1048,7 @@ describe('Timeline', () => {/>);- expect(screen.getByText('正在运行测试')).toBeInTheDocument();+ expect(screen.getByText('Running: Run tests')).toBeInTheDocument();expect(screen.queryByText('pnpm --filter @opencreator/web test -- src/app/App.test.tsx')).not.toBeInTheDocument();expect(screen.queryByText(content)).not.toBeInTheDocument();});@@ -1072,12 +1072,12 @@ describe('Timeline', () => {};const { container, rerender } = render(<Timeline items={[firstTool]} />);- expect(screen.getByText('正在查看项目内容')).toBeInTheDocument();+ expect(screen.getByText('Running: Read project files')).toBeInTheDocument();rerender(<Timeline items={[firstTool, nextTool]} />);- expect(screen.queryByText('正在查看项目内容')).not.toBeInTheDocument();- expect(screen.getByText('正在运行测试')).toBeInTheDocument();+ expect(screen.queryByText('Running: Read project files')).not.toBeInTheDocument();+ expect(screen.getByText('Running: Run tests')).toBeInTheDocument();expect(container.querySelectorAll('.process-step-tool_step')).toHaveLength(1);});@@ -1114,8 +1114,8 @@ describe('Timeline', () => {const { container } = render(<Timeline items={items} />);- expect(screen.getByText('已执行本地命令')).toBeInTheDocument();- expect(screen.queryByText('正在执行本地命令')).not.toBeInTheDocument();+ expect(screen.getByText('Completed: Run local command')).toBeInTheDocument();+ expect(screen.queryByText('Running: Run local command')).not.toBeInTheDocument();expect(container.querySelectorAll('.process-step-tool_step')).toHaveLength(1);expect(container.querySelector('.process-step-tool_step')).toHaveAttribute('aria-live', 'polite');});@@ -1176,9 +1176,9 @@ describe('Timeline', () => {render(<Timeline items={items} />);- expect(screen.getByText('已允许并执行本地命令')).toBeInTheDocument();- expect(screen.queryByText('已允许执行命令')).not.toBeInTheDocument();- expect(screen.queryByText('已执行本地命令')).not.toBeInTheDocument();+ expect(screen.getByText('Approved and ran local command')).toBeInTheDocument();+ expect(screen.queryByText('Allowed: run command')).not.toBeInTheDocument();+ expect(screen.queryByText('Completed: Run local command')).not.toBeInTheDocument();});it('keeps completed business milestones while hiding generic command history', async () => {@@ -1229,7 +1229,7 @@ describe('Timeline', () => {const { container } = render(<Timeline items={items} />);await user.click(screen.getByText('已完成'));- expect(screen.getByText('已使用浏览器')).toBeInTheDocument();+ expect(screen.getByText('Used browser')).toBeInTheDocument();expect(screen.queryByText(/执行本地命令/u)).not.toBeInTheDocument();expect(screen.queryByText('echo done')).not.toBeInTheDocument();expect(container.querySelectorAll('.process-milestone-icon')).toHaveLength(1);@@ -1267,8 +1267,8 @@ describe('Timeline', () => {const { container } = render(<Timeline items={items} />);- expect(screen.getByText('已查看图片(3 次)')).toBeInTheDocument();- expect(screen.queryByText('已查看图片')).not.toBeInTheDocument();+ expect(screen.getByText('Viewed image (3 times)')).toBeInTheDocument();+ expect(screen.queryByText('Viewed image')).not.toBeInTheDocument();expect(container.querySelectorAll('.process-milestone-icon')).toHaveLength(1);});@@ -1338,9 +1338,9 @@ describe('Timeline', () => {await user.click(screen.getByText('已完成'));expect(screen.getByText('我会先确认当前目录,再读取相关文件做判断。')).toBeInTheDocument();- expect(screen.queryByText('正在查看项目内容')).not.toBeInTheDocument();+ expect(screen.queryByText('Running: Read project files')).not.toBeInTheDocument();expect(screen.queryByText('pwd')).not.toBeInTheDocument();- expect(screen.getByText('已读取文件')).toBeInTheDocument();+ expect(screen.getByText('Read files')).toBeInTheDocument();expect(screen.queryByText('工具完成 call_1')).not.toBeInTheDocument();expect(screen.getByText('当前目录是 /repo,检查已完成。')).toBeInTheDocument();expect(container.querySelectorAll('.timeline-assistant_message')).toHaveLength(1);@@ -1483,7 +1483,7 @@ describe('Timeline', () => {);expect(screen.getByText('我会先确认可访问性和索引信号,再检查首页内容与技术要素。')).toBeInTheDocument();- expect(screen.getByText('正在确认执行方案')).toBeInTheDocument();+ expect(screen.getByText('Reviewing the execution plan')).toBeInTheDocument();expect(screen.queryByText('Planning skill reference review')).not.toBeInTheDocument();rerender(@@ -1521,8 +1521,8 @@ describe('Timeline', () => {/>);- expect(screen.queryByText('正在确认执行方案')).not.toBeInTheDocument();- expect(screen.getByText('正在检查网站可访问性')).toBeInTheDocument();+ expect(screen.queryByText('Reviewing the execution plan')).not.toBeInTheDocument();+ expect(screen.getByText('Checking website access')).toBeInTheDocument();expect(screen.queryByText('Inspecting site with curl')).not.toBeInTheDocument();});@@ -1543,12 +1543,12 @@ describe('Timeline', () => {render(<Timeline items={items} onOpenFile={onOpenFile} />);const fileButton = screen.getByRole('button', {- name: '打开文件 apps/web/src/components/timeline/timeline-model.ts'+ name: 'Open file apps/web/src/components/timeline/timeline-model.ts'});expect(fileButton).toHaveAttribute('aria-label',- '打开文件 apps/web/src/components/timeline/timeline-model.ts'+ 'Open file apps/web/src/components/timeline/timeline-model.ts');await user.click(fileButton);@@ -1577,7 +1577,7 @@ describe('Timeline', () => {render(<Timeline items={items} />);expect(screen.queryByRole('button', { name: /查看运行详情/ })).not.toBeInTheDocument();- expect(screen.queryByText('运行详情')).not.toBeInTheDocument();+ expect(screen.queryByText('Run details')).not.toBeInTheDocument();});it('keeps queued follow-ups out of the conversation timeline', () => {@@ -1653,12 +1653,12 @@ describe('Timeline', () => {render(<Timeline items={items} onOpenFile={onOpenFile} />);- expect(screen.getByText('3 次连续文件变更')).toBeInTheDocument();- expect(screen.getByText('2 个文件')).toBeInTheDocument();+ expect(screen.getByText('3 consecutive file changes')).toBeInTheDocument();+ expect(screen.getByText('2 files')).toBeInTheDocument();expect(screen.queryByText('修改 App.tsx')).not.toBeInTheDocument();await user.click(screen.getByRole('button', {- name: '打开文件 apps/web/src/app/App.tsx'+ name: 'Open file apps/web/src/app/App.tsx'}));expect(onOpenFile).toHaveBeenCalledWith('apps/web/src/app/App.tsx');@@ -1696,17 +1696,17 @@ describe('Timeline', () => {/>);- const newContentButton = await screen.findByRole('button', { name: '有新内容' });+ const newContentButton = await screen.findByRole('button', { name: 'New content' });await user.click(newContentButton);- expect(screen.queryByRole('button', { name: '有新内容' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'New content' })).not.toBeInTheDocument();});it('renders the OpenCreator empty state', () => {render(<Timeline items={[]} />);- expect(screen.getByText('暂无任务记录')).toBeInTheDocument();- expect(screen.getByText('发送任务后,OpenCreator 会在这里展示处理过程和结果。')).toBeInTheDocument();+ expect(screen.getByText('No task history')).toBeInTheDocument();+ expect(screen.getByText('Task progress and results will appear here.')).toBeInTheDocument();});it('keeps long histories virtualized and exposes older-page loading', async () => {@@ -1730,7 +1730,7 @@ describe('Timeline', () => {expect(container.querySelectorAll('.timeline-item').length).toBeLessThan(80);- await user.click(screen.getByRole('button', { name: '加载更早记录' }));+ await user.click(screen.getByRole('button', { name: 'Load earlier history' }));expect(onLoadOlder).toHaveBeenCalledTimes(1);});diff --git a/apps/web/src/components/timeline/Timeline.tsx b/apps/web/src/components/timeline/Timeline.tsxindex 32d95618..89287be3 100644--- a/apps/web/src/components/timeline/Timeline.tsx+++ b/apps/web/src/components/timeline/Timeline.tsx@@ -91,21 +91,21 @@ function isInternalRuntimeDiagnostic(item: TimelineItem): boolean {function getTimelineTitle(item: TimelineItem): string {switch (item.kind) {case 'user_message':- return '你';+ return 'You';case 'schedule_trigger':- return '定时执行';+ return 'Scheduled run';case 'assistant_message':return 'OpenCreator';case 'change_card':- return '文件变更';+ return 'File changes';case 'approval':- return '需要确认';+ return 'Confirmation required';case 'reasoning_summary':case 'tool_step':case 'diagnostic':case 'run_status':case 'done':- return '处理过程';+ return 'Process';default:const _exhaustive: never = item;return _exhaustive;@@ -113,8 +113,8 @@ function getTimelineTitle(item: TimelineItem): string {}function getTimelineAvatar(item: TimelineItem): string {- if (item.kind === 'user_message') return '你';- if (item.kind === 'schedule_trigger') return '定';+ if (item.kind === 'user_message') return 'Y';+ if (item.kind === 'schedule_trigger') return 'S';if (item.kind === 'change_card') return 'Δ';if (item.kind === 'assistant_message') return '·';return '·';@@ -311,110 +311,110 @@ function getToolActivity(normalizedName.includes('apply_patch')|| normalizedName.includes('edit')|| normalizedName.includes('write')- ) return '修改项目文件';+ ) return 'Edit project files';if (normalizedName.includes('image')|| normalizedName.includes('screenshot')- ) return '查看图片';+ ) return 'View image';if (normalizedName.includes('browser')|| normalizedName.includes('chrome')|| normalizedName.includes('playwright')- ) return '操作浏览器';+ ) return 'Use browser';if (normalizedName.includes('web')|| normalizedName.includes('query')- ) return '查询资料';+ ) return 'Search information';if (normalizedName.includes('read')|| normalizedName.includes('open')|| normalizedName.includes('find')|| normalizedName.includes('search')- ) return '查看项目内容';+ ) return 'Read project files';if (normalizedName.includes('lark')|| normalizedName.includes('docs')- ) return '处理飞书文档';- return '执行开发操作';+ ) return 'Work with Feishu documents';+ return 'Run development tools';}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 '已更新代码';+ case 'Read project files':+ return 'Read files';+ case 'View image':+ return 'Viewed image';+ case 'Use browser':+ return 'Used browser';+ case 'Search information':+ return 'Searched information';+ case 'Work with Feishu documents':+ return 'Updated Feishu documents';+ case 'Edit project files':+ return 'Updated files';+ case 'Run tests':+ return 'Ran tests';+ case 'Package application':+ return 'Packaged application';+ case 'Build application':+ return 'Built application';+ case 'Review code changes':+ return 'Reviewed code changes';+ case 'Update code':+ return 'Updated code';default:return undefined;}})();if (label === undefined || count === 1) return label;- return `${label}(${count} 次)`;+ return `${label} (${count} times)`;}function getCommandActivity(command: string | undefined): string {- if (command === undefined) return '执行本地命令';+ if (command === undefined) return 'Run local command';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 '运行测试';+ ) return 'Run tests';if (/\b(?:electron-builder|package-release)\b/u.test(normalized)|| /\b(?:pnpm|npm|yarn)\b[^\n]*\bpackage\b/u.test(normalized)- ) return '打包应用';+ ) return 'Package application';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 '更新代码';+ ) return 'Build application';+ if (/^git\s+(?:status|diff|log|show)\b/u.test(normalized)) return 'Review code changes';+ if (/^git\s+/u.test(normalized)) return 'Update code';if (/^(?:rg|grep|sed|cat|ls|find|head|tail|wc|pwd)\b/u.test(normalized)) {- return '查看项目内容';+ return 'Read project files';}- return '执行本地命令';+ return 'Run local command';}function formatTerminationReason(reason: string | undefined): string {switch (reason) {case 'timeout':- return '任务运行时间过长,已自动停止';+ return 'The task exceeded its time limit and was stopped automatically';case 'inactivity_timeout':- return '任务长时间无响应,已自动停止';+ return 'The task stopped responding and was stopped automatically';case 'spawn_timeout':- return 'Codex 启动超时';+ return 'Codex startup timed out';case 'user_canceled':- return '用户已取消';+ return 'Canceled by user';case 'daemon_restart':- return '服务重启,任务已中断';+ return 'The Runtime restarted and interrupted the task';case 'codex_exit_non_zero':- return 'Codex 执行失败';+ return 'Codex execution failed';case 'spawn_failed':- return 'Codex 启动失败';+ return 'Codex failed to start';case 'stream_error':- return 'Codex 输出异常';+ return 'Invalid Codex output';case undefined:- return '未知原因';+ return 'Unknown reason';default:return reason;}@@ -427,14 +427,14 @@ function getProcessStepTitle(item: ProcessTimelineItem): string {return item.text;case 'tool_step': {return getPayloadType(item) === 'tool_result'- ? '操作已完成'- : `正在${getToolActivity(item.name, getToolCommand(item))}`;+ ? 'Operation completed'+ : `Running: ${getToolActivity(item.name, getToolCommand(item))}`;}case 'diagnostic':return item.message;case 'done':return item.status === 'canceled'- ? `运行已取消:${formatTerminationReason(item.terminationReason ?? 'user_canceled')}`+ ? `Run canceled: ${formatTerminationReason(item.terminationReason ?? 'user_canceled')}`: item.status === 'failed'? formatTerminationReason(item.terminationReason): '';@@ -451,13 +451,13 @@ function getTransientProcessActivity(item: VisibleProcessItem): string | undefinconst 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 '正在获取数据';+ if (/^planning\b/i.test(text)) return 'Reviewing the execution plan';+ if (/^inspect(?:ing)?\b.*\b(?:site|website)\b/i.test(text)) return 'Checking website access';+ if (/^read(?:ing)?\b/i.test(text)) return 'Reading task information';+ if (/^search(?:ing)?\b/i.test(text)) return 'Searching information';+ if (/^(?:check(?:ing)?|review(?:ing)?|analyz(?:ing)?)\b/i.test(text)) return 'Analyzing task information';+ if (/^(?:run(?:ning)?|execut(?:ing)?)\b/i.test(text)) return 'Running task';+ if (/^fetch(?:ing)?\b/i.test(text)) return 'Fetching data';return undefined;}@@ -551,7 +551,7 @@ function buildVisibleProcessSteps(process: ProcessBlock): ProcessDisplayStep[] {steps.push({key: `live:${latestToolUse.id}`,item: latestToolUse,- title: `${activityRunning ? '正在' : '已'}${activity}`,+ title: `${activityRunning ? 'Running: ' : 'Completed: '}${activity}`,liveActivity: true,activityRunning});@@ -564,8 +564,8 @@ function getProcessCompletedActivityLabel(activity: string,count = 1): string | undefined {- if (activity === '执行本地命令' && process.approvedCommandExecution === true) {- return count === 1 ? '已允许并执行本地命令' : `已允许并执行本地命令(${count} 次)`;+ if (activity === 'Run local command' && process.approvedCommandExecution === true) {+ return count === 1 ? 'Approved and ran local command' : `Approved and ran local command (${count} times)`;}return getCompletedActivityLabel(activity, count);}@@ -748,7 +748,7 @@ function collectCompletedCommandRunIds(items: TimelineItem[]): Set<string> {if (toolCallId === undefined || runId === undefined) continue;const callKey = `${runId}:${toolCallId}`;const payloadType = getPayloadType(item);- if (payloadType === 'tool_use' && getToolActivity(item.name, getToolCommand(item)) === '执行本地命令') {+ if (payloadType === 'tool_use' && getToolActivity(item.name, getToolCommand(item)) === 'Run local command') {commandUsesByCallId.set(callKey, runId);continue;}@@ -799,13 +799,13 @@ function renderMessageContent(: undefined}/>{artifacts.length > 0 ? (- <div className="timeline-artifacts" aria-label="任务成果">+ <div className="timeline-artifacts" aria-label="Task outputs">{artifacts.map(path => (<buttonkey={path}type="button"className="timeline-artifact-card"- aria-label={`打开成果 ${path}`}+ aria-label={`Open output ${path}`}onClick={() => onOpenFile?.(path)}><FileText aria-hidden="true" size={17} />@@ -813,7 +813,7 @@ function renderMessageContent(<strong>{artifactFileName(path)}</strong><span>{artifactTypeLabel(path)}</span></span>- <span className="timeline-artifact-action">打开</span>+ <span className="timeline-artifact-action">Open</span></button>))}</div>@@ -842,22 +842,22 @@ function artifactTypeLabel(path: string): string {switch (artifactExtension(path)) {case 'html':case 'htm':- return 'HTML 报告';+ return 'HTML report';case 'pdf':- return 'PDF 文档';+ return 'PDF document';case 'doc':case 'docx':- return 'Word 文档';+ return 'Word document';case 'xls':case 'xlsx':- return 'Excel 表格';+ return 'Excel workbook';case 'ppt':case 'pptx':- return '演示文稿';+ return 'Presentation';case 'csv':- return '数据表';+ return 'Data table';default:- return '文档';+ return 'Document';}}@@ -876,15 +876,15 @@ function formatApprovalResolution(approval: Extract<TimelineItem, { kind: 'approconst prefix = (() => {switch (approval.status) {case 'approved':- return '已允许';+ return 'Allowed';case 'rejected':- return '已拒绝';+ return 'Denied';case 'expired':- return '权限申请已过期';+ return 'Permission request expired';case 'canceled':- return '权限申请已取消';+ return 'Permission request canceled';case 'pending':- return '等待批准';+ return 'Waiting for approval';}})();if (approval.status === 'expired' || approval.status === 'canceled') return prefix;@@ -892,10 +892,10 @@ function formatApprovalResolution(approval: Extract<TimelineItem, { kind: 'approif (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}获取权限`;+ return host ? `${prefix}: access ${host}` : `${prefix}: request permissions`;}- if (approval.kind === 'file_change') return `${prefix}修改文件`;- return `${prefix}执行命令`;+ if (approval.kind === 'file_change') return `${prefix}: modify files`;+ return `${prefix}: run command`;}function MessageMeta(props: {@@ -904,7 +904,7 @@ function MessageMeta(props: {onEdit?: (item: Extract<TimelineItem, { kind: 'user_message' }>) => void;}) {const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle');- const itemLabel = props.item.kind === 'assistant_message' ? '回复' : '消息';+ const itemLabel = props.item.kind === 'assistant_message' ? 'Reply' : 'Message';const timestamp = props.item.timestamp ? (<time dateTime={props.item.timestamp}>{formatMessageTime(props.item.timestamp)}</time>) : null;@@ -913,12 +913,12 @@ function MessageMeta(props: {type="button"aria-label={copyState === 'copied'- ? `已复制${itemLabel}`+ ? `Copied ${itemLabel}`: copyState === 'failed'- ? `复制${itemLabel}失败`- : `复制${itemLabel}`+ ? `Could not copy ${itemLabel}`+ : `Copy ${itemLabel}`}- title={copyState === 'copied' ? '已复制' : copyState === 'failed' ? '复制失败' : '复制'}+ title={copyState === 'copied' ? 'Copied' : copyState === 'failed' ? 'Copy failed' : 'Copy'}onClick={async () => {setCopyState(await copyToClipboard(props.item.text) ? 'copied' : 'failed');}}@@ -938,8 +938,8 @@ function MessageMeta(props: {{props.item.kind === 'user_message' && props.onEdit ? (<buttontype="button"- aria-label="编辑消息"- title="编辑"+ aria-label="Edit message"+ title="Edit"onClick={() => {if (props.item.kind === 'user_message') props.onEdit?.(props.item);}}@@ -998,7 +998,7 @@ function renderChangeCard(item: Extract<TimelineItem, { kind: 'change_card' }>,<strong>{item.title}</strong><span>{item.path}</span><code>{item.delta}</code>- {onOpenFile ? <span className="change-card-action">打开</span> : null}+ {onOpenFile ? <span className="change-card-action">Open</span> : null}</>);@@ -1007,7 +1007,7 @@ function renderChangeCard(item: Extract<TimelineItem, { kind: 'change_card' }>,<buttontype="button"className="change-card-content change-card-button"- aria-label={`打开文件 ${item.path}`}+ aria-label={`Open file ${item.path}`}onClick={() => onOpenFile(item.path)}>{content}@@ -1036,8 +1036,8 @@ function renderChangeBlock(return (<div className="change-card-content change-card-group">- <strong>{block.items.length} 次连续文件变更</strong>- <span>{paths.length} 个文件</span>+ <strong>{block.items.length} consecutive file changes</strong>+ <span>{paths.length} files</span><div className="change-card-paths">{visiblePaths.map(path => (onOpenFile ? (@@ -1045,7 +1045,7 @@ function renderChangeBlock(key={path}type="button"className="change-card-path-button"- aria-label={`打开文件 ${path}`}+ aria-label={`Open file ${path}`}onClick={() => onOpenFile(path)}>{path}@@ -1054,7 +1054,7 @@ function renderChangeBlock(<code key={path}>{path}</code>)))}- {hiddenCount > 0 ? <span>另有 {hiddenCount} 个文件</span> : null}+ {hiddenCount > 0 ? <span>Additional {hiddenCount} files</span> : null}</div></div>);@@ -1165,19 +1165,19 @@ function renderProcessStep(step: ProcessDisplayStep) {function renderMilestoneIcon(activity: string) {const props = { className: 'process-milestone-icon', 'aria-hidden': true, size: 14 } as const;switch (activity) {- case '查看项目内容':- case '处理飞书文档':+ case 'Read project files':+ case 'Work with Feishu documents':return <BookOpen {...props} />;- case '查询资料':- case '操作浏览器':+ case 'Search information':+ case 'Use browser':return <Globe2 {...props} />;- case '查看图片':+ case 'View image':return <ImageIcon {...props} />;- case '修改项目文件':+ case 'Edit project files':return <FilePenLine {...props} />;- case '运行测试':- case '构建应用':- case '打包应用':+ case 'Run tests':+ case 'Build application':+ case 'Package application':return <PackageCheck {...props} />;default:return <Check {...props} />;@@ -1395,8 +1395,8 @@ export const Timeline = forwardRef<TimelineHandle, TimelineProps>(function Timel<div className="timeline-list">{props.items.length === 0 ? (<div className="timeline-empty">- <strong>暂无任务记录</strong>- <span>发送任务后,OpenCreator 会在这里展示处理过程和结果。</span>+ <strong>No task history</strong>+ <span>Task progress and results will appear here.</span></div>) : (<div@@ -1446,7 +1446,7 @@ export const Timeline = forwardRef<TimelineHandle, TimelineProps>(function Timel) : (<ArrowUp aria-hidden="true" size={14} />)}- <span>{props.loadingOlder ? '正在加载更早记录' : '加载更早记录'}</span>+ <span>{props.loadingOlder ? 'Loading earlier history' : 'Load earlier history'}</span></button>) : null}</div>@@ -1487,7 +1487,7 @@ export const Timeline = forwardRef<TimelineHandle, TimelineProps>(function TimelonClick={scrollToLatest}><ArrowDown aria-hidden="true" size={15} />- <span>有新内容</span>+ <span>New content</span></button>) : null}</div>diff --git a/apps/web/src/components/timeline/timeline-model.test.ts b/apps/web/src/components/timeline/timeline-model.test.tsindex eeb912a3..1da81bb7 100644--- a/apps/web/src/components/timeline/timeline-model.test.ts+++ b/apps/web/src/components/timeline/timeline-model.test.ts@@ -296,9 +296,9 @@ describe('timeline model', () => {kind: 'change_card',id: 'evt_file_change',runId: 'run_1',- title: '新增 1 个文件,修改 1 个文件',+ title: 'Added 1 file, Modified 1 file',path: '/repo/放假.md',- delta: '2 项变更',+ delta: '2 changes',source: 'runtime'});});diff --git a/apps/web/src/components/timeline/timeline-model.ts b/apps/web/src/components/timeline/timeline-model.tsindex 8691616a..4426e83b 100644--- a/apps/web/src/components/timeline/timeline-model.ts+++ b/apps/web/src/components/timeline/timeline-model.ts@@ -78,18 +78,18 @@ function safeStringify(value: unknown): string {function formatChangeKind(kind: 'add' | 'modify' | 'delete' | 'unknown'): string {switch (kind) {case 'add':- return '新增';+ return 'Added';case 'modify':- return '修改';+ return 'Modified';case 'delete':- return '删除';+ return 'Deleted';case 'unknown':- return '变更';+ return 'Changed';}}function formatFileChangeTitle(changes: Array<{ kind: 'add' | 'modify' | 'delete' | 'unknown' }>): string {- if (changes.length === 0) return '文件变更';+ if (changes.length === 0) return 'File changes';const counts = new Map<'add' | 'modify' | 'delete' | 'unknown', number>();for (const change of changes) counts.set(change.kind, (counts.get(change.kind) ?? 0) + 1);@@ -97,10 +97,10 @@ function formatFileChangeTitle(changes: Array<{ kind: 'add' | 'modify' | 'deletereturn (['add', 'modify', 'delete', 'unknown'] as const).map(kind => {const count = counts.get(kind) ?? 0;- return count === 0 ? undefined : `${formatChangeKind(kind)} ${count} 个文件`;+ return count === 0 ? undefined : `${formatChangeKind(kind)} ${count} ${count === 1 ? 'file' : 'files'}`;}).filter((part): part is string => part !== undefined)- .join(',');+ .join(', ');}export function eventToTimelineItem(event: AgentEventEnvelope): TimelineItem | null {@@ -155,14 +155,14 @@ export function eventToTimelineItem(event: AgentEventEnvelope): TimelineItem | nsource: 'runtime'};case 'file_change': {- const primaryPath = event.payload.changes.find(change => change.path.length > 0)?.path ?? '文件变更';+ const primaryPath = event.payload.changes.find(change => change.path.length > 0)?.path ?? 'File changes';return {kind: 'change_card',id: event.id,runId: event.runId,title: formatFileChangeTitle(event.payload.changes),path: primaryPath,- delta: `${event.payload.changes.length} 项变更`,+ delta: `${event.payload.changes.length} changes`,source: 'runtime'};}diff --git a/apps/web/src/features/approvals/ApprovalPanel.test.tsx b/apps/web/src/features/approvals/ApprovalPanel.test.tsxindex d7ce7efc..951ae6e3 100644--- a/apps/web/src/features/approvals/ApprovalPanel.test.tsx+++ b/apps/web/src/features/approvals/ApprovalPanel.test.tsx@@ -34,14 +34,14 @@ describe('ApprovalPanel', () => {/>);- expect(screen.getByText('终端')).toBeInTheDocument();- expect(screen.getByText('允许 OpenCreator 执行这条命令?')).toBeInTheDocument();- expect(screen.getByText('仅本次')).toBeInTheDocument();- expect(screen.getByText('查看操作详情')).toBeInTheDocument();+ expect(screen.getByText('Terminal')).toBeInTheDocument();+ expect(screen.getByText('Allow OpenCreator to run this command?')).toBeInTheDocument();+ expect(screen.getByText('This time only')).toBeInTheDocument();+ expect(screen.getByText('View operation details')).toBeInTheDocument();expect(screen.getByText('rm -rf build')).toBeInTheDocument();expect(screen.getByText('/workspace')).toBeInTheDocument();- fireEvent.click(screen.getByRole('button', { name: '允许一次' }));- fireEvent.click(screen.getByRole('button', { name: '拒绝' }));+ fireEvent.click(screen.getByRole('button', { name: 'Allow once' }));+ fireEvent.click(screen.getByRole('button', { name: 'Reject' }));expect(onApprove).toHaveBeenCalledWith('approval_1');expect(onReject).toHaveBeenCalledWith('approval_1');@@ -56,8 +56,8 @@ describe('ApprovalPanel', () => {/>);- expect(screen.getByText('已拒绝')).toBeInTheDocument();- expect(screen.queryByRole('button', { name: '允许一次' })).not.toBeInTheDocument();+ expect(screen.getByText('Denied')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Allow once' })).not.toBeInTheDocument();});it('explains an expired approval without exposing technical codes', () => {@@ -74,7 +74,7 @@ describe('ApprovalPanel', () => {/>);- expect(screen.getByText('审批已过期,本次任务不会继续执行。')).toBeInTheDocument();+ expect(screen.getByText('This approval has expired. The task will not continue.')).toBeInTheDocument();expect(screen.queryByText('approval_timeout')).not.toBeInTheDocument();});});diff --git a/apps/web/src/features/approvals/ApprovalPanel.tsx b/apps/web/src/features/approvals/ApprovalPanel.tsxindex 8b2debec..eb8d7a4b 100644--- a/apps/web/src/features/approvals/ApprovalPanel.tsx+++ b/apps/web/src/features/approvals/ApprovalPanel.tsx@@ -32,7 +32,7 @@ export function ApprovalPanel(props: {{hasApprovalDetails(props.approval.details) ? (<details className="approval-disclosure"><summary>- <span>查看操作详情</span>+ <span>View operation details</span><ChevronDown aria-hidden="true" size={14} /></summary><ApprovalDetails details={props.approval.details} />@@ -40,18 +40,18 @@ export function ApprovalPanel(props: {) : null}{props.approval.status === 'expired' ? (<p className="approval-resolution">- 审批已过期,本次任务不会继续执行。+ This approval has expired. The task will not continue.</p>) : null}{props.approval.status === 'rejected' ? (<p className="approval-resolution">- 你已拒绝这项操作,本次任务不会继续执行。+ You denied this operation. The task will not continue.</p>) : null}{props.error ? <p className="inline-error">{props.error}</p> : null}{pending ? (<div className="approval-footer">- <span className="approval-scope">仅本次</span>+ <span className="approval-scope">This time only</span><div className="approval-actions"><buttontype="button"@@ -60,7 +60,7 @@ export function ApprovalPanel(props: {onClick={() => props.onReject(props.approval.id)}><X aria-hidden="true" size={14} />- 拒绝+ Reject</button><buttontype="button"@@ -69,7 +69,7 @@ export function ApprovalPanel(props: {onClick={() => props.onApprove(props.approval.id)}><Check aria-hidden="true" size={14} />- 允许一次+ Allow once</button></div></div>@@ -85,11 +85,11 @@ function getApprovalCopy(kind: RuntimeApproval['kind']): {} {switch (kind) {case 'command_execution':- return { source: '终端', question: '允许 OpenCreator 执行这条命令?', icon: SquareTerminal };+ return { source: 'Terminal', question: 'Allow OpenCreator to run this command?', icon: SquareTerminal };case 'file_change':- return { source: '文件', question: '允许 OpenCreator 修改项目文件?', icon: FilePenLine };+ return { source: 'Files', question: 'Allow OpenCreator to modify project files?', icon: FilePenLine };case 'permissions':- return { source: '权限', question: '允许 OpenCreator 获取这项权限?', icon: ShieldCheck };+ return { source: 'Permission', question: 'Allow OpenCreator to request this permission?', icon: ShieldCheck };}}@@ -117,10 +117,10 @@ function ApprovalDetails(props: { details: Record<string, unknown> }) {return (<dl className="approval-details">- {command ? <Detail label="命令" value={command} code /> : null}- {cwd ? <Detail label="目录" value={cwd} code /> : null}- {grantRoot ? <Detail label="写入范围" value={grantRoot} code /> : null}- {host ? <Detail label="网络目标" value={formatNetwork(network!)} code /> : null}+ {command ? <Detail label="Command" value={command} code /> : null}+ {cwd ? <Detail label="Directory" value={cwd} code /> : null}+ {grantRoot ? <Detail label="Write scope" value={grantRoot} code /> : null}+ {host ? <Detail label="Network target" value={formatNetwork(network!)} code /> : null}</dl>);}@@ -152,15 +152,15 @@ function formatNetwork(network: Record<string, unknown>): string {function formatApprovalStatus(status: RuntimeApproval['status']): string {switch (status) {case 'pending':- return '等待你的决定';+ return 'Waiting for your decision';case 'approved':- return '已批准';+ return 'Approved';case 'rejected':- return '已拒绝';+ return 'Denied';case 'expired':- return '已过期';+ return 'Expired';case 'canceled':- return '已取消';+ return 'Canceled';}}diff --git a/apps/web/src/features/capabilities/CapabilitiesView.test.tsx b/apps/web/src/features/capabilities/CapabilitiesView.test.tsxindex 8704b7b0..ef320f42 100644--- a/apps/web/src/features/capabilities/CapabilitiesView.test.tsx+++ b/apps/web/src/features/capabilities/CapabilitiesView.test.tsx@@ -102,15 +102,15 @@ describe('CapabilitiesView', () => {expect(screen.getByRole('heading', { name: 'MCP' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: 'Profiles' })).toBeInTheDocument();expect(screen.getByText('2 个技能')).toBeInTheDocument();- expect(screen.getByText('1 个 servers')).toBeInTheDocument();- expect(screen.getByText('3 个 profiles')).toBeInTheDocument();+ expect(screen.getByText('1 servers')).toBeInTheDocument();+ expect(screen.getByText('3 profiles')).toBeInTheDocument();});it('shows zero counts when connected capability data is missing', () => {render(<CapabilitiesView connected />);expect(screen.getByText('0 个技能')).toBeInTheDocument();- expect(screen.getByText('0 个 servers')).toBeInTheDocument();- expect(screen.getByText('0 个 profiles')).toBeInTheDocument();+ expect(screen.getByText('0 servers')).toBeInTheDocument();+ expect(screen.getByText('0 profiles')).toBeInTheDocument();});});diff --git a/apps/web/src/features/capabilities/CapabilitiesView.tsx b/apps/web/src/features/capabilities/CapabilitiesView.tsxindex 85494b25..57f37b7b 100644--- a/apps/web/src/features/capabilities/CapabilitiesView.tsx+++ b/apps/web/src/features/capabilities/CapabilitiesView.tsx@@ -21,18 +21,18 @@ export function CapabilitiesView(props: CapabilitiesViewProps) {return (<div className="panel-scroll">- <h2>能力</h2>+ <h2>Capabilities</h2><section><h3>{l('技能', 'Skills')}</h3><p>{props.skills?.skills.length ?? 0} {l('个技能', 'skills')}</p></section><section><h3>MCP</h3>- <p>{props.mcp?.servers.length ?? 0} 个 servers</p>+ <p>{props.mcp?.servers.length ?? 0} servers</p></section><section><h3>Profiles</h3>- <p>{props.profiles?.profiles.length ?? 0} 个 profiles</p>+ <p>{props.profiles?.profiles.length ?? 0} profiles</p></section></div>);diff --git a/apps/web/src/features/connection/ConnectionPanel.tsx b/apps/web/src/features/connection/ConnectionPanel.tsxindex 8adf7edf..dbc99d50 100644--- a/apps/web/src/features/connection/ConnectionPanel.tsx+++ b/apps/web/src/features/connection/ConnectionPanel.tsx@@ -8,21 +8,21 @@ export function ConnectionPanel(props: {}) {const title =props.status === 'connected'- ? `已连接 ${props.codexStatus?.codexVersion ?? 'unknown'}`+ ? `Connected ${props.codexStatus?.codexVersion ?? 'unknown'}`: props.status === 'invalid_token'- ? 'Runtime 授权未就绪'- : '正在等待本机 Runtime';+ ? 'Runtime authorization is not ready'+ : 'Waiting for the local Runtime';const message =props.status === 'connected'? props.codexStatus?.codexHome: props.status === 'invalid_token'- ? '本机 Runtime 握手失败,请重新检测。'+ ? 'The local Runtime handshake failed. Check again.': props.message !== undefined && props.message !== title? props.message- : '应用会自动接入本机 Codex Runtime,无需手动配置。';+ : 'OpenCreator connects to the local Codex Runtime automatically.';return (- <div className="connection-panel" aria-label="Runtime 连接状态">+ <div className="connection-panel" aria-label="Runtime connection status"><div className="panel-header"><div className="connection-status"><span className={`connection-status-dot ${props.status}`} aria-hidden="true" />@@ -32,7 +32,7 @@ export function ConnectionPanel(props: {<div className="connection-summary">{message ? <p>{message}</p> : null}<button type="button" onClick={props.onRetry}>- 重新检测+ Retry detection</button></div></div>diff --git a/apps/web/src/features/conversation/ConversationHeader.test.tsx b/apps/web/src/features/conversation/ConversationHeader.test.tsxindex bc8f9a98..d40e0633 100644--- a/apps/web/src/features/conversation/ConversationHeader.test.tsx+++ b/apps/web/src/features/conversation/ConversationHeader.test.tsx@@ -15,7 +15,7 @@ describe('ConversationHeader', () => {expect(screen.getByRole('heading', { name: '整理本周项目进展' })).toBeInTheDocument();expect(screen.queryByText('content-design')).not.toBeInTheDocument();expect(screen.queryByRole('status')).not.toBeInTheDocument();- expect(screen.getByRole('button', { name: '文件' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Files' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: '详情' })).not.toBeInTheDocument();});@@ -30,7 +30,7 @@ describe('ConversationHeader', () => {/>);- await user.click(screen.getByRole('button', { name: '文件' }));+ await user.click(screen.getByRole('button', { name: 'Files' }));expect(onOpenLocation).toHaveBeenCalledTimes(1);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();@@ -45,13 +45,13 @@ describe('ConversationHeader', () => {/>);- expect(screen.getByRole('button', { name: '文件' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: 'Files' })).toHaveAttribute('aria-pressed','true');- expect(screen.getByRole('button', { name: '文件' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: 'Files' })).toHaveAttribute('title',- '收起文件工作区'+ 'Collapse file workspace');});diff --git a/apps/web/src/features/conversation/ConversationHeader.tsx b/apps/web/src/features/conversation/ConversationHeader.tsxindex 9cfcacba..dfca51ba 100644--- a/apps/web/src/features/conversation/ConversationHeader.tsx+++ b/apps/web/src/features/conversation/ConversationHeader.tsx@@ -18,9 +18,9 @@ export function ConversationHeader(props: {<buttonclassName="sidebar-collapse-button conversation-file-button"type="button"- aria-label="文件"+ aria-label="Files"aria-pressed={props.fileWorkspaceOpen === true}- title={props.fileWorkspaceOpen ? '收起文件工作区' : '打开文件工作区'}+ title={props.fileWorkspaceOpen ? 'Collapse file workspace' : 'Open file workspace'}onClick={props.onOpenLocation}><PanelLeftClose aria-hidden="true" size={18} strokeWidth={1.85} />diff --git a/apps/web/src/features/conversation/MemorySuggestion.test.tsx b/apps/web/src/features/conversation/MemorySuggestion.test.tsxindex 9098b75b..285f182d 100644--- a/apps/web/src/features/conversation/MemorySuggestion.test.tsx+++ b/apps/web/src/features/conversation/MemorySuggestion.test.tsx@@ -19,7 +19,7 @@ describe('MemorySuggestion', () => {/>);- await user.click(screen.getByRole('button', { name: '忽略记忆建议' }));+ await user.click(screen.getByRole('button', { name: 'Dismiss memory suggestion' }));expect(onDismiss).toHaveBeenCalledTimes(1);expect(onSave).not.toHaveBeenCalled();});@@ -38,10 +38,10 @@ describe('MemorySuggestion', () => {/>);- await user.clear(screen.getByRole('textbox', { name: '记忆建议内容' }));- await user.type(screen.getByRole('textbox', { name: '记忆建议内容' }), '默认运行全量测试');- await user.selectOptions(screen.getByRole('combobox', { name: '记忆建议范围' }), 'project');- await user.click(screen.getByRole('button', { name: '保存记忆建议' }));+ await user.clear(screen.getByRole('textbox', { name: 'Suggested memory content' }));+ await user.type(screen.getByRole('textbox', { name: 'Suggested memory content' }), '默认运行全量测试');+ await user.selectOptions(screen.getByRole('combobox', { name: 'Suggested memory scope' }), 'project');+ await user.click(screen.getByRole('button', { name: 'Save memory suggestion' }));expect(onSave).toHaveBeenCalledWith({content: '默认运行全量测试',@@ -71,9 +71,9 @@ describe('MemorySuggestion', () => {/>);- await user.click(screen.getByRole('button', { name: '保存记忆建议' }));- expect(await screen.findByText(/可能包含敏感信息/)).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '确认保存敏感建议' }));+ await user.click(screen.getByRole('button', { name: 'Save memory suggestion' }));+ expect(await screen.findByText(/may contain sensitive information/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Confirm saving the sensitive suggestion' }));expect(onSave).toHaveBeenLastCalledWith({content: 'password=secret',diff --git a/apps/web/src/features/conversation/MemorySuggestion.tsx b/apps/web/src/features/conversation/MemorySuggestion.tsxindex 8c0f54e0..4ace17b7 100644--- a/apps/web/src/features/conversation/MemorySuggestion.tsx+++ b/apps/web/src/features/conversation/MemorySuggestion.tsx@@ -27,11 +27,11 @@ export function MemorySuggestion(props: {? props.projectKey: undefined;if (normalized.length === 0) {- setError('记忆内容不能为空');+ setError('Memory content cannot be empty');return;}if (scope !== 'global' && scopeKey === undefined) {- setError('当前范围不可用,请选择其他范围');+ setError('This scope is unavailable. Select another scope.');return;}@@ -54,7 +54,7 @@ export function MemorySuggestion(props: {) {setConfirmingSensitive(true);} else {- pageIssues.captureOperationFailure('memory-suggestion.save', reason, '保存记忆失败,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('memory-suggestion.save', reason, 'Could not save the memory. Try again.', { retryable: true });}} finally {setSaving(false);@@ -62,13 +62,13 @@ export function MemorySuggestion(props: {}return (- <section className="memory-suggestion" aria-label="记忆建议">+ <section className="memory-suggestion" aria-label="Memory suggestion"><div className="memory-suggestion__title"><Brain aria-hidden="true" size={16} />- <strong>保存为长期记忆?</strong>+ <strong>Save as a long-term memory?</strong></div><textarea- aria-label="记忆建议内容"+ aria-label="Suggested memory content"maxLength={2000}value={content}disabled={saving}@@ -76,39 +76,39 @@ export function MemorySuggestion(props: {/><div className="memory-suggestion__actions"><label>- <span>范围</span>+ <span>Scope</span><select- aria-label="记忆建议范围"+ aria-label="Suggested memory scope"value={scope}disabled={saving}onChange={event => setScope(event.target.value as MemoryScope)}>- {props.threadKey !== undefined ? <option value="thread">当前线程</option> : null}- {props.projectKey !== undefined ? <option value="project">当前项目</option> : null}- <option value="global">全局</option>+ {props.threadKey !== undefined ? <option value="thread">Current thread</option> : null}+ {props.projectKey !== undefined ? <option value="project">Current project</option> : null}+ <option value="global">Global</option></select></label>- <button type="button" disabled={saving} aria-label="忽略记忆建议" onClick={props.onDismiss}>+ <button type="button" disabled={saving} aria-label="Dismiss memory suggestion" onClick={props.onDismiss}><X aria-hidden="true" size={15} />- 忽略+ Dismiss</button><buttonclassName="memory-suggestion__save"type="button"disabled={saving}- aria-label="保存记忆建议"+ aria-label="Save memory suggestion"onClick={() => void save()}><Check aria-hidden="true" size={15} />- {saving ? '正在保存' : '保存记忆'}+ {saving ? 'Saving' : 'Save memory'}</button></div>{confirmingSensitive ? (<div className="memory-suggestion__warning" role="alert"><AlertTriangle aria-hidden="true" size={16} />- <span>内容可能包含敏感信息,仅在确认后保存到本机。</span>- <button type="button" onClick={() => void save(true)} aria-label="确认保存敏感建议">- 确认保存+ <span>This content may contain sensitive information. Confirm before saving it locally.</span>+ <button type="button" onClick={() => void save(true)} aria-label="Confirm saving the sensitive suggestion">+ Confirm save</button></div>) : null}diff --git a/apps/web/src/features/conversation/use-thread-history.ts b/apps/web/src/features/conversation/use-thread-history.tsindex 32d8f036..5067998a 100644--- a/apps/web/src/features/conversation/use-thread-history.ts+++ b/apps/web/src/features/conversation/use-thread-history.ts@@ -102,7 +102,7 @@ export function useThreadHistory(input: {const next: ThreadHistoryState = {...emptyState(threadId),loaded: true,- error: '无法加载聊天历史'+ error: 'Could not load chat history'};stateRef.current = next;setState(next);@@ -174,7 +174,7 @@ export function useThreadHistory(input: {const next = {...stateRef.current,loadingOlder: false,- error: '无法加载更早的聊天历史'+ error: 'Could not load earlier chat history'};stateRef.current = next;setState(next);diff --git a/apps/web/src/features/dashboard/AutoClipWorkspace.tsx b/apps/web/src/features/dashboard/AutoClipWorkspace.tsxindex 3435ec11..a177842c 100644--- a/apps/web/src/features/dashboard/AutoClipWorkspace.tsx+++ b/apps/web/src/features/dashboard/AutoClipWorkspace.tsx@@ -877,7 +877,7 @@ function createAutoClipResultVersions(if (candidates.length === 0) return [];return [{value: readPositiveInteger(artifact.metadata.resultVersion) ?? artifact.version,- description: '识别视频高光片段',+ description: 'Identify video highlights',state: {},artifact,sourceArtifact: artifacts.find(candidate => (diff --git a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsxindex a5123165..306009a3 100644--- a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx+++ b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx@@ -1244,7 +1244,7 @@ function createCoverResultVersions(.sort(([left], [right]) => left - right).map(([value, versionArtifacts]) => ({value,- description: '生成封面',+ description: 'Generate cover',artifacts: versionArtifacts.sort(compareCandidates),state: {},artifactRefs: { cover_image: versionArtifacts.map(artifact => artifact.id) }diff --git a/apps/web/src/features/dashboard/CreatorArtifactDetails.tsx b/apps/web/src/features/dashboard/CreatorArtifactDetails.tsxindex 69a3cc4d..3b19770a 100644--- a/apps/web/src/features/dashboard/CreatorArtifactDetails.tsx+++ b/apps/web/src/features/dashboard/CreatorArtifactDetails.tsx@@ -48,7 +48,7 @@ export default function CreatorArtifactDetails() {if (text.length > 200_000) throw new Error('artifact_text_too_large');return text;} catch (cause) {- session.captureCreatorFailure('creator.compare-artifacts', cause, '无法加载产物对比,请稍后重试。', 'client');+ session.captureCreatorFailure('creator.compare-artifacts', cause, 'Could not load the output comparison. Try again later.', 'client');throw cause;}})).then(values => { if (active) setTexts(values); })@@ -90,7 +90,7 @@ export default function CreatorArtifactDetails() {link.click();window.setTimeout(() => URL.revokeObjectURL(url), 0);} catch (cause) {- session.captureCreatorFailure('creator.download-artifact', cause, '无法下载创作产物,请稍后重试。', 'client');+ session.captureCreatorFailure('creator.download-artifact', cause, 'Could not download the output. Try again later.', 'client');throw cause;}} catch (cause) {@@ -180,7 +180,7 @@ function ArtifactMediaPreview({ artifact }: { artifact: CreatorArtifact }) {objectUrl = URL.createObjectURL(blob);setUrl(objectUrl);} catch (cause) {- session.captureCreatorFailure('creator.preview-artifact', cause, '无法预览创作产物,请稍后重试。', 'client');+ session.captureCreatorFailure('creator.preview-artifact', cause, 'Could not preview the output. Try again later.', 'client');throw cause;}}).catch(() => {diff --git a/apps/web/src/features/dashboard/DashboardPage.tsx b/apps/web/src/features/dashboard/DashboardPage.tsxindex 8de6a5fc..1a6f8c7a 100644--- a/apps/web/src/features/dashboard/DashboardPage.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.tsx@@ -768,7 +768,7 @@ function CreatorWorkspaceSession(props: {loadSnapshot: async options => {const next = (await props.service.getJob(jobId, options)).job;if (next.projectId !== props.projectId || next.templateId !== props.templateId) {- throw new ApiClientError({ status: 409, code: 'CREATOR_SESSION_MISMATCH', message: '该创作项目与当前工作目录或模板不匹配' });+ throw new ApiClientError({ status: 409, code: 'CREATOR_SESSION_MISMATCH', message: 'This creation project does not match the current working directory or template' });}return next;},diff --git a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsxindex 0541aacf..67dd5c4a 100644--- a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx+++ b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx@@ -820,7 +820,7 @@ function createImageResultVersions(.sort(([left], [right]) => left - right).map(([value, versionArtifacts]) => ({value,- description: '生成图片',+ description: 'Generate',artifacts: versionArtifacts.sort(compareCandidates),state: {}}));diff --git a/apps/web/src/features/dashboard/ShortVideoScriptWorkspace.tsx b/apps/web/src/features/dashboard/ShortVideoScriptWorkspace.tsxindex 1a61e879..6a68385a 100644--- a/apps/web/src/features/dashboard/ShortVideoScriptWorkspace.tsx+++ b/apps/web/src/features/dashboard/ShortVideoScriptWorkspace.tsx@@ -429,7 +429,7 @@ function readLatestResult(artifacts: CreatorArtifact[]): {return {artifact,fileName: readString(artifact.metadata.fileName) || 'OpenCreator-short-video-script.md',- title: readString(artifact.metadata.title) || '短视频脚本'+ title: readString(artifact.metadata.title) || 'Short video script'};}diff --git a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsxindex d12ca2ac..919fe770 100644--- a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx+++ b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx@@ -2342,7 +2342,7 @@ function useArtifactUrl(artifactId?: string): string {sessionRef.current,artifactId,'stickman.load-artifact-preview',- '创作产物预览加载失败,请稍后重试。'+ 'Could not load the output preview. Try again later.').then(url => {if (canceled) {URL.revokeObjectURL(url);@@ -2500,7 +2500,7 @@ async function openArtifact(session: CreatorSessionContextValue, artifact: Creatsession,artifact.id,'stickman.open-artifact',- '无法打开创作产物,请稍后重试。'+ 'Could not open the output. Try again later.');window.open(url, '_blank', 'noopener,noreferrer');window.setTimeout(() => URL.revokeObjectURL(url), 60_000);@@ -2511,7 +2511,7 @@ async function downloadArtifact(session: CreatorSessionContextValue, artifact: Csession,artifact.id,'stickman.download-artifact',- '创作产物下载失败,请稍后重试。'+ 'Could not download the output. Try again later.');const anchor = document.createElement('a');anchor.href = url;diff --git a/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx b/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsxindex 0cd0775f..89a116b2 100644--- a/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx@@ -1020,7 +1020,7 @@ function createVideoResultVersions()).map(artifact => ({value: readPositiveInteger(artifact.metadata.resultVersion) ?? artifact.version,- description: '生成视频',+ description: 'Generate',artifact,state: {}}))diff --git a/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx b/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsxindex 21999595..b133c178 100644--- a/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx@@ -83,19 +83,19 @@ describe('WechatArticleWorkspace', () => {fireEvent.click(within(layoutCategories).getByRole('button', { name: '资讯' }));expect(container.querySelectorAll('.wechat-layout-list button')).toHaveLength(1);- expect(screen.getByRole('button', { name: /^热点简报/ })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^News Brief/ })).toBeInTheDocument();fireEvent.click(within(layoutCategories).getByRole('button', { name: '科技' }));expect(container.querySelectorAll('.wechat-layout-list button')).toHaveLength(3);- const podcastLayout = screen.getByRole('button', { name: /^播客访谈/ });- expect(within(podcastLayout).getByText('嘉宾发言')).toBeInTheDocument();+ const podcastLayout = screen.getByRole('button', { name: /^Podcast Interview/ });+ expect(within(podcastLayout).getByText('Guest remarks')).toBeInTheDocument();fireEvent.click(podcastLayout);expect(container.querySelector('.wechat-article-preview')).toHaveAttribute('data-layout', 'podcast');fireEvent.click(within(layoutCategories).getByRole('button', { name: '商业' }));- const businessLayout = screen.getByRole('button', { name: /^商业报告/ });- expect(within(businessLayout).getByText('内容摘要')).toBeInTheDocument();+ const businessLayout = screen.getByRole('button', { name: /^Business Report/ });+ expect(within(businessLayout).getByText('Executive summary')).toBeInTheDocument();fireEvent.click(businessLayout);expect(businessLayout).toHaveAttribute('data-selected', 'true');diff --git a/apps/web/src/features/dashboard/XiaohongshuPostWorkspace.tsx b/apps/web/src/features/dashboard/XiaohongshuPostWorkspace.tsxindex ec159216..f1a36d5f 100644--- a/apps/web/src/features/dashboard/XiaohongshuPostWorkspace.tsx+++ b/apps/web/src/features/dashboard/XiaohongshuPostWorkspace.tsx@@ -426,7 +426,7 @@ function readLatestResult(artifacts: CreatorArtifact[]): {return {artifact,fileName: readString(artifact.metadata.fileName) || 'OpenCreator-xiaohongshu-post.md',- title: readString(artifact.metadata.title) || '小红书帖子'+ title: readString(artifact.metadata.title) || 'Xiaohongshu post'};}diff --git a/apps/web/src/features/dashboard/creator-session-store.tsx b/apps/web/src/features/dashboard/creator-session-store.tsxindex ff3d3f5d..7dfe4c2d 100644--- a/apps/web/src/features/dashboard/creator-session-store.tsx+++ b/apps/web/src/features/dashboard/creator-session-store.tsx@@ -394,7 +394,7 @@ export function CreatorSessionProvider(props: {const captureCreatorFailure = useCallback((operation: string,cause: unknown,- fallbackMessage = '操作未完成,请在 Agent 区域查看诊断。',+ fallbackMessage = 'The operation did not complete. Check diagnostics in the Agent panel.',source: 'upload' | 'preflight' | 'agent' | 'client' = 'client'): OpenCreatorIssue => {const causeObject = typeof cause === 'object' && cause !== null ? cause : undefined;@@ -462,7 +462,7 @@ export function CreatorSessionProvider(props: {const runPreflight = useCallback(async (stageId: string, options?: { inputResultVersion?: number }) => {if (props.service.preflight === undefined) {const cause = new Error('Creator preflight is unavailable');- captureCreatorFailure('creator.preflight', cause, '启动条件检查暂不可用,请稍后重试。', 'preflight');+ captureCreatorFailure('creator.preflight', cause, 'Preflight checks are unavailable. Try again later.', 'preflight');throw cause;}await flush();@@ -475,7 +475,7 @@ export function CreatorSessionProvider(props: {if (!result.canStart) throw new CreatorPreflightBlockedError(result);return result;} catch (cause) {- captureCreatorFailure('creator.preflight', cause, '启动条件检查未通过,请查看诊断并修正后重试。', 'preflight');+ captureCreatorFailure('creator.preflight', cause, 'Preflight checks failed. Review diagnostics and fix the issue before retrying.', 'preflight');throw cause;}}, [captureCreatorFailure, ensurePersistedJob, flush, props.service]);@@ -665,7 +665,7 @@ export function CreatorSessionProvider(props: {const uploadSourceVideo = useCallback(async (file: File) => {if (props.service.uploadSourceVideo === undefined) {const cause = new Error('Creator source upload transport is unavailable');- captureCreatorFailure('creator.upload-source-video', cause, '源视频上传暂不可用,请稍后重试。', 'upload');+ captureCreatorFailure('creator.upload-source-video', cause, 'Source video upload is unavailable. Try again later.', 'upload');throw cause;}let requestRevision = confirmedRef.current.revision;@@ -683,7 +683,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.upload-source-video', cause, '源视频上传未完成,请检查文件后重试。', 'upload');+ captureCreatorFailure('creator.upload-source-video', cause, 'Source video upload did not complete. Check the file and try again.', 'upload');}throw cause;}@@ -692,7 +692,7 @@ export function CreatorSessionProvider(props: {const uploadReferenceImage = useCallback(async (file: File) => {if (props.service.uploadReferenceImage === undefined) {const cause = new Error('Creator reference upload transport is unavailable');- captureCreatorFailure('creator.upload-reference-image', cause, '参考图上传暂不可用,请稍后重试。', 'upload');+ captureCreatorFailure('creator.upload-reference-image', cause, 'Reference image upload is unavailable. Try again later.', 'upload');throw cause;}let requestRevision = confirmedRef.current.revision;@@ -710,7 +710,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.upload-reference-image', cause, '参考图上传未完成,请检查文件后重试。', 'upload');+ captureCreatorFailure('creator.upload-reference-image', cause, 'Reference image upload did not complete. Check the file and try again.', 'upload');}throw cause;}@@ -719,7 +719,7 @@ export function CreatorSessionProvider(props: {const uploadArticleImage = useCallback(async (file: File): Promise<CreatorArtifact> => {if (props.service.uploadArticleImage === undefined) {const cause = new Error('Creator article image upload transport is unavailable');- captureCreatorFailure('creator.upload-article-image', cause, '文章图片上传暂不可用,请稍后重试。', 'upload');+ captureCreatorFailure('creator.upload-article-image', cause, 'Article image upload is unavailable. Try again later.', 'upload');throw cause;}let requestRevision = confirmedRef.current.revision;@@ -738,7 +738,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.upload-article-image', cause, '文章图片上传未完成,请检查文件后重试。', 'upload');+ captureCreatorFailure('creator.upload-article-image', cause, 'Article image upload did not complete. Check the file and try again.', 'upload');}throw cause;}@@ -747,7 +747,7 @@ export function CreatorSessionProvider(props: {const uploadSourceDocument = useCallback(async (file: File) => {if (props.service.uploadSourceDocument === undefined) {const cause = new Error('Creator document upload transport is unavailable');- captureCreatorFailure('creator.upload-source-document', cause, '源文档上传暂不可用,请稍后重试。', 'upload');+ captureCreatorFailure('creator.upload-source-document', cause, 'Source document upload is unavailable. Try again later.', 'upload');throw cause;}let requestRevision = confirmedRef.current.revision;@@ -765,7 +765,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.upload-source-document', cause, '源文档上传未完成,请检查文件后重试。', 'upload');+ captureCreatorFailure('creator.upload-source-document', cause, 'Source document upload did not complete. Check the file and try again.', 'upload');}throw cause;}@@ -817,13 +817,13 @@ export function CreatorSessionProvider(props: {const openArtifact = useCallback(async (artifactId: string) => {if (props.service.openArtifact === undefined) {const cause = new Error('Creator artifact transport is unavailable');- captureCreatorFailure('creator.open-artifact', cause, '无法打开创作产物,请稍后重试。');+ captureCreatorFailure('creator.open-artifact', cause, 'Could not open the output. Try again later.');throw cause;}try {return await props.service.openArtifact(confirmedRef.current.id, artifactId);} catch (cause) {- captureCreatorFailure('creator.open-artifact', cause, '无法打开创作产物,请稍后重试。');+ captureCreatorFailure('creator.open-artifact', cause, 'Could not open the output. Try again later.');throw cause;}}, [captureCreatorFailure, props.service]);@@ -840,7 +840,7 @@ export function CreatorSessionProvider(props: {return captureCreatorClientFailure({ captureCreatorFailure },'creator.read-artifact-json',- '无法读取创作产物内容,请稍后重试。',+ 'Could not read the output content. Try again later.',async () => {if (!response.ok) throw new Error(`Creator artifact request failed: ${response.status}`);return response.json() as Promise<T>;@@ -892,7 +892,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.agent-turn', cause, 'Agent 未能完成诊断,请查看问题详情后重试。', 'agent');+ captureCreatorFailure('creator.agent-turn', cause, 'The Agent could not complete the diagnosis. Review the issue details and retry.', 'agent');}throw cause;} finally {@@ -918,7 +918,7 @@ export function CreatorSessionProvider(props: {} catch (cause) {if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {setError(toSessionError(cause));- captureCreatorFailure('creator.agent-steer', cause, 'Agent 未能接收补充要求。', 'agent');+ captureCreatorFailure('creator.agent-steer', cause, 'The Agent could not receive the additional instructions.', 'agent');}throw cause;} finally {@@ -933,7 +933,7 @@ export function CreatorSessionProvider(props: {setError(null);} catch (cause) {setError(toSessionError(cause));- captureCreatorFailure('creator.agent-interrupt', cause, 'Agent 对话未能停止。', 'agent');+ captureCreatorFailure('creator.agent-interrupt', cause, 'The Agent conversation could not be stopped.', 'agent');throw cause;} finally {await reloadAgentTimeline().catch(() => undefined);@@ -955,7 +955,7 @@ export function CreatorSessionProvider(props: {setError(null);} catch (cause) {setError(toSessionError(cause));- captureCreatorFailure('creator.agent-approval', cause, 'Agent 审批操作未完成。', 'agent');+ captureCreatorFailure('creator.agent-approval', cause, 'The Agent approval operation did not complete.', 'agent');throw cause;} finally {await reloadAgentTimeline().catch(() => undefined);diff --git a/apps/web/src/features/details/DetailPanel.test.tsx b/apps/web/src/features/details/DetailPanel.test.tsxindex 32e72e80..0e32b005 100644--- a/apps/web/src/features/details/DetailPanel.test.tsx+++ b/apps/web/src/features/details/DetailPanel.test.tsx@@ -17,7 +17,7 @@ describe('DetailPanel', () => {expect(screen.getByRole('heading', { name: 'notes.txt' })).toBeInTheDocument();expect(screen.getByText('apps/web/notes.txt')).toBeInTheDocument();- expect(screen.getByRole('region', { name: '详情内容' }).querySelector('pre')?.textContent).toBe(+ expect(screen.getByRole('region', { name: 'Detail content' }).querySelector('pre')?.textContent).toBe('# OpenCreator\n\nDetail content');});@@ -65,7 +65,7 @@ describe('DetailPanel', () => {render(<DetailPanel mode="file" title="README.md" content="content" onClose={onClose} />);- await user.click(screen.getByRole('button', { name: '关闭详情' }));+ await user.click(screen.getByRole('button', { name: 'Close details' }));expect(onClose).toHaveBeenCalledTimes(1);});@@ -86,8 +86,8 @@ describe('DetailPanel', () => {/>);- await user.click(screen.getByRole('button', { name: '撤销' }));- await user.click(screen.getByRole('button', { name: '审核' }));+ await user.click(screen.getByRole('button', { name: 'Undo' }));+ await user.click(screen.getByRole('button', { name: 'Review' }));expect(onRevert).toHaveBeenCalledTimes(1);expect(onApprove).toHaveBeenCalledTimes(1);@@ -96,15 +96,15 @@ describe('DetailPanel', () => {it('disables change actions when callbacks are missing', () => {render(<DetailPanel mode="change" title="变更详情" content="diff content" onClose={vi.fn()} />);- expect(screen.getByRole('button', { name: '撤销' })).toBeDisabled();- expect(screen.getByRole('button', { name: '审核' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Undo' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Review' })).toBeDisabled();});it('shows run content without change actions', () => {render(<DetailPanel mode="run" title="运行详情" content="run completed" onClose={vi.fn()} />);expect(screen.getByText('run completed')).toBeInTheDocument();- expect(screen.queryByRole('button', { name: '撤销' })).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Undo' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Review' })).not.toBeInTheDocument();});});diff --git a/apps/web/src/features/details/DetailPanel.tsx b/apps/web/src/features/details/DetailPanel.tsxindex 3e81a0d6..5c0a7a04 100644--- a/apps/web/src/features/details/DetailPanel.tsx+++ b/apps/web/src/features/details/DetailPanel.tsx@@ -62,12 +62,12 @@ export function DetailPanel(props: DetailPanelProps) {<h2 id="detail-panel-title">{props.title}</h2>{props.subtitle ? <span>{props.subtitle}</span> : null}</div>- <button className="icon-button" type="button" aria-label="关闭详情" onClick={props.onClose}>+ <button className="icon-button" type="button" aria-label="Close details" onClick={props.onClose}><X aria-hidden="true" size={16} /></button></header>- <div className="detail-content" role="region" aria-label="详情内容">+ <div className="detail-content" role="region" aria-label="Detail content"><DetailContent mode={props.mode} title={props.title} subtitle={props.subtitle} content={props.content} /></div>@@ -75,11 +75,11 @@ export function DetailPanel(props: DetailPanelProps) {<footer className="detail-actions"><button className="toolbar-button" type="button" onClick={props.onRevert} disabled={!props.onRevert}><RotateCcw aria-hidden="true" size={16} />- <span>撤销</span>+ <span>Undo</span></button><button className="toolbar-button primary" type="button" onClick={props.onApprove} disabled={!props.onApprove}><Check aria-hidden="true" size={16} />- <span>审核</span>+ <span>Review</span></button></footer>) : null}diff --git a/apps/web/src/features/files/FileEditorPane.test.tsx b/apps/web/src/features/files/FileEditorPane.test.tsxindex 67926136..dcd332ac 100644--- a/apps/web/src/features/files/FileEditorPane.test.tsx+++ b/apps/web/src/features/files/FileEditorPane.test.tsx@@ -18,7 +18,7 @@ describe('FileEditorPane', () => {it('meta 为空时显示空态', () => {render(<FileEditorPane />);- expect(screen.getByText('选择一个文件')).toBeInTheDocument();+ expect(screen.getByText('Select a file')).toBeInTheDocument();});it('markdown 默认源码编辑,可切换到预览', async () => {@@ -31,11 +31,11 @@ describe('FileEditorPane', () => {/>);- expect(screen.getByRole('button', { name: '编辑' })).toHaveAttribute('aria-pressed', 'true');- expect(screen.getByRole('textbox', { name: 'README.md 编辑器' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Edit' })).toHaveAttribute('aria-pressed', 'true');+ expect(screen.getByRole('textbox', { name: 'README.md editor' })).toBeInTheDocument();expect(screen.queryByRole('heading', { name: '标题' })).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '预览' }));+ await user.click(screen.getByRole('button', { name: 'Preview' }));expect(screen.getByRole('heading', { name: '标题' })).toBeInTheDocument();expect(screen.getByText('正文')).toBeInTheDocument();@@ -56,9 +56,9 @@ describe('FileEditorPane', () => {/>);- const preview = await screen.findByTitle('business-cover.html HTML 预览');- expect(screen.getByRole('button', { name: '预览' })).toHaveAttribute('aria-pressed', 'true');- expect(screen.queryByRole('textbox', { name: 'business-cover.html 编辑器' })).not.toBeInTheDocument();+ const preview = await screen.findByTitle('business-cover.html HTML preview');+ expect(screen.getByRole('button', { name: 'Preview' })).toHaveAttribute('aria-pressed', 'true');+ expect(screen.queryByRole('textbox', { name: 'business-cover.html editor' })).not.toBeInTheDocument();expect(preview).toHaveAttribute('sandbox', 'allow-scripts');expect(preview).toHaveAttribute('referrerpolicy', 'no-referrer');expect(preview.getAttribute('srcdoc')).not.toContain('document.body.dataset.ready');@@ -75,7 +75,7 @@ describe('FileEditorPane', () => {/>);- await user.click(screen.getByRole('button', { name: '预览' }));+ await user.click(screen.getByRole('button', { name: 'Preview' }));expect(document.querySelector('.file-preview pre')?.textContent).toBe('{\n "name": "opencreator",\n "version": 1\n}');@@ -86,9 +86,9 @@ describe('FileEditorPane', () => {/>);- await user.click(screen.getByRole('button', { name: '预览' }));+ await user.click(screen.getByRole('button', { name: 'Preview' }));- expect(screen.getByText('JSON 解析失败,以下保留原始内容。')).toBeInTheDocument();+ expect(screen.getByText('Could not parse JSON. The original content is shown below.')).toBeInTheDocument();expect(screen.getByText('{"name": }')).toBeInTheDocument();});@@ -102,8 +102,8 @@ describe('FileEditorPane', () => {/>);- expect(screen.getByRole('textbox', { name: 'notes.txt 编辑器' })).toHaveAttribute('aria-readonly', 'true');- expect(screen.getByRole('button', { name: '保存' })).toBeDisabled();+ expect(screen.getByRole('textbox', { name: 'notes.txt editor' })).toHaveAttribute('aria-readonly', 'true');+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();});it('dirty 时保存按钮可用,点击触发 onSave', async () => {@@ -119,7 +119,7 @@ describe('FileEditorPane', () => {/>);- const saveButton = screen.getByRole('button', { name: '保存' });+ const saveButton = screen.getByRole('button', { name: 'Save' });expect(saveButton).toBeEnabled();await user.click(saveButton);@@ -139,7 +139,7 @@ describe('FileEditorPane', () => {/>);- const editor = screen.getByRole('textbox', { name: 'notes.txt 编辑器' });+ const editor = screen.getByRole('textbox', { name: 'notes.txt editor' });await user.click(editor);await user.keyboard('A');@@ -188,7 +188,7 @@ describe('FileEditorPane', () => {/>);- const objectNode = screen.getByTitle('spec.pdf PDF 预览');+ const objectNode = screen.getByTitle('spec.pdf PDF preview');expect(objectNode).toHaveAttribute('data', 'blob:preview-pdf');expect(objectNode).toHaveAttribute('type', 'application/pdf');});@@ -209,7 +209,7 @@ describe('FileEditorPane', () => {/>);- const panel = screen.getByText('暂不支持预览此文件').closest('.unsupported-file-state');+ const panel = screen.getByText('Preview is not supported for this file').closest('.unsupported-file-state');expect(panel).not.toBeNull();expect(within(panel as HTMLElement).getByText('archive.bin')).toBeInTheDocument();expect(within(panel as HTMLElement).getByText('application/octet-stream')).toBeInTheDocument();@@ -229,7 +229,7 @@ describe('FileEditorPane', () => {/>);- fireEvent.keyDown(screen.getByRole('textbox', { name: 'notes.txt 编辑器' }), {+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'notes.txt editor' }), {key: 's',code: 'KeyS',ctrlKey: true@@ -250,7 +250,7 @@ describe('FileEditorPane', () => {/>);- fireEvent.keyDown(screen.getByRole('textbox', { name: 'notes.txt 编辑器' }), {+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'notes.txt editor' }), {key: 's',code: 'KeyS',ctrlKey: true@@ -278,11 +278,11 @@ describe('FileEditorPane', () => {/>);- expect(screen.getByRole('button', { name: '编辑' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: '预览' })).toBeInTheDocument();- expect(screen.getByRole('textbox', { name: 'logo.svg 编辑器' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Preview' })).toBeInTheDocument();+ expect(screen.getByRole('textbox', { name: 'logo.svg editor' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '预览' }));+ await user.click(screen.getByRole('button', { name: 'Preview' }));expect(screen.queryByRole('img', { name: 'logo.svg' })).not.toBeInTheDocument();expect(document.querySelector('.file-preview pre')?.textContent).toBe(svgSource);diff --git a/apps/web/src/features/files/FileEditorPane.tsx b/apps/web/src/features/files/FileEditorPane.tsxindex 1972a54d..1216b23c 100644--- a/apps/web/src/features/files/FileEditorPane.tsx+++ b/apps/web/src/features/files/FileEditorPane.tsx@@ -47,9 +47,9 @@ export function FileEditorPane(props: FileEditorPaneProps) {if (!meta) {return (- <section className="file-editor-pane" data-toolbar={toolbar} aria-label="文件编辑区">+ <section className="file-editor-pane" data-toolbar={toolbar} aria-label="File editor"><div className="file-preview file-preview-empty">- <p>选择一个文件</p>+ <p>Select a file</p></div></section>);@@ -66,7 +66,7 @@ export function FileEditorPane(props: FileEditorPaneProps) {};return (- <section className="file-editor-pane" data-toolbar={toolbar} aria-label="文件编辑区">+ <section className="file-editor-pane" data-toolbar={toolbar} aria-label="File editor">{toolbar === 'inline' ? (<header className="file-editor-toolbar"><div className="file-editor-toolbar-main">@@ -74,25 +74,25 @@ export function FileEditorPane(props: FileEditorPaneProps) {<strong>{meta.name}</strong><span>{meta.path}</span></div>- {props.dirty ? <span className="dirty-indicator">未保存</span> : null}+ {props.dirty ? <span className="dirty-indicator">Unsaved</span> : null}</div><div className="file-editor-toolbar-actions">{editable && previewable ? (- <div className="file-editor-mode-toggle" aria-label="文件视图模式">+ <div className="file-editor-mode-toggle" aria-label="File view mode"><buttontype="button"aria-pressed={currentMode === 'preview'}onClick={() => setMode('preview')}>- 预览+ Preview</button><buttontype="button"aria-pressed={currentMode === 'edit'}onClick={() => setMode('edit')}>- 编辑+ Edit</button></div>) : null}@@ -104,14 +104,14 @@ export function FileEditorPane(props: FileEditorPaneProps) {disabled={props.saving || !props.dirty || meta.readonly}onClick={() => props.onSave?.()}>- 保存+ Save</button>) : null}</div></header>) : null}- {props.loading ? <div className="file-loading-bar" role="status">正在加载文件...</div> : null}+ {props.loading ? <div className="file-loading-bar" role="status">Loading file...</div> : null}{renderContent({meta,@@ -146,7 +146,7 @@ function renderContent(args: RenderContentArgs) {if (isImagePreview(args.meta)) {return (<div className="file-preview file-preview-media">- {args.objectUrl ? <img src={args.objectUrl} alt={args.meta.name} /> : <p>图片预览不可用</p>}+ {args.objectUrl ? <img src={args.objectUrl} alt={args.meta.name} /> : <p>Image preview unavailable</p>}</div>);}@@ -155,9 +155,9 @@ function renderContent(args: RenderContentArgs) {return (<div className="file-preview file-preview-media">{args.objectUrl ? (- <object data={args.objectUrl} type="application/pdf" title={`${args.meta.name} PDF 预览`} aria-label={`${args.meta.name} PDF 预览`} />+ <object data={args.objectUrl} type="application/pdf" title={`${args.meta.name} PDF preview`} aria-label={`${args.meta.name} PDF preview`} />) : (- <p>PDF 预览不可用</p>+ <p>PDF preview unavailable</p>)}</div>);@@ -248,7 +248,7 @@ function JsonPreview(props: { content: string }) {return (<div className="file-preview">- {parsed.ok ? null : <p className="file-preview-note">JSON 解析失败,以下保留原始内容。</p>}+ {parsed.ok ? null : <p className="file-preview-note">Could not parse JSON. The original content is shown below.</p>}<pre>{parsed.text}</pre></div>);@@ -261,11 +261,11 @@ function renderUnsupported(meta: WorkspaceFileMeta) {{unsupportedIcon(meta)}</div><div className="unsupported-file-state-copy">- <strong>暂不支持预览此文件</strong>+ <strong>Preview is not supported for this file</strong><span>{meta.name}</span><span>{meta.mime}</span><span>{formatSize(meta.size)}</span>- <p>{meta.reason ?? '该文件当前既不可编辑,也没有可用预览。'}</p>+ <p>{meta.reason ?? 'This file cannot be edited and has no available preview.'}</p></div></div>);diff --git a/apps/web/src/features/files/FilePathBar.tsx b/apps/web/src/features/files/FilePathBar.tsxindex 197f255d..2e2e9c98 100644--- a/apps/web/src/features/files/FilePathBar.tsx+++ b/apps/web/src/features/files/FilePathBar.tsx@@ -10,7 +10,7 @@ export function FilePathBar(props: FilePathBarProps) {return (<div className="file-path-bar">- <nav className="file-path-breadcrumbs" aria-label="文件路径">+ <nav className="file-path-breadcrumbs" aria-label="File path"><span>{props.rootName}</span>{segments.map((segment) => (<span key={`${props.path ?? ''}:${segment}`}>{segment}</span>@@ -19,10 +19,10 @@ export function FilePathBar(props: FilePathBarProps) {<div className="file-path-actions"><button className="toolbar-button" type="button" onClick={props.onRevealDirectory} disabled={!props.path}>- 打开所在目录+ Open containing folder</button><button className="toolbar-button" type="button" onClick={props.onCopyPath} disabled={!props.path}>- 复制路径+ Copy path</button></div></div>diff --git a/apps/web/src/features/files/FileTopBar.tsx b/apps/web/src/features/files/FileTopBar.tsxindex e8ba2633..a17b231c 100644--- a/apps/web/src/features/files/FileTopBar.tsx+++ b/apps/web/src/features/files/FileTopBar.tsx@@ -19,7 +19,7 @@ type FileTopBarProps = {};export function FileTopBar(props: FileTopBarProps) {- const title = props.fileName ?? '文件工作区';+ const title = props.fileName ?? 'File workspace';const segments = props.path?.split('/').filter(Boolean) ?? [];return (@@ -27,13 +27,13 @@ export function FileTopBar(props: FileTopBarProps) {<div className="file-top-bar-title-row"><div className="file-top-bar-title"><strong>{title}</strong>- {props.dirty ? <span className="dirty-indicator" aria-label="未保存">未保存</span> : null}+ {props.dirty ? <span className="dirty-indicator" aria-label="Unsaved">Unsaved</span> : null}</div><buttonclassName="icon-button file-toolbar-icon-button"type="button"- aria-label="关闭文件工作区"- title="关闭文件工作区"+ aria-label="Close file workspace"+ title="Close file workspace"onClick={props.onClose}><X aria-hidden="true" size={16} />@@ -42,8 +42,8 @@ export function FileTopBar(props: FileTopBarProps) {<div className="file-top-bar-control-row"><div className="file-top-bar-path-group">- <nav className="file-top-bar-path" aria-label="文件路径">- <span>{props.rootName ?? '工作区'}</span>+ <nav className="file-top-bar-path" aria-label="File path">+ <span>{props.rootName ?? 'Workspace'}</span>{segments.flatMap((segment, index) => [<span className="file-top-bar-path-separator" key={`${props.path ?? ''}:separator:${index}`}>/</span>,<span key={`${props.path ?? ''}:${index}`}>{segment}</span>@@ -53,8 +53,8 @@ export function FileTopBar(props: FileTopBarProps) {<buttonclassName="icon-button file-top-bar-path-open-button"type="button"- aria-label="打开文件"- title="打开文件"+ aria-label="Open file"+ title="Open file"disabled={!props.path}onClick={props.onOpenFile}>@@ -65,20 +65,20 @@ export function FileTopBar(props: FileTopBarProps) {<div className="file-top-bar-actions">{props.canToggleMode && props.mode && props.onModeChange ? (- <div className="file-editor-mode-toggle" aria-label="文件视图模式">+ <div className="file-editor-mode-toggle" aria-label="File view mode"><buttontype="button"aria-pressed={props.mode === 'preview'}onClick={() => props.onModeChange?.('preview')}>- 预览+ Preview</button><buttontype="button"aria-pressed={props.mode === 'edit'}onClick={() => props.onModeChange?.('edit')}>- 编辑+ Edit</button></div>) : null}@@ -89,16 +89,16 @@ export function FileTopBar(props: FileTopBarProps) {disabled={props.saveDisabled}onClick={() => props.onSave?.()}>- 保存+ Save</button>) : null}{props.onToggleTree ? (<buttonclassName="icon-button file-toolbar-icon-button"type="button"- aria-label={props.treeCollapsed ? '展开目录树' : '收起目录树'}+ aria-label={props.treeCollapsed ? 'Expand file tree' : 'Collapse file tree'}aria-pressed={props.treeCollapsed}- title={props.treeCollapsed ? '展开目录树' : '收起目录树'}+ title={props.treeCollapsed ? 'Expand file tree' : 'Collapse file tree'}onClick={props.onToggleTree}>{props.treeCollapsed ? (diff --git a/apps/web/src/features/files/FileWorkspaceView.test.tsx b/apps/web/src/features/files/FileWorkspaceView.test.tsxindex 1e504963..cae2c2a7 100644--- a/apps/web/src/features/files/FileWorkspaceView.test.tsx+++ b/apps/web/src/features/files/FileWorkspaceView.test.tsx@@ -43,7 +43,7 @@ describe('FileWorkspaceView', () => {);const agent = await screen.findByRole('complementary', { name: 'Agent 诊断' });- expect(agent).toHaveTextContent('无法打开文件,请重试。');+ expect(agent).toHaveTextContent('Could not open the file. Try again.');expect(agent).not.toHaveTextContent('private filesystem detail');expect(screen.queryByRole('alert')).not.toBeInTheDocument();});@@ -51,7 +51,7 @@ describe('FileWorkspaceView', () => {it('没有 selected thread 时显示空态', () => {render(<FileWorkspaceView workspaceFileService={createService()} onClose={vi.fn()} />);- expect(screen.getByText('请选择或创建一个会话后查看文件')).toBeInTheDocument();+ expect(screen.getByText('Select or create a conversation to view files')).toBeInTheDocument();});it('切换线程后上报根目录是否包含内容', async () => {@@ -104,8 +104,8 @@ describe('FileWorkspaceView', () => {await waitFor(() => expect(service.getMeta).toHaveBeenCalledWith(thread.id, 'README.md'));await waitFor(() => expect(service.openText).toHaveBeenCalledWith(thread.id, 'README.md'));expect(await screen.findAllByText('README.md')).not.toHaveLength(0);- expect(screen.getByRole('button', { name: '预览' })).toHaveAttribute('aria-pressed', 'true');- expect(screen.queryByRole('textbox', { name: 'README.md 编辑器' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Preview' })).toHaveAttribute('aria-pressed', 'true');+ expect(screen.queryByRole('textbox', { name: 'README.md editor' })).not.toBeInTheDocument();expect(window.localStorage.getItem(`opencreator.file-workspace.recent.${workspaceKey(thread.canonicalCwd)}`)).toBe('README.md');});@@ -186,7 +186,7 @@ describe('FileWorkspaceView', () => {]}));- expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML 预览')).toBeInTheDocument();+ expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML preview')).toBeInTheDocument();expect(service.getMeta).not.toHaveBeenCalledWith(thread.id, 'README.md');});@@ -220,7 +220,7 @@ describe('FileWorkspaceView', () => {/>);- expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML 预览')).toBeInTheDocument();+ expect(await screen.findByTitle('xiaodoujia-apple-aso-audit.html HTML preview')).toBeInTheDocument();expect(service.getMeta).toHaveBeenCalledWith(thread.id, 'xiaodoujia-apple-aso-audit.html');expect(service.getMeta).not.toHaveBeenCalledWith(thread.id,@@ -282,7 +282,7 @@ describe('FileWorkspaceView', () => {await user.click(await screen.findByRole('treeitem', { name: 'docs' }));const agent = await screen.findByRole('complementary', { name: 'Agent 诊断' });- expect(agent).toHaveTextContent('无法加载目录,请重试。');+ expect(agent).toHaveTextContent('Could not load the directory. Try again.');await user.click(within(agent).getByRole('button', { name: '重试' }));expect(await screen.findByRole('treeitem', { name: 'guide.md' })).toBeInTheDocument();@@ -470,7 +470,7 @@ describe('FileWorkspaceView', () => {);await screen.findAllByText('README.md');- await userEvent.setup().click(screen.getByRole('button', { name: '展开目录树' }));+ await userEvent.setup().click(screen.getByRole('button', { name: 'Expand file tree' }));const body = container.querySelector('.file-workspace-body');if (!(body instanceof HTMLElement)) throw new Error('Expected file workspace body');@@ -518,36 +518,36 @@ describe('FileWorkspaceView', () => {const title = toolbar.querySelector('.file-top-bar-title');if (!(title instanceof HTMLElement)) throw new Error('Expected file toolbar title');expect(within(title).getByText('notes.md')).toBeInTheDocument();- expect(within(titleRow).getByRole('button', { name: '关闭文件工作区' })).toBeEnabled();+ expect(within(titleRow).getByRole('button', { name: 'Close file workspace' })).toBeEnabled();const controlRow = toolbar.querySelector('.file-top-bar-control-row');if (!(controlRow instanceof HTMLElement)) throw new Error('Expected file toolbar control row');- const pathNav = within(toolbar).getByLabelText('文件路径');+ const pathNav = within(toolbar).getByLabelText('File path');expect(pathNav).toHaveTextContent('repo/scripts/notes.md');- expect(within(pathNav).queryByRole('button', { name: '复制路径' })).not.toBeInTheDocument();+ expect(within(pathNav).queryByRole('button', { name: 'Copy path' })).not.toBeInTheDocument();const pathGroup = toolbar.querySelector('.file-top-bar-path-group');if (!(pathGroup instanceof HTMLElement)) throw new Error('Expected file toolbar path group');- expect(within(pathGroup).getByRole('button', { name: '打开文件' })).toBeEnabled();- expect(within(controlRow).getByRole('button', { name: '预览' })).toHaveAttribute('aria-pressed', 'true');- expect(within(controlRow).getByRole('button', { name: '编辑' })).toHaveAttribute('aria-pressed', 'false');- expect(within(controlRow).getByRole('button', { name: '保存' })).toBeDisabled();- expect(within(controlRow).getByRole('button', { name: '展开目录树' })).toBeEnabled();+ expect(within(pathGroup).getByRole('button', { name: 'Open file' })).toBeEnabled();+ expect(within(controlRow).getByRole('button', { name: 'Preview' })).toHaveAttribute('aria-pressed', 'true');+ expect(within(controlRow).getByRole('button', { name: 'Edit' })).toHaveAttribute('aria-pressed', 'false');+ expect(within(controlRow).getByRole('button', { name: 'Save' })).toBeDisabled();+ expect(within(controlRow).getByRole('button', { name: 'Expand file tree' })).toBeEnabled();const actions = toolbar.querySelector('.file-top-bar-actions');if (!(actions instanceof HTMLElement)) throw new Error('Expected file toolbar actions');- expect(within(actions).queryByRole('button', { name: '复制路径' })).not.toBeInTheDocument();- expect(within(actions).queryByRole('button', { name: '打开文件' })).not.toBeInTheDocument();- expect(within(actions).queryByRole('button', { name: '关闭文件工作区' })).not.toBeInTheDocument();+ expect(within(actions).queryByRole('button', { name: 'Copy path' })).not.toBeInTheDocument();+ expect(within(actions).queryByRole('button', { name: 'Open file' })).not.toBeInTheDocument();+ expect(within(actions).queryByRole('button', { name: 'Close file workspace' })).not.toBeInTheDocument();const modeButtons = within(toolbar).getAllByRole('button')- .filter(button => button.textContent === '预览' || button.textContent === '编辑');- expect(modeButtons.map(button => button.textContent)).toEqual(['预览', '编辑']);+ .filter(button => button.textContent === 'Preview' || button.textContent === 'Edit');+ expect(modeButtons.map(button => button.textContent)).toEqual(['Preview', 'Edit']);- await user.click(within(toolbar).getByRole('button', { name: '编辑' }));+ await user.click(within(toolbar).getByRole('button', { name: 'Edit' }));- expect(within(toolbar).getByRole('button', { name: '编辑' })).toHaveAttribute('aria-pressed', 'true');- expect(within(toolbar).getByRole('button', { name: '预览' })).toHaveAttribute('aria-pressed', 'false');- expect(screen.getByRole('textbox', { name: 'scripts/notes.md 编辑器' })).toBeInTheDocument();+ expect(within(toolbar).getByRole('button', { name: 'Edit' })).toHaveAttribute('aria-pressed', 'true');+ expect(within(toolbar).getByRole('button', { name: 'Preview' })).toHaveAttribute('aria-pressed', 'false');+ expect(screen.getByRole('textbox', { name: 'scripts/notes.md editor' })).toBeInTheDocument();expect(container.querySelector('.file-path-bar')).not.toBeInTheDocument();expect(container.querySelector('.file-editor-toolbar')).not.toBeInTheDocument();@@ -579,10 +579,10 @@ describe('FileWorkspaceView', () => {render(<FileWorkspaceView selectedThread={thread} workspaceFileService={service} onClose={vi.fn()} />);- const preview = await screen.findByTitle('business-cover.html HTML 预览');- expect(screen.getByRole('button', { name: '预览' })).toHaveAttribute('aria-pressed', 'true');+ const preview = await screen.findByTitle('business-cover.html HTML preview');+ expect(screen.getByRole('button', { name: 'Preview' })).toHaveAttribute('aria-pressed', 'true');expect(preview).toHaveAttribute('sandbox', 'allow-scripts');- expect(screen.queryByRole('textbox', { name: 'business-cover.html 编辑器' })).not.toBeInTheDocument();+ expect(screen.queryByRole('textbox', { name: 'business-cover.html editor' })).not.toBeInTheDocument();});it('可以收起和展开右侧目录树,编辑区保持可用', async () => {@@ -600,16 +600,16 @@ describe('FileWorkspaceView', () => {render(<FileWorkspaceView selectedThread={thread} workspaceFileService={service} onClose={vi.fn()} />);expect(await screen.findAllByText('README.md')).not.toHaveLength(0);- expect(screen.queryByLabelText('项目文件树')).not.toBeInTheDocument();- expect(screen.queryByRole('separator', { name: '调整编辑区和目录树宽度' })).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Project file tree')).not.toBeInTheDocument();+ expect(screen.queryByRole('separator', { name: 'Resize the editor and file tree' })).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '展开目录树' }));+ await user.click(screen.getByRole('button', { name: 'Expand file tree' }));- expect(screen.getByLabelText('项目文件树')).toBeInTheDocument();- expect(screen.getByRole('separator', { name: '调整编辑区和目录树宽度' })).toBeInTheDocument();+ expect(screen.getByLabelText('Project file tree')).toBeInTheDocument();+ expect(screen.getByRole('separator', { name: 'Resize the editor and file tree' })).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '收起目录树' }));- expect(screen.queryByLabelText('项目文件树')).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Collapse file tree' }));+ expect(screen.queryByLabelText('Project file tree')).not.toBeInTheDocument();});it('编辑区和目录树之间的分隔条可以拖动调整目录树宽度', async () => {@@ -628,7 +628,7 @@ describe('FileWorkspaceView', () => {);await screen.findAllByText('README.md');- await userEvent.setup().click(screen.getByRole('button', { name: '展开目录树' }));+ await userEvent.setup().click(screen.getByRole('button', { name: 'Expand file tree' }));const body = container.querySelector('.file-workspace-body');if (!(body instanceof HTMLElement)) throw new Error('Expected file workspace body');@@ -644,7 +644,7 @@ describe('FileWorkspaceView', () => {toJSON: () => undefined});- const separator = screen.getByRole('separator', { name: '调整编辑区和目录树宽度' });+ const separator = screen.getByRole('separator', { name: 'Resize the editor and file tree' });fireEvent.mouseDown(separator, { button: 0, clientX: 620 });expect(document.querySelector('.pane-resize-shield')).not.toBeNull();fireEvent.mouseMove(window, { clientX: 560 });@@ -728,7 +728,7 @@ describe('FileWorkspaceView', () => {const editor = await openFileEditor(user, 'notes.txt');await user.click(editor);await user.keyboard('A');- await user.click(screen.getByRole('button', { name: '保存' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));await waitFor(() => {expect(service.saveText).toHaveBeenCalledWith({@@ -739,7 +739,7 @@ describe('FileWorkspaceView', () => {overwriteConflict: false});});- await waitFor(() => expect(screen.queryByLabelText('未保存')).not.toBeInTheDocument());+ await waitFor(() => expect(screen.queryByLabelText('Unsaved')).not.toBeInTheDocument());});it('409 FILE_CONFLICT 显示重新加载、覆盖保存、取消入口', async () => {@@ -770,11 +770,11 @@ describe('FileWorkspaceView', () => {const editor = await openFileEditor(user, 'notes.txt');await user.click(editor);await user.keyboard('A');- await user.click(screen.getByRole('button', { name: '保存' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));- expect(await screen.findByRole('button', { name: '重新加载' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: '覆盖保存' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: 'Reload' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Overwrite and save' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();});it('编辑后切换文件时,取消 confirm 不切换,确认后才切换', async () => {@@ -809,14 +809,14 @@ describe('FileWorkspaceView', () => {await expandFileTree(user);await user.click(screen.getByRole('treeitem', { name: 'guide.md' }));- expect(screen.getByRole('alertdialog', { name: '放弃未保存的修改?' }))- .toHaveTextContent('切换文件后,当前文件中尚未保存的修改将丢失。');+ expect(screen.getByRole('alertdialog', { name: 'Discard unsaved changes?' }))+ .toHaveTextContent('Switching files will discard unsaved changes in the current file.');await user.click(screen.getByRole('button', { name: '取消' }));expect(service.getMeta).not.toHaveBeenCalledWith(thread.id, 'guide.md');- expect(screen.getByRole('textbox', { name: 'notes.txt 编辑器' })).toBeInTheDocument();+ expect(screen.getByRole('textbox', { name: 'notes.txt editor' })).toBeInTheDocument();await user.click(screen.getByRole('treeitem', { name: 'guide.md' }));- await user.click(screen.getByRole('button', { name: '放弃并切换' }));+ await user.click(screen.getByRole('button', { name: 'Discard and switch' }));await waitFor(() => expect(service.getMeta).toHaveBeenCalledWith(thread.id, 'guide.md'));expect(await screen.findByRole('heading', { name: 'guide' })).toBeInTheDocument();@@ -850,25 +850,25 @@ describe('FileWorkspaceView', () => {const editor = await openFileEditor(user, 'notes.txt');await user.click(editor);await user.keyboard('A');- await user.click(screen.getByRole('button', { name: '保存' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));const issue = await screen.findByRole('alert');- expect(issue).toHaveTextContent('文件已在其他位置更新,请确认是否覆盖。');+ expect(issue).toHaveTextContent('The file was changed elsewhere. Confirm before overwriting it.');expect(issue).not.toHaveTextContent(/诊断编号:OC-/);- const conflictStatus = screen.getByRole('group', { name: '处理文件冲突' });+ const conflictStatus = screen.getByRole('group', { name: 'Resolve file conflict' });expect(conflictStatus).not.toBeNull();const metaCallsBeforeReload = service.getMeta.mock.calls.length;const textCallsBeforeReload = service.openText.mock.calls.length;- await user.click(within(conflictStatus as HTMLElement).getByRole('button', { name: '重新加载' }));+ await user.click(within(conflictStatus as HTMLElement).getByRole('button', { name: 'Reload' }));await waitFor(() => expect(service.getMeta.mock.calls.length).toBe(metaCallsBeforeReload + 1));await waitFor(() => expect(service.openText.mock.calls.length).toBe(textCallsBeforeReload + 1));await user.click(await openFileEditor(user, 'notes.txt'));await user.keyboard('B');- await user.click(screen.getByRole('button', { name: '保存' }));- const conflict = screen.getByRole('group', { name: '处理文件冲突' });- await user.click(within(conflict as HTMLElement).getByRole('button', { name: '覆盖保存' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));+ const conflict = screen.getByRole('group', { name: 'Resolve file conflict' });+ await user.click(within(conflict as HTMLElement).getByRole('button', { name: 'Overwrite and save' }));await waitFor(() => {expect(service.saveText).toHaveBeenLastCalledWith({@@ -882,12 +882,12 @@ describe('FileWorkspaceView', () => {await user.click(await openFileEditor(user, 'notes.txt'));await user.keyboard('C');- await user.click(screen.getByRole('button', { name: '保存' }));- const closeConflict = screen.getByRole('group', { name: '处理文件冲突' });- await user.click(within(closeConflict as HTMLElement).getByRole('button', { name: '取消' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));+ const closeConflict = screen.getByRole('group', { name: 'Resolve file conflict' });+ await user.click(within(closeConflict as HTMLElement).getByRole('button', { name: 'Cancel' }));- await waitFor(() => expect(screen.queryByRole('group', { name: '处理文件冲突' })).not.toBeInTheDocument());- expect(screen.getByRole('alert')).toHaveTextContent('文件已在其他位置更新,请确认是否覆盖。');+ await waitFor(() => expect(screen.queryByRole('group', { name: 'Resolve file conflict' })).not.toBeInTheDocument());+ expect(screen.getByRole('alert')).toHaveTextContent('The file was changed elsewhere. Confirm before overwriting it.');});it('read-only thread 显示只读提示且不能保存', async () => {@@ -909,10 +909,10 @@ describe('FileWorkspaceView', () => {render(<FileWorkspaceView selectedThread={thread} workspaceFileService={service} onClose={vi.fn()} />);- expect(await screen.findByText('当前会话为只读模式,不能保存文件')).toBeInTheDocument();- await userEvent.setup().click(screen.getByRole('button', { name: '编辑' }));- expect(await screen.findByRole('textbox', { name: 'notes.txt 编辑器' })).toHaveAttribute('aria-readonly', 'true');- expect(screen.getByRole('button', { name: '保存' })).toBeDisabled();+ expect(await screen.findByText('This conversation is read-only. Files cannot be saved.')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: 'Edit' }));+ expect(await screen.findByRole('textbox', { name: 'notes.txt editor' })).toHaveAttribute('aria-readonly', 'true');+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();});it('点击打开文件时以 file 模式在系统文件管理器中定位当前文件', async () => {@@ -936,7 +936,7 @@ describe('FileWorkspaceView', () => {render(<FileWorkspaceView selectedThread={thread} workspaceFileService={service} onClose={vi.fn()} />);await screen.findByText('draft');- await user.click(screen.getByRole('button', { name: '打开文件' }));+ await user.click(screen.getByRole('button', { name: 'Open file' }));await waitFor(() => {expect(service.reveal).toHaveBeenCalledWith({@@ -949,7 +949,7 @@ describe('FileWorkspaceView', () => {});async function expandFileTree(user: ReturnType<typeof userEvent.setup>) {- const button = screen.queryByRole('button', { name: '展开目录树' });+ const button = screen.queryByRole('button', { name: 'Expand file tree' });if (button !== null) await user.click(button);}@@ -957,10 +957,10 @@ async function openFileEditor(user: ReturnType<typeof userEvent.setup>,fileName: string): Promise<HTMLElement> {- const existing = screen.queryByRole('textbox', { name: `${fileName} 编辑器` });+ const existing = screen.queryByRole('textbox', { name: `${fileName} editor` });if (existing !== null) return existing;- await user.click(await screen.findByRole('button', { name: '编辑' }));- return await screen.findByRole('textbox', { name: `${fileName} 编辑器` });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));+ return await screen.findByRole('textbox', { name: `${fileName} editor` });}type ServiceOptions = {diff --git a/apps/web/src/features/files/FileWorkspaceView.tsx b/apps/web/src/features/files/FileWorkspaceView.tsxindex f0335d4b..617383f8 100644--- a/apps/web/src/features/files/FileWorkspaceView.tsx+++ b/apps/web/src/features/files/FileWorkspaceView.tsx@@ -51,7 +51,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {const [expandedPaths, setExpandedPaths] = useState<string[]>([]);const [truncatedPaths, setTruncatedPaths] = useState<string[]>([]);const [search, setSearch] = useState('');- const [rootName, setRootName] = useState('工作区');+ const [rootName, setRootName] = useState('Workspace');const [rootPathLabel, setRootPathLabel] = useState('');const [workspaceMessage, setWorkspaceMessage] = useState<string>();const [activePath, setActivePath] = useState<string>();@@ -67,7 +67,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {const [fileMode, setFileMode] = useState<FileEditorMode>('preview');const pageIssues = usePageIssueState('files');const handlePreviewError = useCallback((error: unknown) => {- pageIssues.captureOperationFailure('files.preview-html', error, '无法生成 HTML 预览,请切换到编辑模式查看源码。');+ pageIssues.captureOperationFailure('files.preview-html', error, 'Could not generate the HTML preview. Switch to edit mode to view the source.');}, [pageIssues.captureOperationFailure]);const handlePreviewReady = useCallback(() => {pageIssues.resolveOperation('files.preview-html');@@ -141,7 +141,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {setExpandedPaths([]);setTruncatedPaths([]);setSearch('');- setRootName('工作区');+ setRootName('Workspace');setRootPathLabel('');setWorkspaceMessage(undefined);setActivePath(undefined);@@ -188,7 +188,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {}setWorkspaceMessage(undefined);- pageIssues.captureOperationFailure('files.load-workspace', error, '无法加载文件工作区,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('files.load-workspace', error, 'Could not load the file workspace. Try again.', { retryable: true });});return () => {@@ -270,9 +270,9 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {}if (!options?.skipDirtyConfirm && dirty && !await confirm({- title: '放弃未保存的修改?',- description: '切换文件后,当前文件中尚未保存的修改将丢失。',- confirmLabel: '放弃并切换',+ title: 'Discard unsaved changes?',+ description: 'Switching files will discard unsaved changes in the current file.',+ confirmLabel: 'Discard and switch',destructive: true})) {return;@@ -324,7 +324,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {if (!mountedRef.current || requestId !== openRequestIdRef.current) {return;}- pageIssues.captureOperationFailure('files.open', error, '无法打开文件,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('files.open', error, 'Could not open the file. Try again.', { retryable: true });} finally {if (mountedRef.current && requestId === openRequestIdRef.current) {setLoading(false);@@ -372,7 +372,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {return;}setWorkspaceMessage(undefined);- pageIssues.captureOperationFailure('files.list-directory', error, '无法加载目录,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('files.list-directory', error, 'Could not load the directory. Try again.', { retryable: true });}}@@ -409,12 +409,12 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {if (error instanceof ApiClientError && error.status === 409 && error.code === 'FILE_CONFLICT') {setConflictOpen(true);- pageIssues.captureOperationFailure('files.save', error, '文件已在其他位置更新,请确认是否覆盖。', {+ pageIssues.captureOperationFailure('files.save', error, 'The file was changed elsewhere. Confirm before overwriting it.', {retryable: true,risk: 'overwrite'});} else {- pageIssues.captureOperationFailure('files.save', error, '文件保存失败,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('files.save', error, 'Could not save the file. Try again.', { retryable: true });}} finally {if (mountedRef.current) {@@ -433,15 +433,15 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {await service.reveal({ threadId: thread.id, path: activePath, mode: 'file' });pageIssues.resolveOperation('files.reveal');} catch (error) {- pageIssues.captureOperationFailure('files.reveal', error, '无法在系统中打开文件,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('files.reveal', error, 'Could not open the file in the system application. Try again.', { retryable: true });}}async function handleBack() {if (dirty && !await confirm({- title: '关闭文件工作区?',- description: '当前文件还有未保存的修改,关闭后这些修改将丢失。',- confirmLabel: '放弃并关闭',+ title: 'Close the file workspace?',+ description: 'Closing the workspace will discard unsaved changes in the current file.',+ confirmLabel: 'Discard and close',destructive: true})) {return;@@ -491,11 +491,11 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {}if (!thread) {- return renderEmptyWorkspace('请选择或创建一个会话后查看文件');+ return renderEmptyWorkspace('Select or create a conversation to view files');}if (!service) {- return renderEmptyWorkspace('本地文件服务暂不可用');+ return renderEmptyWorkspace('The local file service is unavailable');}const fileWorkspaceBodyStyle = {@@ -557,19 +557,19 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {onDismiss={pageIssues.dismissIssue}compact/>- {threadReadonly ? <div className="file-workspace-notice">当前会话为只读模式,不能保存文件</div> : null}+ {threadReadonly ? <div className="file-workspace-notice">This conversation is read-only. Files cannot be saved.</div> : null}{workspaceMessage ? <div className="file-workspace-notice">{workspaceMessage}</div> : null}{conflictOpen ? (- <div className="file-workspace-conflict" role="group" aria-label="处理文件冲突">+ <div className="file-workspace-conflict" role="group" aria-label="Resolve file conflict"><div className="file-workspace-conflict-actions"><button className="button-secondary" type="button" onClick={() => void openFilePath(meta?.path ?? '', { skipDirtyConfirm: true })}>- 重新加载+ Reload</button><button className="button-secondary" type="button" onClick={() => void handleSave(true)}>- 覆盖保存+ Overwrite and save</button><button className="button-secondary" type="button" onClick={() => setConflictOpen(false)}>- 取消+ Cancel</button></div></div>@@ -599,7 +599,7 @@ export function FileWorkspaceView(props: FileWorkspaceViewProps) {<divclassName="pane-resize-handle file-tree-resize-handle"role="separator"- aria-label="调整编辑区和目录树宽度"+ aria-label="Resize the editor and file tree"aria-orientation="vertical"aria-valuenow={treeWidth}tabIndex={0}diff --git a/apps/web/src/features/files/HtmlPreview.test.tsx b/apps/web/src/features/files/HtmlPreview.test.tsxindex 7da80f70..b0b0df90 100644--- a/apps/web/src/features/files/HtmlPreview.test.tsx+++ b/apps/web/src/features/files/HtmlPreview.test.tsx@@ -19,7 +19,7 @@ describe('HtmlPreview', () => {render(<HtmlPreview name="broken.html" path="broken.html" content="<main>test</main>" onError={onError} />);await waitFor(() => expect(onError).toHaveBeenCalledWith(failure));- expect(screen.getByRole('status')).toHaveTextContent('预览暂不可用');+ expect(screen.getByRole('status')).toHaveTextContent('Preview is unavailable');expect(screen.queryByRole('alert')).not.toBeInTheDocument();});@@ -42,7 +42,7 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('unsafe.html HTML 预览');+ const frame = await screen.findByTitle('unsafe.html HTML preview');const srcDoc = frame.getAttribute('srcdoc') ?? '';expect(frame).toHaveAttribute('sandbox', 'allow-scripts');expect(frame).toHaveAttribute('referrerpolicy', 'no-referrer');@@ -73,7 +73,7 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('report.html HTML 预览');+ const frame = await screen.findByTitle('report.html HTML preview');const srcDoc = frame.getAttribute('srcdoc') ?? '';const sourceStyleIndex = srcDoc.indexOf('body { opacity: 0; }');const previewStyleIndex = srcDoc.indexOf('data-opencreator-preview="true"');@@ -121,7 +121,7 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('index.html HTML 预览');+ const frame = await screen.findByTitle('index.html HTML preview');await waitFor(() => {expect(frame.getAttribute('srcdoc')).toContain('data:image/png;base64,AQIDBA==');expect(frame.getAttribute('srcdoc')).toContain('data:image/png;base64,BQYHCA==');@@ -154,7 +154,7 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('index.html HTML 预览');+ const frame = await screen.findByTitle('index.html HTML preview');await waitFor(() => expect(frame.getAttribute('srcdoc')).not.toContain('正在准备安全预览'));expect(openBlob).not.toHaveBeenCalled();expect(frame.getAttribute('srcdoc')).not.toContain('secret.png');@@ -173,9 +173,9 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('links.html HTML 预览');+ const frame = await screen.findByTitle('links.html HTML preview');expect(frame.getAttribute('srcdoc')).not.toContain('href="https://example.com/docs"');- await user.click(await screen.findByRole('button', { name: '外部打开 产品文档' }));+ await user.click(await screen.findByRole('button', { name: 'Open externally 产品文档' }));expect(onOpenExternal).toHaveBeenCalledWith('https://example.com/docs');});@@ -209,7 +209,7 @@ describe('HtmlPreview', () => {/>);- await screen.findByTitle('many.html HTML 预览');+ await screen.findByTitle('many.html HTML preview');await waitFor(() => expect(openBlob).toHaveBeenCalledTimes(128));});@@ -235,7 +235,7 @@ describe('HtmlPreview', () => {/>);- const frame = await screen.findByTitle('large.html HTML 预览');+ const frame = await screen.findByTitle('large.html HTML preview');await waitFor(() => {expect(frame.getAttribute('srcdoc')).toContain('data:image/png;base64,AQ==');});diff --git a/apps/web/src/features/files/HtmlPreview.tsx b/apps/web/src/features/files/HtmlPreview.tsxindex 0eb6ae55..088ba76f 100644--- a/apps/web/src/features/files/HtmlPreview.tsx+++ b/apps/web/src/features/files/HtmlPreview.tsx@@ -82,7 +82,7 @@ export function HtmlPreview(props: {if (preview.status === 'loading') {return (<div className="file-preview file-preview-html file-preview-html-status" role="status">- 正在准备 HTML 预览...+ Preparing HTML preview...</div>);}@@ -90,7 +90,7 @@ export function HtmlPreview(props: {if (preview.status === 'error') {return (<div className="file-preview file-preview-html file-preview-html-status" role="status">- 预览暂不可用,可切换至编辑查看源码。+ Preview is unavailable. Switch to edit mode to view the source.</div>);}@@ -98,18 +98,18 @@ export function HtmlPreview(props: {return (<div className="file-preview file-preview-html"><iframe- title={`${props.name} HTML 预览`}+ title={`${props.name} HTML preview`}srcDoc={preview.document.html}sandbox="allow-scripts"referrerPolicy="no-referrer"/>{preview.document.externalLinks.length > 0 && props.onOpenExternal !== undefined ? (- <div className="html-preview-external-links" aria-label="预览外链">+ <div className="html-preview-external-links" aria-label="Preview external link">{preview.document.externalLinks.map(link => (<buttonkey={link.url}type="button"- aria-label={`外部打开 ${link.label}`}+ aria-label={`Open externally ${link.label}`}title={link.url}onClick={() => props.onOpenExternal?.(link.url)}>@@ -436,7 +436,7 @@ function normalizePreviewResourceMime(value: string): string | undefined {async function objectUrlToDataUrl(objectUrl: string, mime: string): Promise<string> {const response = await fetch(objectUrl);- if (!response.ok) throw new Error('无法读取预览资源');+ if (!response.ok) throw new Error('Could not read preview resources');const bytes = new Uint8Array(await response.arrayBuffer());let binary = '';for (let offset = 0; offset < bytes.length; offset += 0x8000) {diff --git a/apps/web/src/features/files/ProjectFileTree.test.tsx b/apps/web/src/features/files/ProjectFileTree.test.tsxindex 31985758..d431b47f 100644--- a/apps/web/src/features/files/ProjectFileTree.test.tsx+++ b/apps/web/src/features/files/ProjectFileTree.test.tsx@@ -8,14 +8,14 @@ describe('ProjectFileTree', () => {it('nodes 为空时显示空态文案', () => {renderTree({ nodes: [] });- expect(screen.getByText('当前工作区暂无可显示文件')).toBeInTheDocument();+ expect(screen.getByText('No files to display in this workspace')).toBeInTheDocument();expect(screen.queryByRole('tree')).not.toBeInTheDocument();});it('渲染搜索框、目录、文件和当前文件高亮', () => {renderTree();- expect(screen.getByRole('searchbox', { name: '筛选文件' })).toHaveAttribute('placeholder', '筛选文件...');+ expect(screen.getByRole('searchbox', { name: 'Filter files' })).toHaveAttribute('placeholder', 'Filter files...');expect(screen.getByRole('tree')).toBeInTheDocument();expect(screen.getByRole('treeitem', { name: 'docs' })).toBeInTheDocument();@@ -73,7 +73,7 @@ describe('ProjectFileTree', () => {it('渲染截断目录提示', () => {renderTree({ truncatedPaths: ['docs'] });- expect(screen.getByText('当前目录文件较多,仅显示前 500 项')).toBeInTheDocument();+ expect(screen.getByText('Only the first 500 items in this directory are shown')).toBeInTheDocument();});it('输入搜索时触发 onSearchChange(value)', async () => {@@ -93,7 +93,7 @@ describe('ProjectFileTree', () => {);for (const value of ['r', 're', 'rea', 'read', 'readm', 'readme']) {- await user.type(screen.getByRole('searchbox', { name: '筛选文件' }), value.slice(-1));+ await user.type(screen.getByRole('searchbox', { name: 'Filter files' }), value.slice(-1));rerender(<ProjectFileTreenodes={createNodes()}diff --git a/apps/web/src/features/files/ProjectFileTree.tsx b/apps/web/src/features/files/ProjectFileTree.tsxindex 3910d9a6..6799aa24 100644--- a/apps/web/src/features/files/ProjectFileTree.tsx+++ b/apps/web/src/features/files/ProjectFileTree.tsx@@ -34,26 +34,26 @@ export function ProjectFileTree(props: ProjectFileTreeProps) {const visibleEntries = filterEntries(tree, query);return (- <section className="file-tree-panel" aria-label="项目文件树">+ <section className="file-tree-panel" aria-label="Project file tree"><label className="file-search"><span className="file-search-icon" aria-hidden="true"><Search size={14} strokeWidth={2} /></span>- <span className="file-search-label">筛选文件</span>+ <span className="file-search-label">Filter files</span><inputtype="search"role="searchbox"- aria-label="筛选文件"- placeholder="筛选文件..."+ aria-label="Filter files"+ placeholder="Filter files..."value={props.search}onChange={(event) => props.onSearchChange(event.target.value)}/></label>{visibleEntries.length === 0 ? (- <p className="file-tree-empty">当前工作区暂无可显示文件</p>+ <p className="file-tree-empty">No files to display in this workspace</p>) : (- <ul className="file-tree-list" role="tree" aria-label="项目文件">+ <ul className="file-tree-list" role="tree" aria-label="Project files">{visibleEntries.map((entry) => (<TreeNodeRowkey={entry.node.path}@@ -110,7 +110,7 @@ function TreeNodeRow(props: TreeNodeRowProps) {{props.truncated.has(node.path) ? (<p className="file-tree-warning" style={{ paddingInlineStart: `${40 + node.depth * 16}px` }}>- 当前目录文件较多,仅显示前 500 项+ Only the first 500 items in this directory are shown</p>) : null}diff --git a/apps/web/src/features/files/TextFileEditor.tsx b/apps/web/src/features/files/TextFileEditor.tsxindex b0ed8c1d..f9c3c368 100644--- a/apps/web/src/features/files/TextFileEditor.tsx+++ b/apps/web/src/features/files/TextFileEditor.tsx@@ -179,7 +179,7 @@ export function TextFileEditor(props: TextFileEditorProps) {function configureContentDom(view: EditorView, path: string, readonly: boolean) {view.contentDOM.setAttribute('role', 'textbox');- view.contentDOM.setAttribute('aria-label', `${path} 编辑器`);+ view.contentDOM.setAttribute('aria-label', `${path} editor`);view.contentDOM.setAttribute('aria-multiline', 'true');view.contentDOM.setAttribute('aria-readonly', readonly ? 'true' : 'false');}diff --git a/apps/web/src/features/issues/IssuePresenter.tsx b/apps/web/src/features/issues/IssuePresenter.tsxindex 33f064fc..6b495e3a 100644--- a/apps/web/src/features/issues/IssuePresenter.tsx+++ b/apps/web/src/features/issues/IssuePresenter.tsx@@ -148,7 +148,7 @@ async function runAction(if (action.kind === 'retry-operation') {if ((action.requiresConfirmation || action.risk !== 'normal')- && !globalThis.confirm('此操作可能产生费用或覆盖结果,确定继续吗?')+ && !globalThis.confirm('This operation may incur charges or overwrite results. Continue?')) return;const handler = registry.retryOperations?.[action.operationId];if (handler === undefined) return;diff --git a/apps/web/src/features/issues/issue-catalog.ts b/apps/web/src/features/issues/issue-catalog.tsindex 0bc0eaf6..c353352c 100644--- a/apps/web/src/features/issues/issue-catalog.ts+++ b/apps/web/src/features/issues/issue-catalog.ts@@ -243,10 +243,10 @@ export function issueDiagnosticText(issue: OpenCreatorIssue, language: AppLanguafunction safeFallback(value: string, language: AppLanguage): string {const normalized = value- .replace(/authorization\s*[:=]\s*(?:Bearer|Basic)\s+\S+/gi, '[已隐藏]')- .replace(/(?:authorization|api[-_ ]?key|token|secret)\s*[:=]\s*\S+/gi, '[已隐藏]')- .replace(/[A-Za-z]:\\Users\\[^\\\s]+/gi, '[用户目录]')- .replace(/\/(?:Users|home)\/[^/\s]+/g, '[用户目录]')+ .replace(/authorization\s*[:=]\s*(?:Bearer|Basic)\s+\S+/gi, '[redacted]')+ .replace(/(?:authorization|api[-_ ]?key|token|secret)\s*[:=]\s*\S+/gi, '[redacted]')+ .replace(/[A-Za-z]:\\Users\\[^\\\s]+/gi, '[user directory]')+ .replace(/\/(?:Users|home)\/[^/\s]+/g, '[user directory]').replace(/\s+at\s+[^\n]+(?:\n|$)/g, ' ').trim().slice(0, 500);diff --git a/apps/web/src/features/issues/page-issue-state.ts b/apps/web/src/features/issues/page-issue-state.tsindex 9e7f43f0..b39a1059 100644--- a/apps/web/src/features/issues/page-issue-state.ts+++ b/apps/web/src/features/issues/page-issue-state.ts@@ -27,7 +27,7 @@ export function usePageIssueState(surface: string): PageIssueState {const captureOperationFailure = useCallback((operationId: string,cause: unknown,- fallbackMessage = '操作未完成,请重试。',+ fallbackMessage = 'The operation did not complete. Try again.',options: { retryable?: boolean; risk?: 'normal' | 'paid' | 'overwrite' } = {}) => {const normalized = normalizePageIssue(surface, operationId, cause, fallbackMessage);@@ -98,7 +98,7 @@ export function normalizePageIssue(operation: operationId,category: 'configuration',summaryKey: 'issue.configuration',- fallbackMessage: `当前页面请求的 ${templateMismatch[1]} 模板版本 ${templateMismatch[2]} 不受本地服务支持,因此任务尚未创建。`,+ fallbackMessage: `The local Runtime does not support version ${templateMismatch[2]} of the ${templateMismatch[1]} template requested by this page. The task was not created.`,fingerprint};}@@ -106,7 +106,7 @@ export function normalizePageIssue(...issue,scope: { kind: 'page', surface },operation: operationId,- fallbackMessage: issue.fallbackMessage === '操作未完成,请稍后重试。'+ fallbackMessage: ['操作未完成,请稍后重试。', 'The operation did not complete. Try again later.'].includes(issue.fallbackMessage)? fallbackMessage: issue.fallbackMessage || fallbackMessage};diff --git a/apps/web/src/features/runs/RunDetailPanel.test.tsx b/apps/web/src/features/runs/RunDetailPanel.test.tsxindex d432e6b7..b3da86dd 100644--- a/apps/web/src/features/runs/RunDetailPanel.test.tsx+++ b/apps/web/src/features/runs/RunDetailPanel.test.tsx@@ -7,7 +7,7 @@ describe('RunDetailPanel', () => {it('shows an empty state when no run is selected', () => {render(<RunDetailPanel />);- expect(screen.getByText('选择 run 查看详情')).toBeInTheDocument();+ expect(screen.getByText('Select a run to view details')).toBeInTheDocument();});it('shows an empty diagnostics state when the selected run has no diagnostic files', () => {@@ -29,7 +29,7 @@ describe('RunDetailPanel', () => {render(<RunDetailPanel runId="run_1" diagnostics={diagnostics} />);- expect(screen.getByText('暂无诊断文件')).toBeInTheDocument();+ expect(screen.getByText('No diagnostic files')).toBeInTheDocument();});it('shows attachments associated with the selected run', () => {@@ -54,7 +54,7 @@ describe('RunDetailPanel', () => {/>);- expect(screen.getByText('附件')).toBeInTheDocument();+ expect(screen.getByText('Attachments')).toBeInTheDocument();expect(screen.getByText('screen.png')).toBeInTheDocument();expect(screen.getByText('image/png · 2 KB')).toBeInTheDocument();});@@ -83,10 +83,10 @@ describe('RunDetailPanel', () => {render(<RunDetailPanel runId="run_2" diagnostics={createDiagnostics()} context={context} />);- expect(screen.getByText('本次使用的上下文')).toBeInTheDocument();- expect(screen.getByText('项目记忆')).toBeInTheDocument();+ expect(screen.getByText('Context used in this run')).toBeInTheDocument();+ expect(screen.getByText('Project memory')).toBeInTheDocument();expect(screen.getByText('提交前运行全部测试')).toBeInTheDocument();- expect(screen.getByText('会话摘要 v3')).toBeInTheDocument();+ expect(screen.getByText('Conversation summary v3')).toBeInTheDocument();expect(screen.getByText('用户:继续开发')).toBeInTheDocument();});@@ -99,7 +99,7 @@ describe('RunDetailPanel', () => {/>);- expect(screen.getByText('本次运行未使用长期记忆或摘要')).toBeInTheDocument();+ expect(screen.getByText('This run used no long-term memories or summaries')).toBeInTheDocument();});it('requires confirmation before exporting the redacted diagnostics bundle', async () => {@@ -114,15 +114,15 @@ describe('RunDetailPanel', () => {/>);- fireEvent.click(screen.getByRole('button', { name: '导出脱敏诊断包' }));- const confirmation = screen.getByRole('region', { name: '确认导出诊断' });- expect(within(confirmation).getByText(/不包含原始 Prompt、Token 或 Secret/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Export redacted diagnostics' }));+ const confirmation = screen.getByRole('region', { name: 'Confirm diagnostics export' });+ expect(within(confirmation).getByText(/without original prompts, tokens, or secrets/)).toBeInTheDocument();- fireEvent.click(within(confirmation).getByRole('button', { name: '取消' }));+ fireEvent.click(within(confirmation).getByRole('button', { name: 'Cancel' }));expect(onExport).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: '导出脱敏诊断包' }));- fireEvent.click(screen.getByRole('button', { name: '确认导出' }));+ fireEvent.click(screen.getByRole('button', { name: 'Export redacted diagnostics' }));+ fireEvent.click(screen.getByRole('button', { name: 'Confirm export' }));await waitFor(() => expect(onExport).toHaveBeenCalledWith(diagnostics));});@@ -175,7 +175,7 @@ describe('RunDetailPanel', () => {render(<RunDetailPanel runId="run_3" diagnostics={diagnostics} />);- expect(screen.getByText('暂无 Codex 诊断')).toBeInTheDocument();+ expect(screen.getByText('No Codex diagnostics')).toBeInTheDocument();});});diff --git a/apps/web/src/features/runs/RunDetailPanel.tsx b/apps/web/src/features/runs/RunDetailPanel.tsxindex 035a1185..7ff3a689 100644--- a/apps/web/src/features/runs/RunDetailPanel.tsx+++ b/apps/web/src/features/runs/RunDetailPanel.tsx@@ -31,7 +31,7 @@ export function RunDetailPanel(props: {if (props.runId === undefined) {return (<div className="panel-scroll">- <p className="empty-state">选择 run 查看详情</p>+ <p className="empty-state">Select a run to view details</p></div>);}@@ -39,7 +39,7 @@ export function RunDetailPanel(props: {if (props.diagnostics === undefined) {return (<div className="run-detail">- <div className="settings-state">正在加载运行详情...</div>+ <div className="settings-state">Loading run details...</div></div>);}@@ -56,7 +56,7 @@ export function RunDetailPanel(props: {pageIssues.resolveOperation('run-detail.export');setConfirmingExport(false);} catch (reason) {- pageIssues.captureOperationFailure('run-detail.export', reason, '诊断包导出失败,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('run-detail.export', reason, 'Could not export the diagnostics package. Try again.', { retryable: true });}}@@ -66,7 +66,7 @@ export function RunDetailPanel(props: {<header className="run-detail__header"><div><h2>Run {props.runId}</h2>- <p>诊断文件由 daemon 脱敏后返回。</p>+ <p>Diagnostic files are redacted by the Daemon.</p></div><buttonclassName="toolbar-button"@@ -74,7 +74,7 @@ export function RunDetailPanel(props: {onClick={() => setConfirmingExport(true)}><Download aria-hidden="true" size={15} />- <span>导出脱敏诊断包</span>+ <span>Export redacted diagnostics</span></button></header><IssueList@@ -84,26 +84,26 @@ export function RunDetailPanel(props: {compact/>{confirmingExport ? (- <section className="run-diagnostics-confirm" role="region" aria-label="确认导出诊断">+ <section className="run-diagnostics-confirm" role="region" aria-label="Confirm diagnostics export"><ShieldCheck aria-hidden="true" size={18} /><div>- <strong>确认导出 daemon 已脱敏的诊断内容</strong>- <p>导出包只包含当前诊断响应,不包含原始 Prompt、Token 或 Secret。</p>+ <strong>Confirm exporting redacted Daemon diagnostics</strong>+ <p>The export contains only the current diagnostic response, without original prompts, tokens, or secrets.</p></div><div><button className="settings-text-button" type="button" onClick={() => setConfirmingExport(false)}>- 取消+ Cancel</button><button className="settings-primary-button" type="button" onClick={() => void exportDiagnostics()}><Download aria-hidden="true" size={15} />- 确认导出+ Confirm export</button></div></section>) : null}{(props.attachments?.length ?? 0) > 0 ? (<section>- <h3>附件</h3>+ <h3>Attachments</h3><ul className="run-detail-attachments">{props.attachments?.map(attachment => (<li key={attachment.id}>@@ -118,11 +118,11 @@ export function RunDetailPanel(props: {</section>) : null}<section className="run-context">- <h3>本次使用的上下文</h3>+ <h3>Context used in this run</h3>{props.context === undefined ? (- <p>正在加载上下文...</p>+ <p>Loading context...</p>) : props.context.items.length === 0 ? (- <p>本次运行未使用长期记忆或摘要</p>+ <p>This run used no long-term memories or summaries</p>) : (<ul>{props.context.items.map(item => (@@ -134,7 +134,7 @@ export function RunDetailPanel(props: {<section><h3>Diagnostics</h3>{diagnosticFiles.length === 0 ? (- <p>暂无诊断文件</p>+ <p>No diagnostic files</p>) : (diagnosticFiles.map((file) => (<details key={file.name}>@@ -147,7 +147,7 @@ export function RunDetailPanel(props: {<section><h3>Warnings</h3>{warnings.length === 0 ? (- <p>暂无诊断警告</p>+ <p>No diagnostic warnings</p>) : (<ul>{warnings.map((warning) => (@@ -174,7 +174,7 @@ export function RunDetailPanel(props: {<dt>Diagnostics</dt><dd>{codexDiagnostics.length === 0 ? (- '暂无 Codex 诊断'+ 'No Codex diagnostics') : (<ul>{codexDiagnostics.map((diagnostic) => (@@ -197,8 +197,8 @@ export function RunDetailPanel(props: {function RunContextListItem(props: { item: RunContextItem }) {const label = props.item.kind === 'summary'- ? `会话摘要 v${props.item.summaryVersion ?? 1}`- : `${memoryScopeLabel(props.item.scope)}记忆`;+ ? `Conversation summary v${props.item.summaryVersion ?? 1}`+ : `${memoryScopeLabel(props.item.scope)} memory`;return (<li className="run-context__item"><div>@@ -211,9 +211,9 @@ function RunContextListItem(props: { item: RunContextItem }) {}function memoryScopeLabel(scope: RunContextItem['scope']): string {- if (scope === 'project') return '项目';- if (scope === 'thread') return '线程';- return '全局';+ if (scope === 'project') return 'Project';+ if (scope === 'thread') return 'Thread';+ return 'Global';}function formatAttachmentSize(size: number): string {diff --git a/apps/web/src/features/schedules/ScheduleEditor.tsx b/apps/web/src/features/schedules/ScheduleEditor.tsxindex 073e4007..fc76917e 100644--- a/apps/web/src/features/schedules/ScheduleEditor.tsx+++ b/apps/web/src/features/schedules/ScheduleEditor.tsx@@ -69,7 +69,7 @@ export function ScheduleEditor(props: {firstInvalidField?.scrollIntoView?.({ block: 'center' });}, [props.errors]);- const formLabel = props.mode === 'create' ? '创建定时任务' : `编辑${values.name || '定时任务'}`;+ const formLabel = props.mode === 'create' ? 'Create scheduled task' : `Edit ${values.name || 'scheduled task'}`;function submit(event: FormEvent<HTMLFormElement>) {event.preventDefault();props.onSubmit(values);@@ -124,12 +124,12 @@ export function ScheduleEditor(props: {return (<form ref={formRef} className="schedule-editor" aria-label={formLabel} onSubmit={submit}><header className="schedule-editor__topbar">- <strong>{props.mode === 'create' ? '创建定时任务' : '编辑定时任务'}</strong>+ <strong>{props.mode === 'create' ? 'Create scheduled task' : 'Edit scheduled task'}</strong><buttonclassName="schedule-icon-button schedule-icon-button--plain"type="button"- aria-label="取消编辑"- title="关闭"+ aria-label="Cancel editing"+ title="Close"onClick={props.onCancel}><X size={18} />@@ -139,7 +139,7 @@ export function ScheduleEditor(props: {{props.loading ? (<div className="schedule-editor__loading" role="status"><LoaderCircle size={18} className="schedule-spin" />- 正在加载计划详情+ Loading schedule details</div>) : (<>@@ -152,13 +152,13 @@ export function ScheduleEditor(props: {<label className="schedule-title-field"><span>- 标题- <small>必填</small>+ Title+ <small>Required</small></span><input- aria-label="定时任务标题"+ aria-label="Scheduled task title"value={values.name}- placeholder="输入任务标题"+ placeholder="Enter task title"aria-invalid={props.errors?.name ? 'true' : undefined}onChange={event => update('name', event.target.value)}/>@@ -168,11 +168,11 @@ export function ScheduleEditor(props: {</label><label className="schedule-prompt-field">- <span>描述</span>+ <span>Description</span><textarea- aria-label="任务内容"+ aria-label="Task instructions"value={values.prompt}- placeholder="描述需要帮你做什么..."+ placeholder="Describe what you need done..."rows={3}aria-invalid={props.errors?.prompt ? 'true' : undefined}onChange={event => update('prompt', event.target.value)}@@ -183,16 +183,16 @@ export function ScheduleEditor(props: {</label><section className="schedule-editor-group" aria-labelledby="schedule-frequency-heading">- <h2 id="schedule-frequency-heading">执行频率</h2>+ <h2 id="schedule-frequency-heading">Frequency</h2><div className="schedule-setting-list schedule-setting-list--time-popover">- <SettingRow label="重复">+ <SettingRow label="Repeat"><SelectControl- ariaLabel="重复"+ ariaLabel="Repeat"value={values.frequency.repeat}onChange={value => updateRepeat(value as ScheduleRepeat)}>{values.frequency.repeat === 'advanced' ? (- <option value="advanced">高级计划(保持原设置)</option>+ <option value="advanced">Advanced schedule (keep existing settings)</option>) : null}{scheduleRepeatOptions.map(option => (<option key={option.value} value={option.value}>@@ -204,18 +204,18 @@ export function ScheduleEditor(props: {{values.frequency.repeat === 'advanced' ? (<div className="schedule-legacy-note">- 这是旧版高级计划。保持当前选项可原样保存,也可以改成更简单的重复频率。+ This is a legacy advanced schedule. Keep the current option to preserve it, or select a simpler frequency.</div>) : (<><SettingRow- label={values.frequency.repeat === 'hourly' ? '分钟' : '时间'}+ label={values.frequency.repeat === 'hourly' ? 'minutes' : 'Time'}>{values.frequency.repeat === 'hourly' ? (<div className="schedule-hourly-control">- <span>每小时第</span>+ <span>Minute</span><input- aria-label="每小时分钟"+ aria-label="Minute of each hour"type="number"min="0"max="59"@@ -231,7 +231,7 @@ export function ScheduleEditor(props: {});}}/>- <span>分钟</span>+ <span>minutes</span></div>) : (<ScheduleTimePicker@@ -246,7 +246,7 @@ export function ScheduleEditor(props: {{values.frequency.repeat === 'weekly'|| values.frequency.repeat === 'custom' ? (- <div className="schedule-day-picker" role="group" aria-label="执行日期">+ <div className="schedule-day-picker" role="group" aria-label="Run dates">{scheduleWeekdays.map(day => {const selected = values.frequency.days.includes(day.value);return (@@ -284,11 +284,11 @@ export function ScheduleEditor(props: {className="schedule-editor-advanced"aria-labelledby="schedule-advanced-heading">- <h2 id="schedule-advanced-heading">请选择访问权限</h2>+ <h2 id="schedule-advanced-heading">Select access permissions</h2><div className="schedule-setting-list">- <SettingRow label="权限">+ <SettingRow label="Permission"><SelectControl- ariaLabel="权限"+ ariaLabel="Permission"value={values.sandbox === 'danger-full-access'? 'danger-full-access': 'workspace-write'}@@ -297,9 +297,9 @@ export function ScheduleEditor(props: {value === 'danger-full-access'&& values.sandbox !== 'danger-full-access'&& !await confirm({- title: '开启完全访问权限',- description: '完全访问权限允许任务访问本机文件并执行本地操作。仅为可信任务开启。',- confirmLabel: '开启'+ title: 'Enable full access',+ description: 'Full access lets tasks access local files and run local operations. Enable it only for trusted tasks.',+ confirmLabel: 'Enable'})) {return;@@ -307,8 +307,8 @@ export function ScheduleEditor(props: {update('sandbox', value as SandboxMode);}}>- <option value="workspace-write">请求批准</option>- <option value="danger-full-access">完全访问权限</option>+ <option value="workspace-write">Ask for approval</option>+ <option value="danger-full-access">Full access</option></SelectControl></SettingRow></div>@@ -321,8 +321,8 @@ export function ScheduleEditor(props: {onChange={event => update('enabled', event.target.checked)}/><span>- <strong>创建后启用</strong>- <small>关闭后会保存为暂停状态</small>+ <strong>Enable after creation</strong>+ <small>When disabled, the task will be saved as paused</small></span></label></div>@@ -333,7 +333,7 @@ export function ScheduleEditor(props: {type="button"onClick={props.onCancel}>- 取消+ Cancel</button><buttonclassName="schedule-button schedule-button--secondary"@@ -345,7 +345,7 @@ export function ScheduleEditor(props: {) : (<Save size={16} />)}- {props.mode === 'create' ? '创建任务' : '保存更改'}+ {props.mode === 'create' ? 'Create task' : 'Save changes'}</button></footer></>@@ -387,7 +387,7 @@ function ScheduleTimePicker(props: {<buttonaria-expanded={open}aria-haspopup="dialog"- aria-label="执行时间"+ aria-label="Run time"className="schedule-time-picker__trigger"type="button"onClick={() => setOpen(current => !current)}@@ -396,15 +396,15 @@ function ScheduleTimePicker(props: {<Clock3 size={15} aria-hidden="true" /></button>{open ? (- <div className="schedule-time-picker__popover" role="dialog" aria-label="选择执行时间">+ <div className="schedule-time-picker__popover" role="dialog" aria-label="Select run time"><TimeColumn- label="小时"+ label="hours"selected={hour}values={Array.from({ length: 24 }, (_, index) => String(index).padStart(2, '0'))}onSelect={nextHour => props.onChange(`${nextHour}:${minute}`)}/><TimeColumn- label="分钟"+ label="minutes"selected={minute}values={Array.from({ length: 60 }, (_, index) => String(index).padStart(2, '0'))}onSelect={nextMinute => props.onChange(`${hour}:${nextMinute}`)}@@ -479,16 +479,16 @@ export function validateScheduleEditorValues(values: ScheduleEditorValues): ScheduleEditorErrors {const errors: ScheduleEditorErrors = {};- if (values.name.trim().length === 0) errors.name = '请输入任务标题';- if (values.prompt.trim().length === 0) errors.prompt = '请描述需要帮你做什么';+ if (values.name.trim().length === 0) errors.name = 'Enter a task title';+ if (values.prompt.trim().length === 0) errors.prompt = 'Describe what you need done';try {scheduleFrequencyToCron(values.frequency);} catch {- errors.frequency = '请选择执行频率';+ errors.frequency = 'Select a frequency';}- if (values.cwd.trim().length === 0) errors.form = '当前项目不可用,请先选择或创建项目';+ if (values.cwd.trim().length === 0) errors.form = 'This project is unavailable. Select or create a project first.';if (values.profile.trim().length === 0) {- errors.form = '当前项目的运行配置不可用,请先在项目设置中修复';+ errors.form = 'This project\'s Runtime configuration is unavailable. Fix it in project settings first.';}return errors;}diff --git a/apps/web/src/features/schedules/ScheduleThreadHeader.test.tsx b/apps/web/src/features/schedules/ScheduleThreadHeader.test.tsxindex 614eb5b9..ef7d95ae 100644--- a/apps/web/src/features/schedules/ScheduleThreadHeader.test.tsx+++ b/apps/web/src/features/schedules/ScheduleThreadHeader.test.tsx@@ -12,18 +12,18 @@ import { ScheduleThreadHeader } from './ScheduleThreadHeader.js';describe('ScheduleThreadHeader', () => {it.each([- ['idle', '已启用'],- ['running', '运行中'],- ['queued', '已排队'],- ['waiting_approval', '等待审批'],- ['failed', '上次失败'],- ['paused', '已暂停'],+ ['idle', 'Enabled'],+ ['running', 'Running'],+ ['queued', 'Queued'],+ ['waiting_approval', 'Awaiting approval'],+ ['failed', 'Last run failed'],+ ['paused', 'Paused'],] satisfies Array<[ScheduleSidebarTaskStatus, string]>)('renders the %s task status',(status, label) => {renderHeader({ status });- expect(screen.getByRole('status', { name: '任务状态' })).toHaveTextContent(label);+ expect(screen.getByRole('status', { name: 'Task status' })).toHaveTextContent(label);if (status === 'idle') {expect(screen.getByText('下次 7/15 09:00')).toBeInTheDocument();}@@ -43,16 +43,16 @@ describe('ScheduleThreadHeader', () => {service: createService({ updateSchedule }),});- await user.click(screen.getByRole('button', { name: '立即运行任务' }));- expect(screen.getByRole('button', { name: '立即运行任务' })).toBeDisabled();- expect(screen.getByRole('button', { name: '暂停任务' })).toBeDisabled();- expect(screen.getByRole('button', { name: '编辑任务' })).toBeDisabled();- expect(screen.getByRole('status', { name: '任务操作状态' })).toHaveTextContent('正在启动');+ await user.click(screen.getByRole('button', { name: 'Run task now' }));+ expect(screen.getByRole('button', { name: 'Run task now' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Pause task' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Edit task' })).toBeDisabled();+ expect(screen.getByRole('status', { name: 'Task operation status' })).toHaveTextContent('Starting');runNow.resolve();- expect(await screen.findByRole('button', { name: '立即运行任务' })).toBeEnabled();+ expect(await screen.findByRole('button', { name: 'Run task now' })).toBeEnabled();- await user.click(screen.getByRole('button', { name: '暂停任务' }));+ await user.click(screen.getByRole('button', { name: 'Pause task' }));expect(updateSchedule).toHaveBeenCalledWith('schedule-1', { enabled: false });expect(onScheduleChanged).toHaveBeenCalledWith(expect.objectContaining({id: 'schedule-1',@@ -72,17 +72,17 @@ describe('ScheduleThreadHeader', () => {service: createService({ getSchedule, updateSchedule }),});- await user.click(screen.getByRole('button', { name: '编辑任务' }));+ await user.click(screen.getByRole('button', { name: 'Edit task' }));expect(getSchedule).toHaveBeenCalledWith('schedule-1');- const dialog = await screen.findByRole('dialog', { name: '编辑任务 每日总结' });+ const dialog = await screen.findByRole('dialog', { name: 'Edit task 每日总结' });expect(dialog).toBeInTheDocument();- expect(screen.getByText('编辑定时任务')).toBeInTheDocument();+ expect(screen.getByText('Edit scheduled task')).toBeInTheDocument();expect(dialog.parentElement).toHaveClass('schedule-thread-editor-backdrop');expect(dialog.parentElement?.parentElement).toBe(document.body);- await user.clear(screen.getByLabelText('定时任务标题'));- await user.type(screen.getByLabelText('定时任务标题'), '每周总结');- await user.click(screen.getByRole('button', { name: '保存更改' }));+ await user.clear(screen.getByLabelText('Scheduled task title'));+ await user.type(screen.getByLabelText('Scheduled task title'), '每周总结');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));expect(updateSchedule).toHaveBeenCalledWith('schedule-1', expect.objectContaining({name: '每周总结',@@ -92,7 +92,7 @@ describe('ScheduleThreadHeader', () => {expect(onScheduleChanged).toHaveBeenCalledWith(expect.objectContaining({name: '每周总结',}));- expect(screen.queryByRole('dialog', { name: '编辑任务 每日总结' })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Edit task 每日总结' })).not.toBeInTheDocument();});it('restores a paused task and settles errors without leaving actions disabled', async () => {@@ -106,14 +106,14 @@ describe('ScheduleThreadHeader', () => {service: createService({ updateSchedule }),});- await user.click(screen.getByRole('button', { name: '恢复任务' }));+ await user.click(screen.getByRole('button', { name: 'Resume task' }));expect(updateSchedule).toHaveBeenCalledWith('schedule-1', { enabled: true });const issue = await screen.findByRole('alert');- expect(issue).toHaveTextContent('无法更新任务状态,请重试。');+ expect(issue).toHaveTextContent('Could not update task status. Try again.');expect(issue).not.toHaveTextContent(/诊断编号:OC-/);expect(issue).not.toHaveTextContent('更新失败');- expect(screen.getByRole('button', { name: '恢复任务' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Resume task' })).toBeEnabled();});});diff --git a/apps/web/src/features/schedules/ScheduleThreadHeader.tsx b/apps/web/src/features/schedules/ScheduleThreadHeader.tsxindex 301e7760..8324f239 100644--- a/apps/web/src/features/schedules/ScheduleThreadHeader.tsx+++ b/apps/web/src/features/schedules/ScheduleThreadHeader.tsx@@ -95,7 +95,7 @@ export function ScheduleThreadHeader(props: {await props.onRunNow(props.schedule);pageIssues.resolveOperation('schedule-thread.run-now');} catch (error) {- pageIssues.captureOperationFailure('schedule-thread.run-now', error, '无法立即运行任务,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('schedule-thread.run-now', error, 'Could not run the task now. Try again.', { retryable: true });} finally {setOperation(undefined);}@@ -111,7 +111,7 @@ export function ScheduleThreadHeader(props: {props.onScheduleChanged(updated);pageIssues.resolveOperation('schedule-thread.toggle');} catch (error) {- pageIssues.captureOperationFailure('schedule-thread.toggle', error, '无法更新任务状态,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('schedule-thread.toggle', error, 'Could not update task status. Try again.', { retryable: true });} finally {setOperation(undefined);}@@ -128,7 +128,7 @@ export function ScheduleThreadHeader(props: {setEditorValues(scheduleResponseToEditorValues(schedule));pageIssues.resolveOperation('schedule-thread.load-editor');} catch (error) {- pageIssues.captureOperationFailure('schedule-thread.load-editor', error, '无法加载计划详情,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('schedule-thread.load-editor', error, 'Could not load schedule details. Try again.', { retryable: true });} finally {setOperation(undefined);}@@ -152,7 +152,7 @@ export function ScheduleThreadHeader(props: {pageIssues.resolveOperation('schedule-thread.save-editor');closeEditor();} catch (error) {- pageIssues.captureOperationFailure('schedule-thread.save-editor', error, '无法保存计划任务,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('schedule-thread.save-editor', error, 'Could not save the scheduled task. Try again.', { retryable: true });} finally {setOperation(undefined);}@@ -168,13 +168,13 @@ export function ScheduleThreadHeader(props: {return (<>- <section className="schedule-thread-header" aria-label="任务管理">+ <section className="schedule-thread-header" aria-label="Task management"><div className="schedule-thread-main"><spanclassName="schedule-thread-status"data-status={props.status}role="status"- aria-label="任务状态"+ aria-label="Task status"><StatusIconclassName={props.status === 'running' ? 'schedule-thread-spinner' : undefined}@@ -187,7 +187,7 @@ export function ScheduleThreadHeader(props: {<span className="schedule-thread-next">{props.nextRunLabel}</span>) : null}{operationLabel(operation) ? (- <span className="schedule-thread-operation" role="status" aria-label="任务操作状态">+ <span className="schedule-thread-operation" role="status" aria-label="Task operation status"><LoaderCircle className="schedule-thread-spinner" size={14} aria-hidden="true" />{operationLabel(operation)}</span>@@ -196,8 +196,8 @@ export function ScheduleThreadHeader(props: {<div className="schedule-thread-actions"><buttontype="button"- aria-label="立即运行任务"- title="立即运行"+ aria-label="Run task now"+ title="Run now"disabled={actionsBusy}onClick={() => void runNow()}>@@ -209,8 +209,8 @@ export function ScheduleThreadHeader(props: {</button><buttontype="button"- aria-label={props.schedule.enabled ? '暂停任务' : '恢复任务'}- title={props.schedule.enabled ? '暂停' : '恢复'}+ aria-label={props.schedule.enabled ? 'Pause task' : 'Resume task'}+ title={props.schedule.enabled ? 'Pause' : 'Restore'}disabled={actionsBusy}onClick={() => void toggleEnabled()}>@@ -225,8 +225,8 @@ export function ScheduleThreadHeader(props: {<buttonref={editButtonRef}type="button"- aria-label="编辑任务"- title="编辑"+ aria-label="Edit task"+ title="Edit"disabled={actionsBusy}onClick={() => void openEditor()}>@@ -258,16 +258,16 @@ export function ScheduleThreadHeader(props: {className="schedule-thread-editor-dialog"role="dialog"aria-modal="true"- aria-label={`编辑任务 ${props.schedule.name}`}+ aria-label={`Edit task ${props.schedule.name}`}>{editorValues === undefined ? (<div className="schedule-thread-editor-loading"><header>- <strong>编辑定时任务</strong>+ <strong>Edit scheduled task</strong><buttontype="button"- aria-label="取消编辑"- title="关闭"+ aria-label="Cancel editing"+ title="Close"onClick={closeEditor}><X size={18} aria-hidden="true" />@@ -278,7 +278,7 @@ export function ScheduleThreadHeader(props: {) : (<span role="status"><LoaderCircle className="schedule-thread-spinner" size={17} aria-hidden="true" />- 正在加载计划详情+ Loading schedule details</span>)}</div>@@ -303,28 +303,28 @@ export function ScheduleThreadHeader(props: {function statusVisual(status: ScheduleSidebarTaskStatus) {switch (status) {case 'idle':- return { label: '已启用', icon: CircleCheck };+ return { label: 'Enabled', icon: CircleCheck };case 'running':- return { label: '运行中', icon: LoaderCircle };+ return { label: 'Running', icon: LoaderCircle };case 'queued':- return { label: '已排队', icon: Clock3 };+ return { label: 'Queued', icon: Clock3 };case 'waiting_approval':- return { label: '等待审批', icon: ShieldAlert };+ return { label: 'Awaiting approval', icon: ShieldAlert };case 'failed':- return { label: '上次失败', icon: CircleAlert };+ return { label: 'Last run failed', icon: CircleAlert };case 'paused':- return { label: '已暂停', icon: CirclePause };+ return { label: 'Paused', icon: CirclePause };case 'repair_required':- return { label: '需要修复', icon: Wrench };+ return { label: 'Needs attention', icon: Wrench };}}function operationLabel(operation: Operation | undefined): string | undefined {switch (operation) {case 'run':- return '正在启动';+ return 'Starting';case 'toggle':- return '正在更新';+ return 'Updating';case 'load_editor':case 'save_editor':case undefined:diff --git a/apps/web/src/features/schedules/SchedulesView.test.tsx b/apps/web/src/features/schedules/SchedulesView.test.tsxindex b8f6b7fd..cfdd64b2 100644--- a/apps/web/src/features/schedules/SchedulesView.test.tsx+++ b/apps/web/src/features/schedules/SchedulesView.test.tsx@@ -18,23 +18,23 @@ describe('SchedulesView', () => {const user = userEvent.setup();renderView();- await user.click(await screen.findByRole('button', { name: /创建/ }));+ await user.click(await screen.findByRole('button', { name: /Create/ }));expect(screen.queryByRole('menu')).not.toBeInTheDocument();expect(screen.queryByText('使用 OpenCreator 创建')).not.toBeInTheDocument();- expect(screen.getByRole('dialog', { name: '创建定时任务' })).toBeInTheDocument();- expect(screen.getByText('标题')).toBeInTheDocument();- expect(screen.getByText('描述')).toBeInTheDocument();- expect(screen.getByRole('heading', { name: '执行频率' })).toBeInTheDocument();- expect(screen.getByLabelText('任务内容')).toHaveAttribute(+ expect(screen.getByRole('dialog', { name: 'Create scheduled task' })).toBeInTheDocument();+ expect(screen.getByText('Title')).toBeInTheDocument();+ expect(screen.getByText('Description')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Frequency' })).toBeInTheDocument();+ expect(screen.getByLabelText('Task instructions')).toHaveAttribute('placeholder',- '描述需要帮你做什么...'+ 'Describe what you need done...');- expect(screen.queryByRole('heading', { name: '详情' })).not.toBeInTheDocument();- expect(screen.getByLabelText('定时任务标题')).toHaveAttribute('placeholder', '输入任务标题');- expect(screen.getByRole('heading', { name: '请选择访问权限' })).toBeInTheDocument();- expect(screen.getByText('请选择访问权限').closest('details')).toBeNull();+ expect(screen.queryByRole('heading', { name: 'details' })).not.toBeInTheDocument();+ expect(screen.getByLabelText('Scheduled task title')).toHaveAttribute('placeholder', 'Enter task title');+ expect(screen.getByRole('heading', { name: 'Select access permissions' })).toBeInTheDocument();+ expect(screen.getByText('Select access permissions').closest('details')).toBeNull();await user.keyboard('{Escape}');- expect(screen.queryByRole('dialog', { name: '创建定时任务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Create scheduled task' })).not.toBeInTheDocument();});it('renders a simple searchable list with friendly schedules and status filters', async () => {@@ -56,18 +56,18 @@ describe('SchedulesView', () => {}),});- expect(await screen.findByRole('heading', { name: '定时任务' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'Scheduled tasks' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: '每日总结' })).toBeInTheDocument();- expect(screen.getByText('每天 18:00')).toBeInTheDocument();+ expect(screen.getByText('Daily at 18:00')).toBeInTheDocument();expect(screen.queryByText('0 18 * * *')).not.toBeInTheDocument();- expect(screen.getByText('建议')).toBeInTheDocument();+ expect(screen.getByText('Suggestions')).toBeInTheDocument();- await user.type(screen.getByRole('searchbox', { name: '搜索定时任务' }), '每周');+ await user.type(screen.getByRole('searchbox', { name: 'Search scheduled tasks' }), '每周');expect(screen.getByRole('heading', { name: '每周回顾' })).toBeInTheDocument();expect(screen.queryByRole('heading', { name: '每日总结' })).not.toBeInTheDocument();- await user.clear(screen.getByRole('searchbox', { name: '搜索定时任务' }));- await user.click(screen.getByRole('button', { name: '已暂停' }));+ await user.clear(screen.getByRole('searchbox', { name: 'Search scheduled tasks' }));+ await user.click(screen.getByRole('button', { name: 'Paused' }));expect(screen.getByRole('heading', { name: '每周回顾' })).toBeInTheDocument();expect(screen.queryByRole('heading', { name: '每日总结' })).not.toBeInTheDocument();});@@ -106,21 +106,21 @@ describe('SchedulesView', () => {await openCreateEditor(user);expect(screen.queryByLabelText('Cron 表达式')).not.toBeInTheDocument();expect(screen.queryByLabelText('运行配置')).not.toBeInTheDocument();- expect(screen.queryByLabelText('项目')).not.toBeInTheDocument();- expect(screen.queryByLabelText('模型')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Project')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Model')).not.toBeInTheDocument();expect(screen.queryByLabelText('推理')).not.toBeInTheDocument();expect(screen.queryByText('运行于')).not.toBeInTheDocument();expect(screen.queryByLabelText('时区')).not.toBeInTheDocument();expect(screen.queryByLabelText('最长运行分钟')).not.toBeInTheDocument();expect(screen.queryByLabelText('任务重叠时')).not.toBeInTheDocument();- await user.type(screen.getByLabelText('定时任务标题'), '每日简报');- await user.type(screen.getByLabelText('任务内容'), '总结今天的项目进展');- await user.selectOptions(screen.getByLabelText('重复'), 'weekdays');- await user.click(screen.getByRole('button', { name: '执行时间' }));- expect(screen.getByRole('dialog', { name: '选择执行时间' })).toBeInTheDocument();- await user.click(screen.getByRole('option', { name: '小时 08' }));- await user.click(screen.getByRole('option', { name: '分钟 00' }));- await user.click(screen.getByRole('button', { name: '创建任务' }));+ await user.type(screen.getByLabelText('Scheduled task title'), '每日简报');+ await user.type(screen.getByLabelText('Task instructions'), '总结今天的项目进展');+ await user.selectOptions(screen.getByLabelText('Repeat'), 'weekdays');+ await user.click(screen.getByRole('button', { name: 'Run time' }));+ expect(screen.getByRole('dialog', { name: 'Select run time' })).toBeInTheDocument();+ await user.click(screen.getByRole('option', { name: 'hours 08' }));+ await user.click(screen.getByRole('option', { name: 'minutes 00' }));+ await user.click(screen.getByRole('button', { name: 'Create task' }));expect(createSchedule).toHaveBeenCalledWith({name: '每日简报',@@ -140,7 +140,7 @@ describe('SchedulesView', () => {threadId: 'thread-created'}));expect(onOpenTask).not.toHaveBeenCalled();- expect(screen.queryByRole('dialog', { name: '创建定时任务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Create scheduled task' })).not.toBeInTheDocument();});it('prefills suggested tasks without creating them immediately', async () => {@@ -153,9 +153,9 @@ describe('SchedulesView', () => {}),});- await user.click(await screen.findByRole('button', { name: /每日简报/ }));- expect(screen.getByLabelText('定时任务标题')).toHaveValue('每日简报');- expect(screen.getByLabelText('重复')).toHaveValue('weekdays');+ await user.click(await screen.findByRole('button', { name: /Daily briefing/ }));+ expect(screen.getByLabelText('Scheduled task title')).toHaveValue('Daily briefing');+ expect(screen.getByLabelText('Repeat')).toHaveValue('weekdays');expect(createSchedule).not.toHaveBeenCalled();});@@ -176,18 +176,18 @@ describe('SchedulesView', () => {});await openCreateEditor(user);- await user.click(screen.getByRole('button', { name: '创建任务' }));- expect(screen.getByText('请输入任务标题')).toBeInTheDocument();- expect(screen.getByText('请描述需要帮你做什么')).toBeInTheDocument();- expect(screen.getByLabelText('定时任务标题')).toHaveFocus();+ await user.click(screen.getByRole('button', { name: 'Create task' }));+ expect(screen.getByText('Enter a task title')).toBeInTheDocument();+ expect(screen.getByText('Describe what you need done')).toBeInTheDocument();+ expect(screen.getByLabelText('Scheduled task title')).toHaveFocus();expect(createSchedule).not.toHaveBeenCalled();- await user.type(screen.getByLabelText('定时任务标题'), '目录检查');- await user.type(screen.getByLabelText('任务内容'), '检查项目状态');- await user.click(screen.getByRole('button', { name: '创建任务' }));+ await user.type(screen.getByLabelText('Scheduled task title'), '目录检查');+ await user.type(screen.getByLabelText('Task instructions'), '检查项目状态');+ await user.click(screen.getByRole('button', { name: 'Create task' }));- expect(await screen.findByRole('alert')).toHaveTextContent('项目目录不存在或无法访问');- expect(within(screen.getByRole('dialog')).queryByText('项目目录不存在或无法访问')).not.toBeInTheDocument();+ expect(await screen.findByRole('alert')).toHaveTextContent('The project directory is missing or inaccessible');+ expect(within(screen.getByRole('dialog')).queryByText('The project directory is missing or inaccessible')).not.toBeInTheDocument();});it('loads full details, preserves legacy schedules, and saves advanced edits', async () => {@@ -214,14 +214,14 @@ describe('SchedulesView', () => {}),});- await user.click(await screen.findByRole('button', { name: '编辑每日总结' }));- expect(await screen.findByText('编辑定时任务')).toBeInTheDocument();+ await user.click(await screen.findByRole('button', { name: 'Edit 每日总结' }));+ expect(await screen.findByText('Edit scheduled task')).toBeInTheDocument();expect(await screen.findByDisplayValue('完整的每日总结执行指令')).toBeInTheDocument();- expect(screen.getByLabelText('重复')).toHaveValue('advanced');- expect(screen.getByText(/旧版高级计划/)).toBeInTheDocument();- await user.clear(screen.getByLabelText('定时任务标题'));- await user.type(screen.getByLabelText('定时任务标题'), '每月总结');- await user.click(screen.getByRole('button', { name: '保存更改' }));+ expect(screen.getByLabelText('Repeat')).toHaveValue('advanced');+ expect(screen.getByText(/legacy advanced schedule/)).toBeInTheDocument();+ await user.clear(screen.getByLabelText('Scheduled task title'));+ await user.type(screen.getByLabelText('Scheduled task title'), '每月总结');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));expect(updateSchedule).toHaveBeenCalledWith('schedule-1', expect.objectContaining({name: '每月总结',@@ -263,10 +263,10 @@ describe('SchedulesView', () => {}),});- await user.click(await screen.findByRole('button', { name: '打开任务会话 每日总结' }));+ await user.click(await screen.findByRole('button', { name: 'Open task conversation 每日总结' }));expect(onOpenTask).toHaveBeenLastCalledWith('thread-schedule-1');- await user.click(screen.getByRole('button', { name: '查看上次运行' }));+ await user.click(screen.getByRole('button', { name: 'View last run' }));expect(onOpenTask).toHaveBeenLastCalledWith('thread-schedule-1', 'run-previous');});@@ -291,7 +291,7 @@ describe('SchedulesView', () => {}),});- const toggle = await screen.findByRole('switch', { name: '暂停每日总结' });+ const toggle = await screen.findByRole('switch', { name: 'Pause 每日总结' });await user.click(toggle);expect(updateSchedule).toHaveBeenCalledWith('schedule-1', { enabled: false });expect(toggle).toHaveAttribute('aria-checked', 'false');@@ -300,13 +300,13 @@ describe('SchedulesView', () => {enabled: false}));- await user.click(screen.getByRole('button', { name: '立即运行每日总结' }));+ await user.click(screen.getByRole('button', { name: 'Run now 每日总结' }));expect(onRunNow).toHaveBeenCalledWith(expect.objectContaining({id: 'schedule-1',threadId: 'thread-schedule-1'}));- await user.click(screen.getByRole('button', { name: '删除每日总结' }));+ await user.click(screen.getByRole('button', { name: 'Delete 每日总结' }));expect(deleteSchedule).toHaveBeenCalledWith('schedule-1');expect(onScheduleDeleted).toHaveBeenCalledWith(expect.objectContaining({id: 'schedule-1',@@ -317,7 +317,7 @@ describe('SchedulesView', () => {it('shows disconnected and load error states', async () => {const { rerender } = renderView({ connected: false, service: null });- expect(screen.getByText('连接本地运行内核后可以创建和管理任务')).toBeInTheDocument();+ expect(screen.getByText('Connect the local Runtime to create and manage tasks')).toBeInTheDocument();rerender(createView({service: createService({@@ -326,13 +326,13 @@ describe('SchedulesView', () => {}),}),}));- expect(await screen.findByRole('alert')).toHaveTextContent('无法加载定时任务');- expect(screen.getByRole('button', { name: '重新加载' })).toBeInTheDocument();+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load scheduled tasks');+ expect(screen.getByRole('button', { name: 'Reload' })).toBeInTheDocument();});});async function openCreateEditor(user: ReturnType<typeof userEvent.setup>) {- await user.click(await screen.findByRole('button', { name: /创建/ }));+ await user.click(await screen.findByRole('button', { name: /Create/ }));}function renderView(overrides: Partial<Parameters<typeof createView>[0]> = {}) {diff --git a/apps/web/src/features/schedules/SchedulesView.tsx b/apps/web/src/features/schedules/SchedulesView.tsxindex ee69d475..8c025390 100644--- a/apps/web/src/features/schedules/SchedulesView.tsx+++ b/apps/web/src/features/schedules/SchedulesView.tsx@@ -124,8 +124,8 @@ export function SchedulesView(props: SchedulesViewProps) {pageIssues.resolveOperation('schedules.load');} catch (cause) {if (generation !== requestGenerationRef.current) return;- setLoadError('无法加载定时任务');- pageIssues.captureOperationFailure('schedules.load', cause, '无法加载定时任务,请重试。', { retryable: true });+ setLoadError('Could not load scheduled tasks');+ pageIssues.captureOperationFailure('schedules.load', cause, 'Could not load scheduled tasks. Try again.', { retryable: true });} finally {if (generation === requestGenerationRef.current && showLoading) setLoading(false);}@@ -194,8 +194,8 @@ export function SchedulesView(props: SchedulesViewProps) {<section className="schedules-view"><div className="schedules-state"><CalendarClock size={28} aria-hidden="true" />- <h2>已安排功能暂不可用</h2>- <p>连接本地运行内核后可以创建和管理任务</p>+ <h2>Scheduled tasks are unavailable</h2>+ <p>Connect the local Runtime to create and manage tasks</p></div></section>);@@ -238,7 +238,7 @@ export function SchedulesView(props: SchedulesViewProps) {: current));} catch (error) {- pageIssues.captureOperationFailure('schedules.load-detail', error, '无法加载计划详情,请重试。');+ pageIssues.captureOperationFailure('schedules.load-detail', error, 'Could not load schedule details. Try again.');setEditor(current => (current?.mode === 'edit' && current.scheduleId === schedule.id? { ...current, loading: false }@@ -269,7 +269,7 @@ export function SchedulesView(props: SchedulesViewProps) {} catch (error) {const mapped = mapScheduleError(error);setEditorErrors({ ...mapped, form: undefined });- pageIssues.captureOperationFailure('schedules.save', error, mapped.form ?? '无法保存计划任务,请检查后重试。');+ pageIssues.captureOperationFailure('schedules.save', error, mapped.form ?? 'Could not save the scheduled task. Check the settings and try again.');} finally {setSaving(false);}@@ -287,7 +287,7 @@ export function SchedulesView(props: SchedulesViewProps) {pageIssues.resolveOperation('schedules.toggle');} catch (error) {setSchedules(current => replaceSchedule(current, schedule));- pageIssues.captureOperationFailure('schedules.toggle', error, '无法更新任务状态,请重试。');+ pageIssues.captureOperationFailure('schedules.toggle', error, 'Could not update task status. Try again.');} finally {setBusy(schedule.id, false);}@@ -300,7 +300,7 @@ export function SchedulesView(props: SchedulesViewProps) {await props.onRunNow(schedule);pageIssues.resolveOperation('schedules.run-now');} catch (error) {- pageIssues.captureOperationFailure('schedules.run-now', error, '无法立即运行任务,请重试。');+ pageIssues.captureOperationFailure('schedules.run-now', error, 'Could not run the task now. Try again.');} finally {setBusy(schedule.id, false);}@@ -310,9 +310,9 @@ export function SchedulesView(props: SchedulesViewProps) {if (props.service === null || busyIds.has(schedule.id)) return;const confirmed = props.confirmDelete?.(schedule)?? await confirm({- title: '删除任务',- description: `确认删除“${schedule.name}”?删除后无法恢复。`,- confirmLabel: '删除任务',+ title: 'Delete task',+ description: `Delete "${schedule.name}"? This cannot be undone.`,+ confirmLabel: 'Delete task',destructive: true});if (!confirmed) return;@@ -326,7 +326,7 @@ export function SchedulesView(props: SchedulesViewProps) {setEditor(undefined);}} catch (error) {- pageIssues.captureOperationFailure('schedules.delete', error, '无法删除任务,请重试。');+ pageIssues.captureOperationFailure('schedules.delete', error, 'Could not delete the task. Try again.');} finally {setBusy(schedule.id, false);}@@ -353,8 +353,8 @@ export function SchedulesView(props: SchedulesViewProps) {<><header className="schedules-view__header"><div>- <h1>定时任务</h1>- <p>安排任务、设置提醒或定期处理工作</p>+ <h1>Scheduled tasks</h1>+ <p>Schedule tasks, set reminders, or run recurring work</p></div><buttonclassName="schedule-button schedule-button--secondary"@@ -362,7 +362,7 @@ export function SchedulesView(props: SchedulesViewProps) {onClick={() => openCreateEditor('manual')}><Plus size={16} />- 创建+ Create</button></header><IssueList@@ -376,15 +376,15 @@ export function SchedulesView(props: SchedulesViewProps) {<label className="schedules-search"><Search size={17} aria-hidden="true" /><input- aria-label="搜索定时任务"+ aria-label="Search scheduled tasks"type="search"value={query}- placeholder="搜索定时任务"+ placeholder="Search scheduled tasks"onChange={event => setQuery(event.target.value)}/></label>- <div className="schedules-filters" role="group" aria-label="任务状态">+ <div className="schedules-filters" role="group" aria-label="Task status">{scheduleFilterOptions.map(option => (<buttonaria-pressed={filter === option.value}@@ -401,30 +401,30 @@ export function SchedulesView(props: SchedulesViewProps) {{loading ? (<div className="schedules-state" role="status"><LoaderCircle size={24} className="schedule-spin" />- 正在加载定时任务+ Loading scheduled tasks</div>) : loadError ? (<div className="schedules-state" role="status">- <p>当前没有可显示的任务。</p>+ <p>No tasks to display.</p><buttonclassName="schedule-button schedule-button--secondary"type="button"onClick={() => void loadSchedules(true)}><RefreshCw size={16} />- 重新加载+ Reload</button></div>) : filteredSchedules.length === 0 ? (<div className="schedules-empty"><CalendarClock size={24} aria-hidden="true" /><strong>- {schedules.length === 0 ? '还没有定时任务' : '没有找到匹配的任务'}+ {schedules.length === 0 ? 'No scheduled tasks yet' : 'No matching tasks'}</strong><span>{schedules.length === 0- ? '从建议开始,或者创建一个自己的任务'- : '换个关键词或状态筛选试试'}+ ? 'Start from a suggestion or create a task'+ : 'Try another keyword or status filter'}</span></div>) : (@@ -446,7 +446,7 @@ export function SchedulesView(props: SchedulesViewProps) {<buttonclassName="schedule-row__title-button"type="button"- aria-label={`打开任务会话 ${schedule.name}`}+ aria-label={`Open task conversation ${schedule.name}`}onClick={() => props.onOpenTask(schedule.threadId)}>{schedule.name}@@ -463,8 +463,8 @@ export function SchedulesView(props: SchedulesViewProps) {<p>{schedule.promptPreviewRedacted}</p><div className="schedule-row__meta"><span>{formatScheduleFrequency(schedule.cron)}</span>- {nextRun ? <span>下次 {nextRun}</span> : null}- {!schedule.enabled ? <span>已暂停</span> : null}+ {nextRun ? <span>Next {nextRun}</span> : null}+ {!schedule.enabled ? <span>Paused</span> : null}</div>{schedule.lastRunId ? (<button@@ -476,7 +476,7 @@ export function SchedulesView(props: SchedulesViewProps) {)}><ExternalLink size={14} />- 查看上次运行+ View last run</button>) : null}</div>@@ -486,15 +486,15 @@ export function SchedulesView(props: SchedulesViewProps) {type="button"role="switch"aria-checked={schedule.enabled}- aria-label={`${schedule.enabled ? '暂停' : '启用'}${schedule.name}`}+ aria-label={`${schedule.enabled ? 'Pause' : 'Enable'} ${schedule.name}`}disabled={busy}onClick={() => void toggleSchedule(schedule)}/><buttonclassName="schedule-icon-button"type="button"- aria-label={`立即运行${schedule.name}`}- title="立即运行"+ aria-label={`Run now ${schedule.name}`}+ title="Run now"disabled={busy}onClick={() => void runSchedule(schedule)}>@@ -507,8 +507,8 @@ export function SchedulesView(props: SchedulesViewProps) {<buttonclassName="schedule-icon-button"type="button"- aria-label={`编辑${schedule.name}`}- title="编辑"+ aria-label={`Edit ${schedule.name}`}+ title="Edit"disabled={busy}onClick={() => void openEditEditor(schedule)}>@@ -517,8 +517,8 @@ export function SchedulesView(props: SchedulesViewProps) {<buttonclassName="schedule-icon-button"type="button"- aria-label={`删除${schedule.name}`}- title="删除"+ aria-label={`Delete ${schedule.name}`}+ title="Remove"disabled={busy}onClick={() => void deleteSchedule(schedule)}>@@ -533,7 +533,7 @@ export function SchedulesView(props: SchedulesViewProps) {{query.trim().length === 0 && filter === 'all' ? (<section className="schedule-suggestions" aria-labelledby="schedule-suggestions-heading">- <h2 id="schedule-suggestions-heading">建议</h2>+ <h2 id="schedule-suggestions-heading">Suggestions</h2><div className="schedule-suggestion-list">{scheduleSuggestions.map(suggestion => {const Icon = suggestion.icon;@@ -573,7 +573,7 @@ export function SchedulesView(props: SchedulesViewProps) {}}><div- aria-label={editor.mode === 'create' ? '创建定时任务' : '编辑定时任务'}+ aria-label={editor.mode === 'create' ? 'Create scheduled task' : 'Edit scheduled task'}aria-modal="true"className="schedule-editor-dialog"role="dialog"@@ -624,16 +624,16 @@ function mapScheduleError(error: unknown): ScheduleEditorErrors {const message = error instanceof Error ? error.message : '';const normalized = message.toLowerCase();if (normalized.includes('cwd') || normalized.includes('directory')) {- return { form: '项目目录不存在或无法访问' };+ return { form: 'The project directory is missing or inaccessible' };}- if (normalized.includes('cron')) return { frequency: '执行频率无效' };- if (normalized.includes('timezone')) return { timezone: '时区无效' };+ if (normalized.includes('cron')) return { frequency: 'Invalid frequency' };+ if (normalized.includes('timezone')) return { timezone: 'Invalid time zone' };if (normalized.includes('profile')) {- return { form: '当前项目的运行配置不可用,请先在项目设置中修复' };+ return { form: 'This project\'s Runtime configuration is unavailable. Fix it in project settings first.' };}- if (normalized.includes('timeout')) return { timeoutMinutes: '最长运行时间无效' };+ if (normalized.includes('timeout')) return { timeoutMinutes: 'Invalid maximum run time' };if (error instanceof ApiClientError) return { form: error.message };- return { form: '无法保存计划任务' };+ return { form: 'Could not save the scheduled task' };}function upsertSchedule(@@ -655,26 +655,26 @@ function replaceSchedule(function lastStatusLabel(status: ScheduleResponse['lastStatus']): string {switch (status) {case 'succeeded':- return '上次成功';+ return 'Last run succeeded';case 'failed':- return '上次失败';+ return 'Last run failed';case 'canceled':- return '上次取消';+ return 'Last run canceled';case 'running':- return '正在运行';+ return 'Running';case 'queued':- return '等待运行';+ return 'Waiting to run';case 'skipped':- return '上次跳过';+ return 'Last run skipped';default:- return '等待首次运行';+ return 'Waiting for first run';}}const scheduleFilterOptions: Array<{ value: ScheduleFilter; label: string }> = [- { value: 'all', label: '全部' },- { value: 'enabled', label: '已启用' },- { value: 'paused', label: '已暂停' },+ { value: 'all', label: 'All' },+ { value: 'enabled', label: 'Enabled' },+ { value: 'paused', label: 'Paused' },];const scheduleSuggestions: Array<{@@ -687,29 +687,29 @@ const scheduleSuggestions: Array<{tone: 'blue' | 'violet' | 'green';}> = [{- name: '每日简报',+ name: 'Daily briefing',prompt: '结合当前项目内容,总结昨天的进展、未完成事项和今天最重要的三件事。',frequency: { repeat: 'weekdays', time: '08:00', days: [] },- scheduleLabel: '工作日 08:00',- description: '汇总项目进展、未完成事项和当天优先级',+ scheduleLabel: 'Weekdays at 08:00',+ description: 'Summarize project progress, open items, and today\'s priorities',icon: Bell,tone: 'blue',},{- name: '每周回顾',+ name: 'Weekly review',prompt: '整理本周完成的工作、遇到的问题、关键决定和下周计划。',frequency: { repeat: 'weekly', time: '16:00', days: [5] },- scheduleLabel: '每周五 16:00',- description: '每周五整理工作进展并形成清晰的状态更新',+ scheduleLabel: 'Fridays at 16:00',+ description: 'Review weekly progress and prepare a status update every Friday',icon: PencilLine,tone: 'violet',},{- name: '跟进监控',+ name: 'Follow-up monitor',prompt: '检查最近的项目和日历活动,列出需要继续跟进或可能阻塞的事项。',frequency: { repeat: 'weekdays', time: '09:00', days: [] },- scheduleLabel: '工作日 09:00',- description: '查看最近活动并标记需要持续关注的事项',+ scheduleLabel: 'Weekdays at 09:00',+ description: 'Review recent activity and flag items needing follow-up',icon: MoreHorizontal,tone: 'green',},diff --git a/apps/web/src/features/schedules/schedule-frequency.test.ts b/apps/web/src/features/schedules/schedule-frequency.test.tsindex dd4d5b62..accfab70 100644--- a/apps/web/src/features/schedules/schedule-frequency.test.ts+++ b/apps/web/src/features/schedules/schedule-frequency.test.ts@@ -44,10 +44,10 @@ describe('schedule frequency', () => {});it('formats schedules in language ordinary users can understand', () => {- expect(formatScheduleFrequency('15 * * * *')).toBe('每小时第 15 分钟');- expect(formatScheduleFrequency('0 8 * * 1-5')).toBe('工作日 08:00');- expect(formatScheduleFrequency('0 16 * * 5')).toBe('每周五 16:00');- expect(formatScheduleFrequency('0 10 * * 1,3,5')).toBe('每周一、周三、周五 10:00');- expect(formatScheduleFrequency('0 9 1 * *')).toBe('自定义计划');+ expect(formatScheduleFrequency('15 * * * *')).toBe('Every hour at minute 15');+ expect(formatScheduleFrequency('0 8 * * 1-5')).toBe('Weekdays at 08:00');+ expect(formatScheduleFrequency('0 16 * * 5')).toBe('Every Friday at 16:00');+ expect(formatScheduleFrequency('0 10 * * 1,3,5')).toBe('Every Monday, Wednesday, Friday at 10:00');+ expect(formatScheduleFrequency('0 9 1 * *')).toBe('Custom schedule');});});diff --git a/apps/web/src/features/schedules/schedule-frequency.ts b/apps/web/src/features/schedules/schedule-frequency.tsindex 6786879f..8ffb0a44 100644--- a/apps/web/src/features/schedules/schedule-frequency.ts+++ b/apps/web/src/features/schedules/schedule-frequency.ts@@ -20,28 +20,28 @@ export const defaultScheduleFrequency: ScheduleFrequency = {};export const scheduleRepeatOptions: Array<{ value: ScheduleRepeat; label: string }> = [- { value: 'hourly', label: '每小时' },- { value: 'daily', label: '每天' },- { value: 'weekdays', label: '工作日' },- { value: 'weekly', label: '每周' },- { value: 'custom', label: '自定义' },+ { value: 'hourly', label: 'Hourly' },+ { value: 'daily', label: 'Daily' },+ { value: 'weekdays', label: 'Weekdays' },+ { value: 'weekly', label: 'Weekly' },+ { value: 'custom', label: 'Custom' },];export const scheduleWeekdays = [- { value: 1, shortLabel: '一', label: '周一' },- { value: 2, shortLabel: '二', label: '周二' },- { value: 3, shortLabel: '三', label: '周三' },- { value: 4, shortLabel: '四', label: '周四' },- { value: 5, shortLabel: '五', label: '周五' },- { value: 6, shortLabel: '六', label: '周六' },- { value: 0, shortLabel: '日', label: '周日' },+ { value: 1, shortLabel: 'Mon', label: 'Monday' },+ { value: 2, shortLabel: 'Tue', label: 'Tuesday' },+ { value: 3, shortLabel: 'Wed', label: 'Wednesday' },+ { value: 4, shortLabel: 'Thu', label: 'Thursday' },+ { value: 5, shortLabel: 'Fri', label: 'Friday' },+ { value: 6, shortLabel: 'Sat', label: 'Saturday' },+ { value: 0, shortLabel: 'Sun', label: 'Sunday' },] as const;export function scheduleFrequencyToCron(frequency: ScheduleFrequency): string {if (frequency.repeat === 'advanced') {const legacyCron = frequency.legacyCron?.trim();if (legacyCron === undefined || legacyCron.length === 0) {- throw new Error('高级计划缺少原始表达式');+ throw new Error('The advanced schedule is missing its original expression');}return legacyCron;}@@ -52,7 +52,7 @@ export function scheduleFrequencyToCron(frequency: ScheduleFrequency): string {if (frequency.repeat === 'weekdays') return `${minute} ${hour} * * 1-5`;const days = normalizeDays(frequency.days);- if (days.length === 0) throw new Error('请至少选择一天');+ if (days.length === 0) throw new Error('Select at least one day');if (frequency.repeat === 'weekly') {return `${minute} ${hour} * * ${days[0]}`;}@@ -98,16 +98,16 @@ export function formatScheduleFrequency(cron: string): string {const frequency = cronToScheduleFrequency(cron);switch (frequency.repeat) {case 'hourly':- return `每小时第 ${Number(frequency.time.slice(3, 5))} 分钟`;+ return `Every hour at minute ${Number(frequency.time.slice(3, 5))}`;case 'daily':- return `每天 ${frequency.time}`;+ return `Daily at ${frequency.time}`;case 'weekdays':- return `工作日 ${frequency.time}`;+ return `Weekdays at ${frequency.time}`;case 'weekly':case 'custom':- return `每${frequency.days.map(day => weekdayLabel(day)).join('、')} ${frequency.time}`;+ return `Every ${frequency.days.map(day => weekdayLabel(day)).join(', ')} at ${frequency.time}`;case 'advanced':- return '自定义计划';+ return 'Custom schedule';}}@@ -118,7 +118,7 @@ export function formatScheduleNextRun(if (value === null || value === undefined) return undefined;const date = new Date(value);if (!Number.isFinite(date.getTime())) return undefined;- return new Intl.DateTimeFormat('zh-CN', {+ return new Intl.DateTimeFormat('en-US', {timeZone: timezone,month: 'numeric',day: 'numeric',@@ -131,14 +131,14 @@ export function formatScheduleNextRun(function parseTime(value: string): { hour: number; minute: number } {const match = /^(\d{2}):(\d{2})$/.exec(value.trim());- if (match === null) throw new Error('请选择有效时间');+ if (match === null) throw new Error('Select a valid time');const hour = Number(match[1]);const minute = Number(match[2]);if (!Number.isInteger(hour) || hour < 0 || hour > 23) {- throw new Error('请选择有效时间');+ throw new Error('Select a valid time');}if (!Number.isInteger(minute) || minute < 0 || minute > 59) {- throw new Error('请选择有效时间');+ throw new Error('Select a valid time');}return { hour, minute };}@@ -184,7 +184,7 @@ function advancedFrequency(cron: string): ScheduleFrequency {}function weekdayLabel(day: number): string {- return scheduleWeekdays.find(option => option.value === day)?.label ?? '周一';+ return scheduleWeekdays.find(option => option.value === day)?.label ?? 'Monday';}function padTime(value: number): string {diff --git a/apps/web/src/features/schedules/schedule-task-model.test.ts b/apps/web/src/features/schedules/schedule-task-model.test.tsindex 9a3e6b2e..42aca80b 100644--- a/apps/web/src/features/schedules/schedule-task-model.test.ts+++ b/apps/web/src/features/schedules/schedule-task-model.test.ts@@ -44,7 +44,7 @@ describe('schedule task model', () => {threadId: null,bindingStatus: 'repair_required',bindingIssue: 'missing_thread_id',- statusMessage: '任务会话需要修复',+ statusMessage: 'The task conversation needs attention',currentRunStatus: null})]);@@ -62,7 +62,7 @@ describe('schedule task model', () => {threadId: 'thread-task',bindingStatus: 'repair_required',bindingIssue: 'thread_not_found',- statusMessage: '任务会话需要修复'+ statusMessage: 'The task conversation needs attention'})]);});diff --git a/apps/web/src/features/schedules/schedule-task-model.ts b/apps/web/src/features/schedules/schedule-task-model.tsindex e501ac64..e489f3b7 100644--- a/apps/web/src/features/schedules/schedule-task-model.ts+++ b/apps/web/src/features/schedules/schedule-task-model.ts@@ -34,7 +34,7 @@ export type ScheduleTaskSummary =threadId: string | null;bindingStatus: 'repair_required';bindingIssue: ScheduleTaskBindingIssue;- statusMessage: '任务会话需要修复';+ statusMessage: 'The task conversation needs attention';currentRunStatus: null;});@@ -100,7 +100,7 @@ function repairSummary(threadId,bindingStatus: 'repair_required',bindingIssue,- statusMessage: '任务会话需要修复',+ statusMessage: 'The task conversation needs attention',currentRunStatus: null};}diff --git a/apps/web/src/features/settings/CleanupSettingsView.test.tsx b/apps/web/src/features/settings/CleanupSettingsView.test.tsxindex e4f94dd8..904b03f9 100644--- a/apps/web/src/features/settings/CleanupSettingsView.test.tsx+++ b/apps/web/src/features/settings/CleanupSettingsView.test.tsx@@ -12,7 +12,7 @@ describe('CleanupSettingsView', () => {render(<CleanupSettingsView connected={false} service={service} />);- expect(screen.getByText('本地服务未连接,无法检查可清理内容。')).toBeInTheDocument();+ expect(screen.getByText('The local Runtime is disconnected. Cleanup candidates cannot be checked.')).toBeInTheDocument();expect(service.previewCleanup).not.toHaveBeenCalled();});@@ -27,10 +27,10 @@ describe('CleanupSettingsView', () => {});render(<CleanupSettingsView connected service={service} />);- fireEvent.click(screen.getByRole('button', { name: '检查可清理内容' }));+ fireEvent.click(screen.getByRole('button', { name: 'Check cleanup candidates' }));- expect(await screen.findByText('没有符合条件的可清理内容')).toBeInTheDocument();- expect(screen.getByText(/运行中、排队中和正在取消的任务不会被清理/)).toBeInTheDocument();+ expect(await screen.findByText('No eligible cleanup candidates')).toBeInTheDocument();+ expect(screen.getByText(/Active, queued, and canceling tasks are retained/)).toBeInTheDocument();expect(service.previewCleanup).toHaveBeenCalledWith(30);});@@ -57,24 +57,24 @@ describe('CleanupSettingsView', () => {});render(<CleanupSettingsView connected service={service} />);- fireEvent.click(screen.getByRole('button', { name: '检查可清理内容' }));+ fireEvent.click(screen.getByRole('button', { name: 'Check cleanup candidates' }));expect(await screen.findByText('/runtime/runs/run_old')).toBeInTheDocument();expect(screen.getByText('/runtime/workspaces/thread_failed')).toBeInTheDocument();expect(screen.getByText('/runtime/workspaces/thread_skipped')).toBeInTheDocument();expect(- screen.getByRole('region', { name: '清理预览' }).querySelector('.cleanup-summary p')- ).toHaveTextContent('3 项 · 4 KB');+ screen.getByRole('region', { name: 'Cleanup preview' }).querySelector('.cleanup-summary p')+ ).toHaveTextContent('3 items | 4 KB');- fireEvent.click(screen.getByRole('button', { name: '删除 3 项' }));- const confirmation = screen.getByRole('region', { name: '确认清理' });- expect(within(confirmation).getByText(/此操作无法撤销/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Remove 3 items' }));+ const confirmation = screen.getByRole('region', { name: 'Confirm cleanup' });+ expect(within(confirmation).getByText(/This cannot be undone/)).toBeInTheDocument();- fireEvent.click(within(confirmation).getByRole('button', { name: '取消' }));+ fireEvent.click(within(confirmation).getByRole('button', { name: 'Cancel' }));expect(service.deleteCleanup).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: '删除 3 项' }));- fireEvent.click(screen.getByRole('button', { name: '确认删除 3 项' }));+ fireEvent.click(screen.getByRole('button', { name: 'Remove 3 items' }));+ fireEvent.click(screen.getByRole('button', { name: 'Confirm deleting 3 items' }));await waitFor(() => {expect(service.deleteCleanup).toHaveBeenCalledWith({@@ -82,9 +82,9 @@ describe('CleanupSettingsView', () => {confirm: true});});- expect(await screen.findByText('已删除 1 项')).toBeInTheDocument();- expect(screen.getByText('删除失败 1 项')).toBeInTheDocument();- expect(screen.getByText('跳过 1 项')).toBeInTheDocument();+ expect(await screen.findByText('Deleted 1 items')).toBeInTheDocument();+ expect(screen.getByText('Deletion failed 1 items')).toBeInTheDocument();+ expect(screen.getByText('Skipped 1 items')).toBeInTheDocument();expect(screen.getByText('permission denied')).toBeInTheDocument();expect(screen.getByText('一个目录在删除前发生变化')).toBeInTheDocument();});diff --git a/apps/web/src/features/settings/CleanupSettingsView.tsx b/apps/web/src/features/settings/CleanupSettingsView.tsxindex 6d87d5b4..fccf5889 100644--- a/apps/web/src/features/settings/CleanupSettingsView.tsx+++ b/apps/web/src/features/settings/CleanupSettingsView.tsx@@ -36,7 +36,7 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {async function loadPreview() {if (!available || phase !== 'idle') return;if (!Number.isInteger(olderThanDays) || olderThanDays <= 0) {- setValidationError('保留天数必须是正整数');+ setValidationError('Retention days must be a positive integer');return;}@@ -52,7 +52,7 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {pageIssues.captureOperationFailure('settings.cleanup.preview',reason,- '无法检查可清理内容,请确认本地服务状态后重试。',+ 'Could not inspect cleanup candidates. Check the local Runtime and try again.',{ retryable: true });} finally {@@ -74,7 +74,7 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {pageIssues.captureOperationFailure('settings.cleanup.delete',reason,- '清理未完成,请检查诊断信息后重试。',+ 'Cleanup did not complete. Check diagnostics and try again.',{ retryable: true, risk: 'overwrite' });} finally {@@ -86,16 +86,16 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {<section className="settings-section settings-management cleanup-settings" aria-labelledby="settings-cleanup-title"><header className="settings-management__header"><div>- <h1 id="settings-cleanup-title">运行数据清理</h1>- <p>先检查候选内容,再确认删除旧 Run 日志和已归档托管工作区。</p>+ <h1 id="settings-cleanup-title">Runtime data cleanup</h1>+ <p>Review candidates before deleting old run logs and archived managed workspaces.</p></div></header>{!props.connected ? (- <p className="settings-notice">本地服务未连接,无法检查可清理内容。</p>+ <p className="settings-notice">The local Runtime is disconnected. Cleanup candidates cannot be checked.</p>) : null}{props.connected && props.service === null ? (- <p className="settings-notice">清理服务当前不可用。</p>+ <p className="settings-notice">The cleanup service is unavailable.</p>) : null}{validationError ? <p className="settings-error" role="alert">{validationError}</p> : null}<IssueList@@ -107,20 +107,20 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {onDismiss={pageIssues.dismissIssue}/>- <section className="cleanup-controls" aria-label="清理范围">+ <section className="cleanup-controls" aria-label="Cleanup scope"><label>- <span>保留最近</span>+ <span>Keep the last</span><span className="cleanup-retention-input"><inputtype="number"min="1"step="1"- aria-label="保留天数"+ aria-label="Retention days"value={olderThanDays}disabled={!available || phase !== 'idle'}onChange={(event) => setOlderThanDays(Number(event.target.value))}/>- <span>天</span>+ <span>days</span></span></label><button@@ -130,16 +130,16 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {onClick={() => void loadPreview()}><RefreshCw className={phase === 'previewing' ? 'settings-spin' : undefined} aria-hidden="true" size={15} />- {phase === 'previewing' ? '正在检查' : '检查可清理内容'}+ {phase === 'previewing' ? 'Checking' : 'Check cleanup candidates'}</button></section><section className="cleanup-rules" aria-labelledby="cleanup-rules-title">- <h2 id="cleanup-rules-title">保留规则</h2>+ <h2 id="cleanup-rules-title">Retention rules</h2><ul>- <li>运行中、排队中和正在取消的任务不会被清理。</li>- <li>只清理已归档的托管工作区,活动工作区和外部目录保持不变。</li>- <li>数据库中的 Run 和会话记录会保留,用于继续查看状态。</li>+ <li>Active, queued, and canceling tasks are retained.</li>+ <li>Only archived managed workspaces are cleaned up. Active workspaces and external directories are retained.</li>+ <li>Run and conversation records stay in the database for status review.</li></ul></section>@@ -147,8 +147,8 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {<section className="cleanup-preview" aria-labelledby="cleanup-preview-title"><div className="cleanup-summary"><div>- <h2 id="cleanup-preview-title">清理预览</h2>- <p>{candidateCount} 项 · {formatBytes(preview.totalSizeBytes)}</p>+ <h2 id="cleanup-preview-title">Cleanup preview</h2>+ <p>{candidateCount} items | {formatBytes(preview.totalSizeBytes)}</p></div>{candidateCount > 0 && result === undefined ? (<button@@ -158,15 +158,15 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {onClick={() => setConfirming(true)}><Trash2 aria-hidden="true" size={15} />- 删除 {candidateCount} 项+ Remove {candidateCount} items</button>) : null}</div>{preview.items.length === 0 ? (- <div className="settings-state">没有符合条件的可清理内容</div>+ <div className="settings-state">No eligible cleanup candidates</div>) : (- <ul className="cleanup-item-list" aria-label="清理候选列表">+ <ul className="cleanup-item-list" aria-label="Cleanup candidates">{preview.items.map(item => <CleanupItem key={`${item.type}:${item.id}`} item={item} />)}</ul>)}@@ -176,11 +176,11 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {) : null}{confirming && preview ? (- <section className="settings-confirmation" role="region" aria-label="确认清理">+ <section className="settings-confirmation" role="region" aria-label="Confirm cleanup"><AlertTriangle aria-hidden="true" size={18} /><div>- <strong>确认永久删除 {candidateCount} 项?</strong>- <p>此操作无法撤销。删除时会重新检查候选内容,发生变化的项目可能被跳过。</p>+ <strong>Permanently delete {candidateCount} items?</strong>+ <p>This cannot be undone. Candidates are checked again before deletion; changed items may be skipped.</p></div><div className="settings-confirmation__actions"><button@@ -189,7 +189,7 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {disabled={phase !== 'idle'}onClick={() => setConfirming(false)}>- 取消+ Cancel</button><buttonclassName="settings-primary-button"@@ -198,7 +198,7 @@ export function CleanupSettingsView(props: CleanupSettingsViewProps) {onClick={() => void deleteCandidates()}><Trash2 aria-hidden="true" size={15} />- {phase === 'deleting' ? '正在删除' : `确认删除 ${candidateCount} 项`}+ {phase === 'deleting' ? 'Deleting' : `Confirm deleting ${candidateCount} items`}</button></div></section>@@ -236,19 +236,19 @@ function CleanupResult(props: {<div className="cleanup-result__title"><CheckCircle2 aria-hidden="true" size={18} /><div>- <h2 id="cleanup-result-title">清理结果</h2>- <p>已释放 {formatBytes(props.result.totalDeletedBytes)}</p>+ <h2 id="cleanup-result-title">Cleanup results</h2>+ <p>Freed {formatBytes(props.result.totalDeletedBytes)}</p></div></div><div className="cleanup-result__counts">- <strong>已删除 {props.result.deleted.length} 项</strong>+ <strong>Deleted {props.result.deleted.length} items</strong><strong data-status={props.result.failed.length > 0 ? 'failed' : 'ok'}>- 删除失败 {props.result.failed.length} 项+ Deletion failed {props.result.failed.length} items</strong>- <strong>跳过 {skipped} 项</strong>+ <strong>Skipped {skipped} items</strong></div>{props.result.failed.length > 0 ? (- <ul className="cleanup-failure-list" aria-label="删除失败明细">+ <ul className="cleanup-failure-list" aria-label="Deletion failures">{props.result.failed.map(item => (<li key={`${item.type}:${item.id}`}><code>{item.path}</code>@@ -265,14 +265,14 @@ function CleanupResult(props: {function WarningList(props: { warnings: string[] }) {if (props.warnings.length === 0) return null;return (- <ul className="settings-warning-list" aria-label="清理告警">+ <ul className="settings-warning-list" aria-label="Cleanup warnings">{props.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>);}function cleanupTypeLabel(type: CleanupPreviewItem['type']): string {- return type === 'run_logs' ? 'Run 日志' : '已归档托管工作区';+ return type === 'run_logs' ? 'Run logs' : 'Archived managed workspace';}function formatBytes(value: number): string {diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.tsxindex b768eeb6..6e96a093 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.tsx@@ -1417,7 +1417,7 @@ function ModelField(props: {}}>{props.suggestions.map(value => <option key={value} value={value}>{value}</option>)}- <option value="__custom__">自定义模型 / Custom model</option>+ <option value="__custom__">Custom model</option></select>) : null}{(!props.suggestions?.length || showCustomInput) ? (diff --git a/apps/web/src/features/settings/DiagnosticsSettingsView.test.tsx b/apps/web/src/features/settings/DiagnosticsSettingsView.test.tsxindex d422ef5e..599b197d 100644--- a/apps/web/src/features/settings/DiagnosticsSettingsView.test.tsx+++ b/apps/web/src/features/settings/DiagnosticsSettingsView.test.tsx@@ -38,8 +38,8 @@ describe('DiagnosticsSettingsView', () => {expect(screen.getByText('/Users/test/.codex')).toBeInTheDocument();expect(screen.getByText('MCP github 登录已过期')).toBeInTheDocument();expect(screen.getByText(/"mcpAdd": true/)).toBeInTheDocument();- expect(screen.getByText('可写')).toBeInTheDocument();- expect(screen.getByText('可正常调用')).toBeInTheDocument();+ expect(screen.getByText('Writable')).toBeInTheDocument();+ expect(screen.getByText('Available')).toBeInTheDocument();});it('shows explicit empty and disconnected states', () => {@@ -51,7 +51,7 @@ describe('DiagnosticsSettingsView', () => {/>);- expect(screen.getByText('当前没有诊断告警')).toBeInTheDocument();+ expect(screen.getByText('No diagnostic warnings')).toBeInTheDocument();rerender(<DiagnosticsSettingsView@@ -60,7 +60,7 @@ describe('DiagnosticsSettingsView', () => {/>);- expect(screen.getByText('本地服务未连接,诊断状态可能已过期。')).toBeInTheDocument();- expect(screen.getAllByText('等待连接')).toHaveLength(2);+ expect(screen.getByText('The local Runtime is disconnected. Diagnostics may be out of date.')).toBeInTheDocument();+ expect(screen.getAllByText('Waiting for connection')).toHaveLength(2);});});diff --git a/apps/web/src/features/settings/DiagnosticsSettingsView.tsx b/apps/web/src/features/settings/DiagnosticsSettingsView.tsxindex a07b58cc..40b3dc40 100644--- a/apps/web/src/features/settings/DiagnosticsSettingsView.tsx+++ b/apps/web/src/features/settings/DiagnosticsSettingsView.tsx@@ -19,13 +19,13 @@ export function DiagnosticsSettingsView(props: DiagnosticsSettingsViewProps) {<section className="settings-section settings-management diagnostics-settings" aria-labelledby="settings-diagnostics-title"><header className="settings-management__header"><div>- <h1 id="settings-diagnostics-title">诊断</h1>- <p>查看本地 Runtime、Codex 路径、能力矩阵和当前告警。</p>+ <h1 id="settings-diagnostics-title">Diagnostics</h1>+ <p>View the local Runtime, Codex paths, capabilities, and current warnings.</p></div></header>{!props.connected ? (- <p className="settings-notice">本地服务未连接,诊断状态可能已过期。</p>+ <p className="settings-notice">The local Runtime is disconnected. Diagnostics may be out of date.</p>) : null}<RuntimeRecoveryNotice diagnostics />@@ -33,31 +33,31 @@ export function DiagnosticsSettingsView(props: DiagnosticsSettingsViewProps) {<section><SquareTerminal aria-hidden="true" size={18} /><span>Runtime</span>- <strong>{props.connected ? '已连接' : '等待连接'}</strong>- <small>{props.runtimeVersion ?? '版本未知'}</small>+ <strong>{props.connected ? 'Connected' : 'Waiting for connection'}</strong>+ <small>{props.runtimeVersion ?? 'Unknown version'}</small></section><section><HardDrive aria-hidden="true" size={18} /><span>Codex Home</span>- <strong>{status?.codexHomeWritable ? '可写' : status ? '只读' : '等待连接'}</strong>- <small>{status?.codexHomeMode ?? '未知模式'}</small>+ <strong>{status?.codexHomeWritable ? 'Writable' : status ? 'Read only' : 'Waiting for connection'}</strong>+ <small>{status?.codexHomeMode ?? 'Unknown mode'}</small></section></div><section className="diagnostics-block" aria-labelledby="diagnostics-runtime-title">- <h2 id="diagnostics-runtime-title">版本与运行目录</h2>+ <h2 id="diagnostics-runtime-title">Versions and Runtime directories</h2><dl>- <dt>Runtime 版本</dt>- <dd>{props.runtimeVersion ?? '未知'}</dd>- <dt>Codex CLI 版本</dt>- <dd>{status?.codexVersion ?? '未知'}</dd>- <dt>Codex CLI 路径</dt>- <dd><code>{status?.codexBin ?? '未连接'}</code></dd>+ <dt>Runtime version</dt>+ <dd>{props.runtimeVersion ?? 'Unknown'}</dd>+ <dt>Codex CLI version</dt>+ <dd>{status?.codexVersion ?? 'Unknown'}</dd>+ <dt>Codex CLI path</dt>+ <dd><code>{status?.codexBin ?? 'Disconnected'}</code></dd><dt>CODEX_HOME</dt>- <dd><code>{status?.codexHome ?? '未连接'}</code></dd>- <dt>配置来源</dt>- <dd>{status ? `${status.codexHomeMode} · ${status.codexHomeSource}` : '未知'}</dd>- <dt>后台可用性验证</dt>+ <dd><code>{status?.codexHome ?? 'Disconnected'}</code></dd>+ <dt>Configuration source</dt>+ <dd>{status ? `${status.codexHomeMode} · ${status.codexHomeSource}` : 'Unknown'}</dd>+ <dt>Background availability check</dt><dd>{availabilityProbeLabel(status?.availabilityProbe?.status)}</dd></dl></section>@@ -68,11 +68,11 @@ export function DiagnosticsSettingsView(props: DiagnosticsSettingsViewProps) {</section><section className="diagnostics-block" aria-labelledby="diagnostics-warnings-title">- <h2 id="diagnostics-warnings-title">日志告警</h2>+ <h2 id="diagnostics-warnings-title">Log warnings</h2>{diagnostics.length === 0 ? (<div className="diagnostics-empty"><CheckCircle2 aria-hidden="true" size={17} />- 当前没有诊断告警+ No diagnostic warnings</div>) : (<ul className="diagnostics-warning-list">@@ -93,7 +93,7 @@ function stringify(value: unknown): string {try {return JSON.stringify(value, null, 2) ?? String(value);} catch {- return '[无法序列化 Capabilities]';+ return '[Could not serialize capabilities]';}}@@ -102,14 +102,14 @@ function availabilityProbeLabel(): string {switch (status) {case 'pending':- return '检查中';+ return 'Checking';case 'succeeded':- return '可正常调用';+ return 'Available';case 'failed':- return '调用失败,请查看告警';+ return 'Unavailable. Check warnings.';case 'skipped':- return '本次已跳过';+ return 'Skipped this time';default:- return '未知';+ return 'Unknown';}}diff --git a/apps/web/src/features/settings/McpSettingsView.test.tsx b/apps/web/src/features/settings/McpSettingsView.test.tsxindex 749a06c2..3e305344 100644--- a/apps/web/src/features/settings/McpSettingsView.test.tsx+++ b/apps/web/src/features/settings/McpSettingsView.test.tsx@@ -43,13 +43,13 @@ describe('McpSettingsView', () => {expect(screen.getByText('GITHUB_TOKEN')).toBeInTheDocument();expect(screen.queryByText('super-secret-value')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '新增 MCP' }));- await user.type(screen.getByLabelText('名称'), 'linear');- await user.type(screen.getByLabelText('命令'), 'node');- await user.type(screen.getByLabelText('参数'), 'server.js');- await user.type(screen.getByLabelText('环境变量名'), 'LINEAR_TOKEN');- await user.type(screen.getByLabelText('环境变量值'), 'super-secret-value');- await user.click(screen.getByRole('button', { name: '保存 MCP' }));+ await user.click(screen.getByRole('button', { name: 'Add MCP server' }));+ await user.type(screen.getByLabelText('Name'), 'linear');+ await user.type(screen.getByLabelText('Command'), 'node');+ await user.type(screen.getByLabelText('Arguments'), 'server.js');+ await user.type(screen.getByLabelText('Environment variable name'), 'LINEAR_TOKEN');+ await user.type(screen.getByLabelText('Environment variable value'), 'super-secret-value');+ await user.click(screen.getByRole('button', { name: 'Save MCP server' }));expect(addServer).toHaveBeenCalledWith({name: 'linear',@@ -77,11 +77,11 @@ describe('McpSettingsView', () => {/>);- expect(screen.getByRole('button', { name: '新增 MCP' })).toBeDisabled();- expect(screen.getByRole('button', { name: '登录 github' })).toBeDisabled();- expect(screen.getByRole('button', { name: '退出 github' })).toBeDisabled();- expect(screen.getByRole('button', { name: '删除 github' })).toBeDisabled();- expect(screen.getByText('当前 Codex 版本不支持新增 MCP')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Add MCP server' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Sign in to github' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Sign out of github' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Remove github' })).toBeDisabled();+ expect(screen.getByText('This Codex version does not support adding MCP servers')).toBeInTheDocument();});it('confirms global writes and performs login, logout, and remove', async () => {@@ -100,9 +100,9 @@ describe('McpSettingsView', () => {/>);- await user.click(screen.getByRole('button', { name: '登录 github' }));- await user.click(screen.getByRole('button', { name: '退出 github' }));- await user.click(screen.getByRole('button', { name: '删除 github' }));+ await user.click(screen.getByRole('button', { name: 'Sign in to github' }));+ await user.click(screen.getByRole('button', { name: 'Sign out of github' }));+ await user.click(screen.getByRole('button', { name: 'Remove github' }));expect(loginServer).toHaveBeenCalledWith('github', true);expect(logoutServer).toHaveBeenCalledWith('github', true);diff --git a/apps/web/src/features/settings/McpSettingsView.tsx b/apps/web/src/features/settings/McpSettingsView.tsxindex 45161a86..71e33aca 100644--- a/apps/web/src/features/settings/McpSettingsView.tsx+++ b/apps/web/src/features/settings/McpSettingsView.tsx@@ -88,7 +88,7 @@ export function McpSettingsView(props: {if (!canceled) pageIssues.captureOperationFailure('settings.mcp.load',reason,- '无法加载 MCP 服务,请重试。',+ 'Could not load MCP servers. Try again.',{ retryable: true });})@@ -119,17 +119,17 @@ export function McpSettingsView(props: {if (props.service === null) return;const removeConfirmed = action !== 'remove'|| (props.confirmRemove?.(server) ?? await confirm({- title: '删除 MCP',- description: `确认删除“${server.name}”?相关连接将立即停用。`,- confirmLabel: '删除',+ title: 'Remove MCP',+ description: `Delete "${server.name}"? Its connections will be disabled immediately.`,+ confirmLabel: 'Remove',destructive: true}));if (!removeConfirmed) return;const confirmed = !data?.requiresWriteConfirmation|| (props.confirmWrite?.() ?? (action === 'remove' ? true : await confirm({- title: '确认修改全局配置',- description: '此操作会修改全局 CODEX_HOME,并影响使用同一配置目录的其他会话。',- confirmLabel: '继续'+ title: 'Confirm global configuration change',+ description: 'This changes the global CODEX_HOME and may affect other sessions using it.',+ confirmLabel: 'Continue'})));if (!confirmed) return;@@ -149,7 +149,7 @@ export function McpSettingsView(props: {pageIssues.captureOperationFailure(operationId,reason,- `MCP ${action === 'login' ? '登录' : action === 'logout' ? '退出' : '删除'}操作未完成,请检查诊断信息后重试。`+ `MCP ${action === 'login' ? 'sign-in' : action === 'logout' ? 'sign-out' : 'removal'} did not complete. Check diagnostics and try again.`);} finally {setBusyName(undefined);@@ -162,8 +162,8 @@ export function McpSettingsView(props: {<section className="settings-section settings-management" aria-labelledby="settings-mcp-title"><header className="settings-management__header"><div>- <h1 id="settings-mcp-title">MCP 服务</h1>- <p>管理 Codex 可连接的本机命令和远程 MCP 服务。</p>+ <h1 id="settings-mcp-title">MCP servers</h1>+ <p>Manage local commands and remote MCP servers available to Codex.</p></div><buttonclassName="settings-primary-button"@@ -172,18 +172,18 @@ export function McpSettingsView(props: {onClick={() => setEditorOpen(true)}><Plus size={16} />- 新增 MCP+ Add MCP server</button></header>{!props.connected || props.service === null ? (- <p className="settings-notice">本地服务连接后可以管理 MCP。</p>+ <p className="settings-notice">Connect the local Runtime to manage MCP servers.</p>) : null}{props.connected && props.service !== null && props.capabilities?.mcpAdd !== true ? (- <p className="settings-notice">当前 Codex 版本不支持新增 MCP</p>+ <p className="settings-notice">This Codex version does not support adding MCP servers</p>) : null}{data?.requiresWriteConfirmation ? (- <p className="settings-notice">写操作会修改全局 CODEX_HOME,每次操作都需要确认。</p>+ <p className="settings-notice">Write operations change the global CODEX_HOME and require confirmation each time.</p>) : null}<IssueListissues={pageIssues.issues}@@ -202,9 +202,9 @@ export function McpSettingsView(props: {if (props.service === null) return;const confirmed = !data?.requiresWriteConfirmation|| (props.confirmWrite?.() ?? await confirm({- title: '确认修改全局配置',- description: '此操作会修改全局 CODEX_HOME,并影响使用同一配置目录的其他会话。',- confirmLabel: '继续'+ title: 'Confirm global configuration change',+ description: 'This changes the global CODEX_HOME and may affect other sessions using it.',+ confirmLabel: 'Continue'}));if (!confirmed) return;try {@@ -228,7 +228,7 @@ export function McpSettingsView(props: {pageIssues.captureOperationFailure('settings.mcp.add',reason,- '无法新增 MCP,请检查配置后重试。'+ 'Could not add the MCP server. Check the settings and try again.');}}}@@ -238,15 +238,15 @@ export function McpSettingsView(props: {{loading ? (<div className="settings-state" role="status"><LoaderCircle size={20} className="settings-spin" />- 正在加载 MCP 服务+ Loading MCP servers</div>) : data !== undefined && data.servers.length === 0 ? (<div className="settings-state"><Server size={22} />- 暂无 MCP 服务+ No MCP servers</div>) : (- <ul className="settings-item-list" aria-label="MCP 服务列表">+ <ul className="settings-item-list" aria-label="MCP server list">{data?.servers.map(server => {const busy = busyName === server.name;return (@@ -255,11 +255,11 @@ export function McpSettingsView(props: {<div className="settings-item__title"><Server size={16} /><h2>{server.name}</h2>- <span data-status={server.status}>{server.status === 'configured' ? '已配置' : server.status}</span>+ <span data-status={server.status}>{server.status === 'configured' ? 'Configured' : server.status}</span></div><p>{mcpEndpoint(server)}</p>{server.envKeys.length > 0 ? (- <div className="settings-tags" aria-label={`${server.name} 环境变量`}>+ <div className="settings-tags" aria-label={`${server.name} environment variables`}><KeyRound size={14} />{server.envKeys.map(key => <code key={key}>{key}</code>)}</div>@@ -271,8 +271,8 @@ export function McpSettingsView(props: {<div className="settings-item__actions"><buttontype="button"- aria-label={`登录 ${server.name}`}- title="登录"+ aria-label={`Sign in to ${server.name}`}+ title="Sign in"disabled={busy || props.capabilities?.mcpLogin !== true}onClick={() => void runServerAction(server, 'login')}>@@ -280,8 +280,8 @@ export function McpSettingsView(props: {</button><buttontype="button"- aria-label={`退出 ${server.name}`}- title="退出"+ aria-label={`Sign out of ${server.name}`}+ title="Sign out"disabled={busy || props.capabilities?.mcpLogout !== true}onClick={() => void runServerAction(server, 'logout')}>@@ -289,8 +289,8 @@ export function McpSettingsView(props: {</button><buttontype="button"- aria-label={`删除 ${server.name}`}- title="删除"+ aria-label={`Remove ${server.name}`}+ title="Remove"disabled={busy || props.capabilities?.mcpRemove !== true}onClick={() => void runServerAction(server, 'remove')}>@@ -327,7 +327,7 @@ export function McpEditor(props: {async function submit(event: FormEvent<HTMLFormElement>) {event.preventDefault();const trimmedName = name.trim();- if (trimmedName.length === 0) return setFormError('请输入 MCP 名称');+ if (trimmedName.length === 0) return setFormError('Enter an MCP server name');const env = Object.fromEntries(envEntries.map(entry => [entry.key.trim(), entry.value] as const)@@ -335,7 +335,7 @@ export function McpEditor(props: {);let input: AddCodexMcpRequest;if (transport === 'stdio') {- if (command.trim().length === 0) return setFormError('请输入启动命令');+ if (command.trim().length === 0) return setFormError('Enter a launch command');input = {name: trimmedName,transport,@@ -344,7 +344,7 @@ export function McpEditor(props: {...(Object.keys(env).length > 0 ? { env } : {})};} else {- if (url.trim().length === 0) return setFormError('请输入 MCP URL');+ if (url.trim().length === 0) return setFormError('Enter an MCP URL');input = {name: trimmedName,transport,@@ -366,26 +366,26 @@ export function McpEditor(props: {}return (- <form className="settings-editor" aria-label="新增 MCP" onSubmit={submit}>+ <form className="settings-editor" aria-label="Add MCP server" onSubmit={submit}><header><div>- <p>新增连接</p>- <h2>配置 MCP 服务</h2>+ <p>Add connection</p>+ <h2>Configure MCP server</h2></div>- <button type="button" aria-label="关闭 MCP 编辑器" title="关闭" onClick={props.onCancel}>+ <button type="button" aria-label="Close MCP editor" title="Close" onClick={props.onCancel}><X size={17} /></button></header>{formError ? <p className="settings-error" role="alert">{formError}</p> : null}<div className="settings-form-grid"><label>- <span>名称</span>- <input aria-label="名称" value={name} onChange={event => setName(event.target.value)} />+ <span>Name</span>+ <input aria-label="Name" value={name} onChange={event => setName(event.target.value)} /></label><label>- <span>传输方式</span>+ <span>Transport</span><select- aria-label="传输方式"+ aria-label="Transport"value={transport}onChange={event => setTransport(event.target.value as typeof transport)}>@@ -397,12 +397,12 @@ export function McpEditor(props: {{transport === 'stdio' ? (<><label>- <span>命令</span>- <input aria-label="命令" value={command} onChange={event => setCommand(event.target.value)} />+ <span>Command</span>+ <input aria-label="Command" value={command} onChange={event => setCommand(event.target.value)} /></label><label>- <span>参数(每行一个)</span>- <textarea aria-label="参数" rows={3} value={args} onChange={event => setArgs(event.target.value)} />+ <span>Arguments (one per line)</span>+ <textarea aria-label="Arguments" rows={3} value={args} onChange={event => setArgs(event.target.value)} /></label></>) : (@@ -412,9 +412,9 @@ export function McpEditor(props: {<input aria-label="MCP URL" value={url} onChange={event => setUrl(event.target.value)} /></label><label>- <span>Bearer Token 环境变量名</span>+ <span>Bearer token environment variable</span><input- aria-label="Bearer Token 环境变量名"+ aria-label="Bearer token environment variable"disabled={props.capabilities?.mcpAddBearerTokenEnvVar !== true}value={bearerTokenEnvVar}onChange={event => setBearerTokenEnvVar(event.target.value)}@@ -442,22 +442,22 @@ export function McpEditor(props: {)}</div><fieldset className="settings-env-editor" disabled={props.capabilities?.mcpAddEnv !== true}>- <legend>环境变量</legend>+ <legend>Environment variables</legend>{envEntries.map((entry, index) => (<div key={entry.id}><input- aria-label={index === 0 ? '环境变量名' : `环境变量名 ${index + 1}`}- placeholder="变量名"+ aria-label={index === 0 ? 'Environment variable name' : `Environment variable name ${index + 1}`}+ placeholder="Variable name"value={entry.key}onChange={event => setEnvEntries(current => current.map(item => (item.id === entry.id ? { ...item, key: event.target.value } : item)))}/><input- aria-label={index === 0 ? '环境变量值' : `环境变量值 ${index + 1}`}+ aria-label={index === 0 ? 'Environment variable value' : `Environment variable value ${index + 1}`}type="password"autoComplete="off"- placeholder="仅在本次保存时使用"+ placeholder="Used only for this save"value={entry.value}onChange={event => setEnvEntries(current => current.map(item => (item.id === entry.id ? { ...item, value: event.target.value } : item@@ -466,7 +466,7 @@ export function McpEditor(props: {{envEntries.length > 1 ? (<buttontype="button"- aria-label={`移除环境变量 ${index + 1}`}+ aria-label={`Remove environment variable ${index + 1}`}onClick={() => setEnvEntries(current => current.filter(item => item.id !== entry.id))}><Trash2 size={15} />@@ -483,15 +483,15 @@ export function McpEditor(props: {])}><Plus size={15} />- 添加变量+ Add variable</button></fieldset>- {props.requiresWriteConfirmation ? <p className="settings-notice">保存时将再次确认全局写入。</p> : null}+ {props.requiresWriteConfirmation ? <p className="settings-notice">Saving requires another confirmation of the global configuration change.</p> : null}<footer>- <button className="settings-secondary-button" type="button" onClick={props.onCancel}>取消</button>+ <button className="settings-secondary-button" type="button" onClick={props.onCancel}>Cancel</button><button className="settings-primary-button" type="submit" disabled={saving}>{saving ? <LoaderCircle size={16} className="settings-spin" /> : <Server size={16} />}- 保存 MCP+ Save MCP server</button></footer></form>diff --git a/apps/web/src/features/settings/MemorySettingsView.test.tsx b/apps/web/src/features/settings/MemorySettingsView.test.tsxindex 19a103c2..476ed84c 100644--- a/apps/web/src/features/settings/MemorySettingsView.test.tsx+++ b/apps/web/src/features/settings/MemorySettingsView.test.tsx@@ -23,17 +23,17 @@ describe('MemorySettingsView', () => {);expect(await screen.findByText('提交前运行全部测试')).toBeInTheDocument();- await user.type(screen.getByRole('searchbox', { name: '搜索记忆' }), '测试');+ await user.type(screen.getByRole('searchbox', { name: 'Search memories' }), '测试');await waitFor(() => expect(service.listMemories).toHaveBeenLastCalledWith(expect.objectContaining({ query: '测试' })));- await user.click(screen.getByRole('button', { name: '新建记忆' }));- await user.clear(screen.getByRole('textbox', { name: '记忆内容' }));- await user.type(screen.getByRole('textbox', { name: '记忆内容' }), '项目使用 pnpm');- await user.selectOptions(screen.getByRole('combobox', { name: '记忆范围' }), 'project');- await user.selectOptions(screen.getByRole('combobox', { name: '范围目标' }), '/workspace/project');- await user.click(screen.getByRole('button', { name: '保存记忆' }));+ await user.click(screen.getByRole('button', { name: 'New memory' }));+ await user.clear(screen.getByRole('textbox', { name: 'Memory content' }));+ await user.type(screen.getByRole('textbox', { name: 'Memory content' }), '项目使用 pnpm');+ await user.selectOptions(screen.getByRole('combobox', { name: 'Memory scope' }), 'project');+ await user.selectOptions(screen.getByRole('combobox', { name: 'Scope target' }), '/workspace/project');+ await user.click(screen.getByRole('button', { name: 'Save memory' }));await waitFor(() => expect(service.createMemory).toHaveBeenCalledWith({content: '项目使用 pnpm',scope: 'project',@@ -41,23 +41,23 @@ describe('MemorySettingsView', () => {source: 'user'}));- await user.click(screen.getByRole('button', { name: '编辑记忆' }));- await user.clear(screen.getByRole('textbox', { name: '记忆内容' }));- await user.type(screen.getByRole('textbox', { name: '记忆内容' }), '提交前运行全量测试');- await user.click(screen.getByRole('button', { name: '保存修改' }));+ await user.click(screen.getByRole('button', { name: 'Edit memory' }));+ await user.clear(screen.getByRole('textbox', { name: 'Memory content' }));+ await user.type(screen.getByRole('textbox', { name: 'Memory content' }), '提交前运行全量测试');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));await waitFor(() => expect(service.updateMemory).toHaveBeenCalledWith('mem_1',{ content: '提交前运行全量测试' }));- await user.click(screen.getByRole('button', { name: '停用记忆' }));+ await user.click(screen.getByRole('button', { name: 'Disable memory' }));await waitFor(() => expect(service.updateMemory).toHaveBeenCalledWith('mem_1', { enabled: false }));- await user.click(screen.getByRole('button', { name: '删除记忆' }));+ await user.click(screen.getByRole('button', { name: 'Delete memory' }));await waitFor(() => expect(service.deleteMemory).toHaveBeenCalledWith('mem_1'));- await user.click(screen.getByRole('button', { name: '全部停用' }));- await user.click(screen.getByRole('button', { name: '确认全部停用' }));+ await user.click(screen.getByRole('button', { name: 'Disable all' }));+ await user.click(screen.getByRole('button', { name: 'Confirm disable all' }));await waitFor(() => expect(service.disableAll).toHaveBeenCalledTimes(1));});@@ -74,12 +74,12 @@ describe('MemorySettingsView', () => {render(<MemorySettingsView connected service={service} projects={[]} threads={[]} />);await screen.findByText('提交前运行全部测试');- await user.click(screen.getByRole('button', { name: '新建记忆' }));- await user.type(screen.getByRole('textbox', { name: '记忆内容' }), 'password=secret');- await user.click(screen.getByRole('button', { name: '保存记忆' }));+ await user.click(screen.getByRole('button', { name: 'New memory' }));+ await user.type(screen.getByRole('textbox', { name: 'Memory content' }), 'password=secret');+ await user.click(screen.getByRole('button', { name: 'Save memory' }));- expect(await screen.findByText(/可能包含敏感信息/)).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '确认保存敏感记忆' }));+ expect(await screen.findByText(/may contain sensitive information/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Confirm saving sensitive memory' }));await waitFor(() => expect(service.createMemory).toHaveBeenLastCalledWith({content: 'password=secret',scope: 'global',@@ -100,9 +100,9 @@ describe('MemorySettingsView', () => {/>);- expect(await screen.findByText('版本 2')).toBeInTheDocument();+ expect(await screen.findByText('Version 2')).toBeInTheDocument();expect(screen.getByText('用户:继续开发')).toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '删除摘要' }));+ await user.click(screen.getByRole('button', { name: 'Delete summary' }));await waitFor(() => expect(service.deleteSummary).toHaveBeenCalledWith('summary_1'));});});diff --git a/apps/web/src/features/settings/MemorySettingsView.tsx b/apps/web/src/features/settings/MemorySettingsView.tsxindex e1a20ba6..f342e08c 100644--- a/apps/web/src/features/settings/MemorySettingsView.tsx+++ b/apps/web/src/features/settings/MemorySettingsView.tsx@@ -96,7 +96,7 @@ export function MemorySettingsView(props: {if (!canceled) pageIssues.captureOperationFailure('settings.memory.load',reason,- '无法加载记忆,请重试。',+ 'Could not load memories. Try again.',{ retryable: true });}).finally(() => {@@ -157,11 +157,11 @@ export function MemorySettingsView(props: {if (!available || editor === undefined) return;const content = editor.content.trim();if (content.length === 0) {- setValidationError('记忆内容不能为空');+ setValidationError('Memory content cannot be empty');return;}if (editor.scope !== 'global' && editor.scopeKey === undefined) {- setValidationError('请选择范围目标');+ setValidationError('Select a scope target');return;}setSaving(true);@@ -195,7 +195,7 @@ export function MemorySettingsView(props: {pageIssues.captureOperationFailure('settings.memory.save',reason,- '保存记忆失败,请检查内容后重试。',+ 'Could not save the memory. Check its content and try again.',{ retryable: true });}@@ -212,7 +212,7 @@ export function MemorySettingsView(props: {await refresh();pageIssues.resolveOperation(operationId);} catch (reason) {- pageIssues.captureOperationFailure(operationId, reason, '更新记忆状态失败,请重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not update memory status. Try again.');}}@@ -224,7 +224,7 @@ export function MemorySettingsView(props: {await refresh();pageIssues.resolveOperation(operationId);} catch (reason) {- pageIssues.captureOperationFailure(operationId, reason, '删除记忆失败,请重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not delete the memory. Try again.');}}@@ -236,7 +236,7 @@ export function MemorySettingsView(props: {await refresh();pageIssues.resolveOperation('settings.memory.disable-all');} catch (reason) {- pageIssues.captureOperationFailure('settings.memory.disable-all', reason, '全部停用失败,请重试。');+ pageIssues.captureOperationFailure('settings.memory.disable-all', reason, 'Could not disable all memories. Try again.');}}@@ -248,7 +248,7 @@ export function MemorySettingsView(props: {await refresh();pageIssues.resolveOperation(operationId);} catch (reason) {- pageIssues.captureOperationFailure(operationId, reason, '删除摘要失败,请重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not delete the summary. Try again.');}}@@ -256,17 +256,17 @@ export function MemorySettingsView(props: {<section className="settings-section settings-management memory-settings" aria-labelledby="settings-memory-title"><header className="settings-management__header"><div>- <h1 id="settings-memory-title">记忆</h1>- <p>只保存你明确确认的长期偏好,并记录每次 Run 实际使用的上下文快照。</p>+ <h1 id="settings-memory-title">Memories</h1>+ <p>Save confirmed long-term preferences and track the context used by each run.</p></div><button className="settings-primary-button" type="button" disabled={!available} onClick={openCreate}><Plus aria-hidden="true" size={15} />- 新建记忆+ New memory</button></header>- {!props.connected ? <p className="settings-notice">本地服务未连接,无法管理记忆。</p> : null}- {props.connected && props.service === null ? <p className="settings-notice">记忆服务当前不可用。</p> : null}+ {!props.connected ? <p className="settings-notice">The local Runtime is disconnected. Memories cannot be managed.</p> : null}+ {props.connected && props.service === null ? <p className="settings-notice">The memory service is unavailable.</p> : null}{validationError ? <p className="settings-error" role="alert">{validationError}</p> : null}<IssueListissues={pageIssues.issues}@@ -282,40 +282,40 @@ export function MemorySettingsView(props: {<Search aria-hidden="true" size={15} /><inputtype="search"- aria-label="搜索记忆"- placeholder="搜索记忆"+ aria-label="Search memories"+ placeholder="Search memories"value={query}disabled={!available}onChange={event => setQuery(event.target.value)}/></label><label>- <span>范围</span>+ <span>Scope</span><select- aria-label="筛选记忆范围"+ aria-label="Filter memory scope"value={scope}disabled={!available}onChange={event => setScope(event.target.value as MemoryScope | 'all')}>- <option value="all">全部范围</option>- <option value="global">全局</option>- <option value="project">项目</option>- <option value="thread">线程</option>+ <option value="all">All scopes</option>+ <option value="global">Global</option>+ <option value="project">Project</option>+ <option value="thread">Thread</option></select></label><label>- <span>状态</span>+ <span>Status</span><select- aria-label="筛选记忆状态"+ aria-label="Filter memory status"value={String(enabled)}disabled={!available}onChange={event => setEnabled(event.target.value === 'all' ? 'all' : event.target.value === 'true')}>- <option value="all">全部状态</option>- <option value="true">已启用</option>- <option value="false">已停用</option>+ <option value="all">All statuses</option>+ <option value="true">Enabled</option>+ <option value="false">Disabled</option></select></label><button@@ -325,7 +325,7 @@ export function MemorySettingsView(props: {onClick={() => setConfirmingDisableAll(true)}><PowerOff aria-hidden="true" size={15} />- 全部停用+ Disable all</button></div>@@ -343,18 +343,18 @@ export function MemorySettingsView(props: {) : null}{confirmingDisableAll ? (- <section className="settings-confirmation" role="region" aria-label="确认全部停用记忆">+ <section className="settings-confirmation" role="region" aria-label="Confirm disabling all memories"><AlertTriangle aria-hidden="true" size={18} /><div>- <strong>确认停用全部长期记忆?</strong>- <p>记录不会删除,但后续 Run 不再注入这些记忆。</p>+ <strong>Disable all long-term memories?</strong>+ <p>Records are retained, but future runs will no longer use these memories.</p></div><div className="settings-confirmation__actions"><button className="settings-text-button" type="button" onClick={() => setConfirmingDisableAll(false)}>- 取消+ Cancel</button><button className="settings-primary-button" type="button" onClick={() => void disableAll()}>- 确认全部停用+ Confirm disable all</button></div></section>@@ -363,14 +363,14 @@ export function MemorySettingsView(props: {<section className="memory-block" aria-labelledby="memory-list-title"><div className="memory-block__header"><div>- <h2 id="memory-list-title">长期记忆</h2>- <p>{memories.length} 条</p>+ <h2 id="memory-list-title">Long-term memories</h2>+ <p>{memories.length} entries</p></div></div>{loading ? (- <div className="settings-state">正在加载记忆...</div>+ <div className="settings-state">Loading memories...</div>) : memories.length === 0 ? (- <div className="settings-state">没有符合条件的记忆</div>+ <div className="settings-state">No matching memories</div>) : (<ul className="memory-list">{memories.map(memory => (@@ -379,29 +379,29 @@ export function MemorySettingsView(props: {<div className="memory-item__meta"><span>{memoryScopeLabel(memory.scope)}</span><span data-status={memory.enabled ? 'enabled' : 'disabled'}>- {memory.enabled ? '已启用' : '已停用'}+ {memory.enabled ? 'Enabled' : 'Disabled'}</span>- {memory.sensitive ? <span data-status="sensitive">敏感</span> : null}- <span>{memory.source === 'user' ? '用户保存' : 'Agent 建议'}</span>+ {memory.sensitive ? <span data-status="sensitive">Sensitive</span> : null}+ <span>{memory.source === 'user' ? 'Saved by user' : 'Suggested by Agent'}</span></div><p>{memory.content}</p>{memory.scopeKey ? <code>{scopeKeyLabel(memory, props.projects, props.threads)}</code> : null}</div><div className="memory-item__actions">- <button type="button" aria-label="编辑记忆" title="编辑记忆" onClick={() => openEdit(memory)}>+ <button type="button" aria-label="Edit memory" title="Edit memory" onClick={() => openEdit(memory)}><Pencil aria-hidden="true" size={15} /></button><buttontype="button"- aria-label={memory.enabled ? '停用记忆' : '启用记忆'}- title={memory.enabled ? '停用记忆' : '启用记忆'}+ aria-label={memory.enabled ? 'Disable memory' : 'Enable memory'}+ title={memory.enabled ? 'Disable memory' : 'Enable memory'}onClick={() => void toggleMemory(memory)}>{memory.enabled? <PowerOff aria-hidden="true" size={15} />: <Power aria-hidden="true" size={15} />}</button>- <button type="button" aria-label="删除记忆" title="删除记忆" onClick={() => void deleteMemory(memory.id)}>+ <button type="button" aria-label="Delete memory" title="Delete memory" onClick={() => void deleteMemory(memory.id)}><Trash2 aria-hidden="true" size={15} /></button></div>@@ -414,12 +414,12 @@ export function MemorySettingsView(props: {<section className="memory-block" aria-labelledby="summary-list-title"><div className="memory-block__header"><div>- <h2 id="summary-list-title">会话摘要</h2>- <p>{summaries.length} 个版本</p>+ <h2 id="summary-list-title">Conversation summaries</h2>+ <p>{summaries.length} versions</p></div></div>{summaries.length === 0 ? (- <div className="settings-state">尚未生成会话摘要</div>+ <div className="settings-state">No conversation summaries yet</div>) : (<ul className="summary-list">{summaries.map(summary => (@@ -427,15 +427,15 @@ export function MemorySettingsView(props: {<header><div><strong>{optionLabel(summary.threadId, props.threads)}</strong>- <span>版本 {summary.version}</span>+ <span>Version {summary.version}</span></div>- <button type="button" aria-label="删除摘要" title="删除摘要" onClick={() => void deleteSummary(summary.id)}>+ <button type="button" aria-label="Delete summary" title="Delete summary" onClick={() => void deleteSummary(summary.id)}><Trash2 aria-hidden="true" size={15} /></button></header><p>{summary.content}</p><small>- {summary.itemCount} 项 · {summary.coveredFromCursor} 至 {summary.coveredToCursor}+ {summary.itemCount} items | {summary.coveredFromCursor} to {summary.coveredToCursor}</small></li>))}@@ -462,21 +462,21 @@ function MemoryEditor(props: {? props.threads: [];return (- <section className="settings-editor memory-editor" aria-label={props.editor.mode === 'create' ? '新建记忆' : '编辑记忆'}>+ <section className="settings-editor memory-editor" aria-label={props.editor.mode === 'create' ? 'New memory' : 'Edit memory'}><header><div>- <h2>{props.editor.mode === 'create' ? '新建记忆' : '编辑记忆'}</h2>- <p>单条最多 2000 字符,只存储在本机 Runtime 数据库。</p>+ <h2>{props.editor.mode === 'create' ? 'New memory' : 'Edit memory'}</h2>+ <p>Up to 2,000 characters per memory, stored only in the local Runtime database.</p></div>- <button type="button" aria-label="关闭记忆编辑器" onClick={props.onClose}>+ <button type="button" aria-label="Close memory editor" onClick={props.onClose}><X aria-hidden="true" size={15} /></button></header><div className="settings-form-grid"><label className="settings-form-wide">- <span>记忆内容</span>+ <span>Memory content</span><textarea- aria-label="记忆内容"+ aria-label="Memory content"rows={4}maxLength={2000}value={props.editor.content}@@ -485,9 +485,9 @@ function MemoryEditor(props: {/></label><label>- <span>范围</span>+ <span>Scope</span><select- aria-label="记忆范围"+ aria-label="Memory scope"value={props.editor.scope}disabled={props.saving || props.editor.mode === 'edit'}onChange={event => {@@ -501,21 +501,21 @@ function MemoryEditor(props: {});}}>- <option value="global">全局</option>- <option value="project">项目</option>- <option value="thread">线程</option>+ <option value="global">Global</option>+ <option value="project">Project</option>+ <option value="thread">Thread</option></select></label>{props.editor.scope !== 'global' ? (<label>- <span>目标</span>+ <span>Target</span><select- aria-label="范围目标"+ aria-label="Scope target"value={props.editor.scopeKey ?? ''}disabled={props.saving || props.editor.mode === 'edit'}onChange={event => props.onChange({ ...props.editor, scopeKey: event.target.value })}>- {options.length === 0 ? <option value="">无可用目标</option> : null}+ {options.length === 0 ? <option value="">No targets available</option> : null}{options.map(option => <option key={option.key} value={option.key}>{option.label}</option>)}</select></label>@@ -524,17 +524,17 @@ function MemoryEditor(props: {{props.confirmingSensitive ? (<div className="settings-inline-warning memory-sensitive-warning" role="alert"><AlertTriangle aria-hidden="true" size={16} />- <span>内容可能包含敏感信息,确认后才会保存到本机。</span>- <button type="button" onClick={() => void props.onSave(true)} aria-label="确认保存敏感记忆">- 确认保存+ <span>This content may contain sensitive information. Confirm before saving it locally.</span>+ <button type="button" onClick={() => void props.onSave(true)} aria-label="Confirm saving sensitive memory">+ Confirm save</button></div>) : null}<footer>- <button className="settings-text-button" type="button" onClick={props.onClose}>取消</button>+ <button className="settings-text-button" type="button" onClick={props.onClose}>Cancel</button><button className="settings-primary-button" type="button" disabled={props.saving} onClick={() => void props.onSave()}><Brain aria-hidden="true" size={15} />- {props.saving ? '正在保存' : props.editor.mode === 'create' ? '保存记忆' : '保存修改'}+ {props.saving ? 'Saving' : props.editor.mode === 'create' ? 'Save memory' : 'Save changes'}</button></footer></section>@@ -542,9 +542,9 @@ function MemoryEditor(props: {}function memoryScopeLabel(scope: MemoryScope): string {- if (scope === 'project') return '项目';- if (scope === 'thread') return '线程';- return '全局';+ if (scope === 'project') return 'Project';+ if (scope === 'thread') return 'Thread';+ return 'Global';}function optionLabel(key: string, options: MemoryScopeOption[]): string {diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsxindex 182c72ab..a3ba1d0d 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx@@ -382,7 +382,7 @@ describe('OpenCreatorSettingsView', () => {expect(await screen.findByRole('textbox', { name: '默认项目位置' })).toHaveValue('/Users/demo/Documents/OpenCreator');- await user.click(screen.getByRole('button', { name: '选择完成产物位置' }));+ await user.click(screen.getByRole('button', { name: 'Select 完成产物位置' }));expect(onSelectStorageDirectory).toHaveBeenCalledWith('output-root');expect(updateStorageSettings).toHaveBeenCalledWith({outputRoot: '/Users/demo/Exports'@@ -420,13 +420,13 @@ describe('OpenCreatorSettingsView', () => {const output = await screen.findByRole('textbox', { name: '完成产物位置' });await user.clear(output);await user.type(output, '/Users/demo/Custom Exports');- await user.click(screen.getByRole('button', { name: '保存完成产物位置' }));+ await user.click(screen.getByRole('button', { name: 'Save 完成产物位置' }));expect(updateStorageSettings).toHaveBeenCalledWith({outputRoot: '/Users/demo/Custom Exports'});expect(output).toHaveValue('/Users/demo/Custom Exports');- expect(screen.queryByRole('button', { name: '选择完成产物位置' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Select 完成产物位置' })).not.toBeInTheDocument();});it('shows the anonymous telemetry scope and allows Desktop users to disable it', () => {@@ -539,7 +539,7 @@ describe('OpenCreatorSettingsView', () => {fireEvent.click(screen.getByRole('button', { name: 'Profiles' }));expect(screen.getByRole('heading', { name: 'Profiles' })).toBeInTheDocument();- expect(screen.getByText('本地服务连接后可以管理 Profile。')).toBeInTheDocument();+ expect(screen.getByText('Connect the local Runtime to manage Profiles.')).toBeInTheDocument();});it('opens Cleanup and Diagnostics pages from settings navigation', () => {@@ -561,10 +561,10 @@ describe('OpenCreatorSettingsView', () => {);fireEvent.click(screen.getByRole('button', { name: '清理' }));- expect(screen.getByRole('heading', { name: '运行数据清理' })).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Runtime data cleanup' })).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: '诊断' }));- expect(screen.getByRole('heading', { name: '诊断' })).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Diagnostics' })).toBeInTheDocument();expect(screen.getByText(runtimeStatus.codexPath)).toBeInTheDocument();});diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.tsxindex 1d14d806..82ae2b47 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx@@ -601,8 +601,8 @@ function StorageDirectoryRow(props: {<buttontype="button"className="icon-button"- aria-label={`保存${props.label}`}- title={`保存${props.label}`}+ aria-label={`Save ${props.label}`}+ title={`Save ${props.label}`}disabled={props.disabled || !dirty}onClick={props.onSave}>@@ -611,8 +611,8 @@ function StorageDirectoryRow(props: {{props.onSelect === undefined ? null : <buttontype="button"className="icon-button"- aria-label={`选择${props.label}`}- title={`选择${props.label}`}+ aria-label={`Select ${props.label}`}+ title={`Select ${props.label}`}disabled={props.disabled}onClick={props.onSelect}>diff --git a/apps/web/src/features/settings/ProfileSettingsView.test.tsx b/apps/web/src/features/settings/ProfileSettingsView.test.tsxindex 05cb70a6..826ce30a 100644--- a/apps/web/src/features/settings/ProfileSettingsView.test.tsx+++ b/apps/web/src/features/settings/ProfileSettingsView.test.tsx@@ -25,12 +25,12 @@ describe('ProfileSettingsView', () => {/>);- await user.click(screen.getByRole('button', { name: '新建 Profile' }));- await user.type(screen.getByLabelText('Profile 名称'), 'review');- await user.type(screen.getByLabelText('模型'), 'gpt-5.3-codex');- await user.selectOptions(screen.getByLabelText('推理级别'), 'high');+ await user.click(screen.getByRole('button', { name: 'New Profile' }));+ await user.type(screen.getByLabelText('Profile name'), 'review');+ await user.type(screen.getByLabelText('Model'), 'gpt-5.3-codex');+ await user.selectOptions(screen.getByLabelText('Reasoning effort'), 'high');await user.selectOptions(screen.getByLabelText('Sandbox'), 'workspace-write');- await user.click(screen.getByRole('button', { name: '保存 Profile' }));+ await user.click(screen.getByRole('button', { name: 'Save Profile' }));expect(createProfile).toHaveBeenCalledWith({name: 'review',@@ -64,10 +64,10 @@ describe('ProfileSettingsView', () => {/>);- await user.click(screen.getByRole('button', { name: '编辑 review' }));+ await user.click(screen.getByRole('button', { name: 'Edit review' }));expect(await screen.findByDisplayValue('gpt-5.3-codex')).toBeInTheDocument();- await user.selectOptions(screen.getByLabelText('推理级别'), 'xhigh');- await user.click(screen.getByRole('button', { name: '保存 Profile' }));+ await user.selectOptions(screen.getByLabelText('Reasoning effort'), 'xhigh');+ await user.click(screen.getByRole('button', { name: 'Save Profile' }));expect(getProfile).toHaveBeenCalledWith('review');expect(updateProfile).toHaveBeenCalledWith('review', {@@ -102,10 +102,10 @@ describe('ProfileSettingsView', () => {/>);- await user.click(screen.getByRole('button', { name: '删除 review' }));+ await user.click(screen.getByRole('button', { name: 'Delete review' }));const issue = await screen.findByRole('alert');- expect(issue).toHaveTextContent('无法删除 Profile,请检查占用情况后重试。');+ expect(issue).toHaveTextContent('Could not delete the Profile. Check whether it is in use and try again.');expect(issue).not.toHaveTextContent(/诊断编号:OC-/);expect(issue).not.toHaveTextContent('Profile is still referenced');expect(screen.getByRole('heading', { name: 'review' })).toBeInTheDocument();@@ -119,8 +119,8 @@ describe('ProfileSettingsView', () => {data={profileData({ writable: false })}/>);- expect(screen.getByRole('button', { name: '新建 Profile' })).toBeDisabled();- expect(screen.getByText('当前 CODEX_HOME 为只读,无法修改 Profile')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'New Profile' })).toBeDisabled();+ expect(screen.getByText('CODEX_HOME is read-only. Profiles cannot be changed.')).toBeInTheDocument();rerender(<ProfileSettingsView@@ -129,8 +129,8 @@ describe('ProfileSettingsView', () => {data={profileData({ baseConfigValid: false, diagnostics: ['config.toml 解析失败'] })}/>);- expect(screen.getByRole('button', { name: '新建 Profile' })).toBeDisabled();- expect(screen.getByText('基础 config.toml 无效,请先修复配置')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'New Profile' })).toBeDisabled();+ expect(screen.getByText('The base config.toml is invalid. Fix it first.')).toBeInTheDocument();});});diff --git a/apps/web/src/features/settings/ProfileSettingsView.tsx b/apps/web/src/features/settings/ProfileSettingsView.tsxindex 85cbec7a..853a2a7b 100644--- a/apps/web/src/features/settings/ProfileSettingsView.tsx+++ b/apps/web/src/features/settings/ProfileSettingsView.tsx@@ -74,7 +74,7 @@ export function ProfileSettingsView(props: {if (!canceled) pageIssues.captureOperationFailure('settings.profiles.load',reason,- '无法加载 Profiles,请重试。',+ 'Could not load Profiles. Try again.',{ retryable: true });})@@ -116,23 +116,23 @@ export function ProfileSettingsView(props: {const detail = await props.service.getProfile(profile.name);if (containsSensitiveConfig(detail.profile.config)) {setEditor(undefined);- setValidationError('该 Profile 含敏感配置,请直接编辑本机配置文件');+ setValidationError('This Profile contains sensitive settings. Edit the local configuration file directly.');return;}setEditor({ mode: 'edit', name: profile.name, profile: detail.profile, loading: false });pageIssues.resolveOperation(operationId);} catch (reason) {setEditor(undefined);- pageIssues.captureOperationFailure(operationId, reason, '无法加载 Profile 详情,请重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not load Profile details. Try again.');}}async function deleteProfile(profile: CodexProfileResponse) {if (props.service === null) return;const confirmed = props.confirmDelete?.(profile) ?? await confirm({- title: '删除 Profile',- description: `确认删除“${profile.name}”?删除后无法恢复。`,- confirmLabel: '删除',+ title: 'Delete Profile',+ description: `Delete "${profile.name}"? This cannot be undone.`,+ confirmLabel: 'Remove',destructive: true});if (!confirmed) return;@@ -145,7 +145,7 @@ export function ProfileSettingsView(props: {}pageIssues.resolveOperation(operationId);} catch (reason) {- pageIssues.captureOperationFailure(operationId, reason, '无法删除 Profile,请检查占用情况后重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not delete the Profile. Check whether it is in use and try again.');} finally {setBusyName(undefined);}@@ -161,7 +161,7 @@ export function ProfileSettingsView(props: {<header className="settings-management__header"><div><h1 id="settings-profiles-title">Profiles</h1>- <p>维护会话和计划任务可复用的 Codex 配置。</p>+ <p>Manage reusable Codex settings for conversations and scheduled tasks.</p></div><buttonclassName="settings-primary-button"@@ -170,18 +170,18 @@ export function ProfileSettingsView(props: {onClick={() => setEditor({ mode: 'create' })}><Plus size={16} />- 新建 Profile+ New Profile</button></header>{!props.connected || props.service === null ? (- <p className="settings-notice">本地服务连接后可以管理 Profile。</p>+ <p className="settings-notice">Connect the local Runtime to manage Profiles.</p>) : null}{data !== undefined && !data.writable ? (- <p className="settings-notice">当前 CODEX_HOME 为只读,无法修改 Profile</p>+ <p className="settings-notice">CODEX_HOME is read-only. Profiles cannot be changed.</p>) : null}{data !== undefined && !data.baseConfigValid ? (- <p className="settings-notice">基础 config.toml 无效,请先修复配置</p>+ <p className="settings-notice">The base config.toml is invalid. Fix it first.</p>) : null}{data?.diagnostics.map(diagnostic => (<p className="settings-inline-warning" key={diagnostic}>{diagnostic}</p>@@ -215,7 +215,7 @@ export function ProfileSettingsView(props: {setEditor(undefined);pageIssues.resolveOperation(operationId);} catch (reason) {- pageIssues.captureOperationFailure(operationId, reason, '无法保存 Profile,请检查配置后重试。');+ pageIssues.captureOperationFailure(operationId, reason, 'Could not save the Profile. Check the settings and try again.');} finally {setSaving(false);}@@ -226,15 +226,15 @@ export function ProfileSettingsView(props: {{loading ? (<div className="settings-state" role="status"><LoaderCircle size={20} className="settings-spin" />- 正在加载 Profiles+ Loading Profiles</div>) : data !== undefined && data.profiles.length === 0 ? (<div className="settings-state"><FileSliders size={22} />- 暂无 Profile+ No Profiles</div>) : (- <ul className="settings-item-list" aria-label="Profile 列表">+ <ul className="settings-item-list" aria-label="Profile list">{data?.profiles.map(profile => {const busy = busyName === profile.name;return (@@ -243,7 +243,7 @@ export function ProfileSettingsView(props: {<div className="settings-item__title"><FileSliders size={16} /><h2>{profile.name}</h2>- <span data-status={profile.status}>{profile.status === 'valid' ? '有效' : '无效'}</span>+ <span data-status={profile.status}>{profile.status === 'valid' ? 'Valid' : 'Invalid'}</span></div><p>{profileSummary(profile)}</p>{profile.diagnostics.map(diagnostic => (@@ -253,8 +253,8 @@ export function ProfileSettingsView(props: {<div className="settings-item__actions"><buttontype="button"- aria-label={`编辑 ${profile.name}`}- title="编辑"+ aria-label={`Edit ${profile.name}`}+ title="Edit"disabled={!writable || busy}onClick={() => void openEdit(profile)}>@@ -262,8 +262,8 @@ export function ProfileSettingsView(props: {</button><buttontype="button"- aria-label={`删除 ${profile.name}`}- title="删除"+ aria-label={`Delete ${profile.name}`}+ title="Remove"disabled={!writable || busy}onClick={() => void deleteProfile(profile)}>@@ -303,9 +303,9 @@ function ProfileEditor(props: {async function submit(event: FormEvent<HTMLFormElement>) {event.preventDefault();- if (name.trim().length === 0) return setFormError('请输入 Profile 名称');+ if (name.trim().length === 0) return setFormError('Enter a Profile name');if (!/^[A-Za-z0-9_.-]+$/.test(name.trim())) {- return setFormError('Profile 名称只能包含字母、数字、下划线、点和短横线');+ return setFormError('Profile names may contain only letters, numbers, underscores, dots, and hyphens');}const parsed = parseAdvancedConfig(advanced);if (!parsed.ok) return setFormError(parsed.message);@@ -321,79 +321,79 @@ function ProfileEditor(props: {return (<div className="settings-editor settings-state" role="status"><LoaderCircle size={20} className="settings-spin" />- 正在加载 Profile 详情+ Loading Profile details</div>);}return (- <form className="settings-editor" aria-label={props.state.mode === 'create' ? '新建 Profile' : `编辑 ${name}`} onSubmit={submit}>+ <form className="settings-editor" aria-label={props.state.mode === 'create' ? 'New Profile' : `Edit ${name}`} onSubmit={submit}><header><div>- <p>{props.state.mode === 'create' ? '新建配置' : '编辑配置'}</p>- <h2>{props.state.mode === 'create' ? '配置 Codex Profile' : name}</h2>+ <p>{props.state.mode === 'create' ? 'New configuration' : 'Edit configuration'}</p>+ <h2>{props.state.mode === 'create' ? 'Configure Codex Profile' : name}</h2></div>- <button type="button" aria-label="关闭 Profile 编辑器" title="关闭" onClick={props.onCancel}>+ <button type="button" aria-label="Close Profile editor" title="Close" onClick={props.onCancel}><X size={17} /></button></header>{formError ? <p className="settings-error" role="alert">{formError}</p> : null}<div className="settings-form-grid"><label>- <span>Profile 名称</span>+ <span>Profile name</span><input- aria-label="Profile 名称"+ aria-label="Profile name"disabled={props.state.mode === 'edit'}value={name}onChange={event => setName(event.target.value)}/></label><label>- <span>模型</span>+ <span>Model</span><input- aria-label="模型"- placeholder="使用 Codex 默认模型"+ aria-label="Model"+ placeholder="Use the default Codex model"value={model}onChange={event => setModel(event.target.value)}/></label><label>- <span>推理级别</span>- <select aria-label="推理级别" value={reasoning} onChange={event => setReasoning(event.target.value)}>- <option value="">使用默认值</option>- <option value="default">默认</option>- <option value="low">低</option>- <option value="medium">中</option>- <option value="high">高</option>- <option value="xhigh">超高</option>+ <span>Reasoning effort</span>+ <select aria-label="Reasoning effort" value={reasoning} onChange={event => setReasoning(event.target.value)}>+ <option value="">Use default</option>+ <option value="default">Default</option>+ <option value="low">Low</option>+ <option value="medium">Medium</option>+ <option value="high">High</option>+ <option value="xhigh">Extra high</option></select></label><label><span>Sandbox</span><select aria-label="Sandbox" value={sandbox} onChange={event => setSandbox(event.target.value)}>- <option value="">使用默认值</option>- <option value="read-only">只读</option>- <option value="workspace-write">工作区可写</option>- <option value="danger-full-access">完全访问</option>+ <option value="">Use default</option>+ <option value="read-only">Read only</option>+ <option value="workspace-write">Workspace write access</option>+ <option value="danger-full-access">Full access</option></select></label><label className="settings-form-wide">- <span>高级配置 JSON</span>+ <span>Advanced configuration JSON</span><textarea- aria-label="高级配置 JSON"+ aria-label="Advanced configuration JSON"rows={7}spellCheck={false}value={advanced}onChange={event => setAdvanced(event.target.value)}/>- <small>仅支持字符串、有限数字、布尔值和同类型数组。</small>+ <small>Only strings, finite numbers, booleans, and arrays of one type are supported.</small></label></div><footer>- <button className="settings-secondary-button" type="button" onClick={props.onCancel}>取消</button>+ <button className="settings-secondary-button" type="button" onClick={props.onCancel}>Cancel</button><button className="settings-primary-button" type="submit" disabled={props.saving}>{props.saving ? <LoaderCircle size={16} className="settings-spin" /> : <Save size={16} />}- 保存 Profile+ Save Profile</button></footer></form>@@ -414,13 +414,13 @@ function parseAdvancedConfig(value: string):try {parsed = JSON.parse(value || '{}');} catch {- return { ok: false, message: '高级配置必须是有效 JSON' };+ return { ok: false, message: 'Advanced configuration must be valid JSON' };}- if (!isPlainObject(parsed)) return { ok: false, message: '高级配置必须是 JSON 对象' };+ if (!isPlainObject(parsed)) return { ok: false, message: 'Advanced configuration must be a JSON object' };for (const [key, entry] of Object.entries(parsed)) {- if (knownKeys.has(key)) return { ok: false, message: `${key} 请使用上方专用字段配置` };- if (isSensitiveKey(key)) return { ok: false, message: `${key} 属于敏感配置,不能在 Web 页面中编辑` };- if (!isProfileValue(entry)) return { ok: false, message: `${key} 不是支持的 Profile 配置值` };+ if (knownKeys.has(key)) return { ok: false, message: `Configure ${key} using the dedicated field above` };+ if (isSensitiveKey(key)) return { ok: false, message: `${key} is sensitive and cannot be edited in the Web interface` };+ if (!isProfileValue(entry)) return { ok: false, message: `${key} is not a supported Profile configuration value` };}return { ok: true, config: parsed as CodexProfileConfig };}@@ -453,11 +453,11 @@ function readString(value: unknown): string {}function profileSummary(profile: CodexProfileResponse): string {- const model = readString(profile.config.model) || '默认模型';- const reasoning = readString(profile.config.model_reasoning_effort) || '默认推理';- const sandbox = readString(profile.config.sandbox_mode) || '默认 Sandbox';+ const model = readString(profile.config.model) || 'Default model';+ const reasoning = readString(profile.config.model_reasoning_effort) || 'Default reasoning';+ const sandbox = readString(profile.config.sandbox_mode) || 'Default sandbox';const advancedCount = Object.keys(profile.config).filter(key => !knownKeys.has(key)).length;- return [model, reasoning, sandbox, advancedCount > 0 ? `${advancedCount} 项高级配置` : '']+ return [model, reasoning, sandbox, advancedCount > 0 ? `${advancedCount} advanced settings` : ''].filter(Boolean).join(' · ');}diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsxindex b1e413af..0c2db19e 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx@@ -110,7 +110,7 @@ describe('OpenCreatorSidebar', () => {expect(screen.queryByRole('separator')).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: '搜索' })).not.toBeInTheDocument();expect(screen.getByRole('button', { name: '定时任务' })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: '任务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Tasks' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: '插件中心' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: '连接器' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: '我的资产' })).not.toBeInTheDocument();@@ -118,7 +118,7 @@ describe('OpenCreatorSidebar', () => {expect(screen.queryByRole('button', { name: '素材中心' })).not.toBeInTheDocument();expect(screen.getByRole('button', { name: '我的项目' }).nextElementSibling).toBe(screen.getByRole('button', { name: '设置' }));expect(primaryActions).toContainElement(screen.getByRole('button', { name: '设置' }));- expect(screen.getByRole('heading', { name: '项目' })).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Project' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'content-design' })).not.toHaveAttribute('aria-current');expect(screen.getByRole('button', { name: 'content-design' })).toHaveAttribute('data-current-project', 'true');expect(screen.getByRole('button', { name: 'bili' })).toBeInTheDocument();@@ -127,7 +127,7 @@ describe('OpenCreatorSidebar', () => {expect(screen.queryByRole('button', { name: '生成 B 站封面 1天' })).not.toBeInTheDocument();expect(screen.getByText('4天')).toBeInTheDocument();expect(screen.queryByText('登录即可享受云端协作')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '登录' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Sign in to' })).not.toBeInTheDocument();expect(screen.getByRole('button', { name: '设置' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: '更新' })).not.toBeInTheDocument();});@@ -265,8 +265,8 @@ describe('OpenCreatorSidebar', () => {runningConversationIds: new Set(['weekly-progress-brief'])});- expect(screen.getByLabelText('正在运行')).toHaveClass('conversation-run-spinner');- expect(screen.getByRole('button', { name: /整理本周项目进展.*正在运行.*4天/ })).toBeInTheDocument();+ expect(screen.getByLabelText('Running')).toHaveClass('conversation-run-spinner');+ expect(screen.getByRole('button', { name: /整理本周项目进展.*Running.*4天/ })).toBeInTheDocument();});it('shows task rows with running, queued, approval, failed, paused, repair, and unread states', () => {@@ -288,17 +288,17 @@ describe('OpenCreatorSidebar', () => {]});- expect(screen.getByRole('heading', { name: '任务' })).toBeInTheDocument();- expect(screen.getByText('草稿')).toBeInTheDocument();- expect(screen.getByText('运行中')).toBeInTheDocument();- expect(screen.getByText('排队中')).toBeInTheDocument();- expect(screen.getByText('待审批')).toBeInTheDocument();- expect(screen.getByText('失败')).toBeInTheDocument();- expect(screen.getByText('已暂停')).toBeInTheDocument();- expect(screen.getByText('需修复')).toBeInTheDocument();- expect(screen.getByLabelText('未读更新')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Tasks' })).toBeInTheDocument();+ expect(screen.getByText('Draft')).toBeInTheDocument();+ expect(screen.getByText('Running')).toBeInTheDocument();+ expect(screen.getByText('Queued')).toBeInTheDocument();+ expect(screen.getByText('Awaiting approval')).toBeInTheDocument();+ expect(screen.getByText('Failed')).toBeInTheDocument();+ expect(screen.getByText('Paused')).toBeInTheDocument();+ expect(screen.getByText('Needs attention')).toBeInTheDocument();+ expect(screen.getByLabelText('Unread updates')).toBeInTheDocument();expect(document.querySelector('.sidebar-task-spinner')).toBeInTheDocument();- expect(screen.getByRole('button', { name: /异常任务.*需修复/ })).toBeDisabled();+ expect(screen.getByRole('button', { name: /异常任务.*Needs attention/ })).toBeDisabled();});it('highlights a selected draft task without marking its execution project as current', () => {@@ -314,7 +314,7 @@ describe('OpenCreatorSidebar', () => {]});- expect(screen.getByRole('button', { name: /任务草稿.*草稿/ }))+ expect(screen.getByRole('button', { name: /任务草稿.*Draft/ })).toHaveAttribute('aria-current', 'page');expect(screen.getByRole('button', { name: 'content-design' })).not.toHaveAttribute('data-current-project');@@ -328,7 +328,7 @@ describe('OpenCreatorSidebar', () => {onSelectTask});- await user.click(screen.getByRole('button', { name: /暂停任务.*已暂停/ }));+ await user.click(screen.getByRole('button', { name: /暂停任务.*Paused/ }));expect(onSelectTask).toHaveBeenCalledWith('thread-paused');});@@ -349,24 +349,24 @@ describe('OpenCreatorSidebar', () => {onDeleteTask});- await user.click(screen.getByRole('button', { name: '更多 任务草稿' }));- await user.click(screen.getByRole('menuitem', { name: '重命名' }));- const input = screen.getByRole('textbox', { name: '重命名任务 任务草稿' });+ await user.click(screen.getByRole('button', { name: 'More 任务草稿' }));+ await user.click(screen.getByRole('menuitem', { name: 'Rename' }));+ const input = screen.getByRole('textbox', { name: 'Rename task 任务草稿' });await user.clear(input);await user.type(input, '新的任务名{Enter}');expect(onRenameTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'draft' }), '新的任务名');- await user.click(screen.getByRole('button', { name: '归档 正式任务' }));+ await user.click(screen.getByRole('button', { name: 'Archive 正式任务' }));expect(onArchiveTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'scheduled' }));- await user.click(screen.getByRole('button', { name: '更多 正式任务' }));- await user.click(screen.getByRole('menuitem', { name: '删除任务' }));+ await user.click(screen.getByRole('button', { name: 'More 正式任务' }));+ await user.click(screen.getByRole('menuitem', { name: 'Delete task' }));- expect(screen.getByRole('alertdialog', { name: '删除任务' })).toBeInTheDocument();+ expect(screen.getByRole('alertdialog', { name: 'Delete task' })).toBeInTheDocument();expect(onDeleteTask).not.toHaveBeenCalled();- await user.click(screen.getByRole('button', { name: '删除任务' }));+ await user.click(screen.getByRole('button', { name: 'Delete task' }));expect(onDeleteTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'scheduled' }));- expect(screen.queryByRole('alertdialog', { name: '删除任务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('alertdialog', { name: 'Delete task' })).not.toBeInTheDocument();});it('keeps a task draft when its deletion is cancelled', async () => {@@ -378,12 +378,12 @@ describe('OpenCreatorSidebar', () => {onDeleteTask});- await user.click(screen.getByRole('button', { name: '更多 任务草稿' }));- await user.click(screen.getByRole('menuitem', { name: '删除任务' }));+ await user.click(screen.getByRole('button', { name: 'More 任务草稿' }));+ await user.click(screen.getByRole('menuitem', { name: 'Delete task' }));await user.click(screen.getByRole('button', { name: '取消' }));expect(onDeleteTask).not.toHaveBeenCalled();- expect(screen.queryByRole('alertdialog', { name: '删除任务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('alertdialog', { name: 'Delete task' })).not.toBeInTheDocument();});it('collapses the selected project when clicking it again', async () => {@@ -416,15 +416,15 @@ describe('OpenCreatorSidebar', () => {renderSidebar({ onArchiveConversation });const conversation = screen.getByRole('group', { name: '整理本周项目进展' });- await user.click(within(conversation).getByRole('button', { name: '归档' }));+ await user.click(within(conversation).getByRole('button', { name: 'Archive' }));- const dialog = screen.getByRole('alertdialog', { name: '归档对话' });+ const dialog = screen.getByRole('alertdialog', { name: 'Archive conversation' });expect(dialog).toHaveTextContent(- '确认归档“整理本周项目进展”?归档后会从项目列表隐藏,但不会删除项目文件或 Codex 历史。'+ 'Archive "整理本周项目进展"? It will be hidden from the project list. Project files and Codex history are retained.');expect(onArchiveConversation).not.toHaveBeenCalled();- await user.click(within(dialog).getByRole('button', { name: '归档' }));+ await user.click(within(dialog).getByRole('button', { name: 'Archive' }));expect(onArchiveConversation).toHaveBeenCalledWith('weekly-progress-brief');});@@ -442,18 +442,18 @@ describe('OpenCreatorSidebar', () => {});const conversation = screen.getByRole('group', { name: '整理本周项目进展' });- expect(within(conversation).getByRole('button', { name: '更多' }))+ expect(within(conversation).getByRole('button', { name: 'More' })).toBeInTheDocument();- await user.click(within(conversation).getByRole('button', { name: '置顶' }));+ await user.click(within(conversation).getByRole('button', { name: 'Pin' }));expect(onPinConversation).toHaveBeenCalledWith('weekly-progress-brief', true);- await user.click(within(conversation).getByRole('button', { name: '更多' }));- const menu = screen.getByRole('menu', { name: '整理本周项目进展 操作' });+ await user.click(within(conversation).getByRole('button', { name: 'More' }));+ const menu = screen.getByRole('menu', { name: '整理本周项目进展 actions' });expect(menu).toHaveClass('sidebar-conversation-menu--portal');expect(menu.parentElement).toBe(document.body);expect(menu).toHaveStyle({ top: '8px', left: '8px' });- await user.click(screen.getByRole('menuitem', { name: '重命名' }));- const input = within(conversation).getByRole('textbox', { name: '重命名 整理本周项目进展' });+ await user.click(screen.getByRole('menuitem', { name: 'Rename' }));+ const input = within(conversation).getByRole('textbox', { name: 'Rename 整理本周项目进展' });await user.clear(input);await user.type(input, '新的会话标题{Enter}');expect(onRenameConversation).toHaveBeenCalledWith(@@ -461,12 +461,12 @@ describe('OpenCreatorSidebar', () => {'新的会话标题');- await user.click(within(conversation).getByRole('button', { name: '更多' }));- await user.click(screen.getByRole('menuitem', { name: '删除任务' }));- const dialog = screen.getByRole('alertdialog', { name: '删除任务' });- expect(dialog).toHaveTextContent('永久删除');- expect(dialog).toHaveTextContent('不会删除项目文件');- await user.click(within(dialog).getByRole('button', { name: '永久删除' }));+ await user.click(within(conversation).getByRole('button', { name: 'More' }));+ await user.click(screen.getByRole('menuitem', { name: 'Delete conversation' }));+ const dialog = screen.getByRole('alertdialog', { name: 'Delete conversation' });+ expect(dialog).toHaveTextContent('Delete permanently');+ expect(dialog).toHaveTextContent('Project files are retained.');+ await user.click(within(dialog).getByRole('button', { name: 'Delete permanently' }));expect(onDeleteConversation).toHaveBeenCalledWith('weekly-progress-brief');});@@ -475,12 +475,12 @@ describe('OpenCreatorSidebar', () => {renderSidebar({ onArchiveConversation: vi.fn() });const conversation = screen.getByRole('group', { name: '整理本周项目进展' });- await user.click(within(conversation).getByRole('button', { name: '更多' }));- expect(screen.getByRole('menu', { name: '整理本周项目进展 操作' })).toBeInTheDocument();+ await user.click(within(conversation).getByRole('button', { name: 'More' }));+ expect(screen.getByRole('menu', { name: '整理本周项目进展 actions' })).toBeInTheDocument();fireEvent(window, new Event('resize'));- expect(screen.queryByRole('menu', { name: '整理本周项目进展 操作' })).not.toBeInTheDocument();+ expect(screen.queryByRole('menu', { name: '整理本周项目进展 actions' })).not.toBeInTheDocument();});it('does not allow archiving a conversation while it is running', () => {@@ -490,7 +490,7 @@ describe('OpenCreatorSidebar', () => {});const conversation = screen.getByRole('group', { name: '整理本周项目进展' });- expect(within(conversation).getByRole('button', { name: '归档' })).toBeDisabled();+ expect(within(conversation).getByRole('button', { name: 'Archive' })).toBeDisabled();});it('opens settings from the primary sidebar navigation', async () => {@@ -512,7 +512,7 @@ describe('OpenCreatorSidebar', () => {renderSidebar({ onAddProject });- await user.click(screen.getByRole('button', { name: '创建项目' }));+ await user.click(screen.getByRole('button', { name: 'Create project' }));expect(onAddProject).toHaveBeenCalledTimes(1);});@@ -526,19 +526,19 @@ describe('OpenCreatorSidebar', () => {onArchiveProject});- await user.click(screen.getByRole('button', { name: '项目操作 content-design' }));- const remove = screen.getByRole('menuitem', { name: '移除项目 content-design' });- expect(remove).toHaveAttribute('title', '仅从项目列表移除,不会删除本机文件');+ await user.click(screen.getByRole('button', { name: 'Project actions content-design' }));+ const remove = screen.getByRole('menuitem', { name: 'Remove project content-design' });+ expect(remove).toHaveAttribute('title', 'Remove from the project list without deleting local files');await user.click(remove);- expect(screen.getByRole('alertdialog', { name: '移除项目' })).toBeInTheDocument();- expect(screen.getByText('确认从 OpenCreator 中移除“content-design”?项目目录和文件不会被删除。'))+ expect(screen.getByRole('alertdialog', { name: 'Remove project' })).toBeInTheDocument();+ expect(screen.getByText('Remove "content-design" from OpenCreator? The project folder and files are retained.')).toBeInTheDocument();expect(onArchiveProject).not.toHaveBeenCalled();- await user.click(screen.getByRole('button', { name: '移除项目' }));+ await user.click(screen.getByRole('button', { name: 'Remove project' }));expect(onArchiveProject).toHaveBeenCalledWith('content-design');- expect(screen.queryByRole('alertdialog', { name: '移除项目' })).not.toBeInTheDocument();+ expect(screen.queryByRole('alertdialog', { name: 'Remove project' })).not.toBeInTheDocument();});it('keeps a project when removal is cancelled', async () => {@@ -546,12 +546,12 @@ describe('OpenCreatorSidebar', () => {const onArchiveProject = vi.fn();renderSidebar({ projects, onArchiveProject });- await user.click(screen.getByRole('button', { name: '项目操作 content-design' }));- await user.click(screen.getByRole('menuitem', { name: '移除项目 content-design' }));+ await user.click(screen.getByRole('button', { name: 'Project actions content-design' }));+ await user.click(screen.getByRole('menuitem', { name: 'Remove project content-design' }));await user.click(screen.getByRole('button', { name: '取消' }));expect(onArchiveProject).not.toHaveBeenCalled();- expect(screen.queryByRole('alertdialog', { name: '移除项目' })).not.toBeInTheDocument();+ expect(screen.queryByRole('alertdialog', { name: 'Remove project' })).not.toBeInTheDocument();});it('shows directory replacement only when the host provides that capability', async () => {@@ -559,16 +559,16 @@ describe('OpenCreatorSidebar', () => {const onReplaceProjectDirectory = vi.fn();const view = renderSidebar({ onArchiveProject: vi.fn() });- await user.click(screen.getByRole('button', { name: '项目操作 content-design' }));- expect(screen.queryByRole('menuitem', { name: '更换目录' })).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Project actions content-design' }));+ expect(screen.queryByRole('menuitem', { name: 'Change folder' })).not.toBeInTheDocument();view.unmount();renderSidebar({onArchiveProject: vi.fn(),onReplaceProjectDirectory});- await user.click(screen.getByRole('button', { name: '项目操作 content-design' }));- await user.click(screen.getByRole('menuitem', { name: '更换目录' }));+ await user.click(screen.getByRole('button', { name: 'Project actions content-design' }));+ await user.click(screen.getByRole('menuitem', { name: 'Change folder' }));expect(onReplaceProjectDirectory).toHaveBeenCalledWith('content-design');});@@ -580,7 +580,7 @@ describe('OpenCreatorSidebar', () => {renderSidebar({ onNewConversation });await user.click(screen.getByRole('button', {- name: '在 content-design 中新建会话'+ name: 'New conversation in content-design'}));expect(onNewConversation).toHaveBeenCalledWith('content-design');@@ -625,8 +625,8 @@ describe('OpenCreatorSidebar', () => {renderSidebar({ projectNavigationMode: 'library' });expect(screen.queryByRole('button', { name: '定时任务' })).not.toBeInTheDocument();- expect(screen.queryByRole('heading', { name: '任务' })).not.toBeInTheDocument();- expect(screen.queryByText('暂无任务')).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Tasks' })).not.toBeInTheDocument();+ expect(screen.queryByText('No tasks')).not.toBeInTheDocument();});it('collapses from the header action', async () => {@@ -657,7 +657,7 @@ describe('OpenCreatorSidebar', () => {expect(screen.queryByRole('button', { name: '收起侧栏' })).not.toBeInTheDocument();expect(screen.getByRole('button', { name: '我的项目' })).toHaveAttribute('title', '我的项目');expect(screen.queryByText('折叠时隐藏的任务')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '登录' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Sign in to' })).not.toBeInTheDocument();expect(screen.getByRole('navigation', { name: 'OpenCreator' })).toHaveAttribute('data-collapsed', 'true');await user.click(screen.getByRole('button', { name: '展开侧栏' }));diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.tsxindex 318635ef..c9846b0b 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.tsx@@ -315,15 +315,15 @@ export function OpenCreatorSidebar(props: {{collapsed || props.projectNavigationMode !== 'tree' ? null : (<section className="sidebar-section" aria-labelledby="opencreator-projects-heading"><div className="sidebar-section-heading">- <h2 id="opencreator-projects-heading">项目</h2>+ <h2 id="opencreator-projects-heading">Project</h2>{props.onAddProject || props.onManageProjects ? (<div className="sidebar-section-actions">{props.onAddProject ? (<buttontype="button"className="sidebar-section-action"- aria-label="创建项目"- title="创建项目"+ aria-label="Create project"+ title="Create project"onClick={props.onAddProject}><FolderPlus size={16} strokeWidth={1.9} aria-hidden="true" />@@ -333,8 +333,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-section-action"- aria-label="管理项目"- title="管理项目"+ aria-label="Manage projects"+ title="Manage projects"onClick={props.onManageProjects}><Settings2 size={16} strokeWidth={1.9} aria-hidden="true" />@@ -343,7 +343,7 @@ export function OpenCreatorSidebar(props: {</div>) : null}</div>- <div className="sidebar-project-tree" aria-label="项目和对话">+ <div className="sidebar-project-tree" aria-label="Projects and conversations">{props.projects.map((project) => {const isCurrentProject =!selectedTaskThread && project.id === props.currentProjectId;@@ -380,8 +380,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-project-new-conversation"- aria-label={`在 ${project.name} 中新建会话`}- title="新建会话"+ aria-label={`New conversation in ${project.name}`}+ title="New conversation"onClick={() => props.onNewConversation(project.id)}><SquarePen size={16} strokeWidth={1.9} aria-hidden="true" />@@ -391,8 +391,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-project-menu-trigger"- aria-label={`项目操作 ${project.name}`}- title="项目操作"+ aria-label={`Project actions ${project.name}`}+ title="Project actions"aria-haspopup="menu"aria-expanded={projectMenuId === project.id}onClick={() => setProjectMenuId(@@ -405,7 +405,7 @@ export function OpenCreatorSidebar(props: {<divclassName="sidebar-project-menu"role="menu"- aria-label={`${project.name} 项目操作`}+ aria-label={`${project.name} project actions`}><buttontype="button"@@ -416,7 +416,7 @@ export function OpenCreatorSidebar(props: {}}><Settings2 size={15} strokeWidth={1.9} aria-hidden="true" />- <span>编辑项目</span>+ <span>Edit project</span></button>{props.onReplaceProjectDirectory ? (<button@@ -428,21 +428,21 @@ export function OpenCreatorSidebar(props: {}}><FolderCog size={15} strokeWidth={1.9} aria-hidden="true" />- <span>更换目录</span>+ <span>Change folder</span></button>) : null}<buttontype="button"role="menuitem"- aria-label={`移除项目 ${project.name}`}- title="仅从项目列表移除,不会删除本机文件"+ aria-label={`Remove project ${project.name}`}+ title="Remove from the project list without deleting local files"onClick={() => {setProjectMenuId(undefined);setProjectPendingRemoval({ id: project.id, name: project.name });}}><FolderMinus size={15} strokeWidth={1.9} aria-hidden="true" />- <span>移除项目</span>+ <span>Remove project</span></button></div>) : null}@@ -451,7 +451,7 @@ export function OpenCreatorSidebar(props: {</div></div>{isExpanded && projectConversations.length > 0 ? (- <div className="sidebar-conversation-tree" aria-label={`${project.name} 对话`}>+ <div className="sidebar-conversation-tree" aria-label={`${project.name} conversations`}>{projectConversations.map((conversation) => {const isRunning = props.runningConversationIds?.has(conversation.id) === true;return (@@ -465,7 +465,7 @@ export function OpenCreatorSidebar(props: {{conversationRename?.id === conversation.id ? (<inputclassName="sidebar-conversation-rename-input"- aria-label={`重命名 ${conversationRename.originalTitle}`}+ aria-label={`Rename ${conversationRename.originalTitle}`}autoFocusvalue={conversationRename.title}onChange={event => setConversationRename(current => (@@ -523,7 +523,7 @@ export function OpenCreatorSidebar(props: {className="conversation-run-spinner"size={13}strokeWidth={2}- aria-label="正在运行"+ aria-label="Running"/>) : null}<span className="conversation-updated-label">{conversation.updatedLabel}</span>@@ -537,8 +537,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-conversation-action"- aria-label="更多"- title="更多"+ aria-label="More"+ title="More"aria-haspopup="menu"aria-expanded={conversationMenuId === conversation.id}onClick={event => {@@ -556,7 +556,7 @@ export function OpenCreatorSidebar(props: {<divclassName="sidebar-conversation-menu sidebar-conversation-menu--portal"role="menu"- aria-label={`${conversation.title} 操作`}+ aria-label={`${conversation.title} actions`}ref={conversationMenuPortalRef}style={conversationMenuPosition}>@@ -573,7 +573,7 @@ export function OpenCreatorSidebar(props: {}}><Pencil size={15} strokeWidth={1.9} aria-hidden="true" />- <span>重命名</span>+ <span>Rename</span></button><buttontype="button"@@ -589,7 +589,7 @@ export function OpenCreatorSidebar(props: {}}><Trash2 size={15} strokeWidth={1.9} aria-hidden="true" />- <span>删除任务</span>+ <span>Delete conversation</span></button></div>), document.body)@@ -599,8 +599,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-conversation-action sidebar-conversation-archive"- aria-label="归档"- title={isRunning ? '任务运行结束后可归档' : '归档会话'}+ aria-label="Archive"+ title={isRunning ? 'Archive after the task finishes' : 'Archive conversation'}disabled={isRunning|| archivingConversationId === conversation.id@@ -628,8 +628,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-conversation-action"- aria-label={conversation.pinnedAt == null ? '置顶' : '取消置顶'}- title={conversation.pinnedAt == null ? '置顶会话' : '取消置顶'}+ aria-label={conversation.pinnedAt == null ? 'Pin' : 'Unpin'}+ title={conversation.pinnedAt == null ? 'Pin conversation' : 'Unpin'}disabled={conversationActionBusyId === conversation.id}onClick={() => {setConversationActionBusyId(conversation.id);@@ -662,11 +662,11 @@ export function OpenCreatorSidebar(props: {className="sidebar-section sidebar-task-section"aria-labelledby="opencreator-tasks-heading">- <h2 id="opencreator-tasks-heading">任务</h2>+ <h2 id="opencreator-tasks-heading">Tasks</h2>{props.tasks.length === 0 ? (- <p className="sidebar-empty">暂无任务</p>+ <p className="sidebar-empty">No tasks</p>) : (- <div className="sidebar-task-list" aria-label="任务会话">+ <div className="sidebar-task-list" aria-label="Task conversations">{props.tasks.map(task => {const visual = taskStatusVisual(task.status);const StatusIcon = visual.icon;@@ -685,7 +685,7 @@ export function OpenCreatorSidebar(props: {{isRenaming ? (<inputclassName="sidebar-task-rename-input"- aria-label={`重命名任务 ${task.name}`}+ aria-label={`Rename task ${task.name}`}autoFocusvalue={taskRename.title}onChange={event => setTaskRename(current => current === undefined@@ -742,7 +742,7 @@ export function OpenCreatorSidebar(props: {<span>{detail}</span></span>{task.unread ? (- <span className="sidebar-task-unread" aria-label="未读更新" />+ <span className="sidebar-task-unread" aria-label="Unread updates" />) : null}</button>}{isRenaming ? null : (@@ -751,7 +751,7 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-task-action"- aria-label={`更多 ${task.name}`}+ aria-label={`More ${task.name}`}aria-haspopup="menu"aria-expanded={taskMenuId === task.id}onClick={event => {@@ -766,7 +766,7 @@ export function OpenCreatorSidebar(props: {<divclassName="sidebar-task-menu sidebar-task-menu--portal"role="menu"- aria-label={`${task.name} 操作`}+ aria-label={`${task.name} actions`}ref={taskMenuPortalRef}style={taskMenuPosition}>@@ -774,13 +774,13 @@ export function OpenCreatorSidebar(props: {setTaskMenuId(undefined);setTaskRename({ id: task.id, originalTitle: task.name, title: task.name });}}>- <Pencil size={15} aria-hidden="true" /><span>重命名</span>+ <Pencil size={15} aria-hidden="true" /><span>Rename</span></button><button type="button" role="menuitem" className="is-destructive" disabled={isRunning} onClick={() => {setTaskMenuId(undefined);setTaskPendingDeletion(task);}}>- <Trash2 size={15} aria-hidden="true" /><span>删除任务</span>+ <Trash2 size={15} aria-hidden="true" /><span>Delete task</span></button></div>), document.body) : null}@@ -788,8 +788,8 @@ export function OpenCreatorSidebar(props: {<buttontype="button"className="sidebar-task-action sidebar-task-archive"- aria-label={`归档 ${task.name}`}- title={isRunning ? '任务运行结束后可归档' : '归档任务'}+ aria-label={`Archive ${task.name}`}+ title={isRunning ? 'Archive after the task finishes' : 'Archive task'}disabled={isRunning || taskActionBusyId === task.id}onClick={() => {setTaskActionBusyId(task.id);@@ -821,11 +821,11 @@ export function OpenCreatorSidebar(props: {<ConfirmDialogopen={conversationPendingDeletion !== undefined}- title="删除任务"+ title="Delete conversation"description={conversationPendingDeletion === undefined- ? '永久删除后无法恢复,但不会删除项目文件。'- : `确认永久删除“${conversationPendingDeletion.title}”?会话及历史记录将无法恢复,但不会删除项目文件。`}- confirmLabel="永久删除"+ ? 'Permanent deletion cannot be undone. Project files are retained.'+ : `Permanently delete "${conversationPendingDeletion.title}"? The conversation and history cannot be recovered. Project files are retained.`}+ confirmLabel="Delete permanently"destructivebusy={conversationActionBusyId !== undefined}onCancel={() => setConversationPendingDeletion(undefined)}@@ -841,11 +841,11 @@ export function OpenCreatorSidebar(props: {/><ConfirmDialogopen={conversationPendingArchive !== undefined}- title="归档对话"+ title="Archive conversation"description={conversationPendingArchive === undefined- ? '归档后会从项目列表隐藏,但不会删除项目文件或 Codex 历史。'- : `确认归档“${conversationPendingArchive.title}”?归档后会从项目列表隐藏,但不会删除项目文件或 Codex 历史。`}- confirmLabel="归档"+ ? 'Archiving hides this conversation from the project list. Project files and Codex history are retained.'+ : `Archive "${conversationPendingArchive.title}"? It will be hidden from the project list. Project files and Codex history are retained.`}+ confirmLabel="Archive"busy={archivingConversationId !== undefined}onCancel={() => setConversationPendingArchive(undefined)}onConfirm={() => {@@ -860,11 +860,11 @@ export function OpenCreatorSidebar(props: {/><ConfirmDialogopen={projectPendingRemoval !== undefined}- title="移除项目"+ title="Remove project"description={projectPendingRemoval === undefined- ? '项目目录和文件不会被删除。'- : `确认从 OpenCreator 中移除“${projectPendingRemoval.name}”?项目目录和文件不会被删除。`}- confirmLabel="移除项目"+ ? 'The project folder and files will not be deleted.'+ : `Remove "${projectPendingRemoval.name}" from OpenCreator? The project folder and files are retained.`}+ confirmLabel="Remove project"destructiveonCancel={() => setProjectPendingRemoval(undefined)}onConfirm={() => {@@ -875,11 +875,11 @@ export function OpenCreatorSidebar(props: {/><ConfirmDialogopen={taskPendingDeletion !== undefined}- title="删除任务"+ title="Delete task"description={taskPendingDeletion === undefined- ? '删除后无法恢复。'- : `确认删除“${taskPendingDeletion.name}”?删除后无法恢复。`}- confirmLabel="删除任务"+ ? 'Deletion cannot be undone.'+ : `Delete "${taskPendingDeletion.name}"? This cannot be undone.`}+ confirmLabel="Delete task"destructivebusy={taskActionBusyId !== undefined}onCancel={() => setTaskPendingDeletion(undefined)}@@ -895,9 +895,9 @@ export function OpenCreatorSidebar(props: {/><ConfirmDialogopen={draftPendingDeletion !== undefined}- title="删除任务草稿"- description="此操作不会删除项目文件。"- confirmLabel="删除草稿"+ title="Delete task draft"+ description="Project files are retained."+ confirmLabel="Delete draft"destructivebusy={deletingDraftThreadId !== undefined}onCancel={() => setDraftPendingDeletion(undefined)}@@ -940,21 +940,21 @@ function taskStatusVisual(status: SidebarTaskStatus): {} {switch (status) {case 'draft':- return { icon: SquarePen, label: '草稿' };+ return { icon: SquarePen, label: 'Draft' };case 'running':- return { icon: LoaderCircle, label: '运行中' };+ return { icon: LoaderCircle, label: 'Running' };case 'queued':- return { icon: Clock3, label: '排队中' };+ return { icon: Clock3, label: 'Queued' };case 'waiting_approval':- return { icon: ShieldAlert, label: '待审批' };+ return { icon: ShieldAlert, label: 'Awaiting approval' };case 'failed':- return { icon: CircleAlert, label: '失败' };+ return { icon: CircleAlert, label: 'Failed' };case 'paused':- return { icon: PauseCircle, label: '已暂停' };+ return { icon: PauseCircle, label: 'Paused' };case 'repair_required':- return { icon: TriangleAlert, label: '需修复' };+ return { icon: TriangleAlert, label: 'Needs attention' };case 'idle':- return { icon: Clock3, label: '等待首次运行' };+ return { icon: Clock3, label: 'Waiting for first run' };}}diff --git a/apps/web/src/features/shell/sidebar-task-model.test.ts b/apps/web/src/features/shell/sidebar-task-model.test.tsindex 402dbcbb..37c22ddc 100644--- a/apps/web/src/features/shell/sidebar-task-model.test.ts+++ b/apps/web/src/features/shell/sidebar-task-model.test.ts@@ -15,7 +15,7 @@ describe('sidebar task model', () => {threadId: null,bindingStatus: 'repair_required',bindingIssue: 'missing_thread_id',- statusMessage: '任务会话需要修复',+ statusMessage: 'The task conversation needs attention',currentRunStatus: null}),createSummary({ scheduleId: 'approval', threadId: 'thread-approval' }),@@ -90,7 +90,7 @@ describe('sidebar task model', () => {status: 'idle',unread: true});- expect(task?.nextRunLabel).toMatch(/^下次 /);+ expect(task?.nextRunLabel).toMatch(/^Next /);});it('shows schedule drafts as task rows with approval and active-run priority', () => {diff --git a/apps/web/src/features/shell/sidebar-task-model.ts b/apps/web/src/features/shell/sidebar-task-model.tsindex c7e6ed07..df5f7593 100644--- a/apps/web/src/features/shell/sidebar-task-model.ts+++ b/apps/web/src/features/shell/sidebar-task-model.ts@@ -75,7 +75,7 @@ export function createScheduleDraftSidebarSummaries(return {id: `draft:${draft.id}`,threadId: draft.id,- name: draft.title?.trim() || '任务草稿',+ name: draft.title?.trim() || 'Task draft',status: resolveScheduleDraftStatus(threadTasks,runningThreadIds.has(draft.id)@@ -128,7 +128,7 @@ function formatNextRunLabel(value: string | null): string | undefined {if (value === null) return undefined;const date = new Date(value);if (!Number.isFinite(date.getTime())) return undefined;- return `下次 ${new Intl.DateTimeFormat('zh-CN', {+ return `Next ${new Intl.DateTimeFormat('en-US', {month: 'numeric',day: 'numeric',hour: '2-digit',diff --git a/apps/web/src/features/tasks/TaskCenter.test.tsx b/apps/web/src/features/tasks/TaskCenter.test.tsxindex a4fc73cb..db676bf6 100644--- a/apps/web/src/features/tasks/TaskCenter.test.tsx+++ b/apps/web/src/features/tasks/TaskCenter.test.tsx@@ -58,7 +58,7 @@ describe('TaskCenter', () => {expect(onMarkRead).toHaveBeenCalledWith('run_1');expect(onOpenTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'run_1' }));- await user.click(screen.getByRole('button', { name: '全部已读' }));+ await user.click(screen.getByRole('button', { name: 'Mark all read' }));expect(onClearUnread).toHaveBeenCalledTimes(1);});@@ -86,13 +86,13 @@ describe('TaskCenter', () => {/>);- await user.click(await screen.findByRole('tab', { name: '待审批' }));+ await user.click(await screen.findByRole('tab', { name: 'Awaiting approval' }));expect(list).toHaveBeenLastCalledWith({status: 'waiting_approval',limit: 20});- await user.click(await screen.findByRole('button', { name: '批准' }));+ await user.click(await screen.findByRole('button', { name: 'Approve' }));expect(approve).toHaveBeenCalledWith('approval_1');});@@ -138,8 +138,8 @@ describe('TaskCenter', () => {.toBeInTheDocument();expect(screen.queryByText('/workspace')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '编辑项目' }));- await user.click(screen.getByRole('button', { name: '暂停任务' }));+ await user.click(screen.getByRole('button', { name: 'Edit project' }));+ await user.click(screen.getByRole('button', { name: 'Pause task' }));expect(onEditSchedule).toHaveBeenCalledWith('schedule_1');expect(onPauseSchedule).toHaveBeenCalledWith('schedule_1');diff --git a/apps/web/src/features/tasks/TaskCenter.tsx b/apps/web/src/features/tasks/TaskCenter.tsxindex 698bd8fd..7ec324d6 100644--- a/apps/web/src/features/tasks/TaskCenter.tsx+++ b/apps/web/src/features/tasks/TaskCenter.tsx@@ -37,11 +37,11 @@ type ApprovalService = {};const FILTERS: Array<{ value: TaskStatusFilter; label: string }> = [- { value: 'all', label: '全部' },- { value: 'active', label: '进行中' },- { value: 'waiting_approval', label: '待审批' },- { value: 'terminal', label: '已结束' },- { value: 'failed', label: '失败' }+ { value: 'all', label: 'All' },+ { value: 'active', label: 'Running' },+ { value: 'waiting_approval', label: 'Awaiting approval' },+ { value: 'terminal', label: 'Finished' },+ { value: 'failed', label: 'Failed' }];export function TaskCenter(props: {@@ -73,7 +73,7 @@ export function TaskCenter(props: {async function loadTasks(reset: boolean) {if (props.service === null) {setTasks([]);- pageIssues.captureOperationFailure('tasks.load', new Error('runtime_unavailable'), '本地运行内核未连接');+ pageIssues.captureOperationFailure('tasks.load', new Error('runtime_unavailable'), 'The local Runtime is disconnected');return;}if (reset) setLoading(true);@@ -89,7 +89,7 @@ export function TaskCenter(props: {setHasMore(response.hasMore);pageIssues.resolveOperation('tasks.load');} catch (loadError) {- pageIssues.captureOperationFailure('tasks.load', loadError, '无法加载任务,请重试。', { retryable: true });+ pageIssues.captureOperationFailure('tasks.load', loadError, 'Could not load tasks. Try again.', { retryable: true });} finally {setLoading(false);setLoadingMore(false);@@ -121,7 +121,7 @@ export function TaskCenter(props: {)));await loadTasks(true);} catch (approvalError) {- pageIssues.captureOperationFailure('tasks.approval', approvalError, '审批操作未完成,请重试。');+ pageIssues.captureOperationFailure('tasks.approval', approvalError, 'The approval operation did not complete. Try again.');} finally {setResolvingIds(current => {const next = new Set(current);@@ -137,7 +137,7 @@ export function TaskCenter(props: {await props.onPauseSchedule(scheduleId);await loadTasks(true);} catch (pauseError) {- pageIssues.captureOperationFailure('tasks.pause-schedule', pauseError, '无法暂停任务,请重试。');+ pageIssues.captureOperationFailure('tasks.pause-schedule', pauseError, 'Could not pause the task. Try again.');}}@@ -146,20 +146,20 @@ export function TaskCenter(props: {<div className="task-center__inner"><header className="task-center__header"><div>- <h1>任务中心</h1>- <p>查看跨会话运行、待审批操作和最近结果。</p>+ <h1>Task center</h1>+ <p>View runs across conversations, pending approvals, and recent results.</p></div><div className="task-center__header-actions">{props.unreadIds.size > 0 ? (<button type="button" onClick={props.onClearUnread}><Check size={15} aria-hidden="true" />- 全部已读+ Mark all read</button>) : null}{props.notificationSettings.enabled ? (<button type="button" onClick={props.onDisableNotifications}><BellOff size={15} aria-hidden="true" />- 关闭通知+ Disable notifications</button>) : (<button@@ -168,13 +168,13 @@ export function TaskCenter(props: {onClick={() => void props.onEnableNotifications()}><Bell size={15} aria-hidden="true" />- 开启通知+ Enable notifications</button>)}<buttontype="button"- aria-label="刷新任务"- title="刷新任务"+ aria-label="Refresh tasks"+ title="Refresh tasks"onClick={() => void loadTasks(true)}><RefreshCw size={15} aria-hidden="true" />@@ -182,7 +182,7 @@ export function TaskCenter(props: {</div></header>- <div className="task-center__filters" role="tablist" aria-label="任务筛选">+ <div className="task-center__filters" role="tablist" aria-label="Task filters">{FILTERS.map(item => (<buttonkey={item.value}@@ -204,12 +204,12 @@ export function TaskCenter(props: {{loading ? (<div className="task-center__state" role="status"><LoaderCircle className="task-center__spin" size={22} />- 正在加载任务+ Loading tasks</div>) : tasks.length === 0 ? (<div className="task-center__state"><Clock3 size={22} />- <strong>当前筛选下没有任务</strong>+ <strong>No tasks match these filters</strong></div>) : (<ul className="task-center__list">@@ -248,7 +248,7 @@ export function TaskCenter(props: {onClick={() => void loadTasks(false)}>{loadingMore ? <LoaderCircle className="task-center__spin" size={15} /> : null}- {loadingMore ? '正在加载' : '加载更多'}+ {loadingMore ? 'Loading' : 'Load more'}</button>) : null}</div>@@ -295,7 +295,7 @@ function TaskRow(props: {<div><button type="button" disabled={props.resolving} onClick={props.onReject}><X size={14} aria-hidden="true" />- 拒绝+ Reject</button><buttonclassName="task-row__approve"@@ -304,7 +304,7 @@ function TaskRow(props: {onClick={props.onApprove}><Check size={14} aria-hidden="true" />- 批准+ Approve</button></div></div>@@ -314,26 +314,26 @@ function TaskRow(props: {<div><strong>{props.task.consecutiveFailureCount === undefined- ? '项目目录需要更新'- : `已连续失败 ${props.task.consecutiveFailureCount} 次`}+ ? 'The project directory needs updating'+ : `${props.task.consecutiveFailureCount} consecutive failures`}</strong><span>{props.task.suggestPause- ? '建议先暂停任务,更新项目目录后再恢复。'- : '更新项目目录后可以重新执行。'}+ ? 'Pause the task, update the project directory, then resume it.'+ : 'Retry after updating the project directory.'}</span></div><div>{props.onEditSchedule === undefined ? null : (<button type="button" onClick={props.onEditSchedule}><FolderOpen size={14} aria-hidden="true" />- 编辑项目+ Edit project</button>)}{!props.task.suggestPause || props.onPauseSchedule === undefined ? null : (<button type="button" onClick={() => void props.onPauseSchedule?.()}><PauseCircle size={14} aria-hidden="true" />- 暂停任务+ Pause task</button>)}</div>@@ -352,17 +352,17 @@ function mergeTasks(current: TaskItem[], incoming: TaskItem[]): TaskItem[] {function formatStatus(status: TaskItem['status']): string {switch (status) {case 'waiting_approval':- return '等待审批';+ return 'Awaiting approval';case 'queued':- return '排队中';+ return 'Queued';case 'running':- return '运行中';+ return 'Running';case 'succeeded':- return '已完成';+ return 'Completed';case 'failed':- return '失败';+ return 'Failed';case 'canceled':- return '已取消';+ return 'Canceled';}}@@ -372,9 +372,9 @@ function taskSummary(task: TaskItem): string {return task.pendingApproval.summary;}if (task.status === 'queued' && task.queuePosition !== undefined) {- return `队列第 ${task.queuePosition} 位 · ${task.cwd}`;+ return `Queue position ${task.queuePosition} · ${task.cwd}`;}- if (task.status === 'failed') return '任务未完成,请打开会话查看详情。';+ if (task.status === 'failed') return 'The task did not complete. Open its conversation for details.';return `${task.profile} · ${task.cwd}`;}@@ -392,15 +392,15 @@ function formatTime(value: string): string {function formatDuration(task: TaskItem): string {const start = new Date(task.startedAt ?? task.createdAt).getTime();const end = new Date(task.endedAt ?? task.updatedAt).getTime();- if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return '时长未知';+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return 'Unknown duration';const seconds = Math.max(0, Math.round((end - start) / 1_000));- if (seconds < 60) return `${seconds} 秒`;+ if (seconds < 60) return `${seconds}s`;const minutes = Math.floor(seconds / 60);const remainingSeconds = seconds % 60;if (minutes < 60) return remainingSeconds === 0- ? `${minutes} 分钟`- : `${minutes} 分 ${remainingSeconds} 秒`;+ ? `${minutes}m`+ : `${minutes}m ${remainingSeconds}s`;const hours = Math.floor(minutes / 60);const remainingMinutes = minutes % 60;- return remainingMinutes === 0 ? `${hours} 小时` : `${hours} 小时 ${remainingMinutes} 分`;+ return remainingMinutes === 0 ? `${hours}h` : `${hours}h ${remainingMinutes}m`;}diff --git a/apps/web/src/features/tasks/task-monitor.test.ts b/apps/web/src/features/tasks/task-monitor.test.tsindex 0c10c951..ba9a8a60 100644--- a/apps/web/src/features/tasks/task-monitor.test.ts+++ b/apps/web/src/features/tasks/task-monitor.test.ts@@ -88,7 +88,7 @@ describe('task monitor', () => {failureSummary: '项目目录不存在或无法访问,请编辑项目后重试。'}))).toEqual({- title: '任务失败',+ title: 'Task failed',body: '整理发布说明:项目目录不存在或无法访问,请编辑项目后重试。',threadId: 'thread_1',runId: 'run_1'@@ -123,8 +123,8 @@ describe('task monitor', () => {errorMessage: 'Authorization: Bearer private-token'}))).toEqual({- title: '每日总结失败',- body: '任务未完成,请打开会话查看详情。',+ title: '每日总结: failed',+ body: 'The task did not complete. Open its conversation for details.',threadId: 'thread_1',runId: 'run_1'});@@ -156,7 +156,7 @@ describe('task monitor', () => {}}))).toEqual({- title: '每日总结等待审批',+ title: '每日总结: awaiting approval',body: '需要允许写入 docs/daily',threadId: 'thread_1',runId: 'run_1',diff --git a/apps/web/src/features/tasks/task-monitor.ts b/apps/web/src/features/tasks/task-monitor.tsindex 8e1c20bf..5a8ec26c 100644--- a/apps/web/src/features/tasks/task-monitor.ts+++ b/apps/web/src/features/tasks/task-monitor.ts@@ -58,11 +58,11 @@ export function createTaskNotification(task: TaskItem): {if (task.createdBy === 'schedule') {return {title: task.status === 'waiting_approval'- ? `${task.title}等待审批`+ ? `${task.title}: awaiting approval`: task.status === 'failed'- ? `${task.title}失败`+ ? `${task.title}: failed`: task.status === 'canceled'- ? `${task.title}已取消`+ ? `${task.title}: canceled`: task.title,body: detail,...target@@ -70,12 +70,12 @@ export function createTaskNotification(task: TaskItem): {}const title = task.status === 'waiting_approval'- ? '任务等待审批'+ ? 'Task awaiting approval': task.status === 'succeeded'- ? '任务已完成'+ ? 'Task completed': task.status === 'canceled'- ? '任务已取消'- : '任务失败';+ ? 'Task canceled'+ : 'Task failed';return {title,body: `${task.title}:${detail}`,@@ -86,17 +86,17 @@ export function createTaskNotification(task: TaskItem): {function notificationDetail(task: TaskItem): string {switch (task.status) {case 'waiting_approval':- return task.pendingApproval?.summary ?? '需要你的审批。';+ return task.pendingApproval?.summary ?? 'Your approval is required.';case 'succeeded':- return task.resultSummary ?? '任务已完成。';+ return task.resultSummary ?? 'The task is complete.';case 'failed':- return task.failureSummary ?? '任务未完成,请打开会话查看详情。';+ return task.failureSummary ?? 'The task did not complete. Open its conversation for details.';case 'canceled':- return '本次任务已取消。';+ return 'This task was canceled.';case 'queued':- return '任务正在排队。';+ return 'The task is queued.';case 'running':- return '任务正在运行。';+ return 'The task is running.';}}diff --git a/apps/web/src/features/threads/ThreadList.tsx b/apps/web/src/features/threads/ThreadList.tsxindex 405afb1a..3ec671e7 100644--- a/apps/web/src/features/threads/ThreadList.tsx+++ b/apps/web/src/features/threads/ThreadList.tsx@@ -10,12 +10,12 @@ export function ThreadList(props: {<div className="thread-list"><div className="panel-header"><button className="thread-new-button" type="button" onClick={props.onNewThread}>- 新对话+ New conversation</button></div><div className="thread-list-scroll">{props.threads.length === 0 ? (- <p className="empty-state compact">暂无真实会话</p>+ <p className="empty-state compact">No conversations yet</p>) : (props.threads.map((thread) => (<buttondiff --git a/apps/web/src/host/browser-bridge.ts b/apps/web/src/host/browser-bridge.tsindex 246c5648..76d5d95c 100644--- a/apps/web/src/host/browser-bridge.ts+++ b/apps/web/src/host/browser-bridge.ts@@ -65,7 +65,7 @@ export const browserBridge: HostBridge = {window.open(url, '_blank', 'noopener,noreferrer');},async revealPath(_path: string): Promise<HostBridgeResult> {- return { ok: false, code: 'UNSUPPORTED', message: '浏览器版不支持在系统文件管理器中显示路径' };+ return { ok: false, code: 'UNSUPPORTED', message: 'Revealing paths in the system file manager is unavailable in the browser' };},async notify(message: HostNotification): Promise<void> {if (diff --git a/apps/web/src/runtime/client.test.ts b/apps/web/src/runtime/client.test.tsindex 9cf7bab4..3e70c49f 100644--- a/apps/web/src/runtime/client.test.ts+++ b/apps/web/src/runtime/client.test.ts@@ -174,7 +174,7 @@ describe('RuntimeClient', () => {code: 'IMAGE_GENERATION_CONFIG_REQUIRED',issue: {publicFacts: { kind: 'configuration', httpStatus: 409 },- fallbackMessage: expect.stringContaining('配置')+ fallbackMessage: expect.stringContaining('configuration')}});});diff --git a/apps/web/src/runtime/client.ts b/apps/web/src/runtime/client.tsindex d2066be0..c7d79515 100644--- a/apps/web/src/runtime/client.ts+++ b/apps/web/src/runtime/client.ts@@ -108,7 +108,7 @@ export class RuntimeClient {code,source: 'network',category: 'network',- fallbackMessage: timeout ? '请求超时,请检查连接后重试。' : '无法连接本地服务,请检查服务状态后重试。',+ fallbackMessage: timeout ? 'The request timed out. Check the connection and try again.' : 'Could not connect to the local Runtime. Check its status and try again.',publicFacts: { kind: timeout ? 'timeout' : 'unknown' }})});@@ -151,7 +151,7 @@ async function readSuccessfulJson(response: Response, path: string): Promise<unkcode: 'INVALID_JSON_RESPONSE',source: 'api',category: 'execution',- fallbackMessage: '本地服务返回了无法读取的结果,请重试。',+ fallbackMessage: 'The local Runtime returned an unreadable response. Try again.',publicFacts: { kind: 'invalid-response' }})});@@ -299,10 +299,10 @@ function categoryForStatus(status: number): IssueCategory {}function fallbackForStatus(status: number): string {- if (status === 401 || status === 403) return '当前操作没有权限,请检查登录或授权设置。';- if (status === 404) return '请求的内容不存在或已被移除。';- if (status === 409) return '当前状态已发生变化,请刷新后重试。';- return '操作未完成,请稍后重试。';+ if (status === 401 || status === 403) return 'This operation requires permission. Check sign-in or authorization settings.';+ if (status === 404) return 'The requested content is missing or was removed.';+ if (status === 409) return 'The current state has changed. Refresh and try again.';+ return 'The operation did not complete. Try again later.';}function publicFactsForApiError(code: string, status: number): PublicErrorFacts {@@ -317,12 +317,12 @@ function publicFactsForApiError(code: string, status: number): PublicErrorFactsfunction fallbackForApiError(code: string, status: number): string {const kind = publicErrorKindForCode(code);- if (kind === 'configuration') return '缺少或无法读取此操作所需的配置,请检查相关服务设置。';- if (kind === 'validation') return '输入或参数未通过校验,请检查后重试。';- if (kind === 'not-found') return '请求的资源不存在或已被移除。';- if (kind === 'conflict') return '当前状态与此操作冲突,请刷新状态后重试。';- if (kind === 'unsupported') return '当前环境或服务不支持此操作。';- if (kind === 'storage') return '本地文件或结果未能写入,请检查存储状态。';+ if (kind === 'configuration') return 'Required configuration is missing or unreadable. Check the service settings.';+ if (kind === 'validation') return 'The input or parameters failed validation. Check them and try again.';+ if (kind === 'not-found') return 'The requested resource is missing or was removed.';+ if (kind === 'conflict') return 'The current state conflicts with this operation. Refresh and try again.';+ if (kind === 'unsupported') return 'This environment or service does not support the operation.';+ if (kind === 'storage') return 'Could not write the local file or result. Check storage status.';return fallbackForStatus(status);}diff --git a/apps/web/src/runtime/use-runtime-connection.ts b/apps/web/src/runtime/use-runtime-connection.tsindex 8d50e2e7..b8486575 100644--- a/apps/web/src/runtime/use-runtime-connection.ts+++ b/apps/web/src/runtime/use-runtime-connection.ts@@ -16,7 +16,7 @@ export type RuntimeRecovery = {export function useRuntimeConnection(host: HostBridge, fetchImpl: typeof fetch) {const [config, setConfig] = useState<ConnectionConfig | null>(null);- const [state, setState] = useState<ConnectionState>({ status: 'disconnected', message: '正在连接本地服务' });+ const [state, setState] = useState<ConnectionState>({ status: 'disconnected', message: 'Connecting to the local Runtime' });const [progress, setProgress] = useState<Omit<RuntimeRecovery, 'state' | 'retry' | 'restart'>>({phase: 'connecting', attempt: 0, epoch: 0});@@ -51,11 +51,11 @@ export function useRuntimeConnection(host: HostBridge, fetchImpl: typeof fetch)setConfig(previous => sameConfig(previous, nextConfig) ? previous : nextConfig);}next = currentConfig === null- ? { status: 'disconnected', message: '正在等待本地服务启动' }+ ? { status: 'disconnected', message: 'Waiting for the local Runtime to start' }: await createConnectionService(new RuntimeClient({ ...currentConfig, fetchImpl })).check({ signal: activeController.signal });} catch (error) {- next = { status: 'disconnected', message: error instanceof Error ? error.message : '本地服务连接失败' };+ next = { status: 'disconnected', message: error instanceof Error ? error.message : 'Could not connect to the local Runtime' };}if (!active()) return;setState(next);@@ -81,7 +81,7 @@ export function useRuntimeConnection(host: HostBridge, fetchImpl: typeof fetch)if (closed) return;if (nextConfig === null) {connected = false;- setState({ status: 'disconnected', message: '本地服务暂时断开,正在重连' });+ setState({ status: 'disconnected', message: 'The local Runtime disconnected. Reconnecting.' });setProgress(previous => ({ ...previous, phase: 'reconnecting' }));} else {currentConfig = nextConfig;@@ -110,7 +110,7 @@ export function useRuntimeConnection(host: HostBridge, fetchImpl: typeof fetch)if (!result.ok) throw new Error(result.message);await refreshRef.current();} catch (error) {- setProgress(previous => ({ ...previous, phase: 'failed', message: error instanceof Error ? error.message : '重启本地服务失败' }));+ setProgress(previous => ({ ...previous, phase: 'failed', message: error instanceof Error ? error.message : 'Could not restart the local Runtime' }));} finally {restartWorkRef.current = undefined;}@@ -132,7 +132,7 @@ function sameConfig(previous: ConnectionConfig | null, next: ConnectionConfig):function readConfig(host: HostBridge, signal: AbortSignal): Promise<ConnectionConfig | null> {return new Promise((resolve, reject) => {- const timer = setTimeout(() => finish(() => reject(new Error('读取本地服务配置超时'))), 4_000);+ const timer = setTimeout(() => finish(() => reject(new Error('Reading the local Runtime configuration timed out'))), 4_000);const onAbort = () => finish(() => reject(signal.reason));function finish(callback: () => void) {clearTimeout(timer);diff --git a/packages/protocol/src/creator-provider-catalog.ts b/packages/protocol/src/creator-provider-catalog.tsindex 9352a99f..bd8d6529 100644--- a/packages/protocol/src/creator-provider-catalog.ts+++ b/packages/protocol/src/creator-provider-catalog.ts@@ -30,16 +30,16 @@ export const creatorProviderCatalog = [entry({ id: 'minimax', kind: 'llm', label: 'MiniMax', protocol: 'openai-compatible', defaultBaseUrl: 'https://api.minimax.io', models: [{ id: 'MiniMax-M2.7', label: 'MiniMax M2.7', recommended: true }, { id: 'MiniMax-M2.7-highspeed', label: 'MiniMax M2.7 Highspeed' }, { id: 'MiniMax-M2.5', label: 'MiniMax M2.5' }, { id: 'MiniMax-M2.5-highspeed', label: 'MiniMax M2.5 Highspeed' }], credentials: ['apiKey'], status: 'supported' }),entry({ id: 'custom', kind: 'llm', label: 'Custom OpenAI-compatible', protocol: 'custom', models: [], credentials: ['apiKey'], status: 'supported' }),entry({ id: 'openai', kind: 'image', label: 'OpenAI', protocol: 'openai-compatible', defaultBaseUrl: 'https://api.openai.com/v1', models: [{ id: 'gpt-image-1', label: 'GPT Image', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-image', 'image-edit', 'reference-image'], status: 'supported' }),- entry({ id: 'jimeng', kind: 'image', label: '即梦 / Seedream', protocol: 'openai-compatible', defaultBaseUrl: 'https://ark.cn-beijing.volces.com/api/v3', models: [{ id: 'doubao-seedream-4-0-250828', label: 'Seedream 4.0', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-image'], status: 'supported' }),- entry({ id: 'kling', kind: 'image', label: '可灵 / Kling', protocol: 'kling', defaultBaseUrl: 'https://api-beijing.klingai.com', models: [{ id: 'kling-v2-1', label: 'Kling v2.1', recommended: true }], credentials: ['accessKey', 'secretKey'], capabilities: ['text-to-image'], status: 'supported' }),+ entry({ id: 'jimeng', kind: 'image', label: 'Jimeng / Seedream', protocol: 'openai-compatible', defaultBaseUrl: 'https://ark.cn-beijing.volces.com/api/v3', models: [{ id: 'doubao-seedream-4-0-250828', label: 'Seedream 4.0', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-image'], status: 'supported' }),+ entry({ id: 'kling', kind: 'image', label: 'Kling', protocol: 'kling', defaultBaseUrl: 'https://api-beijing.klingai.com', models: [{ id: 'kling-v2-1', label: 'Kling v2.1', recommended: true }], credentials: ['accessKey', 'secretKey'], capabilities: ['text-to-image'], status: 'supported' }),entry({ id: 'gemini', kind: 'image', label: 'Nano Banana / Gemini', protocol: 'gemini', defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta', models: [{ id: 'gemini-2.5-flash-image', label: 'Nano Banana', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-image', 'reference-image'], status: 'supported' }),entry({ id: 'codex-native', kind: 'image', label: 'Local Codex image generation', protocol: 'local', models: [], credentials: [], capabilities: ['text-to-image', 'image-edit', 'reference-image'], status: 'experimental' }),entry({ id: 'seedance', kind: 'video', label: 'Seedance', protocol: 'openai-compatible', defaultBaseUrl: 'https://ark.cn-beijing.volces.com/api/v3', models: [{ id: 'doubao-seedance-2-5-260628', label: 'Seedance 2.5', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-video', 'image-to-video'], status: 'supported' }),- entry({ id: 'kling-video', kind: 'video', label: '可灵 / Kling', protocol: 'kling', defaultBaseUrl: 'https://api-beijing.klingai.com', models: [{ id: 'kling-v2-1-master', label: 'Kling v2.1 Master', recommended: true }], credentials: ['accessKey', 'secretKey'], capabilities: ['text-to-video', 'image-to-video'], status: 'supported' }),+ entry({ id: 'kling-video', kind: 'video', label: 'Kling', protocol: 'kling', defaultBaseUrl: 'https://api-beijing.klingai.com', models: [{ id: 'kling-v2-1-master', label: 'Kling v2.1 Master', recommended: true }], credentials: ['accessKey', 'secretKey'], capabilities: ['text-to-video', 'image-to-video'], status: 'supported' }),entry({ id: 'veo', kind: 'video', label: 'Veo', protocol: 'gemini', defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta', models: [{ id: 'veo-3.1-generate-preview', label: 'Veo 3.1', recommended: true }], credentials: ['apiKey'], capabilities: ['text-to-video', 'image-to-video'], status: 'supported' }),entry({ id: 'openai-tts', kind: 'tts', label: 'OpenAI Voice', protocol: 'openai-compatible', defaultBaseUrl: 'https://api.openai.com/v1', models: [{ id: 'gpt-4o-mini-tts', label: 'GPT-4o mini TTS', recommended: true }], credentials: ['apiKey'], capabilities: ['speech-generation', 'voice-preview'], status: 'supported' }),entry({ id: 'minimax-tts', kind: 'tts', label: 'MiniMax Voice', protocol: 'openai-compatible', defaultBaseUrl: 'https://api.minimax.io', models: [{ id: 'speech-2.8-hd', label: 'Speech 2.8 HD', recommended: true }], credentials: ['apiKey'], capabilities: ['speech-generation', 'voice-preview'], status: 'supported' }),- entry({ id: 'aliyun-tts', kind: 'tts', label: '阿里云 Voice', protocol: 'openai-compatible', defaultBaseUrl: 'https://dashscope.aliyuncs.com/api/v1', models: [{ id: 'qwen3-tts-flash', label: 'Qwen3 TTS Flash', recommended: true }], credentials: ['apiKey'], capabilities: ['speech-generation', 'voice-preview'], status: 'supported' }),+ entry({ id: 'aliyun-tts', kind: 'tts', label: 'Alibaba Cloud Voice', protocol: 'openai-compatible', defaultBaseUrl: 'https://dashscope.aliyuncs.com/api/v1', models: [{ id: 'qwen3-tts-flash', label: 'Qwen3 TTS Flash', recommended: true }], credentials: ['apiKey'], capabilities: ['speech-generation', 'voice-preview'], status: 'supported' }),entry({ id: 'edge-tts', kind: 'tts', label: 'Edge TTS', protocol: 'custom', models: [], credentials: [], capabilities: ['speech-generation'], status: 'supported' })] as const;diff --git a/packages/protocol/src/creator-services.ts b/packages/protocol/src/creator-services.tsindex 12373195..2ded0c5b 100644--- a/packages/protocol/src/creator-services.ts+++ b/packages/protocol/src/creator-services.ts@@ -224,8 +224,8 @@ export function creatorPreflightFailure(result: CreatorPreflightResponse): {};const id = Object.keys(codes).find(id => result.blocked.some(item => item.id === id));const code = id === undefined ? 'creator_preflight_blocked' : codes[id]!;- const message = safePublicErrorMessage(result.blocked.map(item => item.message).join(';'))- ?? '启动条件检查未通过,请检查任务配置。';+ const message = safePublicErrorMessage(result.blocked.map(item => item.message).join('; '))+ ?? 'Preflight checks failed. Review the task configuration.';return { code, message, publicFacts: {kind: publicErrorKindForCode(code) ?? 'validation', upstreamMessage: message,...(id === 'reference-image-required' ? { upstreamCode: 'IMAGE_REFERENCE_MISSING' } : {})diff --git a/packages/protocol/src/gateway-account.ts b/packages/protocol/src/gateway-account.tsindex 638c83a6..8b26ec0c 100644--- a/packages/protocol/src/gateway-account.ts+++ b/packages/protocol/src/gateway-account.ts@@ -10,6 +10,7 @@ export type GatewayModel = {durations?: number[];resolutions?: string[];aspectRatios?: string[];+ verification?: { adapterVersion: number; verifiedAt: string; countries: string[] };imageOptions?: {aspectRatios?: string[];resolutions?: string[];diff --git a/packages/protocol/src/wechat-article.ts b/packages/protocol/src/wechat-article.tsindex 7005a75f..6ad38d23 100644--- a/packages/protocol/src/wechat-article.ts+++ b/packages/protocol/src/wechat-article.ts@@ -114,57 +114,57 @@ export const wechatArticleLayoutStyles: ReadonlyArray<{{id: 'minimal',categories: ['recommended', 'technology', 'lifestyle'],- name: '知识手记',- description: '清爽但不单薄,适合观点、复盘与知识分享',- features: ['编号章节', '结论卡片', '阅读留白'],+ name: 'Knowledge Notes',+ description: 'Clean and thoughtful, for insights, reviews, and knowledge sharing',+ features: ['Numbered sections', 'Key takeaways', 'Reading space'],instructions: '使用知识手记式 Markdown 结构。一级标题后用一段加粗导语概括核心判断;主体使用带 01、02、03 编号的二级标题;每节保持二到四个短段落。重要结论使用引用块形成结论卡片,操作要点使用列表,重要转场使用分隔线。结尾用一个简短的行动清单或总结收束。不要堆叠装饰符号。'},{id: 'business',categories: ['recommended', 'business'],- name: '商业报告',- description: '摘要先行、数据醒目,适合行业与公司内容',- features: ['内容摘要', '数据重点', '结论边栏'],+ name: 'Business Report',+ description: 'Summary first, with prominent data, for industry and company analysis',+ features: ['Executive summary', 'Data highlights', 'Conclusion sidebar'],instructions: '使用商业报告式 Markdown 结构。一级标题后先写一段加粗的执行摘要;二级标题直接表达章节结论,三级标题用于拆分论据。数据、对比和关键事实优先使用列表或表格;引用块只承载关键判断或风险提示;章节之间使用分隔线。语气专业克制,结尾明确列出三项以内的决策建议或后续观察。'},{id: 'editorial',categories: ['lifestyle', 'humanities'],- name: '杂志特写',- description: '叙事舒展、金句突出,适合人物与深度故事',- features: ['题记导语', '叙事章节', '金句引用'],+ name: 'Magazine Feature',+ description: 'Flowing narratives and memorable quotes, for profiles and in-depth stories',+ features: ['Opening passage', 'Narrative sections', 'Pull quotes'],instructions: '使用杂志特写式 Markdown 结构。一级标题简洁有叙事张力,随后用一段加粗的题记或导语建立场景;正文段落有长短变化,二级标题写成有画面感的章节标题。关键句单独使用引用块,重要转场使用分隔线;列表只在确有并列信息时使用。结尾回扣开篇场景或核心意象,保留余味,不使用教程式口号。'},{id: 'vibrant',categories: ['recommended', 'lifestyle', 'humanities'],- name: '行动清单',- description: '步骤鲜明、重点醒目,适合方法与实操内容',- features: ['步骤模块', '提示便签', '完成清单'],+ name: 'Action Checklist',+ description: 'Clear steps and key points, for methods and practical guides',+ features: ['Step sections', 'Tip notes', 'Completion checklist'],instructions: '使用行动清单式 Markdown 结构。开篇先说明读者问题和完成后的收益;主体优先使用清晰的步骤编号和动作导向的二级标题。每一步包含目的、操作和注意事项;关键提醒使用引用块,检查项使用任务清单或无序列表,必要时用加粗突出动作。结尾提供可立即执行的完成清单。不要使用大量 emoji 或夸张符号。'},{id: 'technical',categories: ['recommended', 'technology', 'business'],- name: '技术教程',- description: '代码、参数和步骤层次清楚,适合产品与开发教程',- features: ['步骤导航', '代码区块', '避坑提示'],+ name: 'Technical Tutorial',+ description: 'Structured code, parameters, and steps, for product and development tutorials',+ features: ['Step navigation', 'Code blocks', 'Common pitfalls'],instructions: '使用技术教程式 Markdown 结构。一级标题后用加粗导语说明适用对象、前置条件和最终结果;按步骤组织二级标题,三级标题解释原理或备选方案。命令、代码、配置和文件内容必须使用代码块;参数对比可使用表格;引用块用于“注意”“避坑”或兼容性提醒;结尾提供验证清单。不得编造无法由来源确认的命令、版本或配置。'},{id: 'podcast',categories: ['technology'],- name: '播客访谈',- description: '突出对话与原声观点,适合播客、圆桌和人物访谈',- features: ['嘉宾发言', '对话层级', '观点摘录'],+ name: 'Podcast Interview',+ description: 'Conversation and original perspectives, for podcasts, roundtables, and interviews',+ features: ['Guest remarks', 'Conversation structure', 'Insight excerpts'],instructions: '使用播客访谈式 Markdown 结构。一级标题后用一段加粗导语交代节目、嘉宾和核心议题;开篇可选取二到三句最有代表性的原话作为引用块。主体使用概括核心观点的二级标题分章;需要呈现对话时,以“### 主持人 · 姓名”或“### 嘉宾 · 姓名”标明发言者,紧接引用块放置该人物的原话,不得把不同发言者合并在同一个引用块中。引用之后用普通段落补充背景、解释与事实核验。只把来源中可以确认的内容写成直接引语,不得改写后加引号或虚构发言。结尾整理节目来源、关键观点和延伸阅读。'},{id: 'newsroom',categories: ['news', 'business'],- name: '热点简报',- description: '先讲事实再做判断,适合新闻、事件与趋势解读',- features: ['事实速览', '时间脉络', '影响判断'],+ name: 'News Brief',+ description: 'Facts before analysis, for news, events, and trends',+ features: ['Quick facts', 'Timeline', 'Impact analysis'],instructions: '使用热点简报式 Markdown 结构。一级标题后用加粗导语在三句话内说明发生了什么、为什么重要;第一个二级章节为事实速览,用列表列出时间、主体和已确认信息;后续章节依次解释背景、影响和待观察事项。引用块用于标记核心判断,并明确区分事实与推测;分隔线用于切换事实和分析。结尾列出接下来值得关注的二到四个信号。'}];diff --git a/runtime/krillinai/scripts/verify-openrouter-asr/main.go b/runtime/krillinai/scripts/verify-openrouter-asr/main.gonew file mode 100644index 00000000..9ba5f13f--- /dev/null+++ b/runtime/krillinai/scripts/verify-openrouter-asr/main.go@@ -0,0 +1,96 @@+package main++import (+ "encoding/base64"+ "encoding/json"+ "fmt"+ "krillin-ai/pkg/whisper"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+)++func main() {+ if len(os.Args) != 3 {+ panic("Supply a real ASR report.json and its reference WAV")+ }+ data, err := os.ReadFile(os.Args[1])+ must(err)+ var report struct {+ Language string `json:"language"`+ Results []struct {+ Model string `json:"model"`+ Modality string `json:"modality"`+ Status string `json:"status"`+ UpstreamMetadata struct {+ HTTPStatus int `json:"httpStatus"`+ } `json:"upstreamMetadata"`+ } `json:"results"`+ }+ must(json.Unmarshal(data, &report))+ if report.Language == "" {+ report.Language = "en"+ }+ checked := 0+ for _, result := range report.Results {+ if result.Modality != "transcription" || (result.Status != "passed" && result.UpstreamMetadata.HTTPStatus != 200) {+ continue+ }+ root := filepath.Join(filepath.Dir(os.Args[1]), strings.ReplaceAll(result.Model, "/", "__"), "receipts")+ files, err := os.ReadDir(root)+ must(err)+ if len(files) != 1 {+ panic("Expected one real provider receipt")+ }+ data, err = os.ReadFile(filepath.Join(root, files[0].Name()))+ must(err)+ var receipt struct {+ State string `json:"state"`+ Content string `json:"content"`+ }+ must(json.Unmarshal(data, &receipt))+ if receipt.State != "succeeded" {+ panic("Receipt is not a completed real transcription")+ }+ payload, err := base64.StdEncoding.DecodeString(receipt.Content)+ must(err)+ requests := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests+++ must(r.ParseMultipartForm(1 << 20))+ if r.FormValue("model") != result.Model || r.FormValue("response_format") != "verbose_json" || r.FormValue("timestamp_granularities[]") != "segment" {+ panic("Unexpected production ASR request parameters")+ }+ w.Header().Set("Content-Type", "application/json")+ _, err := w.Write(payload)+ must(err)+ }))+ client := whisper.NewOfficialClient(server.URL, "local-replay-only", "", result.Model)+ transcription, err := client.Transcription(os.Args[2], report.Language, filepath.Dir(os.Args[2]))+ server.Close()+ must(err)+ if requests != 1 || strings.TrimSpace(transcription.Text) == "" || len(transcription.Words) == 0 {+ panic("Real response cannot be consumed as subtitles")+ }+ for _, word := range transcription.Words {+ if word.Start < 0 || word.End <= word.Start || strings.TrimSpace(word.Text) == "" {+ panic("Invalid parsed subtitle timing")+ }+ }+ checked+++ output, err := json.Marshal(map[string]any{"model": result.Model, "subtitleEntries": len(transcription.Words), "text": transcription.Text, "paidSubmissions": 0})+ must(err)+ fmt.Println(string(output))+ }+ if checked == 0 {+ panic("No passed real ASR responses in the report")+ }+}++func must(err error) {+ if err != nil {+ panic(err)+ }+}