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
feat: improve creator workflow and media processing
Leggett54fbcbd4b8e7
diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.tsindex 1b192187..bf7b20aa 100644--- a/apps/daemon/src/api/routes.creator.ts+++ b/apps/daemon/src/api/routes.creator.ts@@ -92,6 +92,7 @@ import { readCodexImageConfiguration } from '../image-generation/codex-runtime.jimport type { CodexNativeImageRuntime } from '../image-generation/provider.js';import type { CreatorIssueService } from '../creator/issues.js';import { registerCreatorThumbnailRoutes } from './routes.creator-thumbnail.js';+import { GatewayError } from '../gateway/client.js';export async function registerCreatorRoutes(server: FastifyInstance,@@ -1575,6 +1576,13 @@ function sendCreatorError(reply: FastifyReply, error: unknown, context?: Creator...(error.latestRevision === undefined ? {} : { latestRevision: error.latestRevision })}));}+ if (error instanceof GatewayError && error.code === 'auth_required') {+ return reply.code(401).send(response(+ 'GATEWAY_AUTH_REQUIRED',+ 'OpenCreator sign-in has expired. Sign in again before retrying.',+ undefined+ ));+ }if (error instanceof ZodError || error instanceof TypeError) {return reply.code(400).send(response('VALIDATION_FAILED', error.message));}diff --git a/apps/daemon/src/creator/download/executor.ts b/apps/daemon/src/creator/download/executor.tsindex 637e2142..5ea9ba4c 100644--- a/apps/daemon/src/creator/download/executor.ts+++ b/apps/daemon/src/creator/download/executor.ts@@ -283,6 +283,7 @@ async function downloadSelectedOption(status: 'succeeded',phase: 'completed',percent: 100,+ phasePercent: 100,message: option.mediaType === 'audio'? 'Audio downloaded to the project': 'Video downloaded to the project'@@ -422,6 +423,7 @@ async function preparePreviewSource(progress: {phase: 'completed',percent: 100,+ phasePercent: 100,message: 'Source video is ready; existing subtitles are preserved'}};@@ -497,7 +499,7 @@ async function downloadPlaybackSource(stage.reportProgress({status: 'running',phase: 'validating_output',- percent: preview ? null : 97,+ percent: 97,message: preview ? 'Checking the video for subtitle preview' : 'Checking the YouTube source'});const output = await normalizeVideoForPlayback(@@ -519,6 +521,7 @@ async function downloadPlaybackSource(status: 'succeeded',phase: 'completed',percent: 100,+ phasePercent: 100,message: preview ? 'Source video is ready; existing subtitles are preserved' : 'YouTube source downloaded'};stage.reportProgress(progress);@@ -551,6 +554,16 @@ async function downloadPlaybackSource(}function createPreviewProgressReporter(stage: CreatorExecutorInput): (line: string) => void {+ type PreviewResource = {+ bytes: number;+ total: number | null;+ percent: number | null;+ };++ const resources = new Map<string, PreviewResource>();+ let anonymousResourceKey = 'anonymous:0';+ let reportedPercent = 2;+return line => {const marker = line.indexOf('oc-preview:');if (marker >= 0) {@@ -564,22 +577,66 @@ function createPreviewProgressReporter(stage: CreatorExecutorInput): (line: stri: typeof data.total_bytes_estimate === 'number' && Number.isFinite(data.total_bytes_estimate) && data.total_bytes_estimate > 0? data.total_bytes_estimate: null;+ const identifiedKey = previewResourceKey(data);+ let resourceKey = identifiedKey ?? anonymousResourceKey;+ const previous = resources.get(resourceKey);+ if (identifiedKey === null+ && previous !== undefined+ && previous.percent !== null+ && previous.percent >= 99+ && bytes < previous.bytes) {+ resourceKey = `anonymous:${resources.size}`;+ anonymousResourceKey = resourceKey;+ }+ const existing = resources.get(resourceKey);+ const resource: PreviewResource = {+ bytes: Math.max(existing?.bytes ?? 0, bytes),+ total: total ?? existing?.total ?? null,+ percent: total === null ? existing?.percent ?? null : Math.min(100, Math.max(0, bytes / total * 100))+ };+ resources.set(resourceKey, resource);+ const downloadedBytes = [...resources.values()]+ .reduce((sum, current) => sum + current.bytes, 0);+ const knownTotals = [...resources.values()].map(current => current.total);+ const totalBytes = knownTotals.every(current => current !== null)+ ? knownTotals.reduce((sum, current) => sum + (current ?? 0), 0)+ : null;+ const rawPercent = totalBytes === null || totalBytes <= 0+ ? null+ : Math.min(100, Math.max(0, downloadedBytes / totalBytes * 100));+ // Keep a small amount of headroom for a later audio resource or the+ // merge step, while allowing a single resource to reflect its bytes.+ const combinedPercent = rawPercent === null+ ? null+ : Math.min(95, rawPercent);+ if (combinedPercent !== null) reportedPercent = Math.max(reportedPercent, Math.round(combinedPercent));stage.reportProgress({phase: 'downloading',- percent: total === null ? null : Math.min(100, Math.max(0, bytes / total * 100)),+ percent: combinedPercent === null+ ? reportedPercent > 2 ? reportedPercent : null+ : reportedPercent,message: 'Downloading the current original-video resource; existing subtitles are preserved',- downloadedBytes: bytes,- totalBytes: total+ downloadedBytes,+ totalBytes});} catch {}return;}if (/\[(?:Merger|VideoRemuxer)\]/.test(line)) {- stage.reportProgress({ phase: 'merging_media', percent: null, message: 'Merging video and audio for subtitle preview' });+ reportedPercent = Math.max(reportedPercent, 96);+ stage.reportProgress({ phase: 'merging_media', percent: reportedPercent, message: 'Merging video and audio for subtitle preview' });}};}+function previewResourceKey(data: Record<string, unknown>): string | null {+ for (const field of ['format_id', 'format', 'filename', 'tmpfilename']) {+ const value = data[field];+ if (typeof value === 'string' && value.trim()) return `resource:${value}`;+ }+ return null;+}+async function downloadLegacy(input: DownloadExecutorOptions,url: string,@@ -880,10 +937,12 @@ async function normalizeVideoForPlayback();}+ const conversionDuration = duration ?? await readMediaDuration(path, input, stage);stage.reportProgress({status: 'running',phase: 'normalizing_media',- percent: isPreviewStage(stage) ? null : 98,+ percent: 98,+ phasePercent: 0,message: 'Converting video for local playback'});const outputPath = playbackOutputPath(path);@@ -923,7 +982,7 @@ async function normalizeVideoForPlayback(input.ffmpegPath,[...(input.ffmpegPrefixArgs ?? []), ...args],stage,- line => reportPlaybackConversionProgress(stage, line, duration)+ line => reportPlaybackConversionProgress(stage, line, conversionDuration));await validateMediaFile(outputPath,@@ -955,7 +1014,7 @@ function reportPlaybackConversionProgress(line: string,duration: number | null): void {- if (duration === null || duration <= 0 || isPreviewStage(stage)) return;+ if (duration === null || duration <= 0) return;const match = line.match(/^out_time=(\d+):(\d+):([\d.]+)$/);if (match === null) return;const elapsed = (@@ -964,14 +1023,39 @@ function reportPlaybackConversionProgress(+ Number(match[3]));if (!Number.isFinite(elapsed)) return;+ const phasePercent = Math.min(100, Math.max(0, Math.round(elapsed / duration * 100)));stage.reportProgress({status: 'running',phase: 'normalizing_media',- percent: Math.min(99, 98 + Math.max(0, elapsed / duration)),+ percent: Math.min(99, Math.max(98, Math.round(98 + elapsed / duration))),+ phasePercent,message: 'Converting video for local playback'});}+async function readMediaDuration(+ path: string,+ input: DownloadExecutorOptions,+ stage: CreatorExecutorInput+): Promise<number | null> {+ try {+ const stdout = await run(input.ffprobePath, [+ ...(input.ffprobePrefixArgs ?? []),+ '-v',+ 'error',+ '-show_entries',+ 'format=duration',+ '-of',+ 'default=noprint_wrappers=1:nokey=1',+ path+ ], stage);+ const duration = Number(stdout.trim());+ return Number.isFinite(duration) && duration > 0 ? duration : null;+ } catch {+ return null;+ }+}+async function readPlaybackCodecs(path: string,input: DownloadExecutorOptions,@@ -1055,7 +1139,7 @@ function createDownloadProgressReporter(let completedParts = 0;let previousPartPercent = 0;let reportedPercent = typeof stage.stageRun.progress.percent === 'number'- ? Math.min(95, Math.max(2, stage.stageRun.progress.percent)) : 2;+ ? Math.min(95, Math.max(2, Math.round(stage.stageRun.progress.percent))) : 2;return line => {const match = line.match(/\[download\]\s+([\d.]+)%/);if (match !== null) {@@ -1085,7 +1169,7 @@ function createDownloadProgressReporter() * 93;reportedPercent = Math.max(reportedPercent,- Math.min(95, combinedPercent)+ Math.min(95, Math.round(combinedPercent)));stage.reportProgress({status: 'running',diff --git a/apps/daemon/src/creator/krillin/cli-runner.ts b/apps/daemon/src/creator/krillin/cli-runner.tsindex c2509949..ae126d65 100644--- a/apps/daemon/src/creator/krillin/cli-runner.ts+++ b/apps/daemon/src/creator/krillin/cli-runner.ts@@ -200,8 +200,15 @@ export async function runKrillinCli(input: RunKrillinCliInput): Promise<KrillinRif (cues.length > 0) {const snapshot = source?.metadata.settingsSnapshot;const position = snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && snapshot.subtitlePosition === 'bottom' ? 'bottom' : 'top';+ const sourceVideo = input.stage.inputArtifacts.find(artifact => artifact.kind === 'source_video');+ const horizontal = args[0] === 'render-horizontal';+ const width = typeof sourceVideo?.metadata.width === 'number' && Number.isInteger(sourceVideo.metadata.width) && sourceVideo.metadata.width >= 32+ ? sourceVideo.metadata.width : horizontal ? 1920 : 1080;+ const height = typeof sourceVideo?.metadata.height === 'number' && Number.isInteger(sourceVideo.metadata.height) && sourceVideo.metadata.height >= 32+ ? sourceVideo.metadata.height : horizontal ? 1080 : 1920;const documentPath = join(configDir, 'subtitle-document.json');await writeFile(documentPath, JSON.stringify({+ width, height, horizontal,bilingual: booleanOption(input.options, 'bilingual', false), subtitlePosition: booleanOption(input.options, 'bilingualTop', true) ? 'top' : 'bottom',majorTitle: args[0] === 'render-vertical' ? stringOption(input.options, 'verticalTitle') : undefined,minorTitle: args[0] === 'render-vertical' ? stringOption(input.options, 'verticalSubtitle') : undefined,@@ -439,6 +446,7 @@ function executeCli(input: {signal: AbortSignal;}): Promise<KrillinCliResponse> {return new Promise((resolvePromise, reject) => {+ const reportProgress = createMonotonicProgressReporter(input.reportProgress);const child = spawnCreatorProcess(input.executable, input.args, {cwd: input.cwd,env: createKrillinCliEnvironment(@@ -459,7 +467,7 @@ function executeCli(input: {stdout = boundedAppend(stdout, value);pendingStdoutLine = consumeProgressLines(pendingStdoutLine + value,- input.reportProgress+ reportProgress);});child.stderr?.on('data', chunk => { stderr = boundedAppend(stderr, String(chunk)); });@@ -469,7 +477,7 @@ function executeCli(input: {reject(new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled'));return;}- reportProgressLine(pendingStdoutLine, input.reportProgress);+ reportProgressLine(pendingStdoutLine, reportProgress);const response = parseResponse(stdout);if (response === undefined) {reject(new KrillinCliError(@@ -492,6 +500,30 @@ function executeCli(input: {});}+function createMonotonicProgressReporter(+ reportProgress: (progress: Record<string, CreatorJson>) => void+): (progress: Record<string, CreatorJson>) => void {+ let lastPercent = 0;+ return progress => {+ const incomingPercent = progress.percent;+ if (typeof incomingPercent !== 'number' || !Number.isFinite(incomingPercent)) {+ reportProgress(progress);+ return;+ }+ const percent = Math.max(lastPercent, Math.max(0, Math.min(99, Math.round(incomingPercent))));+ lastPercent = percent;+ const legacyPayload = progress.krillinEventPayload;+ const nextLegacyPayload = legacyPayload && typeof legacyPayload === 'object' && !Array.isArray(legacyPayload)+ ? { ...legacyPayload, percent }+ : undefined;+ reportProgress({+ ...progress,+ percent,+ ...(nextLegacyPayload === undefined ? {} : { krillinEventPayload: nextLegacyPayload })+ });+ };+}+async function collectArtifacts(input: RunKrillinCliInput,response: KrillinCliResponsediff --git a/apps/daemon/src/creator/krillin/config-bridge.ts b/apps/daemon/src/creator/krillin/config-bridge.tsindex 80dbe096..083b62bd 100644--- a/apps/daemon/src/creator/krillin/config-bridge.ts+++ b/apps/daemon/src/creator/krillin/config-bridge.ts@@ -10,7 +10,14 @@ export function createKrillinConfigToml(): string {const llm = llmOverride ?? config.llm;const document = compact({- app: { proxy: officialTranscriptionModel ? '' : config.proxy },+ // Keep media access on the user's configured proxy even when the+ // transcription API is routed through the official gateway. The runtime+ // uses a separate proxy for its YouTube/yt-dlp requests so local gateway+ // calls do not have to go through the media proxy.+ app: {+ proxy: officialTranscriptionModel ? '' : config.proxy,+ youtube_proxy: config.proxy+ },llm: {base_url: llm.baseUrl,api_key: llm.apiKey,diff --git a/apps/daemon/src/creator/krillin/subtitle-render.ts b/apps/daemon/src/creator/krillin/subtitle-render.tsindex 42532e39..968efcf9 100644--- a/apps/daemon/src/creator/krillin/subtitle-render.ts+++ b/apps/daemon/src/creator/krillin/subtitle-render.ts@@ -37,10 +37,18 @@ export function createSubtitleRenderService(input: {const output = join(workdir, 'subtitles.ass');await writeFile(document, JSON.stringify(request), { mode: 0o600 });await writeFile(stylePath, JSON.stringify(style), { mode: 0o600 });- await execute(resolveInside(input.resourceRoot, cli.path), ['compile-subtitles', '--input', document, '--output', output, '--subtitle-style-file', stylePath], {- env: { ...process.env, KRILLINAI_RESOURCE_ROOT: input.resourceRoot },- timeout: 15_000, maxBuffer: 1024 * 1024, windowsHide: true- });+ try {+ await execute(resolveInside(input.resourceRoot, cli.path), ['compile-subtitles', '--input', document, '--output', output, '--subtitle-style-file', stylePath], {+ env: { ...process.env, KRILLINAI_RESOURCE_ROOT: input.resourceRoot },+ timeout: 15_000, maxBuffer: 1024 * 1024, windowsHide: true+ });+ } catch (cause) {+ const stdout = (cause as { stdout?: string }).stdout;+ let response: { error?: { message?: string } } | undefined;+ try { response = JSON.parse(stdout?.trim().split('\n').at(-1) ?? ''); } catch { /* Keep process failures without JSON diagnostics. */ }+ if (response?.error?.message) throw new Error(response.error.message);+ throw cause;+ }const ass = await readFile(output, 'utf8');// Load only families selected by the compiled track, including explicit// script fallbacks. The native renderer reads the same TTF bytes.diff --git a/apps/daemon/src/creator/public-error-facts.ts b/apps/daemon/src/creator/public-error-facts.tsindex ceb2de04..f60b1d68 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 ERROR_KINDS: Record<string, PublicErrorFacts['kind']> = {+ auth_required: 'unauthorized',+ services_not_ready: 'configuration',ERR_FS_FILE_TOO_LARGE: 'storage',EFBIG: 'storage',ENOTFOUND: 'dns',diff --git a/apps/daemon/src/creator/stage-runner.ts b/apps/daemon/src/creator/stage-runner.tsindex 7f5ac180..33f612e3 100644--- a/apps/daemon/src/creator/stage-runner.ts+++ b/apps/daemon/src/creator/stage-runner.ts@@ -548,11 +548,12 @@ export function createCreatorStageRunner(input: {): CreatorStageRun {const current = input.repository.getStageRun(update.id);const download = current?.stageId === 'download' && current.executor === 'download';+ const progress = mergeStageProgress(current, update.progress) ?? (download ? current?.progress : undefined);input.repository.updateStageRun({...update,- ...(update.progress === undefined && !download+ ...(progress === undefined && !download? {}- : { progress: { ...(current?.progress ?? {}), ...update.progress,+ : { progress: { ...(progress ?? {}),...(download ? { downloadProgressSequence: (Number(current.progress.downloadProgressSequence) || 0) + 1 } : {}) } })});const stage = input.repository.getStageRun(update.id);@@ -563,6 +564,33 @@ export function createCreatorStageRunner(input: {return stage;}+ function mergeStageProgress(+ current: CreatorStageRun | undefined,+ incoming: Record<string, CreatorJson> | undefined+ ): Record<string, CreatorJson> | undefined {+ if (incoming === undefined) return undefined;+ const progress = { ...(current?.progress ?? {}), ...incoming };+ const currentPercent = current?.progress.percent;+ const incomingPercent = incoming.percent;+ if (typeof currentPercent === 'number' && Number.isFinite(currentPercent)+ && (incomingPercent === null+ || (typeof incomingPercent === 'number' && Number.isFinite(incomingPercent)+ && incomingPercent < currentPercent))) {+ progress.percent = currentPercent;+ }+ const currentPhasePercent = current?.progress.phasePercent;+ const incomingPhasePercent = incoming.phasePercent;+ if (current?.progress.phase === 'normalizing_media'+ && incoming.phase === 'normalizing_media'+ && typeof currentPhasePercent === 'number' && Number.isFinite(currentPhasePercent)+ && (incomingPhasePercent === null+ || (typeof incomingPhasePercent === 'number' && Number.isFinite(incomingPhasePercent)+ && incomingPhasePercent < currentPhasePercent))) {+ progress.phasePercent = currentPhasePercent;+ }+ return progress;+ }+function finishStageIssueResolution(jobId: string,stageRunId: string,diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.tsindex 59ea58b0..904c7bc0 100644--- a/apps/daemon/src/gateway/account-service.ts+++ b/apps/daemon/src/gateway/account-service.ts@@ -95,6 +95,22 @@ export function createGatewayAccountService(input: {}function assertIdle() { if (localUses > 0 || input.hasActiveTasks()) throw new GatewayError('active_tasks', 409); }function assertSignedIn() { if (!credentials || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401); return credentials; }+ function sameAccount(left: GatewayCredentials, right: GatewayCredentials) {+ return !!left.account?.id && !!right.account?.id && left.account.id === right.account.id;+ }+ function persistedSessionIsNewer(current: GatewayCredentials, persisted: GatewayCredentials) {+ if (!sameAccount(current, persisted) || persisted.refreshToken === current.refreshToken) return false;+ const currentExpiry = Date.parse(current.accessExpiresAt);+ const persistedExpiry = Date.parse(persisted.accessExpiresAt);+ return !Number.isFinite(currentExpiry) || !Number.isFinite(persistedExpiry) || persistedExpiry >= currentExpiry;+ }+ async function adoptPersistedSession(current: GatewayCredentials) {+ const persisted = await store.readCredentials().catch(() => undefined);+ if (!persisted || !persistedSessionIsNewer(current, persisted)) return current;+ credentials = { ...current, ...persisted };+ state.account = credentials.account ?? state.account;+ return credentials;+ }function usesCachedModelKey() { return credentials?.modelUsePolicy === cachedModelUsePolicy && isDirectTransport(credentials.transport) && credentials.keyRotation === false; }function restoreModelAccessError(code: NonNullable<GatewayCredentials['modelAccessError']>) {if (code === 'auth_required') state = { ...state, authState: 'expired', activationState: 'inactive', bindingVersion: null, activationError: null };@@ -251,23 +267,30 @@ export function createGatewayAccountService(input: {async function refresh() {if (refreshWork) return refreshWork;refreshWork = (async () => {- const original = assertSignedIn(); const expected = generation;+ let original = assertSignedIn(); const expected = generation;if (Date.parse(original.accessExpiresAt) > Date.now() + 60_000) return;- try {- const tokens = await input.client.refresh(original.refreshToken);- if (closing || accessPaused || generation !== expected || credentials?.refreshToken !== original.refreshToken || state.authState !== 'signed_in') return;- // 同一登录会话内只更新令牌,保留并发同步的模型凭据。- credentials = { ...assertSignedIn(), ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };- await store.writeCredentials(credentials);- } catch (error) {- if (await blockConfirmedModelAccess(error, expected, original.account?.id)) throw error;- if (!closing && !accessPaused && error instanceof GatewayError && error.status === 401 && generation === expected && credentials?.refreshToken === original.refreshToken && state.authState === 'signed_in') {- state = { ...state, authState: 'expired', activationState: 'inactive', bindingVersion: null, activationError: null };- runtimeTextModel = undefined; accessController?.abort();- clearInterval(usageTimer); usageTimer = undefined;- await input.closeRuntime();+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ const tokens = await input.client.refresh(original.refreshToken);+ if (closing || accessPaused || generation !== expected || credentials?.refreshToken !== original.refreshToken || state.authState !== 'signed_in') return;+ // 同一登录会话内只更新令牌,保留并发同步的模型凭据。+ credentials = { ...assertSignedIn(), ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };+ await store.writeCredentials(credentials);+ return;+ } catch (error) {+ if (await blockConfirmedModelAccess(error, expected, original.account?.id)) throw error;+ if (error instanceof GatewayError && error.status === 401 && attempt === 0) {+ const latest = await adoptPersistedSession(original);+ if (latest.refreshToken !== original.refreshToken) { original = latest; continue; }+ }+ if (!closing && !accessPaused && error instanceof GatewayError && error.status === 401 && generation === expected && credentials?.refreshToken === original.refreshToken && state.authState === 'signed_in') {+ state = { ...state, authState: 'expired', activationState: 'inactive', bindingVersion: null, activationError: null };+ runtimeTextModel = undefined; accessController?.abort();+ clearInterval(usageTimer); usageTimer = undefined;+ await input.closeRuntime();+ }+ throw error;}- throw error;}})();try { await refreshWork; } finally { refreshWork = undefined; }diff --git a/apps/daemon/src/gateway/creator-service-source.ts b/apps/daemon/src/gateway/creator-service-source.tsindex 51af6ed2..4653bbd0 100644--- a/apps/daemon/src/gateway/creator-service-source.ts+++ b/apps/daemon/src/gateway/creator-service-source.ts@@ -51,7 +51,8 @@ export function createGatewayCreatorSource(input: {function snapshot(templateId?: string): CreatorServiceBinding {const state = input.account.peekState();if (state.source === 'manual') return { source: 'manual' };- if (state.authState !== 'signed_in' || state.activationState !== 'ready' || !state.account || !state.bindingVersion) throw new GatewayError('services_not_ready');+ if (state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);+ if (state.activationState !== 'ready' || !state.account || !state.bindingVersion) throw new GatewayError('services_not_ready');const models: Record<string, string> = {};const caps: Record<string, string[]> = {};for (const model of state.models) {@@ -76,7 +77,8 @@ export function createGatewayCreatorSource(input: {}function assertSnapshot(value: CreatorServiceBinding, recovery = false) {const state = input.account.peekState();- if (value.source === 'gateway' && (state.authState !== 'signed_in' || (!recovery && state.activationState !== 'ready'))) throw new GatewayError('services_not_ready');+ if (value.source === 'gateway' && state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);+ if (value.source === 'gateway' && (!recovery && state.activationState !== 'ready')) throw new GatewayError('services_not_ready');if (value.source !== state.source || (value.source === 'gateway' && value.accountId !== state.account?.id)) throw new GatewayError('task_source_mismatch', 409);if (value.source === 'gateway' && state.supplier) {const supplier = value.supplier ?? (value.bindingVersion.startsWith(`${value.accountId}:88api:`) ? '88api'diff --git a/apps/daemon/src/gateway/runtime-source.ts b/apps/daemon/src/gateway/runtime-source.tsindex 23444995..eb5832a6 100644--- a/apps/daemon/src/gateway/runtime-source.ts+++ b/apps/daemon/src/gateway/runtime-source.ts@@ -8,7 +8,8 @@ export function createRuntimeSource(manual: AppServerRuntimeManager, readState:const state = readState();if (state.source === 'manual') return manual;const official = readOfficial();- if (state.authState !== 'signed_in' || state.activationState !== 'ready' || !official) throw new GatewayError('services_not_ready');+ if (state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);+ if (state.activationState !== 'ready' || !official) throw new GatewayError('services_not_ready');return official;}function turn(input: AppServerRuntimeTurnInput): AppServerRuntimeExecution {diff --git a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts b/apps/daemon/test/integration/creator-krillin-cli-runner.test.tsindex 6a619063..95648a5c 100644--- a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts+++ b/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts@@ -408,6 +408,10 @@ describe('KrillinAI CLI runner', () => {providerStatus: 'running',message: 'Platform captions could not be processed. Switching to audio transcription.'}));+ const runningPercents = progress+ .filter(value => value.providerStatus === 'running' && typeof value.percent === 'number')+ .map(value => value.percent as number);+ expect(runningPercents).toEqual([...runningPercents].sort((left, right) => left - right));expect(progress.at(-1)).toMatchObject({krillinMode: 'cli',providerStatus: 'succeeded',diff --git a/apps/daemon/test/unit/creator-download-executor.test.ts b/apps/daemon/test/unit/creator-download-executor.test.tsindex 24d31166..f44b7cd2 100644--- a/apps/daemon/test/unit/creator-download-executor.test.ts+++ b/apps/daemon/test/unit/creator-download-executor.test.ts@@ -191,8 +191,76 @@ describe('creator download executor', () => {metadata: expect.objectContaining({ settingsSnapshot: expect.objectContaining({ sourceUrl }), playbackCompatible: true })})]);expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'downloading', percent: 42, downloadedBytes: 42, totalBytes: 100 }));- expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'downloading', percent: null, downloadedBytes: 10, totalBytes: null }));- expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'merging_media', percent: null }));+ expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'downloading', percent: 42, downloadedBytes: 42, totalBytes: 100 }));+ expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'merging_media', percent: 96 }));+ });++ it('keeps preview progress monotonic when yt-dlp switches from video to audio', async () => {+ const executor = createDownloadExecutor(await fakeBinaries({+ previewProgressEvents: [+ { downloaded_bytes: 100, total_bytes: 100, filename: 'video.mp4' },+ { downloaded_bytes: 25, total_bytes: 100, filename: 'audio.m4a' }+ ]+ }));+ const workdir = join(tempDir, 'preview-multi-resource');+ await mkdir(workdir);+ const reportProgress = vi.fn();+ await executor.run(previewInput({+ workdir,+ sourceUrl: 'https://www.youtube.com/watch?v=demo',+ reportProgress+ }));++ const progress = reportProgress.mock.calls+ .map(([value]) => value as { phase?: string; percent?: number | null; downloadedBytes?: number; totalBytes?: number | null })+ .filter(value => value.phase === 'downloading');+ expect(progress).toEqual([+ expect.objectContaining({ percent: 95, downloadedBytes: 100, totalBytes: 100 }),+ expect.objectContaining({ percent: 95, downloadedBytes: 125, totalBytes: 200 })+ ]);+ expect(progress[1]!.percent).toBeGreaterThanOrEqual(progress[0]!.percent!);+ });++ it('reports the measured ratio for a single preview resource', async () => {+ const downloadedBytes = 39.4 * 1024 ** 2;+ const totalBytes = 44.2 * 1024 ** 2;+ const executor = createDownloadExecutor(await fakeBinaries({+ previewProgressEvents: [{ downloaded_bytes: downloadedBytes, total_bytes: totalBytes, filename: 'video.mp4' }]+ }));+ const workdir = join(tempDir, 'preview-single-resource');+ await mkdir(workdir);+ const reportProgress = vi.fn();+ await executor.run(previewInput({+ workdir,+ sourceUrl: 'https://www.youtube.com/watch?v=demo',+ reportProgress+ }));++ const progress = reportProgress.mock.calls+ .map(([value]) => value as { phase?: string; percent?: number | null; downloadedBytes?: number; totalBytes?: number | null })+ .filter(value => value.phase === 'downloading');+ expect(progress).toEqual([+ expect.objectContaining({ percent: 89, downloadedBytes, totalBytes })+ ]);+ });++ it('reports measured progress while converting a preview for local playback', async () => {+ const executor = createDownloadExecutor(await fakeBinaries({ videoCodec: 'vp9' }));+ const workdir = join(tempDir, 'preview-conversion');+ await mkdir(workdir);+ const reportProgress = vi.fn();+ await executor.run(previewInput({+ workdir,+ sourceUrl: 'https://www.youtube.com/watch?v=demo',+ reportProgress+ }));++ const progress = reportProgress.mock.calls+ .map(([value]) => value as { phase?: string; percent?: number | null; phasePercent?: number | null })+ .filter(value => value.phase === 'normalizing_media')+ expect(progress.map(value => value.percent)).toEqual([98, 99]);+ expect(progress.map(value => value.phasePercent)).toEqual([0, 50]);+ expect(progress.every(value => Number.isInteger(value.percent) && Number.isInteger(value.phasePercent))).toBe(true);});it.each(['matching', 'different-part', 'missing', 'invalid'])('handles %s preview cache without mixing Bilibili parts', async cache => {@@ -999,7 +1067,7 @@ describe('creator download executor', () => {expect(downloadPercents).toEqual([...downloadPercents].sort((left, right) => left - right));- expect(downloadPercents[1]).toBeCloseTo(79.5, 1);+ expect(downloadPercents).toEqual([35, 80, 81]);expect(downloadPercents.at(-1)).toBeGreaterThan(downloadPercents[1]!);expect(reportProgress.mock.calls.map(([progress]) => progress)@@ -1102,7 +1170,8 @@ describe('creator download executor', () => {}));expect(reportProgress).toHaveBeenCalledWith(expect.objectContaining({phase: 'normalizing_media',- percent: 98.5+ percent: 99,+ phasePercent: 50}));}, 20_000);@@ -1676,6 +1745,7 @@ async function fakeBinaries(input?: {splitOutputUtf8?: boolean;subtitleContent?: string | null;holdDownload?: boolean;+ previewProgressEvents?: Array<Record<string, number | string | null>>;}): Promise<{configStore: {read(): Promise<ReturnType<typeof createDefaultCreatorServicesConfig>>;@@ -1698,6 +1768,7 @@ async function fakeBinaries(input?: {import { writeFileSync, readFileSync, existsSync } from 'node:fs';import { join } from 'node:path';const args = process.argv.slice(2);+const previewProgressEvents = ${JSON.stringify(input?.previewProgressEvents ?? null)};writeFileSync(join(process.cwd(), 'args.json'), JSON.stringify(args));writeFileSync(join(process.cwd(), 'runtime-env.json'), JSON.stringify({sslCertificateFile: process.env.SSL_CERT_FILE ?? null@@ -1740,8 +1811,11 @@ if (${input?.holdDownload === true}) {writeFileSync(output, audio ? 'download-audio' : 'download-video');if (args.includes('--progress')) {if (args.includes('--progress-template')) {- process.stderr.write('oc-preview:{"downloaded_bytes":42,"total_bytes":100}\\n');- process.stderr.write('oc-preview:{"downloaded_bytes":10}\\n');+ const events = previewProgressEvents ?? [+ { downloaded_bytes: 42, total_bytes: 100 },+ { downloaded_bytes: 10 }+ ];+ for (const event of events) process.stderr.write('oc-preview:' + JSON.stringify(event) + '\\n');}process.stderr.write('[download] 42.0% of 100B at 2.50MiB/s ETA 00:01\\n');if (!audio) {@@ -1769,6 +1843,11 @@ copyFileSync(args[inputIndex + 1], args.at(-1));process.stderr.write('out_time=00:00:06.000000\\n');`);await writeExecutable(ffprobeScriptPath, `#!/usr/bin/env node+const args = process.argv.slice(2);+if (args.includes('format=duration')) {+ process.stdout.write('12\\n');+ process.exit(0);+}const path = process.argv.at(-1) ?? '';const audio = path.endsWith('.mp3');const compatible = path.endsWith('.playable.mp4');diff --git a/apps/daemon/test/unit/creator-runtime-advanced.test.ts b/apps/daemon/test/unit/creator-runtime-advanced.test.tsindex 52af0723..ac9a1140 100644--- a/apps/daemon/test/unit/creator-runtime-advanced.test.ts+++ b/apps/daemon/test/unit/creator-runtime-advanced.test.ts@@ -90,6 +90,35 @@ describe('creator runtime advanced contracts', () => {await runner.close();db.close();});+ it('keeps the latest stage percent when a subtitle phase reports a lower reset value', async () => {+ const { db, repository, service, templates } = setup();+ const runner = createCreatorStageRunner({+ repository,+ templates,+ workRoot: join(tempDir, 'work'),+ executors: [{+ id: 'krillinai',+ async run({ reportProgress }) {+ reportProgress({ phase: 'preparing_source', percent: 25 });+ reportProgress({ phase: 'reading_platform_captions', percent: 5 });+ throw new Error('caption request failed');+ }+ }]+ });+ try {+ const job = service.createJob({+ projectId: 'p1',+ templateId: 'video-translation',+ state: { sourceType: 'url', sourceUrl: 'https://youtube.com/watch?v=progress-reset', sourceLanguage: 'en', targetLanguage: 'zh_cn' }+ });+ const stage = await runner.run(job.id, 'subtitle');+ expect(stage.status).toBe('failed');+ expect(stage.progress).toMatchObject({ phase: 'reading_platform_captions', percent: 25 });+ } finally {+ 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/creator-video-preview.test.ts b/apps/daemon/test/unit/creator-video-preview.test.tsindex c0ba02c9..b84a3a69 100644--- a/apps/daemon/test/unit/creator-video-preview.test.ts+++ b/apps/daemon/test/unit/creator-video-preview.test.ts@@ -77,6 +77,25 @@ describe('video translation preview preparation', () => {} finally { await context.close(); }});+ it('keeps stage progress monotonic when the phase changes', async () => {+ const context = setup({ id: 'download', async run({ reportProgress, workdir }) {+ reportProgress({ phase: 'preparing_source', percent: 20, message: '正在准备视频来源' });+ reportProgress({ phase: 'reading_platform_captions', percent: 5, message: '正在获取平台字幕' });+ reportProgress({ phase: 'merging_media', percent: null, message: '正在合并视频和音频' });+ const path = join(workdir, 'preview.mp4');+ writeFileSync(path, 'preview');+ return { outputs: [{ kind: 'source_video', path, status: 'completed', sourceArtifactIds: [] }] };+ } });+ try {+ const result = await context.runner.runStageRun(context.start());+ expect(result.progress).toMatchObject({+ phase: 'merging_media',+ message: '正在合并视频和音频',+ percent: 20+ });+ } finally { await context.close(); }+ });+it('preserves draft status on preview failure and rejects unsupported sources', async () => {const context = setup({ id: 'download', async run() { throw new CreatorExecutorError('network_unavailable', 'Preview download failed'); } });try {diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.tsindex f3d2c78c..ba104de1 100644--- a/apps/daemon/test/unit/gateway-account-service.test.ts+++ b/apps/daemon/test/unit/gateway-account-service.test.ts@@ -25,7 +25,7 @@ async function setup(activate = vi.fn(async () => undefined), close = vi.fn(asynasync startDevice() { const id = String(++attempt); return { attemptId: id, deviceSecret: `private-${id}`, authorizationUrl: `https://gateway.example/device?attempt=${id}`, interval: 5, expiresIn: 600 }; },pollDevice: vi.fn(async (id: string) => ({ accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresIn: 900 })),async cancelDevice() {},- refresh: vi.fn(async () => ({ accessToken: 'new-access', refreshToken: 'new-refresh', expiresIn: 900 })),+ refresh: vi.fn(async (_refreshToken: string) => ({ accessToken: 'new-access', refreshToken: 'new-refresh', expiresIn: 900 })),async logout() {},avatar: vi.fn(async () => ({ data: new Uint8Array([1, 2, 3]), contentType: 'image/png' })),bootstrap: vi.fn(async (access: string): Promise<GatewayBootstrap> => { const id = access.split('-').at(-1)!; return { schemaVersion: 1 as const, account: { id, email: `${id}@example.test`, verified: true }, modelKey: `cloud-${id}`, keyVersion: '1', bindingVersion: `${id}:1`, baseUrl: 'https://gateway.example/v1', models: [{ id: 'gateway-text', modality: 'text' as const, capabilities: ['responses'] }], defaults: { text: 'gateway-text' } }; }),@@ -1196,6 +1196,30 @@ it('revokes model readiness when account polling detects an expired session', as} finally { clock.mockRestore(); await server.close(); await f.service.close(); }});+it('adopts a newer persisted refresh token after a stale token receives 401', async () => {+ const f = await setup();+ await seedSavedAccount(f);+ const store = createGatewayConfigStore(f.root);+ await f.service.initialize();+ const original = await store.readCredentials();+ if (!original) throw new Error('test credentials were not persisted');+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 16 * 60_000);+ try {+ f.client.refresh.mockImplementation(async refreshToken => {+ if (refreshToken === original.refreshToken) {+ await store.writeCredentials({ ...original, accessToken: 'persisted-access', refreshToken: 'persisted-refresh', expiresIn: 900, accessExpiresAt: new Date(Date.now() + 900_000).toISOString() });+ throw new GatewayError('auth_required', 401);+ }+ return { accessToken: 'latest-access', refreshToken: 'latest-refresh', expiresIn: 900 };+ });+ await f.service.refresh();+ expect(f.client.refresh).toHaveBeenNthCalledWith(1, original.refreshToken);+ expect(f.client.refresh).toHaveBeenNthCalledWith(2, 'persisted-refresh');+ expect(f.service.peekState().authState).toBe('signed_in');+ await expect(store.readCredentials()).resolves.toMatchObject({ accessToken: 'latest-access', refreshToken: 'latest-refresh' });+ } finally { clock.mockRestore(); await f.service.close(); }+});+it('clears an expired device session before starting reauthorization', async () => {const f = await setup();const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);diff --git a/apps/daemon/test/unit/gateway-proxy.test.ts b/apps/daemon/test/unit/gateway-proxy.test.tsindex 17545be0..4e70b709 100644--- a/apps/daemon/test/unit/gateway-proxy.test.ts+++ b/apps/daemon/test/unit/gateway-proxy.test.ts@@ -28,6 +28,20 @@ it('accepts protocol 3 without supplier keys and pins the gateway origin', asyncawait expect(client.bootstrap('device-access-token')).rejects.toMatchObject({ code: 'invalid_gateway_response' });});+it('reports an expired gateway account as authentication failure before creating a creator binding', () => {+ const manual = createDefaultCreatorServicesConfig();+ const source = createGatewayCreatorSource({+ account: {+ peekState: () => ({ source: 'gateway', transport: 'gateway', authState: 'expired', activationState: 'inactive',+ account: bootstrap.account, bindingVersion: null, models: bootstrap.models, activationError: null }),+ modelCredentials: vi.fn()+ },+ manual: { read: async () => manual, write: async value => value, reset: async () => manual },+ getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ expect(() => source.snapshot()).toThrow(expect.objectContaining({ code: 'auth_required', status: 401 }));+});+it('loads a gateway account, clears old supplier credentials and refreshes device authentication', async () => {const root = await mkdtemp(join(tmpdir(), 'oc-proxy-account-'));const store = createGatewayConfigStore(root);diff --git a/apps/daemon/test/unit/gateway-runtime-source.test.ts b/apps/daemon/test/unit/gateway-runtime-source.test.tsindex 46f19408..7523e498 100644--- a/apps/daemon/test/unit/gateway-runtime-source.test.ts+++ b/apps/daemon/test/unit/gateway-runtime-source.test.ts@@ -63,6 +63,24 @@ it('keeps manual service turns free of official probes', () => {expect(source.startTurn(f.input)).toBe(f.execution);});+it.each([+ ['expired', 'expired', 'inactive', 'auth_required', 401],+ ['signed_out', 'signed_out', 'inactive', 'auth_required', 401],+ ['loading', 'signed_in', 'loading', 'services_not_ready', 503],+ ['blocked', 'signed_in', 'blocked', 'services_not_ready', 503]+] as const)('reports gateway %s as %s without changing service readiness semantics', (_label, authState, activationState, code, status) => {+ const f = fixture();+ f.state.authState = authState;+ f.state.activationState = activationState;+ if (authState === 'signed_out') {+ f.state.account = null;+ f.state.bindingVersion = null;+ }+ const source = createRuntimeSource(f.manual, () => f.state, () => f.official);+ expect(() => source.startTurn(f.input)).toThrow(expect.objectContaining({ code, status }));+ expect(f.startTurn).not.toHaveBeenCalled();+});+it('rejects a missing selected model without silently using another model', () => {const f = fixture();const source = createRuntimeSource(f.manual, () => f.state, () => f.official);diff --git a/apps/daemon/test/unit/krillin-official-config.test.ts b/apps/daemon/test/unit/krillin-official-config.test.tsindex 1f578a48..813fad3a 100644--- a/apps/daemon/test/unit/krillin-official-config.test.ts+++ b/apps/daemon/test/unit/krillin-official-config.test.ts@@ -14,7 +14,10 @@ it('emits the selected ASR marker only for an official runtime and keeps customexpect(parse(createKrillinConfigToml(config))).toMatchObject({ app: { proxy: config.proxy }, transcribe: { openai: { model: 'custom-asr' } } });expect(createKrillinConfigToml(config)).not.toContain('official_model');const official = parse(createKrillinConfigToml(config, undefined, 'official-asr'));- expect(official).toMatchObject({ transcribe: { openai: { official_model: 'official-asr' } } });+ expect(official).toMatchObject({+ app: { youtube_proxy: config.proxy },+ transcribe: { openai: { official_model: 'official-asr' } }+ });expect(official.app).not.toHaveProperty('proxy');expect(config.transcription.openai.model).toBe('custom-asr');});diff --git a/apps/desktop/resources/icon.icns b/apps/desktop/resources/icon.icnsnew file mode 100644index 00000000..decb7666Binary files /dev/null and b/apps/desktop/resources/icon.icns differdiff --git a/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx b/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsxindex 075eb3e4..29497064 100644--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx@@ -79,7 +79,7 @@ describe('shared video progress timing', () => {</CreatorSessionProvider></LanguageProvider>);expect(screen.getByText('初译 40/60;字幕完成 0/60;正在审校、排版')).toBeVisible();- expect(screen.getByRole('progressbar', { name: '当前阶段进度' })).toHaveAttribute('aria-valuenow', '48');+ expect(screen.getByRole('progressbar', { name: '当前任务进度' })).toHaveAttribute('aria-valuenow', '48');});it('keeps subtitle translation progress fixed while waiting and shows real sentence counts', () => {@@ -297,6 +297,29 @@ describe('CreatorCollaborationPanel', () => {expect(ensureJob).not.toHaveBeenCalled();});+ it('offers a direct sign-in action for expired OpenCreator sessions', () => {+ const issue = normalizePageIssue(+ 'creator-launch',+ 'creator-launch.create-job',+ { code: 'GATEWAY_AUTH_REQUIRED' },+ 'OpenCreator sign-in has expired.'+ );+ const pendingJob = { ...videoGenerationJob(), id: 'pending:project_1:video-generation', stages: [], activities: [], issues: [] };+ render(+ <LanguageProvider initialPreference="zh-CN">+ <CreatorSessionProvider+ initialJob={pendingJob}+ externalIssues={[issue]}+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}+ >+ <CreatorCollaborationPanel adapter={videoGenerationPanelAdapter} stepLabel="生成视频" contextSummary="Veo" />+ </CreatorSessionProvider>+ </LanguageProvider>+ );++ expect(screen.getByRole('link', { name: '去登录' })).toHaveAttribute('href', '#/account');+ });+it('keeps entries in top-down order and follows new activity only while reading the latest entries', () => {render(<LanguageProvider initialPreference="zh-CN">diff --git a/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx b/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsxindex b93354f3..c267f915 100644--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx@@ -12,6 +12,7 @@ import {ChevronRight,CircleDot,LoaderCircle,+ LogIn,MessageSquareText,MoreHorizontal,Play,@@ -442,6 +443,12 @@ function CollaborationIssueView(props: {</div>{props.issue.status === 'open' ? (<div className="creator-collaboration-issue-actions">+ {isOpenCreatorAuthIssue(props.issue) ? (+ <a className="creator-collaboration-login-action" href="#/account">+ <LogIn size={15} aria-hidden="true" />+ {l('去登录', 'Sign in')}+ </a>+ ) : null}<button type="button" onClick={props.onFocus} title={l('询问这个问题', 'Ask about this issue')} aria-label={l('询问这个问题', 'Ask about this issue')}><MessageSquareText size={15} aria-hidden="true" /></button>@@ -452,6 +459,10 @@ function CollaborationIssueView(props: {);}+function isOpenCreatorAuthIssue(issue: OpenCreatorIssue): boolean {+ return issue.code === 'auth_required' || issue.code === 'GATEWAY_AUTH_REQUIRED';+}+function CollaborationMessageView(props: { message: CollaborationMessage }) {const l = useLocalizedCopy();const { message } = props;@@ -505,12 +516,16 @@ export function CreatorTaskProgressNotice(props: { stageId?: string; stage?: Creconst adapter = creatorPanelAdapterFor(session?.job.templateId ?? '');const progress = adapter.readStageProgress(stage, localize);const percent = progress.percent === null ? null : Math.max(0, Math.min(100, Math.round(progress.percent)));+ const phasePercent = progress.phase === 'normalizing_media' && progress.phasePercent !== null && progress.phasePercent !== undefined+ ? Math.max(0, Math.min(100, Math.round(progress.phasePercent)))+ : null;return (<section className="creator-task-progress-notice" role="status" aria-label={localize('任务进度', 'Task progress', 'Uppgiftsförlopp')}><div className="creator-task-progress-notice-heading">{stageStatusIcon(stage)}<strong>{stageProgressText(stage, progress, adapter, localize)}{percent === null ? '' : ` · ${percent}%`}</strong></div>+ {phasePercent === null ? null : <small className="creator-task-progress-phase">{localize(`当前转换阶段 ${phasePercent}%`, `Current conversion phase ${phasePercent}%`, `Aktuell konverteringsfas ${phasePercent}%`)}</small>}<div className="creator-collaboration-stage-progress" data-indeterminate={progress.indeterminate || percent === null || undefined}role="progressbar" aria-label={props.stage ? localize('原视频下载进度', 'Source video download progress') : localize('任务进度', 'Task progress')}aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent ?? undefined}@@ -553,8 +568,14 @@ export function useCreatorTaskProgress(options: {const status = starting ? 'starting' : needsInput ? 'needs_input' : workflow?.waitingForNext ? 'running' : stage!.status;const active = status === 'starting' || status === 'queued' || status === 'running';const progress = stage ? adapter.readStageProgress(stage, l) : undefined;- const indeterminate = starting || workflow?.waitingForNext || progress?.indeterminate === true || progress?.percent == null;- const percent = status === 'succeeded' ? 100 : indeterminate ? null : Math.max(0, Math.min(100, Math.round(progress!.percent!)));+ const workflowPercent = workflow?.taskPercent ?? null;+ const indeterminate = starting || (workflow?.waitingForNext === true && workflowPercent === null)+ || progress?.indeterminate === true || (workflowPercent === null && progress?.percent == null);+ const percent = status === 'succeeded'+ ? 100+ : indeterminate+ ? null+ : workflowPercent ?? Math.max(0, Math.min(100, Math.round(progress!.percent!)));const canceling = active && stage?.progress.cancelRequested === true;const label = workflow?.steps[workflow.stepIndex]?.label ?? l('创作任务', 'Creator task');const title = starting ? l('正在启动任务', 'Starting task')@@ -630,6 +651,9 @@ export function CreatorTaskProgressBar(props: {<div><span title={task.controlError ?? task.summary}>{task.controlError ?? task.summary}</span>{task.active && !task.starting && task.stage && task.progress ? <CreatorStageProgressDetails stage={task.stage} progress={task.progress} compact /> : null}</div>+ {task.progress?.phase === 'normalizing_media' && task.progress.phasePercent !== null && task.progress.phasePercent !== undefined+ ? <span>{l(`当前转换阶段 ${Math.round(task.progress.phasePercent)}%`, `Current conversion phase ${Math.round(task.progress.phasePercent)}%`)}</span>+ : null}</div>{!task.starting ? <ol className="creator-task-progress-bar-stages" aria-label={l('执行阶段', 'Workflow stages')}>{task.workflow?.steps.map((step, index) => <li key={step.id} aria-current={!success && index === phase ? 'step' : undefined} data-completed={index < phase || success || undefined}>@@ -637,7 +661,7 @@ export function CreatorTaskProgressBar(props: {<span>{index < phase || success ? <CheckCircle2 size={12} /> : index + 1}</span>{step.label}</li>)}</ol> : null}- {task.percent !== null ? <strong className="creator-task-progress-bar-percent" title={l('当前阶段进度', 'Current stage progress')}>{task.percent}<span>%</span></strong> : null}+ {task.percent !== null ? <strong className="creator-task-progress-bar-percent" title={l('当前任务进度', 'Current task progress')}>{task.percent}<span>%</span></strong> : null}<div className="creator-task-progress-bar-actions">{failed ? <button type="button" disabled={busy} onClick={() => void task.retry()}>{task.retryPending ? l('正在重试…', 'Retrying…') : l('重试当前阶段', 'Retry stage')}</button> : null}{stopped && props.onResume ? <button type="button" disabled={busy} onClick={props.onResume}>{props.controlPending === 'resuming' ? l('正在继续…', 'Resuming…') : l('继续任务', 'Resume task')}</button> : null}@@ -655,7 +679,7 @@ export function CreatorTaskProgressBar(props: {{success ? <button type="button" aria-label={l('关闭完成提示', 'Dismiss completion notice')} onClick={task.dismiss}><X size={15} /></button> : null}</div></div>- {task.active || success ? <div className="creator-task-progress-bar-track" role="progressbar" aria-label={l('当前阶段进度', 'Current stage progress')}+ {task.active || success ? <div className="creator-task-progress-bar-track" role="progressbar" aria-label={l('当前任务进度', 'Current task progress')}data-indeterminate={task.percent === null || undefined} aria-valuemin={0} aria-valuemax={100} aria-valuenow={task.percent ?? undefined}aria-valuetext={task.percent === null ? task.title : `${task.percent}%`}><span style={{ width: `${task.percent ?? 30}%` }} /></div> : null}</section>;@@ -747,6 +771,9 @@ function CollaborationStageView(props: {<div className="creator-collaboration-stage-copy"><small>{actorLabel(actor, l)} · {label}</small><strong>{stageProgressText(stage, progress, adapter, l)}</strong>+ {progress.phase === 'normalizing_media' && progress.phasePercent !== null && progress.phasePercent !== undefined+ ? <small className="creator-task-progress-phase">{l(`当前转换阶段 ${Math.round(progress.phasePercent)}%`, `Current conversion phase ${Math.round(progress.phasePercent)}%`, `Aktuell konverteringsfas ${Math.round(progress.phasePercent)}%`)}</small>+ : null}</div><div className="creator-collaboration-stage-controls">{showPercent ? <b>{percent}%</b> : null}diff --git a/apps/web/src/features/dashboard/CreatorTaskProgressBar.test.tsx b/apps/web/src/features/dashboard/CreatorTaskProgressBar.test.tsxindex c94a30f1..0a496bfa 100644--- a/apps/web/src/features/dashboard/CreatorTaskProgressBar.test.tsx+++ b/apps/web/src/features/dashboard/CreatorTaskProgressBar.test.tsx@@ -60,19 +60,19 @@ describe('shared persistent task progress', () => {expect(view.onCancel).toHaveBeenCalledOnce();});- it('keeps the bar between stages, resets per-stage progress and completes only after the final render', () => {+ it('keeps the task progress monotonic between stages and completes only after the final render', () => {const initial = job();initial.state.videoFormat = 'all';const view = mount(initial);const tts = stage('tts', { status: 'succeeded', progress: { workflow: true, resultVersion: 2, percent: 100 } });view.push({ ...initial, status: 'completed', stages: [tts] });expect(screen.getByRole('region', { name: '当前任务进度' })).toHaveTextContent('正在准备合成横屏视频');- expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow');+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '33');expect(view.onCompleted).not.toHaveBeenCalled();const horizontal = stage('render-horizontal', { id: 'render_1', progress: { workflow: true, workflowParentStageRunId: tts.id, targetResultVersion: 2, phase: 'rendering_video', percent: 12 } });const background = stage('preview-source-video', { id: 'download_1', progress: { backgroundSourceDownload: true, percent: 90, phase: 'downloading' } });view.push({ ...initial, stages: [tts, horizontal, background] });- expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '12');+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '37');expect(screen.getByRole('region', { name: '当前任务进度' })).not.toHaveTextContent('下载原视频');const doneHorizontal = { ...horizontal, status: 'succeeded' as const };// Ignore the completed parallel download when following the render chain.@@ -91,6 +91,37 @@ describe('shared persistent task progress', () => {expect(screen.queryByRole('region', { name: '当前任务进度' })).toBeNull();});+ it('does not move the workflow bar backward when a later stage starts at five percent', () => {+ const subtitle = stage('subtitle', { id: 'subtitle_1', progress: { workflow: true, percent: 25 } });+ const initial = job([subtitle]);+ initial.state.dubbing = false;+ initial.state.composeVideo = true;+ initial.state.videoFormat = 'horizontal';+ const first = videoTranslationPanelAdapter.taskProgress?.(initial, (zh: string) => zh);+ const render = stage('render-horizontal', { id: 'render_1', progress: {+ workflow: true, workflowParentStageRunId: subtitle.id, percent: 5+ } });+ const next = videoTranslationPanelAdapter.taskProgress?.({ ...initial, stages: [+ { ...subtitle, status: 'succeeded', progress: { workflow: true, percent: 100 } }, render+ ] }, (zh: string) => zh);+ expect(first?.taskPercent).toBe(25);+ expect(next?.taskPercent).toBeGreaterThan(first?.taskPercent ?? 0);+ expect(next?.taskPercent).toBe(53);+ });++ it('keeps the overall progress and labels the conversion phase separately', () => {+ const source = stage('prepare-source-video', {+ executor: 'download',+ progress: { phase: 'normalizing_media', percent: 98.90059326924516, phasePercent: 50 }+ });+ const view = mount(job([source]));+ const bar = screen.getByRole('region', { name: '当前任务进度' });+ expect(within(bar).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '99');+ expect(within(bar).getByText('当前转换阶段 50%')).toBeVisible();+ expect(bar).not.toHaveTextContent('98.90059326924516');+ view.unmount();+ });+it('uses elapsed time and reconnect feedback without fabricating a percentage', () => {vi.useFakeTimers();vi.setSystemTime(new Date('2026-10-21T00:00:05Z'));diff --git a/apps/web/src/features/dashboard/DashboardPage.test.tsx b/apps/web/src/features/dashboard/DashboardPage.test.tsxindex 859ebf6c..91eb111c 100644--- a/apps/web/src/features/dashboard/DashboardPage.test.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.test.tsx@@ -1559,7 +1559,7 @@ describe('DashboardPage', () => {})));expect(applyAction.mock.calls.flatMap(([, request]) => request.action === 'run-stage' ? [request.input.stageId] : [])).toEqual(['subtitle', 'render-horizontal']);expect(await screen.findByRole('button', { name: '项目 V2' })).toBeInTheDocument();- expect(screen.getByText('新版本已从“横屏成片”开始,旧版本和已有前置产物会继续保留')).toBeInTheDocument();+ expect(screen.queryByText('新版本已从“横屏成片”开始,旧版本和已有前置产物会继续保留')).not.toBeInTheDocument();});it('does not bind a changed URL source to the selected version input artifacts', async () => {diff --git a/apps/web/src/features/dashboard/SubtitleTimeline.test.tsx b/apps/web/src/features/dashboard/SubtitleTimeline.test.tsxindex 1b05abf9..1e0056d8 100644--- a/apps/web/src/features/dashboard/SubtitleTimeline.test.tsx+++ b/apps/web/src/features/dashboard/SubtitleTimeline.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import SubtitleTimeline from './SubtitleTimeline.js';@@ -88,4 +88,26 @@ describe('SubtitleTimeline playback controls', () => {fireEvent.pointerUp(ui.slider, { clientX: 200 });expect(ui.onSeek).toHaveBeenLastCalledWith(6);});++ it('generates a waveform for a normal high-bitrate video above the old size limit', async () => {+ const bytes = new Uint8Array([1, 2, 3]);+ vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes, {+ headers: { 'content-length': String(128 * 1024 * 1024) }+ })));+ vi.stubGlobal('OfflineAudioContext', class {+ async decodeAudioData() {+ return {+ duration: 20,+ numberOfChannels: 1,+ getChannelData: () => new Float32Array([0, .5, 0, -.25])+ };+ }+ });+ render(<SubtitleTimeline cues={[]} src="blob:large-video" currentTime={5} duration={20}+ playing={false} readOnly onSelect={vi.fn()} onSeek={vi.fn()} onTogglePlay={vi.fn()}+ onPlaybackChange={vi.fn()} onChange={vi.fn()} />);+ await waitFor(() => expect(document.querySelector('.subtitle-timeline-waveform svg')).not.toBeNull());+ expect(document.querySelector('.subtitle-timeline-waveform path')?.getAttribute('d')).toContain('v56.0');+ expect(screen.queryByText('无法生成此媒体的波形,仍可调整字幕时间。')).toBeNull();+ });});diff --git a/apps/web/src/features/dashboard/SubtitleTimeline.tsx b/apps/web/src/features/dashboard/SubtitleTimeline.tsxindex cd56698d..26f754cc 100644--- a/apps/web/src/features/dashboard/SubtitleTimeline.tsx+++ b/apps/web/src/features/dashboard/SubtitleTimeline.tsx@@ -4,12 +4,17 @@ import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { SubtitleCue } from './VideoTranslationResultWorkspace.js';import { mergeSubtitle, retimeSubtitle, splitSubtitle, subtitleSeconds, subtitleTimestamp, waveformPeaks } from './subtitle-editing.js';-const MAX_WAVEFORM_BYTES = 64 * 1024 * 1024;+// Keep waveform decoding bounded while allowing normal high-bitrate videos.+const MAX_WAVEFORM_BYTES = 256 * 1024 * 1024;function waveformSvgPath(peaks: number[]) {+ const sortedPeaks = peaks.filter(Number.isFinite).sort((left, right) => left - right);+ const reference = sortedPeaks[Math.floor(Math.max(0, sortedPeaks.length - 1) * .99)] ?? 0;+ const scale = reference > 0 ? 1 / reference : 1;return peaks.map((peak, i, all) => {const x = i * 10000 / Math.max(1, all.length - 1);- return `M${x.toFixed(1)},${(30 - peak * 28).toFixed(1)}v${(peak * 56).toFixed(1)}`;+ const normalized = Math.min(1, Math.max(0, peak * scale));+ return `M${x.toFixed(1)},${(30 - normalized * 28).toFixed(1)}v${(normalized * 56).toFixed(1)}`;}).join('');}diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsxindex 697187b7..4d586167 100644--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx@@ -1469,7 +1469,7 @@ function downloadProgressPercent(if (artifact !== undefined || stage?.status === 'succeeded') return 100;const percent = readNumber(stage?.progress.percent);if (percent === undefined) return 0;- return Math.min(100, Math.max(0, percent));+ return Math.min(100, Math.max(0, Math.round(percent)));}function downloadPendingTitle(diff --git a/apps/web/src/features/dashboard/VideoTranslationAgentPanel.test.tsx b/apps/web/src/features/dashboard/VideoTranslationAgentPanel.test.tsxindex 6c8f4943..65d47312 100644--- a/apps/web/src/features/dashboard/VideoTranslationAgentPanel.test.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationAgentPanel.test.tsx@@ -29,6 +29,24 @@ describe('VideoTranslationAgentPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'sv-SE' }));expect(screen.getByText(/Laddar ned den aktuella videoresursen: 6.0 MiB/)).toBeVisible();});++ it('keeps the overall percentage and labels the conversion phase separately', async () => {+ const current = job();+ current.status = 'running';+ current.stages.push({+ id: 'source-conversion', jobId: current.id, stageId: 'prepare-source-video', executor: 'download', status: 'running', dispatchStatus: 'claimed',+ claimOwner: 'scheduler', claimExpiresAt: null, attempt: 1, idempotencyKey: 'source-conversion', scopeKey: null, inputFingerprint: null,+ progress: { phase: 'normalizing_media', percent: 98.90059326924516, phasePercent: 90 },+ errorCode: null, errorMessage: null, startedAt: '2026-10-02T00:00:00.000Z', finishedAt: null+ });+ renderPanel({ initialJob: current, getAgentTimeline: vi.fn(async () => emptyTimeline()) });+ const progress = await screen.findByRole('progressbar');+ expect(progress).toHaveAttribute('aria-valuenow', '99');+ expect(screen.getByText('当前转换阶段 90%')).toBeVisible();+ expect(screen.getByText('正在转换原视频为本机兼容格式,已有字幕会保留。')).toBeVisible();+ expect(screen.queryByText(/98\.90059326924516/)).not.toBeInTheDocument();+ });+it('明确显示长时间模型下载的原因、真实进度和自动继续提示', async () => {const current = job();current.status = 'running';diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsxindex bd49ce67..93148fda 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx@@ -40,6 +40,7 @@ import { useLocalizedCopy, type LocalizeCopy } from '../../i18n/useLocalizedCopyimport type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';import type { VideoMetadataService } from '../../services/video-metadata-service.js';import { CreatorTaskProgressBar, CreatorTaskProgressNotice, useCreatorTaskProgress } from './CreatorCollaborationPanel.js';+import { creatorStageProgressPercent } from './creator-panel-adapters.js';import { clearTranslationContinuation, readTranslationContinuation, saveTranslationContinuation, ttsServiceConfigured, type TranslationEditorContext } from './video-translation-continuation.js';import VideoTranslationAgentPanel from './VideoTranslationAgentPanel.js';import CreatorResizableLayout from './CreatorResizableLayout.js';@@ -2969,6 +2970,7 @@ export default function VideoTranslationWorkspace(props: {function requestOutput(type: 'video' | 'voice') {if (speechSyncing || submitting || subtitleSaving || activeStage || sourcePreviewPending || outputStartingRef.current || !selectedResult) return;+ setResultNotice('');if (type === 'voice' && plannedStage === 'subtitle') {setResultNotice(l('翻译语言已修改,请先重新翻译字幕,再生成配音。', 'The translation languages changed. Retranslate the subtitles before generating dubbing.'));return;@@ -3245,17 +3247,19 @@ export default function VideoTranslationWorkspace(props: {setWorkspacePhase('result');setResultTab('subtitles');setSubtitleImmersive(true);- setResultNotice(isRegeneration- ? stageId === undefined- ? l(- '修改已保存,本次无需重新转录或生成',- 'Changes were saved without retranscribing or regenerating.'- )- : l(- `新版本已从“${translationStageLabel(stageId, l)}”开始,已有前置产物会直接复用`,- `The new version started from "${translationStageLabel(stageId, l)}" and will reuse existing upstream outputs.`- )- : translationStartedNotice);+ setResultNotice(isRegeneration && isVideoCompositionStage(stageId)+ ? ''+ : isRegeneration+ ? stageId === undefined+ ? l(+ '修改已保存,本次无需重新转录或生成',+ 'Changes were saved without retranscribing or regenerating.'+ )+ : l(+ `新版本已从“${translationStageLabel(stageId, l)}”开始,已有前置产物会直接复用`,+ `The new version started from "${translationStageLabel(stageId, l)}" and will reuse existing upstream outputs.`+ )+ : translationStartedNotice);} catch (cause) {if ((cause as { code?: unknown })?.code === 'creator_revision_conflict') {setStartRevisionConflict(true);@@ -3502,6 +3506,7 @@ export default function VideoTranslationWorkspace(props: {return;}setSubmitting(true);+ setResultNotice('');try {let speech = { ttsProvider, ttsModel, voiceCode, voiceName };if ((proposal === 'voice' || regenerationSettings.dubbing) && !officialSpeech.official) {@@ -3538,15 +3543,17 @@ export default function VideoTranslationWorkspace(props: {setResultTab('subtitles');if (stageId === 'subtitle') setSubtitleAssistantOpen(true);setResultProposal(undefined);- setResultNotice(stageId === undefined- ? l(- '修改已保存,本次无需重新转录或生成',- 'Changes were saved without retranscribing or regenerating.'- )- : l(- `新版本已从“${translationStageLabel(stageId, l)}”开始,旧版本和已有前置产物会继续保留`,- `The new version started from "${translationStageLabel(stageId, l)}"; previous versions and upstream outputs remain available.`- ));+ setResultNotice(isVideoCompositionStage(stageId)+ ? ''+ : stageId === undefined+ ? l(+ '修改已保存,本次无需重新转录或生成',+ 'Changes were saved without retranscribing or regenerating.'+ )+ : l(+ `新版本已从“${translationStageLabel(stageId, l)}”开始,旧版本和已有前置产物会继续保留`,+ `The new version started from "${translationStageLabel(stageId, l)}"; previous versions and upstream outputs remain available.`+ ));} catch (cause) {setResultNotice(creatorErrorMessage(cause, l));} finally {@@ -4556,6 +4563,10 @@ function creatorErrorMessage(cause: unknown, l: LocalizeCopy): string {return l('启动翻译失败,请在 Agent 区域查看诊断后重试。', 'Failed to start translation. Review the diagnosis in the Agent panel and retry.');}+function isVideoCompositionStage(stageId: TranslationStageId | undefined): boolean {+ return stageId === 'render-horizontal' || stageId === 'render-vertical';+}+function translationStageLabel(stageId: string, l: LocalizeCopy): string {if (stageId === 'prepare-source-video') return l('原视频预览准备', 'Source video preview preparation');if (stageId === 'subtitle') return l('字幕翻译', 'Subtitle translation');@@ -4612,17 +4623,6 @@ function stageResumeDescription();}-function creatorStageProgressPercent(- stage: import('@opencreator/protocol').CreatorStageRun-): number | null {- const value = typeof stage.progress.percent === 'number'- ? stage.progress.percent- : null;- return value === null || !Number.isFinite(value)- ? null- : Math.max(0, Math.min(100, Math.round(value)));-}-function stageErrorMessage(code: string | null, message: string | null, l: LocalizeCopy): string {const configurationCode = normalizeStageConfigurationError(code, message);if (configurationCode !== null) return creatorErrorMessage({ code: configurationCode }, l);diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts b/apps/web/src/features/dashboard/creator-panel-adapters.test.tsindex 40fe9c9a..cfd50365 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.test.ts@@ -220,7 +220,8 @@ describe('video translation component progress', () => {expect(videoTranslationPanelAdapter.normalizeActivity(activity('run-stage', { stageId: running.stageId }), zh)).toEqual({ label: '开始下载原视频预览', fields: [] });expect(videoTranslationPanelAdapter.readStageProgress(running, en)).toMatchObject({ percent: 40, indeterminate: false, message: 'Downloading the source video: 4.0 MiB / 10.0 MiB' });- expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98 } }, zh)).toMatchObject({ percent: null, indeterminate: true });+ expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98, phasePercent: 50 } }, zh)).toMatchObject({ percent: 98, phasePercent: 50, indeterminate: false, message: '正在转换原视频为本机兼容格式' });+ expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98.90059326924516 } }, zh)).toMatchObject({ percent: 99, phasePercent: 90, indeterminate: false });expect(videoTranslationPanelAdapter.failedProgressText?.(running, zh)).toContain('可重试');expect(videoTranslationPanelAdapter.succeededProgressText?.(running, zh)).toContain('已就绪');});@@ -263,7 +264,7 @@ describe('video translation component progress', () => {expect(videoTranslationPanelAdapter.readStageProgress(running, zh)).toMatchObject({ percent: 40, indeterminate: false, message: expect.stringContaining('4.0 MiB / 10.0 MiB') });expect(videoTranslationPanelAdapter.readStageProgress(running, en).message).toContain('subtitles will not be translated again');expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'downloading', percent: null } }, zh)).toMatchObject({ percent: null, indeterminate: true });- expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98 } }, zh)).toMatchObject({ percent: null, indeterminate: true });+ expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: { phase: 'normalizing_media', percent: 98, phasePercent: 50 } }, zh)).toMatchObject({ percent: 98, phasePercent: 50, indeterminate: false, message: '正在转换原视频为本机兼容格式,已有字幕会保留。' });expect(videoTranslationPanelAdapter.normalizeActivity(activity('run-stage', { stageId: 'prepare-source-video' }), zh)).toEqual({ label: '开始准备原视频预览,保留已有字幕', fields: [] });});diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.ts b/apps/web/src/features/dashboard/creator-panel-adapters.tsindex 723b8e28..20a58c9c 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.ts@@ -20,6 +20,7 @@ export type CreatorStageProgressView = {showMessage?: boolean;showTiming?: boolean;percent: number | null;+ phasePercent?: number | null;indeterminate?: boolean;phase: string | null;message: string | null;@@ -61,6 +62,7 @@ export type CreatorTaskWorkflowView = {stage: CreatorStageRun;steps: Array<{ id: string; label: string }>;stepIndex: number;+ taskPercent: number | null;waitingForNext: boolean;resultVersion?: number;completionLabel: string;@@ -195,17 +197,19 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {const amount = `${(bytes / 1024 ** 2).toFixed(1)} MiB${total === null ? '' : ` / ${(total / 1024 ** 2).toFixed(1)} MiB`}${speed && speed > 0 ? ` · ${(speed / 1024 ** 2).toFixed(1)} MiB/s` : ''}${remaining === null ? '' : localize(` · 剩余约 ${Math.ceil(remaining)} 秒`, ` · ~${Math.ceil(remaining)} s remaining`)}`;if (stage.stageId === 'preview-source-video') return { ...standard,showMessage: true,- percent: standard.phase === 'downloading' || standard.phase === 'completed' ? standard.percent : null,- indeterminate: standard.phase !== 'completed' && (standard.phase !== 'downloading' || standard.percent === null),+ indeterminate: standard.percent === null,message: standard.phase === 'downloading'? localize(`正在下载原视频:${amount}`, `Downloading the source video: ${amount}`, `Laddar ned originalvideon: ${amount}`)+ : standard.phase === 'normalizing_media'+ ? localize('正在转换原视频为本机兼容格式', 'Converting the source video for local playback', 'Konverterar originalvideon för lokal uppspelning'): localize('正在准备原视频预览', 'Preparing the source video preview', 'Förbereder originalvideons förhandsvisning') };return { ...standard,showMessage: true,- percent: standard.phase === 'downloading' || standard.phase === 'completed' ? standard.percent : null,- indeterminate: standard.phase !== 'completed' && (standard.phase !== 'downloading' || standard.percent === null),+ indeterminate: standard.percent === null,message: standard.phase === 'downloading'? localize(`正在下载当前视频资源:${amount}。仅用于预览,不会重新翻译。`, `Downloading the current video resource: ${amount}. Preview only; subtitles will not be translated again.`, `Laddar ned den aktuella videoresursen: ${amount}. Endast för förhandsvisning; undertexterna översätts inte igen.`)+ : standard.phase === 'normalizing_media'+ ? localize('正在转换原视频为本机兼容格式,已有字幕会保留。', 'Converting the source video for local playback. Existing subtitles are preserved.', 'Konverterar originalvideon för lokal uppspelning. Befintliga undertexter bevaras.'): localize('正在准备原视频预览,已完成的字幕会保留,不会重新翻译。', 'Preparing source video preview. Existing subtitles are preserved and will not be translated again.') };}if (standard.phase?.endsWith('_dependencies') || standard.phase === 'dependencies_ready') {@@ -217,7 +221,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {const bytes = `${format(downloaded)}${total === null ? '' : ` / ${format(total)}`}${speed ? ` · ${format(speed)}/s` : ''}${remaining === null ? '' : ` · ~${Math.ceil(remaining / 60)} min`}`;return { ...standard,showMessage: true,- percent: standard.phase === 'downloading_dependencies' ? readFiniteNumber(stage.progress.dependencyPercent) : null,+ percent: standard.phase === 'downloading_dependencies' ? normalizeProgressPercent(readFiniteNumber(stage.progress.dependencyPercent)) : null,indeterminate: standard.phase !== 'downloading_dependencies' || readFiniteNumber(stage.progress.dependencyPercent) === null,message: `${fallbackMessage === null ? '' : `${fallbackMessage} `}${standard.phase === 'dependencies_ready'? localize('本地转录组件已准备完成,正在开始语音转录', 'Local transcription components are ready; starting transcription.', 'De lokala transkriptionskomponenterna är redo; startar transkriptionen.')@@ -239,7 +243,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {return {summary: translating && localizedMessage !== null && /^初译 \d+\/\d+;字幕完成 \d+\/\d+;/.test(rawMessage ?? '')? detailMessage ?? undefined : undefined,- percent: standard.percent ?? readFiniteNumber(legacy?.percent),+ percent: standard.percent ?? normalizeProgressPercent(readFiniteNumber(legacy?.percent)),phase,showTiming: detailed,showMessage: fallbackMessage !== null || detailed,@@ -296,6 +300,26 @@ function videoTranslationTaskProgress(job: CreatorJob, l: CreatorPanelLocalize):if (!ids.includes(stage.stageId)) ids.push(stage.stageId);const stepIndex = ids.indexOf(stage.stageId);const waitingForNext = stage.status === 'succeeded' && stepIndex < ids.length - 1 && job.status !== 'canceled';+ const currentStagePercent = videoTranslationPanelAdapter.readStageProgress(stage, l).percent;+ const retryPercent = Math.max(0, ...chain+ .filter(candidate => candidate.stageId === stage.stageId && candidate.id !== stage.id)+ .map(candidate => videoTranslationPanelAdapter.readStageProgress(candidate, l).percent ?? 0));+ const stagePercent = waitingForNext+ ? 0+ : currentStagePercent === null+ ? null+ : Math.max(currentStagePercent, retryPercent);+ const weightedTaskPercent = waitingForNext+ ? Math.round(((stepIndex + 1) / ids.length) * 100)+ : stagePercent === null+ ? null+ : Math.round(((stepIndex + Math.max(0, Math.min(100, stagePercent)) / 100) / ids.length) * 100);+ const taskPercent = stagePercent === null+ ? null+ : Math.max(Math.round(Math.max(0, Math.min(100, stagePercent))), weightedTaskPercent ?? 0);+ const normalizedTaskPercent = generationIds.includes(stage.stageId)+ ? taskPercent+ : currentStagePercent;if (stage.stageId === 'subtitle' && stage.status === 'succeeded' && !waitingForNext) return null;const labels: Record<string, string> = {subtitle: l('翻译字幕', 'Translate subtitles'),@@ -310,6 +334,7 @@ function videoTranslationTaskProgress(job: CreatorJob, l: CreatorPanelLocalize):stage,steps: ids.map(id => ({ id, label: labels[id] ?? videoTranslationPanelAdapter.stageLabel(id, l) })),stepIndex,+ taskPercent: normalizedTaskPercent,waitingForNext,resultVersion,completionLabel: stage.stageId.startsWith('render-') ? l('视频合成完成', 'Video composition complete')@@ -1461,9 +1486,11 @@ function readActivityStageId(activity: CreatorActivity): string | null {}function readStandardProgress(stage: CreatorStageRun): CreatorStageProgressView {+ const phase = readString(stage.progress.phase);return {- percent: readFiniteNumber(stage.progress.percent),- phase: readString(stage.progress.phase),+ percent: creatorStageProgressPercent(stage),+ phasePercent: phase === 'normalizing_media' ? conversionPhasePercent(stage) : null,+ phase,message: readString(stage.progress.message),completed: readFiniteNumber(stage.progress.completed),failed: readFiniteNumber(stage.progress.failed),@@ -1471,6 +1498,25 @@ function readStandardProgress(stage: CreatorStageRun): CreatorStageProgressView};}+function normalizeProgressPercent(value: number | null): number | null {+ return value === null || !Number.isFinite(value)+ ? null+ : Math.max(0, Math.min(100, Math.round(value)));+}++function conversionPhasePercent(stage: CreatorStageRun): number | null {+ const explicit = normalizeProgressPercent(readFiniteNumber(stage.progress.phasePercent));+ if (explicit !== null) return explicit;+ const overall = readFiniteNumber(stage.progress.percent);+ return overall === null+ ? null+ : normalizeProgressPercent((overall - 98) * 100);+}++export function creatorStageProgressPercent(stage: CreatorStageRun): number | null {+ return normalizeProgressPercent(readFiniteNumber(stage.progress.percent));+}+function genericPhaseLabel(phase: string,l: CreatorPanelLocalizediff --git a/apps/web/src/features/dashboard/creator-session-store.test.tsx b/apps/web/src/features/dashboard/creator-session-store.test.tsxindex bd37fb74..a48b8205 100644--- a/apps/web/src/features/dashboard/creator-session-store.test.tsx+++ b/apps/web/src/features/dashboard/creator-session-store.test.tsx@@ -143,6 +143,32 @@ describe('CreatorSessionStore', () => {expect(session.job.stages[0]!.progress.downloadControl).not.toBe('paused');});+ it('retains a newer stage percent when a later phase reports a smaller value', async () => {+ const stage: CreatorStageRun = {+ id: 'subtitle_1', jobId: 'job_1', stageId: 'subtitle', executor: 'krillinai', status: 'running',+ dispatchStatus: 'claimed', claimOwner: null, claimExpiresAt: null, attempt: 1, idempotencyKey: null,+ scopeKey: null, inputFingerprint: null, progress: { phase: 'preparing_source', percent: 20 },+ errorCode: null, errorMessage: null, startedAt: null, finishedAt: null+ };+ const initial = { ...job(2, {}), templateId: 'video-translation', status: 'running' as const, stages: [stage] };+ let session!: ReturnType<typeof useCreatorSession>;+ let emit!: (event: CreatorEventEnvelope) => void;+ const subscribeJobEvents = vi.fn((_id, onEvent) => { emit = onEvent; return { close: vi.fn() }; });+ function SnapshotHarness() { session = useCreatorSession(); return <Harness />; }+ render(<CreatorSessionProvider initialJob={initial} service={{ applyAction: vi.fn(), runAgentTurn: vi.fn(),+ getJob: vi.fn(async () => ({ job: initial })), subscribeJobEvents } as never}><SnapshotHarness /></CreatorSessionProvider>);+ await waitFor(() => expect(emit).toBeDefined());+ const lower = { ...stage, progress: { phase: 'reading_platform_captions', percent: 5, message: '正在获取平台字幕' } };+ act(() => session.applyRemoteSnapshot({ ...initial, stages: [lower] }));+ expect(session.job.stages[0]!.progress).toMatchObject({ phase: 'reading_platform_captions', message: '正在获取平台字幕', percent: 20 });+ act(() => emit({ id: 'subtitle:lower', jobId: initial.id, revision: 2, kind: 'stage_progress',+ payload: { stage: lower as never }, createdAt: initial.updatedAt }));+ expect(session.job.stages[0]!.progress).toMatchObject({ percent: 20 });+ const unknown = { ...stage, progress: { phase: 'merging_media', percent: null } };+ act(() => session.applyRemoteSnapshot({ ...initial, stages: [unknown] }));+ expect(session.job.stages[0]!.progress).toMatchObject({ percent: 20 });+ });+it('does not overwrite a failed job with a delayed successful action response', async () => {let resolveAction!: (value: { job: CreatorJob }) => void;const applyAction = vi.fn(() => new Promise<{ job: CreatorJob }>(resolve => { resolveAction = resolve; }));diff --git a/apps/web/src/features/dashboard/creator-session-store.tsx b/apps/web/src/features/dashboard/creator-session-store.tsxindex a43cf7b5..74dd9556 100644--- a/apps/web/src/features/dashboard/creator-session-store.tsx+++ b/apps/web/src/features/dashboard/creator-session-store.tsx@@ -507,7 +507,9 @@ export function CreatorSessionProvider(props: {if (next.id === current.id) {const stages = next.stages.map(stage => {const previous = current.stages.find(candidate => candidate.id === stage.id);- return previous && olderDownloadProgress(stage, previous) ? previous : stage;+ return previous+ ? olderDownloadProgress(stage, previous) ? previous : mergeMonotonicStageProgress(stage, previous)+ : stage;});if (stages.some((stage, index) => stage !== next.stages[index])) next = { ...next, stages };}@@ -1076,9 +1078,10 @@ function mergeCreatorEvent(job: CreatorJob, event: CreatorEventEnvelope): Creatoif (previous && olderDownloadProgress(stage, previous)) return job;if (previous !== undefined && terminalCreatorStage(previous.status)&& (stage.status === 'queued' || stage.status === 'running') && event.revision <= job.revision) return job;+ const mergedStage = previous ? mergeMonotonicStageProgress(stage, previous) : stage;const stages = index < 0? [...job.stages, stage]- : job.stages.map(candidate => candidate.id === stage.id ? stage : candidate);+ : job.stages.map(candidate => candidate.id === stage.id ? mergedStage : candidate);return {...job,stages,@@ -1115,6 +1118,30 @@ function olderDownloadProgress(incoming: CreatorStageRun, current: CreatorStageR&& (Number(incoming.progress.downloadProgressSequence) || 0) < (Number(current.progress.downloadProgressSequence) || 0);}+function mergeMonotonicStageProgress(incoming: CreatorStageRun, current: CreatorStageRun): CreatorStageRun {+ const currentPercent = current.progress.percent;+ const incomingPercent = incoming.progress.percent;+ const currentPhasePercent = current.progress.phasePercent;+ const incomingPhasePercent = incoming.progress.phasePercent;+ const keepPercent = typeof currentPercent === 'number' && Number.isFinite(currentPercent)+ && (incomingPercent === null+ || (typeof incomingPercent === 'number' && Number.isFinite(incomingPercent) && incomingPercent < currentPercent));+ const keepPhasePercent = current.progress.phase === 'normalizing_media'+ && incoming.progress.phase === 'normalizing_media'+ && typeof currentPhasePercent === 'number' && Number.isFinite(currentPhasePercent)+ && (incomingPhasePercent === null+ || (typeof incomingPhasePercent === 'number' && Number.isFinite(incomingPhasePercent) && incomingPhasePercent < currentPhasePercent));+ if (!keepPercent && !keepPhasePercent) return incoming;+ return {+ ...incoming,+ progress: {+ ...incoming.progress,+ ...(keepPercent ? { percent: currentPercent } : {}),+ ...(keepPhasePercent ? { phasePercent: currentPhasePercent } : {})+ }+ };+}+function mergeIssueIntoJob(job: CreatorJob, issue: OpenCreatorIssue): CreatorJob {const current = job.issues ?? [];return {diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.cssindex 0c8d84b4..65f57efb 100644--- a/apps/web/src/features/dashboard/dashboard.css+++ b/apps/web/src/features/dashboard/dashboard.css@@ -7093,6 +7093,12 @@flex: 0 0 auto;}+.creator-task-progress-phase {+ color: var(--subtle);+ font-size: 11px;+ font-variant-numeric: tabular-nums;+}+.creator-collaboration-stage-details {min-width: 0;display: grid;@@ -14335,6 +14341,21 @@cursor: pointer;}+.creator-collaboration-issue-actions .creator-collaboration-login-action {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ min-height: 28px;+ padding: 0 9px;+ border: 1px solid var(--border-hairline);+ border-radius: 6px;+ background: var(--surface);+ color: var(--text);+ font-size: 12px;+ font-weight: 620;+ text-decoration: none;+}+.creator-collaboration-stage[data-compact="true"] {gap: 0;padding: 8px 10px;diff --git a/apps/web/src/features/issues/issue-catalog.ts b/apps/web/src/features/issues/issue-catalog.tsindex fda1fb4e..fbc5a370 100644--- a/apps/web/src/features/issues/issue-catalog.ts+++ b/apps/web/src/features/issues/issue-catalog.ts@@ -81,6 +81,7 @@ function issuePublicFacts(issue: OpenCreatorIssue): PublicErrorFacts | undefined}function localizedIssueSummary(issue: OpenCreatorIssue, localize: LocalizeCopy): string {+ if (isOpenCreatorAuthIssue(issue.code)) return localize('OpenCreator 登录已过期。', 'OpenCreator sign-in has expired.', 'OpenCreator-inloggningen har gått ut.');if (issue.code === 'creator_codex_config_resynced') return localize('已重新同步本机 Codex 配置,请重试本次操作。', 'Local Codex configuration has been re-synchronized. Retry this operation.', 'Konfigurationen för lokala Codex har synkroniserats igen. Försök igen.');if (issue.code === 'creator_codex_config_check_failed') return localize('本机 Codex 配置检查失败,请检查配置文件和登录信息。', 'Local Codex configuration could not be checked. Check the configuration files and sign-in details.', 'Konfigurationen för lokala Codex kunde inte kontrolleras. Kontrollera konfigurationsfilerna och inloggningsuppgifterna.');if (issue.code === 'platform_request_signature_required') return localize('当前下载器尚未兼容抖音的请求签名校验。', 'The current downloader does not support Douyin request signature verification.', 'Den nuvarande nedladdaren stöder inte Douyins verifiering av begäranssignaturer.');@@ -221,6 +222,8 @@ export function issueConversationText(? 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_codex_config_resynced'? localize('配置已同步,请重新发送刚才的请求。', 'The configuration is synchronized. Send the previous request again.', 'Konfigurationen är synkroniserad. Skicka den föregående begäran igen.')+ : isOpenCreatorAuthIssue(issue.code)+ ? localize('请在账户设置中重新登录 OpenCreator 后重试。', 'Sign in to OpenCreator again in Account settings, then retry.', 'Logga in på OpenCreator igen under Kontoinställningar och försök sedan igen.'): issue.code === 'creator_codex_config_check_failed'? localize('请检查本机 Codex 的配置文件和登录信息,修正后重试。', 'Check local Codex configuration files and sign-in details, then retry.', 'Kontrollera konfigurationsfilerna och inloggningsuppgifterna för lokala Codex och försök igen.'): issue.code === 'creator_template_version_mismatch'@@ -253,6 +256,10 @@ export function issueConversationText(};}+function isOpenCreatorAuthIssue(code: string): boolean {+ return code === 'auth_required' || code === 'GATEWAY_AUTH_REQUIRED';+}+export function buildIssueAgentPrompt(issue: OpenCreatorIssue,question: string,diff --git a/runtime/krillinai/cmd/cli/main.go b/runtime/krillinai/cmd/cli/main.goindex ef893a57..2bdcd5fe 100644--- a/runtime/krillinai/cmd/cli/main.go+++ b/runtime/krillinai/cmd/cli/main.go@@ -34,6 +34,10 @@ func main() {writeAndExit(output, cli.Execute(context.Background(), nil, cmd))return}+ if cmd.Name == "compile-subtitles" {+ writeAndExit(output, cli.Execute(context.Background(), nil, cmd))+ return+ }if cmd.DryRun {writeAndExit(output, cli.Execute(context.Background(), nil, cmd))returndiff --git a/runtime/krillinai/config/config-example.toml b/runtime/krillinai/config/config-example.tomlindex 6d9a29fd..cc3c2e0f 100644--- a/runtime/krillinai/config/config-example.toml+++ b/runtime/krillinai/config/config-example.toml@@ -10,6 +10,7 @@target_language_first = true # 双语字幕中目标语言是否在上方,建议值:true(目标语言在上)short_subtitle_max_chars = 20 # 短字幕英文每行最大字符数,建议值:15-25proxy = "" # 网络代理地址,格式如http://127.0.0.1:7890,可不填+ youtube_proxy = "" # YouTube/yt-dlp 专用代理;留空时回退到 proxy[server]host = "127.0.0.1"diff --git a/runtime/krillinai/config/config.go b/runtime/krillinai/config/config.goindex b69c1fee..0b74641c 100644--- a/runtime/krillinai/config/config.go+++ b/runtime/krillinai/config/config.go@@ -8,6 +8,7 @@ import ("os""path/filepath""runtime"+ "strings""github.com/BurntSushi/toml""go.uber.org/zap"@@ -27,6 +28,7 @@ type App struct {TargetLanguageFirst bool `toml:"target_language_first"` // 双语字幕中目标语言是否在上ShortSubtitleMaxChars int `toml:"short_subtitle_max_chars"` // 短字幕原文按词分组的字符长度,独立于普通字幕的目标语言长度Proxy string `toml:"proxy"`+ YouTubeProxy string `toml:"youtube_proxy"`ParsedProxy *url.URL `toml:"-"`}@@ -39,6 +41,7 @@ type OpenaiCompatibleConfig struct {BaseUrl string `toml:"base_url"`ApiKey string `toml:"api_key"`Model string `toml:"model"`+ ModelName string `toml:"model_name"`OfficialModel string `toml:"official_model"`}@@ -336,6 +339,15 @@ func CheckBaseConfig() error {return err}+// YouTubeProxy returns the dedicated media proxy when provided. Older+// standalone KrillinAI configs only have app.proxy, so retain that fallback.+func YouTubeProxy() string {+ if proxy := strings.TrimSpace(Conf.App.YouTubeProxy); proxy != "" {+ return proxy+ }+ return strings.TrimSpace(Conf.App.Proxy)+}+// SaveConfig 保存配置到文件func SaveConfig() error {configPath := filepath.Join("config", "config.toml")diff --git a/runtime/krillinai/config/config_validation_test.go b/runtime/krillinai/config/config_validation_test.goindex 10320366..11ed1431 100644--- a/runtime/krillinai/config/config_validation_test.go+++ b/runtime/krillinai/config/config_validation_test.go@@ -22,6 +22,22 @@ func TestBaseConfigDoesNotRequireTranscriptionCredentials(t *testing.T) {}}+func TestYouTubeProxyPrefersDedicatedProxyAndFallsBackToAppProxy(t *testing.T) {+ previous := Conf+ t.Cleanup(func() { Conf = previous })++ Conf.App.Proxy = "http://fallback.example:7890"+ Conf.App.YouTubeProxy = ""+ if got := YouTubeProxy(); got != Conf.App.Proxy {+ t.Fatalf("YouTubeProxy() fallback = %q, want %q", got, Conf.App.Proxy)+ }++ Conf.App.YouTubeProxy = " http://media.example:7891 "+ if got := YouTubeProxy(); got != "http://media.example:7891" {+ t.Fatalf("YouTubeProxy() dedicated = %q, want trimmed dedicated proxy", got)+ }+}+func TestValidateTranscriptionConfigAcceptsTinyWhisperCpp(t *testing.T) {previous := Conft.Cleanup(func() { Conf = previous })diff --git a/runtime/krillinai/docs/paired-subtitle-translation.md b/runtime/krillinai/docs/paired-subtitle-translation.mdindex 4bea6b7c..87e21a9e 100644--- a/runtime/krillinai/docs/paired-subtitle-translation.md+++ b/runtime/krillinai/docs/paired-subtitle-translation.md@@ -56,7 +56,7 @@ VTT/SRT 文本读取允许单行最多 4 MiB,之后才进入上述模型输入审核请求失败、限流、截断、坏 JSON、超时及无效修正均保留已完成译文;用户取消仍终止任务。有效修正原子更新单句检查点,音频路径同时更新最终聚合检查点。模型证据并不构成语义正确性的确定保证,仍需检查实际最终字幕,不能用自评分替代质量判断。-DeepSeek V4 的 `deepseek-flash`、`deepseek-v4-flash` 和 `deepseek-v4-pro` 使用 `temperature=0.2`,减少结构和分段的随机变化,并发送 `reasoning_effort=none`,避免推理耗尽字幕 JSON 的输出预算;实测其低强度推理也可能耗尽预算。其他模型保留默认采样,不附加这些参数。接口返回 `finish_reason=length` 时明确报 `llm_translation_truncated`,不把被截断的内容当成完整译文或普通空响应。+DeepSeek V4 Flash 系列(包括 `deepseek-flash`、`deepseek-v4-flash`、`deepseek-v4.1-flash` 及带供应商前缀的模型 ID)和 `deepseek-v4-pro` 使用 `temperature=0.2`,减少结构和分段的随机变化,并发送 `reasoning_effort=none`,避免推理耗尽字幕 JSON 的输出预算;实测其低强度推理也可能耗尽预算。其他模型保留默认采样,不附加这些参数。接口返回 `finish_reason=length` 时明确报 `llm_translation_truncated`,不把被截断的内容当成完整译文或普通空响应。## 时间与产物diff --git a/runtime/krillinai/internal/cli/commands.go b/runtime/krillinai/internal/cli/commands.goindex 546e8c54..be5f777c 100644--- a/runtime/krillinai/internal/cli/commands.go+++ b/runtime/krillinai/internal/cli/commands.go@@ -8,6 +8,7 @@ import ("io""krillin-ai/config""krillin-ai/internal/pipeline"+ krillinservice "krillin-ai/internal/service"subtitlestyle "krillin-ai/internal/subtitle_style""krillin-ai/internal/ttsprovider""krillin-ai/internal/types"@@ -53,11 +54,17 @@ type Command struct {TTS pipeline.TTSRequestSpeech SpeechRequestRender pipeline.RenderRequest+ Compile CompileSubtitleRequestCover pipeline.CoverRequestPipeline pipeline.PipelineRequestVoices VoicesRequest}+type CompileSubtitleRequest struct {+ Input string+ Output string+}+type VoicesRequest struct {Provider string}@@ -92,6 +99,8 @@ func Parse(args []string) (Command, error) {return parseRender(name, args[1:], true)case "render-vertical":return parseRender(name, args[1:], false)+ case "compile-subtitles":+ return parseCompileSubtitles(name, args[1:])case "pipeline":return parsePipeline(name, args[1:])case "cover":@@ -174,6 +183,7 @@ Flags:--video <file> Input video--audio <file> Optional input audio--subtitle <file> Subtitle file to burn in+ --subtitle-document <file> Structured subtitle render document JSON--subtitle-style-file <file> JSON subtitle style override file--line-mode <mode> target-only, bilingual-target-top, or bilingual-target-bottom--preview-width <px> --preview-height <px> Render a transparent subtitle PNG@@ -193,6 +203,7 @@ Flags:--video <file> Input video--audio <file> Optional input audio--subtitle <file> Subtitle file to burn in+ --subtitle-document <file> Structured subtitle render document JSON--subtitle-style-file <file> JSON subtitle style override file--line-mode <mode> target-only, bilingual-target-top, or bilingual-target-bottom--preview-width <px> --preview-height <px> Render a transparent subtitle PNG@@ -203,6 +214,17 @@ Flags:--minor-title <text> Vertical video minor title--dry-run Validate command without external calls-h, --help Show this help+`+ case "compile-subtitles":+ return `Usage:+ krillinai-cli compile-subtitles --input <document.json> --output <subtitles.ass> [flags]++Flags:+ --input <file> Subtitle render document JSON+ --output <file> Output ASS subtitle file+ --subtitle-style-file <file> JSON subtitle style override file+ --dry-run Validate command without external calls+ -h, --help Show this help`case "pipeline":return `Usage:@@ -251,6 +273,7 @@ Commands:speech Generate audio from plain textrender-horizontal Render landscape subtitle or dubbed videosrender-vertical Render portrait subtitle or dubbed videos+ compile-subtitles Compile a subtitle render document to ASSpipeline Plan or run multi-stage workflows when supportedcover Generate a cover image from a promptvoices List available TTS voice codes@@ -287,6 +310,13 @@ func Execute(ctx context.Context, svc pipeline.StageService, cmd Command) pipelicmd.Render.SubtitleStyle = styleresp, err := pipeline.Render(ctx, svc, cmd.Render)return responseWithError(resp, err)+ case "compile-subtitles":+ style, err := loadSubtitleStyleForCLI(cmd.SubtitleStyleFile)+ if err != nil {+ return styleLoadFailure(pipeline.StageRenderHorizontal, "", "", err)+ }+ err = krillinservice.CompileSubtitleDocument(cmd.Compile.Input, cmd.Compile.Output, style)+ return responseWithError(pipeline.Response{OK: err == nil, Stage: pipeline.StageRenderHorizontal}, err)case "cover":resp, err := pipeline.GenerateCover(ctx, svc, cmd.Cover)return responseWithError(resp, err)@@ -598,6 +628,7 @@ func parseRender(name string, args []string, horizontal bool) (Command, error) {mediaWorkdir := fs.String("media-workdir", "", "shared source video cache")audio := fs.String("audio", "", "input audio")subtitle := fs.String("subtitle", "", "subtitle")+ subtitleDocument := fs.String("subtitle-document", "", "structured subtitle render document JSON")dubbed := fs.Bool("dubbed", false, "render dubbed video")majorTitle := fs.String("major-title", "", "vertical major title")minorTitle := fs.String("minor-title", "", "vertical minor title")@@ -629,6 +660,7 @@ func parseRender(name string, args []string, horizontal bool) (Command, error) {MediaWorkdir: *mediaWorkdir,Audio: *audio,Subtitle: *subtitle,+ SubtitleDocument: *subtitleDocument,Horizontal: horizontal,Dubbed: *dubbed,MajorTitle: *majorTitle,@@ -642,6 +674,35 @@ func parseRender(name string, args []string, horizontal bool) (Command, error) {}, nil}+func parseCompileSubtitles(name string, args []string) (Command, error) {+ if hasHelpArg(args) {+ return Command{Name: name, Help: true}, nil+ }+ fs := newFlagSet(name)+ input := fs.String("input", "", "subtitle render document JSON")+ output := fs.String("output", "", "output ASS subtitle file")+ subtitleStyleFile := fs.String("subtitle-style-file", "", "subtitle style JSON file")+ dryRun := fs.Bool("dry-run", false, "validate command without running external services")+ if err := fs.Parse(args); err != nil {+ return Command{}, err+ }+ if fs.NArg() != 0 {+ return Command{}, errors.New("compile-subtitles does not accept positional arguments")+ }+ if strings.TrimSpace(*input) == "" || strings.TrimSpace(*output) == "" {+ return Command{}, errors.New("compile-subtitles requires --input and --output")+ }+ return Command{+ Name: name,+ DryRun: *dryRun,+ SubtitleStyleFile: *subtitleStyleFile,+ Compile: CompileSubtitleRequest{+ Input: *input,+ Output: *output,+ },+ }, nil+}+func parsePipeline(name string, args []string) (Command, error) {if hasHelpArg(args) {return Command{Name: name, Help: true}, nil@@ -696,6 +757,11 @@ func dryRun(cmd Command) pipeline.Response {return styleLoadFailure(pipeline.StageRenderVertical, cmd.Render.Workdir, cmd.Render.TaskID, err)}return dryRunResponse(pipeline.StageRenderVertical, cmd.Render.Workdir, cmd.Render.TaskID)+ case "compile-subtitles":+ if _, err := loadSubtitleStyleForCLI(cmd.SubtitleStyleFile); err != nil {+ return styleLoadFailure(pipeline.StageRenderHorizontal, "", "", err)+ }+ return dryRunResponse(pipeline.StageRenderHorizontal, "", "")case "cover":return dryRunManifest(cmd.Cover.Workdir, cmd.Cover.TaskID, pipeline.StageCover, func(m *pipeline.Manifest) {m.Outputs.FinalCoverPrompt = m.Outputs.FinalCoverPromptdiff --git a/runtime/krillinai/internal/cli/commands_test.go b/runtime/krillinai/internal/cli/commands_test.goindex cba47a6b..bea2c4df 100644--- a/runtime/krillinai/internal/cli/commands_test.go+++ b/runtime/krillinai/internal/cli/commands_test.go@@ -150,6 +150,22 @@ func TestParseRenderCommandAcceptsSubtitleStyleFile(t *testing.T) {}}+func TestParseRenderCommandAcceptsSubtitleDocument(t *testing.T) {+ cmd, err := Parse([]string{+ "render-horizontal",+ "--workdir", "tasks/demo",+ "--video", "origin.mp4",+ "--subtitle", "bilingual.srt",+ "--subtitle-document", "subtitle-document.json",+ })+ if err != nil {+ t.Fatalf("Parse() error = %v", err)+ }+ if cmd.Render.SubtitleDocument != "subtitle-document.json" {+ t.Fatalf("SubtitleDocument = %q", cmd.Render.SubtitleDocument)+ }+}+func TestParseRenderPreviewAndLineMode(t *testing.T) {cmd, err := Parse([]string{"render-vertical", "--workdir", "preview", "--subtitle", "preview.srt", "--line-mode", "bilingual-target-bottom", "--preview-width", "540", "--preview-height", "960"})if err != nil {diff --git a/runtime/krillinai/internal/pipeline/render.go b/runtime/krillinai/internal/pipeline/render.goindex 57abdb39..a5758c9d 100644--- a/runtime/krillinai/internal/pipeline/render.go+++ b/runtime/krillinai/internal/pipeline/render.go@@ -19,6 +19,7 @@ type RenderRequest struct {ReportProgress ProgressReporterAudio stringSubtitle string+ SubtitleDocument stringHorizontal boolDubbed boolMajorTitle string@@ -85,15 +86,16 @@ func Render(ctx context.Context, svc StageService, req RenderRequest) (Response,}forwardTaskProgress(stepParam.TaskPtr, req.ReportProgress, nil)rendered, err := svc.RenderVideo(ctx, service.RenderVideoRequest{- Workdir: req.Workdir,- InputVideo: inputVideo,- AudioFile: req.Audio,- SubtitleFile: subtitle,- OutputFile: output,- Horizontal: req.Horizontal,- StepParam: stepParam,- PreviewWidth: req.PreviewWidth,- PreviewHeight: req.PreviewHeight,+ Workdir: req.Workdir,+ InputVideo: inputVideo,+ AudioFile: req.Audio,+ SubtitleFile: subtitle,+ SubtitleDocument: req.SubtitleDocument,+ OutputFile: output,+ Horizontal: req.Horizontal,+ StepParam: stepParam,+ PreviewWidth: req.PreviewWidth,+ PreviewHeight: req.PreviewHeight,})if err != nil {return failRenderStage(req, manifest, renderStage(req), "render_video_failed", err)diff --git a/runtime/krillinai/internal/pipeline/render_test.go b/runtime/krillinai/internal/pipeline/render_test.goindex 51f3d4e1..bcef920c 100644--- a/runtime/krillinai/internal/pipeline/render_test.go+++ b/runtime/krillinai/internal/pipeline/render_test.go@@ -75,6 +75,26 @@ func TestRenderPassesSubtitleStyleToService(t *testing.T) {}}+func TestRenderPassesSubtitleDocumentToService(t *testing.T) {+ dir := t.TempDir()+ fake := &renderFakeService{}+ req := RenderRequest{+ Workdir: dir,+ TaskID: "demo",+ Video: "origin_video.mp4",+ Subtitle: "bilingual_srt.srt",+ SubtitleDocument: "subtitle-document.json",+ Horizontal: true,+ }++ if _, err := Render(context.Background(), fake, req); err != nil {+ t.Fatalf("Render() error = %v", err)+ }+ if fake.lastRender.SubtitleDocument != req.SubtitleDocument {+ t.Fatalf("SubtitleDocument = %q, want %q", fake.lastRender.SubtitleDocument, req.SubtitleDocument)+ }+}+func TestRenderVerticalBilingualOutputName(t *testing.T) {dir := t.TempDir()fake := &renderFakeService{}diff --git a/runtime/krillinai/internal/service/get_video_info.go b/runtime/krillinai/internal/service/get_video_info.goindex c7328da9..071b287d 100644--- a/runtime/krillinai/internal/service/get_video_info.go+++ b/runtime/krillinai/internal/service/get_video_info.go@@ -23,9 +23,9 @@ func (s Service) getVideoInfo(ctx context.Context, stepParam *types.SubtitleTaskdescriptionCmdArgs := []string{"--no-playlist", "--skip-download", "--encoding", "utf-8", "--get-description", stepParam.Link}titleCmdArgs = appendCookiesArgs(titleCmdArgs, youtubeCookiesPath)descriptionCmdArgs = appendCookiesArgs(descriptionCmdArgs, youtubeCookiesPath)- if config.Conf.App.Proxy != "" {- titleCmdArgs = append(titleCmdArgs, "--proxy", config.Conf.App.Proxy)- descriptionCmdArgs = append(descriptionCmdArgs, "--proxy", config.Conf.App.Proxy)+ if proxy := config.YouTubeProxy(); proxy != "" {+ titleCmdArgs = append(titleCmdArgs, "--proxy", proxy)+ descriptionCmdArgs = append(descriptionCmdArgs, "--proxy", proxy)}if storage.FfmpegPath != "ffmpeg" {titleCmdArgs = append(titleCmdArgs, "--ffmpeg-location", storage.FfmpegPath)diff --git a/runtime/krillinai/internal/service/link2file.go b/runtime/krillinai/internal/service/link2file.goindex 1e131794..4303efcc 100644--- a/runtime/krillinai/internal/service/link2file.go+++ b/runtime/krillinai/internal/service/link2file.go@@ -66,8 +66,8 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskSt"-o", audioPath,stepParam.Link,}- if config.Conf.App.Proxy != "" {- cmdArgs = append(cmdArgs, "--proxy", config.Conf.App.Proxy)+ if proxy := config.YouTubeProxy(); proxy != "" {+ cmdArgs = append(cmdArgs, "--proxy", proxy)}cmdArgs = appendCookiesArgs(cmdArgs, youtubeCookiesPath)if storage.FfmpegPath != "ffmpeg" {diff --git a/runtime/krillinai/internal/service/paired_translation_checkpoint_length_test.go b/runtime/krillinai/internal/service/paired_translation_checkpoint_length_test.goindex f6185453..241f34b1 100644--- a/runtime/krillinai/internal/service/paired_translation_checkpoint_length_test.go+++ b/runtime/krillinai/internal/service/paired_translation_checkpoint_length_test.go@@ -173,8 +173,12 @@ func TestCheckpointLengthOldFallbackExportsSRTDespiteRepairFailure(t *testing.T)wantCues = 4} else if mode == "invalid_json" {wantCalls = 3+ wantCues = 3+ } else if mode == "network" {+ wantCues = 3} else if mode == "budget" {wantCalls = translationSentenceRequestLimit+ wantCues = 3}if calls != wantCalls || len(cues) != wantCues {t.Fatalf("请求预算或交付条数错误: calls=%d cues=%d", calls, len(cues))diff --git a/runtime/krillinai/internal/service/paired_translation_length_repair.go b/runtime/krillinai/internal/service/paired_translation_length_repair.goindex 0059788d..d729297f 100644--- a/runtime/krillinai/internal/service/paired_translation_length_repair.go+++ b/runtime/krillinai/internal/service/paired_translation_length_repair.go@@ -8,6 +8,8 @@ import ("krillin-ai/pkg/util""strconv""strings"++ "github.com/clipperhouse/uax29/v2/graphemes")//go:embed paired_translation_length_repair.txt@@ -23,6 +25,79 @@ func longestPairedSegment(sentence pairedSentence) int {return longest}+// mechanicallySplitPairedText is the last layout fallback after the complete+// translation has been frozen. It keeps both authoritative strings intact and+// cuts only at grapheme boundaries; natural phrase boundaries are deliberately+// not part of this fallback's contract.+func mechanicallySplitPairedText(source, target string, limit int) ([]pairedTranslationSegment, bool) {+ if limit < 1 || !hasSubtitleContent(source) || !hasSubtitleContent(target) {+ return nil, false+ }+ parts := max(2, max((subtitleTargetLength(source)+limit-1)/limit, (subtitleTargetLength(target)+limit-1)/limit))+ sources, ok := mechanicallySplitText(source, parts, limit)+ if !ok {+ return nil, false+ }+ targets, ok := mechanicallySplitText(target, parts, limit)+ if !ok {+ return nil, false+ }+ result := make([]pairedTranslationSegment, parts)+ for i := range result {+ result[i] = pairedTranslationSegment{Source: sources[i], Target: targets[i]}+ }+ return result, true+}++func mechanicallySplitText(text string, parts, limit int) ([]string, bool) {+ if parts < 2 {+ return nil, false+ }+ boundaries := []int{0}+ iter := graphemes.FromString(text)+ for iter.Next() {+ boundaries = append(boundaries, iter.End())+ }+ total := len(boundaries) - 1+ if total < parts || total > parts*limit {+ return nil, false+ }+ cuts := make([]int, parts+1)+ cuts[0], cuts[parts] = 0, total+ previous := 0+ for part := 1; part < parts; part++ {+ minimum := previous + 1+ maximum := total - (parts - part)+ desired := total * part / parts+ best := -1+ bestDistance := total + 1+ for candidate := minimum; candidate <= maximum; candidate++ {+ if candidate-previous > limit || !hasSubtitleContent(text[boundaries[previous]:boundaries[candidate]]) {+ continue+ }+ distance := candidate - desired+ if distance < 0 {+ distance = -distance+ }+ if distance < bestDistance {+ best, bestDistance = candidate, distance+ }+ }+ if best < 0 {+ return nil, false+ }+ cuts[part], previous = best, best+ }+ result := make([]string, parts)+ for i := range result {+ result[i] = text[boundaries[cuts[i]]:boundaries[cuts[i+1]]]+ if !hasSubtitleContent(result[i]) || subtitleTargetLength(result[i]) > limit {+ return nil, false+ }+ }+ return result, true+}+// 修复只插入切口;不审核或重新生成已冻结的译文。func validatePairedLengthRepair(item pairedTranslationOutputSentence, source pairedTranslationSource) (pairedSentence, error) {result := pairedSentence{ID: item.ID, FullSource: source.Text, FullTarget: source.TargetText}@@ -144,11 +219,43 @@ func (t *Translator) repairPairedLengths(ctx context.Context, input pairedTransl}feedback = ""if len(issues) > 0 {+ t.translationNotice(fmt.Sprintf("第%s句局部拆分校验失败:%s", source.ID, subtitleTextPreview(strings.Join(issues, "\n"), 1500)))feedback = "\nPrevious local validation issues:\n" + subtitleTextPreview(strings.Join(issues, "\n"), 1500)}}if !pairedSentenceWithinLimit(sentence, input.MaxTargetChars) {- t.translationNotice(fmt.Sprintf("第%s句局部拆分未全部完成;已保留合格字幕和完整原译文,仅剩余超长对按单行交付", source.ID))+ mechanical := sentence+ mechanical.Source, mechanical.Target = nil, nil+ mechanicalApplied := false+ for i := range sentence.Source {+ if max(subtitleTargetLength(sentence.Source[i]), subtitleTargetLength(sentence.Target[i])) <= acceptedLimit {+ mechanical.Source = append(mechanical.Source, sentence.Source[i])+ mechanical.Target = append(mechanical.Target, sentence.Target[i])+ continue+ }+ parts, ok := mechanicallySplitPairedText(sentence.Source[i], sentence.Target[i], acceptedLimit)+ if !ok {+ mechanical.Source = append(mechanical.Source, sentence.Source[i])+ mechanical.Target = append(mechanical.Target, sentence.Target[i])+ continue+ }+ mechanicalApplied = true+ for _, part := range parts {+ mechanical.Source = append(mechanical.Source, part.Source)+ mechanical.Target = append(mechanical.Target, part.Target)+ }+ }+ if mechanicalApplied {+ mechanical.LayoutFallback = true+ if err := save(mechanical, false); err != nil {+ return sentence, err+ }+ sentence = mechanical+ t.translationNotice(fmt.Sprintf("第%s句模型拆分未通过硬校验,已按字素边界机械拆分;完整译文保留,语义质量降级", source.ID))+ }+ }+ if !pairedSentenceWithinLimit(sentence, input.MaxTargetChars) {+ t.translationNotice(fmt.Sprintf("第%s句局部拆分仍无法全部满足长度上限;已保留完整译文并按单行交付", source.ID))}return sentence, nil}diff --git a/runtime/krillinai/internal/service/paired_translation_length_repair_test.go b/runtime/krillinai/internal/service/paired_translation_length_repair_test.goindex 933b177d..d2ed7986 100644--- a/runtime/krillinai/internal/service/paired_translation_length_repair_test.go+++ b/runtime/krillinai/internal/service/paired_translation_length_repair_test.go@@ -160,18 +160,36 @@ func TestPairedLengthRepairDoesNotCollapseAfterInvalidRepair(t *testing.T) {if mode == "network_error" {wantCalls = 2}- if err != nil || calls != wantCalls || len(final.Source) != len(pairs) || !final.LayoutFallback {- t.Fatalf("局部失败被放大为整组回退: calls=%d final=%+v err=%v", calls, final, err)+ if err != nil || calls != wantCalls || len(final.Source) != 4 || !final.LayoutFallback || !pairedSentenceWithinLimit(final, 60) || !pairedSentenceSegmentsValid(final, input.Sentences[0].Text) {+ t.Fatalf("局部失败未按优先级机械拆短: calls=%d final=%+v err=%v", calls, final, err)}- for i, pair := range pairs {- if final.Source[i] != pair.Source || final.Target[i] != pair.Target {- t.Fatalf("失败回复覆盖了原有字幕: %+v", final)- }+ if final.Source[0] != pairs[0].Source || final.Source[3] != pairs[2].Source || final.Target[0] != pairs[0].Target || final.Target[3] != pairs[2].Target {+ t.Fatalf("机械兜底改动了已合格字幕: %+v", final)}})}}+func TestPairedLengthRepairMechanicalFallbackPreservesBothTexts(t *testing.T) {+ const source = "Everything at level four, including Pride and Prejudice, East of Eden, The Count of Monte Cristo, and The Goldfinch, could easily be read by someone in late high school, but of course, the older you get, the more you'll get out of these."+ const target = "第四级的所有作品,包括《傲慢与偏见》《伊甸之东》《基督山伯爵》和《金翅雀》,高中后期的人都能轻松读懂,但当然,你年纪越大,从这些作品中获得的收获就越多。"+ parts, ok := mechanicallySplitPairedText(source, target, 65)+ if !ok || len(parts) < 2 {+ t.Fatalf("机械兜底未能生成配对片段: ok=%v parts=%+v", ok, parts)+ }+ var sources, targets []string+ for _, part := range parts {+ sources = append(sources, part.Source)+ targets = append(targets, part.Target)+ if subtitleTargetLength(part.Source) > 65 || subtitleTargetLength(part.Target) > 65 || hasSubtitleLineBreak(part.Source) || hasSubtitleLineBreak(part.Target) {+ t.Fatalf("机械兜底产生超长或折行片段: %+v", part)+ }+ }+ if !subtitleSegmentsPreserveText(source, sources) || !subtitleSegmentsPreserveText(target, targets) || !subtitleSegmentsHaveSafeBoundariesInText(source, sources) || !subtitleSegmentsHaveSafeBoundariesInText(target, targets) {+ t.Fatalf("机械兜底改动了完整文本: sources=%q targets=%q", sources, targets)+ }+}+func TestPairedLengthRepairBatchesFailuresAndRetriesOnlyRemainingPairs(t *testing.T) {pairs := append(lengthRepairTestPairs(), pairedTranslationSegment{Source: "and I just have the name of the ingredient with a little emoji that most closely correlates to it ",diff --git a/runtime/krillinai/internal/service/render_stage.go b/runtime/krillinai/internal/service/render_stage.goindex 25ea6d44..84d8f8be 100644--- a/runtime/krillinai/internal/service/render_stage.go+++ b/runtime/krillinai/internal/service/render_stage.go@@ -17,15 +17,16 @@ import ()type RenderVideoRequest struct {- Workdir string- InputVideo string- AudioFile string- SubtitleFile string- OutputFile string- Horizontal bool- StepParam *types.SubtitleTaskStepParam- PreviewWidth int- PreviewHeight int+ Workdir string+ InputVideo string+ AudioFile string+ SubtitleFile string+ SubtitleDocument string+ OutputFile string+ Horizontal bool+ StepParam *types.SubtitleTaskStepParam+ PreviewWidth int+ PreviewHeight int}type resolutionProbe func(inputVideo string) (int, int, error)@@ -132,7 +133,11 @@ func renderSubtitleFile(ctx context.Context, req RenderVideoRequest) (string, erif err := validatePackagedSubtitleFonts(req.StepParam.SubtitleStyle); err != nil {return "", fmt.Errorf("renderSubtitleFile subtitle fonts error: %w", err)}- if err := srtToAss(req.SubtitleFile, assPath, req.Horizontal, req.StepParam); err != nil {+ if req.SubtitleDocument != "" {+ if err := CompileSubtitleDocument(req.SubtitleDocument, assPath, req.StepParam.SubtitleStyle); err != nil {+ return "", fmt.Errorf("renderSubtitleFile compile subtitle document error: %w", err)+ }+ } else if err := srtToAss(req.SubtitleFile, assPath, req.Horizontal, req.StepParam); err != nil {return "", fmt.Errorf("renderSubtitleFile srtToAss error: %w", err)}args, _ := buildEmbedSubtitleArgs(req)diff --git a/runtime/krillinai/internal/service/subtitle_compile.go b/runtime/krillinai/internal/service/subtitle_compile.gonew file mode 100644index 00000000..674bcb4a--- /dev/null+++ b/runtime/krillinai/internal/service/subtitle_compile.go@@ -0,0 +1,107 @@+package service++import (+ "encoding/json"+ "fmt"+ subtitlestyle "krillin-ai/internal/subtitle_style"+ "os"+ "path/filepath"+ "strings"+ "time"+)++type subtitleRenderDocument struct {+ Width int `json:"width"`+ Height int `json:"height"`+ Horizontal bool `json:"horizontal"`+ Bilingual bool `json:"bilingual"`+ SubtitlePosition string `json:"subtitlePosition"`+ // The daemon includes the style in its request document for cache/debug+ // completeness. The compiled style is supplied separately via the CLI flag.+ SubtitleStyle json.RawMessage `json:"subtitleStyle,omitempty"`+ MajorTitle string `json:"majorTitle,omitempty"`+ MinorTitle string `json:"minorTitle,omitempty"`+ Cues []subtitleRenderCue `json:"cues"`+}++type subtitleRenderCue struct {+ StartMs int `json:"startMs"`+ EndMs int `json:"endMs"`+ Text string `json:"text"`+ SourceText string `json:"sourceText,omitempty"`+}++// CompileSubtitleDocument converts the structured Creator preview input to the+// same ASS track used by the video renderer, without requiring a media input.+func CompileSubtitleDocument(input, output string, styleSet *subtitlestyle.StyleSet) error {+ data, err := os.ReadFile(input)+ if err != nil {+ return fmt.Errorf("read subtitle render document: %w", err)+ }+ var document subtitleRenderDocument+ decoder := json.NewDecoder(strings.NewReader(string(data)))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&document); err != nil {+ return fmt.Errorf("parse subtitle render document: %w", err)+ }+ if document.Width < 32 || document.Height < 32 {+ return fmt.Errorf("subtitle render dimensions must be at least 32x32")+ }+ if document.SubtitlePosition != "top" && document.SubtitlePosition != "bottom" {+ return fmt.Errorf("unsupported subtitle position: %s", document.SubtitlePosition)+ }+ if len(document.Cues) == 0 {+ return fmt.Errorf("subtitle render document has no cues")+ }+ if styleSet == nil {+ styleSet = subtitlestyle.DefaultStyleSet()+ }+ if err := subtitlestyle.Validate(styleSet); err != nil {+ return fmt.Errorf("subtitle style invalid: %w", err)+ }++ screenStyle := styleSet.Vertical+ if document.Horizontal {+ screenStyle = styleSet.Horizontal+ }+ majorPrefix := fmt.Sprintf("{\\rMajor}{\\an%d}%s", subtitlestyle.Alignment(screenStyle.Major), subtitlestyle.DialogueTags(screenStyle.Major))+ minorPrefix := fmt.Sprintf("{\\rMinor}{\\an%d}%s", subtitlestyle.Alignment(screenStyle.Minor), subtitlestyle.DialogueTags(screenStyle.Minor))+ firstStyle, secondStyle := screenStyle.Major, screenStyle.Minor+ firstPrefix, secondPrefix := majorPrefix, minorPrefix+ if document.SubtitlePosition == "bottom" {+ firstStyle, secondStyle = screenStyle.Minor, screenStyle.Major+ firstPrefix, secondPrefix = minorPrefix, majorPrefix+ }+ fallbacks := packagedSubtitleFallbacks()+ var ass strings.Builder+ ass.WriteString(strings.Replace(subtitlestyle.BuildAssHeader(styleSet, document.Horizontal), "[Script Info]", "[Script Info]\nWrapStyle: 2", 1))+ for index, cue := range document.Cues {+ if cue.StartMs < 0 || cue.EndMs <= cue.StartMs {+ return fmt.Errorf("invalid subtitle cue %d timing", index+1)+ }+ start := formatTimestamp(time.Duration(cue.StartMs) * time.Millisecond)+ end := formatTimestamp(time.Duration(cue.EndMs) * time.Millisecond)+ var text string+ if document.Bilingual && cue.SourceText != "" {+ first, second := cue.Text, cue.SourceText+ text = firstPrefix + subtitleFallbackFontTags(assText(first), firstStyle.FontName, fallbacks)+ text += `\N` + secondPrefix + subtitleFallbackFontTags(assText(second), secondStyle.FontName, fallbacks)+ } else {+ text = majorPrefix + subtitleFallbackFontTags(assText(cue.Text), screenStyle.Major.FontName, fallbacks)+ }+ ass.WriteString(fmt.Sprintf("Dialogue: 0,%s,%s,Major,,0,0,0,,%s\n", start, end, text))+ }+ if err := os.MkdirAll(filepath.Dir(output), 0755); err != nil {+ return fmt.Errorf("create subtitle output directory: %w", err)+ }+ if err := os.WriteFile(output, []byte(ass.String()), 0600); err != nil {+ return fmt.Errorf("write subtitle ASS: %w", err)+ }+ return nil+}++func assText(value string) string {+ value = strings.ReplaceAll(value, "\r\n", "\n")+ value = strings.ReplaceAll(value, "\r", "\n")+ return strings.ReplaceAll(value, "\n", `\N`)+}diff --git a/runtime/krillinai/internal/service/youtube_subtitle.go b/runtime/krillinai/internal/service/youtube_subtitle.goindex 6b8e3ff3..13b4fc07 100644--- a/runtime/krillinai/internal/service/youtube_subtitle.go+++ b/runtime/krillinai/internal/service/youtube_subtitle.go@@ -351,8 +351,8 @@ func youtubeSubtitleCommandArgs(track youtubeSubtitleTrack, outputPattern string}func appendYouTubeAccessArgs(cmdArgs []string) []string {- if config.Conf.App.Proxy != "" {- cmdArgs = append(cmdArgs, "--proxy", config.Conf.App.Proxy)+ if proxy := config.YouTubeProxy(); proxy != "" {+ cmdArgs = append(cmdArgs, "--proxy", proxy)}return appendCookiesArgs(cmdArgs, youtubeCookiesPath)}diff --git a/runtime/krillinai/pkg/openai/openai.go b/runtime/krillinai/pkg/openai/openai.goindex d5b348d4..9f6498df 100644--- a/runtime/krillinai/pkg/openai/openai.go+++ b/runtime/krillinai/pkg/openai/openai.go@@ -9,9 +9,13 @@ import ("go.uber.org/zap""krillin-ai/config""krillin-ai/log"+ "regexp""strings")+var deepSeekV41FlashModelPattern = regexp.MustCompile(`^(?:[^/]+/)?deepseek-v4(?:[.-]1)-flash(?:-[0-9]+)?$`)+var deepSeekV4ProModelPattern = regexp.MustCompile(`^(?:[^/]+/)?deepseek-v4-pro$`)+func (c *Client) ChatCompletion(query string) (string, error) {return c.ChatCompletionContext(context.Background(), query)}@@ -47,8 +51,8 @@ func (c *Client) ChatCompletionContextWithMaxTokens(ctx context.Context, query sResponseFormat: responseFormat,}// DeepSeek V4 的推理可能耗尽字幕 JSON 的输出预算。- switch strings.ToLower(strings.TrimSpace(req.Model)) {- case "deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro":+ modelNames := []string{req.Model, config.Conf.Llm.ModelName}+ if disablesReasoning(modelNames...) {req.ReasoningEffort = "none"req.Temperature = 0.2}@@ -68,6 +72,16 @@ func (c *Client) ChatCompletionContextWithMaxTokens(ctx context.Context, query sreturn response.Choices[0].Message.Content, nil}+func disablesReasoning(modelNames ...string) bool {+ for _, modelName := range modelNames {+ normalized := strings.ToLower(strings.TrimSpace(modelName))+ if deepSeekV41FlashModelPattern.MatchString(normalized) || deepSeekV4ProModelPattern.MatchString(normalized) {+ return true+ }+ }+ return false+}+func normalizeChatCompletionError(err error) error {if errors.Is(err, context.DeadlineExceeded) {return fmt.Errorf("llm_translation_timeout: %w", err)diff --git a/runtime/krillinai/pkg/openai/openai_test.go b/runtime/krillinai/pkg/openai/openai_test.goindex 6c826ddf..9b76da68 100644--- a/runtime/krillinai/pkg/openai/openai_test.go+++ b/runtime/krillinai/pkg/openai/openai_test.go@@ -72,10 +72,31 @@ func TestChatCompletionRejectsEmptyResponse(t *testing.T) {}func TestChatCompletionDisablesDeepSeekV4Thinking(t *testing.T) {- for _, model := range []string{"deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-chat", "test-model"} {- t.Run(model, func(t *testing.T) {+ for _, testCase := range []struct {+ model string+ modelName string+ want string+ }{+ {model: "deepseek-v4.1-flash", want: "none"},+ {model: "deepseek-v4-1-flash-261017", want: "none"},+ {model: "88api/deepseek-v4.1-flash", want: "none"},+ {model: "deepseek-v4-pro", want: "none"},+ {model: "88api/deepseek-v4-pro", want: "none"},+ {model: "another-provider/deepseek-v4-pro", want: "none"},+ {model: "oc_708ac39a01ac1a51", modelName: "deepseek-v4.1-flash", want: "none"},+ {model: "deepseek-v4-flash"},+ {model: "deepseek-flash"},+ {model: "deepseek-chat"},+ {model: "88api/gpt-5.5"},+ {model: "88api/kimi-k3"},+ {model: "grok-4.7"},+ {model: "gpt-6-luna"},+ {model: "test-model"},+ } {+ t.Run(testCase.model+"/"+testCase.modelName, func(t *testing.T) {setTestModel(t)- config.Conf.Llm.Model = model+ config.Conf.Llm.Model = testCase.model+ config.Conf.Llm.ModelName = testCase.modelNameserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {var request struct {Model string `json:"model"`@@ -85,18 +106,14 @@ func TestChatCompletionDisablesDeepSeekV4Thinking(t *testing.T) {if err := json.NewDecoder(r.Body).Decode(&request); err != nil {t.Error(err)}- want := "none"- if model == "deepseek-chat" || model == "test-model" {- want = ""+ if request.Model != testCase.model || request.ReasoningEffort != testCase.want {+ t.Errorf("model=%q reasoning_effort=%q, want %q %q", request.Model, request.ReasoningEffort, testCase.model, testCase.want)}- if request.Model != model || request.ReasoningEffort != want {- t.Errorf("model=%q reasoning_effort=%q, want %q %q", request.Model, request.ReasoningEffort, model, want)- }- if want == "none" && (request.Temperature == nil || *request.Temperature != 0.2) {+ if testCase.want == "none" && (request.Temperature == nil || *request.Temperature != 0.2) {t.Errorf("DeepSeek V4 temperature = %v, want 0.2", request.Temperature)}- if want == "" && request.Temperature != nil {- t.Errorf("model %q should use default sampling", model)+ if testCase.want == "" && request.Temperature != nil {+ t.Errorf("model %q should use default sampling", testCase.model)}w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`{"id":"translated","choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"完整译文"}}]}`))@@ -231,6 +248,11 @@ func setTestModel(t *testing.T) {t.Helper()log.InitLogger()previous := config.Conf.Llm.Model+ previousModelName := config.Conf.Llm.ModelNameconfig.Conf.Llm.Model = "test-model"- t.Cleanup(func() { config.Conf.Llm.Model = previous })+ config.Conf.Llm.ModelName = ""+ t.Cleanup(func() {+ config.Conf.Llm.Model = previous+ config.Conf.Llm.ModelName = previousModelName+ })}