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(creator): auto-configure local Codex and stabilize media workflows
Leggettfedcd5a8a8de
diff --git a/apps/daemon/src/api/routes.creator-services.ts b/apps/daemon/src/api/routes.creator-services.tsindex da53ebb8..0968a7c8 100644--- a/apps/daemon/src/api/routes.creator-services.ts+++ b/apps/daemon/src/api/routes.creator-services.ts@@ -1,5 +1,6 @@import type {CodexImageStatus,+ CodexProviderConfig,CreatorServicesCapabilitiesResponse,CreatorServicesConfig,CreatorTtsPreviewRequest,@@ -28,9 +29,20 @@ export async function registerCreatorServicesRoutes(createKrillinCreatorServicesCapabilities,ttsService?: Pick<KrillinTtsService, 'listVoices' | 'preview'>,onConfigurationChanged?: () => Promise<void> | void,- readCodexImageStatus?: () => Promise<CodexImageStatus>+ readCodexImageStatus?: () => Promise<CodexImageStatus>,+ readCodexModelStatus?: () => Promise<CodexProviderConfig>): Promise<void> {server.get('/creator-services/capabilities', async () => readCapabilities());+ server.get('/creator-services/model/codex/status', async (_request, reply) => {+ reply.header('Cache-Control', 'no-store');+ try {+ return await readCodexModelStatus?.() ?? {+ authentication: 'none', apiKeyConfigured: false, baseUrl: '', model: ''+ } satisfies CodexProviderConfig;+ } catch {+ return { authentication: 'none', apiKeyConfigured: false, baseUrl: '', model: '' } satisfies CodexProviderConfig;+ }+ });server.get('/creator-services/image/codex/status', async (_request, reply) => {reply.header('Cache-Control', 'no-store');return readCodexImageStatus ? await readCodexImageStatus() : {diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.tsindex e869bf54..b125bb9a 100644--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@ -158,7 +158,7 @@ import {isCodexCredentialStoreConfigurationDiagnostic} from '../codex/credential-storage.js';import { resolveCodexHome } from '../codex/home.js';-import { createCodexIsolatedHome } from '../codex/probe-home.js';+import { createFollowingLocalCodexHome, importLocalCodexConfiguration } from '../codex/probe-home.js';import {createCodexModelCatalog,type CodexModelCatalog@@ -190,6 +190,7 @@ import {createOpenCreatorCreatorServicesConfigStore,type CreatorServicesConfigStore} from '../creator-services/config-store.js';+import { createLocalCodexTextModelDefaults } from '../creator-services/local-codex-defaults.js';import { createSmartDubbingService } from '../smart-dubbing/service.js';import {createCreatorEventHub,@@ -362,7 +363,7 @@ export async function buildServer(input: BuildServerInput) {&& resolvedCodexHome.mode === 'isolated'&& localCodexHome !== codexHome) {- createCodexIsolatedHome(localCodexHome, codexHome);+ importLocalCodexConfiguration(localCodexHome, codexHome);}try {await ensureCodexFileCredentialStore(codexHome);@@ -537,7 +538,9 @@ export async function buildServer(input: BuildServerInput) {const krillinCodexLlmGateway = createKrillinCodexLlmGateway({codexBin,codexHome,- cwd: dataDir+ cwd: dataDir,+ readConfiguration: createFollowingLocalCodexHome(localCodexHome,+ join(runtimeDir, 'creator-text-codex'))});const creatorAgentBootstrapInput = {sourceCodexHome: localCodexHome,@@ -608,20 +611,17 @@ export async function buildServer(input: BuildServerInput) {}}});+ const localCodexTextModelDefaults = createLocalCodexTextModelDefaults({+ codexHome: localCodexHome,+ readGatewayConfig() {+ const baseUrl = resolveListeningOrigin(server.server.address());+ return baseUrl === undefined ? undefined : krillinCodexLlmGateway.config(baseUrl);+ }+ });const creatorServicesConfigStore =createCreatorServicesConfigStoreWithTextModelFallback(storedCreatorServicesConfigStore,- {- async read() {- const provider = await codexProviderConfig.read();- const apiKey = await resolveCodexProviderApiKey(provider);- return {- baseUrl: provider.baseUrl,- model: provider.model,- ...(apiKey === undefined ? {} : { apiKey })- };- }- }+ localCodexTextModelDefaults);const videoMetadataService = input.videoMetadataService ?? createVideoMetadataService({getProxy: async () => (await creatorServicesConfigStore.read()).proxy.trim()@@ -666,7 +666,8 @@ export async function buildServer(input: BuildServerInput) {dataDir,configStore: creatorServicesConfigStore});- const codexImageRuntime = { codexHome, codexBin };+ // Image generation follows the user's local Codex login, independently of Agent settings.+ const codexImageRuntime = { codexHome: localCodexHome, codexBin };const readCodexImageStatus = () => inspectCodexImageRuntime(codexImageRuntime);const imageGenerationService = createImageGenerationService({dataDir,@@ -813,11 +814,7 @@ export async function buildServer(input: BuildServerInput) {configStore: creatorServicesConfigStore,getYtDlpRuntime,verificationCachePath: krillinVerificationCachePath,- ensureRuntimeReady: () => ensureKrillinRuntimeReady(),- getCodexLlmConfig() {- const baseUrl = resolveListeningOrigin(server.server.address());- return baseUrl === undefined ? undefined : krillinCodexLlmGateway.config(baseUrl);- }+ ensureRuntimeReady: () => ensureKrillinRuntimeReady()}));}if (@@ -1434,7 +1431,8 @@ export async function buildServer(input: BuildServerInput) {await coverWorkflow?.resumeConfiguredJobs();await stickmanVideoWorkflow?.resumeConfiguredJobs();},- readCodexImageStatus+ readCodexImageStatus,+ () => localCodexTextModelDefaults.readStatus());await registerSmartDubbingRoutes(server, smartDubbingService);await registerCreatorRuntimeRoutes(server, creatorYtDlpUpdateManager, {diff --git a/apps/daemon/src/codex/local-provider.ts b/apps/daemon/src/codex/local-provider.tsindex a0336d6d..3d1f49c0 100644--- a/apps/daemon/src/codex/local-provider.ts+++ b/apps/daemon/src/codex/local-provider.ts@@ -14,6 +14,22 @@ export type LocalCodexImageConfiguration =| { authentication: 'api_key'; provider: LocalCodexProvider }| { authentication: 'chatgpt' };+export type LocalCodexModelConfiguration =+ | { authentication: 'api_key'; provider: LocalCodexProvider }+ | { authentication: 'chatgpt'; model: string };++export async function readLocalCodexModelConfiguration(input: {+ codexHome: string;+ env?: NodeJS.ProcessEnv;+}): Promise<LocalCodexModelConfiguration> {+ const image = await readLocalCodexImageConfiguration(input);+ const config = await readToml(join(input.codexHome, 'config.toml'), true);+ const model = readString(config.model) || 'codex';+ return image.authentication === 'chatgpt'+ ? { authentication: 'chatgpt', model }+ : { authentication: 'api_key', provider: { ...image.provider, model } };+}+export class LocalCodexProviderError extends Error {constructor(message: string) {super(message);@@ -29,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('ChatGPT 登录凭据不完整,请在 Agent 设置中重新登录');+ throw new LocalCodexProviderError('本机 Codex 的 ChatGPT 登录凭据不完整,请在本机 Codex 中重新登录');}return { authentication: 'chatgpt' };}@@ -41,17 +57,20 @@ export async function readLocalCodexProvider(input: {env?: NodeJS.ProcessEnv;}): Promise<LocalCodexProvider> {const env = input.env ?? process.env;- const config = await readToml(join(input.codexHome, 'config.toml'));+ const config = await readToml(join(input.codexHome, 'config.toml'), true);const providerId = readString(config.model_provider);const providers = readRecord(config.model_providers);const provider = providerId.length === 0? undefined: readRecord(providers?.[providerId]);- const baseUrl = readString(provider?.base_url) || readString(config.openai_base_url);+ const baseUrl = readString(provider?.base_url) || readString(config.openai_base_url)+ || ((!providerId || providerId === 'openai') ? 'https://api.openai.com/v1' : '');const model = readString(config.model);const providerToken = readString(provider?.experimental_bearer_token);const envKey = readString(provider?.env_key);- const envToken = envKey.length === 0 ? '' : (env[envKey]?.trim() ?? '');+ const envToken = envKey.length === 0+ ? ((!providerId || providerId === 'openai') ? env.OPENAI_API_KEY?.trim() ?? '' : '')+ : (env[envKey]?.trim() ?? '');const auth = await readJson(join(input.codexHome, 'auth.json'));const authToken = readString(auth?.OPENAI_API_KEY);const apiKey = providerToken || envToken || authToken;@@ -61,7 +80,7 @@ export async function readLocalCodexProvider(input: {}if (!apiKey) {throw new LocalCodexProviderError(- '本机 Codex 未配置图像接口可用的 API Key,请检查 Agent 配置'+ '本机 Codex 未配置图像接口可用的 API Key,请检查本机 Codex 配置');}return {@@ -71,11 +90,12 @@ export async function readLocalCodexProvider(input: {};}-async function readToml(path: string): Promise<Record<string, TomlValue>> {+async function readToml(path: string, optional = false): Promise<Record<string, TomlValue>> {try {return parse(await readFile(path, 'utf8'));} catch (error) {if (isNotFound(error)) {+ if (optional) return {};throw new LocalCodexProviderError('未找到本机 Codex 配置');}throw new LocalCodexProviderError('无法读取本机 Codex 配置');@@ -90,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 登录凭据,请在 Agent 设置中重新登录或配置 API Key');+ if (strict) throw new LocalCodexProviderError('无法读取本机 Codex 登录凭据,请在本机 Codex 中重新登录或配置 API Key');return undefined;}}diff --git a/apps/daemon/src/codex/probe-home.ts b/apps/daemon/src/codex/probe-home.tsindex 7374b430..31b608eb 100644--- a/apps/daemon/src/codex/probe-home.ts+++ b/apps/daemon/src/codex/probe-home.ts@@ -10,6 +10,7 @@ import {writeFileSync} from 'node:fs';import { tmpdir } from 'node:os';+import { createHash } from 'node:crypto';import {basename,join,@@ -90,6 +91,27 @@ export function importLocalCodexConfiguration(sourceHome: string, isolatedHome:return true;}+export function createFollowingLocalCodexHome(sourceHome: string, isolatedHome: string) {+ let version: string | undefined;+ return () => {+ const digest = createHash('sha256');+ for (const name of ['auth.json', 'config.toml']) {+ const path = join(sourceHome, name);+ digest.update(name);+ if (existsSync(path)) digest.update(readFileSync(path));+ }+ const nextVersion = digest.digest('hex');+ if (nextVersion !== version) {+ for (const name of ['auth.json', 'config.toml']) {+ if (!existsSync(join(sourceHome, name))) rmSync(join(isolatedHome, name), { force: true });+ }+ createCodexIsolatedHome(sourceHome, isolatedHome);+ version = nextVersion;+ }+ return { codexHome: isolatedHome, version: nextVersion };+ };+}+function createMinimalProbeConfig(sourceHome: string, probeHome: string): void {const sourcePath = join(sourceHome, 'config.toml');if (!existsSync(sourcePath)) return;diff --git a/apps/daemon/src/creator-services/config-store.ts b/apps/daemon/src/creator-services/config-store.tsindex fc778704..b108ceb2 100644--- a/apps/daemon/src/creator-services/config-store.ts+++ b/apps/daemon/src/creator-services/config-store.ts@@ -292,7 +292,11 @@ export function createCreatorServicesConfigStoreWithTextModelFallback(},async write(config) {const persisted = structuredClone(config);- if (persisted.llm.source === 'codex') persisted.llm.apiKey = '';+ if (persisted.llm.source === 'codex') {+ const defaults = createDefaultCreatorServicesConfig().llm;+ persisted.llm = { ...persisted.llm, baseUrl: defaults.baseUrl,+ apiKey: '', model: defaults.model };+ }const saved = await store.write(persisted);return resolveTextModelFallback(saved, fallback);},diff --git a/apps/daemon/src/creator-services/local-codex-defaults.ts b/apps/daemon/src/creator-services/local-codex-defaults.tsnew file mode 100644index 00000000..f4c59a52--- /dev/null+++ b/apps/daemon/src/creator-services/local-codex-defaults.ts@@ -0,0 +1,28 @@+import type { CodexProviderConfig } from '@opencreator/protocol';+import { readLocalCodexModelConfiguration } from '../codex/local-provider.js';+import type { CreatorTextModelFallbackProvider, TextModelFallbackConfig } from './config-store.js';++/** Resolve local credentials when used; detecting them never saves a user override. */+export function createLocalCodexTextModelDefaults(input: {+ codexHome: string;+ env?: NodeJS.ProcessEnv;+ readGatewayConfig(): TextModelFallbackConfig | undefined;+}): CreatorTextModelFallbackProvider & { readStatus(): Promise<CodexProviderConfig> } {+ const readLocal = () => readLocalCodexModelConfiguration(input);+ return {+ async readStatus() {+ const local = await readLocal();+ return local.authentication === 'chatgpt'+ ? { authentication: 'chatgpt', apiKeyConfigured: false, baseUrl: '', model: local.model }+ : { authentication: 'api_key', apiKeyConfigured: true,+ baseUrl: local.provider.baseUrl, model: local.provider.model };+ },+ async read() {+ const local = await readLocal();+ // Codex handles both login modes and the selected provider's wire protocol.+ const gateway = input.readGatewayConfig();+ if (gateway === undefined) throw new Error('Local Codex text service is not listening');+ return { ...gateway, model: local.authentication === 'chatgpt' ? local.model : local.provider.model };+ }+ };+}diff --git a/apps/daemon/src/creator/file-hash.ts b/apps/daemon/src/creator/file-hash.tsnew file mode 100644index 00000000..742d05de--- /dev/null+++ b/apps/daemon/src/creator/file-hash.ts@@ -0,0 +1,9 @@+import { createHash } from 'node:crypto';+import { createReadStream } from 'node:fs';++export async function sha256CreatorFile(path: string, signal?: AbortSignal): Promise<string> {+ signal?.throwIfAborted();+ const digest = createHash('sha256');+ for await (const chunk of createReadStream(path, { signal })) digest.update(chunk);+ return digest.digest('hex');+}diff --git a/apps/daemon/src/creator/image/executor.ts b/apps/daemon/src/creator/image/executor.tsindex eb26d197..4ba2b97f 100644--- a/apps/daemon/src/creator/image/executor.ts+++ b/apps/daemon/src/creator/image/executor.ts@@ -5,6 +5,7 @@ import type {ImageGenerationQuality,ImageGenerationSize} from '@opencreator/protocol';+import { imagePromptRequiresReference } from '@opencreator/protocol';import { readFile, rm, writeFile } from 'node:fs/promises';import { join } from 'node:path';import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';@@ -84,6 +85,13 @@ export function createImageExecutor(input: {if (!request.prompt) {throw new CreatorExecutorError('creator_stage_input_missing', 'Image prompt is required');}+ if (stage.job.templateId === 'image-generation' && referenceImage === undefined+ && imagePromptRequiresReference(request.prompt)) {+ const message = '当前提示词需要参考图,但任务没有可用的参考图片。请先上传图片,或移除提示词中对上传图片或原图的要求。';+ throw new CreatorExecutorError('creator_stage_input_missing', message, {}, {+ kind: 'validation', upstreamCode: 'IMAGE_REFERENCE_MISSING', upstreamMessage: message+ });+ }if (request.provider === 'codex-native' && request.count !== 1) {throw new CreatorExecutorError('unsupported_capability',diff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex d66264b8..f86fbdc7 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -1,5 +1,5 @@import { copyFile, link, lstat, mkdir, realpath, rename, writeFile } from 'node:fs/promises';-import { videoSourceIdentity } from '@opencreator/protocol';+import { publicErrorCodeFromFailure, videoSourceIdentity } from '@opencreator/protocol';import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type {CreatorArtifact,@@ -14,6 +14,7 @@ import type {CreatorExecutorResult} from '../executor.js';import { CreatorExecutorError } from '../executor.js';+import { publicFactsFromFailure } from '../public-error-facts.js';import { creatorSubtitleStyleSchema } from '../presets/module-schemas.js';import { validateMediaFile } from '../validators/media.js';import { formatSrtTimestamp, validateSrtFile } from '../validators/srt.js';@@ -116,7 +117,7 @@ export function createKrillinExecutor(input: {code: error.kind === 'usage' ? 'usage' : error.code,message: error.message});- throw new CreatorExecutorError(normalized.code, normalized.message);+ throw CreatorExecutorError.from(normalized.code, error, normalized.message);}const relevantArtifacts = stage.job.templateId === 'auto-clip'&& stage.stageRun.stageId === 'subtitle'@@ -265,13 +266,16 @@ function combineKrillinFallbackFailures(platformFailure: KrillinCliError, fallbafallbackFailure.code,message,fallbackFailure.kind,- fallbackFailure.retryable+ fallbackFailure.retryable,+ { cause: fallbackFailure });}if (fallbackFailure instanceof CreatorExecutorError) {- return new CreatorExecutorError(fallbackFailure.code, message);+ return new CreatorExecutorError(fallbackFailure.code, message, {},+ fallbackFailure.publicFacts, { cause: fallbackFailure });}- return new CreatorExecutorError('krillin_stage_failed', message);+ return new CreatorExecutorError(publicErrorCodeFromFailure(fallbackFailure) ?? 'krillin_stage_failed',+ message, {}, publicFactsFromFailure(fallbackFailure), { cause: fallbackFailure });}export function buildKrillinSubtitleStyle(value: CreatorJson | undefined): Record<string, unknown> | undefined {diff --git a/apps/daemon/src/creator/krillin/cli-runner.ts b/apps/daemon/src/creator/krillin/cli-runner.tsindex 9625b6aa..002fdbf5 100644--- a/apps/daemon/src/creator/krillin/cli-runner.ts+++ b/apps/daemon/src/creator/krillin/cli-runner.ts@@ -1,4 +1,4 @@-import { copyFile, link, mkdir, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';+import { copyFile, link, mkdir, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';import { createHash } from 'node:crypto';import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type {@@ -7,6 +7,8 @@ import type {} from '@opencreator/protocol';import type { CreatorExecutorInput } from '../executor.js';import { CreatorExecutorError } from '../executor.js';+import { sha256CreatorFile } from '../file-hash.js';+import { publicErrorKindForCode, sanitizePublicErrorFacts, type PublicErrorFacts } from '@opencreator/protocol';import { spawnCreatorProcess } from '../process-tree.js';import { createKrillinConfigToml } from './config-bridge.js';import { isYouTubeSource } from './execution-plan.js';@@ -60,14 +62,20 @@ type RunProcess = (input: {}) => Promise<void>;export class KrillinCliError extends Error {+ readonly publicFacts: PublicErrorFacts;constructor(readonly code: string,message: string,readonly kind?: string,- readonly retryable = false+ readonly retryable = false,+ options?: ErrorOptions) {- super(message);+ super(message, options);this.name = 'KrillinCliError';+ this.publicFacts = sanitizePublicErrorFacts({+ kind: publicErrorKindForCode(code) ?? 'unknown', provider: 'krillinai',+ upstreamCode: code, upstreamMessage: message+ });}}@@ -423,7 +431,7 @@ async function collectArtifacts(relativePath: relative(input.jobsRoot, path).replaceAll('\\', '/'),mimeType: mimeType(path),size: info.size,- sha256: createHash('sha256').update(await readFile(path)).digest('hex')+ sha256: await sha256CreatorFile(path, input.stage.signal)});}return result;diff --git a/apps/daemon/src/creator/krillin/codex-llm-gateway.ts b/apps/daemon/src/creator/krillin/codex-llm-gateway.tsindex c3bbd879..62e64a06 100644--- a/apps/daemon/src/creator/krillin/codex-llm-gateway.ts+++ b/apps/daemon/src/creator/krillin/codex-llm-gateway.ts@@ -10,7 +10,7 @@ import {export const KRILLIN_LLM_ROUTE_PREFIX = '/internal/krillin-llm';type ChatMessage = { role: 'system' | 'user' | 'assistant'; content: string };-type HostSlot = { host?: CodexAppServerHost; busy: boolean };+type HostSlot = { host?: CodexAppServerHost; busy: boolean; configurationVersion?: string };const HOST_POOL_SIZE = 2;const MAX_QUEUED_REQUESTS = 32;@@ -21,6 +21,7 @@ export function createKrillinCodexLlmGateway(input: {codexHome: string;cwd: string;createHost?: typeof createCodexAppServerHost;+ readConfiguration?(): { codexHome: string; version: string };}) {const token = `ocllm_${randomBytes(32).toString('base64url')}`;const slots: HostSlot[] = Array.from({ length: HOST_POOL_SIZE }, () => ({ busy: false }));@@ -99,11 +100,13 @@ export function createKrillinCodexLlmGateway(input: {async function runCompletion(messages: ChatMessage[], jsonMode: boolean): Promise<string> {const slot = await acquireSlot();try {- if (slot.host === undefined || !slot.host.isReusable()) {+ const configuration = input.readConfiguration?.();+ if (slot.host === undefined || !slot.host.isReusable()+ || slot.configurationVersion !== configuration?.version) {await slot.host?.close('krillin-llm-host-replaced').catch(() => undefined);slot.host = (input.createHost ?? createCodexAppServerHost)({codexBin: input.codexBin,- codexHome: input.codexHome,+ codexHome: configuration?.codexHome ?? input.codexHome,cwd: resolve(input.cwd),profile: 'default',builtInTools: {@@ -115,6 +118,7 @@ export function createKrillinCodexLlmGateway(input: {}});await slot.host.started;+ slot.configurationVersion = configuration?.version;}return await complete({ host: slot.host, cwd: input.cwd, messages, jsonMode });} catch (error) {diff --git a/apps/daemon/src/creator/preflight.ts b/apps/daemon/src/creator/preflight.tsindex 28c46333..ba716fe8 100644--- a/apps/daemon/src/creator/preflight.ts+++ b/apps/daemon/src/creator/preflight.ts@@ -5,8 +5,10 @@ import type {CreatorPreflightExecutionMode,CreatorPreflightResponse,CreatorServicesCapabilitiesResponse,- CreatorServicesConfig+ CreatorServicesConfig,+ PublicErrorFacts} from '@opencreator/protocol';+import { creatorPreflightFailure, imagePromptRequiresReference } from '@opencreator/protocol';import { access, mkdir } from 'node:fs/promises';import { constants } from 'node:fs';import { join } from 'node:path';@@ -32,25 +34,14 @@ export type CreatorPreflightOptions = {};export class CreatorPreflightError extends Error {+ readonly code: string;+ readonly publicFacts: PublicErrorFacts;constructor(readonly result: CreatorPreflightResponse) {- super('Creator preflight blocked this stage');+ const failure = creatorPreflightFailure(result);+ super(failure.message);this.name = 'CreatorPreflightError';- }-- get code(): string {- const ids = new Set(this.result.blocked.map(item => item.id));- const id = ids.has('llm') ? 'llm'- : ids.has('tts') ? 'tts'- : ids.has('image-provider') ? 'image-provider'- : ids.has('video-provider') ? 'video-provider'- : ids.has('reference-image-capability') ? 'reference-image-capability'- : this.result.blocked[0]?.id;- if (id === 'llm') return 'creator_llm_config_missing';- if (id === 'tts') return 'creator_tts_config_missing';- if (id === 'image-provider') return 'creator_image_config_missing';- if (id === 'video-provider') return 'VIDEO_GENERATION_CONFIG_REQUIRED';- if (id === 'reference-image-capability') return 'unsupported_capability';- return 'creator_preflight_blocked';+ this.code = failure.code;+ this.publicFacts = failure.publicFacts;}}@@ -142,6 +133,16 @@ export function createCreatorPreflight(input: {inputSnapshot?.artifactRefs,inputSnapshot?.state);+ if (job.templateId === 'image-generation' && stage.id === 'generate'+ && typeof inputState.prompt === 'string' && imagePromptRequiresReference(inputState.prompt)+ && !resolvedInputs.artifacts.some(artifact => artifact.kind === 'reference_image'+ && artifact.status === 'completed' && artifact.path !== null)) {+ add('blocked', {+ id: 'reference-image-required', title: '缺少参考图',+ message: '当前提示词需要基于已有图片生成,请先上传参考图;如需纯文字生图,请移除对上传图片或原图的要求。',+ executionMode: 'local'+ }, { label: '上传参考图', deepLink: `#/workbench?tool=image-generation&jobId=${encodeURIComponent(job.id)}` });+ }await checkInputs(stage, resolvedInputs.artifacts, resolvedInputs.missing, add);await checkRuntimeDependencies(job, stage, config, add);await checkManagedDirectory(add);@@ -327,7 +328,7 @@ async function checkProviderConfig(if (stage.executor === 'wechat-article' && stage.id === 'images') needs.add('image');if (needs.has('llm')) {- if (config.llm.source === 'codex' && stage.executor === 'krillinai') {+ if (config.llm.source === 'codex' && stage.executor === 'krillinai' && config.llm.apiKey.trim()) {add('ready', {id: 'llm',title: '文本模型',@@ -357,7 +358,7 @@ async function checkProviderConfig(try { status = await readCodexImageStatus?.(); } catch { status = undefined; }add(status?.ready ? 'ready' : 'blocked', {id: 'image-provider', title: '本机 Codex 生图',- message: status?.message ?? '无法检查 Codex 生图认证和 Runtime 能力,请检查 Agent 配置。',+ message: status?.message ?? '无法检查 Codex 生图认证和 Runtime 能力,请检查本机 Codex 登录和配置。',executionMode: status?.executionMode === 'api' ? 'remote' : 'local'}, { label: '检查生图设置', deepLink: '#/settings?tab=ai-services§ion=image' });} else if (imageProviderConfigured(config, provider)) {diff --git a/apps/daemon/src/creator/public-error-facts.ts b/apps/daemon/src/creator/public-error-facts.tsindex a417062b..ceb2de04 100644--- a/apps/daemon/src/creator/public-error-facts.ts+++ b/apps/daemon/src/creator/public-error-facts.ts@@ -1,6 +1,8 @@import { isPublicErrorFacts, publicErrorKindForCode, sanitizePublicErrorFacts, type PublicErrorFacts } from '@opencreator/protocol';-const NETWORK_CODES: Record<string, PublicErrorFacts['kind']> = {+const ERROR_KINDS: Record<string, PublicErrorFacts['kind']> = {+ ERR_FS_FILE_TOO_LARGE: 'storage',+ EFBIG: 'storage',ENOTFOUND: 'dns',EAI_AGAIN: 'dns',ECONNREFUSED: 'connection-refused',@@ -29,7 +31,7 @@ export function publicFactsFromFailure(? 'timeout': code === undefined? publicErrorKindForCode(errorCode(error) ?? '') ?? 'unknown'- : NETWORK_CODES[code]!;+ : ERROR_KINDS[code]!;return {kind,...(provider === undefined ? {} : { provider }),@@ -87,7 +89,7 @@ function findKnownErrorCode(error: unknown): string | undefined {if (seen.has(current)) break;seen.add(current);const code = (current as { code?: unknown }).code;- if (typeof code === 'string' && NETWORK_CODES[code] !== undefined) return code;+ if (typeof code === 'string' && ERROR_KINDS[code] !== undefined) return code;current = (current as { cause?: unknown }).cause;}return undefined;diff --git a/apps/daemon/src/creator/stage-runner.ts b/apps/daemon/src/creator/stage-runner.tsindex 9e3b9895..6303fc85 100644--- a/apps/daemon/src/creator/stage-runner.ts+++ b/apps/daemon/src/creator/stage-runner.ts@@ -1,9 +1,10 @@-import { createHash } from 'node:crypto';-import { mkdir, readFile } from 'node:fs/promises';+import { mkdir } from 'node:fs/promises';import { join } from 'node:path';import {readCreatorResultSnapshots,publicErrorKindForCode,+ publicErrorCodeFromFailure,+ publicErrorMessageFromFailure,type CreatorArtifact,type CreatorJob,type CreatorJson,@@ -15,6 +16,7 @@ import type { CreatorRepository } from './repository.js';import type { CreatorIssueService } from './issues.js';import { CreatorProviderRequestError } from './provider-requests.js';import { publicFactsFromFailure } from './public-error-facts.js';+import { sha256CreatorFile } from './file-hash.js';import {appendCreatorResultSnapshot,attachCreatorResultArtifacts,@@ -208,7 +210,7 @@ export function createCreatorStageRunner(input: {throw new CreatorOutputValidationError(blockingFinding);}const outputHashes = await Promise.all(result.outputs.map(async output => (- output.path === null ? null : sha256File(output.path)+ output.path === null ? null : sha256CreatorFile(output.path, controller.signal))));input.repository.transaction(() => {const beforeOutputs = requireJob(input.repository, jobId);@@ -341,9 +343,7 @@ export function createCreatorStageRunner(input: {const failureCode = canceled ? 'creator_stage_canceled' : errorCode(error);const failureMessage = canceled? 'Creator stage was canceled'- : error instanceof Error- ? error.message- : 'Creator stage failed';+ : publicErrorMessageFromFailure(error) ?? 'Creator stage failed';const configurationInput = creatorConfigurationInput(error,failureCode,@@ -453,7 +453,7 @@ export function createCreatorStageRunner(input: {: '创作步骤执行失败,可以重试或询问 Agent。',technicalDetail: failureMessage,publicFacts: configurationInput !== null- ? { kind: 'configuration' }+ ? { ...stageFailureFacts(error, failureCode), kind: 'configuration' }: stageFailureFacts(error, failureCode),retryable: !unknownProviderAcceptance,repairActions: [@@ -601,11 +601,6 @@ export function createCreatorStageRunner(input: {}}-async function sha256File(path: string): Promise<string> {- const content = await readFile(path);- return createHash('sha256').update(content).digest('hex');-}-function subtitleOutputSources(kind: string, outputs: CreatorArtifact[], inputs: CreatorArtifact[]): string[] {if (kind === 'source_video') return inputs.filter(artifact => artifact.kind === 'source_video').map(artifact => artifact.id);const imported = inputs.find(artifact => artifact.kind === kind);@@ -788,7 +783,7 @@ function errorCode(error: unknown): string {|| error instanceof CreatorProviderRequestError|| error instanceof CreatorOutputValidationError? error.code- : 'creator_stage_failed';+ : publicErrorCodeFromFailure(error) ?? 'creator_stage_failed';}function resultSnapshotDescription(stageId: string, templateId: string): string {@@ -862,7 +857,10 @@ function creatorConfigurationInput(function stageFailureFacts(error: unknown, code: string) {const facts = publicFactsFromFailure(error);const codeKind = publicErrorKindForCode(code);- return facts.kind === 'unknown' && codeKind !== undefined- ? { ...facts, kind: codeKind }- : facts;+ const message = publicErrorMessageFromFailure(error);+ return {+ ...facts,+ ...(facts.kind === 'unknown' && codeKind !== undefined ? { kind: codeKind } : {}),+ ...(facts.upstreamMessage === undefined && message !== undefined ? { upstreamMessage: message } : {})+ };}diff --git a/apps/daemon/src/image-generation/codex-native.ts b/apps/daemon/src/image-generation/codex-native.tsindex a7935175..7f8ff71b 100644--- a/apps/daemon/src/image-generation/codex-native.ts+++ b/apps/daemon/src/image-generation/codex-native.ts@@ -1,4 +1,4 @@-import type { CreateImageGenerationRequest } from '@opencreator/protocol';+import { safePublicErrorMessage, type CreateImageGenerationRequest, type PublicErrorFacts } from '@opencreator/protocol';import { mkdtemp, mkdir, readFile, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { isAbsolute, join, relative, sep } from 'node:path';@@ -11,6 +11,19 @@ const MAX_IMAGE_BYTES = 30 * 1024 * 1024;const TIMEOUT_MS = 180_000;export type NativeImageProgress = { phase: string; message: string };+class CodexNativeImageError extends Error {+ readonly publicFacts: PublicErrorFacts;+ constructor(message: string, kind: PublicErrorFacts['kind'], detail = message, upstreamCode?: string) {+ super(message);+ this.name = 'CodexNativeImageError';+ this.publicFacts = {+ kind, provider: 'codex-native',+ upstreamMessage: safePublicErrorMessage((detail === message ? message : `${message}。${detail}`).slice(0, 4_000)) ?? message,+ ...(upstreamCode === undefined ? {} : { upstreamCode })+ };+ }+}+export async function generateCodexNativeImage(input: {runtime: CodexNativeImageRuntime;request: CreateImageGenerationRequest;@@ -19,15 +32,16 @@ export async function generateCodexNativeImage(input: {onProgress?(progress: NativeImageProgress): void;}): Promise<GeneratedImageContent> {input.signal.throwIfAborted();- if (!input.runtime.codexBin) throw new Error('当前 Runtime 缺少 Codex 可执行程序');+ if (!input.runtime.codexBin) throw new CodexNativeImageError('当前 Runtime 缺少 Codex 可执行程序', 'configuration');const workdir = await mkdtemp(join(tmpdir(), 'opencreator-codex-image-'));const outputDir = join(workdir, 'output');let process: CodexExecProcess | undefined;const abort = () => process?.cancel();let threadId: string | undefined;let savedPath: string | undefined;- let failure: string | undefined;- let streamError: string | undefined;+ let failure: CodexNativeImageError | undefined;+ let streamError: CodexNativeImageError | undefined;+ let lastAgentMessage = '';let turnFailed = false;const report = (phase: string, message: string) => {if (!input.signal.aborted) input.onProgress?.({ phase, message });@@ -69,18 +83,21 @@ export async function generateCodexNativeImage(input: {if (event.type === 'turn.started') report('generating_image', '正在通过 ChatGPT 登录态生成图片,请稍候。');if (event.type === 'turn.failed' || event.type === 'error') {const error = isRecord(event.error) ? event.error : event;- if (typeof error.message === 'string') streamError = nativeFailureMessage(error.message);+ if (typeof error.message === 'string') streamError = nativeFailure(error.message);if (event.type === 'turn.failed') turnFailed = true;}const item = isRecord(event.item) ? event.item : undefined;+ if (event.type === 'item.completed' && item?.type === 'agent_message' && typeof item.text === 'string') {+ lastAgentMessage = item.text.slice(0, 4_000);+ }if (item && (item.type === 'image_generation' || item.type === 'imageGeneration')) {report('generating_image', 'Codex 原生生图工具正在处理图片,请稍候。');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 = typeof error.message === 'string' ? nativeFailureMessage(error.message)- : typeof error.type === 'string' ? nativeFailureMessage(error.type) : 'Codex 原生生图工具执行失败';+ failure = nativeFailure(typeof error.message === 'string' ? error.message+ : typeof error.type === 'string' ? error.type : 'Codex 原生生图工具执行失败');} else if (item.status === 'completed') failure = undefined;}}@@ -91,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 Error('Codex 原生生图超时,请稍后重试');+ throw new CodexNativeImageError('Codex 原生生图超时,请稍后重试', 'timeout');}- throw new Error(nativeFailureMessage(error.message));+ throw nativeFailure(error.stderr || error.message);}- throw new Error('无法启动或执行 Codex 原生生图,请检查 Runtime');+ throw new CodexNativeImageError('无法启动或执行 Codex 原生生图,请检查 Runtime', 'unavailable');});input.signal.throwIfAborted();if (result.terminationReason !== 'completed' || result.exitCode !== 0 || turnFailed || failure) {- throw new Error(failure ?? streamError ?? nativeFailureMessage(result.stderr));+ throw failure ?? streamError ?? nativeFailure(result.stderr || lastAgentMessage);}- report('collecting_outputs', '图片已生成,正在检查并保存本地产物。');+ report('collecting_outputs', 'Codex 执行已结束,正在检查是否生成有效图片并保存产物。');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)) {@@ -130,28 +147,59 @@ export async function generateCodexNativeImage(input: {if (!mime) throw new Error('Codex 图片产物不是受支持的 PNG、JPEG 或 WebP 图片');images.push({ content, mime });}- if (images.length !== 1) throw new Error(`Codex 没有返回唯一的新图片产物(${images.length} 张),不能将文字回复视为生图成功`);+ if (images.length !== 1) {+ let diagnostic = nativeFailure(lastAgentMessage || result.stderr);+ 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} 张),不能将文字回复视为生图成功`;+ throw new CodexNativeImageError(message, 'invalid-response',+ `${message}。${lastAgentMessage ? `Codex 最后回复:${lastAgentMessage}` : 'Codex 未返回图片或更具体的失败说明,请重试;持续失败时检查本机 Codex 登录、网络和原生生图能力。'}`,+ 'IMAGE_OUTPUT_MISSING');+ }return images[0]!;+ } catch (error) {+ input.signal.throwIfAborted();+ if (error instanceof CodexNativeImageError) throw error;+ if (error instanceof Error) throw new CodexNativeImageError(+ safePublicErrorMessage(error.message) ?? 'Codex 图片产物检查失败', 'invalid-response'+ );+ throw error;} finally {input.signal.removeEventListener('abort', abort);await rm(workdir, { recursive: true, force: true });}}-function nativeFailureMessage(message: string): string {- if (/unauthorized|401|token.*expired|refresh.*token|not.*logged|authentication|login|sign.?in/i.test(message)) {- return 'ChatGPT 登录已失效或无法验证,请在 Agent 设置中重新登录后重试';+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');}- if (/usage.?limit|rate.?limit|quota|429|limit.?exceeded/i.test(message)) {- return 'ChatGPT 生图额度或请求频率受限,请稍后重试';+ 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);}- if (/unsupported|not.*support|not.*available|403|access.*denied/i.test(message)) {- return '当前 ChatGPT 账号或 Codex Runtime 无法使用原生生图,请检查账号权限或更新 Runtime';+ if (/usage.?limit|rate.?limit|quota|\b429\b|limit.?exceeded/i.test(message)) {+ return new CodexNativeImageError('ChatGPT 生图额度或请求频率受限,请稍后重试', '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);}if (/policy|moderation|safety|content_filter/i.test(message)) {- return '图片请求被安全策略拒绝,请调整描述后重试';+ return new CodexNativeImageError('图片请求被安全策略拒绝,请调整描述后重试', 'http-rejected', message);+ }+ if (/timed?\s*out|timeout/i.test(message)) {+ return new CodexNativeImageError('Codex 原生生图请求超时,请稍后重试', 'timeout', message);+ }+ if (/ENOTFOUND|EAI_AGAIN/i.test(message)) {+ return new CodexNativeImageError('Codex 生图服务域名解析失败,请检查网络后重试', 'dns', message);+ }+ if (/ECONNREFUSED/i.test(message)) {+ return new CodexNativeImageError('Codex 生图服务连接被拒绝,请检查网络或代理', 'connection-refused', message);+ }+ if (/ECONNRESET|connection.*reset/i.test(message)) {+ return new CodexNativeImageError('Codex 生图服务连接中断,请检查网络后重试', 'connection-reset', message);}- return 'Codex 原生生图失败,请检查登录状态、网络或 Runtime 后重试';+ return new CodexNativeImageError('Codex 原生生图失败,请查看服务说明后重试', 'provider-failed', message);}async function imageFiles(root: string, depth = 0): Promise<string[]> {diff --git a/apps/daemon/src/image-generation/codex-runtime.ts b/apps/daemon/src/image-generation/codex-runtime.tsindex 3a887c79..fd4a764d 100644--- a/apps/daemon/src/image-generation/codex-runtime.ts+++ b/apps/daemon/src/image-generation/codex-runtime.ts@@ -11,7 +11,7 @@ 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 生图,请检查 Agent 设置');+ if (!runtime) throw new Error('当前 Runtime 未配置本机 Codex 生图,请检查 Runtime 配置');const configuration = await readCodexImageConfiguration(runtime);authentication = configuration.authentication;if (configuration.authentication === 'api_key') return {diff --git a/apps/daemon/src/image-generation/provider.ts b/apps/daemon/src/image-generation/provider.tsindex efcb710a..84585da6 100644--- a/apps/daemon/src/image-generation/provider.ts+++ b/apps/daemon/src/image-generation/provider.ts@@ -4,6 +4,7 @@ import type {ImageGenerationAsset} from '@opencreator/protocol';import type { PublicErrorFacts } from '@opencreator/protocol';+import { publicErrorKindForCode, sanitizePublicErrorFacts } from '@opencreator/protocol';import {LocalCodexProviderError,type LocalCodexProvider@@ -54,14 +55,19 @@ export function imageGenerationCapabilities(}export class ImageGenerationProviderError extends Error {+ readonly publicFacts: PublicErrorFacts;constructor(readonly code: 'config_missing' | 'upstream_error' | 'unsupported_capability',message: string,- readonly publicFacts?: PublicErrorFacts,+ publicFacts?: PublicErrorFacts,options?: ErrorOptions) {super(message, options);this.name = 'ImageGenerationProviderError';+ this.publicFacts = sanitizePublicErrorFacts({+ ...(publicFacts ?? { kind: publicErrorKindForCode(code) ?? 'unknown' }),+ upstreamMessage: publicFacts?.upstreamMessage ?? message+ });}}@@ -167,10 +173,12 @@ 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') {- throw new ImageGenerationProviderError('upstream_error', '图片生成超时,请稍后重试');+ throw new ImageGenerationProviderError('upstream_error', '图片生成超时,请稍后重试',+ { kind: 'timeout', provider: request.provider, upstreamMessage: '图片生成超过等待时间,请稍后重试。' }, { cause: error });}if (nativeExecution && error instanceof Error) {- throw new ImageGenerationProviderError('upstream_error', error.message);+ throw new ImageGenerationProviderError('upstream_error', error.message,+ publicFactsFromFailure(error, request.provider), { cause: error });}throw new ImageGenerationProviderError('upstream_error',diff --git a/apps/daemon/src/main.ts b/apps/daemon/src/main.tsindex ddd19cfb..82fc37dc 100644--- a/apps/daemon/src/main.ts+++ b/apps/daemon/src/main.ts@@ -18,7 +18,7 @@ import {type RuntimeCapabilityMatrix} from './codex/capabilities.js';import { resolveCodexHome } from './codex/home.js';-import { createCodexIsolatedHome, importLocalCodexConfiguration } from './codex/probe-home.js';+import { importLocalCodexConfiguration } from './codex/probe-home.js';import {CODEX_PROBE_TIMEOUT_MS,probeCodex@@ -82,14 +82,10 @@ async function main(): Promise<void> {} = paths;const codexBin = environment.codexBin ?? 'codex';const codexHome = resolveCodexHome({ isolatedHome: paths.codexHome }).path;- const localCodexHome = environment.codexHome === undefined- ? resolveCodexHome().path- : codexHome;- if (environment.codexHome === undefined) {- createCodexIsolatedHome(localCodexHome, codexHome);- } else if (process.env.OPENCREATOR_LOCAL_CODEX_HOME) {- importLocalCodexConfiguration(process.env.OPENCREATOR_LOCAL_CODEX_HOME, codexHome);- }+ const localCodexHome = environment.localCodexHome === undefined+ ? environment.codexHome === undefined ? resolveCodexHome().path : codexHome+ : resolveCodexHome({ isolatedHome: environment.localCodexHome }).path;+ importLocalCodexConfiguration(localCodexHome, codexHome);readOpenCreatorConfig(configFile);mkdirSync(dataDir, { recursive: true });mkdirSync(codexHome, { recursive: true });diff --git a/apps/daemon/src/startup.ts b/apps/daemon/src/startup.tsindex a6d072eb..1dd086d5 100644--- a/apps/daemon/src/startup.ts+++ b/apps/daemon/src/startup.ts@@ -42,6 +42,7 @@ export function resolveProductionServerEnvironment(| 'creatorDir'| 'codexBin'| 'codexHome'+ | 'localCodexHome'| 'defaultCwd'| 'defaultProjectRoot'| 'creatorYtDlpPath'@@ -58,6 +59,7 @@ export function resolveProductionServerEnvironment('codexHome',env.CODEX_HOME ?? env.OPENCREATOR_CODEX_HOME),+ ...optionalEnvironmentValue('localCodexHome', env.OPENCREATOR_LOCAL_CODEX_HOME),...optionalEnvironmentValue('defaultCwd', env.OPENCREATOR_DEFAULT_CWD),...optionalEnvironmentValue('defaultProjectRoot',diff --git a/apps/daemon/test/fixtures/fake-codex-image.mjs b/apps/daemon/test/fixtures/fake-codex-image.mjsindex 5ac27e08..3b745242 100644--- a/apps/daemon/test/fixtures/fake-codex-image.mjs+++ b/apps/daemon/test/fixtures/fake-codex-image.mjs@@ -39,6 +39,10 @@ if (!args.includes('--ignore-user-config') || !args.includes('image_generation')} else if (mode === 'text-only') {emit({ type: 'item.completed', item: { type: 'agent_message', text: 'An image has been generated' } });emit({ type: 'turn.completed' });+ } else if (mode === 'missing-reference' || mode === 'missing-reference-stderr') {+ if (mode === 'missing-reference') emit({ type: 'item.completed', item: { type: 'agent_message', text: '无法生成:当前会话中没有可用的已上传人物照片。请重新上传照片后再次发送请求。 token=private-oauth-secret' } });+ else process.stderr.write('ERROR codex_core::tools::router: requested the last 1 conversation images, but only 0 were available\n');+ emit({ type: 'turn.completed' });} else if (mode === 'quota') {emit({ type: 'item.completed', item: { type: 'image_generation', status: 'failed', failure: { type: 'usageLimitExceeded', limitId: 'test-limit', resetsAt: null } } });emit({ type: 'turn.completed' });@@ -52,7 +56,8 @@ if (!args.includes('--ignore-user-config') || !args.includes('image_generation')if (mode === 'old') await utimes(path, new Date(0), new Date(0));const outputPath = mode === 'symlink' ? join(process.cwd(), 'output', 'linked.png') : path;if (mode === 'symlink') await symlink(path, outputPath);- emit({ type: 'item.completed', item: { type: 'image_generation', status: 'completed', ...(mode === 'home' || mode === 'other-thread' ? {} : { saved_path: outputPath }) } });+ if (mode !== 'cli-only') emit({ type: 'item.completed', item: { type: 'image_generation', status: 'completed', ...(mode === 'home' || mode === 'other-thread' ? {} : { saved_path: outputPath }) } });+ else emit({ type: 'item.completed', item: { type: 'agent_message', text: 'Saved the generated image.' } });emit({ type: 'turn.completed' });}}diff --git a/apps/daemon/test/integration/creator-image-generation.test.ts b/apps/daemon/test/integration/creator-image-generation.test.tsindex 4a7f54e0..61bccd73 100644--- a/apps/daemon/test/integration/creator-image-generation.test.ts+++ b/apps/daemon/test/integration/creator-image-generation.test.ts@@ -1,6 +1,6 @@import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';import type { FastifyInstance } from 'fastify';-import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';@@ -20,20 +20,52 @@ afterEach(async () => {});describe('creator image generation', () => {+ it('persists an actionable native tool refusal in stage issues without exposing credentials', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-native-image-error-'));+ const home = join(tempDir, 'local-codex-home');+ await mkdir(home);+ await writeFile(join(home, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'private-oauth-secret' } }));+ vi.stubEnv('TEST_CODEX_IMAGE_MODE', 'missing-reference');+ const fetchImpl = vi.fn();+ vi.stubGlobal('fetch', fetchImpl);+ server = await buildServer({ token: 'secret', dataDir: tempDir, codexHome: home, codexBin: await createImageCodexBin(home) });+ const initial = (await request('POST', '/creator/jobs', { projectId: 'project_image', templateId: 'image-generation' })).json().job;+ const updated = (await request('POST', `/creator/jobs/${initial.id}/actions`, {+ action: 'update-settings', expectedRevision: initial.revision,+ input: { patch: { prompt: 'One orange cat', provider: 'codex-native', candidateCount: 1 } }+ })).json().job;+ expect((await request('POST', `/creator/jobs/${initial.id}/actions`, {+ action: 'run-stage', expectedRevision: updated.revision, input: { stageId: 'generate' }+ })).statusCode).toBe(200);+ await vi.waitFor(async () => {+ const job = (await request('GET', `/creator/jobs/${initial.id}`)).json().job;+ expect(job.stages).toContainEqual(expect.objectContaining({ status: 'failed', errorCode: 'image_generation_failed', errorMessage: expect.stringContaining('参考图') }));+ });+ const issues = (await request('GET', `/creator/jobs/${initial.id}/issues`)).json().issues;+ expect(issues).toContainEqual(expect.objectContaining({ code: 'image_generation_failed', publicFacts: {+ kind: 'validation', provider: 'codex-native', upstreamCode: 'IMAGE_REFERENCE_MISSING',+ upstreamMessage: expect.stringContaining('没有可用的已上传人物照片')+ } }));+ expect(JSON.stringify(issues)).not.toContain('private-oauth-secret');+ expect(fetchImpl).not.toHaveBeenCalled();+ });+it('runs native ChatGPT generation with checked capability, visible progress and saved Creator artifacts', async () => {tempDir = await mkdtemp(join(tmpdir(), 'creator-native-image-api-'));- const home = join(tempDir, 'codex-home');+ const home = join(tempDir, 'local-codex-home');+ const agentHome = join(tempDir, 'agent-codex-home');await mkdir(home);+ await mkdir(agentHome);await writeFile(join(home, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'private-oauth-secret' } }));- const fixture = fileURLToPath(new URL('../fixtures/fake-codex-image.mjs', import.meta.url));- const bin = join(tempDir, 'fake-codex-image.mjs');- await writeFile(bin, `#!/usr/bin/env node\nawait import(${JSON.stringify(fixture)});\n`);- await chmod(bin, 0o755);+ const agentAuth = JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: 'agent-api-secret' });+ await writeFile(join(agentHome, 'auth.json'), agentAuth);+ await writeFile(join(agentHome, 'config.toml'), 'model = "agent-model"\nopenai_base_url = "https://agent.example.test/v1"\n');+ const bin = await createImageCodexBin(home);const fetchImpl = vi.fn();vi.stubGlobal('fetch', fetchImpl);vi.stubEnv('TEST_CODEX_IMAGE_DELAY_MS', '250');const config = createDefaultCreatorServicesConfig();- server = await buildServer({ token: 'secret', dataDir: tempDir, codexHome: home, codexBin: bin, creatorServicesConfigStore: {+ server = await buildServer({ token: 'secret', dataDir: tempDir, codexHome: agentHome, localCodexHome: home, codexBin: bin, creatorServicesConfigStore: {async read() { return structuredClone(config); }, async write(next) { return structuredClone(next); }, async reset() { return structuredClone(config); }} });const status = await request('GET', '/creator-services/image/codex/status');@@ -56,6 +88,57 @@ describe('creator image generation', () => {expect(content.rawPayload.subarray(0, 4).toString('hex')).toBe('89504e47');expect(fetchImpl).not.toHaveBeenCalled();expect(status.rawPayload.toString()).not.toContain('private-oauth-secret');+ expect(await readFile(join(agentHome, 'auth.json'), 'utf8')).toBe(agentAuth);+ expect(await readFile(join(agentHome, 'config.toml'), 'utf8')).toContain('agent-model');+ });++ it('uses local API credentials and follows local login changes without falling back to the Agent', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-local-image-auth-'));+ const home = join(tempDir, 'local-codex-home');+ const agentHome = join(tempDir, 'agent-codex-home');+ await mkdir(home);+ await mkdir(agentHome);+ await writeFile(join(home, 'auth.json'), JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: 'local-api-secret' }));+ await writeFile(join(home, 'config.toml'), 'model = "gpt-image-2"\nopenai_base_url = "https://local.example.test/v1"\n');+ const agentAuth = JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'agent-oauth-secret' } });+ await writeFile(join(agentHome, 'auth.json'), agentAuth);+ const bin = await createImageCodexBin(home);+ const image = png('local-api-image');+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ data: [{ b64_json: image.toString('base64') }] }), { status: 200 }));+ vi.stubGlobal('fetch', fetchImpl);+ server = await buildServer({ token: 'secret', dataDir: tempDir, codexHome: agentHome, localCodexHome: home, codexBin: bin });+ const payload = { prompt: 'One orange cat', provider: 'codex-native', size: '1024x1024', quality: 'medium', count: 1 };++ const apiStatus = await request('GET', '/creator-services/image/codex/status');+ expect(apiStatus.json()).toMatchObject({ authentication: 'api_key', ready: true, executionMode: 'api', model: 'gpt-image-2' });+ const apiResult = await request('POST', '/image-generation/results', payload);+ expect(apiResult.statusCode).toBe(201);+ expect(apiResult.json().result.model).toBe('gpt-image-2');+ expect(fetchImpl).toHaveBeenCalledWith(new URL('https://local.example.test/v1/images/generations'), expect.objectContaining({+ headers: expect.objectContaining({ Authorization: 'Bearer local-api-secret' })+ }));++ await writeFile(join(home, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'local-oauth-secret' }, OPENAI_API_KEY: 'old-local-key' }));+ const nativeStatus = await request('GET', '/creator-services/image/codex/status');+ expect(nativeStatus.json()).toMatchObject({ authentication: 'chatgpt', ready: true, executionMode: 'native' });+ const nativeResult = await request('POST', '/image-generation/results', payload);+ expect(nativeResult.statusCode).toBe(201);+ expect(nativeResult.json().result.model).toBe('codex-native');+ expect(fetchImpl).toHaveBeenCalledOnce();++ await writeFile(join(home, 'auth.json'), JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: 'replacement-local-key', tokens: { access_token: 'old-local-oauth' } }));+ expect((await request('GET', '/creator-services/image/codex/status')).json()).toMatchObject({ authentication: 'api_key', ready: true, executionMode: 'api' });+ expect((await request('POST', '/image-generation/results', payload)).statusCode).toBe(201);+ expect(fetchImpl).toHaveBeenLastCalledWith(new URL('https://local.example.test/v1/images/generations'), expect.objectContaining({+ headers: expect.objectContaining({ Authorization: 'Bearer replacement-local-key' })+ }));++ await rm(join(home, 'auth.json'));+ expect((await request('GET', '/creator-services/image/codex/status')).json()).toMatchObject({ ready: false, executionMode: null });+ expect((await request('POST', '/image-generation/results', payload)).statusCode).toBe(409);+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ expect(await readFile(join(agentHome, 'auth.json'), 'utf8')).toBe(agentAuth);+ expect(JSON.stringify([apiStatus.json(), nativeStatus.json(), apiResult.json(), nativeResult.json()])).not.toContain('secret');});it('runs image generation through Creator Job, Stage, Artifact and ResultSnapshot', async () => {@@ -103,7 +186,7 @@ describe('creator image generation', () => {expectedRevision: initial.revision,input: {patch: {- prompt: 'A bright creative studio',+ prompt: '参考上传图片的主体和构图生成创意工作室画面',provider: 'openai',size: '1536x1024',quality: 'high',@@ -111,6 +194,14 @@ describe('creator image generation', () => {}}});+ const blocked = await request('POST', `/creator/jobs/${initial.id}/actions`, {+ action: 'run-stage', expectedRevision: updated.json().job.revision, input: { stageId: 'generate' }+ });+ expect(blocked.statusCode).toBeGreaterThanOrEqual(400);+ expect(blocked.json()).toMatchObject({ error: { code: 'creator_stage_input_missing', issue: { publicFacts: { kind: 'validation', upstreamCode: 'IMAGE_REFERENCE_MISSING' } } } });+ expect(fetchImpl).not.toHaveBeenCalled();+ expect((await request('GET', `/creator/jobs/${initial.id}`)).json().job.stages).toHaveLength(0);+const reference = png('image-reference');const uploaded = await server.inject({method: 'POST',@@ -187,6 +278,14 @@ describe('creator image generation', () => {});});+async function createImageCodexBin(expectedHome: string): Promise<string> {+ const fixture = fileURLToPath(new URL('../fixtures/fake-codex-image.mjs', import.meta.url));+ const bin = join(tempDir, 'fake-codex-image.mjs');+ await writeFile(bin, `#!/usr/bin/env node\nif (process.argv[2] === 'exec' && process.env.CODEX_HOME !== ${JSON.stringify(expectedHome)}) throw new Error('Image generation used the wrong Codex home');\nawait import(${JSON.stringify(fixture)});\n`);+ await chmod(bin, 0o755);+ return bin;+}+async function waitForCompletedJob(jobId: string) {const deadline = Date.now() + 10_000;let lastJob: unknown;diff --git a/apps/daemon/test/integration/creator-local-codex-defaults.test.ts b/apps/daemon/test/integration/creator-local-codex-defaults.test.tsnew file mode 100644index 00000000..13aee670--- /dev/null+++ b/apps/daemon/test/integration/creator-local-codex-defaults.test.ts@@ -0,0 +1,85 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import Fastify from 'fastify';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';+import { createFileCreatorServicesConfigStore, createCreatorServicesConfigStoreWithTextModelFallback } from '../../src/creator-services/config-store.js';+import { createLocalCodexTextModelDefaults } from '../../src/creator-services/local-codex-defaults.js';+import { createKrillinCodexLlmGateway } from '../../src/creator/krillin/codex-llm-gateway.js';+import { registerCreatorServicesRoutes } from '../../src/api/routes.creator-services.js';+import { createWechatArticleModel } from '../../src/creator/article/model.js';++let root = '';+afterEach(async () => { if (root) await rm(root, { recursive: true, force: true }); root = ''; });++describe('local Codex defaults', () => {+ it.each(['chatgpt', 'api_key'] as const)('enables detected %s services without a settings write and preserves saved overrides after reopening', async authentication => {+ root = await mkdtemp(join(tmpdir(), 'creator-local-defaults-'));+ await writeFile(join(root, 'config.toml'), 'model = "local-model"\nopenai_base_url = "https://local.example/v1"\n');+ await writeFile(join(root, 'auth.json'), JSON.stringify(authentication === 'chatgpt'+ ? { auth_mode: 'chatgpt', tokens: { access_token: 'oauth-secret' } }+ : { auth_mode: 'apikey', OPENAI_API_KEY: 'local-key' }));+ const raw = createFileCreatorServicesConfigStore(join(root, 'creator-services.json'));+ const write = vi.spyOn(raw, 'write');+ const defaults = createLocalCodexTextModelDefaults({ codexHome: root,+ readGatewayConfig: () => ({ baseUrl: 'http://127.0.0.1:1234/internal/krillin-llm/v1', apiKey: 'bridge-key', model: 'codex' }) });+ let store = createCreatorServicesConfigStoreWithTextModelFallback(raw, defaults);+ let server = Fastify();+ await registerCreatorServicesRoutes(server, store, undefined, undefined, undefined, undefined, defaults.readStatus);+ try {+ expect((await server.inject('/creator-services/model/codex/status')).json()).toMatchObject({ authentication, model: 'local-model' });+ const response = await server.inject('/creator-services/config');+ expect(response.statusCode).toBe(200);+ expect(response.json()).toMatchObject({ config: { llm: { source: 'codex', model: 'local-model' }, image: { provider: 'codex-native' } } });+ expect(response.body).not.toMatch(/oauth-secret|local-key|bridge-key/);+ expect(write).not.toHaveBeenCalled();+ expect((await store.read()).llm).toMatchObject({ apiKey: 'bridge-key' });++ const custom = createDefaultCreatorServicesConfig();+ custom.llm = { source: 'custom', baseUrl: 'https://manual.example/v1', apiKey: 'manual-key', model: 'manual-model', jsonMode: true };+ custom.image.provider = 'gemini';+ custom.image.gemini.apiKey = 'manual-image-key';+ expect((await server.inject({ method: 'PATCH', url: '/creator-services/config', payload: custom })).statusCode).toBe(200);+ await server.close();+ await writeFile(join(root, 'config.toml'), 'model = "changed-local-model"\n');+ store = createCreatorServicesConfigStoreWithTextModelFallback(createFileCreatorServicesConfigStore(join(root, 'creator-services.json')), defaults);+ server = Fastify();+ await registerCreatorServicesRoutes(server, store);+ expect(await store.read()).toMatchObject({ llm: custom.llm, image: { provider: 'gemini', gemini: { apiKey: 'manual-image-key' } } });+ expect((await server.inject('/creator-services/config')).json().config.image.provider).toBe('gemini');+ expect((await server.inject({ method: 'DELETE', url: '/creator-services/config' })).json().config.image.provider).toBe('codex-native');+ expect((await store.read()).llm.source).toBe('codex');+ } finally { await server.close(); }+ });++ it.each(['chatgpt', 'api_key'] as const)('runs a regular text task through %s before any save, and never persists temporary bridge credentials', async authentication => {+ root = await mkdtemp(join(tmpdir(), 'creator-local-chatgpt-'));+ await writeFile(join(root, 'auth.json'), JSON.stringify(authentication === 'chatgpt'+ ? { auth_mode: 'chatgpt', tokens: { access_token: 'oauth-secret' } }+ : { auth_mode: 'apikey', OPENAI_API_KEY: 'local-api-secret' }));+ const run = vi.fn((request: { onNotification?(value: Record<string, unknown>): void }) => {+ request.onNotification?.({ method: 'item/completed', params: { item: { id: 'answer', type: 'agentMessage', text: '# Outline' } } });+ return { cancel() {}, result: Promise.resolve({ threadId: 'thread', turnId: 'turn', turnStatus: 'completed' as const,+ stderr: '', terminationReason: 'completed' as const, outputTruncation: { stderr: { truncated: false, droppedBytes: 0, droppedItems: 0 }, frames: { truncated: false, droppedBytes: 0, droppedItems: 0 } } }) };+ });+ const createHost = vi.fn(() => ({ pid: 1, started: Promise.resolve(1), run, isReusable: () => true, close: vi.fn(async () => undefined) }));+ const gateway = createKrillinCodexLlmGateway({ codexBin: '/fake/codex', codexHome: root, cwd: root, createHost });+ const server = Fastify();+ await gateway.register(server);+ const origin = await server.listen({ port: 0, host: '127.0.0.1' });+ const raw = createFileCreatorServicesConfigStore(join(root, 'creator-services.json'));+ const store = createCreatorServicesConfigStoreWithTextModelFallback(raw, createLocalCodexTextModelDefaults({ codexHome: root, readGatewayConfig: () => gateway.config(origin) }));+ try {+ const model = createWechatArticleModel({ configStore: store });+ await expect(model.generateOutline({ sources: [], topic: { id: 'topic', title: 'Title', angle: '', summary: '' }, writingPrompt: '', templatePrompt: '', signal: new AbortController().signal })).resolves.toBe('# Outline');+ expect(run).toHaveBeenCalledOnce();+ await store.write(await store.read());+ const persisted = await readFile(join(root, 'creator-services.json'), 'utf8');+ expect(persisted).not.toContain('ocllm_');+ expect(persisted).not.toContain(origin);+ expect(persisted).not.toContain('oauth-secret');+ expect(persisted).not.toContain('local-api-secret');+ } finally { await gateway.close(); await server.close(); }+ });+});diff --git a/apps/daemon/test/unit/codex-local-provider.test.ts b/apps/daemon/test/unit/codex-local-provider.test.tsindex 13182968..e1559b61 100644--- a/apps/daemon/test/unit/codex-local-provider.test.ts+++ b/apps/daemon/test/unit/codex-local-provider.test.ts@@ -5,12 +5,21 @@ import { afterEach, describe, expect, it } from 'vitest';import {LocalCodexProviderError,readLocalCodexProvider,- readLocalCodexImageConfiguration+ readLocalCodexImageConfiguration,+ readLocalCodexModelConfiguration} from '../../src/codex/local-provider.js';describe('local Codex provider', () => {let root = '';+ it('uses the standard API endpoint with a local key and preserves the text model', async () => {+ root = await codexHome(['model = "local-text-model"']);+ await writeFile(join(root, 'auth.json'), JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: 'local-key' }));+ await expect(readLocalCodexModelConfiguration({ codexHome: root, env: {} })).resolves.toEqual({+ authentication: 'api_key', provider: { baseUrl: 'https://api.openai.com/v1', apiKey: 'local-key', model: 'local-text-model' }+ });+ });+afterEach(async () => {if (root) await rm(root, { recursive: true, force: true });root = '';diff --git a/apps/daemon/test/unit/codex-native-image.test.ts b/apps/daemon/test/unit/codex-native-image.test.tsindex 91562a63..16fca0cf 100644--- a/apps/daemon/test/unit/codex-native-image.test.ts+++ b/apps/daemon/test/unit/codex-native-image.test.ts@@ -46,6 +46,19 @@ describe('ChatGPT native image execution', () => {await expect(generateCodexNativeImage({ runtime: runtime('recovered'), request, referenceImages: [], signal: new AbortController().signal })).resolves.toMatchObject({ mime: 'image/png' });});+ it('discovers output when the CLI omits image tool events', async () => {+ await expect(generateCodexNativeImage({ runtime: runtime('cli-only'), request, referenceImages: [], signal: new AbortController().signal })).resolves.toMatchObject({ mime: 'image/png' });+ });++ it.each(['missing-reference', 'missing-reference-stderr'])('keeps tool refusal details despite successful process exit (%s)', async mode => {+ 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('参考图')+ } });+ expect(JSON.stringify(error.publicFacts)).not.toContain('private-oauth-secret');+ });+it('keeps reference images attached and does not mistake them for generated images', async () => {const base = runtime('text-only');const reference = Buffer.from('reference-image');diff --git a/apps/daemon/test/unit/codex-probe-home.test.ts b/apps/daemon/test/unit/codex-probe-home.test.tsindex ecac39cc..57018e7d 100644--- a/apps/daemon/test/unit/codex-probe-home.test.ts+++ b/apps/daemon/test/unit/codex-probe-home.test.ts@@ -13,7 +13,8 @@ import { afterEach, describe, expect, it } from 'vitest';import {createCodexIsolatedHome,createCodexProbeHome,- importLocalCodexConfiguration+ importLocalCodexConfiguration,+ createFollowingLocalCodexHome} from '../../src/codex/probe-home.js';let tempDir = '';@@ -24,6 +25,26 @@ afterEach(() => {});describe('Codex Probe 临时 Home', () => {+ it('refreshes automatic model credentials only when local configuration changes', () => {+ tempDir = mkdtempSync(join(tmpdir(), 'opencreator-follow-local-'));+ const source = join(tempDir, 'source');+ const isolated = join(tempDir, 'isolated');+ mkdirSync(source);+ writeFileSync(join(source, 'auth.json'), '{"OPENAI_API_KEY":"local-secret"}');+ writeFileSync(join(source, 'config.toml'), 'model = "first-model"\n');+ const read = createFollowingLocalCodexHome(source, isolated);+ const initial = read();+ writeFileSync(join(isolated, 'auth.json'), '{"OPENAI_API_KEY":"refreshed-secret"}');+ expect(read()).toEqual(initial);+ expect(readFileSync(join(isolated, 'auth.json'), 'utf8')).toContain('refreshed-secret');+ writeFileSync(join(source, 'config.toml'), 'model = "second-model"\n');+ expect(read().version).not.toBe(initial.version);+ expect(readFileSync(join(isolated, 'config.toml'), 'utf8')).toContain('second-model');+ expect(readFileSync(join(source, 'auth.json'), 'utf8')).toContain('local-secret');+ rmSync(join(source, 'auth.json'));+ read();+ expect(existsSync(join(isolated, 'auth.json'))).toBe(false);+ });it('imports a local login once and does not overwrite an existing OpenCreator selection', () => {tempDir = mkdtempSync(join(tmpdir(), 'opencreator-codex-import-test-'));const sourceHome = join(tempDir, 'source');diff --git a/apps/daemon/test/unit/creator-file-hash.test.ts b/apps/daemon/test/unit/creator-file-hash.test.tsnew file mode 100644index 00000000..4f29b192--- /dev/null+++ b/apps/daemon/test/unit/creator-file-hash.test.ts@@ -0,0 +1,25 @@+import { createHash } from 'node:crypto';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { sha256CreatorFile } from '../../src/creator/file-hash.js';++let root = '';+afterEach(async () => { if (root) await rm(root, { recursive: true, force: true }); });++describe('streamed Creator file hashing', () => {+ it('hashes multi-chunk output without loading the complete file into a buffer', async () => {+ root = await mkdtemp(join(tmpdir(), 'creator-file-hash-'));+ const path = join(root, 'output.mp4');+ const content = Buffer.alloc(2 * 1024 * 1024 + 7, 0x42);+ await writeFile(path, content);+ expect(await sha256CreatorFile(path)).toBe(createHash('sha256').update(content).digest('hex'));+ const signal = AbortSignal.abort();+ await expect(sha256CreatorFile(path, signal)).rejects.toMatchObject({ name: 'AbortError' });+ });+ it('keeps the filesystem code when an output cannot be opened', async () => {+ root = await mkdtemp(join(tmpdir(), 'creator-file-hash-'));+ await expect(sha256CreatorFile(join(root, 'missing.mp4'))).rejects.toMatchObject({ code: 'ENOENT' });+ });+});diff --git a/apps/daemon/test/unit/creator-image-executor.test.ts b/apps/daemon/test/unit/creator-image-executor.test.tsindex a8f8f207..858dba1b 100644--- a/apps/daemon/test/unit/creator-image-executor.test.ts+++ b/apps/daemon/test/unit/creator-image-executor.test.ts@@ -20,6 +20,14 @@ afterEach(async () => {});describe('creator image executor', () => {+ it.each(['openai', 'codex-native'] as const)('rejects a missing required image before invoking %s', async provider => {+ const generate = vi.fn();+ const executor = createImageExecutor({ configStore: { read: async () => createDefaultCreatorServicesConfig() }, generate });+ await expect(executor.run(stageInput({ provider, prompt: '以上传的人物照片为唯一主体,生成复古海报。' }))).rejects.toMatchObject({+ code: 'creator_stage_input_missing', publicFacts: { kind: 'validation', upstreamCode: 'IMAGE_REFERENCE_MISSING' }+ });+ expect(generate).not.toHaveBeenCalled();+ });it('preserves provider diagnostics when all image candidates fail', async () => {const publicFacts = { kind: 'http-rejected' as const, provider: 'openai', httpStatus: 400,upstreamCode: 'invalid_image', upstreamMessage: 'Reference image is invalid', requestId: 'request-123' };diff --git a/apps/daemon/test/unit/creator-preflight.test.ts b/apps/daemon/test/unit/creator-preflight.test.tsindex fca24527..c3e6de70 100644--- a/apps/daemon/test/unit/creator-preflight.test.ts+++ b/apps/daemon/test/unit/creator-preflight.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import { createDefaultCreatorServicesConfig, type CreatorJob, type CreatorJson } from '@opencreator/protocol';-import { createCreatorPreflight } from '../../src/creator/preflight.js';+import { createCreatorPreflight, CreatorPreflightError } from '../../src/creator/preflight.js';import { createImageGenerationTemplate } from '../../src/creator/templates/image-generation.js';import { createVideoDownloadTemplate } from '../../src/creator/templates/video-download.js';import { createStickmanVideoTemplate } from '../../src/creator/templates/stickman-video.js';@@ -20,6 +20,19 @@ afterEach(async () => {});describe('creator preflight', () => {+ it.each(['openai', 'codex-native'])('blocks missing reference input for %s before starting a task', async provider => {+ root = await mkdtemp(join(tmpdir(), 'creator-preflight-reference-'));+ const check = createCreatorPreflight({+ configStore: { read: async () => createDefaultCreatorServicesConfig() },+ readCapabilities: () => createKrillinCreatorServicesCapabilities('darwin', 'arm64'),+ resourceRoot: root, jobsRoot: join(root, 'jobs'), executorIds: ['image'], validateRuntimeAssets: false+ });+ 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(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 () => {root = await mkdtemp(join(tmpdir(), 'creator-preflight-remotion-'));const status = vi.fn(async () => ({ id: 'remotion' as const, name: 'Remotion', available: true, version: null, supportedVersion: '4.0.473', installedAt: null, path: root, source: 'release', models: [], model: null, state: 'not_installed' as const, item: null, downloadedBytes: 0, totalBytes: null, percent: null, bytesPerSecond: null, remainingSeconds: null, error: null }));@@ -313,11 +326,11 @@ describe('creator preflight', () => {expect(result.blocked.map(item => item.id)).toContain('transcription-config');});- it('accepts the Codex runtime for Krillin subtitle translation without a creator API key', async () => {+ it('accepts automatically resolved Codex credentials for subtitle translation', async () => {root = await mkdtemp(join(tmpdir(), 'creator-preflight-'));const config = createDefaultCreatorServicesConfig();config.llm.source = 'codex';- config.llm.apiKey = '';+ config.llm.apiKey = 'internal-bridge-key';config.llm.model = 'gpt-5.6-sol';const stage = createVideoTranslationTemplate().stages.find(candidate => candidate.id === 'subtitle')!;const result = await createCreatorPreflight({diff --git a/apps/daemon/test/unit/creator-public-error-facts.test.ts b/apps/daemon/test/unit/creator-public-error-facts.test.tsindex 27094b37..3f7b8317 100644--- a/apps/daemon/test/unit/creator-public-error-facts.test.ts+++ b/apps/daemon/test/unit/creator-public-error-facts.test.ts@@ -4,6 +4,12 @@ import { creatorServiceErrorInfo, creatorServiceFailureFacts } from '../../src/cimport { CreatorExecutorError } from '../../src/creator/executor.js';describe('public error facts', () => {+ it('keeps the filesystem code through wrapped artifact collection failures', () => {+ const bottom = Object.assign(new Error('File size (4014655674) is greater than 2 GiB'), { code: 'ERR_FS_FILE_TOO_LARGE' });+ expect(publicFactsFromFailure(new Error('Output collection failed', { cause: bottom }))).toEqual({+ kind: 'storage', upstreamCode: 'ERR_FS_FILE_TOO_LARGE'+ });+ });it('classifies only known network codes through nested causes', () => {const error = new Error('Authorization: Bearer secret', {cause: Object.assign(new Error('private endpoint'), { code: 'ENOTFOUND' })diff --git a/apps/daemon/test/unit/creator-runtime-advanced.test.ts b/apps/daemon/test/unit/creator-runtime-advanced.test.tsindex 367bc607..61e9a46a 100644--- a/apps/daemon/test/unit/creator-runtime-advanced.test.ts+++ b/apps/daemon/test/unit/creator-runtime-advanced.test.ts@@ -12,6 +12,7 @@ import { parseClipCandidates } from '../../src/creator/clip/analyzer.js';import { createCreatorCommandDispatcher } from '../../src/creator/command-dispatcher.js';import { parseDownloadProbe } from '../../src/creator/download/probe-parser.js';import { CreatorExecutorError, type CreatorExecutor } from '../../src/creator/executor.js';+import { createCreatorIssueService } from '../../src/creator/issues.js';import { createCreatorRepository } from '../../src/creator/repository.js';import { createCreatorService } from '../../src/creator/service.js';import { createCreatorStageRunner } from '../../src/creator/stage-runner.js';@@ -41,6 +42,23 @@ function setup() {}describe('creator runtime advanced contracts', () => {+ it.each(['direct', 'wrapped'])('preserves a bottom-level error code and reason in stage and issue records (%s)', async mode => {+ const { db, repository, service, templates } = setup();+ const issueService = createCreatorIssueService(repository);+ const bottom = Object.assign(new Error('File size (4014655674) is greater than 2 GiB token=private'), { code: 'ERR_FS_FILE_TOO_LARGE' });+ const runner = createCreatorStageRunner({ repository, templates, issueService,+ executors: [{ id: 'krillinai', async run() { throw mode === 'direct' ? bottom : new Error('Output collection failed', { cause: bottom }); } }],+ workRoot: join(tempDir, 'work') });+ const job = service.createJob({ projectId: 'p1', templateId: 'video-translation',+ state: { sourceType: 'url', sourceUrl: 'https://youtube.com/watch?v=test', sourceLanguage: 'en', targetLanguage: 'zh_cn' } });+ const stage = await runner.run(job.id, 'subtitle');+ expect(stage).toMatchObject({ status: 'failed', errorCode: 'ERR_FS_FILE_TOO_LARGE' });+ const issue = issueService.list(job.id)[0]!;+ expect(issue).toMatchObject({ code: 'ERR_FS_FILE_TOO_LARGE', publicFacts: { kind: 'storage', upstreamCode: 'ERR_FS_FILE_TOO_LARGE', upstreamMessage: expect.stringContaining('File size (4014655674)') } });+ expect(JSON.stringify(issue.publicFacts)).not.toContain('private');+ await runner.close();+ db.close();+ });it('does not treat generated subtitles from an older result snapshot as imported subtitles', async () => {const { db, repository, service, templates, dispatcher } = setup();const runner = createCreatorStageRunner({ repository, templates, workRoot: join(tempDir, 'work'), executors: [{diff --git a/apps/daemon/test/unit/krillin-codex-llm-gateway.test.ts b/apps/daemon/test/unit/krillin-codex-llm-gateway.test.tsindex 20908854..80418d6b 100644--- a/apps/daemon/test/unit/krillin-codex-llm-gateway.test.ts+++ b/apps/daemon/test/unit/krillin-codex-llm-gateway.test.ts@@ -31,11 +31,13 @@ describe('Krillin Codex LLM gateway', () => {isReusable: () => true,close: vi.fn(async () => undefined)}));+ let configurationVersion = 'first';const gateway = createKrillinCodexLlmGateway({codexBin: '/bundled/codex',codexHome: '/isolated/codex-home',cwd: '/workspace',- createHost+ createHost,+ readConfiguration: () => ({ codexHome: '/following/local-home', version: configurationVersion })});const server = Fastify();await gateway.register(server);@@ -92,6 +94,14 @@ describe('Krillin Codex LLM gateway', () => {expect(streamBody).toContain('data: [DONE]');expect(createHost).toHaveBeenCalledTimes(1);expect(run).toHaveBeenCalledTimes(2);+ expect(createHost).toHaveBeenCalledWith(expect.objectContaining({ codexHome: '/following/local-home' }));+ configurationVersion = 'changed';+ expect((await server.inject({ method: 'POST', url: '/internal/krillin-llm/v1/chat/completions',+ headers: { authorization: `Bearer ${config.apiKey}` },+ payload: { messages: [{ role: 'user', content: 'New configuration' }] }+ })).statusCode).toBe(200);+ expect(createHost).toHaveBeenCalledTimes(2);+ expect(createHost.mock.results[0]!.value.close).toHaveBeenCalledOnce();await gateway.close();await server.close();});diff --git a/apps/daemon/test/unit/startup.test.ts b/apps/daemon/test/unit/startup.test.tsindex b250a2a4..15ebf332 100644--- a/apps/daemon/test/unit/startup.test.ts+++ b/apps/daemon/test/unit/startup.test.ts@@ -45,6 +45,7 @@ describe('daemon production startup', () => {OPENCREATOR_DATA_DIR: ' /tmp/opencreator-data ',OPENCREATOR_CODEX_BIN: ' /tmp/fake-codex ',CODEX_HOME: ' /tmp/opencreator-codex-home ',+ OPENCREATOR_LOCAL_CODEX_HOME: ' /tmp/local-codex-home ',OPENCREATOR_DEFAULT_CWD: ' /tmp/default-workspace ',OPENCREATOR_DEFAULT_PROJECT_ROOT: ' /tmp/Documents ',OPENCREATOR_YT_DLP_PATH: ' /tmp/yt-dlp '@@ -52,6 +53,7 @@ describe('daemon production startup', () => {dataDir: '/tmp/opencreator-data',codexBin: '/tmp/fake-codex',codexHome: '/tmp/opencreator-codex-home',+ localCodexHome: '/tmp/local-codex-home',defaultCwd: '/tmp/default-workspace',defaultProjectRoot: '/tmp/Documents',creatorYtDlpPath: '/tmp/yt-dlp'@@ -61,6 +63,7 @@ describe('daemon production startup', () => {OPENCREATOR_DATA_DIR: ' ',OPENCREATOR_CODEX_BIN: '',CODEX_HOME: '\t',+ OPENCREATOR_LOCAL_CODEX_HOME: ' ',OPENCREATOR_DEFAULT_CWD: '\n',OPENCREATOR_DEFAULT_PROJECT_ROOT: ' ',OPENCREATOR_YT_DLP_PATH: ''diff --git a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.test.tsx b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.test.tsxindex 63ac89a3..b172b0f4 100644--- a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import type {CreatorActionRequest,CreatorArtifact,@@ -8,7 +8,7 @@ import type {import { beforeEach, describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';import CoverGeneratorWorkspace from './CoverGeneratorWorkspace.js';-import { CreatorSessionProvider } from './creator-session-store.js';+import { CreatorSessionProvider, useOptionalCreatorSession, type CreatorSessionContextValue } from './creator-session-store.js';describe('CoverGeneratorWorkspace', () => {beforeEach(() => {@@ -35,6 +35,75 @@ describe('CoverGeneratorWorkspace', () => {.not.toBe(0);});+ it.each(['none', 'reference_image', 'source_keyframe'] as const)(+ 'keeps the same cover preview across repeated snapshots (%s)',+ async referenceKind => {+ const fixture = createFixture();+ const base = fixture.currentJob();+ const cover = coverArtifact(base.id, 1, 1, base.createdAt);+ const reference = referenceKind === 'none' ? undefined : {+ ...sourceKeyframeArtifact(base.id, base.createdAt),+ id: 'preview_reference', kind: referenceKind+ };+ const snapshot = coverResultSnapshot(1, cover, base.createdAt) as Record<string, CreatorJson>;+ snapshot.artifactRefs = {+ cover_image: [cover.id],+ ...(reference === undefined ? {} : { [referenceKind]: [reference.id] })+ };+ const job: CreatorJob = {+ ...base, status: 'completed', artifacts: [cover, ...(reference === undefined ? [] : [reference])],+ state: { ...base.state, currentStep: 2, furthestStep: 2, resultVersion: 1,+ latestResultVersion: 1, resultSnapshots: [snapshot],+ referenceImageArtifactId: referenceKind === 'reference_image' ? reference!.id : null }+ };+ const view = renderWorkspace(fixture, job);+ const image = await screen.findByAltText('封面方案 1');+ const url = image.getAttribute('src');+ const requests = fixture.openArtifact.mock.calls.length;+ expect(requests).toBe(referenceKind === 'none' ? 1 : referenceKind === 'source_keyframe' ? 2 : 3);+ for (let revision = 1; revision <= 3; revision += 1) {+ await view.pushSnapshot({ ...structuredClone(job), revision });+ expect(screen.getByAltText('封面方案 1')).toBe(image);+ expect(image).toHaveAttribute('src', url);+ }+ expect(fixture.openArtifact).toHaveBeenCalledTimes(requests);+ expect(URL.revokeObjectURL).not.toHaveBeenCalled();+ view.unmount();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(url);+ }+ );++ it('loads a different preview when the selected result version changes', async () => {+ const fixture = createFixture();+ const base = fixture.currentJob();+ const first = { ...coverArtifact(base.id, 1, 1, base.createdAt), id: 'cover_v1' };+ const second = { ...coverArtifact(base.id, 1, 2, base.createdAt), id: 'cover_v2' };+ const job: CreatorJob = { ...base, status: 'completed', artifacts: [first, second],+ state: { ...base.state, currentStep: 2, resultVersion: 1, latestResultVersion: 2,+ resultSnapshots: [coverResultSnapshot(1, first, base.createdAt), coverResultSnapshot(2, second, base.createdAt)] }+ };+ const view = renderWorkspace(fixture, job);+ const firstUrl = (await screen.findByAltText('封面方案 1')).getAttribute('src');+ await view.pushSnapshot({ ...job, revision: 1, state: { ...job.state, resultVersion: 2 } });+ const image = await screen.findByAltText('封面方案 1');+ expect(image.getAttribute('src')).not.toBe(firstUrl);+ expect(fixture.openArtifact).toHaveBeenCalledTimes(2);+ expect(fixture.openArtifact).toHaveBeenLastCalledWith(job.id, second.id);+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(firstUrl);+ });++ it('releases a preview whose fetch completes after unmount', async () => {+ const fixture = createFixture();+ const base = fixture.currentJob();+ let finish!: (response: Response) => void;+ fixture.openArtifact.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const view = renderWorkspace(fixture, { ...base, artifacts: [coverArtifact(base.id, 1, 1, base.createdAt)] });+ await waitFor(() => expect(fixture.openArtifact).toHaveBeenCalledOnce());+ view.unmount();+ await act(async () => { finish(new Response(new Blob([png('cover')], { type: 'image/png' }))); });+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(vi.mocked(URL.createObjectURL).mock.results[0]!.value);+ });+it('renders real result artifacts and downloads them without a selection state', async () => {const fixture = createFixture();const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click')@@ -496,7 +565,8 @@ function renderWorkspace(initialJob = fixture.currentJob(),language: 'zh-CN' | 'en-US' = 'zh-CN') {- return render(+ let currentSession: CreatorSessionContextValue | null = null;+ const view = render(<LanguageProvider initialPreference={language}><CreatorSessionProviderinitialJob={initialJob}@@ -507,10 +577,19 @@ function renderWorkspace(runAgentTurn: vi.fn()} as never}>+ <SessionObserver onSession={session => { currentSession = session; }} /><CoverGeneratorWorkspace onBack={vi.fn()} /></CreatorSessionProvider></LanguageProvider>);+ return { ...view, async pushSnapshot(job: CreatorJob) {+ await act(async () => { currentSession!.applyRemoteSnapshot(job); });+ } };+}++function SessionObserver(props: { onSession(session: CreatorSessionContextValue | null): void }) {+ props.onSession(useOptionalCreatorSession());+ return null;}function createFixture() {diff --git a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsxindex ea986345..a5123165 100644--- a/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx+++ b/apps/web/src/features/dashboard/CoverGeneratorWorkspace.tsx@@ -177,6 +177,19 @@ export default function CoverGeneratorWorkspace(props: {const currentReferenceName = referenceFile?.name?? readArtifactString(activeReferenceArtifact, 'fileName');const resolvedCoverTextLanguage = coverTextLanguage;+ const previewContext = useRef({ session, l });+ previewContext.current = { session, l };+ // Job snapshots replace arrays even when the preview files are unchanged.+ const resultPreviewKey = JSON.stringify({+ jobId: session?.job.id,+ artifacts: uniqueArtifacts([+ ...(selectedResult?.artifacts ?? []),+ ...(selectedReferenceArtifact === undefined ? [] : [selectedReferenceArtifact]),+ ...(selectedKeyframeArtifact === undefined ? [] : [selectedKeyframeArtifact])+ ]).map(artifact => [artifact.id, artifact.version, artifact.sha256, artifact.path])+ });+ const referencePreviewKey = JSON.stringify([session?.job.id, activeReferenceArtifact?.id,+ activeReferenceArtifact?.version, activeReferenceArtifact?.sha256, activeReferenceArtifact?.path]);useEffect(() => {if (latestResult !== undefined) {@@ -187,8 +200,10 @@ export default function CoverGeneratorWorkspace(props: {}, [latestResult?.value]);useEffect(() => {+ const { session, l } = previewContext.current;+ const [, artifactId] = JSON.parse(referencePreviewKey) as Array<string | number | null>;if (referenceFile === null) {- if (activeReferenceArtifact === undefined || session === null) {+ if (typeof artifactId !== 'string' || session === null) {setReferencePreview('');return undefined;}@@ -196,13 +211,14 @@ export default function CoverGeneratorWorkspace(props: {let objectUrl = '';void createCreatorArtifactObjectUrl(session,- activeReferenceArtifact.id,+ artifactId,'cover.load-reference-preview',l('参考图预览加载失败,请稍后重试。', 'The reference preview failed to load. Try again later.')).then(url => {objectUrl = url;if (active) setReferencePreview(objectUrl);+ else URL.revokeObjectURL(url);}).catch(() => {if (active) setReferencePreview('');@@ -212,6 +228,7 @@ export default function CoverGeneratorWorkspace(props: {if (objectUrl) URL.revokeObjectURL(objectUrl);};}+ let active = true;let objectUrl = '';void captureCreatorClientFailure(session,@@ -220,17 +237,15 @@ export default function CoverGeneratorWorkspace(props: {() => URL.createObjectURL(referenceFile)).then(url => {objectUrl = url;- setReferencePreview(url);- }).catch(() => setReferencePreview(''));- return () => { if (objectUrl) URL.revokeObjectURL(objectUrl); };- }, [activeReferenceArtifact?.id, l, referenceFile, session?.captureCreatorFailure, session?.openArtifact]);+ if (active) setReferencePreview(url);+ else URL.revokeObjectURL(url);+ }).catch(() => { if (active) setReferencePreview(''); });+ return () => { active = false; if (objectUrl) URL.revokeObjectURL(objectUrl); };+ }, [referencePreviewKey, referenceFile]);useEffect(() => {- const artifacts = uniqueArtifacts([- ...(selectedResult?.artifacts ?? []),- ...(selectedReferenceArtifact === undefined ? [] : [selectedReferenceArtifact]),- ...(selectedKeyframeArtifact === undefined ? [] : [selectedKeyframeArtifact])- ]);+ const { session, l } = previewContext.current;+ const { artifacts } = JSON.parse(resultPreviewKey) as { artifacts: Array<[string, number, string | null, string | null]> };if (session === null || artifacts.length === 0) {setArtifactUrls({});return undefined;@@ -238,15 +253,16 @@ export default function CoverGeneratorWorkspace(props: {let active = true;const objectUrls: string[] = [];setArtifactUrls({});- void Promise.all(artifacts.map(async artifact => {+ void Promise.all(artifacts.map(async ([artifactId]) => {const objectUrl = await createCreatorArtifactObjectUrl(session,- artifact.id,+ artifactId,'cover.load-result-preview',l('封面预览加载失败,请稍后重试。', 'Thumbnail previews failed to load. Try again later.'));- objectUrls.push(objectUrl);- return [artifact.id, objectUrl] as const;+ if (active) objectUrls.push(objectUrl);+ else URL.revokeObjectURL(objectUrl);+ return [artifactId, objectUrl] as const;})).then(entries => {if (active) setArtifactUrls(Object.fromEntries(entries));}).catch(() => undefined);@@ -254,14 +270,7 @@ export default function CoverGeneratorWorkspace(props: {active = false;objectUrls.forEach(url => URL.revokeObjectURL(url));};- }, [- selectedKeyframeArtifact?.id,- selectedReferenceArtifact?.id,- selectedResult?.artifacts,- l,- session?.captureCreatorFailure,- session?.openArtifact- ]);+ }, [resultPreviewKey]);function openStep(step: CoverStep) {const nextFurthest = Math.max(reachableFurthestStep, step) as CoverStep;diff --git a/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx b/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsxindex fa496e98..11bf89c4 100644--- a/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx@@ -9,7 +9,7 @@ import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';import ImageGenerationWorkspace from './ImageGenerationWorkspace.js';-import { CreatorSessionProvider } from './creator-session-store.js';+import { CreatorSessionProvider, useOptionalCreatorSession, type CreatorSessionContextValue } from './creator-session-store.js';describe('ImageGenerationWorkspace', () => {beforeEach(() => {@@ -37,6 +37,95 @@ describe('ImageGenerationWorkspace', () => {.not.toBe(0);});+ it('validates required reference input while typing and blocks continuing until uploaded', async () => {+ const fixture = createFixture();+ renderWorkspace(fixture);+ const prompt = screen.getByRole('textbox', { name: '提示词' });+ fireEvent.change(prompt, { target: { value: '以上传的人物照片为唯一主体,生成复古海报' } });+ expect(prompt).toHaveAttribute('aria-invalid', 'true');+ expect(screen.getByRole('status')).toHaveTextContent('请先上传参考图');+ fireEvent.click(screen.getByRole('button', { name: '继续' }));+ expect(screen.getByRole('textbox', { name: '提示词' })).toBeInTheDocument();+ expect(fixture.uploadReferenceImage).not.toHaveBeenCalled();+ await act(async () => {+ fireEvent.change(screen.getByLabelText('上传图像生成参考图'), { target: { files: [new File([png('reference')], 'reference.png', { type: 'image/png' })] } });+ });+ expect(prompt).toHaveAttribute('aria-invalid', 'false');+ fireEvent.click(screen.getByRole('button', { name: '继续' }));+ expect(screen.getByRole('heading', { name: '生成设置' })).toBeInTheDocument();+ });++ it('blocks generation from a restored settings step with a missing reference', () => {+ const fixture = createFixture();+ renderWorkspace(fixture, { ...fixture.currentJob(), state: {+ ...fixture.currentJob().state, prompt: 'Edit the attached photo', currentStep: 2, furthestStep: 2+ } });+ fireEvent.click(screen.getByRole('button', { name: '开始生成' }));+ expect(screen.getByRole('textbox', { name: '提示词' })).toBeInTheDocument();+ expect(fixture.applyAction).not.toHaveBeenCalled();+ });++ it('shows the actual stage failure instead of discarding it for a generic service error', () => {+ const fixture = createFixture();+ const job = fixture.currentJob();+ renderWorkspace(fixture, { ...job, status: 'failed', stages: [{+ id: 'stage-failed', jobId: job.id, stageId: 'generate', executor: 'image',+ status: 'failed', dispatchStatus: 'finished', claimOwner: null, claimExpiresAt: null,+ attempt: 1, idempotencyKey: null, scopeKey: null, inputFingerprint: null, progress: {},+ errorCode: 'image_generation_failed', errorMessage: 'Codex 无法获取所需的参考图,请先上传图片后重试。 token=private-secret',+ startedAt: job.createdAt, finishedAt: job.createdAt+ }] });+ expect(screen.getByRole('alert')).toHaveTextContent('Codex 无法获取所需的参考图,请先上传图片后重试');+ expect(screen.getByRole('alert')).not.toHaveTextContent('private-secret');+ });++ it.each([+ ['empty.png', '', 'image/png'],+ ['file.txt', 'text', 'text/plain']+ ])('rejects an invalid reference before uploading (%s)', (name, content, type) => {+ const file = new File([content], name, { type });+ const fixture = createFixture();+ renderWorkspace(fixture);+ fireEvent.change(screen.getByLabelText('上传图像生成参考图'), { target: { files: [file] } });+ expect(screen.getByRole('alert')).toHaveTextContent('参考图必须是非空的 PNG、JPEG 或 WebP 图片,且不超过 20 MB。');+ expect(fixture.uploadReferenceImage).not.toHaveBeenCalled();+ });++ it('keeps preview URLs and image nodes across repeated job snapshots, but reloads changed results', async () => {+ const fixture = createFixture();+ const artifact = imageArtifact(fixture.currentJob().id, 1, fixture.currentJob().createdAt);+ const job: CreatorJob = { ...fixture.currentJob(), status: 'completed', artifacts: [artifact] };+ vi.mocked(URL.createObjectURL).mockImplementationOnce(() => 'blob:result-1').mockImplementationOnce(() => 'blob:result-2');+ const view = renderWorkspace(fixture, job);+ const image = await screen.findByRole('img', { name: '生成图片 1' });+ expect(image).toHaveAttribute('src', 'blob:result-1');+ for (let revision = 1; revision <= 3; revision += 1) {+ await view.pushSnapshot({ ...structuredClone(job), revision });+ expect(screen.getByRole('img', { name: '生成图片 1' })).toBe(image);+ expect(image).toHaveAttribute('src', 'blob:result-1');+ }+ expect(fixture.openArtifact).toHaveBeenCalledTimes(1);+ expect(URL.revokeObjectURL).not.toHaveBeenCalled();+ await view.pushSnapshot({ ...job, revision: 4, artifacts: [artifact, imageArtifact(job.id, 2, job.createdAt)] });+ await waitFor(() => expect(screen.getByRole('img', { name: '生成图片 1' })).toHaveAttribute('src', 'blob:result-2'));+ expect(fixture.openArtifact).toHaveBeenCalledTimes(2);+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:result-1');+ view.unmount();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:result-2');+ });++ it('releases preview URLs when an in-flight fetch finishes after unmount', async () => {+ const fixture = createFixture();+ let finish!: (response: Response) => void;+ fixture.openArtifact.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const artifact = imageArtifact(fixture.currentJob().id, 1, fixture.currentJob().createdAt);+ const view = renderWorkspace(fixture, { ...fixture.currentJob(), artifacts: [artifact] });+ await waitFor(() => expect(fixture.openArtifact).toHaveBeenCalledOnce());+ view.unmount();+ await act(async () => { finish(new Response(new Blob([png('result')], { type: 'image/png' }))); });+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:image-generation-reference');+ });+it('does not persist an untouched pending project', async () => {vi.useFakeTimers();try {@@ -200,7 +289,8 @@ function renderWorkspace(initialJob = fixture.currentJob(),creatorServicesService?: { getConfig(): Promise<unknown> }) {- return render(+ let currentSession: CreatorSessionContextValue | null = null;+ const view = render(<LanguageProvider initialPreference="zh-CN"><CreatorSessionProviderinitialJob={initialJob}@@ -212,6 +302,7 @@ function renderWorkspace(runAgentTurn: vi.fn()} as never}>+ <SessionObserver onSession={session => { currentSession = session; }} /><ImageGenerationWorkspaceonBack={vi.fn()}creatorServicesService={creatorServicesService as never}@@ -219,6 +310,14 @@ function renderWorkspace(</CreatorSessionProvider></LanguageProvider>);+ return { ...view, async pushSnapshot(job: CreatorJob) {+ await act(async () => { currentSession!.applyRemoteSnapshot(job); });+ } };+}++function SessionObserver(props: { onSession(session: CreatorSessionContextValue | null): void }) {+ props.onSession(useOptionalCreatorSession());+ return null;}function imageArtifact(jobId: string, resultVersion: number, createdAt: string): CreatorArtifact {diff --git a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsxindex 39ba722c..433c1799 100644--- a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx+++ b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx@@ -1,6 +1,9 @@import {creatorPromptMaxLength,+ imagePromptRequiresReference,readCreatorResultSnapshots,+ safePublicErrorMessage,+ type PublicErrorFacts,type CreatorArtifact,type CreatorJson,type ImageGenerationProvider,@@ -20,11 +23,12 @@ import {X,WandSparkles} from 'lucide-react';-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import CreatorResultVersionMenu from './CreatorResultVersionMenu.js';import CreatorTaskSummary from './CreatorTaskSummary.js';import CreatorToolShell from './CreatorToolShell.js';+import { publicErrorReason } from '../issues/issue-catalog.js';import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';import {captureCreatorClientFailure,@@ -109,7 +113,8 @@ export default function ImageGenerationWorkspace(props: {const latestStage = session?.job.stages.filter(stage => stage.stageId === 'generate').at(-1);const generating = latestStage?.status === 'queued' || latestStage?.status === 'running';const runtimeError = latestStage?.status === 'failed'- ? formatImageError({ code: latestStage.errorCode, message: latestStage.errorMessage }, l)+ ? formatImageError({ code: latestStage.errorCode, message: latestStage.errorMessage,+ publicFacts: session?.issues.find(issue => issue.stageRunId === latestStage.id)?.publicFacts }, l): session?.error === null || session?.error === undefined? '': formatImageError(session.error, l);@@ -129,6 +134,21 @@ export default function ImageGenerationWorkspace(props: {session?.state.referenceImageArtifactId,'reference_image');+ const missingReference = imagePromptRequiresReference(prompt)+ && referenceFile === null && activeReferenceArtifact === undefined;+ const referenceValidationMessage = missingReference ? l(+ '当前提示词需要基于已有图片生成,请先上传参考图;如需纯文字生图,请移除对上传图片或原图的要求。',+ 'This prompt requires an existing image. Upload a reference, or remove the uploaded/original image requirements for text-only generation.'+ ) : '';+ const previewContext = useRef({ session, l });+ previewContext.current = { session, l };+ // Snapshots replace artifact arrays frequently; only changed file identities need a new preview.+ const resultPreviewKey = JSON.stringify({+ jobId: session?.job.id,+ artifacts: (selectedResult?.artifacts ?? []).map(artifact => [artifact.id, artifact.version, artifact.sha256, artifact.path])+ });+ const referencePreviewKey = JSON.stringify([session?.job.id, activeReferenceArtifact?.id,+ activeReferenceArtifact?.version, activeReferenceArtifact?.sha256, activeReferenceArtifact?.path]);const currentReferenceName = referenceFile?.name?? readArtifactString(activeReferenceArtifact, 'fileName');const shouldLoadDefaultProvider = session !== null@@ -164,8 +184,10 @@ export default function ImageGenerationWorkspace(props: {}, [count, props.creatorServicesService, session, shouldLoadDefaultProvider]);useEffect(() => {+ const { session, l } = previewContext.current;+ const [, artifactId] = JSON.parse(referencePreviewKey) as Array<string | number | null>;if (referenceFile === null) {- if (activeReferenceArtifact === undefined || session === null) {+ if (typeof artifactId !== 'string' || session === null) {setReferencePreview('');return undefined;}@@ -173,13 +195,14 @@ export default function ImageGenerationWorkspace(props: {let objectUrl = '';void createCreatorArtifactObjectUrl(session,- activeReferenceArtifact.id,+ artifactId,'image-generation.load-reference-preview',l('参考图预览加载失败,请稍后重试。', 'The reference preview failed to load. Try again later.')).then(url => {objectUrl = url;if (active) setReferencePreview(objectUrl);+ else URL.revokeObjectURL(url);}).catch(() => {if (active) setReferencePreview('');@@ -189,6 +212,7 @@ export default function ImageGenerationWorkspace(props: {if (objectUrl) URL.revokeObjectURL(objectUrl);};}+ let active = true;let objectUrl = '';void captureCreatorClientFailure(session,@@ -197,13 +221,15 @@ export default function ImageGenerationWorkspace(props: {() => URL.createObjectURL(referenceFile)).then(url => {objectUrl = url;- setReferencePreview(url);- }).catch(() => setReferencePreview(''));- return () => { if (objectUrl) URL.revokeObjectURL(objectUrl); };- }, [activeReferenceArtifact?.id, l, referenceFile, session?.captureCreatorFailure, session?.openArtifact]);+ if (active) setReferencePreview(url);+ else URL.revokeObjectURL(url);+ }).catch(() => { if (active) setReferencePreview(''); });+ return () => { active = false; if (objectUrl) URL.revokeObjectURL(objectUrl); };+ }, [referencePreviewKey, referenceFile]);useEffect(() => {- const artifacts = selectedResult?.artifacts ?? [];+ const { session, l } = previewContext.current;+ const { artifacts } = JSON.parse(resultPreviewKey) as { artifacts: Array<[string, number, string | null, string | null]> };if (session === null || artifacts.length === 0) {setImageUrls({});setPreviewError('');@@ -213,18 +239,19 @@ export default function ImageGenerationWorkspace(props: {const objectUrls: string[] = [];setImageUrls({});setPreviewError('');- void Promise.all(artifacts.map(async artifact => {+ void Promise.all(artifacts.map(async ([artifactId]) => {const url = await createCreatorArtifactObjectUrl(session,- artifact.id,+ artifactId,'image-generation.load-result-preview',l('图片预览加载失败,可以稍后重试或重新生成。', 'Image previews failed to load. Retry later or generate them again.'));- objectUrls.push(url);- return [artifact.id, url] as const;+ if (active) objectUrls.push(url);+ else URL.revokeObjectURL(url);+ return [artifactId, url] as const;})).then(entries => {if (active) setImageUrls(Object.fromEntries(entries));- }).catch(cause => {+ }).catch(() => {if (active) {setPreviewError(l('图片预览加载失败,可以稍后重试或重新生成',@@ -236,7 +263,7 @@ export default function ImageGenerationWorkspace(props: {active = false;objectUrls.forEach(url => URL.revokeObjectURL(url));};- }, [l, selectedResult?.artifacts, session?.captureCreatorFailure, session?.openArtifact]);+ }, [resultPreviewKey]);useEffect(() => {if (latestVersion !== undefined && !generating) {@@ -260,6 +287,11 @@ export default function ImageGenerationWorkspace(props: {setError(l('请先描述需要生成的画面', 'Describe the image you want to create'));return;}+ if (missingReference) {+ setError(referenceValidationMessage);+ openStep(0);+ return;+ }openStep(Math.min(2, currentStep + 1) as ImageStep);}@@ -301,6 +333,12 @@ export default function ImageGenerationWorkspace(props: {}function chooseReference(file: File | null) {+ if (file !== null && (!['image/png', 'image/jpeg', 'image/webp'].includes(file.type)+ || file.size === 0 || file.size > 20 * 1024 * 1024)) {+ setError(l('参考图必须是非空的 PNG、JPEG 或 WebP 图片,且不超过 20 MB。',+ 'Select a non-empty PNG, JPEG, or WebP reference image no larger than 20 MB.'));+ return;+ }setReferenceFile(file);setError('');}@@ -325,6 +363,11 @@ export default function ImageGenerationWorkspace(props: {openStep(0);return;}+ if (missingReference) {+ setError(referenceValidationMessage);+ openStep(0);+ return;+ }setError('');setNotice('');session.updateDraft({@@ -527,9 +570,16 @@ export default function ImageGenerationWorkspace(props: {value={prompt}onChange={event => updatePrompt(event.target.value)}aria-labelledby="image-prompt-label"+ aria-invalid={missingReference}+ aria-describedby={missingReference ? 'image-reference-validation' : undefined}placeholder={l('例如:一位产品设计师站在明亮的工作室中,真实摄影,柔和侧光,画面简洁', 'For example: A product designer in a bright studio, realistic photography, soft side lighting, clean composition')}/></div>+ {missingReference ? (+ <p id="image-reference-validation" className="creator-services-inline-note" role="status">+ {referenceValidationMessage}+ </p>+ ) : null}</div><button className="smart-dubbing-sample" type="button" onClick={() => updatePrompt(l(samplePromptZh, samplePromptEn))}><WandSparkles size={14} strokeWidth={1.8} />@@ -687,7 +737,7 @@ export default function ImageGenerationWorkspace(props: {/></div>) : null}- {error ? <p className="creator-tool-error" role="alert">{error}</p> : null}+ {visibleError ? <p className="creator-tool-error" role="alert">{visibleError}</p> : null}{notice ? <p className="creator-tool-notice" role="status">{notice}</p> : null}</div>@@ -835,8 +885,15 @@ function formatImageError(error: unknown, l: (zh: string, en: string) => string)const message = error.result.blocked.map(item => item.message).filter(Boolean).join(';');return message || l('启动前检查未通过,请检查任务配置', 'Preflight checks failed. Review the task settings.');}- const candidate = error as { code?: unknown; message?: unknown };+ const candidate = error as { code?: unknown; message?: unknown; publicFacts?: PublicErrorFacts; issue?: { publicFacts?: PublicErrorFacts } };const code = typeof candidate?.code === 'string' ? candidate.code : '';+ const facts = candidate?.issue?.publicFacts ?? candidate?.publicFacts;+ if (facts !== undefined && (facts.kind !== 'unknown' || facts.upstreamMessage !== undefined)) {+ return publicErrorReason(facts, l);+ }+ const message = safePublicErrorMessage(candidate?.message);+ if (message && (code === 'image_generation_failed' || code === 'creator_stage_input_missing'+ || code === 'unsupported_capability' || code === 'creator_image_config_missing')) return message;if (code === 'creator_image_config_missing') {return l('请先在设置的 AI 服务中配置所选图像服务', 'Configure the selected image provider in AI Services first');}diff --git a/apps/web/src/features/dashboard/creator-session-store.test.tsx b/apps/web/src/features/dashboard/creator-session-store.test.tsxindex d188c6f1..0ce35efd 100644--- a/apps/web/src/features/dashboard/creator-session-store.test.tsx+++ b/apps/web/src/features/dashboard/creator-session-store.test.tsx@@ -1233,7 +1233,7 @@ describe('CreatorSessionStore', () => {ready: [],warning: [],blocked: [{- id: 'provider',+ id: 'llm',title: '服务未配置',message: '请先配置服务。',executionMode: 'remote'@@ -1257,6 +1257,8 @@ describe('CreatorSessionStore', () => {source: 'preflight'}));expect(session!.issues).toHaveLength(1);+ expect(session!.issues[0]).toMatchObject({ code: 'creator_llm_config_missing',+ category: 'configuration', publicFacts: { kind: 'configuration', upstreamMessage: '请先配置服务。' } });});it('uses the current display language and original evidence when asking about a local issue', async () => {diff --git a/apps/web/src/features/dashboard/creator-session-store.tsx b/apps/web/src/features/dashboard/creator-session-store.tsxindex cc0f97af..cb854392 100644--- a/apps/web/src/features/dashboard/creator-session-store.tsx+++ b/apps/web/src/features/dashboard/creator-session-store.tsx@@ -1,6 +1,8 @@import {isOpenCreatorIssue,+ creatorPreflightFailure,type OpenCreatorIssue,+ type PublicErrorFacts,CreatorActionRequest,CreatorActivity,CreatorAgentApproval,@@ -136,9 +138,14 @@ export type CreatorSessionError = {};export class CreatorPreflightBlockedError extends Error {+ readonly code: string;+ readonly publicFacts: PublicErrorFacts;constructor(readonly result: CreatorPreflightResponse) {- super('Creator preflight blocked this stage');+ const failure = creatorPreflightFailure(result);+ super(failure.message);this.name = 'CreatorPreflightBlockedError';+ this.code = failure.code;+ this.publicFacts = failure.publicFacts;}}diff --git a/apps/web/src/features/issues/issue-catalog.test.ts b/apps/web/src/features/issues/issue-catalog.test.tsindex b39d2e0b..199b80a4 100644--- a/apps/web/src/features/issues/issue-catalog.test.ts+++ b/apps/web/src/features/issues/issue-catalog.test.ts@@ -6,6 +6,44 @@ const raw = '后台原文:操作无法完成';const issue = normalizePageIssue('runtime', 'creator.prepare', new Error(raw), raw);describe('localized issue copy', () => {+ it('shows the filesystem failure code and actual cause with relevant retry guidance', () => {+ const next = { ...issue, source: 'stage' as const, code: 'ERR_FS_FILE_TOO_LARGE', publicFacts: {+ kind: 'storage' as const, upstreamCode: 'ERR_FS_FILE_TOO_LARGE',+ upstreamMessage: 'File size (4014655674) is greater than 2 GiB'+ } };+ const text = issueConversationText(next, 'zh-CN');+ expect(text.message).toContain('ERR_FS_FILE_TOO_LARGE');+ expect(text.message).toContain('超过大小限制');+ expect(text.message).toContain('4014655674');+ expect(text.nextStep).toContain('重试当前步骤');+ expect(text.message).not.toContain('尚未确认更细的原因');+ });+ it('shows sanitized saved evidence for an older stage whose structured facts were lost', () => {+ const next = { ...issue, code: 'creator_stage_failed', source: 'stage' as const,+ publicFacts: { kind: 'unknown' as const }, technicalDetail: 'File size (4014655674) is greater than 2 GiB token=private' };+ expect(presentIssue(next, 'zh-CN').description).toContain('4014655674');+ expect(presentIssue(next, 'zh-CN').description).toContain('ERR_FS_FILE_TOO_LARGE');+ expect(presentIssue(next, 'zh-CN').description).toContain('3.74 GiB');+ expect(presentIssue(next, 'zh-CN').description).not.toContain('尚未确认更细的原因');+ expect(presentIssue(next, 'zh-CN').description).not.toContain('private');+ expect(presentIssue(next, 'zh-CN').description).toContain('超过大小限制');+ expect(presentIssue(next, 'zh-CN').description).toContain('底层错误码:ERR_FS_FILE_TOO_LARGE');+ expect(presentIssue(next, 'zh-CN').description).not.toContain('。。');+ expect(issueConversationText(next, 'zh-CN').nextStep).toContain('重试当前步骤');+ expect(issueDiagnosticText(next)).toContain('File size (4014655674)');+ expect(issueDiagnosticText(next)).not.toContain('private');+ });+ it('explains a missing native reference and gives an upload action', () => {+ const next = { ...issue, code: 'image_generation_failed', publicFacts: {+ kind: 'validation' as const, provider: 'codex-native', upstreamCode: 'IMAGE_REFERENCE_MISSING',+ upstreamMessage: '当前会话中没有可用的已上传人物照片。'+ } };+ const conversation = issueConversationText(next, 'zh-CN');+ expect(conversation.message).toContain('图片生成失败');+ expect(conversation.message).toContain('没有可用的已上传人物照片');+ expect(conversation.nextStep).toContain('上传参考图');+ expect(conversation.message).not.toContain('尚未确认更细的原因');+ });it.each(['zh-CN', 'en-US', 'sv-SE'] as const)('shows the actual upstream reason and request ID in %s', language => {const next = { ...issue, code: 'creator_video_upstream_error', publicFacts: {kind: 'http-rejected' as const, provider: 'seedance', httpStatus: 400,diff --git a/apps/web/src/features/issues/issue-catalog.ts b/apps/web/src/features/issues/issue-catalog.tsindex bc28dc30..0bea070b 100644--- a/apps/web/src/features/issues/issue-catalog.ts+++ b/apps/web/src/features/issues/issue-catalog.ts@@ -1,4 +1,4 @@-import { safePublicErrorCode, sanitizePublicErrorFacts, type OpenCreatorIssue, type PublicErrorFacts } from '@opencreator/protocol';+import { safePublicErrorCode, safePublicErrorMessage, sanitizePublicErrorFacts, type OpenCreatorIssue, type PublicErrorFacts } from '@opencreator/protocol';import type { AppLanguage } from '../../i18n/language.js';import { createLocalizedCopy, type LocalizeCopy } from '../../i18n/localized-copy.js';@@ -40,21 +40,39 @@ export function presentIssue(function issueDescription(issue: OpenCreatorIssue, language: AppLanguage): string {const localize = createLocalizedCopy(language);- const summary = localizedIssueSummary(issue, localize);+ const facts = issuePublicFacts(issue);+ const summary = localizedIssueSummary({ ...issue, publicFacts: facts }, localize);const code = safePublicErrorCode(issue.code) ?? 'UNKNOWN_ERROR';- const reason = issue.publicFacts === undefined+ const reason = facts === undefined? localize('当前记录未提供更细的原因。', 'No more specific cause was recorded.', 'Ingen mer specifik orsak har registrerats.')- : publicErrorReason(issue.publicFacts, language);+ : publicErrorReason(facts, language);return localize(`${summary} 错误码:${code}。${reason}`, `${summary} Error code: ${code}. ${reason}`, `${summary} Felkod: ${code}. ${reason}`);}+function issuePublicFacts(issue: OpenCreatorIssue): PublicErrorFacts | undefined {+ const historicalReason = issue.source === 'stage' || issue.source === 'preflight'+ ? safePublicErrorMessage(issue.technicalDetail) : undefined;+ let facts = (issue.publicFacts === undefined || issue.publicFacts.kind === 'unknown')+ && issue.publicFacts?.upstreamMessage === undefined && historicalReason !== undefined+ ? { ...(issue.publicFacts ?? { kind: 'unknown' as const }), upstreamMessage: historicalReason }+ : issue.publicFacts;+ // Older stage records discarded Node's code but retained its exact file-size error.+ if (issue.source === 'stage' && issue.code === 'creator_stage_failed'+ && facts?.kind === 'unknown' && /\bFile size \(\d+\) is greater than 2 GiB\b/.test(facts.upstreamMessage ?? '')) {+ facts = { ...facts, kind: 'storage', upstreamCode: 'ERR_FS_FILE_TOO_LARGE' };+ }+ return facts;+}+function localizedIssueSummary(issue: OpenCreatorIssue, localize: LocalizeCopy): string {+ if (issue.code === 'ERR_FS_FILE_TOO_LARGE' || issue.publicFacts?.upstreamCode === 'ERR_FS_FILE_TOO_LARGE') return localize('本地文件读取超过大小限制。', 'The local file exceeded the read-size limit.', 'Den lokala filen överskred storleksgränsen för läsning.');if (issue.stageId === 'prepare-source-video') return localize('原视频准备失败,已有字幕不受影响。', 'Source video preparation failed; existing subtitles are unchanged.', 'Förberedelsen av originalvideon misslyckades; befintliga undertexter är oförändrade.');if (issue.operation === 'creator.agent-turn') return localize('Agent 未能完成诊断,请查看问题详情后重试。', 'The Agent could not complete the diagnosis. Review the issue details and retry.', 'Agent kunde inte slutföra diagnostiken. Läs probleminformationen och försök igen.');if (issue.code === 'creator_dependency_prepare_failed') return localize('本地转录组件准备失败,请前往组件页面检查并重试。', 'Local transcription preparation failed. Check the component page and retry.', 'Förberedelsen av lokal transkription misslyckades. Kontrollera komponentsidan och försök igen.');if (issue.code === 'creator_source_part_required' || issue.code === 'INVALID_PART') return localize('请检查 B 站链接并选择有效的视频分集。', 'Check the Bilibili URL and select a valid video part.', 'Kontrollera Bilibili-länken och välj en giltig videodel.');if (issue.code === 'creator_template_version_mismatch') return localize('项目模板版本不匹配,请刷新页面后重试。', 'The project template version does not match. Refresh the page and retry.', 'Projektets mallversion stämmer inte. Uppdatera sidan och försök igen.');if (issue.code === 'creator_upload_failed') return localize('上传未完成,请重试。', 'The upload did not complete. Please retry.', 'Uppladdningen slutfördes inte. Försök igen.');+ if (issue.code === 'image_generation_failed') return localize('图片生成失败。', 'Image generation failed.', 'Bildgenereringen misslyckades.');const entry = catalog[issue.summaryKey] ?? catalog[`issue.${issue.category}`] ?? catalog['issue.unknown']!;return localize(entry.zh, entry.en);}@@ -90,10 +108,16 @@ export function publicErrorReason(input: PublicErrorFacts, language: AppLanguage}if (facts.httpStatus !== undefined) parts.push(`HTTP ${facts.httpStatus}`);if (facts.upstreamCode !== undefined && safePublicErrorCode(facts.upstreamCode) !== undefined) {- parts.push(`upstream: ${safeIdentifier(facts.upstreamCode)}`);+ parts.push(localize(`底层错误码:${safeIdentifier(facts.upstreamCode)}`, `Upstream error code: ${safeIdentifier(facts.upstreamCode)}`, `Underliggande felkod: ${safeIdentifier(facts.upstreamCode)}`));}if (facts.upstreamMessage !== undefined) {- parts.push(localize(`服务说明:${facts.upstreamMessage}`, `Provider message: ${facts.upstreamMessage}`, `Leverantörens meddelande: ${facts.upstreamMessage}`));+ const size = /\bFile size \((\d+)\) is greater than 2 GiB\b/.exec(facts.upstreamMessage);+ const message = size === null ? facts.upstreamMessage : localize(+ `文件为 ${size[1]} 字节(约 ${(Number(size[1]) / 1024 ** 3).toFixed(2)} GiB),超过本地单次读取的 2 GiB 限制`,+ `The file is ${size[1]} bytes (about ${(Number(size[1]) / 1024 ** 3).toFixed(2)} GiB), exceeding the local 2 GiB limit for a single read`,+ `Filen är ${size[1]} byte (cirka ${(Number(size[1]) / 1024 ** 3).toFixed(2)} GiB) och överskrider den lokala gränsen på 2 GiB för en enskild läsning`+ );+ parts.push(localize(`服务说明:${message}`, `Provider message: ${message}`, `Leverantörens meddelande: ${message}`));}if (facts.requestId !== undefined) {parts.push(localize(`请求编号:${facts.requestId}`, `Request ID: ${facts.requestId}`, `Begärans-ID: ${facts.requestId}`));@@ -118,12 +142,19 @@ export function issueConversationText(): { message: string; nextStep: string } {const detail = presentIssue(issue, language).description;const localize = createLocalizedCopy(language);- const nextStep = issue.code === 'creator_template_version_mismatch'+ const facts = issuePublicFacts(issue);+ const nextStep = issue.code === 'ERR_FS_FILE_TOO_LARGE' || facts?.upstreamCode === 'ERR_FS_FILE_TOO_LARGE'+ ? localize('请重试当前步骤;如果仍然失败,可先切分视频,并向 Agent 提供文件大小和诊断编号。', 'Retry the current step. If it still fails, split the video and provide the file size and diagnostic ID to the Agent.', 'Försök igen. Om det fortfarande misslyckas, dela videon och ge filstorleken och diagnostik-ID till Agent.')+ : issue.publicFacts?.upstreamCode === 'IMAGE_REFERENCE_MISSING'+ ? localize('请先上传参考图;如需纯文字生图,请移除对上传图片或原图的要求后重试。', 'Upload a reference image, or remove the uploaded/original image requirements for text-only generation, then retry.', 'Ladda upp en referensbild, eller ta bort kraven på en uppladdad eller ursprunglig bild för textgenerering och försök igen.')+ : issue.code === 'creator_template_version_mismatch'? localize('请刷新页面以加载当前模板版本;如果仍然失败,请重新启动本地服务。', 'Refresh the page to load the current template version. If the problem persists, restart the local service.', 'Uppdatera sidan för att läsa in den aktuella mallversionen. Om problemet kvarstår, starta om den lokala tjänsten.'): issue.publicFacts?.kind === 'http-rejected' || issue.publicFacts?.kind === 'provider-failed'? localize('请根据服务返回的原因调整输入或请求参数后重试;仍有疑问时,可提供请求编号向服务方查询。', 'Review the provider reason and adjust the input or request parameters before retrying. Use the request ID to ask the provider for details if needed.', 'Läs leverantörens felorsak och justera indata eller parametrarna innan du försöker igen. Använd begärans-ID för att fråga leverantören vid behov.'): issue.publicFacts?.kind === 'unauthorized'- ? localize('请检查服务凭据和模型访问权限后重试。', 'Check the provider credentials and model access permissions before retrying.', 'Kontrollera leverantörens autentiseringsuppgifter och modellbehörigheter innan du försöker igen.')+ ? issue.publicFacts.provider === 'codex-native'+ ? localize('请在本机 Codex 中重新登录 ChatGPT 后重试。', 'Sign in to ChatGPT again in local Codex, then retry.', 'Logga in på ChatGPT igen i lokala Codex och försök igen.')+ : localize('请检查服务凭据和模型访问权限后重试。', 'Check the provider credentials and model access permissions before retrying.', 'Kontrollera leverantörens autentiseringsuppgifter och modellbehörigheter innan du försöker igen.'): issue.publicFacts?.kind === 'rate-limited'? localize('请检查服务配额或稍后重试。', 'Check the provider quota or retry later.', 'Kontrollera leverantörens kvot eller försök igen senare.'): issue.category === 'network'@@ -160,7 +191,7 @@ export function buildIssueAgentPrompt(}export function issueDiagnosticText(issue: OpenCreatorIssue, language: AppLanguage = 'zh-CN'): string {- return safeFallback(issue.fallbackMessage, language);+ return safeFallback(safePublicErrorMessage(issue.technicalDetail) ?? issue.fallbackMessage, language);}function safeFallback(value: string, language: AppLanguage): string {diff --git a/apps/web/src/features/issues/page-issue-state.test.tsx b/apps/web/src/features/issues/page-issue-state.test.tsxindex 863e39fc..5c6a9476 100644--- a/apps/web/src/features/issues/page-issue-state.test.tsx+++ b/apps/web/src/features/issues/page-issue-state.test.tsx@@ -3,8 +3,22 @@ import { describe, expect, it } from 'vitest';import { ApiClientError } from '../../runtime/errors.js';import { buildIssueAgentPrompt, issueConversationText } from './issue-catalog.js';import { normalizePageIssue, usePageIssueState } from './page-issue-state.js';+import { CreatorPreflightBlockedError } from '../dashboard/creator-session-store.js';describe('usePageIssueState', () => {+ it('keeps a client-side preflight blocker code and sanitized reason in the Agent message', () => {+ const error = new CreatorPreflightBlockedError({ templateId: 'video-translation', templateVersion: 2,+ stageId: 'subtitle', executionMode: 'local', canStart: false, ready: [], warning: [],+ blocked: [{ id: 'transcription-config', title: '转录服务', message: '请配置 OpenAI 转录凭据。 token=private', executionMode: 'remote', repair: { label: '配置' } }], checkedAt: '' });+ const issue = normalizePageIssue('creator-session', 'creator.preflight', error, '启动检查未通过。');+ expect(issue).toMatchObject({ code: 'creator_transcription_config_missing', category: 'configuration',+ publicFacts: { kind: 'configuration', upstreamMessage: expect.stringContaining('请配置 OpenAI 转录凭据') } });+ const text = issueConversationText(issue).message;+ expect(text).toContain('creator_transcription_config_missing');+ expect(text).toContain('请配置 OpenAI 转录凭据');+ expect(text).not.toContain('CLIENT_OPERATION_FAILED');+ expect(text).not.toContain('private');+ });it('explains a confirmed template version mismatch without exposing an arbitrary server response', () => {const issue = normalizePageIssue('creator-launch',diff --git a/apps/web/src/features/issues/page-issue-state.ts b/apps/web/src/features/issues/page-issue-state.tsindex ccea5471..9e7f43f0 100644--- a/apps/web/src/features/issues/page-issue-state.ts+++ b/apps/web/src/features/issues/page-issue-state.ts@@ -1,4 +1,4 @@-import { publicErrorKindForCode, safePublicErrorCode, type OpenCreatorIssue } from '@opencreator/protocol';+import { isPublicErrorFacts, publicErrorCodeFromFailure, publicErrorKindForCode, safePublicErrorCode, sanitizePublicErrorFacts, type PublicErrorFacts, type OpenCreatorIssue } from '@opencreator/protocol';import { useCallback, useMemo, useState } from 'react';import { ApiClientError } from '../../runtime/errors.js';import {@@ -115,8 +115,15 @@ export function normalizePageIssue(const now = new Date().toISOString();const code = readCode(cause);const kind = publicErrorKindForCode(code);+ const suppliedFacts = cause !== null && typeof cause === 'object'+ ? (cause as { publicFacts?: PublicErrorFacts }).publicFacts : undefined;+ const facts = suppliedFacts !== undefined && suppliedFacts !== null && typeof suppliedFacts === 'object'+ ? sanitizePublicErrorFacts(suppliedFacts) : undefined;const network = kind === 'dns' || kind === 'connection-refused'|| kind === 'connection-reset' || kind === 'timeout';+ const confirmedKind = facts !== undefined && isPublicErrorFacts(facts) ? facts.kind : kind;+ const category = network ? 'network' : confirmedKind === 'configuration' ? 'configuration'+ : confirmedKind === 'validation' ? 'input' : 'execution';const key = stableKey(`${surface}:${operationId}:${code}`);return {id: `page:${createId()}`,@@ -124,15 +131,15 @@ export function normalizePageIssue(code,scope: { kind: 'page', surface },source: network ? 'network' : 'client',- category: network ? 'network' : 'execution',+ category,severity: 'error',status: 'open',operation: operationId,- summaryKey: 'issue.execution',+ summaryKey: `issue.${category}`,summaryParams: {},fallbackMessage,- ...(cause instanceof ApiClientError && cause.publicFacts !== undefined- ? { publicFacts: cause.publicFacts }+ ...(facts !== undefined && isPublicErrorFacts(facts)+ ? { publicFacts: facts }: kind === undefined ? {} : { publicFacts: { kind } }),retryable: false,repairActions: [],@@ -156,12 +163,7 @@ function mergeOccurrence(previous: OpenCreatorIssue | undefined, next: OpenCreatfunction readCode(cause: unknown): string {if (cause instanceof ApiClientError) return safePublicErrorCode(cause.code) ?? 'CLIENT_OPERATION_FAILED';- if (cause !== null && typeof cause === 'object' && 'code' in cause) {- const code = (cause as { code?: unknown }).code;- const safeCode = safePublicErrorCode(code);- if (safeCode !== undefined) return safeCode;- }- return 'CLIENT_OPERATION_FAILED';+ return publicErrorCodeFromFailure(cause) ?? 'CLIENT_OPERATION_FAILED';}function createId(): string {diff --git a/apps/web/src/features/settings/CodexImageStatusNotice.test.tsx b/apps/web/src/features/settings/CodexImageStatusNotice.test.tsxindex 5504ddfd..b233abcf 100644--- a/apps/web/src/features/settings/CodexImageStatusNotice.test.tsx+++ b/apps/web/src/features/settings/CodexImageStatusNotice.test.tsx@@ -29,10 +29,10 @@ describe('Codex image status notice', () => {it('switches a not-ready explanation and keeps the raw reason in diagnostics', async () => {const raw = '当前 Codex Runtime 不支持原生生图';render(<LanguageProvider initialPreference="en-US"><LanguageSwitchControls /><CodexImageStatusNotice service={service(async () => ({ authentication: 'chatgpt', ready: false, executionMode: null, message: raw }))} /></LanguageProvider>);- expect(await screen.findByText(/Check Agent sign-in, configuration, and Runtime tool support/)).toBeVisible();+ expect(await screen.findByText(/Check local Codex sign-in, configuration, and Runtime tool support/)).toBeVisible();expect(screen.getByText(raw)).not.toBeVisible();fireEvent.click(screen.getByRole('button', { name: 'sv-SE' }));- expect(screen.getByText(/Kontrollera Agent-inloggningen/)).toBeVisible();+ expect(screen.getByText(/Kontrollera den lokala Codex-inloggningen/)).toBeVisible();fireEvent.click(screen.getByText('Visa ursprunglig diagnostik'));expect(screen.getByText(raw)).toBeVisible();});@@ -49,13 +49,12 @@ describe('Codex image status notice', () => {expect(screen.queryByText(api.message)).not.toBeInTheDocument();});- it('offers the real Agent setup callback when login or capability is unavailable', async () => {- const onOpenAgentSetup = vi.fn();- render(<CodexImageStatusNotice service={service(async () => ({ authentication: 'chatgpt', ready: false, executionMode: null, message: '请重新登录' }))} onOpenAgentSetup={onOpenAgentSetup} />);- expect(await screen.findByText(/请检查 Agent 登录、配置和 Runtime 工具支持/)).toBeVisible();+ it('directs unavailable image login to local Codex configuration', async () => {+ render(<CodexImageStatusNotice service={service(async () => ({ authentication: 'chatgpt', ready: false, executionMode: null, message: '请重新登录' }))} />);+ expect(await screen.findByText(/请检查本机 Codex 的登录、配置和 Runtime 工具支持/)).toBeVisible();expect(screen.getByText('请重新登录')).not.toBeVisible();- await userEvent.click(screen.getByRole('button', { name: '配置 Agent' }));- expect(onOpenAgentSetup).toHaveBeenCalledOnce();+ expect(screen.getByText(/生图方式跟随本机 Codex 的登录和配置/)).toBeVisible();+ expect(screen.queryByRole('button', { name: '配置 Agent' })).not.toBeInTheDocument();expect(screen.queryByText(/以实际生成结果为准/)).not.toBeInTheDocument();});diff --git a/apps/web/src/features/settings/CodexImageStatusNotice.tsx b/apps/web/src/features/settings/CodexImageStatusNotice.tsxindex bbf1e232..a2fed23d 100644--- a/apps/web/src/features/settings/CodexImageStatusNotice.tsx+++ b/apps/web/src/features/settings/CodexImageStatusNotice.tsx@@ -6,7 +6,7 @@ import { OriginalErrorDetails } from '../issues/OriginalErrorDetails.js';export function CodexImageStatusNotice(props: {service: CreatorServicesSettingsService | null;- onOpenAgentSetup?(): void;+ enabled?: boolean;}) {const localize = useLocalizedCopy();const [status, setStatus] = useState<CodexImageStatus>();@@ -42,15 +42,20 @@ export function CodexImageStatusNotice(props: {<p>{failed ? localize('无法读取生图状态,请检查 Runtime 连接后重试。', 'Cannot read image status. Check the Runtime connection and retry.'): status?.ready ? status.executionMode === 'native'? localize('已检测到本地 ChatGPT 登录凭据和原生生图工具;无需额外配置图片 API Key。', 'Local ChatGPT credentials and native image tools were detected; no additional image API key is required.', 'Lokala ChatGPT-inloggningsuppgifter och inbyggda bildverktyg har hittats; ingen extra API-nyckel för bilder behövs.')- : localize('已检测到 Codex API 配置;当前接口和模型需要支持图片生成。', 'Codex API configuration was detected; the configured API and model must support image generation.', 'API-inställningar för Codex har hittats; det konfigurerade API:et och modellen måste stödja bildgenerering.')- : status ? localize('Codex 生图尚未就绪,请检查 Agent 登录、配置和 Runtime 工具支持。', 'Codex image generation is not ready. Check Agent sign-in, configuration, and Runtime tool support.', 'Bildgenerering med Codex är inte redo. Kontrollera Agent-inloggningen, inställningarna och verktygsstödet i Runtime.')+ : localize('已检测到本机 Codex API 配置;将使用本机配置的 API Key 和接口,当前接口和模型需要支持图片生成。', 'Local Codex API configuration was detected; image generation uses its API key and endpoint. The configured API and model must support image generation.', 'Lokala API-inställningar för Codex har hittats; bildgenerering använder dess API-nyckel och adress. Det konfigurerade API:et och modellen måste stödja bildgenerering.')+ : status ? localize('Codex 生图尚未就绪,请检查本机 Codex 的登录、配置和 Runtime 工具支持。', 'Codex image generation is not ready. Check local Codex sign-in, configuration, and Runtime tool support.', 'Bildgenerering med Codex är inte redo. Kontrollera den lokala Codex-inloggningen, inställningarna och verktygsstödet i Runtime.'): !readStatus ? localize('当前 Runtime 无法检查生图能力,请更新 Runtime。', 'This Runtime cannot check image capabilities. Update the Runtime.') : ''}</p>{!status?.ready && status?.message ? <OriginalErrorDetails detail={status.message} /> : null}+ {props.enabled && status?.ready ? <p>{localize(+ '本机 Codex 生图已生效,无需保存即可使用。手动更改服务后,请保存配置。',+ 'Local Codex image generation is active and ready without saving. Save settings after changing the service.',+ 'Bildgenerering med lokala Codex är aktiv och kan användas utan att spara. Spara inställningarna efter att du bytt tjänst.'+ )}</p> : null}{status?.version ? <p>{localize('Runtime 版本', 'Runtime version')}: {status.version}</p> : null}+ <p>{localize('生图方式跟随本机 Codex 的登录和配置;切换后可刷新状态。', 'Image generation follows local Codex sign-in and configuration. Refresh the status after switching.', 'Bildgenerering följer den lokala Codex-inloggningen och inställningarna. Uppdatera statusen efter ett byte.')}</p>{status?.ready ? <p>{localize('这里只检查本地配置和工具能力,不会执行生图请求;账号权限、额度及接口可用性以实际生成结果为准。', 'This checks local configuration and tool support without generating an image. Account access, quota, and API availability are verified during generation.')}</p> : null}<div className="creator-services-codex-image-actions">{readStatus ? <button type="button" className="settings-secondary-button" disabled={loading} onClick={() => setRefreshToken(value => value + 1)}>{localize('刷新状态', 'Refresh status')}</button> : null}- {props.onOpenAgentSetup ? <button type="button" className="settings-secondary-button" onClick={props.onOpenAgentSetup}>{localize('配置 Agent', 'Set up Agent')}</button> : null}</div></div>;}diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsxindex a72dfdbd..81f94bc6 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx@@ -14,19 +14,50 @@ import type { CreatorServicesSettingsService } from '../../services/creator-servimport { CreatorServicesSettingsView } from './CreatorServicesSettingsView.js';describe('CreatorServicesSettingsView', () => {+ it('keeps the saved image service active until a detected local service is manually saved', async () => {+ const user = userEvent.setup();+ const service = createService();+ const originalRead = service.getConfig;+ service.getConfig = vi.fn(async () => {+ const response = await originalRead();+ return { ...response, config: { ...response.config, image: { ...response.config.image, provider: 'openai' as const } } };+ });+ service.getCodexImageStatus = vi.fn(async () => ({ authentication: 'chatgpt' as const, ready: true, executionMode: 'native' as const, message: 'ready' }));+ render(<CreatorServicesSettingsView connected service={service} modelService={createModelService()} initialSection="image" />);+ await user.click(await screen.findByRole('combobox', { name: '服务商' }));+ await user.click(screen.getByRole('option', { name: '本机 Codex 生图' }));+ expect(await screen.findByText('ChatGPT 登录态 · 原生生图')).toBeVisible();+ expect(screen.queryByText(/本机 Codex 生图已生效/)).not.toBeInTheDocument();+ expect(service.saveConfig).not.toHaveBeenCalled();+ await user.click(screen.getByRole('button', { name: '保存配置' }));+ expect(await screen.findByText(/本机 Codex 生图已生效,无需保存即可使用/)).toBeVisible();+ expect(service.saveConfig).toHaveBeenCalledOnce();+ });+ it.each(['chatgpt', 'api_key'] as const)('uses detected %s defaults without asking for a settings save', async authentication => {+ const service = createService([], runtimeCapabilities('darwin', 'arm64'), 'codex');+ service.getCodexModelStatus = vi.fn(async () => ({ authentication, apiKeyConfigured: authentication === 'api_key', baseUrl: '', model: 'local-model' }));+ service.getCodexImageStatus = vi.fn(async () => ({ authentication, ready: true, executionMode: authentication === 'chatgpt' ? 'native' as const : 'api' as const, message: 'ready' }));+ const modelService = createModelService();+ render(<CreatorServicesSettingsView connected service={service} modelService={modelService} />);+ expect(await screen.findByText(/已自动启用本机 Codex,无需保存即可使用/)).toBeVisible();+ expect(modelService.getCodexProvider).not.toHaveBeenCalled();+ expect(service.saveConfig).not.toHaveBeenCalled();+ await userEvent.click(screen.getByRole('tab', { name: '图像生成' }));+ expect(await screen.findByText(/本机 Codex 生图已生效,无需保存即可使用/)).toBeVisible();+ expect(service.saveConfig).not.toHaveBeenCalled();+ });it('loads the real Codex image status only in the native image settings section', async () => {const service = createService();service.getCodexImageStatus = vi.fn(async () => ({ authentication: 'chatgpt' as const, ready: true, executionMode: 'native' as const, message: '本地登录凭据已就绪' }));- const onOpenAgentSetup = vi.fn();- render(<CreatorServicesSettingsView connected service={service} modelService={createModelService()} onOpenAgentSetup={onOpenAgentSetup} />);+ render(<CreatorServicesSettingsView connected service={service} modelService={createModelService()} />);expect(service.getCodexImageStatus).not.toHaveBeenCalled();await userEvent.click(await screen.findByRole('tab', { name: '图像生成' }));expect(await screen.findByText('ChatGPT 登录态 · 原生生图')).toBeInTheDocument();expect(screen.getByText(/已检测到本地 ChatGPT 登录凭据和原生生图工具/)).toBeInTheDocument();expect(screen.queryByText('本地登录凭据已就绪')).not.toBeInTheDocument();expect(service.getCodexImageStatus).toHaveBeenCalledOnce();- await userEvent.click(screen.getByRole('button', { name: '配置 Agent' }));- expect(onOpenAgentSetup).toHaveBeenCalledOnce();+ expect(screen.getByText(/生图方式跟随本机 Codex 的登录和配置/)).toBeVisible();+ expect(screen.queryByRole('button', { name: '配置 Agent' })).not.toBeInTheDocument();});it('saves an OSS region and optional endpoint in the shared settings form', async () => {const user = userEvent.setup();diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.tsxindex 3fdec527..e1d87c36 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.tsx@@ -63,7 +63,6 @@ export function CreatorServicesSettingsView(props: {service: CreatorServicesSettingsService | null;modelService?: ModelSettingsService | null;initialSection?: CreatorServicesSection;- onOpenAgentSetup?(): void;}) {const l = useLocalizedCopy();const confirm = useConfirmDialog();@@ -71,6 +70,7 @@ export function CreatorServicesSettingsView(props: {props.initialSection ?? 'text');const [config, setConfig] = useState<CreatorServicesConfig>();+ const [savedImageProvider, setSavedImageProvider] = useState<CreatorServicesConfig['image']['provider']>();const [capabilities, setCapabilities] = useState<CreatorServicesCapabilitiesResponse>();const [modelProvider, setModelProvider] = useState<CodexProviderConfig>();const [textModelMode, setTextModelMode] = useState<TextModelMode>('codex');@@ -110,7 +110,7 @@ export function CreatorServicesSettingsView(props: {void Promise.allSettled([props.service.getConfig(),props.service.getCapabilities(),- props.modelService?.getCodexProvider()+ props.service.getCodexModelStatus?.() ?? props.modelService?.getCodexProvider()?? Promise.reject(new Error('Model provider configuration is unavailable')),props.modelService?.getCodexModels?.()?? Promise.reject(new Error('Model catalog is unavailable'))@@ -138,6 +138,7 @@ export function CreatorServicesSettingsView(props: {? modelsResult.value.models.map(model => model.model): []);setConfig(response.config);+ setSavedImageProvider(response.config.image.provider);setTextModelMode(response.config.llm.source);setCapabilities(capabilitiesResult.value);setConfiguredCredentials(new Set(response.configuredCredentials));@@ -146,7 +147,10 @@ export function CreatorServicesSettingsView(props: {if (providerResult.status === 'fulfilled') {const provider = providerResult.value;setModelProvider(provider);- setModelProviderId(inferLlmProviderId(provider.baseUrl, provider.model));+ setModelProviderId(inferLlmProviderId(+ useLegacyTextModel ? response.config.llm.baseUrl : provider.baseUrl,+ useLegacyTextModel ? response.config.llm.model : provider.model+ ));setModelBaseUrl(useLegacyTextModel ? response.config.llm.baseUrl : provider.baseUrl);setModelName(useLegacyTextModel ? response.config.llm.model : provider.model);pageIssues.resolveOperation('settings.creator-services.load-model-provider');@@ -155,7 +159,7 @@ export function CreatorServicesSettingsView(props: {setModelProviderId('custom');setModelBaseUrl(response.config.llm.baseUrl);setModelName(response.config.llm.model);- if (props.modelService !== null && props.modelService !== undefined) {+ if (props.service?.getCodexModelStatus !== undefined || props.modelService != null) {pageIssues.captureOperationFailure('settings.creator-services.load-model-provider',providerResult.reason,@@ -279,6 +283,7 @@ export function CreatorServicesSettingsView(props: {}const response = await props.service.saveConfig(nextConfig);setConfig(response.config);+ setSavedImageProvider(response.config.image.provider);setConfiguredCredentials(new Set(response.configuredCredentials));setSavedTranscriptionSelection(transcriptionSelection(response.config));pageIssues.resolveOperation('settings.creator-services.save');@@ -320,6 +325,7 @@ export function CreatorServicesSettingsView(props: {try {const response = await props.service.resetConfig();setConfig(response.config);+ setSavedImageProvider(response.config.image.provider);setConfiguredCredentials(new Set(response.configuredCredentials));setSavedTranscriptionSelection(transcriptionSelection(response.config));pageIssues.resolveOperation('settings.creator-services.reset');@@ -445,7 +451,7 @@ export function CreatorServicesSettingsView(props: {/>) : null}{activeSection === 'image' ? (- <ImageSettings config={config} update={updateConfig} configuredCredentials={configuredCredentials} service={props.service} onOpenAgentSetup={props.onOpenAgentSetup} />+ <ImageSettings config={config} update={updateConfig} configuredCredentials={configuredCredentials} service={props.service} enabled={savedImageProvider === config.image.provider} />) : null}{activeSection === 'video' ? (<VideoSettings config={config} update={updateConfig} configuredCredentials={configuredCredentials} />@@ -596,6 +602,13 @@ function TextModelSettings(props: SettingsGroupProps & {: l('文本任务需要 API Key', 'Text tasks require an API key')}</span></div>+ {props.mode === 'codex' && props.config.llm.source === 'codex' && codexAvailable ? (+ <p className="creator-services-inline-note">{l(+ '已自动启用本机 Codex,无需保存即可使用。手动更改服务后,请保存配置。',+ 'Local Codex is enabled automatically and ready without saving. Save settings after changing the service.',+ 'Lokala Codex aktiveras automatiskt och kan användas utan att spara. Spara inställningarna efter att du bytt tjänst.'+ )}</p>+ ) : null}{props.error === undefined ? null : (<p className="creator-services-inline-note is-warning" role="alert">{props.error}@@ -1032,7 +1045,7 @@ function TtsSettings(props: SettingsGroupProps) {function ImageSettings(props: SettingsGroupProps & {service: CreatorServicesSettingsService | null;- onOpenAgentSetup?(): void;+ enabled: boolean;}) {const l = useLocalizedCopy();const provider = props.config.image.provider;@@ -1064,7 +1077,7 @@ function ImageSettings(props: SettingsGroupProps & {/>{provider === 'codex-native' ? (<Suspense fallback={<div className="creator-services-inline-note" role="status">{l('正在检查 Codex 生图配置…', 'Checking Codex image configuration…', 'Kontrollerar bildinställningar för Codex…')}</div>}>- <CodexImageStatusNotice service={props.service} onOpenAgentSetup={props.onOpenAgentSetup} />+ <CodexImageStatusNotice service={props.service} enabled={props.enabled} /></Suspense>) : null}{provider === 'openai' ? <OpenAiFields id="image-openai" credential="image.openai.apiKey" configuredCredentials={props.configuredCredentials} value={props.config.image.openai} modelPlaceholder="gpt-image-1" modelSuggestions={creatorProviderOfKind('image', 'openai')?.models.map(model => model.id)} onChange={value => props.update(config => { config.image.openai = value; })} /> : null}diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.tsxindex 1a328e1b..dc8bca63 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx@@ -190,7 +190,6 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {service={props.creatorServicesService ?? null}modelService={props.codexRuntimeService ?? null}initialSection={props.initialSection}- onOpenAgentSetup={props.onOpenAgentSetup}/></Suspense></>diff --git a/apps/web/src/services/creator-services-service.test.ts b/apps/web/src/services/creator-services-service.test.tsindex f8cd25c0..7a0247d1 100644--- a/apps/web/src/services/creator-services-service.test.ts+++ b/apps/web/src/services/creator-services-service.test.ts@@ -50,6 +50,7 @@ describe('creator services service', () => {await service.resetConfig();await service.getTtsVoices('aliyun', 'qwen3-tts-flash');await service.getCodexImageStatus();+ await service.getCodexModelStatus();await service.previewTtsVoice({provider: 'aliyun',model: 'qwen3-tts-flash',@@ -65,6 +66,7 @@ describe('creator services service', () => {'/creator-services/tts/voices?provider=aliyun&model=qwen3-tts-flash');expect(get).toHaveBeenNthCalledWith(4, '/creator-services/image/codex/status');+ expect(get).toHaveBeenNthCalledWith(5, '/creator-services/model/codex/status');expect(rawRequest).toHaveBeenCalledWith('/creator-services/tts/preview', {method: 'POST',body: {diff --git a/apps/web/src/services/creator-services-service.ts b/apps/web/src/services/creator-services-service.tsindex f8e2e9d0..23d30ff4 100644--- a/apps/web/src/services/creator-services-service.ts+++ b/apps/web/src/services/creator-services-service.ts@@ -1,5 +1,6 @@import type {CodexImageStatus,+ CodexProviderConfig,CreatorServicesCapabilitiesResponse,CreatorServicesConfig,CreatorServicesConfigResponse,@@ -11,12 +12,16 @@ import type { RuntimeClient } from '../runtime/client.js';type ClientLike = Pick<RuntimeClient, 'get' | 'patch' | 'delete' | 'rawRequest'>;-export type CreatorServicesSettingsService = Omit<ReturnType<typeof createCreatorServicesService>, 'getCodexImageStatus'> & {+export type CreatorServicesSettingsService = Omit<ReturnType<typeof createCreatorServicesService>, 'getCodexImageStatus' | 'getCodexModelStatus'> & {getCodexImageStatus?: () => Promise<CodexImageStatus>;+ getCodexModelStatus?: () => Promise<CodexProviderConfig>;};export function createCreatorServicesService(client: ClientLike) {return {+ getCodexModelStatus(): Promise<CodexProviderConfig> {+ return client.get('/creator-services/model/codex/status');+ },getCodexImageStatus(): Promise<CodexImageStatus> {return client.get('/creator-services/image/codex/status');},diff --git a/packages/protocol/src/creator-services.ts b/packages/protocol/src/creator-services.tsindex 35298415..12373195 100644--- a/packages/protocol/src/creator-services.ts+++ b/packages/protocol/src/creator-services.ts@@ -1,4 +1,6 @@import { defaultVideoGenerationModels } from './media-generation.js';+import { publicErrorKindForCode, safePublicErrorMessage } from './errors.js';+import type { PublicErrorFacts } from './issues.js';export type OpenAiCompatibleConfig = {baseUrl: string;@@ -205,6 +207,31 @@ export type CreatorPreflightResponse = {checkedAt: string;};+/** Keep client-side and daemon-side preflight failures identical. */+export function creatorPreflightFailure(result: CreatorPreflightResponse): {+ code: string; message: string; publicFacts: PublicErrorFacts;+} {+ const codes: Record<string, string> = {+ 'reference-image-required': 'creator_stage_input_missing',+ llm: 'creator_llm_config_missing',+ tts: 'creator_tts_config_missing',+ 'image-provider': 'creator_image_config_missing',+ 'video-provider': 'VIDEO_GENERATION_CONFIG_REQUIRED',+ 'reference-image-capability': 'unsupported_capability',+ 'transcription-config': 'creator_transcription_config_missing',+ 'input-file': 'creator_stage_input_missing',+ 'managed-directory': 'creator_storage_failed'+ };+ 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(';'))+ ?? '启动条件检查未通过,请检查任务配置。';+ return { code, message, publicFacts: {+ kind: publicErrorKindForCode(code) ?? 'validation', upstreamMessage: message,+ ...(id === 'reference-image-required' ? { upstreamCode: 'IMAGE_REFERENCE_MISSING' } : {})+ } };+}+export type CreatorServicesCredentialField =| 'llm.apiKey'| 'transcription.openai.apiKey'diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.tsindex f2d64d99..d558f79f 100644--- a/packages/protocol/src/errors.ts+++ b/packages/protocol/src/errors.ts@@ -172,6 +172,7 @@ export function publicErrorKindForCode(code: string): PublicErrorFacts['kind'] |if (normalized === 'ECONNREFUSED') return 'connection-refused';if (normalized === 'ECONNRESET' || normalized === 'EPIPE') return 'connection-reset';if (normalized === 'ETIMEDOUT' || normalized.startsWith('UND_ERR_') && normalized.endsWith('_TIMEOUT')) return 'timeout';+ if (normalized === 'ERR_FS_FILE_TOO_LARGE' || normalized === 'EFBIG') return 'storage';if (/(?:^|_)CONFIG(?:_[A-Z]+)*_(?:REQUIRED|MISSING|INVALID|UNAVAILABLE)$/.test(normalized)) return 'configuration';if (normalized === 'UNAUTHORIZED' || /(?:^|_)(?:AUTH_FAILED|PERMISSION_DENIED|ACCESS_DENIED)$/.test(normalized)) return 'unauthorized';if (/(?:^|_)VALIDATION_FAILED$/.test(normalized) || /(?:^|_)(?:INPUT_)?INVALID$/.test(normalized)) return 'validation';@@ -192,6 +193,31 @@ export function safePublicErrorCode(value: unknown): string | undefined {: undefined;}+export function publicErrorCodeFromFailure(error: unknown): string | undefined {+ const seen = new Set<unknown>();+ for (let depth = 0; depth < 4 && error !== null && typeof error === 'object'; depth += 1) {+ if (seen.has(error)) break;+ seen.add(error);+ const code = safePublicErrorCode((error as { code?: unknown }).code);+ if (code !== undefined) return code;+ error = (error as { cause?: unknown }).cause;+ }+ return undefined;+}++export function publicErrorMessageFromFailure(error: unknown): string | undefined {+ const seen = new Set<unknown>();+ const messages: string[] = [];+ for (let depth = 0; depth < 4 && error !== null && typeof error === 'object'; depth += 1) {+ if (seen.has(error)) break;+ seen.add(error);+ const message = safePublicErrorMessage((error as { message?: unknown }).message);+ if (message !== undefined && !messages.includes(message)) messages.unshift(message);+ error = (error as { cause?: unknown }).cause;+ }+ return safePublicErrorMessage(messages.join(';'));+}+export function safePublicRequestId(value: unknown): string | undefined {return typeof value === 'string'&& /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,159}$/.test(value)diff --git a/packages/protocol/src/media-generation.ts b/packages/protocol/src/media-generation.tsindex f5750247..fc6a5b3b 100644--- a/packages/protocol/src/media-generation.ts+++ b/packages/protocol/src/media-generation.ts@@ -32,6 +32,15 @@ export type CreateImageGenerationRequest = {count: number;};+/** Detect explicit references to an existing image, rather than ordinary photo styles. */+export function imagePromptRequiresReference(prompt: string): boolean {+ const brief = prompt.replace(+ /(?:无需|不需要|不用|不要|不使用|没有)(?:再|任何)?(?:上传|提供|使用|添加)?(?:的)?(?:参考图|参考图片|图片|照片|原图)|(?:without|no|do not use)\s+(?:(?:an?|any|the)\s+)?(?:(?:reference|uploaded|attached|original)\s+)?(?:images?|photos?|pictures?)/gi,+ ''+ );+ return /(?:上传|上傳|附上|附带|所附|提供|给定|原始|输入|这张|该|這張|此|参考|參考)[^。!?\n]{0,12}(?:图片|照片|图像|圖片|相片|圖像)|(?:基于|根据|使用|编辑|修改|重绘|保留|保持)[^。!?\n]{0,8}参考图|参考图[^。!?\n]{0,8}(?:改成|转换|主体|构图)|(?:原图|原圖|上图|上圖)|\b(?:uploaded|attached|provided|input|reference|original|source|this|that)\s+(?:[\w-]+\s+){0,3}(?:image|photo|picture)s?\b/i.test(brief);+}+export type ImageGenerationAsset = {index: number;fileName: string;diff --git a/packages/protocol/test/creator-preflight.test.ts b/packages/protocol/test/creator-preflight.test.tsnew file mode 100644index 00000000..08a96687--- /dev/null+++ b/packages/protocol/test/creator-preflight.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';+import { creatorPreflightFailure, type CreatorPreflightResponse } from '../src/creator-services.js';++describe('shared preflight diagnostics', () => {+ it.each([+ ['llm', 'creator_llm_config_missing', 'configuration'],+ ['transcription-config', 'creator_transcription_config_missing', 'configuration'],+ ['reference-image-required', 'creator_stage_input_missing', 'validation'],+ ['input-file', 'creator_stage_input_missing', 'validation'],+ ['other', 'creator_preflight_blocked', 'validation']+ ])('preserves the %s blocker with an actionable reason', (id, code, kind) => {+ const result: CreatorPreflightResponse = { templateId: 'video-translation', templateVersion: 2,+ stageId: 'subtitle', executionMode: 'local', canStart: false, ready: [], warning: [],+ blocked: [{ id, title: '启动条件', message: '请配置服务或输入。 token=private', executionMode: 'local', repair: { label: '配置' } }], checkedAt: '' };+ expect(creatorPreflightFailure(result)).toMatchObject({ code, message: expect.stringContaining('请配置服务或输入'), publicFacts: { kind, upstreamMessage: expect.stringContaining('请配置服务或输入') } });+ expect(JSON.stringify(creatorPreflightFailure(result))).not.toContain('private');+ });+});diff --git a/packages/protocol/test/error-facts.test.ts b/packages/protocol/test/error-facts.test.tsindex 1945d0df..1d00da71 100644--- a/packages/protocol/test/error-facts.test.ts+++ b/packages/protocol/test/error-facts.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { publicErrorKindForCode, safePublicErrorCode, safePublicErrorMessage, safePublicRequestId } from '../src/errors.js';+import { publicErrorCodeFromFailure, publicErrorMessageFromFailure, publicErrorKindForCode, safePublicErrorCode, safePublicErrorMessage, safePublicRequestId } from '../src/errors.js';import { isPublicErrorFacts, sanitizePublicErrorFacts } from '../src/issues.js';describe('public error kind for business code', () => {@@ -13,12 +13,26 @@ describe('public error kind for business code', () => {['IMAGE_GENERATION_STORAGE_FAILED', 'storage'],['krillin_auth_failed', 'unauthorized'],['ENOTFOUND', 'dns'],+ ['ERR_FS_FILE_TOO_LARGE', 'storage'],['creator_provider_request_failed', undefined]])('classifies %s conservatively', (code, expected) => {expect(publicErrorKindForCode(code)).toBe(expected);});});+it('preserves a nested filesystem code and reason with bounded, sanitized cause traversal', () => {+ const bottom = Object.assign(new Error('File size (4014655674) is greater than 2 GiB token=private'), { code: 'ERR_FS_FILE_TOO_LARGE' });+ const error = new Error('Output collection failed', { cause: bottom });+ expect(publicErrorCodeFromFailure(error)).toBe('ERR_FS_FILE_TOO_LARGE');+ expect(publicErrorMessageFromFailure(error)).toContain('File size (4014655674)');+ expect(publicErrorMessageFromFailure(error)).not.toContain('private');+ expect(publicErrorCodeFromFailure({ code: 'sk-private-secret' })).toBeUndefined();+ const cycle: { message: string; cause?: unknown } = { message: 'Cyclic failure' };+ cycle.cause = cycle;+ expect(publicErrorCodeFromFailure(cycle)).toBeUndefined();+ expect(publicErrorMessageFromFailure(cycle)).toBe('Cyclic failure');+});+it('rejects token-like business codes before Agent output', () => {expect(safePublicErrorCode('IMAGE_GENERATION_UPSTREAM_ERROR')).toBe('IMAGE_GENERATION_UPSTREAM_ERROR');expect(safePublicErrorCode('sk-private-long-secret-value')).toBeUndefined();diff --git a/packages/protocol/test/image-reference.test.ts b/packages/protocol/test/image-reference.test.tsnew file mode 100644index 00000000..be571410--- /dev/null+++ b/packages/protocol/test/image-reference.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';+import { imagePromptRequiresReference } from '../src/media-generation.js';++describe('explicit image reference requirements', () => {+ it.each([+ '以上传的人物照片为唯一主体与场景参考,生成复古海报。',+ '参考上传图片的主体和构图生成新画面',+ '保持原图的人物身份和服装',+ '将参考图改成水彩画',+ '基于参考图生成海报',+ 'Preserve the identity in the uploaded person photo.',+ 'Edit the attached image into a poster.',+ 'Use this photo as the reference.'+ ])('requires a reference for %s', prompt => {+ expect(imagePromptRequiresReference(prompt)).toBe(true);+ });++ it.each([+ '', '生成一张猫的真实摄影照片', '生成一张角色设计参考图',+ '无需上传图片,生成一张风景照', '不需要参考图,画一只橘猫',+ 'Create a realistic photo of a studio.', 'Generate a cat without any reference image.'+ ])('allows text-only generation for %s', prompt => {+ expect(imagePromptRequiresReference(prompt)).toBe(false);+ });+});