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: prepare OpenCreator 3.2.6 account and YouTube improvements
Leggettb710f5e2e023
diff --git a/apps/daemon/package.json b/apps/daemon/package.jsonindex 853b38d4..5bbb614c 100644--- a/apps/daemon/package.json+++ b/apps/daemon/package.json@@ -23,7 +23,7 @@"dependencies": {"@fastify/cors": "^11.0.1","@iarna/toml": "2.2.5",- "@modelcontextprotocol/sdk": "1.29.0",+ "@modelcontextprotocol/sdk": "1.31.0","@opencreator/config": "workspace:*","@opencreator/protocol": "workspace:*","@opencreator/skill-market": "workspace:*",@@ -38,7 +38,7 @@"nanoid": "^5.0.9","pdf-parse": "1.1.1","pdfkit": "^0.20.2",- "sharp": "0.35.4",+ "sharp": "0.35.5","toml": "4.2.0","yaml": "^2.8.1","yauzl": "3.4.0",diff --git a/apps/daemon/src/api/routes.gateway-account.ts b/apps/daemon/src/api/routes.gateway-account.tsindex 01665a75..22a09486 100644--- a/apps/daemon/src/api/routes.gateway-account.ts+++ b/apps/daemon/src/api/routes.gateway-account.ts@@ -16,6 +16,16 @@ export async function registerGatewayAccountRoutes(server: FastifyInstance, serv}}server.get('/gateway/account', (_r, reply) => respond(() => service.readState(), reply));+ server.post('/gateway/account/web', (r, reply) => respond(async () => {+ const value = z.object({ destination: z.enum(['recharge', 'account', 'usage', 'faq']), locale: z.enum(['zh', 'en']), returnUrl: z.string().max(2048).optional() }).strict().safeParse(r.body);+ if (!value.success) throw new GatewayError('invalid_parameters', 400);+ try { return await service.billing('/api/v1/auth/browser/start', value.data); }+ catch (error) {+ // Older gateways apply browser CSRF checks before recognizing the new device endpoint.+ if (error instanceof GatewayError && error.status === 403 && error.code === 'invalid_origin') throw new GatewayError('browser_handoff_unavailable', 404);+ throw error;+ }+ }, reply));server.get('/gateway/avatar', (r, reply) => respond(async () => {const query = z.object({ accountId: z.string().min(1).max(512) }).strict().safeParse(r.query);if (!query.success) throw new GatewayError('invalid_parameters', 400);@@ -23,6 +33,7 @@ export async function registerGatewayAccountRoutes(server: FastifyInstance, servreturn reply.header('X-Content-Type-Options', 'nosniff').type(image.contentType).send(Buffer.from(image.data));}, reply));server.post('/gateway/auth/start', (_r, reply) => respond(() => service.startAuthorization(), reply));+ server.post('/gateway/auth/check', (_r, reply) => respond(async () => { service.checkAuthorization(); return service.readState(); }, reply));server.post('/gateway/auth/cancel', (_r, reply) => respond(async () => { await service.cancelAuthorization(); return service.readState(); }, reply));server.post('/gateway/auth/logout', (_r, reply) => respond(async () => { await service.logout(); return service.readState(); }, reply));server.post('/gateway/auth/activate', (_r, reply) => respond(async () => { await service.activate(); return service.readState(); }, reply));@@ -35,6 +46,17 @@ export async function registerGatewayAccountRoutes(server: FastifyInstance, serv}, reply));server.get('/gateway/billing/summary', (_r, reply) => respond(() => service.billing('/api/v1/billing/summary'), reply));server.get('/gateway/plans', (_r, reply) => respond(() => service.readPlans(), reply));- for (const resource of ['orders', 'ledger'] as const) server.get(`/gateway/billing/${resource}`, (_r, reply) => respond(() => service.billing(`/api/v1/billing/${resource}`), reply));+ server.get('/gateway/billing/orders', (_r, reply) => respond(() => service.billing('/api/v1/billing/orders'), reply));+ server.get('/gateway/billing/orders/:id', (r, reply) => respond(() => {+ const params = z.object({ id: z.string().min(1).max(128) }).safeParse(r.params);+ if (!params.success) throw new GatewayError('invalid_parameters', 400);+ return service.billing('/api/v1/billing/orders/' + encodeURIComponent(params.data.id));+ }, reply));+ server.get('/gateway/billing/ledger', (r, reply) => respond(() => {+ const query = z.object({ cursor: z.string().max(256).optional() }).strict().safeParse(r.query);+ if (!query.success) throw new GatewayError('invalid_parameters', 400);+ const suffix = query.data.cursor ? '?cursor=' + encodeURIComponent(query.data.cursor) : '';+ return service.billing('/api/v1/billing/ledger' + suffix);+ }, reply));for (const action of ['checkout', 'portal'] as const) server.post(`/gateway/billing/${action}`, (r, reply) => respond(() => service.billing(`/api/v1/billing/${action}`, r.body ?? {}), reply));}diff --git a/apps/daemon/src/api/routes.platform-connections.ts b/apps/daemon/src/api/routes.platform-connections.tsnew file mode 100644index 00000000..8421bd69--- /dev/null+++ b/apps/daemon/src/api/routes.platform-connections.ts@@ -0,0 +1,27 @@+import type { FastifyInstance } from 'fastify';+import type { YouTubeConnectionService } from '../platform-connections/youtube.js';+import { apiError } from './errors.js';++export async function registerPlatformConnectionRoutes(server: FastifyInstance, youtube: YouTubeConnectionService) {+ server.addHook('onSend', async (request, reply, payload) => {+ if (request.url.startsWith('/platform-connections/')) reply.header('Cache-Control', 'no-store');+ return payload;+ });+ server.get('/platform-connections/youtube', () => youtube.getState());+ server.post<{ Body: { profileId?: unknown } }>('/platform-connections/youtube/connect', (request, reply) => {+ const profileId = request.body?.profileId;+ if (profileId !== undefined && (typeof profileId !== 'string' || !/^[a-f0-9]{24}$/.test(profileId))) {+ return reply.code(400).send(apiError('VALIDATION_FAILED', '请选择有效的浏览器账号。'));+ }+ return youtube.connect(profileId as string | undefined);+ });+ server.post('/platform-connections/youtube/cancel', () => youtube.cancel());+ server.delete('/platform-connections/youtube', () => youtube.disconnect());+ server.post<{ Body: { cookies?: unknown } }>('/platform-connections/youtube/import', async (request, reply) => {+ if (typeof request.body?.cookies !== 'string' || Buffer.byteLength(request.body.cookies) > 1024 * 1024) {+ return reply.code(400).send(apiError('VALIDATION_FAILED', '请选择有效的 Cookie 文件。'));+ }+ try { return await youtube.importCookies(request.body.cookies); }+ catch { return reply.code(400).send(apiError('VALIDATION_FAILED', '文件中没有有效的 YouTube 登录态,请检查文件或重新连接。')); }+ });+}diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.tsindex dbac1f85..9fd839bc 100644--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@ -264,6 +264,8 @@ import { registerTaskRoutes } from './routes.tasks.js';import { registerThreadRoutes } from './routes.threads.js';import { registerWorkspaceFileRoutes } from './routes.workspace-files.js';import { registerVideoMetadataRoutes } from './routes.video-metadata.js';+import { YouTubeConnectionService } from '../platform-connections/youtube.js';+import { registerPlatformConnectionRoutes } from './routes.platform-connections.js';export type BuildServerInput = {token: string;@@ -688,9 +690,17 @@ export async function buildServer(input: BuildServerInput) {const creatorServicesConfigStore = gatewayCreatorSource.store;if (stickmanContentRuntimeManager) stickmanContentRuntimeManager = createRuntimeSource(stickmanContentRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('stickman'));let getCreatorYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;+ const youtubeConnection = new YouTubeConnectionService({+ root: join(dataDir, 'platform-connections', 'youtube'),+ getRuntime: () => getCreatorYtDlpRuntime?.()+ });+ await youtubeConnection.initialize();+ await registerPlatformConnectionRoutes(server, youtubeConnection);const videoMetadataService = input.videoMetadataService ?? createVideoMetadataService({getProxy: async () => (await readCommonProxy()).trim(),- getYtDlpRuntime: () => getCreatorYtDlpRuntime?.()+ getYtDlpRuntime: () => getCreatorYtDlpRuntime?.(),+ isYouTubeConnected: () => youtubeConnection.hasAuthentication(),+ withYouTubeCookies: operation => youtubeConnection.withCookies(operation)});const creatorService = input.creatorService ?? createCreatorService({jobsRoot: creatorJobsRoot,@@ -869,8 +879,9 @@ export async function buildServer(input: BuildServerInput) {console.warn(`yt-dlp updater is unavailable: ${formatError(error)}`);}}- getYtDlpRuntime = () =>- creatorYtDlpUpdateManager?.getRuntime() ?? ytDlp;+ getYtDlpRuntime = () => youtubeConnection.authenticatedRuntime(+ creatorYtDlpUpdateManager?.getRuntime() ?? ytDlp+ );getCreatorYtDlpRuntime = getYtDlpRuntime;if (input.creatorExecutors === undefined) {creatorExecutors.push(createKrillinExecutor({@@ -1052,7 +1063,10 @@ export async function buildServer(input: BuildServerInput) {workRoot: creatorJobsRoot,executors: creatorExecutors.map(executor => ({id: executor.id,- run: stage => gatewayCreatorSource!.runForJob(stage.job.id, stage.stageRun.id, () => executor.run(stage))+ run: stage => gatewayCreatorSource!.runForJob(stage.job.id, stage.stageRun.id, () =>+ ['download', 'krillinai', 'cover-analysis', 'wechat-article'].includes(executor.id)+ ? youtubeConnection.withCookies(() => executor.run(stage))+ : executor.run(stage))})),async beforeRun(job, stageId) {gatewayCreatorSource!.assertJob(job.id);@@ -1399,6 +1413,7 @@ export async function buildServer(input: BuildServerInput) {});server.addHook('onClose', async () => {+ await youtubeConnection.close();await gatewayAccount.close();let firstError: unknown;const capture = async (operation: () => void | Promise<void>) => {diff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex adb99862..8345fc0e 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -53,6 +53,7 @@ export function createKrillinExecutor(input: {const materializedArtifacts = await writeArtifactIndex(input.jobsRoot, stage);const options = buildKrillinStageOptions(stage);let artifacts: KrillinResultArtifact[];+ let captionFallbackProgress: Record<string, CreatorJson> = {};try {const attempts = createKrillinCliExecutionPlan(resolveKrillinStageContract(stage).stageType,@@ -65,13 +66,22 @@ export function createKrillinExecutor(input: {let completed: KrillinResultArtifact[] | undefined;let deferredFailure: KrillinCliError | undefined;for (const attempt of attempts) {+ const attemptStage: CreatorExecutorInput = {+ ...stage,+ reportProgress(progress) {+ if (progress.providerStatus === 'failed' && attempt.continueOnErrorCodes !== undefined) return;+ stage.reportProgress({ ...progress, ...captionFallbackProgress });+ }+ };try {if (requiresTranscriptionDependency(stage.stageRun.stageId, attempt.options)) {await ensureKrillinTranscriptionDependency(input.dependencyLoader,preflight.config,- stage,- deferredFailure !== undefined+ attemptStage,+ typeof captionFallbackProgress.captionFallbackMessage === 'string'+ ? captionFallbackProgress.captionFallbackMessage+ : undefined);}completed = await runKrillinCli({@@ -79,7 +89,7 @@ export function createKrillinExecutor(input: {jobsRoot: input.jobsRoot,dependencyRoot: input.dependencyLoader.root,manifest: preflight.manifest,- stage,+ stage: attemptStage,config: preflight.config,artifacts: materializedArtifacts,source: attempt.source,@@ -93,9 +103,25 @@ export function createKrillinExecutor(input: {} catch (error) {if (error instanceof KrillinCliError- && error.code === attempt.continueOnErrorCode+ && attempt.continueOnErrorCodes?.includes(error.code)+ && !stage.signal.aborted) {deferredFailure = error;+ const message = error.code === 'platform_caption_invalid'+ ? '平台字幕解析失败,已自动切换到语音转录'+ : '未找到可用的平台字幕,已自动切换到语音转录';+ captionFallbackProgress = {+ captionSource: 'whisper',+ captionFallbackCode: error.code,+ captionFallbackMessage: message+ };+ stage.reportProgress({+ ...captionFallbackProgress,+ phase: 'fallback_to_transcription',+ providerStatus: 'running',+ percent: 25,+ message+ });continue;}if (deferredFailure !== undefined) {@@ -137,6 +163,7 @@ export function createKrillinExecutor(input: {})),progress: {...stage.stageRun.progress,+ ...captionFallbackProgress,krillinMode: 'cli',providerStatus: 'succeeded',percent: 100,@@ -174,7 +201,7 @@ async function ensureKrillinTranscriptionDependency(loader: KrillinDependencyLoader,config: CreatorServicesConfig,stage: CreatorExecutorInput,- platformFallback = false+ fallbackMessage?: string): Promise<void> {if (stage.job.templateId === 'video-translation' && (stage.stageRun.stageId === 'subtitle'@@ -186,8 +213,8 @@ async function ensureKrillinTranscriptionDependency(signal: stage.signal,reportProgress(progress) {stage.reportProgress({ ...stage.stageRun.progress, ...progress,- ...(platformFallback && typeof progress.message === 'string'- ? { message: `未找到可用的原始字幕,已切换到本地语音转录。${progress.message}` }+ ...(fallbackMessage && typeof progress.message === 'string'+ ? { message: `${fallbackMessage}。${progress.message}` }: {})});}diff --git a/apps/daemon/src/creator/krillin/cli-runner.ts b/apps/daemon/src/creator/krillin/cli-runner.tsindex 25a7f9a4..d861deb2 100644--- a/apps/daemon/src/creator/krillin/cli-runner.ts+++ b/apps/daemon/src/creator/krillin/cli-runner.ts@@ -525,6 +525,7 @@ function reportProgressLine(providerStatus: 'running',percent: frame.percent,...(frame.phase === undefined ? {} : { phase: frame.phase }),+ ...(frame.message === undefined ? {} : { message: frame.message }),krillinEventPayload: payload});}diff --git a/apps/daemon/src/creator/krillin/execution-plan.ts b/apps/daemon/src/creator/krillin/execution-plan.tsindex 42b2b82c..17b92a3c 100644--- a/apps/daemon/src/creator/krillin/execution-plan.ts+++ b/apps/daemon/src/creator/krillin/execution-plan.ts@@ -1,7 +1,7 @@export type KrillinCliExecutionAttempt = {source?: string;options: Record<string, unknown>;- continueOnErrorCode?: string;+ continueOnErrorCodes?: string[];};export type KrillinCliExecutionSources = {@@ -43,7 +43,7 @@ export function createKrillinCliExecutionPlan({source: sources.sourceUrl,options: { ...options, captionSource: 'platform' },- continueOnErrorCode: 'platform_caption_failed'+ continueOnErrorCodes: ['platform_caption_failed', 'platform_caption_invalid']},{...(mediaSource === undefined ? {} : { source: mediaSource }),diff --git a/apps/daemon/src/creator/krillin/manifest.ts b/apps/daemon/src/creator/krillin/manifest.tsindex 270affc9..530b349b 100644--- a/apps/daemon/src/creator/krillin/manifest.ts+++ b/apps/daemon/src/creator/krillin/manifest.ts@@ -14,11 +14,18 @@ const resourceSchema = z.object({model: z.string().optional()}).strict();+const javascriptRuntimeSchema = z.object({+ name: z.literal('node'),+ version: z.string().min(1),+ executable: z.string().min(1)+}).strict();+const ytDlpRuntimeSchema = z.discriminatedUnion('mode', [z.object({mode: z.literal('standalone'),version: z.string().min(1),- executable: z.string().min(1)+ executable: z.string().min(1),+ javascriptRuntime: javascriptRuntimeSchema.optional()}).strict(),z.object({mode: z.literal('python'),@@ -26,7 +33,8 @@ const ytDlpRuntimeSchema = z.discriminatedUnion('mode', [pythonVersion: z.string().min(1),executable: z.string().min(1),script: z.string().min(1),- certificateBundle: z.string().min(1)+ certificateBundle: z.string().min(1),+ javascriptRuntime: javascriptRuntimeSchema.optional()}).strict()]);diff --git a/apps/daemon/src/creator/yt-dlp/runtime.ts b/apps/daemon/src/creator/yt-dlp/runtime.tsindex 2bfc4a9f..4eb09c07 100644--- a/apps/daemon/src/creator/yt-dlp/runtime.ts+++ b/apps/daemon/src/creator/yt-dlp/runtime.ts@@ -16,6 +16,10 @@ export function resolveYtDlpRuntime(input: {manifest: KrillinRuntimeManifest;overridePath?: string;}): YtDlpRuntime | undefined {+ const javascriptRuntime = input.manifest.ytDlp?.javascriptRuntime;+ const javascriptArgs = javascriptRuntime === undefined ? [] : [+ '--js-runtimes', `${javascriptRuntime.name}:${manifestResource(input, javascriptRuntime.executable, 'executable')}`+ ];if (input.overridePath !== undefined) {const executable = resolve(input.overridePath);if (!existsSync(executable)) {@@ -24,7 +28,7 @@ export function resolveYtDlpRuntime(input: {return {version: 'external',executable,- prefixArgs: [],+ prefixArgs: javascriptArgs,env: {}};}@@ -34,7 +38,7 @@ export function resolveYtDlpRuntime(input: {return {version: descriptor.version,executable: manifestResource(input, descriptor.executable, 'executable'),- prefixArgs: [],+ prefixArgs: javascriptArgs,env: {}};}@@ -49,7 +53,7 @@ export function resolveYtDlpRuntime(input: {return {version: descriptor.version,executable,- prefixArgs: ['-I', '-B', script],+ prefixArgs: ['-I', '-B', script, ...javascriptArgs],env: {SSL_CERT_FILE: certificateBundle},@@ -66,7 +70,7 @@ export function resolveYtDlpRuntime(input: {: {version: 'legacy',executable: resolveInside(input.resourceRoot, legacy.path),- prefixArgs: [],+ prefixArgs: javascriptArgs,env: {}};}diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.tsindex e4d8515f..60306552 100644--- a/apps/daemon/src/gateway/account-service.ts+++ b/apps/daemon/src/gateway/account-service.ts@@ -16,9 +16,10 @@ export function createGatewayAccountService(input: {const store = createGatewayConfigStore(input.dataDir);let state: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };let credentials: GatewayCredentials | undefined;- let attempt: (GatewayDeviceGrant & { generation: number; expiresAt: number; previousAuthState: GatewayAccountState['authState'] }) | undefined;+ let attempt: (GatewayDeviceGrant & { generation: number; expiresAt: number; nextPollAt: number; previousAuthState: GatewayAccountState['authState'] }) | undefined;let generation = 0;let pollTimer: NodeJS.Timeout | undefined;+ let pollWork: { attempt: NonNullable<typeof attempt>; work: Promise<void> } | undefined;let initialization: Promise<void> | undefined;let refreshWork: Promise<void> | undefined;let profileWork: Promise<void> | undefined;@@ -126,17 +127,19 @@ export function createGatewayAccountService(input: {try { await refreshWork; } finally { refreshWork = undefined; }}async function activateCurrent() {- assertIdle(); await refresh();+ // Connecting a new session must not wait for unrelated or persisted jobs.+ if (state.activationState === 'ready') assertIdle();+ await refresh();const original = assertSignedIn(); const expected = generation;state.activationState = 'loading'; state.activationError = null;try {- if (state.source !== 'gateway' && input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);state.source = 'gateway'; state.bindingVersion = null;await saveConfiguration();await reportUsage();const bootstrap = await input.client.bootstrap(original.accessToken, { rotate: !input.hasPendingTasks?.() });if (generation !== expected || state.authState !== 'signed_in') return;if (original.account && bootstrap.account.id !== original.account.id) throw new GatewayError('account_mismatch');+ state.account = bootstrap.account;for (const [modality, model] of Object.entries(selectedModels)) {if (bootstrap.models.some(candidate => candidate.modality === modality && candidate.id === model)) bootstrap.defaults[modality] = model;}@@ -197,9 +200,14 @@ export function createGatewayAccountService(input: {try { await catalogWork; } finally { catalogWork = undefined; }}function schedulePoll(id: string, seconds: number) {+ if (attempt?.attemptId !== id) return;+ attempt.nextPollAt = Date.now() + Math.max(5, seconds) * 1000;if (input.automaticPolling === false) return;clearTimeout(pollTimer);- pollTimer = setTimeout(() => { void pollAuthorization(id).catch(() => undefined); }, Math.max(5, seconds) * 1000); pollTimer.unref();+ pollTimer = setTimeout(() => { void pollAuthorization(id).catch(() => undefined); }, Math.max(0, attempt.nextPollAt - Date.now())); pollTimer.unref();+ }+ function checkAuthorization() {+ if (attempt && Date.now() >= attempt.nextPollAt) void pollAuthorization(attempt.attemptId).catch(() => undefined);}async function cancelAuthorization() {clearTimeout(pollTimer); const old = attempt; attempt = undefined; generation++;@@ -212,19 +220,18 @@ export function createGatewayAccountService(input: {}}async function startAuthorization() {- await initialize(); assertIdle();+ await initialize();if (credentials && state.authState === 'expired') {if (!input.hasPendingTasks?.()) await logout();}else if (credentials) throw new GatewayError('already_signed_in', 409);- else if (input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);await cancelAuthorization();const expected = generation;const grant = await input.client.startDevice();const url = new URL(grant.authorizationUrl);if (url.origin !== input.client.origin || url.pathname !== '/device') throw new GatewayError('invalid_authorization_url');if (generation !== expected) { await input.client.cancelDevice(grant.attemptId, grant.deviceSecret); throw new GatewayError('authorization_canceled'); }- attempt = { ...grant, generation: expected, expiresAt: Date.now() + grant.expiresIn * 1000, previousAuthState: state.authState };+ attempt = { ...grant, generation: expected, expiresAt: Date.now() + grant.expiresIn * 1000, nextPollAt: Date.now(), previousAuthState: state.authState };state.source = 'gateway'; state.authState = 'authorizing'; state.activationState = 'loading'; state.activationError = null;await saveConfiguration();schedulePoll(grant.attemptId, grant.interval);@@ -232,6 +239,15 @@ export function createGatewayAccountService(input: {}async function pollAuthorization(id: string) {const current = attempt; if (!current || current.attemptId !== id) return;+ if (pollWork?.attempt === current) return pollWork.work;+ clearTimeout(pollTimer);+ current.nextPollAt = Date.now() + Math.max(5, current.interval) * 1000;+ const work = performAuthorizationPoll(current);+ const pending = { attempt: current, work }; pollWork = pending;+ try { await work; } finally { if (pollWork === pending) pollWork = undefined; }+ }+ async function performAuthorizationPoll(current: NonNullable<typeof attempt>) {+ const id = current.attemptId;if (current.expiresAt <= Date.now()) { await cancelAuthorization(); state.activationError = { code: 'device_expired', message: '登录授权已过期,请重新登录' }; return; }try {const tokens = await input.client.pollDevice(id, current.deviceSecret);@@ -250,12 +266,14 @@ export function createGatewayAccountService(input: {if (generation !== current.generation || attempt !== current) return;state.source = 'gateway'; state.authState = 'signed_in'; attempt = undefined;await saveConfiguration();- if (input.hasPendingTasks?.() && current.previousAuthState !== 'expired') { fail(new GatewayError('active_tasks', 409)); return; }await activateCurrent();});} catch (error) {if (generation !== current.generation) return;- if (error instanceof GatewayError && ['authorization_pending', 'slow_down', 'gateway_unavailable'].includes(error.code)) { schedulePoll(id, error.code === 'slow_down' ? current.interval + 5 : current.interval); return; }+ if (error instanceof GatewayError && ['authorization_pending', 'slow_down', 'gateway_unavailable'].includes(error.code)) {+ if (error.code === 'slow_down') current.interval += 5;+ schedulePoll(id, current.interval); return;+ }fail(error); await cancelAuthorization();}}@@ -327,9 +345,7 @@ export function createGatewayAccountService(input: {accessPaused = true;accessController?.abort(); await accessWork;await serialize(async () => {- assertIdle();- if (input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);- await reportUsage();+ await reportUsage().catch(() => undefined);state.authState = 'signing_out'; state.activationState = 'inactive';clearInterval(usageTimer); usageTimer = undefined;await cancelAuthorization();@@ -351,7 +367,7 @@ export function createGatewayAccountService(input: {}return {peekState() { return structuredClone(state); },- startAuthorization, cancelAuthorization, pollAuthorization, refresh, logout, modelCredentials, beginModelUse, readBalance, billing,+ startAuthorization, cancelAuthorization, pollAuthorization, checkAuthorization, refresh, logout, modelCredentials, beginModelUse, readBalance, billing,readPlans() { return input.client.request('/api/v1/plans', ''); },async readAvatar(accountId: string) {await initialize(); await refresh();@@ -362,7 +378,14 @@ export function createGatewayAccountService(input: {return image;},async activate() { await initialize(); const expected = generation; await serialize(async () => { if (expected === generation) await activateCurrent(); }); },- async readState() { await initialize(); await readProfile(); await readCatalog(); if (needsAccessibleRuntime()) await serialize(synchronizeAccessibleRuntime); scheduleModelAccess(); return structuredClone(state); },+ async readState() {+ await initialize();+ // Login is visible while model preparation still owns the mutation queue.+ if (state.activationState === 'loading' || state.authState === 'signing_out') return structuredClone(state);+ await readProfile(); await readCatalog();+ if (needsAccessibleRuntime()) await serialize(synchronizeAccessibleRuntime);+ scheduleModelAccess(); return structuredClone(state);+ },async setSource(source: ServiceSource) {await initialize(); await serialize(async () => {if (source === 'manual' && (credentials || state.authState !== 'signed_out')) throw new GatewayError('logout_required', 409);diff --git a/apps/daemon/src/platform-connections/browser.ts b/apps/daemon/src/platform-connections/browser.tsnew file mode 100644index 00000000..ccc1afe9--- /dev/null+++ b/apps/daemon/src/platform-connections/browser.ts@@ -0,0 +1,107 @@+import { createHash } from 'node:crypto';+import { readFile, stat } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { spawnCreatorProcess } from '../creator/process-tree.js';+import type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';+import { filterYouTubeCookies, type YouTubeCookie } from './cookies.js';++export type BrowserProfile = { id: string; browser: 'chrome' | 'edge'; label: string; directory: string; preferred: boolean };++export async function listBrowserProfiles(): Promise<BrowserProfile[]> {+ const roots: Array<['chrome' | 'edge', string]> = process.platform === 'darwin' ? [+ ['chrome', join(homedir(), 'Library/Application Support/Google/Chrome')],+ ['edge', join(homedir(), 'Library/Application Support/Microsoft Edge')]+ ] : process.platform === 'win32' ? [+ ['chrome', join(process.env.LOCALAPPDATA ?? '', 'Google/Chrome/User Data')],+ ['edge', join(process.env.LOCALAPPDATA ?? '', 'Microsoft/Edge/User Data')]+ ] : [+ ['chrome', join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'google-chrome')],+ ['edge', join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'microsoft-edge')]+ ];+ const profiles: BrowserProfile[] = [];+ for (const [browser, root] of roots) {+ let state: { profile?: { last_used?: string; info_cache?: Record<string, { name?: string }> } };+ try { state = JSON.parse(await readFile(join(root, 'Local State'), 'utf8')); }+ catch { continue; }+ for (const [directoryName, metadata] of Object.entries(state.profile?.info_cache ?? { Default: {} })) {+ if (!/^(?:Default|Profile \d+)$/.test(directoryName)) continue;+ const directory = join(root, directoryName);+ const exists = await stat(join(directory, 'Network/Cookies')).catch(() =>+ stat(join(directory, 'Cookies')).catch(() => undefined));+ if (!exists?.isFile()) continue;+ profiles.push({ id: createHash('sha256').update(directory).digest('hex').slice(0, 24), browser,+ label: `${browser === 'chrome' ? 'Chrome' : 'Edge'} · ${metadata.name || directoryName}`,+ directory, preferred: directoryName === (state.profile?.last_used ?? 'Default') });+ }+ }+ return profiles.sort((a, b) => Number(b.preferred) - Number(a.preferred));+}++// Use yt-dlp's maintained browser decryption implementation. Only YouTube cookies+// cross the private stdout pipe; no all-site plaintext cookie file is exported.+const READ_BROWSER_COOKIES = String.raw`+import sys, json, time+sys.path.insert(0, sys.argv[1])+from yt_dlp.cookies import extract_cookies_from_browser, YDLLogger+from yt_dlp.utils import DownloadError+class QuietLogger(YDLLogger):+ decryption_failed = False+ def debug(self, *args, **kwargs): pass+ def info(self, *args, **kwargs): pass+ def warning(self, message, *args, **kwargs):+ if 'decrypt' in str(message) or 'key found' in str(message) or 'find-generic-password failed' in str(message):+ self.decryption_failed = True+ def error(self, *args, **kwargs): raise DownloadError('Browser cookie extraction failed')+try:+ logger = QuietLogger()+ jar = extract_cookies_from_browser(sys.argv[2], profile=sys.argv[3], logger=logger)+ cookies = []+ for c in jar:+ host = c.domain.lstrip('.').lower()+ expires = c.expires or 0+ if expires > 100000000000:+ expires = int(expires / 1000000 - 11644473600)+ if (host == 'youtube.com' or host.endswith('.youtube.com')) and (expires <= 0 or expires > time.time()):+ cookies.append(dict(name=c.name, value=c.value, domain=c.domain, path=c.path,+ secure=bool(c.secure), httpOnly=c.has_nonstandard_attr('HttpOnly'), expires=expires))+ sys.stdout.write(json.dumps(dict(cookies=cookies, decryptionFailed=logger.decryption_failed)))+except Exception:+ sys.exit(1)+`;++export async function readBrowserYouTubeCookies(input: {+ profile: BrowserProfile;+ runtime: YtDlpRuntime | undefined;+ signal: AbortSignal;+}): Promise<YouTubeCookie[]> {+ const { runtime, profile, signal } = input;+ if (!runtime?.script) throw new Error('浏览器连接需要内置 yt-dlp 组件,请更新本地组件后重试。');+ signal.throwIfAborted();+ const output = await new Promise<string>((resolve, reject) => {+ const child = spawnCreatorProcess(runtime.executable, ['-I', '-B', '-c', READ_BROWSER_COOKIES,+ runtime.script!, profile.browser, profile.directory], {+ env: { ...process.env, ...runtime.env }, stdio: ['ignore', 'pipe', 'pipe']+ }, signal);+ const chunks: Buffer[] = [];+ let length = 0;+ child.stdout?.on('data', (chunk: Buffer) => {+ length += chunk.length;+ if (length > 1024 * 1024) { child.kill(); reject(new Error('浏览器 Cookie 读取失败,请重试。')); return; }+ chunks.push(chunk);+ });+ child.stderr?.on('data', () => undefined);+ child.once('error', () => reject(new Error('无法读取浏览器 Cookie,请检查本地组件。')));+ child.once('close', code => {+ if (signal.aborted) reject(new Error('连接已取消。'));+ else if (code !== 0) reject(new Error('无法读取 Chrome / Edge 的 Cookie。请允许钥匙串访问;若浏览器加密或文件锁阻止读取,可导入 Cookie 文件。'));+ else resolve(Buffer.concat(chunks).toString('utf8'));+ });+ });+ const result = JSON.parse(output) as { cookies?: unknown; decryptionFailed?: boolean };+ const cookies = filterYouTubeCookies(result.cookies);+ if (result.decryptionFailed && cookies.length === 0) {+ throw new Error('浏览器 Cookie 解密失败,请允许 macOS 钥匙串访问后重新连接;当前浏览器的加密方式也可能不受 yt-dlp 支持。');+ }+ return cookies;+}diff --git a/apps/daemon/src/platform-connections/cookies.ts b/apps/daemon/src/platform-connections/cookies.tsnew file mode 100644index 00000000..fd829ec2--- /dev/null+++ b/apps/daemon/src/platform-connections/cookies.ts@@ -0,0 +1,57 @@+export type YouTubeCookie = {+ name: string;+ value: string;+ domain: string;+ path: string;+ secure: boolean;+ httpOnly: boolean;+ expires: number;+};++export function isYouTubeDomain(domain: string): boolean {+ const host = domain.replace(/^\./, '').toLowerCase();+ return host === 'youtube.com' || host.endsWith('.youtube.com');+}++export function filterYouTubeCookies(value: unknown, now = Date.now()): YouTubeCookie[] {+ if (!Array.isArray(value)) return [];+ return value.filter((cookie): cookie is YouTubeCookie => {+ if (!cookie || typeof cookie !== 'object') return false;+ const c = cookie as Record<string, unknown>;+ return typeof c.domain === 'string' && isYouTubeDomain(c.domain)+ && typeof c.name === 'string' && !!c.name && typeof c.value === 'string'+ && typeof c.path === 'string' && c.path.startsWith('/')+ && [c.domain, c.name, c.value, c.path].every(field => !/[\t\r\n\0]/.test(field as string))+ && typeof c.secure === 'boolean' && typeof c.httpOnly === 'boolean'+ && typeof c.expires === 'number' && Number.isFinite(c.expires)+ && (c.expires <= 0 || c.expires * 1000 > now);+ }).map(c => ({ name: c.name, value: c.value, domain: c.domain, path: c.path,+ secure: c.secure, httpOnly: c.httpOnly, expires: c.expires }));+}++export function hasYouTubeAuthentication(cookies: YouTubeCookie[]): boolean {+ return cookies.some(c => ['SID', '__Secure-1PSID', '__Secure-3PSID'].includes(c.name) && !!c.value)+ && cookies.some(c => ['SAPISID', '__Secure-1PAPISID', '__Secure-3PAPISID'].includes(c.name) && !!c.value);+}++export function serializeYouTubeCookies(cookies: YouTubeCookie[]): string {+ return '# Netscape HTTP Cookie File\n' + filterYouTubeCookies(cookies).map(c => [+ `${c.httpOnly ? '#HttpOnly_' : ''}${c.domain}`, c.domain.startsWith('.') ? 'TRUE' : 'FALSE',+ c.path, c.secure ? 'TRUE' : 'FALSE', Math.max(0, Math.floor(c.expires)), c.name, c.value+ ].join('\t')).join('\n') + '\n';+}++export function parseYouTubeCookies(source: string): YouTubeCookie[] {+ if (Buffer.byteLength(source) > 1024 * 1024 || !/^\uFEFF?# (?:Netscape )?HTTP Cookie File/.test(source)) {+ throw new Error('Invalid Netscape cookie file');+ }+ const cookies = source.split(/\r?\n/).flatMap(line => {+ if (!line.trim() || line.startsWith('#') && !line.startsWith('#HttpOnly_')) return [];+ const fields = line.replace(/^#HttpOnly_/, '').split('\t');+ if (fields.length !== 7) return [];+ const [domain, , path, secure, expires, name, value] = fields;+ return [{ domain, path, secure: secure === 'TRUE', expires: Number(expires), name, value,+ httpOnly: line.startsWith('#HttpOnly_') }];+ });+ return filterYouTubeCookies(cookies);+}diff --git a/apps/daemon/src/platform-connections/youtube.ts b/apps/daemon/src/platform-connections/youtube.tsnew file mode 100644index 00000000..a492d195--- /dev/null+++ b/apps/daemon/src/platform-connections/youtube.ts@@ -0,0 +1,167 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import type { YouTubeConnectionState } from '@opencreator/protocol';+import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';+import type { YtDlpRuntime } from '../creator/yt-dlp/runtime.js';+import { listBrowserProfiles, readBrowserYouTubeCookies, type BrowserProfile } from './browser.js';+import { filterYouTubeCookies, hasYouTubeAuthentication, parseYouTubeCookies,+ serializeYouTubeCookies, type YouTubeCookie } from './cookies.js';++type Credential = { version: 1; cookies: YouTubeCookie[]; connectedAt: string;+ browser?: 'chrome' | 'edge'; profileId?: string; invalidated?: boolean };+type ConnectionAttempt = { controller: AbortController; work: Promise<void> };++export class YouTubeConnectionService {+ private state: YouTubeConnectionState = { platform: 'youtube', status: 'disconnected' };+ private attempt?: ConnectionAttempt;+ private context = new AsyncLocalStorage<{ path: string; credential: Credential }>();+ private mutations: Promise<unknown> = Promise.resolve();+ private readonly credentialFile: string;+ constructor(private input: {+ root: string;+ getRuntime(): YtDlpRuntime | undefined;+ listProfiles?: typeof listBrowserProfiles;+ readBrowserCookies?: typeof readBrowserYouTubeCookies;+ connectionTimeoutMs?: number;+ }) { this.credentialFile = join(input.root, 'credentials.json'); }++ async initialize(): Promise<void> {+ await mkdir(this.input.root, { recursive: true, mode: 0o700 });+ if (process.platform !== 'win32') await chmod(this.input.root, 0o700);+ for (const entry of await readdir(this.input.root)) {+ if (/^(?:login-|task-)/.test(entry)) await rm(join(this.input.root, entry), { recursive: true, force: true });+ }+ await this.refreshState();+ }+ async getState(): Promise<YouTubeConnectionState> {+ if (!this.attempt && this.state.status !== 'error') await this.refreshState();+ return this.publicState();+ }+ async hasAuthentication(): Promise<boolean> {+ const credential = await this.readCredential();+ return !!credential && !credential.invalidated && hasYouTubeAuthentication(filterYouTubeCookies(credential.cookies));+ }+ connect(profileId?: string): Promise<YouTubeConnectionState> {+ return this.serialize(async () => {+ if (this.attempt) return this.publicState();+ const profiles = await (this.input.listProfiles ?? listBrowserProfiles)();+ const profile = profileId ? profiles.find(p => p.id === profileId) : profiles[0];+ if (!profile) {+ this.state = { platform: 'youtube', status: 'error', message: '未找到可用的浏览器账号,请先在 Chrome 或 Edge 中登录 YouTube。' };+ return this.publicState();+ }+ const attempt = { controller: new AbortController(), work: Promise.resolve() };+ this.attempt = attempt;+ this.state = { platform: 'youtube', status: 'connecting', browser: profile.browser, profileId: profile.id };+ attempt.work = this.finishConnection(attempt, profile);+ return this.publicState();+ });+ }+ cancel(): Promise<YouTubeConnectionState> {+ return this.serialize(async () => { await this.stopConnection(); await this.refreshState(); return this.publicState(); });+ }+ disconnect(): Promise<YouTubeConnectionState> {+ return this.serialize(async () => {+ await this.stopConnection();+ await rm(this.credentialFile, { force: true });+ this.state = { platform: 'youtube', status: 'disconnected' };+ return this.publicState();+ });+ }+ importCookies(source: string): Promise<YouTubeConnectionState> {+ return this.serialize(async () => {+ const cookies = parseYouTubeCookies(source);+ if (!hasYouTubeAuthentication(cookies)) throw new Error('Cookie 文件中没有有效的 YouTube 登录态。');+ await this.stopConnection();+ await writePrivateJsonFile(this.credentialFile, { version: 1, cookies, connectedAt: new Date().toISOString() } satisfies Credential);+ await this.refreshState();+ return this.publicState();+ });+ }+ authenticatedRuntime(runtime: YtDlpRuntime | undefined): YtDlpRuntime | undefined {+ const context = this.context.getStore();+ return runtime && context ? { ...runtime, prefixArgs: [...runtime.prefixArgs, '--cookies', context.path] } : runtime;+ }+ async withCookies<T>(operation: () => Promise<T>): Promise<T> {+ if (this.context.getStore()) return operation();+ // Browser reads can prompt for keychain access. Only explicit connections+ // refresh the saved credential; background requests and tasks use snapshots.+ const credential = await this.readCredential();+ const cookies = filterYouTubeCookies(credential?.cookies);+ if (!credential || credential.invalidated || !hasYouTubeAuthentication(cookies)) return operation();+ const directory = await mkdtemp(join(this.input.root, 'task-'));+ if (process.platform !== 'win32') await chmod(directory, 0o700);+ const path = join(directory, 'cookies.txt');+ try {+ await writeFile(path, serializeYouTubeCookies(cookies), { mode: 0o600, flag: 'wx' });+ return await this.context.run({ path, credential }, operation);+ } catch (error) {+ // A media 403 or bot challenge alone is not proof that the account expired.+ if (error instanceof Error && /cookies (?:are )?no longer valid|cookies? (?:have |has )?expired/i.test(error.message)) {+ await this.serialize(async () => {+ const current = await this.readCredential();+ if (current?.connectedAt === credential.connectedAt) {+ await writePrivateJsonFile(this.credentialFile, { ...current, invalidated: true });+ await this.refreshState();+ }+ });+ }+ throw error;+ } finally { await rm(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }); }+ }+ async close(): Promise<void> { await this.serialize(() => this.stopConnection()); }+ private async finishConnection(attempt: ConnectionAttempt, profile: BrowserProfile): Promise<void> {+ const timeout = setTimeout(() => attempt.controller.abort(), this.input.connectionTimeoutMs ?? 120_000);+ try {+ const cookies = await (this.input.readBrowserCookies ?? readBrowserYouTubeCookies)({+ profile, runtime: this.input.getRuntime(), signal: attempt.controller.signal });+ attempt.controller.signal.throwIfAborted();+ if (!hasYouTubeAuthentication(cookies)) throw new Error('此浏览器账号尚未登录 YouTube,或登录已过期。请在该账号中登录后重新连接。');+ const connectedAt = new Date().toISOString();+ await writePrivateJsonFile(this.credentialFile, {+ version: 1, cookies, connectedAt, browser: profile.browser, profileId: profile.id+ } satisfies Credential);+ this.state = { platform: 'youtube', status: 'connected', connectedAt, browser: profile.browser, profileId: profile.id };+ } catch (error) {+ this.state = { platform: 'youtube', status: 'error', message: attempt.controller.signal.aborted+ ? '连接已取消或超时,请重新连接。' : publicConnectionError(error) };+ } finally {+ clearTimeout(timeout);+ if (this.attempt === attempt) this.attempt = undefined;+ }+ }+ private async stopConnection(): Promise<void> {+ const attempt = this.attempt;+ if (!attempt) return;+ attempt.controller.abort();+ await attempt.work;+ }+ private async readCredential(): Promise<Credential | undefined> {+ const raw = await readPrivateJsonFile(this.credentialFile);+ if (!raw || typeof raw !== 'object') return undefined;+ const value = raw as Partial<Credential>;+ if (value.version !== 1 || !Array.isArray(value.cookies) || typeof value.connectedAt !== 'string') return undefined;+ return value as Credential;+ }+ private async refreshState(): Promise<void> {+ const credential = await this.readCredential();+ this.state = credential ? {+ platform: 'youtube', status: !credential.invalidated && hasYouTubeAuthentication(filterYouTubeCookies(credential.cookies)) ? 'connected' : 'expired',+ connectedAt: credential.connectedAt, browser: credential.browser, profileId: credential.profileId+ } : { platform: 'youtube', status: 'disconnected' };+ }+ private async publicState(): Promise<YouTubeConnectionState> {+ const profiles = await (this.input.listProfiles ?? listBrowserProfiles)();+ return { ...this.state, profiles: profiles.map(({ id, browser, label }) => ({ id, browser, label })) };+ }+ private serialize<T>(operation: () => Promise<T>): Promise<T> {+ const work = this.mutations.then(operation);+ this.mutations = work.catch(() => undefined);+ return work;+ }+}+function publicConnectionError(error: unknown): string {+ const message = error instanceof Error ? error.message : '';+ return /^[\u4e00-\u9fff]/.test(message) ? message : '读取浏览器登录态失败,请重试或选择其他浏览器账号。';+}diff --git a/apps/daemon/src/video-metadata/service.ts b/apps/daemon/src/video-metadata/service.tsindex 620df504..948e94a1 100644--- a/apps/daemon/src/video-metadata/service.ts+++ b/apps/daemon/src/video-metadata/service.ts@@ -23,12 +23,24 @@ export function createVideoMetadataService(input: {fetchImpl?: typeof fetch;getProxy?(): string | Promise<string>;getYtDlpRuntime?(): YtDlpRuntime | undefined;+ withYouTubeCookies?<T>(operation: () => Promise<T>): Promise<T>;+ isYouTubeConnected?(): Promise<boolean>;} = {}): VideoMetadataService {const cache = new Map<string, { payload: unknown; expiresAt: number }>();return {async get(value: string): Promise<VideoMetadataResponse> {const normalized = normalizeVideoSourceUrl(value);const platform = supportedVideoSourcePlatform(normalized);+ if (platform === 'youtube' && input.withYouTubeCookies && input.getYtDlpRuntime?.()+ && (await input.isYouTubeConnected?.() ?? true)) {+ return input.withYouTubeCookies(async () => {+ try {+ const { previewUrl: _previewUrl, ...metadata } = await resolveOnlineVideoMetadata({ url: normalized, platform,+ runtime: input.getYtDlpRuntime!()!, proxy: await resolveProxy(input.getProxy) });+ return metadata;+ } catch { throw new VideoMetadataError('UPSTREAM_ERROR', 'YouTube 视频信息暂不可用,请检查网络或平台连接后重试'); }+ });+ }if (platform !== null && platform !== 'youtube' && platform !== 'bilibili') {const runtime = input.getYtDlpRuntime?.();if (runtime === undefined) throw new VideoMetadataError('UPSTREAM_ERROR', 'Online video preview resolver is unavailable');diff --git a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts b/apps/daemon/test/integration/creator-krillin-cli-runner.test.tsindex 3da06efb..13375878 100644--- a/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts+++ b/apps/daemon/test/integration/creator-krillin-cli-runner.test.ts@@ -259,6 +259,7 @@ describe('KrillinAI CLI runner', () => {const cli = join(resourceRoot, 'bin', process.platform === 'win32' ? 'krillinai-cli.exe' : 'krillinai-cli');const ffmpeg = join(resourceRoot, 'bin', process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg');const ytDlp = join(tempDir, "managed yt'dlp");+ const cookieFile = join(tempDir, "YouTube cookie's.txt");const whisperKit = join(dependencyRoot,'bin',@@ -269,6 +270,7 @@ describe('KrillinAI CLI runner', () => {mkdirSync(dirname(source), { recursive: true });mkdirSync(workdir, { recursive: true });writeFileSync(source, 'fixture-video');+ writeFileSync(cookieFile, '# Netscape HTTP Cookie File\n', { mode: 0o600 });writeFileSync(cli, `#!${process.execPath}\n${FAKE_CLI}`);writeFileSync(ffmpeg, 'fixture-ffmpeg');writeFileSync(@@ -329,7 +331,7 @@ describe('KrillinAI CLI runner', () => {ytDlpRuntime: {version: '2026.08.31.120000',executable: process.execPath,- prefixArgs: [ytDlp],+ prefixArgs: [ytDlp, '--cookies', cookieFile],env: { SSL_CERT_FILE: '/tmp/opencreator-cacert.pem' },script: ytDlp}@@ -362,11 +364,17 @@ describe('KrillinAI CLI runner', () => {whisperKit: realpathSync(whisperKit),ytDlp: join(realpathSync(workdir), '.krillin-cli', 'bin', 'yt-dlp'),ytDlpMode: 0o700,- ytDlpVersion: '2026.08.31.120000'+ ytDlpVersion: '2026.08.31.120000',+ ytDlpPrefixArgs: [ytDlp, '--cookies', cookieFile]});expect(existsSync(join(workdir, '.krillin-cli'))).toBe(false);expect(existsSync(join(dependencyRoot, 'bin', '.yt-dlp-last-check'))).toBe(true);expect(existsSync(join(dependencyRoot, 'models'))).toBe(true);+ expect(progress).toContainEqual(expect.objectContaining({+ phase: 'fallback_to_transcription',+ providerStatus: 'running',+ message: 'Platform captions could not be processed. Switching to audio transcription.'+ }));expect(progress.at(-1)).toMatchObject({krillinMode: 'cli',providerStatus: 'succeeded',@@ -496,6 +504,7 @@ describe('KrillinAI CLI runner', () => {providerStatus: 'running',percent: 64,phase: 'generating_voice',+ message: 'generating',krillinEventPayload: {percent: 64,phase: 'generating_voice',@@ -647,6 +656,12 @@ if (args[0] === 'tts') {};writeFileSync(outputs.vertical_video, 'video');} else {+ process.stdout.write(JSON.stringify({+ type: 'progress',+ phase: 'fallback_to_transcription',+ percent: 25,+ message: 'Platform captions could not be processed. Switching to audio transcription.'+ }) + '\n');const ytDlpPath = join(process.env.KRILLINAI_RESOURCE_ROOT,'bin',@@ -665,7 +680,8 @@ if (args[0] === 'tts') {whisperKit: realpathSync(join(process.env.KRILLINAI_RESOURCE_ROOT, 'bin', 'whisperkit-cli')),ytDlp: realpathSync(ytDlpPath),ytDlpMode: statSync(ytDlpPath).mode & 0o777,- ytDlpVersion: ytDlpResult.stdout.trim()+ ytDlpVersion: ytDlpResult.stdout.trim(),+ ytDlpPrefixArgs: JSON.parse(process.env.KRILLINAI_YT_DLP_PREFIX_ARGS || '[]')}));outputs = {origin_video: join(workdir, 'origin_video.mp4'),diff --git a/apps/daemon/test/integration/gateway-account-api.test.ts b/apps/daemon/test/integration/gateway-account-api.test.tsindex 3732ba50..9b60d2e5 100644--- a/apps/daemon/test/integration/gateway-account-api.test.ts+++ b/apps/daemon/test/integration/gateway-account-api.test.ts@@ -1,11 +1,52 @@import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { expect, it } from 'vitest';+import { expect, it, vi } from 'vitest';import Fastify from 'fastify';import { registerGatewayAccountRoutes } from '../../src/api/routes.gateway-account.js';import { createGatewayClient } from '../../src/gateway/client.js';-import { createGatewayAccountService } from '../../src/gateway/account-service.js';+import { GatewayError } from '../../src/gateway/client.js';+import { createGatewayAccountService, type GatewayAccountService } from '../../src/gateway/account-service.js';++it('proxies account-owned orders and encoded grant cursors without caching', async () => {+ const billing = vi.fn(async () => ({ items: [] }));+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, { billing } as unknown as GatewayAccountService);+ const order = await server.inject({ method: 'GET', url: '/gateway/billing/orders/order-a' });+ expect(order.statusCode).toBe(200);+ expect(order.headers['cache-control']).toBe('no-store');+ expect(billing).toHaveBeenLastCalledWith('/api/v1/billing/orders/order-a');+ const ledger = await server.inject({ method: 'GET', url: '/gateway/billing/ledger?cursor=trial%3Aa%2Bb' });+ expect(ledger.statusCode).toBe(200);+ expect(billing).toHaveBeenLastCalledWith('/api/v1/billing/ledger?cursor=trial%3Aa%2Bb');+ billing.mockClear();+ const invalid = await server.inject({ method: 'GET', url: '/gateway/billing/ledger?cursor=' + 'a'.repeat(257) });+ expect(invalid.statusCode).toBe(400);+ expect(billing).not.toHaveBeenCalled();+ } finally { await server.close(); }+});++it('proxies validated website handoffs through the authenticated account service', async () => {+ const billing = vi.fn(async () => ({ url: 'https://gateway.example/auth#handoff=example' }));+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, { billing } as unknown as GatewayAccountService);+ const body = { destination: 'recharge', locale: 'zh', returnUrl: 'opencreator://billing/return' };+ const result = await server.inject({ method: 'POST', url: '/gateway/account/web', payload: body });+ expect(result.statusCode).toBe(200);+ expect(result.headers['cache-control']).toBe('no-store');+ expect(billing).toHaveBeenCalledWith('/api/v1/auth/browser/start', body);+ billing.mockClear();+ const invalid = await server.inject({ method: 'POST', url: '/gateway/account/web', payload: { ...body, destination: 'https://evil.test' } });+ expect(invalid.statusCode).toBe(400);+ expect(billing).not.toHaveBeenCalled();+ billing.mockRejectedValueOnce(new GatewayError('invalid_origin', 403));+ const legacy = await server.inject({ method: 'POST', url: '/gateway/account/web', payload: body });+ expect(legacy.statusCode).toBe(404);+ expect(legacy.json().error.details.gatewayCode).toBe('browser_handoff_unavailable');+ } finally { await server.close(); }+});it.skipIf(!process.env.GATEWAY_BROWSER_TEST_ORIGIN)('device service completes authorization against the local Go gateway', async () => {const origin = process.env.GATEWAY_BROWSER_TEST_ORIGIN!;diff --git a/apps/daemon/test/integration/video-metadata-api.test.ts b/apps/daemon/test/integration/video-metadata-api.test.tsindex f5025f70..82c92c5f 100644--- a/apps/daemon/test/integration/video-metadata-api.test.ts+++ b/apps/daemon/test/integration/video-metadata-api.test.ts@@ -29,8 +29,12 @@ describe('video metadata API', () => {width: 1920,height: 1080}), { status: 200, headers: { 'Content-Type': 'application/json' } }));+ const authentication = vi.fn();await registerVideoMetadataRoutes(server, createVideoMetadataService({- fetchImpl: fetchImpl as typeof fetch+ fetchImpl: fetchImpl as typeof fetch,+ getYtDlpRuntime: () => ({ version: 'test', executable: '/unused', prefixArgs: [], env: {} }),+ isYouTubeConnected: async () => false,+ withYouTubeCookies: async operation => { authentication(); return operation(); }}));const response = await server.inject({@@ -50,6 +54,7 @@ describe('video metadata API', () => {const requestedUrl = new URL(String(fetchImpl.mock.calls[0]?.[0]));expect(requestedUrl.origin + requestedUrl.pathname).toBe('https://www.youtube.com/oembed');expect(requestedUrl.searchParams.get('url')).toBe('https://www.youtube.com/watch?v=video_123');+ expect(authentication).not.toHaveBeenCalled();});it('rejects unsupported links without making an upstream request', async () => {diff --git a/apps/daemon/test/integration/youtube-browser-import.test.ts b/apps/daemon/test/integration/youtube-browser-import.test.tsnew file mode 100644index 00000000..72f35b89--- /dev/null+++ b/apps/daemon/test/integration/youtube-browser-import.test.ts@@ -0,0 +1,34 @@+import Database from 'better-sqlite3';+import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { expect, it } from 'vitest';+import { readBrowserYouTubeCookies } from '../../src/platform-connections/browser.js';+import { hasYouTubeAuthentication } from '../../src/platform-connections/cookies.js';+import { resolveYtDlpRuntime } from '../../src/creator/yt-dlp/runtime.js';++it.runIf(!!process.env.OPENCREATOR_TEST_BROWSER_RUNTIME_ROOT)('uses the real portable Python and yt-dlp importer and normalizes Chromium cookie types and epoch', async () => {+ const resourceRoot = process.env.OPENCREATOR_TEST_BROWSER_RUNTIME_ROOT!;+ const manifest = JSON.parse(await readFile(join(resourceRoot, 'manifest.json'), 'utf8'));+ const runtime = resolveYtDlpRuntime({ resourceRoot, manifest });+ const root = await mkdtemp(join(tmpdir(), 'youtube-browser-import-'));+ const directory = join(root, 'Default');+ try {+ await mkdir(directory);+ const db = new Database(join(directory, 'Cookies'));+ try {+ db.exec("CREATE TABLE meta (key TEXT, value TEXT); INSERT INTO meta VALUES ('version','24'); CREATE TABLE cookies (host_key TEXT, name TEXT, value TEXT, encrypted_value BLOB, path TEXT, expires_utc INTEGER, is_secure INTEGER)");+ const insert = db.prepare('INSERT INTO cookies VALUES (?, ?, ?, ?, ?, ?, ?)');+ const future = Math.floor(Date.now() / 1000) + 3600;+ const webkitFuture = (future + 11644473600) * 1000000;+ for (const name of ['SID', 'SAPISID']) insert.run('.youtube.com', name, `fixture-${name}`, Buffer.alloc(0), '/', webkitFuture, 1);+ insert.run('.google.com', 'SID', 'excluded', Buffer.alloc(0), '/', webkitFuture, 1);+ insert.run('.youtube.com.evil.test', 'SID', 'excluded', Buffer.alloc(0), '/', webkitFuture, 1);+ insert.run('.youtube.com', 'expired', 'excluded', Buffer.alloc(0), '/', 11644473601000000, 1);+ const cookies = await readBrowserYouTubeCookies({ profile: { id: 'fixture', browser: 'edge', directory, label: 'Test', preferred: true }, runtime, signal: AbortSignal.timeout(15000) });+ expect(cookies).toHaveLength(2);+ expect(hasYouTubeAuthentication(cookies)).toBe(true);+ expect(cookies).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'SID', secure: true, expires: future })]));+ } finally { db.close(); }+ } finally { await rm(root, { recursive: true, force: true }); }+}, 20_000);diff --git a/apps/daemon/test/integration/youtube-connection.test.ts b/apps/daemon/test/integration/youtube-connection.test.tsnew file mode 100644index 00000000..5c604a5d--- /dev/null+++ b/apps/daemon/test/integration/youtube-connection.test.ts@@ -0,0 +1,175 @@+import { access, mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import Fastify from 'fastify';+import { afterEach, expect, it, vi } from 'vitest';+import { YouTubeConnectionService } from '../../src/platform-connections/youtube.js';+import { filterYouTubeCookies, hasYouTubeAuthentication, parseYouTubeCookies, serializeYouTubeCookies } from '../../src/platform-connections/cookies.js';+import { registerPlatformConnectionRoutes } from '../../src/api/routes.platform-connections.js';+import { requireAuth } from '../../src/api/auth.js';+import type { BrowserProfile, readBrowserYouTubeCookies } from '../../src/platform-connections/browser.js';+import type { YtDlpRuntime } from '../../src/creator/yt-dlp/runtime.js';++const cookies = ['SID', 'SAPISID'].map(name => ({ name, value: `secret-${name}`, domain: '.youtube.com',+ path: '/', secure: true, httpOnly: true, expires: Date.now() / 1000 + 3600 }));+const roots: string[] = [];+const services: YouTubeConnectionService[] = [];+afterEach(async () => {+ await Promise.all(services.splice(0).map(service => service.close()));+ await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));+});++const profile: BrowserProfile = { id: 'a'.repeat(24), browser: 'chrome', label: 'Chrome · Test', directory: '/test/profile', preferred: true };+async function setup(readBrowserCookies?: typeof readBrowserYouTubeCookies) {+ const root = await mkdtemp(join(tmpdir(), 'youtube-connection-'));+ roots.push(root);+ const service = new YouTubeConnectionService({ root, getRuntime: () => runtime, listProfiles: async () => [profile], readBrowserCookies });+ services.push(service);+ await service.initialize();+ return { root, service };+}+const runtime: YtDlpRuntime = { executable: '/yt-dlp', prefixArgs: ['--js-runtimes', 'node:/node'], version: 'test', env: {} };++it('exports only valid YouTube cookies including HttpOnly, and rejects malicious cookie fields', () => {+ const filtered = filterYouTubeCookies([...cookies,+ { ...cookies[0], domain: '.google.com' }, { ...cookies[0], domain: '.youtube.com.evil.test' },+ { ...cookies[0], value: 'injection\n.example.com' }, { ...cookies[0], expires: 1 }]);+ expect(filtered).toEqual(cookies);+ const text = serializeYouTubeCookies(filtered);+ expect(text).toContain('#HttpOnly_.youtube.com\tTRUE\t/\tTRUE\t');+ expect(parseYouTubeCookies(text)).toEqual(cookies.map(c => ({ ...c, expires: Math.floor(c.expires) })));+ expect(parseYouTubeCookies(text.replace('# Netscape HTTP Cookie File', '# HTTP Cookie File'))).toHaveLength(2);+ expect(() => parseYouTubeCookies(JSON.stringify(cookies))).toThrow();+ expect(hasYouTubeAuthentication(filterYouTubeCookies([{ ...cookies[0], expires: 1 }]))).toBe(false);+});++it('keeps task snapshots isolated, preserves an active task on disconnect, and cleans files on success/failure', async () => {+ const { root, service } = await setup();+ await service.importCookies(serializeYouTubeCookies(cookies));+ const paths: string[] = [];+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ const first = service.withCookies(async () => {+ const path = service.authenticatedRuntime(runtime)!.prefixArgs.at(-1)!;+ paths.push(path);+ expect(await readFile(path, 'utf8')).toContain('secret-SID');+ if (process.platform !== 'win32') expect((await stat(path)).mode & 0o777).toBe(0o600);+ await gate;+ await access(path);+ });+ await vi.waitFor(() => expect(paths).toHaveLength(1));+ await expect(service.withCookies(async () => {+ const path = service.authenticatedRuntime(runtime)!.prefixArgs.at(-1)!;+ paths.push(path);+ throw new Error('download failed');+ })).rejects.toThrow('download failed');+ expect(paths[0]).not.toBe(paths[1]);+ await expect(access(paths[1]!)).rejects.toThrow();+ await service.disconnect();+ expect(service.authenticatedRuntime(runtime)).toBe(runtime);+ release(); await first;+ await expect(access(paths[0]!)).rejects.toThrow();+ expect(await readdir(root)).toEqual([]);+ expect((await service.getState()).status).toBe('disconnected');+});++it('automatically reads the selected browser profile without returning cookie secrets or its filesystem path', async () => {+ let finish!: (value: typeof cookies) => void;+ const read = vi.fn(() => new Promise<typeof cookies>(resolve => { finish = resolve; }));+ const { root, service } = await setup(read);+ expect((await service.connect()).status).toBe('connecting');+ await service.connect(); expect(read).toHaveBeenCalledTimes(1);+ expect(read).toHaveBeenCalledWith(expect.objectContaining({ profile }));+ finish(cookies);+ await vi.waitFor(async () => expect((await service.getState()).status).toBe('connected'));+ const publicState = JSON.stringify(await service.getState());+ expect(publicState).not.toMatch(/secret|SID|cookies|credentials|\/test\/profile/);+ if (process.platform !== 'win32') expect((await stat(join(root, 'credentials.json'))).mode & 0o777).toBe(0o600);+});++it('cancels an in-progress import and preserves the previous credential', async () => {+ const read: typeof readBrowserYouTubeCookies = ({ signal }) => new Promise((resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('canceled')), { once: true });+ });+ const { root, service } = await setup(read);+ await service.importCookies(serializeYouTubeCookies(cookies));+ const before = await readFile(join(root, 'credentials.json'), 'utf8');+ await service.connect();+ expect((await service.cancel()).status).toBe('connected');+ expect(await readFile(join(root, 'credentials.json'), 'utf8')).toBe(before);+});++it('requires Runtime auth and returns only public connection state through the API', async () => {+ const { service } = await setup();+ const server = Fastify(); server.addHook('onRequest', requireAuth('runtime-token'));+ await registerPlatformConnectionRoutes(server, service);+ try {+ expect((await server.inject({ method: 'POST', url: '/platform-connections/youtube/import', payload: { cookies: serializeYouTubeCookies(cookies) } })).statusCode).toBe(401);+ const response = await server.inject({ method: 'POST', url: '/platform-connections/youtube/import',+ headers: { authorization: 'Bearer runtime-token' }, payload: { cookies: serializeYouTubeCookies(cookies) } });+ expect(response.statusCode).toBe(200);+ expect(response.headers['cache-control']).toBe('no-store');+ expect(response.json().status).toBe('connected');+ expect(response.body).not.toMatch(/secret|SID|cookies/);+ } finally { await server.close(); }+});++it('marks explicit cookie expiry and preserves the connection on a media 403', async () => {+ const { service } = await setup();+ await service.importCookies(serializeYouTubeCookies(cookies));+ await expect(service.withCookies(async () => { throw new Error('HTTP Error 403: Forbidden'); })).rejects.toThrow('403');+ expect((await service.getState()).status).toBe('connected');+ await expect(service.withCookies(async () => { throw new Error('The cookies are no longer valid'); })).rejects.toThrow('no longer valid');+ expect((await service.getState()).status).toBe('expired');+ await service.withCookies(async () => expect(service.authenticatedRuntime(runtime)).toBe(runtime));+});++it('reuses saved browser cookies for polling, concurrent tasks, nested requests and app restarts without keychain reads', async () => {+ const read = vi.fn(async () => cookies);+ const { root, service } = await setup(read);+ await service.connect();+ await vi.waitFor(async () => expect((await service.getState()).status).toBe('connected'));++ async function useSavedCookies(connection: YouTubeConnectionService) {+ expect((await connection.getState()).status).toBe('connected');+ expect(await connection.hasAuthentication()).toBe(true);+ await connection.withCookies(async () => {+ const path = connection.authenticatedRuntime(runtime)!.prefixArgs.at(-1)!;+ expect(await readFile(path, 'utf8')).toContain('secret-SID');+ await connection.withCookies(async () => {+ expect(connection.authenticatedRuntime(runtime)!.prefixArgs.at(-1)).toBe(path);+ });+ });+ }+ await Promise.all(Array.from({ length: 5 }, () => useSavedCookies(service)));+ expect(read).toHaveBeenCalledTimes(1);++ const restarted = new YouTubeConnectionService({ root, getRuntime: () => runtime,+ listProfiles: async () => [profile], readBrowserCookies: read });+ services.push(restarted);+ await restarted.initialize();+ await useSavedCookies(restarted);+ expect(read).toHaveBeenCalledTimes(1);+});++it('requires an explicit reconnect to refresh expired browser cookies without automatic keychain prompts', async () => {+ const read = vi.fn(async () => cookies);+ const { service } = await setup(read);+ await service.connect();+ await vi.waitFor(async () => expect((await service.getState()).status).toBe('connected'));+ await expect(service.withCookies(async () => { throw new Error('The cookies are no longer valid'); }))+ .rejects.toThrow('no longer valid');+ expect((await service.getState()).status).toBe('expired');+ expect(await service.hasAuthentication()).toBe(false);+ await service.withCookies(async () => expect(service.authenticatedRuntime(runtime)).toBe(runtime));+ expect(read).toHaveBeenCalledTimes(1);++ read.mockResolvedValue(cookies.map(cookie => ({ ...cookie, value: `fresh-${cookie.name}` })));+ await service.connect(profile.id);+ await vi.waitFor(async () => expect((await service.getState()).status).toBe('connected'));+ await service.withCookies(async () => {+ const path = service.authenticatedRuntime(runtime)!.prefixArgs.at(-1)!;+ expect(await readFile(path, 'utf8')).toContain('fresh-SID');+ });+ expect(read).toHaveBeenCalledTimes(2);+});diff --git a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.tsindex 8fa2e730..230f163e 100644--- a/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts+++ b/apps/daemon/test/unit/creator-krillin-adapter-dependency.test.ts@@ -76,16 +76,19 @@ describe('KrillinAI configured transcription dependency', () => {});});- it('prepares transcription only after platform captions fail and uses the local video', async () => {+ it.each(['platform_caption_failed', 'platform_caption_invalid'])('prepares transcription after %s and reports the fallback to the frontend', async code => {const fixture = setup();runKrillinCli.mockRejectedValueOnce(new KrillinCliError(- 'platform_caption_failed',+ code,'No platform captions are available'))- .mockImplementationOnce(async input => [writeTargetSubtitle(input.jobsRoot)]);+ .mockImplementationOnce(async input => {+ input.stage.reportProgress({ phase: 'transcribing_audio', percent: 55 });+ return [writeTargetSubtitle(input.jobsRoot)];+ });- await fixture.executor.run(fixture.stage);+ const result = await fixture.executor.run(fixture.stage);expect(fixture.ensure).toHaveBeenCalledTimes(1);expect(runKrillinCli).toHaveBeenCalledTimes(2);@@ -101,13 +104,23 @@ describe('KrillinAI configured transcription dependency', () => {targetLanguage: 'zh_cn'}});+ const stage = fixture.stage as CreatorExecutorInput;+ expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({+ phase: 'fallback_to_transcription', providerStatus: 'running',+ captionSource: 'whisper', captionFallbackCode: code,+ message: expect.stringContaining('已自动切换到语音转录')+ }));+ expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({+ phase: 'transcribing_audio', percent: 55, captionFallbackCode: code, captionSource: 'whisper'+ }));+ expect(result.progress).toMatchObject({ captionFallbackCode: code, captionSource: 'whisper' });});- it('preserves platform caption diagnostics when transcription fallback also fails', async () => {+ it.each(['platform_caption_failed', 'platform_caption_invalid'])('preserves %s diagnostics when transcription fallback also fails', async code => {const fixture = setup();runKrillinCli.mockRejectedValueOnce(new KrillinCliError(- 'platform_caption_failed',+ code,'No original YouTube captions are available')).mockRejectedValueOnce(new KrillinCliError(@@ -121,6 +134,48 @@ describe('KrillinAI configured transcription dependency', () => {});});+ it('continues from unusable VTT without a local video and keeps the component preparation notice', async () => {+ const fixture = setup();+ const stage = fixture.stage as CreatorExecutorInput;+ stage.job.templateId = 'video-translation';+ stage.inputArtifacts = [];+ fixture.ensure.mockImplementationOnce(async input => {+ input.reportProgress({ phase: 'downloading_dependencies', message: 'Preparing the transcription model' });+ });+ runKrillinCli.mockImplementationOnce(async input => {+ input.stage.reportProgress({ providerStatus: 'failed', phase: 'failed' });+ throw new KrillinCliError('platform_caption_invalid', 'No usable text');+ }).mockImplementationOnce(async input => {+ const subtitle = writeTargetSubtitle(input.jobsRoot);+ return ['source_subtitle', 'target_subtitle', 'vertical_subtitle'].map(kind => ({ ...subtitle, kind }));+ });++ await fixture.executor.run(stage);++ expect(runKrillinCli.mock.calls[1]?.[0]).toMatchObject({+ source: 'https://www.youtube.com/watch?v=demo', options: { captionSource: 'whisper' }+ });+ expect(stage.reportProgress).not.toHaveBeenCalledWith(expect.objectContaining({ providerStatus: 'failed' }));+ expect(stage.reportProgress).toHaveBeenCalledWith(expect.objectContaining({+ phase: 'downloading_dependencies', captionFallbackCode: 'platform_caption_invalid',+ message: expect.stringContaining('平台字幕解析失败,已自动切换到语音转录')+ }));+ });++ it('does not start transcription after the task is canceled', async () => {+ const fixture = setup();+ const controller = new AbortController();+ const stage = fixture.stage as CreatorExecutorInput;+ stage.signal = controller.signal;+ runKrillinCli.mockImplementationOnce(async () => {+ controller.abort();+ throw new KrillinCliError('platform_caption_invalid', 'No usable text');+ });+ await expect(fixture.executor.run(stage)).rejects.toMatchObject({ code: 'platform_caption_invalid' });+ expect(fixture.ensure).not.toHaveBeenCalled();+ expect(runKrillinCli).toHaveBeenCalledTimes(1);+ });+it.each(['platform_caption_access_failed', 'platform_caption_processing_failed'])('does not download transcription components after %s', async code => {const fixture = setup();runKrillinCli.mockRejectedValueOnce(new KrillinCliError(code, 'Platform request failed'));@@ -227,7 +282,7 @@ function setup() {manifest: { resources: [] },config});- const ensure = vi.fn(async () => undefined);+ const ensure = vi.fn(async (_input: { reportProgress(progress: Record<string, unknown>): void }) => undefined);const executor = createKrillinExecutor({resourceRoot,jobsRoot,diff --git a/apps/daemon/test/unit/creator-krillin-execution-plan.test.ts b/apps/daemon/test/unit/creator-krillin-execution-plan.test.tsindex f27ab4b9..38fef923 100644--- a/apps/daemon/test/unit/creator-krillin-execution-plan.test.ts+++ b/apps/daemon/test/unit/creator-krillin-execution-plan.test.ts@@ -5,6 +5,18 @@ import {} from '../../src/creator/krillin/execution-plan.js';describe('KrillinAI CLI execution plan', () => {+ it('defers transcription until captions are absent or unusable', () => {+ expect(createKrillinCliExecutionPlan('subtitle', {+ sourceUrl: 'https://www.youtube.com/watch?v=demo', mediaSource: 'local:/video.mp4'+ }, { captionSource: 'any' })).toEqual([+ {+ source: 'https://www.youtube.com/watch?v=demo', options: { captionSource: 'platform' },+ continueOnErrorCodes: ['platform_caption_failed', 'platform_caption_invalid']+ },+ { source: 'local:/video.mp4', options: { captionSource: 'whisper' } }+ ]);+ });+it('delegates platform-caption fallback to KrillinAI in one attempt', () => {const plan = createKrillinCliExecutionPlan('subtitle',diff --git a/apps/daemon/test/unit/creator-yt-dlp-runtime.test.ts b/apps/daemon/test/unit/creator-yt-dlp-runtime.test.tsindex 9eefdf62..f3123205 100644--- a/apps/daemon/test/unit/creator-yt-dlp-runtime.test.ts+++ b/apps/daemon/test/unit/creator-yt-dlp-runtime.test.ts@@ -18,10 +18,12 @@ describe('yt-dlp runtime resolver', () => {const executable = runtimePath('yt-dlp-runtime/python/bin/python3.13');const script = runtimePath('yt-dlp-runtime/yt-dlp');const certificateBundle = runtimePath('yt-dlp-runtime/cacert.pem');+ const node = runtimePath('bin/node');await Promise.all([writeResource(executable),writeResource(script),- writeResource(certificateBundle)+ writeResource(certificateBundle),+ writeResource(node)]);expect(resolveYtDlpRuntime({@@ -32,16 +34,18 @@ describe('yt-dlp runtime resolver', () => {pythonVersion: '3.13.15',executable: 'yt-dlp-runtime/python/bin/python3.13',script: 'yt-dlp-runtime/yt-dlp',- certificateBundle: 'yt-dlp-runtime/cacert.pem'+ certificateBundle: 'yt-dlp-runtime/cacert.pem',+ javascriptRuntime: { name: 'node', version: '22.23.2', executable: 'bin/node' }}, [resource('yt-dlp-runtime/python/bin/python3.13', 'executable'),resource('yt-dlp-runtime/yt-dlp', 'asset'),- resource('yt-dlp-runtime/cacert.pem', 'asset')+ resource('yt-dlp-runtime/cacert.pem', 'asset'),+ resource('bin/node', 'executable')])})).toEqual({version: '2026.08.29.232711',executable,- prefixArgs: ['-I', '-B', script],+ prefixArgs: ['-I', '-B', script, '--js-runtimes', `node:${node}`],env: {SSL_CERT_FILE: certificateBundle},@@ -49,6 +53,17 @@ describe('yt-dlp runtime resolver', () => {});});+ it('rejects a JavaScript runtime that is not pinned as an executable', async () => {+ root = await mkdtemp(join(tmpdir(), 'creator-yt-dlp-runtime-'));+ expect(() => resolveYtDlpRuntime({+ resourceRoot: root,+ manifest: manifest({+ mode: 'standalone', version: 'test', executable: 'bin/yt-dlp',+ javascriptRuntime: { name: 'node', version: '22.23.2', executable: 'bin/node' }+ }, [resource('bin/yt-dlp', 'executable'), resource('bin/node', 'asset')])+ })).toThrow(/dependency_not_packaged.*node/);+ });+it('resolves standalone and legacy packaged executables', async () => {root = await mkdtemp(join(tmpdir(), 'creator-yt-dlp-runtime-'));const executable = runtimePath('bin/yt-dlp');diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.tsindex 0502e74e..226228cc 100644--- a/apps/daemon/test/unit/gateway-account-service.test.ts+++ b/apps/daemon/test/unit/gateway-account-service.test.ts@@ -8,6 +8,8 @@ import { createGatewayConfigStore } from '../../src/gateway/config-store.js';import Fastify from 'fastify';import { registerGatewayAccountRoutes } from '../../src/api/routes.gateway-account.js';import { createOfficialModelAccess, type OfficialModelAccess } from '../../src/gateway/model-access.js';+import { createGatewayCreatorSource } from '../../src/gateway/creator-service-source.js';+import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';const roots: string[] = [];afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });@@ -30,6 +32,69 @@ async function setup(activate = vi.fn(async () => undefined), close = vi.fn(asynreturn { service, root, client, activate, close };}+it('returns signed-in state immediately while bootstrap is still preparing model services', async () => {+ const f = await setup();+ const bootstrap = await f.client.bootstrap('access-1');+ let release!: () => void;+ const waiting = new Promise<void>(resolve => { release = resolve; });+ f.client.bootstrap.mockImplementationOnce(async () => { await waiting; return bootstrap; });+ const grant = await f.service.startAuthorization();+ const work = f.service.pollAuthorization(grant.attemptId);+ try {+ await expect.poll(() => f.service.peekState().authState).toBe('signed_in');+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, f.service);+ const response = await server.inject({ method: 'GET', url: '/gateway/account' });+ expect(response.json()).toMatchObject({ authState: 'signed_in', activationState: 'loading' });+ expect(JSON.stringify(response.json())).not.toMatch(/access-1|refresh-1|private-1/);+ const returned = await server.inject({ method: 'POST', url: '/gateway/auth/check', payload: {} });+ expect(returned.json()).toMatchObject({ authState: 'signed_in', activationState: 'loading' });+ } finally { await server.close(); }+ } finally { release(); await work; await f.service.close(); }+});++it('coalesces simultaneous authorization polls so a grant is consumed only once', async () => {+ const f = await setup();+ let release!: () => void;+ const waiting = new Promise<void>(resolve => { release = resolve; });+ f.client.pollDevice.mockImplementationOnce(async () => { await waiting; return { accessToken: 'access-1', refreshToken: 'refresh-1', expiresIn: 900 }; });+ const grant = await f.service.startAuthorization();+ const first = f.service.pollAuthorization(grant.attemptId);+ const second = f.service.pollAuthorization(grant.attemptId);+ release(); await Promise.all([first, second]);+ expect(f.client.pollDevice).toHaveBeenCalledOnce();+ expect(f.service.peekState().authState).toBe('signed_in');+ await f.service.close();+});++it('checks on foreground return without bypassing polling intervals or slow-down responses', async () => {+ const f = await setup();+ const clock = vi.spyOn(Date, 'now');+ let now = Date.now(); clock.mockImplementation(() => now);+ try {+ f.client.pollDevice.mockRejectedValue(new GatewayError('authorization_pending', 428));+ await f.service.startAuthorization();+ f.service.checkAuthorization();+ expect(f.client.pollDevice).not.toHaveBeenCalled();+ now += 5000;+ f.service.checkAuthorization();+ await f.service.pollAuthorization('1');+ expect(f.client.pollDevice).toHaveBeenCalledTimes(1);+ f.service.checkAuthorization();+ expect(f.client.pollDevice).toHaveBeenCalledTimes(1);+ f.client.pollDevice.mockRejectedValueOnce(new GatewayError('slow_down', 429));+ now += 5000; f.service.checkAuthorization(); await f.service.pollAuthorization('1');+ expect(f.client.pollDevice).toHaveBeenCalledTimes(2);+ now += 5000; f.service.checkAuthorization();+ expect(f.client.pollDevice).toHaveBeenCalledTimes(2);+ now += 5000; f.service.checkAuthorization(); await f.service.pollAuthorization('1');+ expect(f.client.pollDevice).toHaveBeenCalledTimes(3);+ now += 5000; f.service.checkAuthorization();+ expect(f.client.pollDevice).toHaveBeenCalledTimes(3);+ } finally { clock.mockRestore(); await f.service.close(); }+});+it('silently filters official families without blocking model selection or changing the raw candidate catalog', async () => {let finishProbe!: () => void;const waiting = new Promise<void>(resolve => { finishProbe = resolve; });@@ -271,13 +336,11 @@ it('reads only the public plan catalog without signing in or changing account stawait f.service.close();});-it('blocks logout with pending requests but permits same-account reauthorization after expiry', async () => {+it('permits same-account reauthorization after expiry with pending requests', async () => {let pending = false;const f = await setup(undefined, undefined, () => pending);const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);pending = true;- await expect(f.service.logout()).rejects.toMatchObject({ code: 'active_tasks' });- expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready' });const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 16 * 60_000);try {f.client.refresh.mockRejectedValueOnce(new GatewayError('auth_required', 401));@@ -292,6 +355,83 @@ it('blocks logout with pending requests but permits same-account reauthorization} finally { clock.mockRestore(); await f.service.close(); }});+it('allows the logout route with pending supplier requests and clears local credentials', async () => {+ let pending = false;+ const f = await setup(undefined, undefined, () => pending);+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ const revoke = vi.spyOn(f.client, 'logout');+ pending = true;+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, f.service);+ const response = await server.inject({ method: 'POST', url: '/gateway/auth/logout' });+ expect(response.statusCode).toBe(200);+ expect(response.json()).toMatchObject({ source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, models: [] });+ expect(f.close).toHaveBeenCalledOnce();+ expect(revoke).toHaveBeenCalledWith('access-1');+ expect(await createGatewayConfigStore(f.root).readCredentials()).toBeUndefined();+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ status: 401 });+ } finally { await server.close(); await f.service.close(); }+});++it('allows login with active and pending jobs without rotating their supplier key', async () => {+ const f = await setup(undefined, undefined, () => true, () => true);+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, f.service);+ const response = await server.inject({ method: 'POST', url: '/gateway/auth/start' });+ expect(response.statusCode).toBe(200);+ await f.service.pollAuthorization(response.json().attemptId);+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ expect(f.client.bootstrap).toHaveBeenLastCalledWith('access-1', { rotate: false });+ expect((await f.service.modelCredentials()).accountId).toBe('1');+ } finally { await server.close(); await f.service.close(); }+});++it('can sign out and sign back in with unfinished jobs, while keeping old jobs bound to their account', async () => {+ let busy = false;+ const f = await setup(undefined, undefined, () => busy, () => busy);+ const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);+ const manual = createDefaultCreatorServicesConfig();+ let original: ReturnType<ReturnType<typeof createGatewayCreatorSource>['snapshot']>;+ const source = createGatewayCreatorSource({+ account: f.service, readJobBinding: () => original,+ manual: { read: async () => manual, write: async value => value, reset: async () => manual },+ getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ original = source.snapshot();+ busy = true;+ try {+ await f.service.logout();+ const same = await f.service.startAuthorization();+ f.client.pollDevice.mockResolvedValueOnce({ accessToken: 'access-1', refreshToken: 'refresh-1', expiresIn: 900 });+ await f.service.pollAuthorization(same.attemptId);+ expect(await f.service.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ expect(() => source.assertJob('original')).not.toThrow();+ await f.service.logout();+ const other = await f.service.startAuthorization(); await f.service.pollAuthorization(other.attemptId);+ expect(await f.service.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready', account: { id: '3' } });+ const execute = vi.fn();+ await expect(source.runForJob('original', 'stage', execute)).rejects.toMatchObject({ code: 'task_source_mismatch' });+ expect(execute).not.toHaveBeenCalled();+ } finally { await source.revoke(); await f.service.close(); }+});++it('signs out locally when usage reporting and remote logout are unavailable', async () => {+ const f = await setup();+ const binding = { ...await f.client.bootstrap('access-1'), keyRotation: true };+ f.client.bootstrap.mockResolvedValue(binding);+ const request = vi.spyOn(f.client, 'request').mockResolvedValue({ keyVersion: binding.keyVersion });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ request.mockRejectedValue(new GatewayError('gateway_unavailable'));+ vi.spyOn(f.client, 'logout').mockRejectedValue(new GatewayError('gateway_unavailable'));+ await f.service.logout();+ expect(await f.service.readState()).toMatchObject({ source: 'manual', authState: 'signed_out', account: null });+ expect(f.close).toHaveBeenCalledOnce();+ expect(await createGatewayConfigStore(f.root).readCredentials()).toBeUndefined();+ await f.service.close();+});+it('rejects a different account during expired-session recovery and preserves original credentials', async () => {let pending = false;const f = await setup(undefined, undefined, () => pending);@@ -407,16 +547,27 @@ it('restores a failed activation on restart from a fresh bootstrap without signi} finally { await restored.close(); }});-it('blocks official activation when pending tasks appear during initial authorization', async () => {+it('completes official activation when pending tasks appear during initial authorization', async () => {let pending = false;const f = await setup(undefined, undefined, () => pending);const grant = await f.service.startAuthorization(); pending = true;await f.service.pollAuthorization(grant.attemptId);- expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'blocked', activationError: { code: 'active_tasks' } });- expect(f.activate).not.toHaveBeenCalled();+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: '1' }, activationError: null });+ expect(f.client.bootstrap).toHaveBeenLastCalledWith('access-1', { rotate: false });+ expect(f.activate).toHaveBeenCalledOnce();await f.service.close();});+it('restores a signed-in session after restart even when unfinished jobs remain', async () => {+ const f = await setup();+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId); await f.service.close();+ const restored = module.createGatewayAccountService({ dataDir: f.root, client: f.client, activateRuntime: f.activate, closeRuntime: f.close, hasActiveTasks: () => true, hasPendingTasks: () => true, automaticPolling: false });+ try {+ expect(await restored.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ expect(f.client.bootstrap).toHaveBeenLastCalledWith('access-1', { rotate: false });+ } finally { await restored.close(); }+});+it('restores existing signed-in manual sessions as official and keeps guests manual', async () => {const f = await setup();const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId); await f.service.close();@@ -430,15 +581,19 @@ it('restores existing signed-in manual sessions as official and keeps guests manawait guest.close();});-it('blocks logout before changing account state while tasks are active', async () => {+it('allows logout while tasks and model uses are active, closing Runtime and rejecting new uses', async () => {let active = false;const f = await setup(undefined, undefined, undefined, () => active);const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ const use = await f.service.beginModelUse();active = true;- await expect(f.service.logout()).rejects.toMatchObject({ code: 'active_tasks' });- expect((await f.service.readState()).authState).toBe('signed_in');- expect(f.close).not.toHaveBeenCalled();- active = false; await f.service.logout(); await f.service.close();+ await f.service.logout();+ expect(await f.service.readState()).toMatchObject({ source: 'manual', authState: 'signed_out', account: null });+ expect(f.close).toHaveBeenCalledOnce();+ await expect(f.service.beginModelUse()).rejects.toMatchObject({ status: 401 });+ expect(await createGatewayConfigStore(f.root).readCredentials()).toBeUndefined();+ await use.release();+ await f.service.close();});it('syncs profile photos independently of unavailable model services and protects the avatar route', async () => {diff --git a/apps/desktop/e2e/creator-packaged-app.spec.ts b/apps/desktop/e2e/creator-packaged-app.spec.tsindex bbdc4296..7781c496 100644--- a/apps/desktop/e2e/creator-packaged-app.spec.ts+++ b/apps/desktop/e2e/creator-packaged-app.spec.ts@@ -624,6 +624,7 @@ test('@package-smoke 实际 Desktop 包创建并重启恢复 Creator Job,且executable: string;script: string;certificateBundle: string;+ javascriptRuntime: { name: 'node'; version: string; executable: string };};resources: Array<{ path: string; kind: string }>;};@@ -636,6 +637,7 @@ test('@package-smoke 实际 Desktop 包创建并重启恢复 Creator Job,且executableResource('bin/krillinai-cli'),executableResource('bin/ffmpeg'),executableResource('bin/ffprobe'),+ runtimeManifest.ytDlp.javascriptRuntime.executable,runtimeManifest.ytDlp.executable,runtimeManifest.ytDlp.script,runtimeManifest.ytDlp.certificateBundle@@ -644,8 +646,14 @@ test('@package-smoke 实际 Desktop 包创建并重启恢复 Creator Job,且expect(runtimeManifest.ytDlp).toMatchObject({mode: 'python',version: '2026.08.29.232711',- pythonVersion: '3.13.15'+ pythonVersion: '3.13.15',+ javascriptRuntime: { name: 'node', version: '22.23.2' }});+ expect(execFileSync(join(runtimeRoot, runtimeManifest.ytDlp.javascriptRuntime.executable),+ ['--version'], { encoding: 'utf8', timeout: 10_000 }).trim()).toBe('v22.23.2');+ expect(execFileSync(join(runtimeRoot, runtimeManifest.ytDlp.javascriptRuntime.executable),+ ['-e', 'let sum = 0; for (let i = 0; i < 100000; i++) sum += i; process.stdout.write(String(sum))'],+ { encoding: 'utf8', timeout: 10_000 }).trim()).toBe('4999950000');expect(runtimeManifest.resources.some(resource => (resource.path.endsWith('.pyc')|| resource.path.includes('/__pycache__/')@@ -1673,9 +1681,10 @@ async function waitForWorkspace(page: Page): Promise<void> {)?.phase).toBe('ready');const confirmed = await page.evaluate(() => window.localStorage.getItem('opencreator.agent-setup-confirmed.v1') !== null);if (!confirmed) {- const setup = page.getByRole('heading', { name: '开始使用 Agent' });+ const setup = page.getByRole('region', { name: '开始使用 Agent' });await setup.waitFor({ state: 'visible', timeout: 5_000 }).catch(() => undefined);if (await setup.isVisible()) {+ await page.getByRole('button', { name: '本地模式', exact: true }).click();await page.getByRole('button', { name: '使用本机 Codex,继续' }).click();await expect(setup).toBeHidden();}diff --git a/apps/desktop/e2e/desktop.spec.ts b/apps/desktop/e2e/desktop.spec.tsindex 0bdaae08..a2b347ba 100644--- a/apps/desktop/e2e/desktop.spec.ts+++ b/apps/desktop/e2e/desktop.spec.ts@@ -46,19 +46,133 @@ const fakeCodexLauncherSource = join(e2eDir, 'fixtures', 'fake-codex-launcher.gotest.describe.configure({ mode: 'serial' });+test('@package-smoke 充值回跳进入个人中心并以网关订单确认到账', async ({}, testInfo) => {+ let paid = false;+ let orderChecks = 0;+ const account = { id: 'billing-test', email: '[email protected]', verified: true };+ const gateway = createServer((request, response) => {+ response.setHeader('Content-Type', 'application/json');+ const path = request.url?.split('?')[0];+ if (path === '/api/v1/auth/device/start') response.end(JSON.stringify({ attemptId: 'billing-attempt', deviceSecret: 'test-device-secret', authorizationUrl: `${origin}/device`, interval: 5, expiresIn: 600 }));+ else if (path === '/api/v1/auth/device/token') response.end(JSON.stringify({ accessToken: 'billing-access', refreshToken: 'billing-refresh', expiresIn: 900 }));+ else if (path === '/api/v1/client/bootstrap') { response.statusCode = 503; response.end(JSON.stringify({ error: { code: 'services_not_ready' } })); }+ else if (path === '/api/v1/me') response.end(JSON.stringify({ account }));+ else if (path === '/api/v1/billing/summary') response.end(JSON.stringify({ balance: { availableUnits: paid ? '2500000000' : '0', reservedUnits: '0', periodEnd: null, asOf: new Date().toISOString() }, subscription: null, billingAvailable: false, plansUrl: origin + '/pricing' }));+ else if (path === '/api/v1/billing/orders/order-a') {+ if (request.headers.authorization !== 'Bearer billing-access') { response.statusCode = 401; response.end(JSON.stringify({ error: { code: 'auth_required' } })); return; }+ orderChecks++;+ response.end(JSON.stringify({ order: { id: 'order-a', planId: 'starter', currency: 'usd', amountUnits: '500', creditUnits: '2500000000', status: paid ? 'completed' : 'pending', paymentStatus: paid ? 'paid' : 'pending', creditStatus: paid ? 'ready' : 'pending', reviewRequired: false, paymentMode: 'test', createdAt: new Date().toISOString(), paidAt: null, completedAt: null } }));+ } else response.end(JSON.stringify({ items: [] }));+ });+ await new Promise<void>(resolve => gateway.listen(0, '127.0.0.1', resolve));+ const origin = `http://127.0.0.1:${(gateway.address() as AddressInfo).port}`;+ let fixture: DesktopFixture | undefined;+ try {+ fixture = await launchPackagedDesktop('success', { gatewayOrigin: origin });+ await waitForWorkspace(fixture.page);+ await runtimeRequest(fixture.page, 'POST', '/gateway/auth/start', {});+ await runtimeRequest(fixture.page, 'POST', '/gateway/auth/check', {});+ await navigateToAppRoute(fixture.page, '#/account');+ await expect(fixture.page.getByRole('heading', { name: account.email })).toBeVisible();+ await navigateToAppRoute(fixture.page, '#/new');+ await launchSecondInstance(fixture, ['opencreator://billing/return?orderId=order-a']);+ await expect(fixture.page).toHaveURL(/#\/account\?billing=return&orderId=order-a$/);+ await expect(fixture.page.getByText('待付款', { exact: true })).toBeVisible();+ await expect(fixture.page.getByText(/充值成功/)).toHaveCount(0);+ paid = true;+ await fixture.page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await expect(fixture.page.getByText('充值成功,已到账 2500 积分', { exact: true })).toBeVisible();+ await expect(fixture.page.locator('.account-credits__value')).toContainText('2500');+ expect(orderChecks).toBeGreaterThanOrEqual(2);+ await expect(fixture.page.getByRole('dialog')).toHaveCount(0);+ await expect(fixture.page.getByRole('tab')).toHaveCount(0);+ await fixture.page.screenshot({ path: testInfo.outputPath('billing-return-account.png') });+ } finally {+ if (fixture) await closeFixture(fixture);+ gateway.closeAllConnections();+ await new Promise<void>(resolve => gateway.close(() => resolve()));+ }+});++test('@package-smoke 授权回调唤起个人中心,模型初始化期间立即显示登录态', async ({}, testInfo) => {+ let approved = false;+ let tokenRequests = 0;+ let releaseBootstrap!: () => void;+ const bootstrapReady = new Promise<void>(resolve => { releaseBootstrap = resolve; });+ const account = { id: 'login-test', email: '[email protected]', verified: true };+ const gateway = createServer(async (request, response) => {+ response.setHeader('Content-Type', 'application/json');+ const path = request.url?.split('?')[0];+ if (path === '/api/v1/auth/device/start') {+ response.end(JSON.stringify({ attemptId: 'login-attempt', deviceSecret: 'private-device-secret', authorizationUrl: `${origin}/device?grant=login-attempt`, interval: 5, expiresIn: 600 }));+ } else if (path === '/api/v1/auth/device/token') {+ tokenRequests++;+ response.statusCode = approved ? 200 : 428;+ response.end(JSON.stringify(approved ? { accessToken: 'private-access', refreshToken: 'private-refresh', expiresIn: 900 } : { error: { code: 'authorization_pending' } }));+ } else if (path === '/api/v1/client/bootstrap') {+ await bootstrapReady;+ response.statusCode = 503;+ response.end(JSON.stringify({ error: { code: 'services_not_ready' } }));+ } else if (path === '/api/v1/me') {+ response.end(JSON.stringify({ account }));+ } else if (path === '/api/v1/plans') {+ response.end(JSON.stringify({ plans: [], billingAvailable: false }));+ } else if (path === '/api/v1/billing/summary') {+ response.end(JSON.stringify({ balance: { availableUnits: '0', reservedUnits: '0', periodEnd: null, asOf: new Date().toISOString() }, subscription: null, billingAvailable: false }));+ } else {+ response.end(JSON.stringify({ ok: true }));+ }+ });+ await new Promise<void>(resolve => gateway.listen(0, '127.0.0.1', resolve));+ const origin = `http://127.0.0.1:${(gateway.address() as AddressInfo).port}`;+ let fixture: DesktopFixture | undefined;+ try {+ fixture = await launchPackagedDesktop('success', { gatewayOrigin: origin });+ await waitForWorkspace(fixture.page);+ const grant = await runtimeRequest(fixture.page, 'POST', '/gateway/auth/start', {});+ expect(grant.status).toBe(200);+ await navigateToAppRoute(fixture.page, '#/account');+ await expect(fixture.page.getByText('请在浏览器中完成登录')).toBeVisible();+ await fixture.page.getByRole('button', { name: '最小化窗口', exact: true }).click();+ approved = true;+ const checks: string[] = [];+ fixture.page.on('request', request => { if (request.url().endsWith('/gateway/auth/check')) checks.push(request.url()); });+ await launchSecondInstance(fixture, ['opencreator://auth/complete']);+ await expect(fixture.page).toHaveURL(/#\/account\?login=complete$/);+ await expect.poll(() => checks.length).toBeGreaterThan(0);+ await expect(fixture.page.getByText('已登录,正在连接模型服务…')).toBeVisible({ timeout: 10_000 });+ const state = await runtimeRequest<{ authState: string; activationState: string }>(fixture.page, 'GET', '/gateway/account');+ expect(state.body).toMatchObject({ authState: 'signed_in', activationState: 'loading' });+ expect(tokenRequests).toBe(1);+ await fixture.page.screenshot({ path: testInfo.outputPath('login-models-loading.png') });+ releaseBootstrap();+ await expect(fixture.page.getByRole('heading', { name: account.email, exact: true })).toBeVisible();+ await expect(fixture.page.getByText('已登录,模型服务暂不可用', { exact: true })).toBeVisible();+ await expect(fixture.page.getByRole('button', { name: '重新连接', exact: true })).toBeEnabled();+ const signedIn = await runtimeRequest(fixture.page, 'GET', '/gateway/account');+ expect(signedIn.body).toMatchObject({ authState: 'signed_in', activationState: 'blocked', account });+ expect(JSON.stringify(signedIn.body)).not.toMatch(/private-access|private-refresh|private-device-secret/);+ } finally {+ releaseBootstrap();+ if (fixture) await closeFixture(fixture);+ gateway.closeAllConnections();+ await new Promise<void>(resolve => gateway.close(() => resolve()));+ }+});+test('@package-smoke 全新账号启动时引导配置 Agent,跳过后可重新配置', async () => {const fixture = await launchPackagedDesktop('success', { signedOut: true });try {await waitForRuntimeReady(fixture.page, false);- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeVisible();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeVisible();await expect(fixture.page.getByRole('combobox', { name: '供应商' })).toBeVisible();await expect(fixture.page.getByRole('button', { name: '使用 ChatGPT 登录' })).toHaveCount(0);- await fixture.page.getByRole('button', { name: '暂时跳过' }).click();+ await fixture.page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();await fixture.page.getByRole('button', { name: '设置', exact: true }).click();await fixture.page.getByRole('button', { name: /AI 服务/ }).click();await expect(fixture.page.getByText('Agent 尚未配置,无法发送任务。')).toBeVisible();await fixture.page.getByRole('button', { name: '配置 Agent' }).click();- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeVisible();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeVisible();} finally {await closeFixture(fixture);}@@ -68,12 +182,12 @@ test('@package-smoke 已有 API 凭据时仍显示复用确认和手动填写入const fixture = await launchPackagedDesktop('success');try {await waitForRuntimeReady(fixture.page, false);- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeVisible();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeVisible();await expect(fixture.page.getByRole('button', { name: '自定义模型服务' })).toBeVisible();await expect(fixture.page.getByText(/API Key 已配置/)).toBeVisible();await expect(fixture.page.getByLabel('API Key')).toHaveCount(0);await fixture.page.getByRole('button', { name: '使用本机 Codex,继续' }).click();- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeHidden();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeHidden();} finally {await closeFixture(fixture);}@@ -83,12 +197,12 @@ test('@package-smoke 自定义 Provider 无 ChatGPT 登录态时可复用已有const fixture = await launchPackagedDesktop('success', { seedLocalCodexProvider: true });try {await waitForRuntimeReady(fixture.page, false);- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeVisible();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeVisible();await expect(fixture.page.getByText('已找到本机 Codex')).toBeVisible();await expect(fixture.page.getByText(/API Key 已配置 · custom-model/)).toBeVisible();await expect(fixture.page.getByLabel('API Key')).toHaveCount(0);await fixture.page.getByRole('button', { name: '使用本机 Codex,继续' }).click();- await expect(fixture.page.getByRole('heading', { name: '开始使用 Agent' })).toBeHidden();+ await expect(fixture.page.getByRole('region', { name: '开始使用 Agent' })).toBeHidden();expect(existsSync(join(fixture.root, 'codex-home', 'auth.json'))).toBe(false);} finally {await closeFixture(fixture);@@ -1191,6 +1305,42 @@ test('@package-smoke 创作模块连接内嵌 Runtime 并使用默认项目', as}});+test('@package-smoke YouTube 连接复用已登录 Chrome 并自动保存登录态', async ({}, testInfo) => {+ test.skip(process.platform !== 'darwin' || process.env.OPENCREATOR_E2E_REAL_YOUTUBE !== '1', 'Requires an existing signed-in local Chrome profile');+ let fixture = await launchPackagedDesktop('success');+ try {+ await waitForWorkspace(fixture.page);+ await navigateToAppRoute(fixture.page, '#/settings?tab=platform-connections');+ await expect(fixture.page.getByRole('heading', { name: '平台连接', exact: true })).toBeVisible();+ await expect(fixture.page.getByRole('combobox', { name: '浏览器账号' })).toBeVisible();+ await fixture.page.getByRole('button', { name: '连接', exact: true }).click();+ await expect(fixture.page.getByRole('status').filter({ hasText: '已连接' })).toBeVisible({ timeout: 30_000 });+ const state = await runtimeRequest<{ status: string }>(fixture.page, 'GET', '/platform-connections/youtube');+ expect(state.body.status).toBe('connected');+ expect(JSON.stringify(state.body)).not.toMatch(/SAPISID|secret|cookies|credentials/);+ await fixture.page.screenshot({ path: testInfo.outputPath('youtube-connected.png') });+ if (process.env.OPENCREATOR_E2E_YOUTUBE_PROXY) {+ expect((await runtimeRequest(fixture.page, 'PATCH', '/creator-services/network', { proxy: process.env.OPENCREATOR_E2E_YOUTUBE_PROXY })).status).toBe(200);+ }+ for (let attempt = 0; attempt < 2; attempt++) {+ const metadata = await runtimeRequest<{ title: string }>(fixture.page, 'GET', '/video-metadata?url=' + encodeURIComponent('https://www.youtube.com/watch?v=m5yrQMnc_jQ'));+ expect(metadata.status).toBe(200);+ expect(metadata.body.title.length).toBeGreaterThan(0);+ }+ const previous = fixture;+ await closePackagedApp(previous);+ fixture = { ...await relaunchPackagedApp(previous), root: previous.root, stateDir: previous.stateDir };+ await waitForWorkspace(fixture.page);+ await navigateToAppRoute(fixture.page, '#/settings?tab=platform-connections');+ await expect(fixture.page.getByRole('status').filter({ hasText: '已连接' })).toBeVisible();+ const restoredMetadata = await runtimeRequest<{ title: string }>(fixture.page, 'GET', '/video-metadata?url=' + encodeURIComponent('https://www.youtube.com/watch?v=m5yrQMnc_jQ'));+ expect(restoredMetadata.status).toBe(200);+ expect(restoredMetadata.body.title.length).toBeGreaterThan(0);+ await fixture.page.getByRole('button', { name: '断开', exact: true }).click();+ await expect(fixture.page.getByRole('status').filter({ hasText: '未连接' })).toBeVisible();+ } finally { await closeFixture(fixture); }+});+test('@package-smoke 设置关闭后退出时,关闭按钮结束实际 App', async () => {test.skip(process.platform !== 'darwin', 'Custom window controls are macOS only');const fixture = await launchPackagedDesktop('success');@@ -1225,6 +1375,7 @@ async function launchPackagedDesktop(seedLocalCodex?: boolean;seedLocalCodexProvider?: boolean;telemetryUrl?: string;+ gatewayOrigin?: string;} = {}): Promise<DesktopFixture> {const root = mkdtempSync(join(tmpdir(), 'opencreator-desktop-e2e-'));@@ -1300,6 +1451,7 @@ async function launchPackagedDesktop(OPENCREATOR_E2E_FAKE_CODEX_CUSTOM_PROVIDER: options.seedLocalCodexProvider ? '1' : '0',OPENCREATOR_E2E_NODE_BINARY: process.execPath,OPENCREATOR_E2E_FAKE_CODEX_SCRIPT: fakeCodexScript,+ ...(options.gatewayOrigin ? { OPENCREATOR_GATEWAY_ORIGIN: options.gatewayOrigin } : {}),...(options.telemetryUrl === undefined? {}: { OPENCREATOR_TELEMETRY_URL: options.telemetryUrl }),@@ -1398,7 +1550,6 @@ async function waitForRuntimeReady(page: Page, confirmSetup = true): Promise<voiawait expect.poll(async () => await page.evaluate(async () => {return (await window.opencreatorDesktop?.readBootstrapState())?.phase;})).toBe('ready');- if (!confirmSetup) return;const confirmed = await page.evaluate(() => window.localStorage.getItem('opencreator.agent-setup-confirmed.v1') !== null);if (confirmed) return;const setup = page.getByRole('region', { name: '开始使用 Agent' });@@ -1406,10 +1557,11 @@ async function waitForRuntimeReady(page: Page, confirmSetup = true): Promise<voiif (!await setup.isVisible()) return;const localMode = page.getByRole('button', { name: '本地模式', exact: true });if (await localMode.isVisible()) await localMode.click();+ if (!confirmSetup) return;const useLocalCodex = page.getByRole('button', { name: '使用本机 Codex,继续' });if (await useLocalCodex.isVisible()) await useLocalCodex.click();await setup.waitFor({ state: 'hidden', timeout: 3_000 }).catch(() => undefined);- if (await setup.isVisible()) await page.getByRole('button', { name: '暂时跳过' }).click();+ if (await setup.isVisible()) await page.getByRole('button', { name: '稍后配置,进入本地模式' }).click();}async function runtimeRequest<T>(diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex fafeb7d0..4b46010d 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -1,6 +1,6 @@{"name": "@opencreator/desktop",- "version": "3.2.5",+ "version": "3.2.6","private": true,"description": "OpenCreator 本地 Codex Dashboard","author": "OpenCreator",@@ -47,7 +47,7 @@"esbuild": "^0.25.0","fontkit": "2.0.4","node-gyp": "13.0.2",- "sharp": "0.35.4",+ "sharp": "0.35.5","typescript": "^5.7.3","vite": "^6.0.7","vitest": "^3.2.7"diff --git a/apps/desktop/packaging/daemon-runtime/package.json b/apps/desktop/packaging/daemon-runtime/package.jsonindex a1dce913..85193524 100644--- a/apps/desktop/packaging/daemon-runtime/package.json+++ b/apps/desktop/packaging/daemon-runtime/package.json@@ -6,7 +6,7 @@"dependencies": {"@fastify/cors": "11.2.0","@iarna/toml": "2.2.5",- "@modelcontextprotocol/sdk": "1.29.0",+ "@modelcontextprotocol/sdk": "1.31.0","better-sqlite3": "12.11.1","cheerio": "1.1.2","cron-parser": "5.6.1",@@ -17,7 +17,7 @@"nanoid": "5.1.16","pdf-parse": "1.1.1","pdfkit": "0.20.2",- "sharp": "0.35.4",+ "sharp": "0.35.5","toml": "4.2.0","yaml": "2.9.0","yauzl": "3.4.0",@@ -25,6 +25,7 @@},"pnpm": {"overrides": {+ "proxy-addr@<2.0.8": "2.0.8","ws@>=8.0.0 <8.21.0": "8.21.0"}}diff --git a/apps/desktop/packaging/daemon-runtime/pnpm-lock.yaml b/apps/desktop/packaging/daemon-runtime/pnpm-lock.yamlindex c88d2453..eecd4537 100644--- a/apps/desktop/packaging/daemon-runtime/pnpm-lock.yaml+++ b/apps/desktop/packaging/daemon-runtime/pnpm-lock.yaml@@ -5,6 +5,7 @@ settings:excludeLinksFromLockfile: falseoverrides:+ proxy-addr@<2.0.8: 2.0.8ws@>=8.0.0 <8.21.0: 8.21.0importers:@@ -18,8 +19,8 @@ importers:specifier: 2.2.5version: 2.2.5'@modelcontextprotocol/sdk':- specifier: 1.29.0- version: 1.29.0([email protected])+ specifier: 1.31.0+ version: 1.31.0([email protected])better-sqlite3:specifier: 12.11.1version: 12.11.1@@ -51,8 +52,8 @@ importers:specifier: 0.20.2version: 0.20.2sharp:- specifier: 0.35.4- version: 0.35.4+ specifier: 0.35.5+ version: 0.35.5toml:specifier: 4.2.0version: 4.2.0@@ -105,166 +106,150 @@ packages:resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}engines: {node: '>=18'}- '@img/[email protected]':- resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}engines: {node: '>=20.9.0'}cpu: [x64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}engines: {node: '>=20.9.0'}os: [freebsd]- '@img/[email protected]':- resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}cpu: [arm64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}cpu: [x64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}cpu: [arm64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}cpu: [arm]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}cpu: [ppc64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}cpu: [riscv64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==}+ '@img/[email protected]':+ resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}cpu: [s390x]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}cpu: [x64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}cpu: [arm64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}cpu: [x64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}engines: {node: '>=20.9.0'}cpu: [arm]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}engines: {node: '>=20.9.0'}cpu: [ppc64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}engines: {node: '>=20.9.0'}cpu: [riscv64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}engines: {node: '>=20.9.0'}cpu: [s390x]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}engines: {node: '>=20.9.0'}- '@img/[email protected]':- resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}engines: {node: '>=20.9.0'}cpu: [wasm32]- '@img/[email protected]':- resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [win32]- '@img/[email protected]':- resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}engines: {node: ^20.9.0}cpu: [ia32]os: [win32]- '@img/[email protected]':- resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}engines: {node: '>=20.9.0'}cpu: [x64]os: [win32]- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==}engines: {node: '>=18'}peerDependencies:'@cfworker/json-schema': ^4.1.1@@ -832,8 +817,8 @@ packages:resolution: {integrity: sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==}- resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}+ resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}engines: {node: '>= 0.10'}@@ -927,8 +912,8 @@ packages:resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}- resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==}+ resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}engines: {node: '>=20.9.0'}peerDependencies:'@types/node': '*'@@ -1118,111 +1103,111 @@ snapshots:'@img/[email protected]': {}- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-darwin-arm64': 1.3.3+ '@img/sharp-libvips-darwin-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-darwin-x64': 1.3.3+ '@img/sharp-libvips-darwin-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:- '@img/sharp-wasm32': 0.35.4+ '@img/sharp-wasm32': 0.35.5optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-arm64': 1.3.3+ '@img/sharp-libvips-linux-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-arm': 1.3.3+ '@img/sharp-libvips-linux-arm': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-ppc64': 1.3.3+ '@img/sharp-libvips-linux-ppc64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-riscv64': 1.3.3+ '@img/sharp-libvips-linux-riscv64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-s390x': 1.3.3+ '@img/sharp-libvips-linux-s390x': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-x64': 1.3.3+ '@img/sharp-libvips-linux-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linuxmusl-x64': 1.3.3+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:'@emnapi/runtime': 1.11.3optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:- '@img/sharp-wasm32': 0.35.4+ '@img/sharp-wasm32': 0.35.5optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@modelcontextprotocol/[email protected]([email protected])':+ '@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 1.19.17([email protected])ajv: 8.20.0@@ -1515,7 +1500,7 @@ snapshots:on-finished: 2.4.1once: 1.4.0parseurl: 1.3.3- proxy-addr: 2.0.7+ proxy-addr: 2.0.8qs: 6.16.0range-parser: 1.3.0router: 2.2.0@@ -1850,7 +1835,7 @@ snapshots:dependencies:forwarded: 0.2.0ipaddr.js: 1.9.1@@ -1956,37 +1941,37 @@ snapshots:dependencies:'@img/colour': 1.1.0detect-libc: 2.1.2semver: 7.8.5optionalDependencies:- '@img/sharp-darwin-arm64': 0.35.4- '@img/sharp-darwin-x64': 0.35.4- '@img/sharp-freebsd-wasm32': 0.35.4- '@img/sharp-libvips-darwin-arm64': 1.3.3- '@img/sharp-libvips-darwin-x64': 1.3.3- '@img/sharp-libvips-linux-arm': 1.3.3- '@img/sharp-libvips-linux-arm64': 1.3.3- '@img/sharp-libvips-linux-ppc64': 1.3.3- '@img/sharp-libvips-linux-riscv64': 1.3.3- '@img/sharp-libvips-linux-s390x': 1.3.3- '@img/sharp-libvips-linux-x64': 1.3.3- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3- '@img/sharp-libvips-linuxmusl-x64': 1.3.3- '@img/sharp-linux-arm': 0.35.4- '@img/sharp-linux-arm64': 0.35.4- '@img/sharp-linux-ppc64': 0.35.4- '@img/sharp-linux-riscv64': 0.35.4- '@img/sharp-linux-s390x': 0.35.4- '@img/sharp-linux-x64': 0.35.4- '@img/sharp-linuxmusl-arm64': 0.35.4- '@img/sharp-linuxmusl-x64': 0.35.4- '@img/sharp-webcontainers-wasm32': 0.35.4- '@img/sharp-win32-arm64': 0.35.4- '@img/sharp-win32-ia32': 0.35.4- '@img/sharp-win32-x64': 0.35.4+ '@img/sharp-darwin-arm64': 0.35.5+ '@img/sharp-darwin-x64': 0.35.5+ '@img/sharp-freebsd-wasm32': 0.35.5+ '@img/sharp-libvips-darwin-arm64': 1.3.4+ '@img/sharp-libvips-darwin-x64': 1.3.4+ '@img/sharp-libvips-linux-arm': 1.3.4+ '@img/sharp-libvips-linux-arm64': 1.3.4+ '@img/sharp-libvips-linux-ppc64': 1.3.4+ '@img/sharp-libvips-linux-riscv64': 1.3.4+ '@img/sharp-libvips-linux-s390x': 1.3.4+ '@img/sharp-libvips-linux-x64': 1.3.4+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4+ '@img/sharp-linux-arm': 0.35.5+ '@img/sharp-linux-arm64': 0.35.5+ '@img/sharp-linux-ppc64': 0.35.5+ '@img/sharp-linux-riscv64': 0.35.5+ '@img/sharp-linux-s390x': 0.35.5+ '@img/sharp-linux-x64': 0.35.5+ '@img/sharp-linuxmusl-arm64': 0.35.5+ '@img/sharp-linuxmusl-x64': 0.35.5+ '@img/sharp-webcontainers-wasm32': 0.35.5+ '@img/sharp-win32-arm64': 0.35.5+ '@img/sharp-win32-ia32': 0.35.5+ '@img/sharp-win32-x64': 0.35.5dependencies:diff --git a/apps/desktop/release-notes/v3.2.6.md b/apps/desktop/release-notes/v3.2.6.mdnew file mode 100644index 00000000..7613ce41--- /dev/null+++ b/apps/desktop/release-notes/v3.2.6.md@@ -0,0 +1,9 @@+## What's New++- Connect an OpenCreator account to use official model and media services, view credit balances, and manage account settings.+- Simplify the personal center and open the website for subscriptions and credit purchases, with payment status refreshed when returning to the app.+- Show sign-in status promptly after browser authorization and allow signing in or out while tasks are pending.+- Connect YouTube through an existing Chrome profile and save its login session for video downloads and translation.+- Fall back to Whisper transcription when platform captions are unusable and show the fallback reason in task progress.+- Bundle a JavaScript runtime for yt-dlp to improve YouTube download compatibility.+- Update runtime dependencies and fix high-severity dependency audit findings.diff --git a/apps/desktop/scripts/creator-runtime-contract.mjs b/apps/desktop/scripts/creator-runtime-contract.mjsindex b1213386..ec02d2e4 100644--- a/apps/desktop/scripts/creator-runtime-contract.mjs+++ b/apps/desktop/scripts/creator-runtime-contract.mjs@@ -93,8 +93,23 @@ function verifyYtDlpRuntime(descriptor, resourcesByPath) {) {throw new Error('Creator Runtime yt-dlp descriptor is missing or invalid');}+ const javascriptKeys = descriptor.javascriptRuntime === undefined ? [] : ['javascriptRuntime'];+ if (descriptor.javascriptRuntime !== undefined) {+ const javascript = descriptor.javascriptRuntime;+ if (+ javascript === null+ || typeof javascript !== 'object'+ || javascript.name !== 'node'+ || typeof javascript.version !== 'string'+ || javascript.version.length === 0+ ) {+ throw new Error('Creator Runtime yt-dlp JavaScript runtime is invalid');+ }+ assertDescriptorKeys(javascript, ['name', 'version', 'executable']);+ assertRuntimeResource(resourcesByPath, javascript.executable, 'executable', 'Node executable');+ }if (descriptor.mode === 'standalone') {- assertDescriptorKeys(descriptor, ['mode', 'version', 'executable']);+ assertDescriptorKeys(descriptor, ['mode', 'version', 'executable', ...javascriptKeys]);assertRuntimeResource(resourcesByPath,descriptor.executable,@@ -110,7 +125,8 @@ function verifyYtDlpRuntime(descriptor, resourcesByPath) {'pythonVersion','executable','script',- 'certificateBundle'+ 'certificateBundle',+ ...javascriptKeys]);if (typeof descriptor.pythonVersion !== 'string'diff --git a/apps/desktop/scripts/creator-runtime-releases.mjs b/apps/desktop/scripts/creator-runtime-releases.mjsindex 079ab3aa..7bee43e8 100644--- a/apps/desktop/scripts/creator-runtime-releases.mjs+++ b/apps/desktop/scripts/creator-runtime-releases.mjs@@ -2,6 +2,7 @@ export function creatorRuntimeReleases() {return {'darwin-arm64': creatorRuntimeRelease({mediaTarget: 'darwin-arm64',+ nodeSha256: '61130f394c1630d211dd50aecc4353d379480f36d3ac913cd85dbba1aed585c6',ffmpegSha256: 'a90e3db6a3fd35f6074b013f948b1aa45b31c6375489d39e572bea3f18336584',ffprobeSha256: 'bb2db6f5d8cef919da12fbf592119a987202a8c060a886f3cab091f9cab90b64',pythonAsset: 'cpython-3.13.15+20260825-aarch64-apple-darwin-install_only_stripped.tar.gz',@@ -9,6 +10,7 @@ export function creatorRuntimeReleases() {}),'darwin-x64': creatorRuntimeRelease({mediaTarget: 'darwin-x64',+ nodeSha256: '58e99022c2ff89395576cc7fd4d98cea24bb68081475d5f88b801ee8729fb026',mediaVersion: '6.1.1',ffmpegSha256: 'ebdddc936f61e14049a2d4b549a412b8a40deeff6540e58a9f2a2da9e6b18894',ffprobeSha256: 'fa3add0ce901f7241abe0dfc0155d958fc834aca3f8ce61f87cc712ae669c1e0',@@ -17,6 +19,7 @@ export function creatorRuntimeReleases() {}),'linux-arm64': creatorRuntimeRelease({mediaTarget: 'linux-arm64',+ nodeSha256: '013b59cfd2819703a6f4a14ab891fc46fc2a4e3f5bcd92de3fb4929b43e35b30',ffmpegSha256: '6bb182d0d75d23028db82e9e4f723ca69b853d055698486e6984ddb2c06fb8ce',ffprobeSha256: 'd17ae9b4c297d48e2521ba14e417bb0537c6ff77c584cdbcd6bb0d8d0307a2e8',pythonAsset: 'cpython-3.13.15+20260825-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz',@@ -24,6 +27,7 @@ export function creatorRuntimeReleases() {}),'linux-x64': creatorRuntimeRelease({mediaTarget: 'linux-x64',+ nodeSha256: 'b294a556e639d64338823920e5866c21c02741742d2e1529ee1a225c1ec9252a',ffmpegSha256: 'e7e7fb30477f717e6f55f9180a70386c62677ef8a4d4d1a5d948f4098aa3eb99',ffprobeSha256: '4f231a1960d83e403d08f7971e271707bec278a9ae18e21b8b5b03186668450d',pythonAsset: 'cpython-3.13.15+20260825-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz',@@ -31,6 +35,7 @@ export function creatorRuntimeReleases() {}),'win32-x64': creatorRuntimeRelease({mediaTarget: 'win32-x64',+ nodeSha256: '1177b4137ba5adaa56354ae40f1080c7450e8ae09cecb47da459d1c52ac99f97',mediaVersion: '6.1.1',ffmpegSha256: '04e1307997530f9cf2fe35cba2ca7e8875ca91da02f89d6c7243df819c94ad00',ffprobeSha256: '3a7e2dc003dc2cd1472827e4c7c4f056ae1ae0ae7c5bbc580c99b49827351ba4',@@ -47,6 +52,9 @@ function creatorRuntimeRelease(input) {const pythonRelease = '20260825';const pythonVersion = '3.13.15';const ytDlpVersion = '2026.08.29.232711';+ const nodeVersion = '22.23.2';+ const nodeTarget = input.mediaTarget.replace('win32-', 'win-');+ const nodeExtension = suffix === '.exe' ? 'zip' : 'tar.gz';const encodedPythonAsset = input.pythonAsset.replace('+', '%2B');return {ffmpeg: {@@ -79,6 +87,12 @@ function creatorRuntimeRelease(input) {url: `https://github.com/astral-sh/python-build-standalone/releases/download/${pythonRelease}/${encodedPythonAsset}`,sha256: input.pythonSha256},+ nodeRuntime: {+ version: nodeVersion,+ fileName: `node-runtime.${nodeExtension}`,+ url: `https://nodejs.org/dist/v${nodeVersion}/node-v${nodeVersion}-${nodeTarget}.${nodeExtension}`,+ sha256: input.nodeSha256+ },certificateBundle: {version: '2026.07.22',fileName: 'cacert.pem',diff --git a/apps/desktop/scripts/prepare-creator-runtime.mjs b/apps/desktop/scripts/prepare-creator-runtime.mjsindex 1ec40799..f3a2e29a 100644--- a/apps/desktop/scripts/prepare-creator-runtime.mjs+++ b/apps/desktop/scripts/prepare-creator-runtime.mjs@@ -18,6 +18,7 @@ import { tmpdir } from 'node:os';import { dirname, join, relative, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import * as fontkit from 'fontkit';+import { verifyRuntimeExecutable } from './runtime-executable-check.mjs';const scriptDir = dirname(fileURLToPath(import.meta.url));const desktopDir = resolve(scriptDir, '..');@@ -73,6 +74,10 @@ for (const [name, configured, vendored] of externalInputs) {copyExecutable(source, target);}const ytDlpRuntime = prepareYtDlpRuntime(vendorVersions);+const javascriptRuntime = prepareYtDlpJavascriptRuntime(vendorVersions);+ytDlpRuntime.descriptor.javascriptRuntime = javascriptRuntime.descriptor;+ytDlpRuntime.resourcePaths.push(...javascriptRuntime.resourcePaths);+ytDlpRuntime.executablePaths.push(javascriptRuntime.executable);for (const path of [primaryExecutablePath,...externalInputs.map(([name]) => join(binDir, `${name}${executableSuffix}`)),@@ -331,7 +336,8 @@ function ensureExternalDependencies() {[process.env.OPENCREATOR_FFPROBE_PATH, join(vendorRoot, `ffprobe${executableSuffix}`)],[configuredYtDlpPath, join(vendorRoot, 'yt-dlp')],[configuredYtDlpPath, join(vendorRoot, 'python-runtime.tar.gz')],- [configuredYtDlpPath, join(vendorRoot, 'cacert.pem')]+ [configuredYtDlpPath, join(vendorRoot, 'cacert.pem')],+ [process.env.OPENCREATOR_YT_DLP_NODE_PATH, join(vendorRoot, targetPlatform === 'win32' ? 'node-runtime.zip' : 'node-runtime.tar.gz')]];if (required.every(([configured, vendored]) => configured || existsSync(vendored))) return;execFileSync(process.execPath, [join(scriptDir, 'install-creator-runtime-dependencies.mjs')], {@@ -441,6 +447,44 @@ function prepareYtDlpRuntime(vendorVersions) {};}+function prepareYtDlpJavascriptRuntime(vendorVersions) {+ const configured = process.env.OPENCREATOR_YT_DLP_NODE_PATH?.trim();+ const executable = join(binDir, `node${executableSuffix}`);+ const resourcePaths = [executable];+ let version = vendorVersions?.dependencies?.nodeRuntime?.version;+ if (configured) {+ copyExecutable(resolveExecutable('node', configured), executable);+ version = commandOutput(executable, ['--version'], rootDir).trim().replace(/^v/, '');+ } else {+ if (!version) throw new Error('yt-dlp JavaScript runtime version is missing');+ const extractionRoot = mkdtempSync(join(tmpdir(), 'opencreator-node-runtime-'));+ try {+ execFileSync(process.platform === 'win32' ? 'tar.exe' : 'tar', [+ '-xf', join(vendorRoot, targetPlatform === 'win32' ? 'node-runtime.zip' : 'node-runtime.tar.gz'),+ '-C', extractionRoot+ ], { stdio: 'ignore' });+ const nodeTarget = `${targetPlatform === 'win32' ? 'win' : targetPlatform}-${targetArch}`;+ const extracted = join(extractionRoot, `node-v${version}-${nodeTarget}`);+ copyExecutable(join(extracted, targetPlatform === 'win32' ? 'node.exe' : 'bin/node'), executable);+ const license = join(outputRoot, 'licenses', 'node', 'LICENSE');+ mkdirSync(dirname(license), { recursive: true });+ copyFileSync(join(extracted, 'LICENSE'), license);+ resourcePaths.push(license);+ } finally {+ rmSync(extractionRoot, { recursive: true, force: true });+ }+ }+ if (targetPlatform === process.platform && targetArch === process.arch) {+ verifyRuntimeExecutable({ name: 'yt-dlp Node runtime', path: executable,+ args: ['--version'], expected: /^v(?:2[2-9]|[3-9]\d)\./, timeoutMs: 20_000 });+ }+ return {+ descriptor: { name: 'node', version, executable: relative(outputRoot, executable).replaceAll('\\', '/') },+ executable,+ resourcePaths+ };+}+function extractPythonRuntime(archive, destination) {execFileSync(process.platform === 'win32' ? 'tar.exe' : 'tar', ['-xzf',diff --git a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjsindex 36be5cd0..b215131a 100644--- a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs+++ b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs@@ -103,7 +103,8 @@ export async function signCreatorRuntimeBundle(context, options = {}) {return signPackagedRuntime(context, options, {name: 'Creator Runtime',relativeRoot: ['creator-runtime', 'krillinai'],- verifyRuntime: options.verifyRuntime ?? verifyCreatorRuntime+ verifyRuntime: options.verifyRuntime ?? verifyCreatorRuntime,+ javascriptEntitlements: remotionBrowserEntitlements});}@@ -143,7 +144,10 @@ async function signPackagedRuntime(context, options, runtime) {}const verifyRuntime = runtime.verifyRuntime;- verifyRuntime(runtimeRoot, 'darwin', arch);+ const manifest = verifyRuntime(runtimeRoot, 'darwin', arch);+ const javascriptExecutable = runtime.javascriptEntitlements && manifest?.ytDlp?.javascriptRuntime+ ? resolve(runtimeRoot, manifest.ytDlp.javascriptRuntime.executable)+ : undefined;const signingInfo = await context.packager.codeSigningInfo.value;const keychainFile = signingInfo?.keychainFile ?? null;@@ -157,7 +161,12 @@ async function signPackagedRuntime(context, options, runtime) {const signBinary = options.signBinary ?? signMachOBinary;for (const path of binaries) {- await signBinary(path, identity, keychainFile);+ if (resolve(path) === javascriptExecutable) {+ // Node's V8 needs JIT permissions under macOS hardened runtime.+ await signBinary(path, identity, keychainFile, runtime.javascriptEntitlements);+ } else {+ await signBinary(path, identity, keychainFile);+ }}if (runtime.updateManifest !== false) {updateManifestHashes(runtimeRoot, binaries);diff --git a/apps/desktop/src/main/deep-link-manager.ts b/apps/desktop/src/main/deep-link-manager.tsindex 15dbba38..a5cf218f 100644--- a/apps/desktop/src/main/deep-link-manager.ts+++ b/apps/desktop/src/main/deep-link-manager.ts@@ -7,7 +7,7 @@ export function deepLinkToRoute(value: string): string | undefined {} catch {return undefined;}- if (url.protocol !== 'opencreator:') return undefined;+ if (url.protocol !== 'opencreator:' || url.username || url.password || url.port) return undefined;const rawSegments = [url.hostname, ...url.pathname.split('/')].filter(segment => segment.length > 0);@@ -20,6 +20,16 @@ export function deepLinkToRoute(value: string): string | undefined {const queryValues = parseStrictQuery(url.search);if (queryValues === undefined) return undefined;+ if (segments[0] === 'auth' && segments[1] === 'complete' && segments.length === 2) {+ if (url.search || url.hash) return undefined;+ return '#/account?login=complete';+ }+ if (segments[0] === 'billing' && segments[1] === 'return' && segments.length === 2) {+ if (url.hash || [...queryValues.keys()].some(key => key !== 'orderId')) return undefined;+ const orderId = queryValues.get('orderId');+ if (orderId !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(orderId)) return undefined;+ return '#/account?billing=return' + (orderId ? '&orderId=' + encodeURIComponent(orderId) : '');+ }if (segments[0] === 'new' && segments.length === 1) return '#/';if (segments[0] === 'tasks' && segments.length === 1) return '#/tasks';if (segments[0] !== 'thread' || segments.length !== 2) return undefined;diff --git a/apps/desktop/test/creator-runtime-package.test.mjs b/apps/desktop/test/creator-runtime-package.test.mjsindex 45623ce5..dc1868e8 100644--- a/apps/desktop/test/creator-runtime-package.test.mjs+++ b/apps/desktop/test/creator-runtime-package.test.mjs@@ -33,6 +33,17 @@ describe('Creator Runtime package contract', () => {});});+ it.each(['python', 'standalone'])('validates the bundled Node runtime in %s mode', ytDlpMode => {+ createFixture({ ytDlpMode, javascriptRuntime: true });+ expect(verifyCreatorRuntime(root, process.platform, process.arch).ytDlp.javascriptRuntime).toMatchObject({+ name: 'node', version: '22.23.2'+ });+ createFixture({ ytDlpMode, javascriptRuntime: true, mutateManifest(manifest) {+ manifest.resources.find(resource => resource.path === manifest.ytDlp.javascriptRuntime.executable).kind = 'asset';+ } });+ expect(() => verifyCreatorRuntime(root, process.platform, process.arch)).toThrow(/Node executable is not a manifest-pinned executable/);+ });+it('rejects the legacy source-built OpenCreator service runtime', () => {createFixture({ legacyService: true });expect(() => verifyCreatorRuntime(root, process.platform, process.arch)).toThrow(@@ -124,6 +135,7 @@ function createFixture(options = {}) {primary: join(bin, `krillinai-cli${suffix}`),ffmpeg: join(bin, `ffmpeg${suffix}`),ffprobe: join(bin, `ffprobe${suffix}`),+ ...(options.javascriptRuntime ? { node: join(bin, `node${suffix}`) } : {}),...(ytDlpMode === 'standalone'? {ytDlp: join(bin, `yt-dlp${suffix}`)@@ -176,6 +188,12 @@ function createFixture(options = {}) {script: resources.find(resource => resource.path.endsWith('/yt-dlp')).path,certificateBundle: resources.find(resource => resource.path.endsWith('/cacert.pem')).path};+ if (options.javascriptRuntime) {+ ytDlp.javascriptRuntime = {+ name: 'node', version: '22.23.2',+ executable: resources.find(resource => resource.path === `bin/node${suffix}`).path+ };+ }const manifest = {version: 1,runtimeMode: legacyService ? 'service' : 'cli',diff --git a/apps/desktop/test/creator-runtime-signing.test.mjs b/apps/desktop/test/creator-runtime-signing.test.mjsindex 658f28d0..dc99c8cb 100644--- a/apps/desktop/test/creator-runtime-signing.test.mjs+++ b/apps/desktop/test/creator-runtime-signing.test.mjs@@ -165,6 +165,22 @@ describe('Creator Runtime Developer ID signing', () => {)).toThrow(/absent from its manifest/i);});+ it('grants V8 JIT permissions only to the bundled Node executable', async () => {+ const fixture = createFixture({ javascriptRuntime: true });+ const signBinary = vi.fn();+ await signCreatorRuntimeBundle(createContext(fixture.appOutDir), {+ env: signingEnv(), findIdentity: () => 'Developer ID Application: Junxi YIN (NVRH5R5DJ5)',+ findBinaries: () => fixture.binaryPaths, signBinary+ });+ for (const call of signBinary.mock.calls) {+ if (call[0] === join(fixture.runtimeRoot, 'bin', 'node')) {+ expect(readFileSync(call[3], 'utf8')).toMatch(/com\.apple\.security\.cs\.allow-jit<\/key>\s*<true\/>/);+ } else {+ expect(call).toHaveLength(3);+ }+ }+ });+it('signs the packaged Stickman browser and refreshes its manifest', async () => {const fixture = createStickmanFixture();const signBinary = vi.fn(path => {@@ -246,7 +262,7 @@ function signingEnv() {};}-function createFixture() {+function createFixture(options = {}) {const root = mkdtempSync(join(tmpdir(), 'opencreator-runtime-signing-'));temporaryDirectories.push(root);const appOutDir = join(root, 'mac-arm64');@@ -263,6 +279,7 @@ function createFixture() {'bin/ffmpeg': 'ffmpeg','bin/ffprobe': 'ffprobe','bin/yt-dlp': 'yt-dlp',+ ...(options.javascriptRuntime ? { 'bin/node': 'node' } : {}),'build-record.json': '{"version":1}','subtitle-style.json': '{"version":1}'};@@ -288,7 +305,10 @@ function createFixture() {ytDlp: {mode: 'standalone',version: 'test',- executable: 'bin/yt-dlp'+ executable: 'bin/yt-dlp',+ ...(options.javascriptRuntime ? { javascriptRuntime: {+ name: 'node', version: '22.23.2', executable: 'bin/node'+ } } : {})},resources};@@ -303,7 +323,8 @@ function createFixture() {join(runtimeRoot, 'bin', 'krillinai-cli'),join(runtimeRoot, 'bin', 'ffmpeg'),join(runtimeRoot, 'bin', 'ffprobe'),- join(runtimeRoot, 'bin', 'yt-dlp')+ join(runtimeRoot, 'bin', 'yt-dlp'),+ ...(options.javascriptRuntime ? [join(runtimeRoot, 'bin', 'node')] : [])]};}diff --git a/apps/desktop/test/deep-link-manager.test.ts b/apps/desktop/test/deep-link-manager.test.tsindex 1ab67249..4557f903 100644--- a/apps/desktop/test/deep-link-manager.test.ts+++ b/apps/desktop/test/deep-link-manager.test.ts@@ -2,6 +2,21 @@ import { describe, expect, it } from 'vitest';import { deepLinkToRoute } from '../src/main/deep-link-manager.js';describe('Desktop deep-link validation', () => {+ it('returns to the account page with an order ID but never trusts payment claims', () => {+ expect(deepLinkToRoute('opencreator://billing/return')).toBe('#/account?billing=return');+ expect(deepLinkToRoute('opencreator://billing/return?orderId=order-1')).toBe('#/account?billing=return&orderId=order-1');+ for (const value of ['opencreator://billing/return?orderId=', 'opencreator://billing/return?orderId=order%2F1', 'opencreator://billing/return?paid=true', 'opencreator://billing/return#paid', 'opencreator://billing/return/extra']) expect(deepLinkToRoute(value), value).toBeUndefined();+ });+ it('opens the account page for the fixed authorization callback without accepting credentials', () => {+ expect(deepLinkToRoute('opencreator://auth/complete')).toBe('#/account?login=complete');+ for (const value of [+ 'opencreator://auth/complete?token=secret',+ 'opencreator://auth/complete#secret',+ 'opencreator://user@auth/complete',+ 'opencreator://auth:80/complete',+ 'opencreator://auth/complete/extra'+ ]) expect(deepLinkToRoute(value), value).toBeUndefined();+ });it('rejects any malformed path or query encoding as one invalid link', () => {for (const value of ['opencreator://thread/%',diff --git a/apps/desktop/test/release-runtime-regressions.test.mjs b/apps/desktop/test/release-runtime-regressions.test.mjsindex ab171702..75fda7da 100644--- a/apps/desktop/test/release-runtime-regressions.test.mjs+++ b/apps/desktop/test/release-runtime-regressions.test.mjs@@ -58,7 +58,7 @@ describe('Desktop release runtime regressions', () => {'@iarna/toml': '2.2.5','cross-spawn': '7.0.6',fastify: '5.12.2',- sharp: '0.35.4',+ sharp: '0.35.5',toml: '4.2.0',yauzl: '3.4.0'});diff --git a/apps/web/e2e/gateway-web-desktop-parity.spec.ts b/apps/web/e2e/gateway-web-desktop-parity.spec.tsindex 51aeb4c5..9622c2e9 100644--- a/apps/web/e2e/gateway-web-desktop-parity.spec.ts+++ b/apps/web/e2e/gateway-web-desktop-parity.spec.ts@@ -1,27 +1,55 @@import { test, expect } from './fixtures/runtime.js';-test('账户入口在同尺寸 Browser/Desktop Bridge 下读取同一个 Daemon 并显示一致', async ({ browser, runtime }, testInfo) => {+test('个人中心在 Browser/Desktop 使用同一布局与网页充值入口', async ({ browser, runtime }, testInfo) => {test.skip(testInfo.project.name !== 'chromium-desktop');- const states: unknown[] = [];- for (const platform of ['browser', 'desktop']) {- const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: 'reduce' });- const page = await context.newPage();- if (platform === 'desktop') await page.addInitScript(() => {- Object.defineProperty(window, 'opencreatorDesktop', { value: {- kind:'desktop', readAppVersion:async()=> '3.2.2', readConnectionConfig:async()=>({baseUrl:'/.opencreator/runtime'}), subscribeConnectionConfig:()=>()=>undefined,- readDesktopPreferences:async()=>({closeBehavior:'hide'}), updateDesktopPreferences:async()=>({closeBehavior:'hide'}), workspaceReady:()=>undefined,- subscribeNavigation:()=>()=>undefined, notify:async()=>undefined, configureBackgroundNotifications:async()=>({ok:true}),- openExternal:async(url:string)=>{ (window as unknown as { __gatewayURL?: string }).__gatewayURL=url; }- } });- });- try {- await runtime.openApp(page); await page.getByRole('button', { name: '账户', exact: true }).click();- const account = page.getByRole('region', { name:'OpenCreator 账户' });- await expect(account.getByRole('button', { name:'登录 / 注册' })).toBeVisible();- await expect(account.getByRole('button', { name:'本地模式' })).toHaveCount(0);- states.push({text:await account.innerText(),box:await account.boundingBox()});- await page.screenshot({path:testInfo.outputPath(`gateway-${platform}.png`)});- } finally { await context.close(); }+ for (const viewport of [{ width: 1280, height: 800 }, { width: 390, height: 844 }]) {+ const snapshots: unknown[] = [];+ for (const platform of ['browser', 'desktop']) {+ const context = await browser.newContext({ viewport, reducedMotion: 'reduce' });+ const page = await context.newPage();+ await page.addInitScript(() => localStorage.setItem('opencreator.agent-setup-confirmed.v1', '1'));+ const handoffURL = runtime.origin + '/auth?lang=zh#handoff=' + 'a'.repeat(43);+ const requests: Array<{ destination: string; locale: string }> = [];+ await context.route('**/auth?lang=zh*', route => route.fulfill({ body: '<html><body>Account portal</body></html>', contentType: 'text/html' }));+ await context.route('**/gateway/**', async route => {+ const path = new URL(route.request().url()).pathname;+ let value: unknown;+ if (path.endsWith('/gateway/account') || path.endsWith('/gateway/auth/check')) value = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'account-a', email: '[email protected]', verified: true }, bindingVersion: null, models: [], activationError: null };+ else if (path.endsWith('/gateway/billing/summary')) value = { balance: { availableUnits: '413937000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-10T01:00:00Z' }, subscription: null, billingAvailable: false, plansUrl: runtime.origin + '/pricing' };+ else if (path.endsWith('/gateway/billing/orders')) value = { items: [] };+ else if (path.endsWith('/gateway/account/web')) { const body = route.request().postDataJSON(); requests.push({ destination: body.destination, locale: body.locale }); value = { url: handoffURL }; }+ else { await route.continue(); return; }+ await route.fulfill({ json: value });+ });+ if (platform === 'desktop') await page.addInitScript(() => {+ Object.defineProperty(window, 'opencreatorDesktop', { value: {+ kind: 'desktop', readAppVersion: async () => '3.2.5', readConnectionConfig: async () => ({ baseUrl: '/.opencreator/runtime' }), subscribeConnectionConfig: () => () => {},+ readDesktopPreferences: async () => ({ closeBehavior: 'hide' }), updateDesktopPreferences: async () => ({ closeBehavior: 'hide' }), workspaceReady: () => {},+ subscribeNavigation: () => () => {}, notify: async () => {}, configureBackgroundNotifications: async () => ({ ok: true }),+ openExternal: async (url: string) => { (window as unknown as { __gatewayURL?: string }).__gatewayURL = url; }+ } });+ });+ try {+ await runtime.openApp(page);+ await page.evaluate(() => { window.location.hash = '#/account'; });+ const center = page.getByRole('main', { name: '个人中心' });+ await expect(center.locator('.account-credits__value')).toContainText('413.937');+ await expect(center.getByRole('button', { name: '充值积分' })).toBeEnabled();+ await expect(center.getByRole('tab')).toHaveCount(0);+ snapshots.push({ text: await center.innerText(), box: await center.locator('.personal-center__content').boundingBox() });+ await page.screenshot({ path: testInfo.outputPath(`account-${platform}-${viewport.width}.png`) });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ if (platform === 'browser') {+ const popup = page.waitForEvent('popup');+ await center.getByRole('button', { name: '充值积分' }).click();+ const portal = await popup; await expect(portal).toHaveURL(handoffURL); await portal.close();+ } else {+ await center.getByRole('button', { name: '充值积分' }).click();+ await expect.poll(() => page.evaluate(() => (window as unknown as { __gatewayURL?: string }).__gatewayURL)).toBe(handoffURL);+ }+ expect(requests).toEqual([{ destination: 'recharge', locale: 'zh' }]);+ } finally { await context.close(); }+ }+ expect(snapshots[1]).toEqual(snapshots[0]);}- expect(states[1]).toEqual(states[0]);});diff --git a/apps/web/public/youtube.ico b/apps/web/public/youtube.iconew file mode 100644index 00000000..f4d96647Binary files /dev/null and b/apps/web/public/youtube.ico differdiff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsxindex 4b7aaf73..a7754d05 100644--- a/apps/web/src/app/AppController.tsx+++ b/apps/web/src/app/AppController.tsx@@ -134,6 +134,7 @@ import { createApprovalService } from '../services/approval-service.js';import { createConnectionService, type ConnectionState } from '../services/connection-service.js';import { createCreatorServicesService } from '../services/creator-services-service.js';import { createGatewayAccountService } from '../services/gateway-account-service.js';+import { createPlatformConnectionsService } from '../services/platform-connections-service.js';import type { GatewayAccountState } from '@opencreator/protocol';import { createCreatorService } from '../services/creator-service.js';import { createCleanupService } from '../services/cleanup-service.js';@@ -617,7 +618,11 @@ export function AppController(props: AppControllerProps) {() => runtimeClient === null ? null : createCreatorServicesService(runtimeClient),[runtimeClient]);- const gatewayAccountService = useMemo(() => runtimeClient === null ? null : createGatewayAccountService(runtimeClient), [runtimeClient]);+ const gatewayAccountService = useMemo(() => runtimeClient === null ? null : createGatewayAccountService(runtimeClient, { authorizationReturnUrl: hostBridge.authorizationReturnUrl, billingReturnUrl: hostBridge.billingReturnUrl }), [runtimeClient, hostBridge]);+ useEffect(() => hostBridge.subscribeBillingReturn?.(billingOrderId => {+ props.onNavigate({ view: 'account', ...(billingOrderId ? { billingOrderId } : {}) });+ }), [hostBridge, props.onNavigate]);+ const platformConnectionsService = useMemo(() => runtimeClient === null ? null : createPlatformConnectionsService(runtimeClient), [runtimeClient]);const [gatewayAccountState, setGatewayAccountState] = useState<GatewayAccountState>();const officialTextModels = useMemo(() => {if (!gatewayAccountState || (gatewayAccountState.source === 'manual' && gatewayAccountState.authState === 'signed_out')) return undefined;@@ -637,10 +642,26 @@ export function AppController(props: AppControllerProps) {useEffect(() => {if (connectionState.status !== 'connected' || !gatewayAccountService) return;let canceled = false;- const refresh = () => { void gatewayAccountService.getState().then(next => { if (!canceled) onGatewayStateChange(next); }).catch(() => undefined); };+ let sequence = 0;+ const refresh = (checkAuthorization = false) => {+ const request = ++sequence;+ void gatewayAccountService.getState({ checkAuthorization }).then(next => {+ if (!canceled && request === sequence) onGatewayStateChange(next);+ }).catch(() => undefined);+ };+ const onReturn = () => refresh(true);+ const onVisible = () => { if (document.visibilityState === 'visible') onReturn(); };refresh();const timer = setInterval(() => { if (previousGatewaySource.current === 'gateway') refresh(); }, 3000);- return () => { canceled = true; clearInterval(timer); };+ window.addEventListener('focus', onReturn);+ window.addEventListener('hashchange', onReturn);+ document.addEventListener('visibilitychange', onVisible);+ return () => {+ canceled = true; clearInterval(timer);+ window.removeEventListener('focus', onReturn);+ window.removeEventListener('hashchange', onReturn);+ document.removeEventListener('visibilitychange', onVisible);+ };}, [gatewayAccountService, connectionState.status, onGatewayStateChange]);const openCreatorSettingsService = useMemo(() => runtimeClient === null ? null : createOpenCreatorSettingsService(runtimeClient),@@ -4697,15 +4718,16 @@ export function AppController(props: AppControllerProps) {/>) : state.activeView === 'account' || state.activeView === 'subscription' ? (<PersonalCenterPage- key={state.activeView}view={state.activeView}service={gatewayAccountService}accountState={gatewayAccountState}+ billingOrderId={props.route.view === 'account' ? props.route.billingOrderId : undefined}+ billingReturnUrl={hostBridge.billingReturnUrl}+ prepareExternalNavigation={hostBridge.prepareExternalNavigation}onStateChange={onGatewayStateChange}openExternal={url => hostBridge.openExternal(url)}- onOpenSubscription={() => openPrimaryView('subscription')}+ onOpenModelSettings={() => navigateToRoute({ view: 'settings', tab: 'ai-services' })}onBack={() => {- if (state.activeView === 'subscription') { openPrimaryView('account'); return; }applyRouteFromLocation(accountReturnRouteRef.current);navigateToRoute(accountReturnRouteRef.current);}}@@ -4723,6 +4745,7 @@ export function AppController(props: AppControllerProps) {customAccentColor={customAccentColor}onCustomAccentColorChange={handleCustomAccentColorChange}storageSettingsService={openCreatorSettingsService}+ platformConnectionsService={platformConnectionsService}onSelectStorageDirectory={hostBridge.selectProjectDirectory}desktopCloseBehavior={desktopCloseBehavior}onDesktopCloseBehaviorChange={(behavior: 'hide' | 'quit') => {diff --git a/apps/web/src/app/routes.test.ts b/apps/web/src/app/routes.test.tsindex d7d2ac4c..c71f9bfc 100644--- a/apps/web/src/app/routes.test.ts+++ b/apps/web/src/app/routes.test.ts@@ -2,6 +2,12 @@ import { describe, expect, it } from 'vitest';import { formatRoute, parseRoute } from './routes.js';describe('app routes', () => {+ it('round-trips a billing order return and ignores unverified payment parameters', () => {+ const route = { view: 'account' as const, billingOrderId: 'order-a' };+ expect(parseRoute(formatRoute(route))).toEqual(route);+ expect(parseRoute('#/account?billing=return&orderId=order-a&paid=true')).toEqual(route);+ expect(parseRoute('#/account?billing=return&orderId=..%2Fother')).toEqual({ view: 'account' });+ });it('round-trips the personal center route', () => {expect(formatRoute({ view: 'account' })).toBe('#/account');expect(parseRoute('#/account')).toEqual({ view: 'account' });diff --git a/apps/web/src/app/routes.ts b/apps/web/src/app/routes.tsindex 7b558588..56dc6887 100644--- a/apps/web/src/app/routes.ts+++ b/apps/web/src/app/routes.ts@@ -18,7 +18,7 @@ export type AppRoute =| { view: 'schedules'; scheduleId?: string }| { view: 'tasks' }| { view: 'dashboard' }- | { view: 'account' }+ | { view: 'account'; billingOrderId?: string }| { view: 'subscription' }| {view: 'plugins';@@ -36,7 +36,7 @@ export type AppRoute =| { view: 'files'; threadId?: string; path?: string };export type AiServicesSection = 'text' | 'transcription' | 'tts' | 'image' | 'video';-export type SettingsRouteTab = 'ai-services' | 'local-components';+export type SettingsRouteTab = 'ai-services' | 'local-components' | 'platform-connections';export function parseRoute(hash: string): AppRoute {const [path = '', query = ''] = hash.split('?', 2);@@ -79,7 +79,11 @@ export function parseRoute(hash: string): AppRoute {}if (path === '#/tasks') return { view: 'tasks' };if (path === '#/dashboard') return { view: 'dashboard' };- if (path === '#/account') return { view: 'account' };+ if (path === '#/account') {+ const params = new URLSearchParams(query);+ const id = params.get('orderId');+ return { view: 'account', ...(params.get('billing') === 'return' && id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? { billingOrderId: id } : {}) };+ }if (path === '#/subscription') return { view: 'subscription' };if (path === '#/plugins') {const fields = parseQuery(query);@@ -103,7 +107,7 @@ export function parseRoute(hash: string): AppRoute {}return {view: 'settings',- ...(tab === 'local-components'+ ...(tab === 'local-components' || tab === 'platform-connections'? { tab }: tab === 'ai-services' || section !== undefined? { tab: 'ai-services' as const }@@ -161,7 +165,7 @@ export function formatRoute(route: AppRoute): string {case 'dashboard':return '#/dashboard';case 'account':- return '#/account';+ return route.billingOrderId ? '#/account?billing=return&orderId=' + encodeURIComponent(route.billingOrderId) : '#/account';case 'subscription':return '#/subscription';case 'plugins': {diff --git a/apps/web/src/features/account/PersonalCenterPage.test.tsx b/apps/web/src/features/account/PersonalCenterPage.test.tsxindex 199d3245..e3d65728 100644--- a/apps/web/src/features/account/PersonalCenterPage.test.tsx+++ b/apps/web/src/features/account/PersonalCenterPage.test.tsx@@ -6,31 +6,32 @@ import { LanguageProvider } from '../../i18n/LanguageProvider.js';import type { GatewayAccountSettingsService, GatewayBillingSummary } from '../../services/gateway-account-service.js';import PersonalCenterPage from './PersonalCenterPage.js';-afterEach(cleanup);+afterEach(() => { cleanup(); sessionStorage.clear(); });const signedOut: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };const signedIn: GatewayAccountState = { ...signedOut, source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true } };const summary: GatewayBillingSummary = { balance: { availableUnits: '123000000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' }, subscription: null, billingAvailable: true };function createService(initial = signedIn): GatewayAccountSettingsService {- return { getState: vi.fn(async () => initial), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(async () => signedOut), activate: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(async () => summary), getPlans: vi.fn(), checkout: vi.fn(), portal: vi.fn() };+ return { getState: vi.fn(async () => initial), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(async () => signedOut), activate: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(async () => summary), getPlans: vi.fn(async () => ({ plans: [], billingAvailable: false })), getOrders: vi.fn(async () => ({ items: [] })), getOrder: vi.fn(), getCreditGrants: vi.fn(async () => ({ items: [] })), checkout: vi.fn(), portal: vi.fn() };}-function page(service: GatewayAccountSettingsService | null, accountState?: GatewayAccountState, onBack = vi.fn(), openExternal = vi.fn(), view: 'account' | 'subscription' = 'account', onOpenSubscription = vi.fn()) {- return <LanguageProvider initialPreference="zh-CN"><PersonalCenterPage view={view} service={service} accountState={accountState} onBack={onBack} openExternal={openExternal} onOpenSubscription={onOpenSubscription}/></LanguageProvider>;+function page(service: GatewayAccountSettingsService | null, accountState?: GatewayAccountState, onBack = vi.fn(), openExternal = vi.fn(), view: 'account' | 'subscription' = 'account', onOpenModelSettings = vi.fn()) {+ return <LanguageProvider initialPreference="zh-CN"><PersonalCenterPage view={view} service={service} accountState={accountState} onBack={onBack} openExternal={openExternal} onOpenModelSettings={onOpenModelSettings}/></LanguageProvider>;}it('provides a single login action and a credits entry with no fabricated guest balance', async () => {const service = createService(signedOut); const open = vi.fn();- render(page(service, signedOut, vi.fn(), vi.fn(), 'account', open));+ render(page(service, signedOut, vi.fn(), open));expect(await screen.findByRole('button', { name: '登录 / 注册' })).toBeEnabled();expect(screen.getAllByRole('button', { name: '登录 / 注册' })).toHaveLength(1);- await userEvent.setup().click(screen.getByRole('button', { name: '积分与充值' }));- expect(open).toHaveBeenCalledOnce();- expect(screen.queryByRole('heading', { name: '可用积分' })).not.toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(open).toHaveBeenCalledWith(expect.stringContaining('/pricing?lang=zh'));+ expect(screen.queryByText('123')).not.toBeInTheDocument();expect(service.getSummary).not.toHaveBeenCalled();});-it('links guests to website plans from the recharge page', async () => {+it('keeps the old recharge route on the unified personal center', async () => {const service = createService(signedOut);render(page(service, signedOut, vi.fn(), vi.fn(), 'subscription'));- expect(screen.getByRole('main', { name: '积分与充值' })).toBeInTheDocument();- expect(await screen.findByRole('link', { name: '查看积分方案' })).toHaveAttribute('href', 'https://www.open-creator.ai/pricing?lang=zh');+ expect(screen.getByRole('main', { name: '个人中心' })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: '充值积分' })).toBeEnabled();expect(service.checkout).not.toHaveBeenCalled();expect(service.getSummary).not.toHaveBeenCalled();});@@ -51,17 +52,18 @@ it('loads credits immediately after login', async () => {render(page(service, signedOut, vi.fn(), open));await userEvent.setup().click(await screen.findByRole('button', { name: '登录 / 注册' }));expect(await screen.findByText('123')).toBeInTheDocument();- expect(open).toHaveBeenCalledWith('https://gateway.example/device');+ expect(open).toHaveBeenCalledWith('https://gateway.example/device?lang=zh');});it('clears the balance after logout', async () => {const service = createService();vi.mocked(service.logout).mockImplementation(async () => { vi.mocked(service.getState).mockResolvedValue(signedOut); return signedOut; });render(page(service, signedIn, vi.fn(), vi.fn(), 'subscription'));expect(await screen.findByText('123')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByLabelText('账号菜单'));await userEvent.setup().click(screen.getByRole('button', { name: '退出登录' }));expect(await screen.findByRole('button', { name: '登录 / 注册' })).toBeInTheDocument();expect(screen.queryByText('123')).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: '充值积分' })).not.toBeInTheDocument();+ expect(screen.queryByRole('tab', { name: '充值订单' })).not.toBeInTheDocument();});it('ignores a previous account balance response after switching accounts', async () => {const service = createService(); let complete!: (result: GatewayBillingSummary) => void;@@ -81,3 +83,13 @@ it('shows unavailable login without an enabled action', () => {expect(within(screen.getByRole('region', { name: 'OpenCreator 账户' })).getByText('登录服务暂不可用')).toBeInTheDocument();expect(screen.getByRole('button', { name: '登录 / 注册' })).toBeDisabled();});+it('keeps model availability separate from sign-in and opens model settings', async () => {+ const blocked = { ...signedIn, activationState: 'blocked' as const, activationError: { code: 'services_not_ready', message: 'Unavailable' } };+ const settings = vi.fn();+ render(page(createService(blocked), blocked, vi.fn(), vi.fn(), 'account', settings));+ expect(await screen.findByText('已登录', { exact: true })).toBeInTheDocument();+ expect(screen.getByText('官方模型服务暂不可用')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '模型设置' }));+ expect(settings).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/account/PersonalCenterPage.tsx b/apps/web/src/features/account/PersonalCenterPage.tsxindex 6cf7e8d2..70e2ade5 100644--- a/apps/web/src/features/account/PersonalCenterPage.tsx+++ b/apps/web/src/features/account/PersonalCenterPage.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react';-import { ArrowLeft } from 'lucide-react';+import { ArrowLeft, Settings2 } from 'lucide-react';import type { GatewayAccountState } from '@opencreator/protocol';+import type { ExternalNavigation } from '../../host/bridge.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';import { GatewayAccountSettingsView } from '../settings/GatewayAccountSettingsView.js';@@ -12,17 +13,21 @@ export default function PersonalCenterPage(props: {view?: 'account' | 'subscription';service: GatewayAccountSettingsService | null;accountState?: GatewayAccountState;+ billingOrderId?: string;+ billingReturnUrl?: string;+ prepareExternalNavigation?(): ExternalNavigation;onStateChange?(state: GatewayAccountState): void;openExternal?(url: string): Promise<void> | void;onBack(): void;- onOpenSubscription(): void;+ onOpenModelSettings?(): void;}) {const l = useLocalizedCopy();const [state, setState] = useState(props.accountState);+ const [signInRequest, setSignInRequest] = useState(0);useEffect(() => { setState(props.accountState); }, [props.accountState]);const email = state?.authState === 'signed_in' ? state.account?.email : undefined;- const subscriptionPage = props.view === 'subscription';- const title = subscriptionPage ? l('积分与充值', 'Credits') : l('账户', 'Account');+ const title = l('个人中心', 'Account');+ const modelUnavailable = state?.authState === 'signed_in' && state.source === 'gateway' && state.activationState !== 'ready';return <main className="opencreator-scroll-page personal-center" aria-label={title}><div className="personal-center__content">@@ -36,17 +41,23 @@ export default function PersonalCenterPage(props: {variant="profile"service={props.service}accountState={state}+ signInRequest={signInRequest}openExternal={props.openExternal}onStateChange={next => {setState(next); props.onStateChange?.(next);}}/></section>+ {modelUnavailable ? <div className="personal-center__model-status" role="status">+ <span>{state.activationState === 'loading' ? l('官方模型服务正在连接', 'Connecting to official model services') : l('官方模型服务暂不可用', 'Official model services are unavailable')}</span>+ {props.onOpenModelSettings ? <button type="button" onClick={props.onOpenModelSettings}><Settings2 size={15}/>{l('模型设置', 'Model settings')}</button> : null}+ </div> : null}<GatewaySubscriptionSettingsView- variant={subscriptionPage ? 'subscription' : 'overview'}key={`${state?.authState}:${state?.account?.id ?? ''}`}service={props.service} embedded accountState={state} openExternal={props.openExternal}- onOpenSubscription={props.onOpenSubscription}+ billingOrderId={props.billingOrderId} billingReturnUrl={props.billingReturnUrl}+ prepareExternalNavigation={props.prepareExternalNavigation}+ onRequestSignIn={() => setSignInRequest(value => value + 1)}/></div></main>;diff --git a/apps/web/src/features/account/billing-display.ts b/apps/web/src/features/account/billing-display.tsnew file mode 100644index 00000000..2c20f37f--- /dev/null+++ b/apps/web/src/features/account/billing-display.ts@@ -0,0 +1,56 @@+import type { LocalizeCopy } from '../../i18n/useLocalizedCopy.js';+import type { GatewayBillingAvailability, GatewayRechargeOrder } from '../../services/gateway-account-service.js';++export function billingUnavailableMessage(reason: GatewayBillingAvailability['billingUnavailableReason'], l: LocalizeCopy) {+ switch (reason) {+ case 'purchases_disabled': return l('当前环境暂未开放充值,仍可查看积分方案。', 'Purchases are not enabled in this environment. Credit plans are available to browse.');+ case 'payment_service_unavailable': return l('支付服务暂不可用,请稍后重试。', 'The payment service is unavailable. Try again later.');+ case 'official_services_unavailable': return l('官方积分服务暂不可用,充值已暂停。', 'Official credit services are unavailable. Purchases are paused.');+ case 'payment_review': return l('付款正在审核,充值和积分使用已暂停,请联系客服。', 'Your payment is under review. Purchases and credit usage are paused. Contact support.');+ default: return l('充值暂不可用,仍可查看积分方案。', 'Purchases are currently unavailable. Credit plans are available to browse.');+ }+}++export function formatBillingMoney(units: string, currency: string, language: string) {+ if (!/^\d+$/.test(units) || !Number.isSafeInteger(Number(units))) return '—';+ try { return new Intl.NumberFormat(language, { style: 'currency', currency: currency.toUpperCase() }).format(Number(units) / 100); }+ catch { return '—'; }+}++export function rechargeOrderStatus(order: GatewayRechargeOrder) {+ if (order.reviewRequired) return 'review';+ if (order.status === 'pending' && order.expiresAt && new Date(order.expiresAt).getTime() <= Date.now()) return 'expired';+ return order.status;+}++export function rechargeOrderLabel(order: GatewayRechargeOrder, l: LocalizeCopy) {+ switch (rechargeOrderStatus(order)) {+ case 'pending': return l('待付款', 'Awaiting payment');+ case 'processing': return l('积分到账中', 'Adding credits');+ case 'completed': return l('已到账', 'Completed');+ case 'expired': return l('已过期', 'Expired');+ case 'failed': return l('付款失败', 'Payment failed');+ case 'refunded': return l('已退款', 'Refunded');+ case 'disputed': return l('付款争议处理中', 'Payment disputed');+ case 'review': return l('付款审核中', 'Under review');+ default: return l('等待确认', 'Awaiting confirmation');+ }+}++export function creditPlansURL(raw: string | undefined, language: string) {+ try {+ const url = new URL(raw || 'https://www.open-creator.ai/pricing');+ const local = ['127.0.0.1', 'localhost'].includes(url.hostname);+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) || url.username || url.password || url.pathname !== '/pricing') return undefined;+ url.searchParams.set('lang', language === 'zh-CN' ? 'zh' : 'en');+ return url.href;+ } catch { return undefined; }+}++export function checkedPaymentURL(raw: string, plansURL?: string) {+ const url = new URL(raw);+ if (url.username || url.password) throw new Error('Invalid payment URL');+ if (url.protocol === 'https:' && url.hostname === 'checkout.stripe.com' && url.port === '' && url.pathname.startsWith('/')) return url.href;+ if (plansURL && url.origin === new URL(plansURL).origin && url.pathname === '/billing/return') return url.href;+ throw new Error('Invalid payment URL');+}diff --git a/apps/web/src/features/account/credits.css b/apps/web/src/features/account/credits.cssnew file mode 100644index 00000000..f3f50e42--- /dev/null+++ b/apps/web/src/features/account/credits.css@@ -0,0 +1,34 @@+.account-credits { color: var(--text); font-size: 14px; min-width: 0; }+.account-credits h2 { margin: 0; letter-spacing: 0; }+.account-credits button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 34px; padding: 7px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface-2); color: var(--text); font: inherit; cursor: pointer; }+.account-credits button:disabled { opacity: .5; cursor: default; }+.account-credits svg { flex-shrink: 0; }+.account-credits button.credit-primary { background: var(--accent); color: var(--on-accent); border-color: var(--accent); min-width: 132px; }+.account-credits button.credit-icon-button { width: 34px; height: 34px; padding: 0; flex: 0 0 34px; background: transparent; }+.account-credits button:focus-visible, .account-credits a:focus-visible, .gateway-account__menu summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.account-credits__balance { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 28px 0; }+.account-credits__balance > div { min-width: 0; }+.account-credits__balance h2 { font-size: 13px; font-weight: 500; color: var(--muted); }+.account-credits__value { margin: 8px 0 0; font-size: 30px; line-height: 1.3; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }+.account-credits__value small { font-size: 12px; color: var(--muted); }+.account-credits__actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }+.credit-muted { color: var(--muted); font-size: 12px; line-height: 1.6; margin: 8px 0 0; }+.credit-notice { margin: 0 0 18px; padding: 10px 12px; border-left: 3px solid var(--border); background: var(--surface-2); color: var(--muted); font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }+.credit-loading { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }+.credit-error { color: var(--danger); font-size: 12px; line-height: 1.6; }+.account-payment { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 0; margin-bottom: 12px; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); font-size: 13px; }+.account-payment > div { display: flex; align-items: center; gap: 8px; min-width: 0; }+.account-payment [role=status] { overflow-wrap: anywhere; }+.account-payment.is-completed > div { color: var(--success, #23865b); }+.account-credits__links { border-top: 1px solid var(--border); }+.account-credits__links > button, .account-credits__links > a { display: flex; align-items: center; gap: 12px; width: 100%; min-height: 50px; box-sizing: border-box; padding: 12px 0; border: 0; border-bottom: 1px solid var(--border); border-radius: 0; background: transparent; text-align: left; color: var(--text); font: inherit; font-size: 13px; text-decoration: none; }+.account-credits__links > button:hover, .account-credits__links > a:hover { color: var(--accent-strong); }+.account-credits__links > button > svg:first-child, .account-credits__links > a > svg:first-child { color: var(--muted); }+.account-credits__links span { flex: 1; overflow-wrap: anywhere; }+.account-credits__links > button > svg:last-child, .account-credits__links > a > svg:last-child { color: var(--muted); }+.credit-loading svg, .is-spinning { animation: gateway-loading-spin 1s linear infinite; }+@media (max-width: 640px) {+ .account-credits__balance { align-items: flex-start; flex-direction: column; gap: 16px; padding: 24px 0; }+ .account-credits__actions { width: 100%; justify-content: flex-end; }+}+@media (prefers-reduced-motion: reduce) { .credit-loading svg, .is-spinning { animation: none; } }diff --git a/apps/web/src/features/account/credits.test.tsx b/apps/web/src/features/account/credits.test.tsxnew file mode 100644index 00000000..cd5e2016--- /dev/null+++ b/apps/web/src/features/account/credits.test.tsx@@ -0,0 +1,123 @@+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';+import { afterEach, expect, it, vi } from 'vitest';+import type { GatewayAccountState } from '@opencreator/protocol';+import { LanguageProvider } from '../../i18n/LanguageProvider.js';+import { ApiClientError } from '../../runtime/errors.js';+import type { GatewayAccountSettingsService, GatewayBillingSummary, GatewayRechargeOrder } from '../../services/gateway-account-service.js';+import { GatewaySubscriptionSettingsView } from '../settings/GatewaySubscriptionSettingsView.js';++afterEach(() => { cleanup(); sessionStorage.clear(); });+const account: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'account-a', email: '[email protected]', verified: true }, bindingVersion: null, models: [], activationError: null };+const summary: GatewayBillingSummary = { balance: { availableUnits: '413937000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-10T01:00:00Z' }, subscription: null, billingAvailable: true, plansUrl: 'https://www.open-creator.ai/pricing' };+const order: GatewayRechargeOrder = { id: 'order-a', planId: 'starter', currency: 'usd', amountUnits: '500', creditUnits: '2500000000', status: 'pending', paymentStatus: 'pending', creditStatus: 'pending', reviewRequired: false, paymentMode: 'test', createdAt: new Date().toISOString(), paidAt: null, completedAt: null, expiresAt: '2099-01-01T00:00:00Z' };+const handoff = 'https://www.open-creator.ai/auth?lang=zh#handoff=' + 'a'.repeat(43);+function service(): GatewayAccountSettingsService {+ return { getState: vi.fn(async () => account), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(async () => summary),+ openWebAccount: vi.fn(async () => ({ url: handoff })), getPlans: vi.fn(), getOrders: vi.fn(async () => ({ items: [] })), getOrder: vi.fn(async () => ({ order })), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn() };+}+function page(value: GatewayAccountSettingsService, openExternal = vi.fn(), state = account, billingOrderId?: string) {+ return <LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} embedded accountState={state} openExternal={openExternal} billingOrderId={billingOrderId} billingReturnUrl="opencreator://billing/return"/></LanguageProvider>;+}++it('opens the website through a one-time account handoff without an app checkout', async () => {+ const value = service(); const open = vi.fn(); render(page(value, open));+ expect(await screen.findByText('413.937')).toBeInTheDocument();+ expect(value.getOrders).not.toHaveBeenCalled();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(value.openWebAccount).toHaveBeenCalledWith('recharge', 'zh');+ expect(open).toHaveBeenCalledWith(handoff);+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(screen.queryByRole('tab')).not.toBeInTheDocument();+ expect(value.checkout).not.toHaveBeenCalled();+ expect(value.getPlans).not.toHaveBeenCalled();+ expect(value.getCreditGrants).not.toHaveBeenCalled();+});++it.each([['账单与充值记录', 'account'], ['积分用量估算', 'usage'], ['FAQ', 'faq']])('opens %s at its website destination', async (label, destination) => {+ const value = service(); const open = vi.fn(); render(page(value, open));+ expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: label }));+ expect(value.openWebAccount).toHaveBeenCalledWith(destination, 'zh');+ expect(open).toHaveBeenCalledWith(handoff);+});++it('keeps website recharge available when purchases are disabled globally', async () => {+ const value = service(); vi.mocked(value.getSummary).mockResolvedValue({ ...summary, billingAvailable: false });+ render(page(value)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: '充值积分' })).toBeEnabled();+ expect(screen.queryByText(/充值暂不可用/)).not.toBeInTheDocument();+});++it('falls back to the existing website when an older gateway lacks handoffs', async () => {+ const value = service(); const open = vi.fn();+ vi.mocked(value.openWebAccount!).mockRejectedValue(new ApiClientError({ status: 404, code: 'GATEWAY_UNAVAILABLE', message: 'Not found' }));+ render(page(value, open)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ const url = new URL(open.mock.calls[0]![0]);+ expect(url.pathname).toBe('/pricing');+ expect(url.searchParams.get('account')).toBe('account-a');+ expect(url.searchParams.get('returnTo')).toBe('opencreator://billing/return');+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+});++it('rejects a handoff to an unexpected origin and permits retry', async () => {+ const value = service(); const open = vi.fn();+ vi.mocked(value.openWebAccount!).mockResolvedValueOnce({ url: 'https://evil.test/auth#handoff=' + 'a'.repeat(43) });+ render(page(value, open)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('网页未打开');+ expect(open).not.toHaveBeenCalled();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(open).toHaveBeenCalledWith(handoff);+});++it('does not claim success when returning without a confirmed order', async () => {+ const value = service(); render(page(value)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(screen.queryByText(/充值成功/)).not.toBeInTheDocument();+ expect(value.getOrder).not.toHaveBeenCalled();+});++it('finds a new website order on focus and distinguishes payment from credit completion', async () => {+ const value = service(); render(page(value)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ vi.mocked(value.getOrders).mockResolvedValue({ items: [order] });+ vi.mocked(value.getOrder).mockResolvedValue({ order: { ...order, status: 'processing', paymentStatus: 'paid' } });+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(await screen.findByText('付款成功,积分到账中')).toBeInTheDocument();+ expect(screen.queryByText(/充值成功/)).not.toBeInTheDocument();+ vi.mocked(value.getOrder).mockResolvedValue({ order: { ...order, status: 'completed', paymentStatus: 'paid', creditStatus: 'ready' } });+ vi.mocked(value.getSummary).mockResolvedValue({ ...summary, balance: { ...summary.balance, availableUnits: '2913937000' } });+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(await screen.findByText('充值成功,已到账 2500 积分')).toBeInTheDocument();+ expect(screen.getByText('2913.937')).toBeInTheDocument();+ expect(sessionStorage.getItem('opencreator:billing-visit:account-a')).toBeNull();+});++it('verifies the returned order under the signed-in account rather than trusting the URL', async () => {+ const value = service(); vi.mocked(value.getOrder).mockRejectedValue(new Error('order belongs to another account'));+ render(page(value, vi.fn(), account, 'other-order'));+ expect(await screen.findByRole('alert')).toHaveTextContent('暂时无法确认订单');+ expect(screen.queryByText(/充值成功/)).not.toBeInTheDocument();+});++it('restores a website visit and ignores orders that already existed', async () => {+ sessionStorage.setItem('opencreator:billing-visit:account-a', JSON.stringify({ startedAt: Date.now(), knownOrders: ['old-order'] }));+ const value = service(); vi.mocked(value.getOrders).mockResolvedValue({ items: [{ ...order, id: 'old-order' }] });+ render(page(value)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await waitFor(() => expect(value.getOrders).toHaveBeenCalled());+ expect(value.getOrder).not.toHaveBeenCalled();+});++it('ignores a website response from the previous account', async () => {+ const value = service(); const open = vi.fn(); let finish!: (value: { url: string }) => void;+ vi.mocked(value.openWebAccount!).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const view = render(page(value, open)); expect(await screen.findByText('413.937')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ view.rerender(page(value, open, { ...account, account: { id: 'account-b', email: '[email protected]', verified: true } }));+ await act(async () => finish({ url: handoff }));+ expect(open).not.toHaveBeenCalled();+ expect(sessionStorage.getItem('opencreator:billing-visit:account-a')).toBeNull();+});diff --git a/apps/web/src/features/account/personal-center.css b/apps/web/src/features/account/personal-center.cssindex 297ac176..b9b6e311 100644--- a/apps/web/src/features/account/personal-center.css+++ b/apps/web/src/features/account/personal-center.css@@ -9,8 +9,8 @@.sidebar-account__copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; color: var(--muted); }.opencreator-sidebar[data-collapsed=true] .sidebar-account { justify-content: center; padding: 6px 0; }.personal-center { min-width: 0; height: 100%; padding: var(--page-title-inset) 32px 40px; }-.personal-center__content { width: 100%; max-width: 800px; margin: 0 auto; }-.personal-center__heading { display: flex; align-items: center; gap: 12px; margin-bottom: 32px; }+.personal-center__content { width: 100%; max-width: 640px; margin: 0 auto; }+.personal-center__heading { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }.personal-center__heading h1 { margin: 0; font-size: 22px; font-weight: 600; letter-spacing: 0; }.personal-center__heading button { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; flex: 0 0 32px; padding: 0; border: 1px solid var(--border); border-radius: 6px; background: transparent; color: var(--muted); cursor: pointer; }.personal-center__heading button:hover { color: var(--text); background: var(--surface-2); }@@ -22,10 +22,18 @@.gateway-account--profile .gateway-account__actions, .gateway-account--profile > button:first-of-type { grid-column: 2; grid-row: 1; margin: 0; }.gateway-account--profile > [role=alert], .gateway-account--profile > a { grid-column: 1 / -1; margin: 4px 0; }.personal-center .gateway-subscription { padding: 0; }+.gateway-account__menu { position: relative; grid-column: 2; grid-row: 1; }+.gateway-account__menu > summary { display: flex; align-items: center; justify-content: center; width: 34px; height: 34px; border-radius: 6px; cursor: pointer; list-style: none; color: var(--muted); }+.gateway-account__menu > summary::-webkit-details-marker { display: none; }+.gateway-account__menu > summary:hover, .gateway-account__menu[open] > summary { background: var(--surface-2); color: var(--text); }+.gateway-account__menu > div { position: absolute; z-index: 3; top: 40px; right: 0; width: 160px; padding: 4px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); box-shadow: 0 4px 16px #00000018; }+.gateway-account__menu > div button { width: 100%; border: 0; background: transparent; justify-content: flex-start; }+.personal-center__model-status { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 12px 0; border-bottom: 1px solid var(--border); color: var(--muted); font-size: 12px; }+.personal-center__model-status button { display: inline-flex; gap: 6px; align-items: center; background: transparent; border: 0; color: var(--text); font: inherit; cursor: pointer; padding: 4px 0; }@media (max-width: 640px) {.personal-center { padding: 20px 20px 32px; }.personal-center__heading { margin-bottom: 24px; }.personal-center__identity { align-items: flex-start; gap: 14px; }- .personal-center .gateway-account--profile { grid-template-columns: minmax(0, 1fr); }+ .personal-center .gateway-account--profile { grid-template-columns: minmax(0, 1fr) auto; }.gateway-account--profile .gateway-account__actions, .gateway-account--profile > button:first-of-type { grid-column: 1; grid-row: auto; justify-self: start; margin-top: 6px; }}diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts b/apps/web/src/features/dashboard/creator-panel-adapters.test.tsindex 1c6b6323..0e0c49dc 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.test.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.test.ts@@ -82,6 +82,33 @@ describe('shared native image progress', () => {});describe('video translation component progress', () => {+ it.each(['zh-CN', 'en-US', 'sv-SE'] as const)('keeps caption fallback visible during preparation, transcription and after success in %s', language => {+ const localize = createLocalizedCopy(language);+ const running = { ...stage('subtitle', '', 'running', null, 'subtitle'), progress: {+ phase: 'fallback_to_transcription', percent: 25, captionSource: 'whisper',+ captionFallbackCode: 'platform_caption_invalid', message: 'platform captions contained no usable text'+ } };+ for (const phase of ['fallback_to_transcription', 'downloading_dependencies', 'transcribing_audio']) {+ const progress = videoTranslationPanelAdapter.readStageProgress({+ ...running, progress: { ...running.progress, phase }+ }, localize);+ expect(progress.showMessage).toBe(true);+ expect(progress.message).toContain(language === 'zh-CN' ? '已自动切换' : language === 'en-US' ? 'Automatically switched' : 'Bytte automatiskt');+ expect(progress.message).not.toContain('contained no usable text');+ if (language !== 'zh-CN') expect(progress.message).not.toMatch(/\p{Script=Han}/u);+ }+ expect(videoTranslationPanelAdapter.succeededProgressText?.({ ...running, status: 'succeeded' }, localize))+ .toContain(language === 'zh-CN' ? '已使用语音转录' : language === 'en-US' ? 'audio transcription' : 'ljudtranskription');+ });++ it('distinguishes missing captions from unusable VTT in the fallback notice', () => {+ const running = { ...stage('subtitle', '', 'running', null, 'subtitle'), progress: {+ phase: 'fallback_to_transcription', captionFallbackCode: 'platform_caption_failed'+ } };+ expect(videoTranslationPanelAdapter.readStageProgress(running, zh).message).toContain('未找到可用的平台字幕');+ expect(videoTranslationPanelAdapter.readStageProgress({ ...running, progress: {} }, zh).showMessage).toBe(false);+ });+it('labels draft preview activity and reports real progress without translation claims', () => {const running = { ...stage('draft-preview', '', 'running', null, 'preview-source-video'),progress: { phase: 'downloading', percent: 40, downloadedBytes: 4 * 1024 ** 2, totalBytes: 10 * 1024 ** 2 } };diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.ts b/apps/web/src/features/dashboard/creator-panel-adapters.tsindex 75049e0a..464dd31a 100644--- a/apps/web/src/features/dashboard/creator-panel-adapters.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.ts@@ -82,6 +82,9 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {},succeededProgressText(stage, localize) {if (stage.stageId === 'preview-source-video') return localize('原视频预览已就绪', 'Source video preview ready', 'Originalvideons förhandsvisning är redo');+ if (stage.stageId === 'subtitle' && captionFallbackMessage(stage, localize) !== null) {+ return localize('字幕已生成,平台字幕不可用,已使用语音转录', 'Subtitles generated using audio transcription because platform captions were unavailable', 'Undertexter skapades med ljudtranskription eftersom plattformens undertexter inte kunde användas');+ }return stage.stageId === 'prepare-source-video'? localize('原视频已就绪,已有字幕保持不变', 'Source video ready; existing subtitles are unchanged'): null;@@ -104,6 +107,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {preparing_source: l('准备视频来源', 'Preparing the video source'),reading_platform_captions: l('获取平台字幕', 'Fetching platform captions'),processing_platform_captions: l('解析平台字幕', 'Processing platform captions'),+ fallback_to_transcription: l('切换到语音转录', 'Switching to audio transcription', 'Byter till ljudtranskription'),translating_subtitles: l('翻译字幕', 'Translating subtitles'),collecting_subtitles: l('生成双语字幕', 'Generating bilingual subtitles'),preparing_original_media: l('准备原始视频', 'Preparing the original video'),@@ -147,6 +151,7 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {},readStageProgress(stage, localize) {const standard = readStandardProgress(stage);+ const fallbackMessage = captionFallbackMessage(stage, localize);if (stage.stageId === 'prepare-source-video' || stage.stageId === 'preview-source-video') {const bytes = readFiniteNumber(stage.progress.downloadedBytes) ?? 0;const total = readFiniteNumber(stage.progress.totalBytes);@@ -177,17 +182,23 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {showMessage: true,percent: standard.phase === 'downloading_dependencies' ? readFiniteNumber(stage.progress.dependencyPercent) : null,indeterminate: standard.phase !== 'downloading_dependencies' || readFiniteNumber(stage.progress.dependencyPercent) === null,- message: `${standard.phase === 'dependencies_ready'+ message: `${fallbackMessage === null ? '' : `${fallbackMessage} `}${standard.phase === 'dependencies_ready'? localize('本地转录组件已准备完成,正在开始语音转录', 'Local transcription components are ready; starting transcription.', 'De lokala transkriptionskomponenterna är redo; startar transkriptionen.'): localComponentPreparationMessage(standard.phase === 'verifying_dependencies' ? 'verifying' : standard.phase === 'extracting_dependencies' ? 'extracting' : 'downloading', localize)}${standard.phase === 'downloading_dependencies' ? ` ${bytes}` : ''}`,detailsHref: `#/settings?tab=local-components&from=video-translation&returnPath=${encodeURIComponent(`#/workbench?tool=video-translation&jobId=${encodeURIComponent(stage.jobId)}`)}`};}const legacy = readRecord(stage.progress.krillinEventPayload);+ const phase = standard.phase ?? readString(legacy?.phase);+ const phaseLabel = phase === null ? null : videoTranslationPanelAdapter.phaseLabel(phase, localize);return {percent: standard.percent ?? readFiniteNumber(legacy?.percent),- phase: standard.phase ?? readString(legacy?.phase),- message: standard.message ?? readString(legacy?.message),+ phase,+ showMessage: fallbackMessage !== null,+ message: fallbackMessage === null+ ? standard.message ?? readString(legacy?.message)+ : `${fallbackMessage}${phaseLabel === null || phase === 'fallback_to_transcription'+ ? '' : ` ${phaseLabel}`}`,completed: standard.completed,failed: standard.failed,total: standard.total@@ -195,6 +206,16 @@ export const videoTranslationPanelAdapter: CreatorPanelAdapter = {}};+function captionFallbackMessage(stage: CreatorStageRun, l: CreatorPanelLocalize): string | null {+ if (stage.progress.captionFallbackCode === 'platform_caption_invalid') {+ return l('平台字幕解析失败,已自动切换到语音转录。', 'Platform captions could not be processed. Automatically switched to audio transcription.', 'Plattformens undertexter kunde inte bearbetas. Bytte automatiskt till ljudtranskription.');+ }+ if (stage.progress.captionFallbackCode === 'platform_caption_failed') {+ return l('未找到可用的平台字幕,已自动切换到语音转录。', 'No usable platform captions were found. Automatically switched to audio transcription.', 'Inga användbara undertexter hittades på plattformen. Bytte automatiskt till ljudtranskription.');+ }+ return null;+}+export const coverPanelAdapter: CreatorPanelAdapter = {id: 'cover',composerPlaceholder: l => l(diff --git a/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsx b/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsxindex 31c3d31f..24a5da6f 100644--- a/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsx+++ b/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsx@@ -6,13 +6,13 @@ import { GatewayAccountSettingsView } from './GatewayAccountSettingsView.js';import { GatewaySubscriptionSettingsView } from './GatewaySubscriptionSettingsView.js';import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';import type { GatewayAccountState } from '@opencreator/protocol';-afterEach(cleanup);+afterEach(() => { cleanup(); sessionStorage.clear(); });const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null };function service(): GatewayAccountSettingsService {return { getState: vi.fn(async () => state), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(),getBalance: vi.fn(),getSummary: vi.fn(async () => ({ balance: { availableUnits: '123000000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' }, subscription: null, billingAvailable: true, purchaseMode: 'credits' as const, plansUrl: 'https://www.open-creator.ai/pricing' })),- getPlans: vi.fn(), checkout: vi.fn(), portal: vi.fn() };+ getPlans: vi.fn(async () => ({ plans: [{ id: 'starter', name: 'Starter', amountUnits: '500', creditUnits: '2500000000', currency: 'usd' }], billingAvailable: true })), getOrders: vi.fn(async () => ({ items: [] })), getOrder: vi.fn(), getCreditGrants: vi.fn(async () => ({ items: [] })), checkout: vi.fn(), portal: vi.fn() };}it('shows an expired session explicitly and keeps reauthorization available', async () => {const value = service();@@ -21,30 +21,58 @@ it('shows an expired session explicitly and keeps reauthorization available', asexpect(await screen.findByText('登录已过期,请重新登录')).toBeInTheDocument();expect(screen.getByRole('button', { name: '登录 OpenCreator' })).toBeEnabled();});-it('shows credits and opens website recharge without creating checkout in the application', async () => {+it('checks authorization on return and displays sign-in before model services are ready', async () => {+ const value = service();+ vi.mocked(value.getState).mockResolvedValue({ ...state, authState: 'authorizing', activationState: 'loading', account: null });+ render(<LanguageProvider initialPreference="zh-CN"><GatewayAccountSettingsView variant="profile" service={value}/></LanguageProvider>);+ expect(await screen.findByText('请在浏览器中完成登录')).toBeInTheDocument();+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(await screen.findByText('正在确认登录结果…')).toBeInTheDocument();+ vi.mocked(value.getState).mockResolvedValue({ ...state, activationState: 'loading' });+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(await screen.findByText('已登录', { exact: true })).toBeInTheDocument();+ expect(value.getState).toHaveBeenLastCalledWith({ checkAuthorization: true });+ await userEvent.setup().click(screen.getByLabelText('账号菜单'));+ expect(screen.getByRole('button', { name: '退出登录' })).toBeEnabled();+ expect(screen.queryByRole('button', { name: '重新连接' })).not.toBeInTheDocument();+});+it('describes an expired authorization as a sign-in problem with a retry entry', async () => {+ const value = service();+ vi.mocked(value.getState).mockResolvedValue({ ...state, source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null,+ activationError: { code: 'device_expired', message: 'Expired' } });+ render(<LanguageProvider initialPreference="zh-CN"><GatewayAccountSettingsView variant="profile" service={value}/></LanguageProvider>);+ expect(await screen.findByRole('alert')).toHaveTextContent('登录授权已过期,请重新登录。');+ expect(screen.getByRole('button', { name: '登录 / 注册' })).toBeEnabled();+});+it('shows credits and opens the existing website for recharge', async () => {const value = service(); const open = vi.fn();render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} openExternal={open}/></LanguageProvider>);expect(await screen.findByText('123')).toBeInTheDocument();expect(screen.queryByText('未订阅')).not.toBeInTheDocument();await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));- expect(open).toHaveBeenCalledWith('https://www.open-creator.ai/pricing?lang=zh');+ expect(open).toHaveBeenCalledWith(expect.stringContaining('https://www.open-creator.ai/pricing'));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();expect(value.checkout).not.toHaveBeenCalled();expect(value.portal).not.toHaveBeenCalled();});it('keeps a plans link available with purchases disabled', async () => {const value = service();vi.mocked(value.getSummary).mockResolvedValue({ balance: { availableUnits: '0', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' }, subscription: null, billingAvailable: false });- render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value}/></LanguageProvider>);- expect(await screen.findByText('充值暂不可用')).toBeInTheDocument();- expect(screen.getByRole('button', { name: '充值积分' })).toBeDisabled();- expect(screen.getByRole('link', { name: '查看积分方案' })).toHaveAttribute('href', 'https://www.open-creator.ai/pricing?lang=zh');+ const open = vi.fn();+ render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} openExternal={open}/></LanguageProvider>);+ expect(await screen.findByText('0')).toBeInTheDocument();+ expect(screen.queryByText(/充值暂不可用/)).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: '充值积分' })).toBeEnabled();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(open).toHaveBeenCalledOnce();});-it('shows refund review and prevents new recharge', async () => {+it('shows account-specific refund review and leaves billing management accessible', async () => {const value = service();vi.mocked(value.getSummary).mockResolvedValue({ balance: { availableUnits: '1000000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' }, subscription: null, billingAvailable: false, paymentReview: true });render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value}/></LanguageProvider>);- expect(await screen.findByText('付款正在审核,积分使用已暂停,请联系客服')).toBeInTheDocument();- expect(screen.getByRole('button', { name: '充值积分' })).toBeDisabled();+ expect(await screen.findByText('付款正在审核,充值和积分使用已暂停,请联系客服。')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: '账单与充值记录' })).toBeEnabled();+ expect(value.checkout).not.toHaveBeenCalled();});it('keeps the last balance marked stale on failure and recovers through retry', async () => {const value = service();@@ -52,12 +80,12 @@ it('keeps the last balance marked stale on failure and recovers through retry',expect(await screen.findByText('123')).toBeInTheDocument();vi.mocked(value.getSummary).mockRejectedValueOnce(new Error('offline'));await act(async () => window.dispatchEvent(new Event('focus')));- expect(await screen.findByRole('alert')).toHaveTextContent('积分信息暂不可用');+ expect(await screen.findByRole('alert')).toHaveTextContent('积分信息加载失败');expect(screen.getByText(/上次更新/)).toBeInTheDocument();expect(screen.getByText('123')).toBeInTheDocument();- expect(screen.getByRole('button', { name: '充值积分' })).toBeDisabled();- await userEvent.setup().click(screen.getByRole('button', { name: '重试' }));- await waitFor(() => expect(screen.getByRole('button', { name: '充值积分' })).toBeEnabled());+ expect(screen.getByRole('button', { name: '充值积分' })).toBeEnabled();+ await userEvent.setup().click(screen.getByRole('button', { name: '刷新积分' }));+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());});it('refreshes the purchased balance on application focus', async () => {const value = service();@@ -67,12 +95,15 @@ it('refreshes the purchased balance on application focus', async () => {await act(async () => window.dispatchEvent(new Event('focus')));expect(await screen.findByText('2500')).toBeInTheDocument();});-it('rejects invalid recharge URL schemes', async () => {+it('rejects invalid website URL schemes', async () => {const value = service();- vi.mocked(value.getSummary).mockResolvedValue({ balance: { availableUnits: '0', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' }, subscription: null, billingAvailable: true, plansUrl: 'javascript:alert(1)' });- render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value}/></LanguageProvider>);- expect(await screen.findByRole('button', { name: '充值积分' })).toBeDisabled();- expect(screen.queryByRole('link', { name: '查看积分方案' })).not.toBeInTheDocument();+ value.openWebAccount = vi.fn(async () => ({ url: 'javascript:alert(1)' }));+ const open = vi.fn();+ render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} openExternal={open}/></LanguageProvider>);+ expect(await screen.findByText('123')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '充值积分' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('网页未打开');+ expect(open).not.toHaveBeenCalled();});it('reconnects a signed-in account without manual provider fields', async () => {const value = service(); const changed = vi.fn();diff --git a/apps/web/src/features/settings/GatewayAccountSettingsView.tsx b/apps/web/src/features/settings/GatewayAccountSettingsView.tsxindex ea045552..17bec4e9 100644--- a/apps/web/src/features/settings/GatewayAccountSettingsView.tsx+++ b/apps/web/src/features/settings/GatewayAccountSettingsView.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from 'react';-import { CreditCard, ExternalLink, LogIn, LogOut, RefreshCw } from 'lucide-react';+import { CreditCard, ExternalLink, LogIn, LogOut, MoreHorizontal, RefreshCw } from 'lucide-react';import type { GatewayAccountState, GatewayAuthorization } from '@opencreator/protocol';import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';@@ -27,6 +27,7 @@ export function GatewayAccountSettingsView(props: {const l = useLocalizedCopy();const [state, setState] = useState<GatewayAccountState | undefined>(props.accountState);const [authorization, setAuthorization] = useState<GatewayAuthorization>();+ const [confirmingAuthorization, setConfirmingAuthorization] = useState(() => window.location.hash === '#/account?login=complete');const [busy, setBusy] = useState(false);const [error, setError] = useState('');const callback = useRef(props.onStateChange); callback.current = props.onStateChange;@@ -34,46 +35,71 @@ export function GatewayAccountSettingsView(props: {const busyRef = useRef(false);const refreshSequence = useRef(0);const lastSignInRequest = useRef(0);+ const accountMenu = useRef<HTMLDetailsElement>(null);const service = props.service;const compact = props.variant === 'login';const profile = props.variant === 'profile';useEffect(() => { if (props.accountState) { refreshSequence.current++; setState(props.accountState); } }, [props.accountState]);+ useEffect(() => {+ const closeOutside = (event: PointerEvent) => { if (accountMenu.current && !accountMenu.current.contains(event.target as Node)) accountMenu.current.open = false; };+ const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape' && accountMenu.current?.open) { accountMenu.current.open = false; accountMenu.current.querySelector('summary')?.focus(); } };+ document.addEventListener('pointerdown', closeOutside); document.addEventListener('keydown', closeOnEscape);+ return () => { document.removeEventListener('pointerdown', closeOutside); document.removeEventListener('keydown', closeOnEscape); };+ }, []);function update(next: GatewayAccountState) {if (!alive.current) return;refreshSequence.current++;setState(next); callback.current?.(next);- if (next.authState !== 'authorizing') setAuthorization(undefined);+ if (next.authState !== 'authorizing') { setAuthorization(undefined); setConfirmingAuthorization(false); }}- async function refresh() {+ async function refresh(checkAuthorization = false) {const request = ++refreshSequence.current;if (service) {- const next = await service.getState();+ const next = await service.getState({ checkAuthorization });if (alive.current && request === refreshSequence.current) { update(next); setError(''); }}}useEffect(() => {alive.current = true;void refresh().catch(() => { if (alive.current) setError(l('账户服务暂不可用,请稍后重试', 'Account service is unavailable. Try again later.')); });- const timer = setInterval(() => { if (!busyRef.current) void refresh().catch(() => undefined); }, 3000);- return () => { alive.current = false; refreshSequence.current++; clearInterval(timer); };+ const onReturn = () => {+ if (busyRef.current) return;+ setConfirmingAuthorization(true);+ void refresh(true).catch(() => undefined);+ };+ const onVisible = () => { if (document.visibilityState === 'visible') onReturn(); };+ window.addEventListener('focus', onReturn);+ document.addEventListener('visibilitychange', onVisible);+ return () => {+ alive.current = false; refreshSequence.current++;+ window.removeEventListener('focus', onReturn);+ document.removeEventListener('visibilitychange', onVisible);+ };}, [service]);+ useEffect(() => {+ const interval = state?.authState === 'authorizing' || state?.activationState === 'loading' ? 1000 : 3000;+ const timer = setInterval(() => { if (!busyRef.current) void refresh().catch(() => undefined); }, interval);+ return () => clearInterval(timer);+ }, [service, state?.authState, state?.activationState]);async function action(work: () => Promise<void>) {busyRef.current = true; refreshSequence.current++;setBusy(true); props.onBusyChange?.(true); setError('');try { await work(); }- catch (cause) { if (alive.current) setError(cause instanceof ApiClientError && cause.code === 'GATEWAY_REQUEST_CONFLICT' ? l('请先完成或取消当前任务,再退出登录', 'Complete or cancel the current tasks before signing out.') : l('操作未完成,请稍后重试', 'Request failed. Try again later.')); }+ catch (cause) { if (alive.current) setError(cause instanceof ApiClientError && cause.code === 'GATEWAY_REQUEST_CONFLICT' ? l('当前操作与正在进行的任务冲突,请稍后重试', 'This operation conflicts with current tasks. Try again later.') : l('操作未完成,请稍后重试', 'Request failed. Try again later.')); }finally { busyRef.current = false; if (alive.current) { setBusy(false); props.onBusyChange?.(false); } }}async function signIn() {if (!service) return;+ setConfirmingAuthorization(false);try {const value = await service.start();const url = new URL(value.authorizationUrl);if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('Invalid authorization URL');+ url.searchParams.set('lang', l('zh', 'en'));if (!alive.current) return;- setAuthorization(value); await refresh(); await props.openExternal?.(value.authorizationUrl);+ setAuthorization({ ...value, authorizationUrl: url.href }); await refresh(); await props.openExternal?.(url.href);} catch (cause) { props.onSignInCanceled?.(); throw cause; }}useEffect(() => {@@ -84,7 +110,7 @@ export function GatewayAccountSettingsView(props: {const signedIn = state?.authState === 'signed_in';const status = <p role="status">{!service ? l('登录服务暂不可用', 'Sign-in service is unavailable'): state === undefined ? l('正在连接账户服务…', 'Connecting to account service…')- : state.authState === 'authorizing' ? l('请在浏览器中完成登录', 'Complete sign-in in your browser')+ : state.authState === 'authorizing' ? confirmingAuthorization ? l('正在确认登录结果…', 'Confirming sign-in…') : l('请在浏览器中完成登录', 'Complete sign-in in your browser'): state.authState === 'signing_out' ? l('正在退出登录…', 'Signing out…'): state.authState === 'expired' ? l('登录已过期,请重新登录', 'Session expired; sign in again'): signedIn && profile ? l('已登录', 'Signed in')@@ -99,8 +125,11 @@ export function GatewayAccountSettingsView(props: {</div> : null}{state?.account && !profile ? <p className="gateway-account__email">{state.account.email}</p> : null}{profile ? <div className="gateway-account__identity"><h2>{signedIn ? state.account?.email ?? l('OpenCreator 账户', 'OpenCreator Account') : l('OpenCreator 账户', 'OpenCreator Account')}</h2>{status}</div> : status}- {state?.activationError && (!profile || state.source === 'gateway') ? <p role="alert">{state.activationError.code === 'active_tasks' ? l('请等待当前任务结束后再连接官方服务。', 'Wait for the current tasks to finish before connecting official services.') : l('模型服务暂不可用,请重新连接。', 'Model service is unavailable. Please reconnect.')}</p> : null}- {signedIn ? <div className="gateway-account__actions">+ {state?.activationError && (!profile || !signedIn) ? <p role="alert">{state.activationError.code === 'device_expired' ? l('登录授权已过期,请重新登录。', 'Authorization expired. Please sign in again.')+ : !signedIn ? l('登录未完成,请重新登录。', 'Sign-in did not complete. Please try again.')+ : state.activationError.code === 'active_tasks' ? l('请等待当前任务结束后再连接官方服务。', 'Wait for the current tasks to finish before connecting official services.') : l('模型服务暂不可用,请重新连接。', 'Model service is unavailable. Please reconnect.')}</p> : null}+ {signedIn && profile ? <details ref={accountMenu} className="gateway-account__menu"><summary title={l('账号菜单', 'Account menu')} aria-label={l('账号菜单', 'Account menu')}><MoreHorizontal size={20}/></summary><div><button type="button" disabled={busy || !service} onClick={() => void action(async () => update(await service!.logout()))}><LogOut size={16}/>{l('退出登录', 'Sign out')}</button></div></details>+ : signedIn ? <div className="gateway-account__actions">{(profile ? state.source === 'gateway' && state.activationState !== 'ready' : state.activationState !== 'ready' || state.source !== 'gateway') ? <button type="button" disabled={busy || !service || state.activationState === 'loading'} onClick={() => void action(async () => update(await service!.activate()))}><RefreshCw size={16}/>{l('重新连接', 'Reconnect')}</button> : null}{props.onOpenSubscription ? <button type="button" onClick={props.onOpenSubscription}><CreditCard size={16}/>{l('积分与充值', 'Credits')}</button> : null}<button type="button" disabled={busy || !service} onClick={() => void action(async () => update(await service!.logout()))}><LogOut size={16}/>{l('退出登录', 'Sign out')}</button>diff --git a/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsxindex fa5909bd..a993f397 100644--- a/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx+++ b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx@@ -1,101 +1,192 @@import { useEffect, useRef, useState } from 'react';-import { ArrowRight, CreditCard, ExternalLink, LoaderCircle, RefreshCw } from 'lucide-react';+import { CircleCheck, CreditCard, ExternalLink, HelpCircle, LoaderCircle, MessageSquare, ReceiptText, RefreshCw, Sparkles, X } from 'lucide-react';import type { GatewayAccountState } from '@opencreator/protocol';-import type { GatewayAccountSettingsService, GatewayBillingSummary } from '../../services/gateway-account-service.js';+import type { ExternalNavigation } from '../../host/bridge.js';+import type { GatewayAccountSettingsService, GatewayBillingSummary, GatewayRechargeOrder, GatewayWebDestination } from '../../services/gateway-account-service.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import { useAppLanguage } from '../../i18n/LanguageProvider.js';+import { ApiClientError } from '../../runtime/errors.js';import { formatGatewayCredits, GatewayAccountSettingsView } from './GatewayAccountSettingsView.js';+import { billingUnavailableMessage, creditPlansURL, rechargeOrderLabel, rechargeOrderStatus } from '../account/billing-display.js';import './gateway-account-settings.css';+import '../account/credits.css';++type PortalVisit = { startedAt: number; knownOrders?: string[]; orderId?: string };+const visitKey = (id: string) => `opencreator:billing-visit:${id}`;+function readVisit(id?: string): PortalVisit | undefined {+ if (!id) return;+ try {+ const value = JSON.parse(sessionStorage.getItem(visitKey(id)) ?? 'null');+ if (value && typeof value.startedAt === 'number' && Date.now() - value.startedAt < 2 * 60 * 60 * 1000+ && (!value.orderId || /^[A-Za-z0-9_-]{1,128}$/.test(value.orderId))+ && (!value.knownOrders || (Array.isArray(value.knownOrders) && value.knownOrders.every((item: unknown) => typeof item === 'string')))) return value;+ } catch { /* The current visit still works without browser storage. */ }+}export function GatewaySubscriptionSettingsView(props: {service: GatewayAccountSettingsService | null;embedded?: boolean;- variant?: 'overview' | 'subscription';accountState?: GatewayAccountState;- onOpenSubscription?(): void;+ billingOrderId?: string;+ billingReturnUrl?: string;+ prepareExternalNavigation?(): ExternalNavigation;openExternal?(url: string): Promise<void> | void;onStateChange?(state: GatewayAccountState): void;+ onRequestSignIn?(): void;}) {const l = useLocalizedCopy();const { language } = useAppLanguage();- const [state, setState] = useState<GatewayAccountState>();+ const [state, setState] = useState(props.accountState);+ const account = props.embedded ? props.accountState : state;+ const accountId = account?.authState === 'signed_in' ? account.account?.id : undefined;const [summary, setSummary] = useState<GatewayBillingSummary>();- const [loading, setLoading] = useState(true);- const [error, setError] = useState('');- const [busy, setBusy] = useState(false);- const alive = useRef(true);- const sequence = useRef(0);- const owner = useRef<string>();- const supplied = useRef(props.accountState); supplied.current = props.accountState;- const callback = useRef(props.onStateChange); callback.current = props.onStateChange;+ const [refreshing, setRefreshing] = useState(false);+ const [balanceError, setBalanceError] = useState(false);+ const [webError, setWebError] = useState(false);+ const [orderError, setOrderError] = useState(false);+ const [opening, setOpening] = useState<GatewayWebDestination>();+ const [order, setOrder] = useState<GatewayRechargeOrder>();+ const [signInRequest, setSignInRequest] = useState(0);+ const generation = useRef(0);+ const working = useRef(false);+ const webWorking = useRef(false);+ const visit = useRef<PortalVisit>();+ const dismissedOrder = useRef<string>();const service = props.service;- const overview = props.variant === 'overview';- const account = props.embedded ? props.accountState : state;- const signedIn = account?.authState === 'signed_in';+ const plansURL = creditPlansURL(summary?.plansUrl, language);+ function saveVisit(value?: PortalVisit) {+ visit.current = value;+ if (accountId) try {+ if (value) sessionStorage.setItem(visitKey(accountId), JSON.stringify(value));+ else sessionStorage.removeItem(visitKey(accountId));+ } catch { /* Optional recovery storage. */ }+ }async function refresh() {- const request = ++sequence.current;- if (!service) { setLoading(false); return; }+ if (!service || !accountId || working.current) return;+ working.current = true; setRefreshing(true);+ const request = generation.current;try {- const next = props.embedded ? supplied.current : await service.getState();- if (!alive.current || request !== sequence.current) return;- const id = next?.authState === 'signed_in' ? next.account?.id : undefined;- if (owner.current !== id) { owner.current = id; setSummary(undefined); }- setState(next);- if (!props.embedded && next) callback.current?.(next);- const value = id ? await service.getSummary() : undefined;- if (!alive.current || request !== sequence.current) return;- setSummary(value); setError('');- } catch {- if (alive.current && request === sequence.current) setError(l('积分信息暂不可用,请重试', 'Credit information is unavailable. Try again.'));- } finally { if (alive.current && request === sequence.current) setLoading(false); }+ const value = await service.getSummary();+ if (request !== generation.current) return;+ setSummary(value); setBalanceError(false);+ } catch { if (request === generation.current) setBalanceError(true); }+ const tracked = visit.current;+ const requestedOrder = props.billingOrderId ?? tracked?.orderId;+ if (tracked || requestedOrder) try {+ let id = requestedOrder;+ if (!id && tracked) {+ const result = await service.getOrders();+ if (request !== generation.current) return;+ id = [...result.items].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))+ .find(item => tracked.knownOrders ? !tracked.knownOrders.includes(item.id) : Date.parse(item.createdAt) >= tracked.startedAt)?.id;+ if (id) saveVisit({ ...tracked, orderId: id });+ }+ if (id && id !== dismissedOrder.current) {+ const result = await service.getOrder(id);+ if (request !== generation.current) return;+ setOrder(result.order); setOrderError(false);+ if (rechargeOrderStatus(result.order) === 'completed') {+ const updated = await service.getSummary();+ if (request !== generation.current) return;+ setSummary(updated); setBalanceError(false);+ saveVisit();+ }+ }+ } catch { if (request === generation.current) setOrderError(true); }+ if (request === generation.current) { working.current = false; setRefreshing(false); }}useEffect(() => {- alive.current = true; setLoading(true); setSummary(undefined); setBusy(false); setError('');+ generation.current++; working.current = false; webWorking.current = false;+ visit.current = readVisit(accountId); dismissedOrder.current = undefined;+ setSummary(undefined); setOrder(undefined); setOpening(undefined); setBalanceError(false); setWebError(false); setOrderError(false);void refresh();- const timer = setInterval(() => { void refresh(); }, 15_000);- const focus = () => { void refresh(); };- window.addEventListener('focus', focus);- return () => { alive.current = false; sequence.current++; clearInterval(timer); window.removeEventListener('focus', focus); };- }, [service, props.embedded, props.accountState?.account?.id, props.accountState?.authState]);-- const plansURL = (() => {- try {- const url = new URL(summary?.plansUrl || 'https://www.open-creator.ai/pricing');- const local = ['127.0.0.1', 'localhost'].includes(url.hostname);- if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) || url.username || url.password || url.pathname !== '/pricing') return undefined;- url.searchParams.set('lang', language === 'zh-CN' ? 'zh' : 'en');- return url.href;- } catch { return undefined; }- })();+ const onReturn = () => { if (document.visibilityState === 'visible') void refresh(); };+ const timer = setInterval(onReturn, 15_000);+ window.addEventListener('focus', onReturn); document.addEventListener('visibilitychange', onReturn);+ return () => { generation.current++; clearInterval(timer); window.removeEventListener('focus', onReturn); document.removeEventListener('visibilitychange', onReturn); };+ }, [service, accountId, props.billingOrderId]);+ useEffect(() => {+ if (!order || !['pending', 'processing'].includes(rechargeOrderStatus(order))) return;+ const timer = setInterval(() => { if (document.visibilityState === 'visible') void refresh(); }, 3_000);+ return () => clearInterval(timer);+ }, [order?.id, order?.status]);- async function recharge() {- if (!plansURL) return;- const id = owner.current;- setBusy(true); setError('');+ function fallbackURL(destination: GatewayWebDestination) {+ if (!plansURL) throw new Error('Account website is unavailable');+ const url = new URL(plansURL);+ if (destination === 'account') url.pathname = '/account';+ if (destination === 'usage') url.hash = 'usage';+ if (destination === 'faq') url.hash = 'faq-title';+ if (accountId) url.searchParams.set('account', accountId);+ url.searchParams.set('from', 'app');+ if (props.billingReturnUrl) url.searchParams.set('returnTo', props.billingReturnUrl);+ return url.href;+ }+ async function openWeb(destination: GatewayWebDestination) {+ if (webWorking.current) return;+ webWorking.current = true; setOpening(destination); setWebError(false);+ const request = generation.current;+ let navigation: ExternalNavigation | undefined;try {- if (props.openExternal) await props.openExternal(plansURL);- else window.open(plansURL, '_blank', 'noopener,noreferrer');- } catch {- if (alive.current && id === owner.current) setError(l('无法打开充值页面,请重试', 'Unable to open credit plans. Try again.'));- } finally { if (alive.current && id === owner.current) setBusy(false); }+ navigation = props.prepareExternalNavigation?.();+ let url = fallbackURL(destination);+ if (accountId && service?.openWebAccount) {+ try {+ const result = await service.openWebAccount(destination, language === 'zh-CN' ? 'zh' : 'en');+ const target = new URL(result.url);+ if (!plansURL || target.origin !== new URL(plansURL).origin || target.pathname !== '/auth' || !/^#handoff=[A-Za-z0-9_-]{32,128}$/.test(target.hash) || target.username || target.password) throw new Error('Invalid account link');+ url = target.href;+ } catch (error) {+ // Older gateways keep the existing website usable during the rollout.+ if (!(error instanceof ApiClientError && error.status === 404)) throw error;+ }+ }+ if (request !== generation.current) { navigation?.close(); return; }+ if (accountId && service && destination === 'recharge') {+ const startedAt = Date.now();+ let knownOrders: string[] | undefined;+ try { knownOrders = (await service.getOrders()).items.map(item => item.id); } catch { /* Match new orders by their creation time if history is unavailable. */ }+ if (request !== generation.current) { navigation?.close(); return; }+ saveVisit({ startedAt, knownOrders }); setOrder(undefined); dismissedOrder.current = undefined;+ }+ if (navigation) navigation.navigate(url);+ else if (props.openExternal) await props.openExternal(url);+ else { window.open(url, '_blank', 'noopener,noreferrer'); }+ } catch { navigation?.close(); if (request === generation.current) { setWebError(true); if (destination === 'recharge') saveVisit(); } }+ finally { if (request === generation.current) { webWorking.current = false; setOpening(undefined); } }}+ const status = order ? rechargeOrderStatus(order) : undefined;+ const paymentMessage = order && status === 'completed' ? l(`充值成功,已到账 ${formatGatewayCredits(order.creditUnits)} 积分`, `Recharge complete. ${formatGatewayCredits(order.creditUnits)} credits added.`)+ : status === 'processing' ? l('付款成功,积分到账中', 'Payment received. Credits are being added.')+ : order ? rechargeOrderLabel(order, l) : '';- return <section className={`gateway-account gateway-subscription${props.embedded ? ' gateway-subscription--embedded' : ''}`} aria-label={l('积分与充值', 'Credits')}>- {!props.embedded ? <GatewayAccountSettingsView service={service} variant="login" onStateChange={value => { setState(value); callback.current?.(value); void refresh(); }}/>: null}- {loading && !summary ? <p className="gateway-subscription__loading" role="status"><LoaderCircle size={16}/>{l('正在加载积分', 'Loading credits')}</p> : null}- {signedIn ? <div className="gateway-subscription__overview">- <div><h2>{l('可用积分', 'Available credits')}</h2><p className="gateway-subscription__credit-value">{summary ? formatGatewayCredits(summary.balance.availableUnits) : '—'} <small>{l('积分', 'credits')}</small></p>- {summary ? <p className="gateway-subscription__detail">{l(error ? '上次更新' : '更新于', error ? 'Last updated' : 'Updated')} {new Date(summary.balance.asOf).toLocaleString()}</p> : null}+ return <section className="account-credits" aria-label={l('积分与充值', 'Credits')}>+ {!props.embedded ? <GatewayAccountSettingsView service={service} variant="login" signInRequest={signInRequest} openExternal={props.openExternal} onStateChange={value => { setState(value); props.onStateChange?.(value); }}/> : null}+ <div className="account-credits__balance">+ <div><h2>{l('可用积分', 'Available credits')}</h2>+ {accountId ? <p className="account-credits__value">{summary ? formatGatewayCredits(summary.balance.availableUnits) : '--'} <small>{l('积分', 'credits')}</small></p>+ : <p className="credit-muted">{l('登录后查看积分', 'Sign in to view your credits')}</p>}+ {accountId && !summary && refreshing ? <p className="credit-loading" role="status"><LoaderCircle size={14}/>{l('正在加载积分', 'Loading credits')}</p> : null}+ {balanceError && summary ? <p className="credit-muted">{l('上次更新', 'Last updated')} {new Date(summary.balance.asOf).toLocaleString(language)}</p> : null}</div>- <div><h2>{l('充值积分', 'Buy credits')}</h2><p className="gateway-subscription__detail">{l('一次性购买 · 积分长期有效 · 无自动续费', 'One-time purchase · Credits never expire · No automatic renewal')}</p>- {summary?.paymentReview ? <p role="status">{l('付款正在审核,积分使用已暂停,请联系客服', 'Your payment is under review. Credit usage is paused. Contact support.')}</p> : null}- {!overview ? <button type="button" className="gateway-account__primary" disabled={busy || loading || !summary || !plansURL || !!error || !summary.billingAvailable} onClick={() => { void recharge(); }}><CreditCard size={16}/>{l('充值积分', 'Buy credits')}<ExternalLink size={14}/></button> : null}- {!overview && summary && !summary.billingAvailable && !summary.paymentReview ? <p className="gateway-subscription__detail" role="status">{l('充值暂不可用', 'Credit purchases are currently unavailable')}</p> : null}+ <div className="account-credits__actions">+ {accountId ? <button type="button" className="credit-icon-button" title={l('刷新积分', 'Refresh credits')} aria-label={l('刷新积分', 'Refresh credits')} disabled={refreshing} onClick={() => void refresh()}><RefreshCw size={17} className={refreshing ? 'is-spinning' : ''}/></button> : null}+ <button type="button" className="credit-primary" disabled={!!opening || !plansURL} onClick={() => void openWeb('recharge')}>+ {opening === 'recharge' ? <LoaderCircle size={16} className="is-spinning"/> : <CreditCard size={16}/>}{l('充值积分', 'Buy credits')}<ExternalLink size={14}/>+ </button></div>- </div> : !loading && !overview ? <p className="gateway-subscription__detail">{l('登录后可查看积分、购买积分并使用官方模型', 'Sign in to view your balance, buy credits, and use official models')}</p> : null}- {overview && props.onOpenSubscription ? <button type="button" className="gateway-subscription__entry" onClick={props.onOpenSubscription}><span>{l('积分与充值', 'Credits')}</span><ArrowRight size={17}/></button> : null}- {!overview && plansURL ? <a href={plansURL} target="_blank" rel="noreferrer">{l('查看积分方案', 'View credit plans')} <ExternalLink size={14}/></a> : null}- {error ? <div className="gateway-subscription__error"><p role="alert">{error}</p><button type="button" disabled={loading} onClick={() => { setLoading(true); void refresh(); }}><RefreshCw size={16}/>{l('重试', 'Retry')}</button></div> : null}+ </div>+ {balanceError ? <p className="credit-error" role="alert">{l('积分信息加载失败,请刷新重试。', 'Credits could not be loaded. Refresh to try again.')}</p> : null}+ {summary?.paymentReview ? <p className="credit-notice" role="status">{billingUnavailableMessage('payment_review', l)}</p> : null}+ {orderError ? <p className="credit-error" role="alert">{l('暂时无法确认订单,请刷新重试,勿重复付款。', 'Your order could not be confirmed. Refresh to try again; do not pay again.')}</p> : null}+ {order ? <div className={`account-payment${status === 'completed' ? ' is-completed' : ''}`}><div>{status === 'completed' ? <CircleCheck size={18}/> : <CreditCard size={18}/>}<span role="status">{paymentMessage}</span></div><button type="button" className="credit-icon-button" title={l('关闭付款提示', 'Dismiss payment status')} aria-label={l('关闭付款提示', 'Dismiss payment status')} onClick={() => { dismissedOrder.current = order.id; saveVisit(); setOrder(undefined); setOrderError(false); }}><X size={16}/></button></div> : null}+ {webError ? <p className="credit-error" role="alert">{l('网页未打开,请重试。', 'The website could not be opened. Try again.')}</p> : null}+ <nav className="account-credits__links" aria-label={l('账户与帮助', 'Account and help')}>+ <button type="button" disabled={!!opening || !plansURL} onClick={() => void openWeb('account')}><ReceiptText size={17}/><span>{l('账单与充值记录', 'Billing and recharge history')}</span><ExternalLink size={14}/></button>+ <button type="button" disabled={!!opening || !plansURL} onClick={() => void openWeb('usage')}><Sparkles size={17}/><span>{l('积分用量估算', 'Estimate credit usage')}</span><ExternalLink size={14}/></button>+ <button type="button" disabled={!!opening || !plansURL} onClick={() => void openWeb('faq')}><HelpCircle size={17}/><span>FAQ</span><ExternalLink size={14}/></button>+ <a href="https://github.com/krillinai/OpenCreator/issues" target="_blank" rel="noreferrer" onClick={props.openExternal ? event => { event.preventDefault(); void Promise.resolve(props.openExternal!('https://github.com/krillinai/OpenCreator/issues')).catch(() => setWebError(true)); } : undefined}><MessageSquare size={17}/><span>{l('问题反馈', 'Report an issue')}</span><ExternalLink size={14}/></a>+ </nav></section>;}diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsxindex f29a1a99..e64beba2 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx@@ -50,7 +50,7 @@ describe('OpenCreatorSettingsView', () => {});it('shows custom settings for guests and directs sign-in to the personal center', async () => {const gateway: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };- const service: GatewayAccountSettingsService = { getState: vi.fn(async () => gateway), setSource: vi.fn(), selectModel: vi.fn(), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), checkout: vi.fn(), portal: vi.fn() };+ const service: GatewayAccountSettingsService = { getState: vi.fn(async () => gateway), setSource: vi.fn(), selectModel: vi.fn(), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), getOrders: vi.fn(), getOrder: vi.fn(), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn() };const onOpenPersonalCenter = vi.fn();render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={gateway} initialTab="ai-services" onOpenPersonalCenter={onOpenPersonalCenter} onBack={vi.fn()}/>);expect(await screen.findByText('自定义配置')).toBeInTheDocument();@@ -62,7 +62,7 @@ describe('OpenCreatorSettingsView', () => {it('keeps signed-in accounts in official settings and restores custom settings after sign-out', async () => {const gateway: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: null, models: [], activationError: null };const local = { ...gateway, source: 'manual' as const, authState: 'signed_out' as const, activationState: 'inactive' as const, account: null };- const service: GatewayAccountSettingsService = { getState: vi.fn(async () => gateway), setSource: vi.fn(async () => local), selectModel: vi.fn(), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), checkout: vi.fn(), portal: vi.fn() };+ const service: GatewayAccountSettingsService = { getState: vi.fn(async () => gateway), setSource: vi.fn(async () => local), selectModel: vi.fn(), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), getOrders: vi.fn(), getOrder: vi.fn(), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn() };const onGatewayStateChange = vi.fn();const view = render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={gateway} initialTab="ai-services" onGatewayStateChange={onGatewayStateChange} onBack={vi.fn()}/>);expect(await screen.findByText('官方服务')).toBeInTheDocument();diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.tsxindex 01728a3f..140f0799 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx@@ -40,6 +40,8 @@ import type { GatewayAccountSettingsService } from '../../services/gateway-accouimport type { GatewayAccountState } from '@opencreator/protocol';import { OfficialServicesSettingsView } from './OfficialServicesSettingsView.js';import { NetworkSettings } from './NetworkSettings.js';+import { PlatformConnectionsSettingsView } from './PlatformConnectionsSettingsView.js';+import type { PlatformConnectionsService } from '../../services/platform-connections-service.js';const CreatorServicesSettingsView = lazy(async () => {const module = await import('./CreatorServicesSettingsView.js');@@ -78,6 +80,7 @@ export type OpenCreatorSettingsViewProps = {onProfileDataChange?(data: CodexProfileListResponse): void;cleanupService?: CleanupSettingsService | null;creatorServicesService?: CreatorServicesSettingsService | null;+ platformConnectionsService?: PlatformConnectionsService | null;gatewayAccountService?: GatewayAccountSettingsService | null;gatewayAccountState?: GatewayAccountState;onGatewayStateChange?(state: GatewayAccountState): void;@@ -103,6 +106,7 @@ export type OpenCreatorSettingsViewProps = {type SettingsTab =| 'general'| 'ai-services'+ | 'platform-connections'| 'local-components'| 'plugins'| 'memory'@@ -120,6 +124,7 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {const tabs: Array<{ id: SettingsTab; label: string }> = [{ id: 'general', label: t('settings.tab.general') },{ id: 'ai-services', label: t('settings.tab.aiServices') },+ { id: 'platform-connections', label: l('平台连接', 'Platform connections') },{ id: 'local-components', label: t('settings.tab.runtimeComponents') },{ id: 'plugins', label: t('settings.tab.plugins') },{ id: 'memory', label: t('settings.tab.memory') },@@ -242,6 +247,7 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {controller={props.runtimeDependencies}/>) : null}+ {activeTab === 'platform-connections' ? <PlatformConnectionsSettingsView connected={props.runtimeStatus.connected} service={props.platformConnectionsService} /> : null}{activeTab === 'plugins' ? <PluginSettings runtimeStatus={props.runtimeStatus} /> : null}{activeTab === 'memory' ? (<MemorySettingsViewdiff --git a/apps/web/src/features/settings/PlatformConnectionsSettingsView.test.tsx b/apps/web/src/features/settings/PlatformConnectionsSettingsView.test.tsxnew file mode 100644index 00000000..4d5fc45c--- /dev/null+++ b/apps/web/src/features/settings/PlatformConnectionsSettingsView.test.tsx@@ -0,0 +1,40 @@+import { render, screen, waitFor } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';+import { expect, it, vi } from 'vitest';+import type { YouTubeConnectionState } from '@opencreator/protocol';+import { PlatformConnectionsSettingsView } from './PlatformConnectionsSettingsView.js';++function api(initial: YouTubeConnectionState['status'] = 'disconnected') {+ let state: YouTubeConnectionState = { platform: 'youtube', status: initial };+ return {+ getYouTube: vi.fn(async () => state),+ connectYouTube: vi.fn(async () => state = { platform: 'youtube', status: 'connecting' }),+ cancelYouTube: vi.fn(async () => state = { platform: 'youtube', status: 'disconnected' }),+ disconnectYouTube: vi.fn(async () => state = { platform: 'youtube', status: 'disconnected' }),+ importYouTube: vi.fn(async () => state),+ finish: () => { state = { platform: 'youtube', status: 'connected' }; }+ };+}++it('connects with one click, polls automatic completion, and allows disconnect', async () => {+ const service = api(); const user = userEvent.setup();+ render(<PlatformConnectionsSettingsView connected service={service} />);+ await screen.findByText('未连接');+ await user.click(screen.getByRole('button', { name: '连接' }));+ expect(service.connectYouTube).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('status')).toHaveTextContent('正在读取浏览器登录态');+ service.finish();+ await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('已连接'), { timeout: 3000 });+ await user.click(screen.getByRole('button', { name: '断开' }));+ expect(service.disconnectYouTube).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('status')).toHaveTextContent('未连接');+});++it('cancels a login and disables actions when the runtime is disconnected', async () => {+ const service = api('connecting'); const user = userEvent.setup();+ const view = render(<PlatformConnectionsSettingsView connected service={service} />);+ await user.click(await screen.findByRole('button', { name: '取消' }));+ expect(service.cancelYouTube).toHaveBeenCalledTimes(1);+ view.rerender(<PlatformConnectionsSettingsView connected={false} service={service} />);+ expect(screen.getByRole('button', { name: '连接' })).toBeDisabled();+});diff --git a/apps/web/src/features/settings/PlatformConnectionsSettingsView.tsx b/apps/web/src/features/settings/PlatformConnectionsSettingsView.tsxnew file mode 100644index 00000000..14d70f51--- /dev/null+++ b/apps/web/src/features/settings/PlatformConnectionsSettingsView.tsx@@ -0,0 +1,82 @@+import { useEffect, useRef, useState } from 'react';+import { CheckCircle2, Link2, Loader2, RefreshCw, Unlink, Upload, X } from 'lucide-react';+import type { YouTubeConnectionState } from '@opencreator/protocol';+import type { PlatformConnectionsService } from '../../services/platform-connections-service.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import './platform-connections.css';++export function PlatformConnectionsSettingsView(props: { connected: boolean; service?: PlatformConnectionsService | null }) {+ const l = useLocalizedCopy();+ const [state, setState] = useState<YouTubeConnectionState>();+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string>();+ const [selectedProfile, setSelectedProfile] = useState('');+ const fileInput = useRef<HTMLInputElement>(null);+ const requestVersion = useRef(0);++ useEffect(() => {+ const service = props.service;+ if (!props.connected || !service) return;+ let canceled = false;+ let timer: ReturnType<typeof setTimeout>;+ const poll = async () => {+ const version = requestVersion.current;+ try {+ const next = await service.getYouTube();+ if (!canceled && version === requestVersion.current) { setState(next); setError(undefined); }+ } catch { if (!canceled) setError(l('无法读取连接状态,请重试。', 'Unable to read connection status. Try again.')); }+ if (!canceled) timer = setTimeout(poll, 1500);+ };+ void poll();+ return () => { canceled = true; clearTimeout(timer); };+ }, [props.connected, props.service, l]);++ async function act(operation: () => Promise<YouTubeConnectionState>) {+ setBusy(true); setError(undefined); ++requestVersion.current;+ try { setState(await operation()); }+ catch { setError(l('操作未完成,请检查网络或重新连接。', 'The operation failed. Check your network or reconnect.')); }+ finally { ++requestVersion.current; setBusy(false); }+ }++ const service = props.service;+ const disabled = !props.connected || !service || busy;+ const connecting = state?.status === 'connecting';+ const connected = state?.status === 'connected';+ const profiles = state?.profiles ?? [];+ const profileId = profiles.some(profile => profile.id === selectedProfile) ? selectedProfile+ : state?.profileId ?? profiles[0]?.id;+ const label = connected ? l('已连接', 'Connected') : connecting ? l('正在读取浏览器登录态', 'Reading browser session')+ : state?.status === 'expired' ? l('登录已过期', 'Session expired') : state?.status === 'error' ? l('连接失败', 'Connection failed')+ : l('未连接', 'Disconnected');++ return <section className="settings-section" aria-labelledby="platform-connections-title">+ <header><h1 id="platform-connections-title">{l('平台连接', 'Platform connections')}</h1></header>+ <div className="platform-connection-row">+ <div className="platform-connection-identity">+ <img src="/youtube.ico" width="36" height="36" alt="" />+ <div><h2>YouTube</h2><span className={`platform-connection-status${connected ? ' is-connected' : ''}`} role="status">+ {connected ? <CheckCircle2 size={15} /> : connecting ? <Loader2 size={15} className="platform-connection-spinner" /> : null}{label}</span></div>+ </div>+ <div className="platform-connection-actions">+ {profiles.length ? <select aria-label={l('浏览器账号', 'Browser profile')} value={profileId} disabled={disabled || connecting}+ onChange={event => setSelectedProfile(event.target.value)}>+ {profiles.map(profile => <option key={profile.id} value={profile.id}>{profile.label}</option>)}+ </select> : null}+ {connecting ? <button type="button" disabled={disabled} onClick={() => service && void act(service.cancelYouTube)}><X size={16} />{l('取消', 'Cancel')}</button>+ : <button type="button" disabled={disabled} onClick={() => service && void act(() => service.connectYouTube(profileId))}>+ {connected || state?.status === 'expired' ? <RefreshCw size={16} /> : <Link2 size={16} />}+ {connected || state?.status === 'expired' ? l('重新连接', 'Reconnect') : l('连接', 'Connect')}</button>}+ {connected || state?.status === 'expired' ? <button type="button" disabled={disabled} onClick={() => service && void act(service.disconnectYouTube)}><Unlink size={16} />{l('断开', 'Disconnect')}</button> : null}+ {!connecting ? <button type="button" disabled={disabled} aria-label={l('导入 Cookie 文件', 'Import cookie file')} title={l('导入 Cookie 文件', 'Import cookie file')} onClick={() => fileInput.current?.click()}><Upload size={16} /></button> : null}+ </div>+ </div>+ {state?.message ? <p role="status">{state.message}</p> : null}+ {error ? <p role="alert">{error}</p> : null}+ <input ref={fileInput} type="file" accept=".txt" hidden onChange={event => {+ const file = event.currentTarget.files?.[0]; event.currentTarget.value = '';+ if (!file || !service) return;+ if (file.size > 1024 * 1024) { setError(l('文件过大,请选择有效的 Cookie 文件。', 'The file is too large. Select a valid cookie file.')); return; }+ void act(async () => service.importYouTube(await file.text()));+ }} />+ </section>;+}diff --git a/apps/web/src/features/settings/StartupAgentSetup.test.tsx b/apps/web/src/features/settings/StartupAgentSetup.test.tsxindex 2901e5ff..8238cade 100644--- a/apps/web/src/features/settings/StartupAgentSetup.test.tsx+++ b/apps/web/src/features/settings/StartupAgentSetup.test.tsx@@ -219,7 +219,7 @@ describe('StartupAgentSetup', () => {getState: vi.fn(async () => state),start: vi.fn(async () => { state = { ...state, authState: 'authorizing' }; return { attemptId: 'a', authorizationUrl: 'https://gateway.example/device', expiresAt: '2026-11-01T00:00:00Z' }; }),cancel: vi.fn(async () => { state = { ...state, authState: 'signed_out' }; return state; }),- activate: vi.fn(), logout: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), checkout: vi.fn(), portal: vi.fn()+ activate: vi.fn(), logout: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(), getPlans: vi.fn(), getOrders: vi.fn(), getOrder: vi.fn(), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn()};render(<LanguageProvider initialPreference="zh-CN"><StartupAgentSetup service={createService()} gatewayService={gateway} onReady={vi.fn()} onSkip={vi.fn()}/></LanguageProvider>);const user = userEvent.setup();diff --git a/apps/web/src/features/settings/platform-connections.css b/apps/web/src/features/settings/platform-connections.cssnew file mode 100644index 00000000..bfdaaaa1--- /dev/null+++ b/apps/web/src/features/settings/platform-connections.css@@ -0,0 +1,14 @@+.platform-connection-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 20px 0; border-bottom: 1px solid var(--border); }+.platform-connection-identity { display: flex; align-items: center; gap: 12px; min-width: 0; }+.platform-connection-identity h2 { font-size: 16px; margin: 0 0 6px; }+.platform-connection-status { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); }+.platform-connection-status.is-connected { color: var(--success); }+.platform-connection-actions { display: flex; flex-wrap: wrap; gap: 8px; }+.platform-connection-actions select { min-width: 0; max-width: 220px; min-height: 34px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; color: var(--text); background: var(--surface); }+.platform-connection-actions button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 34px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: transparent; color: inherit; cursor: pointer; }+.platform-connection-actions button:hover:not(:disabled) { background: var(--surface-hover); }+.platform-connection-actions button:disabled { opacity: .5; cursor: default; }+.platform-connection-spinner { animation: platform-connection-spin 1s linear infinite; }+@keyframes platform-connection-spin { to { transform: rotate(360deg); } }+@media (max-width: 600px) { .platform-connection-row { align-items: flex-start; flex-direction: column; } }+@media (prefers-reduced-motion: reduce) { .platform-connection-spinner { animation: none; } }diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsxindex 2430faed..b1e413af 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx@@ -72,10 +72,10 @@ describe('OpenCreatorSidebar', () => {])('opens the personal center from the footer when collapsed=$collapsed and activeView=$activeView', ({ collapsed, activeView }) => {const onOpenView = vi.fn();renderSidebar({ collapsed, activeView, onOpenView });- const button = screen.getByRole('button', { name: '账户' });+ const button = screen.getByRole('button', { name: '个人中心' });expect(button.parentElement).toHaveClass('sidebar-bottom');expect(button).toHaveAttribute('aria-current', 'page');- expect(button).toHaveAttribute('title', '账户');+ expect(button).toHaveAttribute('title', '个人中心');fireEvent.click(button);expect(onOpenView).toHaveBeenCalledWith('account');});diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.tsxindex a35ebfff..318635ef 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.tsx@@ -813,9 +813,9 @@ export function OpenCreatorSidebar(props: {)}<div className="sidebar-bottom">- <button type="button" className="sidebar-account" aria-label={l('账户', 'Account')} title={l('账户', 'Account')} aria-current={props.activeView === 'account' || props.activeView === 'subscription' ? 'page' : undefined} onClick={() => props.onOpenView('account')}>+ <button type="button" className="sidebar-account" aria-label={l('个人中心', 'Account')} title={l('个人中心', 'Account')} aria-current={props.activeView === 'account' || props.activeView === 'subscription' ? 'page' : undefined} onClick={() => props.onOpenView('account')}><AccountAvatar email={accountEmail} accountId={props.gatewayAccountState?.account?.id} avatarUrl={props.gatewayAccountState?.account?.avatarUrl} loadAvatar={props.loadAccountAvatar}/>- {!collapsed ? <span className="sidebar-account__copy"><strong>{l('账户', 'Account')}</strong><small>{accountEmail ?? (props.gatewayAccountState?.authState === 'expired' ? l('登录已过期', 'Session expired') : l('未登录', 'Signed out'))}</small></span> : null}+ {!collapsed ? <span className="sidebar-account__copy"><strong>{l('个人中心', 'Account')}</strong><small>{accountEmail ?? (props.gatewayAccountState?.authState === 'expired' ? l('登录已过期', 'Session expired') : l('未登录', 'Signed out'))}</small></span> : null}</button></div>diff --git a/apps/web/src/host/bridge.ts b/apps/web/src/host/bridge.tsindex 6ca51759..8e0de549 100644--- a/apps/web/src/host/bridge.ts+++ b/apps/web/src/host/bridge.ts@@ -21,6 +21,7 @@ export type DesktopPreferences = {};export type DirectorySelectionPurpose = 'project' | 'default-project-root' | 'output-root';+export type ExternalNavigation = { navigate(url: string): void; close(): void };export type HostWindowChrome = {integratedTitleBar: true;@@ -31,6 +32,10 @@ export type HostWindowChrome = {export type HostBridge = {kind: 'browser' | 'desktop';windowChrome?: HostWindowChrome;+ authorizationReturnUrl?: string;+ billingReturnUrl?: string;+ prepareExternalNavigation?(): ExternalNavigation;+ subscribeBillingReturn?(listener: (orderId?: string) => void): () => void;readAppVersion?(): Promise<string>;readConnectionConfig(): Promise<ConnectionConfig | null>;openExternal(url: string): Promise<void>;diff --git a/apps/web/src/host/browser-bridge.test.ts b/apps/web/src/host/browser-bridge.test.tsindex f7a0ade7..196ff529 100644--- a/apps/web/src/host/browser-bridge.test.ts+++ b/apps/web/src/host/browser-bridge.test.ts@@ -25,6 +25,39 @@ describe('browserBridge', () => {});expect(fetch).toHaveBeenCalledWith('/.opencreator/runtime-config', expect.objectContaining({ method: 'GET' }));});+ it('opens a tab synchronously and removes its opener before an account request', () => {+ const replace = vi.fn(); const close = vi.fn();+ const tab = { opener: window, name: '', closed: false, location: { replace }, close };+ const open = vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ const navigation = browserBridge.prepareExternalNavigation!();+ expect(open).toHaveBeenCalledWith('about:blank', '_blank');+ expect(tab.opener).toBeNull();+ navigation.navigate('https://www.open-creator.ai/pricing');+ expect(replace).toHaveBeenCalledWith('https://www.open-creator.ai/pricing');+ navigation.close(); expect(close).toHaveBeenCalledOnce();+ open.mockRestore();+ });++ it('signals an order return to the original tab without accepting a payment claim', () => {+ let latest: { onmessage?: (event: { data: unknown }) => void; postMessage: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };+ class Channel {+ onmessage?: (event: { data: unknown }) => void;+ postMessage = vi.fn(); close = vi.fn();+ constructor() { latest = this; }+ }+ vi.stubGlobal('BroadcastChannel', Channel);+ const focus = vi.spyOn(window, 'focus').mockImplementation(() => {});+ const received = vi.fn();+ const unsubscribe = browserBridge.subscribeBillingReturn!(received);+ const tabId = new URL(browserBridge.billingReturnUrl!).hash.split('tabId=')[1];+ latest!.onmessage!({ data: { type: 'return', tabId, nonce: 'return-request', orderId: 'order-a' } });+ expect(received).toHaveBeenCalledWith('order-a');+ expect(latest!.postMessage).toHaveBeenCalledWith({ type: 'ack', nonce: 'return-request' });+ latest!.onmessage!({ data: { type: 'return', tabId, nonce: 'bad-request', orderId: '../other' } });+ latest!.onmessage!({ data: { type: 'return', tabId: 'other-tab', nonce: 'other-request', orderId: 'order-b' } });+ expect(received).toHaveBeenCalledOnce();+ unsubscribe(); expect(latest!.close).toHaveBeenCalledOnce(); focus.mockRestore();+ });it('falls back to local storage when same-origin runtime config is unavailable', async () => {window.localStorage.setItem(diff --git a/apps/web/src/host/browser-bridge.ts b/apps/web/src/host/browser-bridge.tsindex 84315a85..246c5648 100644--- a/apps/web/src/host/browser-bridge.ts+++ b/apps/web/src/host/browser-bridge.ts@@ -5,9 +5,56 @@ import type { HostBridge, HostBridgeResult, HostNotification } from './bridge.jsconst CONNECTION_KEY = 'opencreator.web.connection.v1';const DEV_RUNTIME_CONFIG_PATH = '/.opencreator/runtime-config';+let billingTabId: string | undefined;+function getBillingTabId() {+ if (!billingTabId) {+ try { billingTabId = sessionStorage.getItem('opencreator:billing-tab') ?? undefined; } catch { /* Tab memory is sufficient for the current return. */ }+ billingTabId ||= crypto.randomUUID();+ try { sessionStorage.setItem('opencreator:billing-tab', billingTabId); } catch { /* Optional reload recovery. */ }+ }+ return billingTabId;+}export const browserBridge: HostBridge = {kind: 'browser',+ get authorizationReturnUrl() { return new URL('/#/account?login=complete', window.location.href).href; },+ get billingReturnUrl() { return new URL('/#/account?billing=return&tabId=' + getBillingTabId(), window.location.href).href; },+ prepareExternalNavigation() {+ const tab = window.open('about:blank', '_blank');+ if (!tab) throw new Error('Browser blocked the new tab');+ tab.opener = null;+ tab.name = 'opencreator-billing';+ return {+ navigate(url: string) { if (tab.closed) throw new Error('The new tab was closed'); tab.location.replace(url); },+ close() { tab.close(); }+ };+ },+ subscribeBillingReturn(listener) {+ if (typeof BroadcastChannel === 'undefined') return () => {};+ const channel = new BroadcastChannel('opencreator.billing-return.v1');+ const params = new URLSearchParams(window.location.hash.split('?')[1] ?? '');+ const returnTabId = params.get('tabId');+ const returning = params.get('billing') === 'return' && !!returnTabId;+ const tabId = getBillingTabId();+ const nonce = crypto.randomUUID();+ channel.onmessage = event => {+ const value = event.data;+ if (returning) {+ if (value?.type === 'ack' && value.nonce === nonce) window.close();+ } else if (value?.type === 'return' && value.tabId === tabId && typeof value.nonce === 'string'+ && (value.orderId === undefined || (typeof value.orderId === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value.orderId)))) {+ listener(value.orderId);+ channel.postMessage({ type: 'ack', nonce: value.nonce });+ window.focus();+ }+ };+ // The return tab signals the original app; the app still verifies the order with the server.+ if (returning) {+ const orderId = params.get('orderId');+ if (!orderId || /^[A-Za-z0-9_-]{1,128}$/.test(orderId)) channel.postMessage({ type: 'return', tabId: returnTabId, nonce, ...(orderId ? { orderId } : {}) });+ }+ return () => channel.close();+ },async readConnectionConfig(): Promise<ConnectionConfig | null> {const sameOriginConfig = await readSameOriginRuntimeConfig();return sameOriginConfig ?? parseStoredConnectionConfig(diff --git a/apps/web/src/host/desktop-bridge.ts b/apps/web/src/host/desktop-bridge.tsindex b4c7570b..d8eda2ea 100644--- a/apps/web/src/host/desktop-bridge.ts+++ b/apps/web/src/host/desktop-bridge.ts@@ -74,6 +74,8 @@ export function readDesktopHostBridge(): DesktopHostBridge | undefined {: undefined;return {kind: 'desktop',+ authorizationReturnUrl: 'opencreator://auth/complete',+ billingReturnUrl: 'opencreator://billing/return',...(windowChrome === undefined ? {} : { windowChrome }),readAppVersion: () => api.readAppVersion(),readConnectionConfig: () => api.readConnectionConfig(),diff --git a/apps/web/src/services/gateway-account-service.test.ts b/apps/web/src/services/gateway-account-service.test.tsindex ef23b69e..cd3ad33c 100644--- a/apps/web/src/services/gateway-account-service.test.ts+++ b/apps/web/src/services/gateway-account-service.test.ts@@ -2,6 +2,18 @@ import { expect, it, vi } from 'vitest';import { RuntimeClient } from '../runtime/client.js';import { createGatewayAccountService } from './gateway-account-service.js';+it('checks browser authorization through the shared Daemon and adds the host return destination', async () => {+ const grant = { attemptId: 'attempt-1', authorizationUrl: 'https://gateway.example/device?grant=attempt-1', expiresAt: '2026-10-10T12:00:00Z' };+ const client = new RuntimeClient({ baseUrl: 'http://localhost', fetchImpl: vi.fn(async () => Response.json(grant)) });+ const post = vi.spyOn(client, 'post');+ const service = createGatewayAccountService(client, { authorizationReturnUrl: 'opencreator://auth/complete' });+ const result = await service.start();+ expect(new URL(result.authorizationUrl).searchParams.get('returnTo')).toBe('opencreator://auth/complete');+ expect(new URL(result.authorizationUrl).searchParams.get('grant')).toBe('attempt-1');+ expect(result.attemptId).toBe(grant.attemptId);+ await service.getState({ checkAuthorization: true });+ expect(post).toHaveBeenLastCalledWith('/gateway/auth/check', {});+});it('displays a signed-in account when official activation is blocked', async () => {const snapshot = { source: 'manual', authState: 'signed_in', activationState: 'blocked', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: null, models: [], activationError: { code: 'services_not_ready', message: 'Official service is not ready' } };const client = new RuntimeClient({ baseUrl: 'http://localhost', fetchImpl: vi.fn(async () => Response.json(snapshot)) });@@ -14,6 +26,23 @@ it('reads the subscription summary through the shared Daemon', async () => {await createGatewayAccountService(client).getSummary();expect(read).toHaveBeenCalledWith('/gateway/billing/summary');});+it('requests a website session with the host billing return address', async () => {+ const client = new RuntimeClient({ baseUrl: 'http://localhost', fetchImpl: vi.fn(async () => Response.json({ url: 'https://gateway.example/auth#handoff=code' })) });+ const post = vi.spyOn(client, 'post');+ await createGatewayAccountService(client, { billingReturnUrl: 'opencreator://billing/return' }).openWebAccount('recharge', 'zh');+ expect(post).toHaveBeenLastCalledWith('/gateway/account/web', { destination: 'recharge', locale: 'zh', returnUrl: 'opencreator://billing/return' });+});+it('loads private order details and pages credit grants through the shared Daemon', async () => {+ const client = new RuntimeClient({ baseUrl: 'http://localhost', fetchImpl: vi.fn(async () => Response.json({})) });+ const read = vi.spyOn(client, 'get'); const post = vi.spyOn(client, 'post');+ const service = createGatewayAccountService(client);+ await service.getOrder('order/a');+ expect(read).toHaveBeenLastCalledWith('/gateway/billing/orders/order%2Fa');+ await service.getCreditGrants('trial:a+b');+ expect(read).toHaveBeenLastCalledWith('/gateway/billing/ledger?cursor=trial%3Aa%2Bb');+ await service.checkout('starter', 'operation-id', { locale: 'zh', currency: 'hkd' });+ expect(post).toHaveBeenLastCalledWith('/gateway/billing/checkout', { planId: 'starter', operationId: 'operation-id', locale: 'zh', currency: 'hkd' });+});it('loads and shares photo bytes through the authenticated Runtime client', async () => {const fetcher = vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { headers: { 'Content-Type': 'image/png' } }));diff --git a/apps/web/src/services/gateway-account-service.ts b/apps/web/src/services/gateway-account-service.tsindex 0f820b14..e2e6aae9 100644--- a/apps/web/src/services/gateway-account-service.ts+++ b/apps/web/src/services/gateway-account-service.ts@@ -1,15 +1,29 @@import type { GatewayAccountState, GatewayAuthorization, GatewayBalanceSnapshot, GatewayBalanceState, ServiceSource } from '@opencreator/protocol';import type { RuntimeClient } from '../runtime/client.js';-export type GatewayPlan = { id: string; name: string; currency: string; amountUnits: string; creditUnits: string };+export type GatewayPlan = { id: string; name: string; currency: string; amountUnits: string; creditUnits: string; wechatAmountUnits?: string };+export type GatewayBillingAvailability = {+ billingAvailable: boolean;+ billingUnavailableReason?: 'purchases_disabled' | 'payment_service_unavailable' | 'official_services_unavailable' | 'payment_review' | string;+};+export type GatewayPlans = GatewayBillingAvailability & { plans: GatewayPlan[]; plansUrl?: string; purchaseMode?: 'credits'; paymentMode?: 'test' | 'live' };+export type GatewayRechargeOrder = {+ id: string; planId: string; planName?: string; operationId?: string;+ amountUnits: string; currency: string; creditUnits: string;+ status: string; paymentStatus: string; creditStatus: string; reviewRequired: boolean;+ paymentMode: 'test' | 'live'; createdAt: string; expiresAt?: string; paidAt: string | null; completedAt: string | null;+};+export type GatewayCreditGrant = { id: string; kind: 'grant'; units: string; createdAt: string; businessKey: string; source: string };export type GatewayBillingSummary = {balance: GatewayBalanceSnapshot;subscription: { id: string; status: string; periodStart: string; periodEnd: string; cancelAtPeriodEnd: boolean; nextPlanId: string | null; plan?: GatewayPlan } | null;billingAvailable: boolean;+ billingUnavailableReason?: GatewayBillingAvailability['billingUnavailableReason'];purchaseMode?: 'credits';plansUrl?: string;paymentReview?: boolean;};-export function createGatewayAccountService(client: Pick<RuntimeClient, 'get' | 'post' | 'patch'> & Partial<Pick<RuntimeClient, 'rawGet'>>) {+export type GatewayWebDestination = 'recharge' | 'account' | 'usage' | 'faq';+export function createGatewayAccountService(client: Pick<RuntimeClient, 'get' | 'post' | 'patch'> & Partial<Pick<RuntimeClient, 'rawGet'>>, options: { authorizationReturnUrl?: string; billingReturnUrl?: string } = {}) {const rawGet = client.rawGet?.bind(client);let avatarCache: { key: string; work: Promise<Blob> } | undefined;return {@@ -23,8 +37,16 @@ export function createGatewayAccountService(client: Pick<RuntimeClient, 'get' |avatarCache = { key, work };return work;} } : {}),- getState(): Promise<GatewayAccountState> { return client.get('/gateway/account'); },- start(): Promise<GatewayAuthorization> { return client.post('/gateway/auth/start', {}); },+ getState(options?: { checkAuthorization?: boolean }): Promise<GatewayAccountState> {+ return options?.checkAuthorization ? client.post('/gateway/auth/check', {}) : client.get('/gateway/account');+ },+ async start(): Promise<GatewayAuthorization> {+ const grant = await client.post<GatewayAuthorization>('/gateway/auth/start', {});+ if (!options.authorizationReturnUrl) return grant;+ const url = new URL(grant.authorizationUrl);+ url.searchParams.set('returnTo', options.authorizationReturnUrl);+ return { ...grant, authorizationUrl: url.href };+ },cancel(): Promise<GatewayAccountState> { return client.post('/gateway/auth/cancel', {}); },logout(): Promise<GatewayAccountState> { return client.post('/gateway/auth/logout', {}); },activate(): Promise<GatewayAccountState> { return client.post('/gateway/auth/activate', {}); },@@ -32,9 +54,15 @@ export function createGatewayAccountService(client: Pick<RuntimeClient, 'get' |selectModel(modality: import('@opencreator/protocol').GatewayModel['modality'], model: string): Promise<GatewayAccountState> { return client.patch('/gateway/model', { modality, model }); },getBalance(): Promise<GatewayBalanceState> { return client.get('/gateway/billing'); },getSummary(): Promise<GatewayBillingSummary> { return client.get('/gateway/billing/summary'); },- getPlans(): Promise<{ plans: GatewayPlan[]; billingAvailable: boolean; plansUrl?: string; purchaseMode?: 'credits'; paymentMode?: 'test' | 'live' }> { return client.get('/gateway/plans'); },- checkout(planId: string, operationId: string): Promise<{ url: string }> { return client.post('/gateway/billing/checkout', { planId, operationId }); },+ openWebAccount(destination: GatewayWebDestination, locale: 'zh' | 'en'): Promise<{ url: string }> {+ return client.post('/gateway/account/web', { destination, locale, ...(options.billingReturnUrl ? { returnUrl: options.billingReturnUrl } : {}) });+ },+ getPlans(): Promise<GatewayPlans> { return client.get('/gateway/plans'); },+ getOrders(): Promise<{ items: GatewayRechargeOrder[] }> { return client.get('/gateway/billing/orders'); },+ getOrder(id: string): Promise<{ order: GatewayRechargeOrder }> { return client.get('/gateway/billing/orders/' + encodeURIComponent(id)); },+ getCreditGrants(cursor?: string): Promise<{ items: GatewayCreditGrant[] }> { return client.get('/gateway/billing/ledger' + (cursor ? '?cursor=' + encodeURIComponent(cursor) : '')); },+ checkout(planId: string, operationId: string, options: { locale?: 'zh' | 'en'; currency?: string } = {}): Promise<{ url: string; orderId: string }> { return client.post('/gateway/billing/checkout', { planId, operationId, ...options }); },portal(): Promise<{ url: string }> { return client.post('/gateway/billing/portal', {}); }};}-export type GatewayAccountSettingsService = ReturnType<typeof createGatewayAccountService>;+export type GatewayAccountSettingsService = Omit<ReturnType<typeof createGatewayAccountService>, 'openWebAccount'> & Partial<Pick<ReturnType<typeof createGatewayAccountService>, 'openWebAccount'>>;diff --git a/apps/web/src/services/platform-connections-service.ts b/apps/web/src/services/platform-connections-service.tsnew file mode 100644index 00000000..39587ad6--- /dev/null+++ b/apps/web/src/services/platform-connections-service.ts@@ -0,0 +1,15 @@+import type { YouTubeConnectionState } from '@opencreator/protocol';+import type { RuntimeClient } from '../runtime/client.js';++export function createPlatformConnectionsService(client: Pick<RuntimeClient, 'get' | 'post' | 'delete'>) {+ const path = '/platform-connections/youtube';+ return {+ getYouTube(): Promise<YouTubeConnectionState> { return client.get(path); },+ connectYouTube(profileId?: string): Promise<YouTubeConnectionState> { return client.post(`${path}/connect`, { profileId }); },+ cancelYouTube(): Promise<YouTubeConnectionState> { return client.post(`${path}/cancel`); },+ disconnectYouTube(): Promise<YouTubeConnectionState> { return client.delete(path); },+ importYouTube(cookies: string): Promise<YouTubeConnectionState> { return client.post(`${path}/import`, { cookies }); }+ };+}++export type PlatformConnectionsService = ReturnType<typeof createPlatformConnectionsService>;diff --git a/package.json b/package.jsonindex 0a1e807e..760ff65f 100644--- a/package.json+++ b/package.json@@ -47,6 +47,9 @@"undici@>=8.0.0 <8.10.2": "8.10.2","find-my-way@<=9.6.0": "9.7.0","postcss@<=8.5.17": "8.5.18",+ "proxy-addr@<2.0.8": "2.0.8",+ "source-map-js@<1.2.2": "1.2.2",+ "tinypool@<2.1.2": "2.1.2","brace-expansion@<1.1.20": "1.1.20","brace-expansion@>=2.0.0 <2.1.6": "2.1.6","brace-expansion@>=4.0.0 <5.0.11": "5.0.11",diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 3d118d44..56982260 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -16,3 +16,4 @@ export * from './video-metadata.js';export * from './wechat-article.js';export * from './stickman.js';export * from './gateway-account.js';+export * from './platform-connections.js';diff --git a/packages/protocol/src/platform-connections.ts b/packages/protocol/src/platform-connections.tsnew file mode 100644index 00000000..eab7e2ca--- /dev/null+++ b/packages/protocol/src/platform-connections.ts@@ -0,0 +1,9 @@+export type YouTubeConnectionState = {+ platform: 'youtube';+ status: 'disconnected' | 'connecting' | 'connected' | 'expired' | 'error';+ browser?: 'chrome' | 'edge';+ connectedAt?: string;+ profileId?: string;+ profiles?: Array<{ id: string; browser: 'chrome' | 'edge'; label: string }>;+ message?: string;+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 769270de..b40a357e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -13,6 +13,9 @@ overrides:undici@>=8.0.0 <8.10.2: 8.10.2find-my-way@<=9.6.0: 9.7.0postcss@<=8.5.17: 8.5.18+ proxy-addr@<2.0.8: 2.0.8+ source-map-js@<1.2.2: 1.2.2+ tinypool@<2.1.2: 2.1.2brace-expansion@<1.1.20: 1.1.20brace-expansion@>=2.0.0 <2.1.6: 2.1.6brace-expansion@>=4.0.0 <5.0.11: 5.0.11@@ -52,8 +55,8 @@ importers:specifier: 2.2.5version: 2.2.5'@modelcontextprotocol/sdk':- specifier: 1.29.0- version: 1.29.0([email protected])+ specifier: 1.31.0+ version: 1.31.0([email protected])'@opencreator/config':specifier: workspace:*version: link:../../packages/config@@ -97,8 +100,8 @@ importers:specifier: ^0.20.2version: 0.20.2sharp:- specifier: 0.35.4- version: 0.35.4(@types/[email protected])+ specifier: 0.35.5+ version: 0.35.5(@types/[email protected])toml:specifier: 4.2.0version: 4.2.0@@ -171,8 +174,8 @@ importers:specifier: 13.0.2version: 13.0.2sharp:- specifier: 0.35.4- version: 0.35.4(@types/[email protected])+ specifier: 0.35.5+ version: 0.35.5(@types/[email protected])typescript:specifier: ^5.7.3version: 5.9.3@@ -1056,160 +1059,144 @@ packages:resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}engines: {node: '>=18'}- '@img/[email protected]':- resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}engines: {node: '>=20.9.0'}cpu: [x64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}engines: {node: '>=20.9.0'}os: [freebsd]- '@img/[email protected]':- resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}cpu: [arm64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}cpu: [x64]os: [darwin]- '@img/[email protected]':- resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}cpu: [arm64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}cpu: [arm]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}cpu: [ppc64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}cpu: [riscv64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==}+ '@img/[email protected]':+ resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}cpu: [s390x]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}cpu: [x64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}cpu: [arm64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}cpu: [x64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}engines: {node: '>=20.9.0'}cpu: [arm]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}engines: {node: '>=20.9.0'}cpu: [ppc64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}engines: {node: '>=20.9.0'}cpu: [riscv64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==}+ '@img/[email protected]':+ resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}engines: {node: '>=20.9.0'}cpu: [s390x]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [glibc]- '@img/[email protected]':- resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [musl]- '@img/[email protected]':- resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}engines: {node: '>=20.9.0'}- '@img/[email protected]':- resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==}+ '@img/[email protected]':+ resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}engines: {node: '>=20.9.0'}cpu: [wasm32]- '@img/[email protected]':- resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [win32]- '@img/[email protected]':- resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==}+ '@img/[email protected]':+ resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}engines: {node: ^20.9.0}cpu: [ia32]os: [win32]- '@img/[email protected]':- resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==}+ '@img/[email protected]':+ resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}engines: {node: '>=20.9.0'}cpu: [x64]os: [win32]@@ -1293,8 +1280,8 @@ packages:peerDependencies:mediabunny: ^1.0.0- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==}engines: {node: '>=18'}peerDependencies:'@cfworker/json-schema': ^4.1.1@@ -1386,25 +1373,21 @@ packages:resolution: {integrity: sha512-HeV247O9dwhSfXFYoA7Dd0zPmyn2grbrIhaYs2MJZxO6IHmEUk0gm9/drWyjDHy4e2WCg98uSlcycNOmWtG5ng==}cpu: [arm64]os: [linux]- libc: [glibc]'@remotion/[email protected]':resolution: {integrity: sha512-7EGy2MtQch3yLzwxvWncz/3rmXOWQkWigCDL37I90aHhlf8JgrMZXo8dUtIoD0LP/zHWtFNBcJmgg9Ej+bHshA==}cpu: [arm64]os: [linux]- libc: [musl]'@remotion/[email protected]':resolution: {integrity: sha512-X5Gzod9Q8sTtzjc+hIYKw6PMaB3tY0ADx68j2z+Zm8nJanmkzLZEDyZvlMexmE4nkb7IdOkHzYGm9NpynbMH2A==}cpu: [x64]os: [linux]- libc: [glibc]'@remotion/[email protected]':resolution: {integrity: sha512-REyhvrjGYfFTxGaaRDP31zANM744JI7pKXCgTqXHZBCe8mCZjxZCxmwt9pNL2lJsQ+qLr9zai488Bbj/PUuB6g==}cpu: [x64]os: [linux]- libc: [musl]'@remotion/[email protected]':resolution: {integrity: sha512-J69HIENHpH1m8I85kTe111viqB5AGgKJdTCSKp4mGBxM95IL4nydzrYxVd91BvWjanQfVVq1C3voaF8YLwkT7A==}@@ -1498,79 +1481,66 @@ packages:resolution: {integrity: sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==}cpu: [arm]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==}cpu: [arm]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==}cpu: [arm64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==}cpu: [arm64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==}cpu: [loong64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==}cpu: [loong64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==}cpu: [ppc64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==}cpu: [ppc64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==}cpu: [riscv64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==}cpu: [riscv64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==}cpu: [s390x]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==}cpu: [x64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==}cpu: [x64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==}@@ -1616,25 +1586,21 @@ packages:resolution: {integrity: sha512-eQfcsaxhFrv5FmtaA7+O1F9/2yFDNIoPZzV/ZvqvFz5bBXVc4FAm/1fVpBg8Po/kX1h0chBc7Xkpry3cabFW8w==}cpu: [arm64]os: [linux]- libc: [glibc]'@rspack/[email protected]':resolution: {integrity: sha512-DfQXKiyPIl7i1yECHy4eAkSmlUzzsSAbOjgMuKn7pudsWf483jg0UUYutNgXSlBjc/QSUp7906Cg8oty9OfwPA==}cpu: [arm64]os: [linux]- libc: [musl]'@rspack/[email protected]':resolution: {integrity: sha512-NdA+2X3lk2GGrMMnTGyYTzM3pn+zNjaqXqlgKmFBXvjfZqzSsKq3pdD1KHZCd5QHN+Fwvoszj0JFsquEVhE1og==}cpu: [x64]os: [linux]- libc: [glibc]'@rspack/[email protected]':resolution: {integrity: sha512-rEy6MHKob02t/77YNgr6dREyJ0e0tv1X6Xsg8Z5E7rPXead06zefUbfazj4RELYySWnM38ovZyJAkPx/gOn3VA==}cpu: [x64]os: [linux]- libc: [musl]'@rspack/[email protected]':resolution: {integrity: sha512-YupOrz0daSG+YBbCIgpDgzfMM38YpChv+afZpaxx5Ml7xPeAZIIdgWmLHnQ2rts73N2M1NspAiBwV00Xx0N4Vg==}@@ -3433,8 +3399,8 @@ packages:resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}- resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}+ resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}engines: {node: '>= 0.10'}@@ -3689,8 +3655,8 @@ packages:resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}- resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==}+ resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}engines: {node: '>=20.9.0'}peerDependencies:'@types/node': '*'@@ -3741,8 +3707,8 @@ packages:resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}- resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}engines: {node: '>=0.10.0'}@@ -3927,9 +3893,9 @@ packages:resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}engines: {node: '>=12.0.0'}- resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}- engines: {node: ^18.0.0 || >=20.0.0}+ resolution: {integrity: sha512-9YodfrxS9g9IbFr/KOjE5bAeJ0p61n3bW6mqvy0jtoeKd1kTW1Cxm0oulm6KX2lyM9Gl6WIe8nEbY7LWv5ZJww==}+ engines: {node: ^20.0.0 || >=22.0.0}resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}@@ -4922,108 +4888,108 @@ snapshots:'@img/[email protected]': {}- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-darwin-arm64': 1.3.3+ '@img/sharp-libvips-darwin-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-darwin-x64': 1.3.3+ '@img/sharp-libvips-darwin-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:- '@img/sharp-wasm32': 0.35.4+ '@img/sharp-wasm32': 0.35.5optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-arm64': 1.3.3+ '@img/sharp-libvips-linux-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-arm': 1.3.3+ '@img/sharp-libvips-linux-arm': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-ppc64': 1.3.3+ '@img/sharp-libvips-linux-ppc64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-riscv64': 1.3.3+ '@img/sharp-libvips-linux-riscv64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-s390x': 1.3.3+ '@img/sharp-libvips-linux-s390x': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linux-x64': 1.3.3+ '@img/sharp-libvips-linux-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':optionalDependencies:- '@img/sharp-libvips-linuxmusl-x64': 1.3.3+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:'@emnapi/runtime': 1.11.3optional: true- '@img/[email protected]':+ '@img/[email protected]':dependencies:- '@img/sharp-wasm32': 0.35.4+ '@img/sharp-wasm32': 0.35.5optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true- '@img/[email protected]':+ '@img/[email protected]':optional: true'@isaacs/[email protected]':@@ -5132,7 +5098,7 @@ snapshots:dependencies:mediabunny: 1.45.0- '@modelcontextprotocol/[email protected]([email protected])':+ '@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 1.19.14([email protected])ajv: 8.20.0@@ -6648,7 +6614,7 @@ snapshots:on-finished: 2.4.1once: 1.4.0parseurl: 1.3.3- proxy-addr: 2.0.7+ proxy-addr: 2.0.8qs: 6.15.3range-parser: 1.3.0router: 2.2.0@@ -7476,7 +7442,7 @@ snapshots:dependencies:nanoid: 3.3.18picocolors: 1.1.1- source-map-js: 1.2.1+ source-map-js: 1.2.2dependencies:@@ -7527,7 +7493,7 @@ snapshots:retry: 0.12.0signal-exit: 3.0.7dependencies:forwarded: 0.2.0ipaddr.js: 1.9.1@@ -7811,37 +7777,37 @@ snapshots:- [email protected](@types/[email protected]):+ [email protected](@types/[email protected]):dependencies:'@img/colour': 1.1.0detect-libc: 2.1.2semver: 7.8.5optionalDependencies:- '@img/sharp-darwin-arm64': 0.35.4- '@img/sharp-darwin-x64': 0.35.4- '@img/sharp-freebsd-wasm32': 0.35.4- '@img/sharp-libvips-darwin-arm64': 1.3.3- '@img/sharp-libvips-darwin-x64': 1.3.3- '@img/sharp-libvips-linux-arm': 1.3.3- '@img/sharp-libvips-linux-arm64': 1.3.3- '@img/sharp-libvips-linux-ppc64': 1.3.3- '@img/sharp-libvips-linux-riscv64': 1.3.3- '@img/sharp-libvips-linux-s390x': 1.3.3- '@img/sharp-libvips-linux-x64': 1.3.3- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3- '@img/sharp-libvips-linuxmusl-x64': 1.3.3- '@img/sharp-linux-arm': 0.35.4- '@img/sharp-linux-arm64': 0.35.4- '@img/sharp-linux-ppc64': 0.35.4- '@img/sharp-linux-riscv64': 0.35.4- '@img/sharp-linux-s390x': 0.35.4- '@img/sharp-linux-x64': 0.35.4- '@img/sharp-linuxmusl-arm64': 0.35.4- '@img/sharp-linuxmusl-x64': 0.35.4- '@img/sharp-webcontainers-wasm32': 0.35.4- '@img/sharp-win32-arm64': 0.35.4- '@img/sharp-win32-ia32': 0.35.4- '@img/sharp-win32-x64': 0.35.4+ '@img/sharp-darwin-arm64': 0.35.5+ '@img/sharp-darwin-x64': 0.35.5+ '@img/sharp-freebsd-wasm32': 0.35.5+ '@img/sharp-libvips-darwin-arm64': 1.3.4+ '@img/sharp-libvips-darwin-x64': 1.3.4+ '@img/sharp-libvips-linux-arm': 1.3.4+ '@img/sharp-libvips-linux-arm64': 1.3.4+ '@img/sharp-libvips-linux-ppc64': 1.3.4+ '@img/sharp-libvips-linux-riscv64': 1.3.4+ '@img/sharp-libvips-linux-s390x': 1.3.4+ '@img/sharp-libvips-linux-x64': 1.3.4+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4+ '@img/sharp-linux-arm': 0.35.5+ '@img/sharp-linux-arm64': 0.35.5+ '@img/sharp-linux-ppc64': 0.35.5+ '@img/sharp-linux-riscv64': 0.35.5+ '@img/sharp-linux-s390x': 0.35.5+ '@img/sharp-linux-x64': 0.35.5+ '@img/sharp-linuxmusl-arm64': 0.35.5+ '@img/sharp-linuxmusl-x64': 0.35.5+ '@img/sharp-webcontainers-wasm32': 0.35.5+ '@img/sharp-win32-arm64': 0.35.5+ '@img/sharp-win32-ia32': 0.35.5+ '@img/sharp-win32-x64': 0.35.5'@types/node': 22.20.0@@ -7898,7 +7864,7 @@ snapshots:dependencies:atomic-sleep: 1.0.0- [email protected]: {}+ [email protected]: {}dependencies:@@ -8052,7 +8018,7 @@ snapshots:fdir: 6.5.0([email protected])picomatch: 4.0.5- [email protected]: {}+ [email protected]: {}@@ -8257,7 +8223,7 @@ snapshots:tinybench: 2.9.0tinyexec: 0.3.2tinyglobby: 0.2.17- tinypool: 1.1.1+ tinypool: 2.1.2tinyrainbow: 2.0.0vite: 6.4.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])@@ -8300,7 +8266,7 @@ snapshots:tinybench: 2.9.0tinyexec: 0.3.2tinyglobby: 0.2.17- tinypool: 1.1.1+ tinypool: 2.1.2tinyrainbow: 2.0.0vite: 6.4.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])diff --git a/runtime/krillinai/internal/pipeline/subtitle.go b/runtime/krillinai/internal/pipeline/subtitle.goindex 68a41090..744bb9c0 100644--- a/runtime/krillinai/internal/pipeline/subtitle.go+++ b/runtime/krillinai/internal/pipeline/subtitle.go@@ -94,7 +94,7 @@ func GenerateSubtitles(ctx context.Context, svc StageService, req SubtitleRequesreportSubtitleProgress(req, "processing_platform_captions", 25, "正在解析平台字幕")youtubeReq.VttFile = vttFile_, err = svc.ProcessYouTubeSubtitle(ctx, youtubeReq)- if err != nil {+ if err != nil && !errors.Is(err, service.ErrYouTubeCaptionInvalid) {return failSubtitleStage(req, manifest, ErrorKindRetryable, "platform_caption_processing_failed", err)}}@@ -119,10 +119,19 @@ func GenerateSubtitles(ctx context.Context, svc StageService, req SubtitleRequesreturn failSubtitleStage(req, manifest, ErrorKindRetryable, "platform_caption_access_failed", err)}if req.CaptionSource != CaptionSourceAny {- return failSubtitleStage(req, manifest, ErrorKindRetryable, "platform_caption_failed", err)+ code := "platform_caption_failed"+ if errors.Is(err, service.ErrYouTubeCaptionInvalid) {+ code = "platform_caption_invalid"+ }+ return failSubtitleStage(req, manifest, ErrorKindRetryable, code, err)}platformCaptionErr = err- manifest.Warnings = append(manifest.Warnings, "平台字幕不可用,回退到转录")+ fallbackMessage := "未找到可用的平台字幕,已自动切换到语音转录"+ if errors.Is(err, service.ErrYouTubeCaptionInvalid) {+ fallbackMessage = "平台字幕解析失败,已自动切换到语音转录"+ }+ manifest.Warnings = append(manifest.Warnings, fallbackMessage)+ reportSubtitleProgress(req, "fallback_to_transcription", 25, fallbackMessage)stepParam.VttSwitch = falseif req.PrepareVideo {stepParam.EmbedSubtitleVideoType = "all"diff --git a/runtime/krillinai/internal/pipeline/subtitle_test.go b/runtime/krillinai/internal/pipeline/subtitle_test.goindex 638566bd..2aaf9721 100644--- a/runtime/krillinai/internal/pipeline/subtitle_test.go+++ b/runtime/krillinai/internal/pipeline/subtitle_test.go@@ -601,6 +601,65 @@ func TestPlatformTranslationFailureDoesNotDownloadOrTranscribe(t *testing.T) {}}+func TestUnusablePlatformCaptionsFallBackToAudio(t *testing.T) {+ fake := &fakeStageService{processErr: fmt.Errorf("%w: no usable VTT text", service.ErrYouTubeCaptionInvalid)}+ var messages []string+ response, err := GenerateSubtitles(context.Background(), fake, SubtitleRequest{+ Input: "https://www.youtube.com/watch?v=m5yrQMnc_jQ", Workdir: t.TempDir(), TaskID: "invalid-vtt",+ OriginLang: "en", TargetLang: "zh_cn", CaptionSource: CaptionSourceAny,+ ReportProgress: func(phase string, _ int, message string) {+ if phase == "fallback_to_transcription" {+ messages = append(messages, message)+ }+ },+ })+ if err != nil || !response.OK {+ t.Fatalf("response = %+v, error = %v", response, err)+ }+ if !reflect.DeepEqual(fake.calls, []string{"download-youtube", "process-youtube", "prepare", "audio"}) {+ t.Fatalf("calls = %v, want caption processing followed by audio transcription", fake.calls)+ }+ if !reflect.DeepEqual(fake.prepareVTT, []bool{false}) {+ t.Fatalf("prepare VttSwitch values = %v, want [false]", fake.prepareVTT)+ }+ manifest, err := LoadManifest(response.Workdir)+ if err != nil {+ t.Fatal(err)+ }+ if manifest.CaptionSource != "whisper" || !reflect.DeepEqual(manifest.Warnings, messages) || len(messages) != 1 {+ t.Fatalf("manifest = %+v, fallback messages = %v", manifest, messages)+ }+}++func TestUnusablePlatformCaptionsSignalDeferredTranscription(t *testing.T) {+ fake := &fakeStageService{processErr: service.ErrYouTubeCaptionInvalid}+ response, err := GenerateSubtitles(context.Background(), fake, SubtitleRequest{+ Input: "https://www.youtube.com/watch?v=abc", Workdir: t.TempDir(), TaskID: "invalid-vtt",+ CaptionSource: CaptionSourcePlatform,+ })+ if err == nil || response.Error.Code != "platform_caption_invalid" {+ t.Fatalf("response = %+v, error = %v", response, err)+ }+ if !reflect.DeepEqual(fake.calls, []string{"download-youtube", "process-youtube"}) {+ t.Fatalf("calls = %v, want platform-only attempt", fake.calls)+ }+}++func TestUnusableCaptionsPreserveAudioFallbackFailure(t *testing.T) {+ fake := &fakeStageService{+ processErr: fmt.Errorf("%w: invalid VTT timestamps", service.ErrYouTubeCaptionInvalid),+ audioErr: errors.New("transcription unavailable"),+ }+ response, err := GenerateSubtitles(context.Background(), fake, SubtitleRequest{+ Input: "https://www.youtube.com/watch?v=abc", Workdir: t.TempDir(), TaskID: "fallback-failed",+ CaptionSource: CaptionSourceAny,+ })+ if err == nil || response.Error.Code != "audio_transcription_failed" ||+ !strings.Contains(err.Error(), "invalid VTT timestamps") || !strings.Contains(err.Error(), "transcription unavailable") {+ t.Fatalf("response = %+v, error = %v", response, err)+ }+}+func TestPlatformAccessFailureDoesNotTriggerWhisperDownload(t *testing.T) {for _, captionSource := range []CaptionSource{CaptionSourceAny, CaptionSourcePlatform} {t.Run(string(captionSource), func(testCase *testing.T) {diff --git a/runtime/krillinai/internal/service/link2file.go b/runtime/krillinai/internal/service/link2file.goindex 28fe36bb..514553db 100644--- a/runtime/krillinai/internal/service/link2file.go+++ b/runtime/krillinai/internal/service/link2file.go@@ -13,7 +13,9 @@ import ("os""os/exec""regexp"+ "slices""strings"+ "time""go.uber.org/zap")@@ -72,8 +74,7 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStif storage.FfmpegPath != "ffmpeg" {cmdArgs = append(cmdArgs, "--ffmpeg-location", storage.FfmpegPath)}- cmd := storage.YtdlpCommand(cmdArgs...)- output, err = cmd.CombinedOutput()+ output, err = downloadYouTubeMedia(ctx, cmdArgs)if err != nil {log.GetLogger().Error("linkToFile download audio yt-dlp error", zap.Any("step param", stepParam), zap.String("output", string(output)), zap.Error(err))return fmt.Errorf("linkToFile download audio yt-dlp error: %w: %s", err, compactCommandOutput(output))@@ -137,8 +138,11 @@ func (s Service) linkToFile(ctx context.Context, stepParam *types.SubtitleTaskStif storage.FfmpegPath != "ffmpeg" {cmdArgs = append(cmdArgs, "--ffmpeg-location", storage.FfmpegPath)}- cmd := storage.YtdlpCommand(cmdArgs...)- output, err = cmd.CombinedOutput()+ if util.IsYouTubeURL(stepParam.Link) {+ output, err = downloadYouTubeMedia(ctx, cmdArgs)+ } else {+ output, err = storage.YtdlpCommandContext(ctx, cmdArgs...).CombinedOutput()+ }if err != nil {log.GetLogger().Error("linkToFile download video yt-dlp error", zap.Any("step param", stepParam), zap.String("output", string(output)), zap.Error(err))return fmt.Errorf("linkToFile download video yt-dlp error: %w: %s", err, compactCommandOutput(output))@@ -201,8 +205,62 @@ func resolveLocalMediaInput(input string) (string, bool) {func compactCommandOutput(output []byte) string {const maximum = 1200value := strings.TrimSpace(string(output))+ var fatalLines []string+ for _, line := range strings.Split(value, "\n") {+ if strings.HasPrefix(strings.TrimSpace(line), "ERROR:") {+ fatalLines = append(fatalLines, strings.TrimSpace(line))+ }+ }+ if len(fatalLines) > 0 {+ value = strings.Join(fatalLines, "\n") + "\n" + value+ return value[:min(len(value), maximum)]+ }if len(value) <= maximum {return value}return value[len(value)-maximum:]}++func downloadYouTubeMedia(ctx context.Context, args []string) ([]byte, error) {+ const maxAttempts = 3+ var output []byte+ var err error+ for attempt := 1; attempt <= maxAttempts; attempt++ {+ if err := ctx.Err(); err != nil {+ return output, err+ }+ commandArgs := args+ if attempt == maxAttempts {+ // HLS can remain available when the direct audio format is rejected.+ commandArgs = youtubeAudioFallbackArgs(args)+ }+ output, err = storage.YtdlpCommandContext(ctx, commandArgs...).CombinedOutput()+ if err == nil || !strings.Contains(string(output), "HTTP Error 403") || attempt == maxAttempts {+ return output, err+ }+ // Re-run extraction to replace a rejected or expired signed media URL.+ log.GetLogger().Warn("YouTube media download returned 403; refreshing media URL", zap.Int("attempt", attempt))+ timer := time.NewTimer(time.Duration(attempt) * time.Second)+ select {+ case <-ctx.Done():+ timer.Stop()+ return output, ctx.Err()+ case <-timer.C:+ }+ }+ return output, err+}++func youtubeAudioFallbackArgs(args []string) []string {+ if !slices.Contains(args, "--extract-audio") {+ return args+ }+ fallback := append([]string{}, args...)+ for index, arg := range fallback {+ if (arg == "-f" || arg == "--format") && index+1 < len(fallback) {+ fallback[index+1] = "bestaudio[protocol^=m3u8]/" + fallback[index+1]+ return append(fallback, "--concurrent-fragments", "4")+ }+ }+ return args+}diff --git a/runtime/krillinai/internal/service/link2file_test.go b/runtime/krillinai/internal/service/link2file_test.goindex 6359860c..dc1d41e9 100644--- a/runtime/krillinai/internal/service/link2file_test.go+++ b/runtime/krillinai/internal/service/link2file_test.go@@ -2,9 +2,12 @@ package serviceimport ("context"+ "errors"+ "fmt""krillin-ai/config""krillin-ai/internal/storage""krillin-ai/internal/types"+ "krillin-ai/log""os""path/filepath""runtime"@@ -12,6 +15,68 @@ import ("testing")+func TestYouTubeMediaRefreshesRejectedURLs(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell downloader fixture requires POSIX")+ }+ log.InitLogger()+ originalPath, originalPrefix := storage.YtdlpPath, storage.YtdlpPrefixArgs+ t.Cleanup(func() { storage.YtdlpPath, storage.YtdlpPrefixArgs = originalPath, originalPrefix })+ for _, test := range []struct {+ name string+ failures int+ message string+ attempts int+ audio bool+ }{+ {"refresh-403", 1, "ERROR: unable to download video data: HTTP Error 403: Forbidden", 2, false},+ {"limit-403", 9, "ERROR: HTTP Error 403: Forbidden", 3, false},+ {"no-bot-retry", 9, "ERROR: Sign in to confirm you are not a bot", 1, false},+ {"hls-audio-fallback", 2, "ERROR: HTTP Error 403: Forbidden", 3, true},+ } {+ t.Run(test.name, func(t *testing.T) {+ dir := t.TempDir()+ counter := filepath.Join(dir, "attempts")+ downloader := filepath.Join(dir, "yt-dlp")+ t.Setenv("YTDLP_MEDIA_COUNTER", counter)+ t.Setenv("YTDLP_MEDIA_ERROR", test.message)+ fixture := fmt.Sprintf("#!/bin/sh\nn=0\nif [ -f \"$YTDLP_MEDIA_COUNTER\" ]; then n=$(cat \"$YTDLP_MEDIA_COUNTER\"); fi\nn=$((n+1))\nprintf '%%s' \"$n\" > \"$YTDLP_MEDIA_COUNTER\"\nif [ \"$n\" -le %d ]; then printf '%%s\\n' \"$YTDLP_MEDIA_ERROR\" >&2; exit 1; fi\nprintf 'audio ready\\n'\nprintf '%%s\\n' \"$@\"\n", test.failures)+ if err := os.WriteFile(downloader, []byte(fixture), 0700); err != nil {+ t.Fatal(err)+ }+ storage.YtdlpPath, storage.YtdlpPrefixArgs = downloader, nil+ args := []string{"https://www.youtube.com/watch?v=demo"}+ if test.audio {+ args = append(args, "--extract-audio", "-f", "bestaudio[ext=m4a]/bestaudio")+ }+ output, err := downloadYouTubeMedia(context.Background(), args)+ if (err == nil) != (test.failures < test.attempts) {+ t.Fatalf("error = %v", err)+ }+ count, readErr := os.ReadFile(counter)+ if readErr != nil || string(count) != fmt.Sprint(test.attempts) {+ t.Fatalf("attempts = %s, error = %v", count, readErr)+ }+ if test.audio && !strings.Contains(string(output), "bestaudio[protocol^=m3u8]/bestaudio[ext=m4a]/bestaudio\n--concurrent-fragments\n4") {+ t.Fatalf("final audio retry did not select HLS: %s", output)+ }+ })+ }+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if _, err := downloadYouTubeMedia(ctx, nil); !errors.Is(err, context.Canceled) {+ t.Fatalf("error = %v, want cancellation", err)+ }+}++func TestCompactCommandOutputPrioritizesFatalDownloadError(t *testing.T) {+ output := "[youtube] Downloading webpage\nWARNING: " + strings.Repeat("runtime warning ", 100) + "\nERROR: unable to download video data: HTTP Error 403: Forbidden\n"+ message := compactCommandOutput([]byte(output))+ if len(message) > 1200 || !strings.HasPrefix(message, "ERROR: unable to download video data: HTTP Error 403: Forbidden") {+ t.Fatalf("fatal download error was lost: %s", message)+ }+}+func TestBilibiliDownloadsOnlySelectedPart(testRunner *testing.T) {if runtime.GOOS == "windows" {testRunner.Skip("shell downloader fixture requires POSIX")diff --git a/runtime/krillinai/internal/service/youtube_cookies.go b/runtime/krillinai/internal/service/youtube_cookies.goindex d5942120..536c369c 100644--- a/runtime/krillinai/internal/service/youtube_cookies.go+++ b/runtime/krillinai/internal/service/youtube_cookies.go@@ -42,7 +42,7 @@ func isNetscapeCookiesFile(cookiesPath string) bool {continue}line = strings.TrimPrefix(line, "\ufeff")- if strings.HasPrefix(line, "# Netscape HTTP Cookie File") {+ if strings.HasPrefix(line, "# Netscape HTTP Cookie File") || strings.HasPrefix(line, "# HTTP Cookie File") {return true}if logger := log.GetLogger(); logger != nil {diff --git a/runtime/krillinai/internal/service/youtube_cookies_test.go b/runtime/krillinai/internal/service/youtube_cookies_test.goindex 176b02cf..efcf7a9f 100644--- a/runtime/krillinai/internal/service/youtube_cookies_test.go+++ b/runtime/krillinai/internal/service/youtube_cookies_test.go@@ -59,3 +59,13 @@ func TestAppendCookiesArgsUsesNetscapeCookieFile(t *testing.T) {t.Fatalf("appendCookiesArgs() = %v, want %v", args, want)}}++func TestAppendCookiesArgsUsesHTTPCookieFile(t *testing.T) {+ path := filepath.Join(t.TempDir(), "cookies.txt")+ if err := os.WriteFile(path, []byte("# HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tfixture\n"), 0600); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(appendCookiesArgs(nil, path), []string{"--cookies", path}) {+ t.Fatal("expected cookies exported with the alternative official header to be accepted")+ }+}diff --git a/runtime/krillinai/internal/service/youtube_subtitle.go b/runtime/krillinai/internal/service/youtube_subtitle.goindex 14bcd262..2337adbf 100644--- a/runtime/krillinai/internal/service/youtube_subtitle.go+++ b/runtime/krillinai/internal/service/youtube_subtitle.go@@ -27,6 +27,7 @@ import ()var ErrYouTubeCaptionAccess = errors.New("platform caption access failed")+var ErrYouTubeCaptionInvalid = errors.New("platform caption content is unusable")// VttWord 表示VTT文件中的一个单词及其时间戳信息type VttWord struct {@@ -512,7 +513,7 @@ func (s *YouTubeSubtitleService) findDownloadedSubtitleFile(taskBasePath, langua// 处理YouTube字幕文件,转换为标准格式并进行翻译func (s *YouTubeSubtitleService) processYouTubeSubtitle(ctx context.Context, req *YoutubeSubtitleReq) (string, error) {if req.VttFile == "" {- return "", fmt.Errorf("processYouTubeSubtitle: no original subtitle file found")+ return "", fmt.Errorf("%w: no original subtitle file found", ErrYouTubeCaptionInvalid)}log.GetLogger().Info("processYouTubeSubtitle start",@@ -536,11 +537,11 @@ func (s *YouTubeSubtitleService) processYouTubeSubtitle(ctx context.Context, reqvttWords, err := s.ExtractWordsFromVtt(vttFilePath)if err != nil {- return "", fmt.Errorf("failed to extract VTT words: %w", err)+ return "", fmt.Errorf("%w: failed to extract VTT words: %w", ErrYouTubeCaptionInvalid, err)}log.GetLogger().Info("提取VTT单词完成", zap.Int("单词数", len(vttWords)))if len(vttWords) == 0 {- return "", fmt.Errorf("platform captions contained no usable text after filtering music, sound annotations and punctuation")+ return "", fmt.Errorf("%w: platform captions contained no usable text after filtering music, sound annotations and punctuation", ErrYouTubeCaptionInvalid)}// 更新进度:提取完成@@ -556,7 +557,7 @@ func (s *YouTubeSubtitleService) processYouTubeSubtitle(ctx context.Context, reqsentences = s.groupWordsIntoSentences(vttWords)}if len(sentences) == 0 {- return "", fmt.Errorf("no sentences formed from VTT words")+ return "", fmt.Errorf("%w: no sentences formed from VTT words", ErrYouTubeCaptionInvalid)}log.GetLogger().Info("组织句子完成", zap.Int("句子数", len(sentences)))diff --git a/runtime/krillinai/internal/service/youtube_subtitle_test.go b/runtime/krillinai/internal/service/youtube_subtitle_test.goindex 55263999..aadbefbd 100644--- a/runtime/krillinai/internal/service/youtube_subtitle_test.go+++ b/runtime/krillinai/internal/service/youtube_subtitle_test.go@@ -2,6 +2,7 @@ package serviceimport ("context"+ "errors""krillin-ai/config""krillin-ai/internal/deps""krillin-ai/internal/storage"@@ -15,6 +16,36 @@ import ("testing")+func TestProcessYouTubeSubtitleClassifiesUnusableVTT(t *testing.T) {+ log.InitLogger()+ for name, content := range map[string]string{+ "empty": "WEBVTT\n\n",+ "music-only": "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n[Music]\n\n",+ "block-text": "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:11.840 --> 00:00:17.360\nuh these efforts by lawmakers to pass some form of \nAI regulation. There have been more than a hundred\n\n",+ "malformed": "WEBVTT\n\ninvalid --> timestamps\nNormal speech\n\n",+ } {+ t.Run(name, func(t *testing.T) {+ root := t.TempDir()+ path := filepath.Join(root, "captions.vtt")+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ _, err := (&YouTubeSubtitleService{}).processYouTubeSubtitle(context.Background(), &YoutubeSubtitleReq{+ TaskBasePath: root, VttFile: path, SourceOnly: true,+ })+ if !errors.Is(err, ErrYouTubeCaptionInvalid) {+ t.Fatalf("error = %v, want unusable caption classification", err)+ }+ })+ }+ _, err := (&YouTubeSubtitleService{}).processYouTubeSubtitle(context.Background(), &YoutubeSubtitleReq{+ VttFile: filepath.Join(t.TempDir(), "missing.vtt"),+ })+ if !errors.Is(err, ErrYouTubeCaptionInvalid) {+ t.Fatalf("missing VTT error = %v, want unusable caption classification", err)+ }+}+func TestSelectYouTubeSubtitleTrackPrefersManualOriginLanguage(t *testing.T) {metadata := youtubeSubtitleMetadata{Language: "en",