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: integrate official gateway accounts and media services
Leggettd785d804979f
diff --git a/.gitignore b/.gitignoreindex 1cecc269..43e2d2fe 100644--- a/.gitignore+++ b/.gitignore@@ -7,6 +7,7 @@ apps/desktop/.pack/apps/desktop/.cache/apps/desktop/release/.runtime/+.local/.codegraph/coverage/*.logdiff --git a/README.md b/README.mdindex e17d99ef..940591dc 100644--- a/README.md+++ b/README.md@@ -478,6 +478,20 @@ Open **Settings → AI Services** to configure the model, transcription, voice,Credentials are saved through the local Runtime's system credential storage and should never be committed to the repository. Some local or system-backed providers, such as Edge TTS, do not require an API Key.+### Account and Subscriptions++The personal center displays your account, confirmed subscription and available+credits. Sign-in opens `https://www.open-creator.ai/device` in your browser. Sign+in on the website and approve the device; the local Daemon obtains its own+session. The browser and client share an account but keep independent sessions.++Subscription plans are selected inside OpenCreator. Purchasing opens Stripe+Checkout, and managing a subscription opens Stripe Billing Portal. Client billing+returns use the website's `/billing/return` page without requiring a website+session. OpenCreator refreshes benefits from Gateway after verified Stripe+notifications. The website's `/pricing` and `/account` pages provide another+purchase entry to the same subscription backend.+### Third-party Runtime ComponentsOpen **Settings → Third-party Components** to inspect the yt-dlp nightly version currently in use, the version bundled with OpenCreator, its source, and the latest available release. OpenCreator checks for updates every seven days but never installs them automatically. Updates require an explicit user action, and the current working version remains available if downloading, verification, or installation fails.@@ -491,6 +505,7 @@ Most users do not need environment variables. Use these when you need isolated d| Environment variable | Default | Purpose || --- | --- | --- || `OPENCREATOR_DATA_DIR` | `.runtime` | OpenCreator database, Runs, attachments, and managed workspaces |+| `OPENCREATOR_GATEWAY_ORIGIN` | `https://www.open-creator.ai` | Gateway for account sign-in, subscriptions, credits, and official model services; override for a local Gateway || `OPENCREATOR_CODEX_BIN` | `codex` | Path to the Codex CLI executable || `CODEX_HOME` | `~/.codex` | Source of truth for Codex sessions, configuration, Skills, MCP, and Profiles || `OPENCREATOR_DEFAULT_CWD` | Current working directory | Default daemon working directory |diff --git a/apps/daemon/src/api/routes.creator-services.ts b/apps/daemon/src/api/routes.creator-services.tsindex 0968a7c8..5297b2a2 100644--- a/apps/daemon/src/api/routes.creator-services.ts+++ b/apps/daemon/src/api/routes.creator-services.ts@@ -21,6 +21,7 @@ import {type KrillinTtsService} from '../creator/krillin/tts-service.js';import { apiError } from './errors.js';+import { gatewayCreatorBinding } from '../gateway/creator-service-source.js';export async function registerCreatorServicesRoutes(server: FastifyInstance,@@ -30,8 +31,34 @@ export async function registerCreatorServicesRoutes(ttsService?: Pick<KrillinTtsService, 'listVoices' | 'preview'>,onConfigurationChanged?: () => Promise<void> | void,readCodexImageStatus?: () => Promise<CodexImageStatus>,- readCodexModelStatus?: () => Promise<CodexProviderConfig>+ readCodexModelStatus?: () => Promise<CodexProviderConfig>,+ networkStore: CreatorServicesConfigStore = store): Promise<void> {+ server.get('/creator-services/network', async (_request, reply) => {+ reply.header('Cache-Control', 'no-store');+ try { return { proxy: (await networkStore.read()).proxy }; }+ catch (error) { return sendStoreError(reply, error); }+ });+ server.patch<{ Body: unknown }>('/creator-services/network', async (request, reply) => {+ const body = request.body as { proxy?: unknown } | null;+ const proxy = typeof body?.proxy === 'string' ? body.proxy.trim() : undefined;+ let valid = proxy !== undefined && proxy.length <= 2048;+ if (proxy) {+ try {+ const url = new URL(proxy);+ valid = valid && ['http:', 'https:'].includes(url.protocol) && !!url.hostname+ && !url.search && !url.hash && (url.pathname === '/' || url.pathname === '');+ } catch { valid = false; }+ }+ if (!valid || !body || Object.keys(body).some(key => key !== 'proxy')) {+ return reply.code(400).send(apiError('VALIDATION_FAILED', 'Enter a valid HTTP or HTTPS proxy URL'));+ }+ try {+ const current = await networkStore.read();+ const saved = await networkStore.write({ ...current, proxy: proxy! });+ return { proxy: saved.proxy };+ } catch (error) { return sendStoreError(reply, error); }+ });server.get('/creator-services/capabilities', async () => readCapabilities());server.get('/creator-services/model/codex/status', async (_request, reply) => {reply.header('Cache-Control', 'no-store');@@ -53,7 +80,14 @@ export async function registerCreatorServicesRoutes(server.get('/creator-services/config', async (_request, reply) => {try {- return presentCreatorServicesConfig(await store.read());+ const config = await store.read();+ if (gatewayCreatorBinding(config)) {+ const result = presentCreatorServicesConfig(config);+ clearOfficialAddresses(result.config);+ result.configuredCredentials = [];+ return result;+ }+ return presentCreatorServicesConfig(config);} catch (error) {return sendStoreError(reply, error);}@@ -73,6 +107,7 @@ export async function registerCreatorServicesRoutes());}const current = await store.read();+ if (networkStore !== store) config.proxy = (await networkStore.read()).proxy;const saved = await store.write(retainCreatorServicesCredentials(config, current));try {await onConfigurationChanged?.();@@ -126,7 +161,9 @@ export async function registerCreatorServicesRoutes(server.delete('/creator-services/config', async (_request, reply) => {try {- return presentCreatorServicesConfig(await store.reset());+ const proxy = networkStore !== store ? (await networkStore.read()).proxy : undefined;+ const reset = await store.reset();+ return presentCreatorServicesConfig(proxy === undefined ? reset : await store.write({ ...reset, proxy }));} catch (error) {return sendStoreError(reply, error);}@@ -185,6 +222,14 @@ export async function registerCreatorServicesRoutes(}}+function clearOfficialAddresses(value: unknown): void {+ if (!value || typeof value !== 'object') return;+ for (const [key, child] of Object.entries(value)) {+ if (key === 'baseUrl' || key === 'apiKey' || key === 'proxy') (value as Record<string, unknown>)[key] = '';+ else clearOfficialAddresses(child);+ }+}+function sendStoreError(reply: FastifyReply, error: unknown) {if (error instanceof CreatorServicesConfigStoreError) {return reply.code(503).send(apiError(error.code, 'Local configuration file is unavailable'));diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.tsindex 1bb1c0f7..648ca89d 100644--- a/apps/daemon/src/api/routes.creator.ts+++ b/apps/daemon/src/api/routes.creator.ts@@ -167,7 +167,12 @@ export async function registerCreatorRoutes(const presetCatalogRoot = options.presetCatalogRoot;server.get('/creator/presets', async request => {const locale = normalizeCreatorPresetLocale(readObject(request.query).locale);- const config = await options.readServicesConfig?.();+ let config: CreatorServicesConfig | undefined;+ try {+ config = await options.readServicesConfig?.();+ } catch {+ // Model details are optional; credentials must not prevent browsing templates.+ }const published = presets.listPublished(locale);let codexImageModel: string | undefined;if (config !== undefined && options.codexImageRuntime !== undefined && published.some(preset => {diff --git a/apps/daemon/src/api/routes.gateway-account.ts b/apps/daemon/src/api/routes.gateway-account.tsnew file mode 100644index 00000000..01665a75--- /dev/null+++ b/apps/daemon/src/api/routes.gateway-account.ts@@ -0,0 +1,40 @@+import type { FastifyInstance } from 'fastify';+import { z } from 'zod';+import { apiError } from './errors.js';+import { GatewayError } from '../gateway/client.js';+import type { GatewayAccountService } from '../gateway/account-service.js';++export async function registerGatewayAccountRoutes(server: FastifyInstance, service: GatewayAccountService) {+ async function respond(work: () => Promise<unknown>, reply: import('fastify').FastifyReply) {+ reply.header('Cache-Control', 'no-store');+ try { return await work(); } catch (error) {+ const cloud = error instanceof GatewayError ? error : new GatewayError('gateway_unavailable');+ const code = cloud.status === 401 ? 'GATEWAY_AUTH_REQUIRED' : cloud.code === 'account_disabled' ? 'GATEWAY_ACCOUNT_DISABLED'+ : cloud.status === 402 ? 'GATEWAY_CREDITS_INSUFFICIENT' : cloud.status === 409 ? 'GATEWAY_REQUEST_CONFLICT'+ : cloud.code === 'services_not_ready' ? 'GATEWAY_SERVICES_NOT_READY' : 'GATEWAY_UNAVAILABLE';+ return reply.code(cloud.status).send(apiError(code, code === 'GATEWAY_REQUEST_CONFLICT' ? '请等待当前任务结束后再切换账户或服务来源' : cloud.message, { gatewayCode: cloud.code }));+ }+ }+ server.get('/gateway/account', (_r, reply) => respond(() => service.readState(), 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);+ const image = await service.readAvatar(query.data.accountId);+ return 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/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));+ server.patch('/gateway/source', (r, reply) => respond(async () => { const value = z.object({ source: z.enum(['manual', 'gateway']) }).strict().safeParse(r.body); if (!value.success) throw new GatewayError('invalid_source', 400); await service.setSource(value.data.source); return service.readState(); }, reply));+ server.get('/gateway/billing', (_r, reply) => respond(() => service.readBalance(), reply));+ server.patch('/gateway/model', (r, reply) => respond(async () => {+ const value = z.object({ modality: z.enum(['text', 'image', 'video', 'speech', 'transcription']), model: z.string().min(1).max(256) }).strict().safeParse(r.body);+ if (!value.success) throw new GatewayError('invalid_model', 400);+ return service.selectModel(value.data.modality, value.data.model);+ }, 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));+ 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/server.ts b/apps/daemon/src/api/server.tsindex 441f44f1..dbac1f85 100644--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@ -235,6 +235,15 @@ import { registerApprovalRoutes } from './routes.approvals.js';import { registerCodexRoutes } from './routes.codex.js';import { registerCleanupRoutes } from './routes.cleanup.js';import { registerCreatorServicesRoutes } from './routes.creator-services.js';+import { registerGatewayAccountRoutes } from './routes.gateway-account.js';+import { createGatewayAccountService } from '../gateway/account-service.js';+import { createGatewayClient, GatewayError, type GatewayClient } from '../gateway/client.js';+import { createGatewayRuntimeBindings } from '../gateway/runtime-bindings.js';+import { createOfficialFetch } from '../gateway/official-fetch.js';+import { createOfficialModelAccess } from '../gateway/model-access.js';+import { createRuntimeSource } from '../gateway/runtime-source.js';+import { createGatewayCreatorSource } from '../gateway/creator-service-source.js';+import { createCodexAppServerHost } from '../codex/app-server-host-2026-07-28.js';import { registerCreatorRoutes } from './routes.creator.js';import { registerCreatorRuntimeRoutes } from './routes.creator-runtime.js';import { registerDiagnosticsRoutes } from './routes.diagnostics.js';@@ -262,6 +271,7 @@ export type BuildServerInput = {dataDir?: string;configFile?: string;credentialsFile?: string;+ gatewayOrigin?: string;runtimeDir?: string;creatorDir?: string;db?: Database.Database;@@ -425,7 +435,7 @@ export async function buildServer(input: BuildServerInput) {| undefined;let appServerRuntimeManager: AppServerRuntimeManager | undefined;let creatorAppServerRuntimeManager: AppServerRuntimeManager | undefined;- const stickmanContentRuntimeManager = input.creatorExecutors === undefined+ let stickmanContentRuntimeManager = input.creatorExecutors === undefined? createAppServerRuntimeManager({ codexBin, codexHome }): undefined;const invalidatePersistentRuntime = (reason: string): Promise<void> => {@@ -491,7 +501,8 @@ export async function buildServer(input: BuildServerInput) {const creatorJobsRoot = join(creatorDir, 'jobs');await purgeLegacyStickmanJobs({ db, jobsRoot: creatorJobsRoot });migrateStickmanVisualAssetState({ db });- const creatorRepository = createCreatorRepository(db);+ let gatewayCreatorSource: ReturnType<typeof createGatewayCreatorSource> | undefined;+ const creatorRepository = createCreatorRepository(db, { serviceBinding: () => gatewayCreatorSource?.snapshot() ?? { source: 'manual' } });const creatorIssueService = createCreatorIssueService(creatorRepository, {onChanged(issue) {if (issue.scope.kind !== 'creator-job') return;@@ -511,6 +522,56 @@ export async function buildServer(input: BuildServerInput) {creatorRepository,creatorIssueService);+ const officialManagers = new Map<string, AppServerRuntimeManager>();+ let officialBindings: ReturnType<typeof createGatewayRuntimeBindings> | undefined;+ const gatewayOrigin = input.gatewayOrigin ?? process.env.OPENCREATOR_GATEWAY_ORIGIN;+ const unavailable = async (): Promise<never> => { throw new GatewayError('services_not_ready'); };+ const readCommonProxy = async () => (await storedCreatorServicesConfigStore.read()).proxy;+ const gatewayClient: GatewayClient = gatewayOrigin ? createGatewayClient(gatewayOrigin, createOfficialFetch({ readProxy: readCommonProxy })) : {+ origin: '', startDevice: unavailable, pollDevice: unavailable, cancelDevice: unavailable,+ refresh: unavailable, bootstrap: unavailable, avatar: unavailable, logout: unavailable, request: unavailable+ };+ let officialInjectors: Record<string, import('../agent-tools/run-injection.js').AgentScheduleProcessInjector> = {};+ const gatewayAccount = createGatewayAccountService({+ dataDir, client: gatewayClient,+ modelAccess: createOfficialModelAccess({ dataDir, fetcher: createOfficialFetch({ readProxy: readCommonProxy }), readProxy: readCommonProxy }),+ hasActiveTasks: () => [appServerRuntimeManager, creatorAppServerRuntimeManager, stickmanContentRuntimeManager]+ .some(manager => manager?.listScopes().some(scope => scope.active || scope.pending > 0))+ || creatorRepository.listJobs().some(job => job.status === 'running' || job.stages.some(stage => stage.status === 'queued')) || gatewayCreatorSource?.isBusy() === true,+ hasPendingTasks: () => creatorRepository.listJobs().some(job => job.providerRequests.some(request => request.billingSideEffect && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(request.status))),+ async closeRuntime() {+ await gatewayCreatorSource?.revoke();+ officialBindings?.beginLogout();+ await officialBindings?.close();+ officialBindings = undefined;+ officialManagers.clear();+ },+ async activateRuntime(bootstrap) {+ if (runtimeTransport !== 'app-server') throw new GatewayError('services_not_ready');+ const model = bootstrap.models.find(value => value.id === bootstrap.defaults.text && value.modality === 'text' && value.capabilities.includes('responses'));+ if (!model) throw new GatewayError('services_not_ready');+ await officialBindings?.close(); officialManagers.clear();+ const home = join(runtimeDir, 'gateway-codex');+ const bootstrapResult = bootstrapCreatorAgentRuntime({ ...creatorAgentBootstrapInput, codexHome: home, source: 'gateway' });+ if (!bootstrapResult.available) throw new GatewayError('services_not_ready');+ officialBindings = createGatewayRuntimeBindings({+ codexHome: home, baseUrl: bootstrap.baseUrl, model: model.id, direct: bootstrap.transport === 'openrouter-direct',+ readProxy: readCommonProxy,+ beginUse: async () => { const use = await gatewayAccount.beginModelUse(); return { key: use.credentials.modelKey, release: use.release }; },+ readCredentials: async () => ({ accountId: bootstrap.account.id, modelKey: bootstrap.modelKey, keyVersion: bootstrap.keyVersion }),+ closeRuntime: async () => { await Promise.all([...officialManagers.values()].map(manager => manager.close())); }+ });+ const prepared = await officialBindings.prepare();+ const probe = createCodexAppServerHost({ codexBin, codexHome: home, cwd: dataDir, profile: 'default', baseEnvironment: prepared.env, spawnTimeoutMs: 15_000 });+ try { await probe.ready; } finally { await probe.close('gateway-activation-probe'); }+ for (const name of ['general', 'creator', 'stickman']) {+ officialManagers.set(name, createAppServerRuntimeManager({+ codexBin, codexHome: home, processInjector: officialInjectors[name],+ createHost(host) { return createCodexAppServerHost({ ...host, codexHome: home, baseEnvironment: prepared.env }); }+ }));+ }+ }+ });const creatorAgentRepository = createCreatorAgentRepository(db);const creatorAgentReconciler = createCreatorAgentReconciler({repository: creatorAgentRepository@@ -618,14 +679,17 @@ export async function buildServer(input: BuildServerInput) {return baseUrl === undefined ? undefined : krillinCodexLlmGateway.config(baseUrl);}});- const creatorServicesConfigStore =+ const manualCreatorServicesConfigStore =createCreatorServicesConfigStoreWithTextModelFallback(storedCreatorServicesConfigStore,localCodexTextModelDefaults);+ gatewayCreatorSource = createGatewayCreatorSource({ account: gatewayAccount, manual: manualCreatorServicesConfigStore, getLocalOrigin: getAgentToolBaseUrl, readJobBinding: creatorRepository.getServiceBinding, readJobState: id => creatorRepository.getJob(id)?.state, readStageRun: creatorRepository.getStageRun, ledger: creatorProviderRequestLedger, directRequestsRoot: join(dataDir, 'gateway', 'requests') });+ const creatorServicesConfigStore = gatewayCreatorSource.store;+ if (stickmanContentRuntimeManager) stickmanContentRuntimeManager = createRuntimeSource(stickmanContentRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('stickman'));let getCreatorYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;const videoMetadataService = input.videoMetadataService ?? createVideoMetadataService({- getProxy: async () => (await creatorServicesConfigStore.read()).proxy.trim(),+ getProxy: async () => (await readCommonProxy()).trim(),getYtDlpRuntime: () => getCreatorYtDlpRuntime?.()});const creatorService = input.creatorService ?? createCreatorService({@@ -666,7 +730,8 @@ export async function buildServer(input: BuildServerInput) {});const videoGenerationService = createVideoGenerationService({dataDir,- configStore: creatorServicesConfigStore+ configStore: creatorServicesConfigStore,+ gatewaySource: gatewayCreatorSource});// Image generation follows the user's local Codex login, independently of Agent settings.const codexImageRuntime = { codexHome: localCodexHome, codexBin };@@ -884,9 +949,11 @@ export async function buildServer(input: BuildServerInput) {configStore: creatorServicesConfigStore}));creatorExecutors.push(createSmartDubbingExecutor({- ttsService: krillinTtsService+ ttsService: krillinTtsService,+ isOfficial: () => gatewayAccount.peekState().source === 'gateway'}));creatorExecutors.push(createImageExecutor({+ ledger: creatorProviderRequestLedger,configStore: creatorServicesConfigStore,codexNative: codexImageRuntime,...(creatorFfmpegPath === undefined@@ -899,6 +966,7 @@ export async function buildServer(input: BuildServerInput) {}));if (creatorFfprobePath !== undefined) {creatorExecutors.push(createVideoExecutor({+ ledger: creatorProviderRequestLedger,service: videoGenerationService,probeVideo: path => validateMediaFile(path, creatorFfprobePath!)}));@@ -916,6 +984,7 @@ export async function buildServer(input: BuildServerInput) {}));}const creatorPreflight = createCreatorPreflight({+ assertServiceSource: gatewayCreatorSource.assertJob,readCodexImageStatus,videoMetadataService,configStore: creatorServicesConfigStore,@@ -981,8 +1050,12 @@ export async function buildServer(input: BuildServerInput) {issueService: creatorIssueService,templates: creatorService.templates,workRoot: creatorJobsRoot,- executors: creatorExecutors,+ executors: creatorExecutors.map(executor => ({+ id: executor.id,+ run: stage => gatewayCreatorSource!.runForJob(stage.job.id, stage.stageRun.id, () => executor.run(stage))+ })),async beforeRun(job, stageId) {+ gatewayCreatorSource!.assertJob(job.id);assertCreatorPresetStageRequirement({job,stageId,@@ -1164,6 +1237,9 @@ export async function buildServer(input: BuildServerInput) {codexHome,processInjector: creatorAgentToolProcessInjector});+ officialInjectors = { general: agentToolProcessInjector, creator: creatorAgentToolProcessInjector };+ appServerRuntimeManager = createRuntimeSource(appServerRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('general'));+ creatorAppServerRuntimeManager = createRuntimeSource(creatorAppServerRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('creator'));const creatorAgentRuntime = input.creatorAgentRuntime ?? (creatorAgentBootstrap.available? createCodexCreatorAdapter({runtimeManager: creatorAppServerRuntimeManager,@@ -1323,6 +1399,7 @@ export async function buildServer(input: BuildServerInput) {});server.addHook('onClose', async () => {+ await gatewayAccount.close();let firstError: unknown;const capture = async (operation: () => void | Promise<void>) => {try {@@ -1371,9 +1448,27 @@ export async function buildServer(input: BuildServerInput) {codexBin,codexHome: resolvedCodexHome,capabilities,- modelCatalog: codexModelCatalog,+ modelCatalog: {+ ...codexModelCatalog,+ async listModels() {+ const gateway = gatewayAccount.peekState();+ if (gateway.source === 'manual') return codexModelCatalog.listModels();+ return { models: gateway.models.filter(model => model.modality === 'text' && model.capabilities.includes('responses')).map((model, index) => ({ id: model.id, model: model.id, displayName: /openrouter/i.test(model.id) ? 'Auto' : model.id.split('/').pop()!, description: '', supportedReasoningEfforts: [], defaultReasoningEffort: null, inputModalities: ['text' as const], isDefault: gateway.selectedModels?.text ? model.id === gateway.selectedModels.text : index === 0 })) };+ }+ },readiness: codexRuntimeReadiness,- providerConfig: codexProviderConfig,+ providerConfig: {+ ...codexProviderConfig,+ async read() {+ const state = gatewayAccount.peekState();+ if (state.source === 'gateway') return { authentication: 'api_key' as const, apiKeyConfigured: false, baseUrl: '', model: state.selectedModels?.text ?? '' };+ return codexProviderConfig.read();+ },+ async update(update) {+ await gatewayAccount.setSource('manual');+ return codexProviderConfig.update(update);+ }+ },getAvailabilityProbe: input.getCodexAvailabilityProbe});await registerProfileRoutes(server, {@@ -1433,8 +1528,14 @@ export async function buildServer(input: BuildServerInput) {await stickmanVideoWorkflow?.resumeConfiguredJobs();},readCodexImageStatus,- () => localCodexTextModelDefaults.readStatus()+ async () => gatewayAccount.peekState().source === 'gateway'+ ? { authentication: 'api_key' as const, apiKeyConfigured: false, baseUrl: '', model: gatewayAccount.peekState().selectedModels?.text ?? '' }+ : localCodexTextModelDefaults.readStatus(),+ storedCreatorServicesConfigStore);+ await gatewayAccount.readState();+ await registerGatewayAccountRoutes(server, gatewayAccount);+ await gatewayCreatorSource.register(server);await registerSmartDubbingRoutes(server, smartDubbingService);await registerCreatorRuntimeRoutes(server, creatorYtDlpUpdateManager, {loader: krillinDependencyLoader,diff --git a/apps/daemon/src/codex/app-server-host-2026-07-28.ts b/apps/daemon/src/codex/app-server-host-2026-07-28.tsindex db53b3d2..11f55a32 100644--- a/apps/daemon/src/codex/app-server-host-2026-07-28.ts+++ b/apps/daemon/src/codex/app-server-host-2026-07-28.ts@@ -98,6 +98,7 @@ export type CodexAppServerHostInput = {mcpServers?: CodexMcpServerConfig[];builtInTools?: BuiltInToolPolicy;env?: Record<string, string>;+ baseEnvironment?: NodeJS.ProcessEnv;skillRoots?: string[];requiredSkillNames?: string[];spawnTimeoutMs?: number;@@ -108,6 +109,7 @@ export type CodexAppServerHostInput = {export type CodexAppServerHost = {readonly pid: number | undefined;readonly started: Promise<number>;+ readonly ready?: Promise<void>;run(input: CodexAppServerTurnInput): CodexAppServerProcess;isReusable(): boolean;close(reason?: string, forceKillGraceMs?: number): Promise<void>;@@ -167,7 +169,7 @@ export function createCodexAppServerHost(buildCodexAppServerArgs(input),{cwd: input.cwd,- env: { ...process.env, ...input.env, CODEX_HOME: input.codexHome },+ env: { ...(input.baseEnvironment ?? process.env), ...input.env, CODEX_HOME: input.codexHome },stdio: ['pipe', 'pipe', 'pipe']});@@ -951,6 +953,7 @@ export function createCodexAppServerHost(return child.pid;},started,+ ready: initializePromise,run,isReusable() {return state === 'starting' || state === 'ready';diff --git a/apps/daemon/src/codex/runner.ts b/apps/daemon/src/codex/runner.tsindex a5efa8c3..64d6c982 100644--- a/apps/daemon/src/codex/runner.ts+++ b/apps/daemon/src/codex/runner.ts@@ -26,6 +26,7 @@ export type RunCodexExecInput = {forceKillGraceMs?: number;finalKillSettleMs?: number;env?: NodeJS.ProcessEnv;+ baseEnvironment?: NodeJS.ProcessEnv;beforeSpawn?: () => Promise<void>;onStdoutLine?: (line: string) => Promise<void> | void;onStderrChunk?: (chunk: string) => Promise<void> | void;@@ -113,7 +114,7 @@ export function startCodexExec(input: RunCodexExecInput): CodexExecProcess {const result = new Promise<RunCodexExecResult>((resolve, reject) => {const child = spawnCodexProcess(input.codexBin, input.args, {cwd: input.cwd,- env: { ...process.env, ...input.env, CODEX_HOME: input.codexHome },+ env: { ...(input.baseEnvironment ?? process.env), ...input.env, CODEX_HOME: input.codexHome },stdio: ['pipe', 'pipe', 'pipe']});diff --git a/apps/daemon/src/creator/agent/bootstrap.ts b/apps/daemon/src/creator/agent/bootstrap.tsindex 63c22245..f3db3934 100644--- a/apps/daemon/src/creator/agent/bootstrap.ts+++ b/apps/daemon/src/creator/agent/bootstrap.ts@@ -26,11 +26,13 @@ export function bootstrapCreatorAgentRuntime(input: {runtimeRoot: string;codexHome?: string;bundledSkillDir: string;+ source?: 'manual' | 'gateway';}): CreatorAgentBootstrapResult {const codexHome = input.codexHome ?? join(input.runtimeRoot, 'codex-home');const skillPath = join(codexHome, 'skills', 'opencreator-runtime');try {- createCodexIsolatedHome(input.sourceCodexHome, codexHome);+ if (input.source === 'gateway') mkdirSync(codexHome, { recursive: true, mode: 0o700 });+ else createCodexIsolatedHome(input.sourceCodexHome, codexHome);const manifest = JSON.parse(readFileSync(join(input.bundledSkillDir, 'manifest.json'), 'utf8')) as { version: number };const hash = hashSkill(input.bundledSkillDir);const currentHash = existsSync(join(skillPath, '.opencreator-hash'))diff --git a/apps/daemon/src/creator/command-dispatcher.ts b/apps/daemon/src/creator/command-dispatcher.tsindex f5b81c3d..dc21b3f3 100644--- a/apps/daemon/src/creator/command-dispatcher.ts+++ b/apps/daemon/src/creator/command-dispatcher.ts@@ -122,7 +122,8 @@ export function createCreatorCommandDispatcher(input: {});let response = actionResponse;let stageRunId: string | null = null;- if (request.action === 'run-stage') {+ if (request.action === 'run-stage'+ || (request.action === 'retry-stage' && actionResponse.job.templateId === 'image-generation')) {const stageId = readStageId(request.input.stageId);const template = input.service.templates.get(actionResponse.job.templateId,diff --git a/apps/daemon/src/creator/image/executor.ts b/apps/daemon/src/creator/image/executor.tsindex 4ba2b97f..33f909bd 100644--- a/apps/daemon/src/creator/image/executor.ts+++ b/apps/daemon/src/creator/image/executor.ts@@ -7,6 +7,9 @@ import type {} from '@opencreator/protocol';import { imagePromptRequiresReference } from '@opencreator/protocol';import { readFile, rm, writeFile } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { gatewayCreatorBinding } from '../../gateway/creator-service-source.js';+import type { CreatorProviderRequestLedger } from '../provider-requests.js';import { join } from 'node:path';import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';import {@@ -54,6 +57,7 @@ type CoverImageNormalizer = (input: {}) => Promise<{ width: number; height: number }>;export function createImageExecutor(input: {+ ledger?: CreatorProviderRequestLedger;configStore: Pick<CreatorServicesConfigStore, 'read'>;generate?: GenerateImageContents;codexNative?: CodexNativeImageRuntime;@@ -113,12 +117,22 @@ export function createImageExecutor(input: {total: request.count});const settled = await Promise.allSettled(- Array.from({ length: request.count }, (_, index) => (- generate(+ Array.from({ length: request.count }, (_, index) => {+ const gateway = gatewayCreatorBinding(config);+ const logicalId = `${gateway?.logicalId ?? stage.stageRun.id}:candidate:${index}`;+ let ledger = gateway && input.ledger ? input.ledger.registerBeforeSubmit({+ jobId:stage.job.id, stageRunId:stage.stageRun.id, provider:'opencreator-gateway-image', requestKey:logicalId,+ gateway:{ accountId:gateway.accountId, bindingVersion:gateway.bindingVersion, logicalId },+ request:{prompt:request.prompt,size:request.size,quality:request.quality,model:gateway.models.image ?? '',reference:referenceImage ? createHash('sha256').update(referenceImage.content).digest('hex') : null}+ }) : undefined;+ if (ledger) ledger = input.ledger!.markSubmitting(ledger.id);+ return generate({ ...request, count: 1 },config,{signal: stage.signal,+ logicalId,+ onGatewayRequest: id => { if (ledger) ledger = input.ledger!.markWaitingRemote(ledger.id,id); },onProgress: progress => stage.reportProgress({...progress, completed, failed, total: request.count}),@@ -168,6 +182,7 @@ export function createImageExecutor(input: {if (sourcePath !== path) await rm(sourcePath, { force: true });}const metadata = await validateImageFile(path);+ if (ledger) ledger = input.ledger!.markSucceeded(ledger.id);completed += 1;stage.reportProgress({status: 'running',@@ -221,18 +236,24 @@ export function createImageExecutor(input: {} satisfies CreatorExecutorOutput;}).catch(error => {+ if (ledger && ['submitting', 'waiting_remote'].includes(ledger.status)) {+ const status = error instanceof ImageGenerationProviderError ? error.publicFacts.httpStatus : undefined;+ ledger = status && [400, 401, 402, 403, 404, 422, 429].includes(status)+ ? input.ledger!.markFailed(ledger.id, error)+ : input.ledger!.markUnknownRemoteAcceptance(ledger.id);+ }failed += 1;stage.reportProgress({- status: 'running',+ status: completed + failed === request.count && completed === 0 ? 'failed' : 'running',phase: 'generating_candidates',- percent: candidateProgress(completed, failed, request.count),+ percent: candidateProgress(completed, 0, request.count),completed,failed,total: request.count});throw error;})- ))+ }));const outputs = settled.flatMap(item => item.status === 'fulfilled' ? [item.value] : []);const failures = settled.flatMap((item, index) => item.status === 'rejected'@@ -319,7 +340,12 @@ function imageRequest(provider: settings.provider,size,quality,- count: settings.candidateCount+ count: settings.candidateCount,+ ...(gatewayCreatorBinding(config) && stage.job.templateId === 'image-generation' ? {+ aspectRatio: readString(stage.job.state.aspectRatio) || undefined,+ resolution: readString(stage.job.state.resolution) || undefined,+ officialQuality: readString(stage.job.state.officialQuality) || undefined+ } : {})},...(cover === undefined ? {} : { cover: cover.details })};diff --git a/apps/daemon/src/creator/krillin/adapter.ts b/apps/daemon/src/creator/krillin/adapter.tsindex 328d0cb0..adb99862 100644--- a/apps/daemon/src/creator/krillin/adapter.ts+++ b/apps/daemon/src/creator/krillin/adapter.ts@@ -114,7 +114,8 @@ export function createKrillinExecutor(input: {} catch (error) {if (!(error instanceof KrillinCliError)) throw error;const normalized = normalizeKrillinFailure({- code: error.kind === 'usage' ? 'usage' : error.code,+ code: error.code,+ kind: error.kind,message: error.message});throw CreatorExecutorError.from(normalized.code, error, normalized.message);@@ -193,11 +194,17 @@ async function ensureKrillinTranscriptionDependency(});}-export function normalizeKrillinFailure(error: { code?: string; message?: string } | undefined): {+export function normalizeKrillinFailure(error: { code?: string; kind?: string; message?: string } | undefined): {code: string;message: string;} {const message = error?.message ?? 'KrillinAI stage failed';+ if (error?.code !== undefined && [+ 'audio_no_speech', 'audio_transcription_empty', 'audio_transcription_invalid_response',+ 'audio_transcription_timestamps_missing', 'audio_transcription_api_failed'+ ].includes(error.code)) {+ return { code: error.code, message };+ }if (error?.code === 'subtitle_style_load_failed'|| error?.code === 'default_subtitle_style_load_failed'@@ -208,7 +215,7 @@ export function normalizeKrillinFailure(error: { code?: string; message?: stringif (/OpenAI.*(?:杞綍|转录|transcri)|(?:杞綍|转录|transcri).*OpenAI/i.test(message)) {return { code: 'creator_transcription_config_missing', message };}- if (error?.code === 'usage') {+ if (error?.code === 'usage' || error?.kind === 'usage') {if (/(?:TTS|閰嶉煶|配音|语音合成)/i.test(message)) {return { code: 'creator_tts_config_missing', message };}@@ -216,7 +223,7 @@ export function normalizeKrillinFailure(error: { code?: string; message?: stringreturn { code: 'creator_llm_config_missing', message };}}- return { code: error?.code ?? 'krillin_stage_failed', message };+ return { code: error?.kind === 'usage' ? 'usage' : error?.code ?? 'krillin_stage_failed', message };}export function buildKrillinStageOptions(input: CreatorExecutorInput): Record<string, unknown> {diff --git a/apps/daemon/src/creator/krillin/cli-runner.ts b/apps/daemon/src/creator/krillin/cli-runner.tsindex 002fdbf5..25a7f9a4 100644--- a/apps/daemon/src/creator/krillin/cli-runner.ts+++ b/apps/daemon/src/creator/krillin/cli-runner.ts@@ -11,6 +11,7 @@ import { sha256CreatorFile } from '../file-hash.js';import { publicErrorKindForCode, sanitizePublicErrorFacts, type PublicErrorFacts } from '@opencreator/protocol';import { spawnCreatorProcess } from '../process-tree.js';import { createKrillinConfigToml } from './config-bridge.js';+import { gatewayCreatorBinding } from '../../gateway/creator-service-source.js';import { isYouTubeSource } from './execution-plan.js';import {resolveInside,@@ -121,7 +122,7 @@ export async function runKrillinCli(input: RunKrillinCliInput): Promise<KrillinRconst cliConfig = stageConfig(input.config, krillinCliStageId(input.stage.stageRun.stageId), input.options);await writeFile(join(configDir, 'config.toml'),- createKrillinConfigToml(cliConfig, input.llmOverride),+ createKrillinConfigToml(cliConfig, input.llmOverride, gatewayCreatorBinding(input.config)?.models.transcription),{ mode: 0o600 });await writeFile(join(dependencyBin, '.yt-dlp-last-check'), new Date().toISOString(), { mode: 0o600 });diff --git a/apps/daemon/src/creator/krillin/config-bridge.ts b/apps/daemon/src/creator/krillin/config-bridge.tsindex a9006c90..85ae6622 100644--- a/apps/daemon/src/creator/krillin/config-bridge.ts+++ b/apps/daemon/src/creator/krillin/config-bridge.ts@@ -3,11 +3,12 @@ import type { AliyunOssConfig, CreatorServicesConfig } from '@opencreator/protocexport function createKrillinConfigToml(config: CreatorServicesConfig,- llmOverride?: { baseUrl: string; apiKey: string; model: string }+ llmOverride?: { baseUrl: string; apiKey: string; model: string },+ officialTranscriptionModel?: string): string {const llm = llmOverride ?? config.llm;const document = compact({- app: { proxy: config.proxy },+ app: { proxy: officialTranscriptionModel ? '' : config.proxy },llm: {base_url: llm.baseUrl,api_key: llm.apiKey,@@ -17,7 +18,7 @@ export function createKrillinConfigToml(transcribe: {provider: normalizeTranscriptionProvider(config.transcription.provider),enable_gpu_acceleration: config.transcription.enableGpuAcceleration,- openai: openAi(config.transcription.openai),+ openai: { ...openAi(config.transcription.openai), ...(officialTranscriptionModel ? { official_model: officialTranscriptionModel } : {}) },fasterwhisper: config.transcription.fasterWhisper,whisperkit: config.transcription.whisperKit,whispercpp: {diff --git a/apps/daemon/src/creator/krillin/tts-service.ts b/apps/daemon/src/creator/krillin/tts-service.tsindex efd31b46..3614f6d1 100644--- a/apps/daemon/src/creator/krillin/tts-service.ts+++ b/apps/daemon/src/creator/krillin/tts-service.ts@@ -7,6 +7,7 @@ import type {PublicErrorFacts,RuntimeErrorCode} from '@opencreator/protocol';+import { gatewayDefaultVoiceId } from '@opencreator/protocol';import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { join, resolve } from 'node:path';import { spawn } from 'node:child_process';@@ -25,6 +26,7 @@ import {import { parseVolcengineV3Audio } from './volcengine-tts-v3.js';import { creatorServiceErrorInfo } from '../../creator-services/upstream-fetch.js';import { publicFactsFromFailure } from '../public-error-facts.js';+import { gatewayCreatorBinding } from '../../gateway/creator-service-source.js';const MAX_OUTPUT_BYTES = 100 * 1024 * 1024;const MAX_PROCESS_OUTPUT_BYTES = 4 * 1024 * 1024;@@ -60,6 +62,9 @@ type ExecuteUtilityInput = {};type ExecuteSynthesisInput = {+ onGatewayRequest?(id: string): void;+ logicalId?: string;+ official?: boolean;config: CreatorServicesConfig;provider: Exclude<CreatorTtsProvider, 'edge-tts'>;model: string;@@ -77,6 +82,8 @@ type ExecuteSynthesisResult = {};export type KrillinTtsSynthesisRequest = {+ onGatewayRequest?(id: string): void;+ logicalId?: string;text: string;provider?: CreatorTtsProvider;model?: string;@@ -146,10 +153,18 @@ export function createKrillinTtsService(input: {provider: CreatorTtsProvider,model?: string): Promise<CreatorTtsVoicesResponse> {+ const config = await input.configStore.read();+ const gateway = gatewayCreatorBinding(config);+ if (gateway) {+ const selected = gateway.catalog?.find(candidate => candidate.modality === 'speech' && candidate.id === (model || gateway.models.speech));+ if (model && model !== gateway.models.speech && !selected) throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择官方语音模型', 400);+ const defaultVoice = selected?.capabilities.includes('default_voice') ?? gateway.capabilities?.speech?.includes('default_voice');+ return { provider: 'openai', model: selected?.id ?? gateway.models.speech ?? '', voices: (defaultVoice ? [gatewayDefaultVoiceId] : selected?.voices ?? gateway.speechVoices ?? []).map(id => ({ id, name: id === gatewayDefaultVoiceId ? '默认音色' : id, provider: 'openai' as const, kind: 'builtin' as const })) };+ }if (provider === 'edge-tts') {return { provider, model: '', voices: [] };}- const prepared = prepareConfig(await input.configStore.read(), provider, model);+ const prepared = prepareConfig(config, provider, model);const bundledVoices = listBundledTtsVoices(provider, prepared.model);if (bundledVoices !== undefined) {return {@@ -186,7 +201,10 @@ export function createKrillinTtsService(input: {throw new KrillinTtsServiceError('VALIDATION_FAILED', 'Speech text is required', 400);}const configured = await input.configStore.read();- const provider = request.provider ?? configured.tts.provider;+ const gateway = gatewayCreatorBinding(configured);+ const selected = gateway?.catalog?.find(candidate => candidate.modality === 'speech' && candidate.id === (request.model || gateway.models.speech));+ if (gateway && request.model && request.model !== gateway.models.speech && (gateway.stageRunId || !selected)) throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择当前任务的官方语音模型', 400);+ const provider = gateway ? 'openai' : request.provider ?? configured.tts.provider;if (provider === 'edge-tts') {throw new KrillinTtsServiceError('unsupported_capability',@@ -196,12 +214,18 @@ export function createKrillinTtsService(input: {}const prepared = prepareConfig(configured, provider, request.model);ensureCredentials(prepared.config, provider);- const voiceId = request.voiceId?.trim() || prepared.providerConfig.defaultVoiceId;+ const defaultVoice = gateway && (selected?.capabilities.includes('default_voice') ?? gateway.capabilities?.speech?.includes('default_voice'));+ const voiceId = request.voiceId?.trim() || (defaultVoice ? gatewayDefaultVoiceId : selected?.voices?.[0] || prepared.providerConfig.defaultVoiceId);+ const allowedVoices = defaultVoice ? [gatewayDefaultVoiceId] : selected?.voices ?? gateway?.speechVoices;+ if (allowedVoices && !allowedVoices.includes(voiceId)) {+ throw new KrillinTtsServiceError('VALIDATION_FAILED', '请选择当前模型支持的音色', 400);+ }if (!voiceId) {throw new KrillinTtsServiceError('VALIDATION_FAILED', 'A voice must be selected', 400);}const format = request.format ?? 'wav';const speed = request.speed ?? 1;+ if (gateway && (speed !== 1 || request.instructions)) throw new KrillinTtsServiceError('unsupported_capability', '当前官方语音路由未验证此生成参数', 400);if (!Number.isFinite(speed) || speed < 0.5 || speed > 2) {throw new KrillinTtsServiceError('VALIDATION_FAILED',@@ -210,8 +234,12 @@ export function createKrillinTtsService(input: {);}+ const logicalId = gateway && request.logicalId !== undefined && request.logicalId === gateway.stageRunId+ ? gateway.logicalId ?? request.logicalId+ : request.logicalId ?? gateway?.logicalId ?? crypto.randomUUID();try {const synthesis = await executeSynthesis({+ ...(gateway ? { official: true, logicalId, onGatewayRequest: request.onGatewayRequest } : {}),config: prepared.config,provider,model: prepared.model,@@ -447,9 +475,9 @@ async function synthesizeOpenAi({model: input.model,input: input.text,- voice: input.voiceId,+ ...(input.official && input.voiceId === gatewayDefaultVoiceId ? {} : { voice: input.voiceId }),response_format: input.format,- speed: input.speed,+ ...(input.official ? {} : { speed: input.speed }),...(input.instructions === undefined ? {} : { instructions: input.instructions })},input@@ -551,10 +579,13 @@ async function providerFetch(method: 'POST',headers: {authorization: `Bearer ${apiKey}`,- 'content-type': 'application/json'+ 'content-type': 'application/json',+ ...(input.logicalId ? { 'Idempotency-Key': input.logicalId } : {})},body: JSON.stringify(body)}, input);+ const requestId = response.headers.get('x-request-id');+ if (input.official && requestId && /^[A-Za-z0-9_-]{12,128}$/.test(requestId)) input.onGatewayRequest?.(requestId);if (!response.ok) await throwProviderHttpError(response, input.provider);return response;}diff --git a/apps/daemon/src/creator/preflight.ts b/apps/daemon/src/creator/preflight.tsindex 565988c6..16c0789e 100644--- a/apps/daemon/src/creator/preflight.ts+++ b/apps/daemon/src/creator/preflight.ts@@ -1,5 +1,6 @@import type {CodexImageStatus,+ CreatorArtifact,CreatorJob,CreatorPreflightCheck,CreatorPreflightExecutionMode,@@ -9,7 +10,7 @@ import type {PublicErrorFacts} from '@opencreator/protocol';import { creatorPreflightFailure, imagePromptRequiresReference } from '@opencreator/protocol';-import { access, mkdir } from 'node:fs/promises';+import { access, mkdir, readFile } from 'node:fs/promises';import { constants } from 'node:fs';import { join } from 'node:path';import type { CreatorTemplateStage } from './templates/types.js';@@ -26,6 +27,9 @@ import { readStickmanRemotionRuntime } from './stickman/remotion-runtime.js';import type { RemotionComponentManager } from './stickman/remotion-component.js';import { validateBilibiliSource } from './templates/video-translation-actions.js';import type { VideoMetadataService } from '../video-metadata/service.js';+import { gatewayCreatorBinding } from '../gateway/creator-service-source.js';+import { stickmanShotSpecSchema } from './stickman/contracts.js';+import { shouldUsePreviousShotReference } from './stickman/image-prompt.js';export type CreatorPreflight = ReturnType<typeof createCreatorPreflight>;@@ -61,6 +65,7 @@ export function createCreatorPreflight(input: {validateRuntimeAssets?: boolean;readCodexImageStatus?(): Promise<CodexImageStatus>;videoMetadataService?: VideoMetadataService;+ assertServiceSource?(jobId: string): void;}) {const executorIds = new Set(input.executorIds ?? []);@@ -91,8 +96,11 @@ export function createCreatorPreflight(input: {add('ready', { id: 'executor', title: '执行器', message: `${stage.executor} 已加载`, executionMode: mode });}+ try { input.assertServiceSource?.(job.id); } catch {+ add('blocked', { id: 'service-source', title: '任务服务来源不匹配', message: '请恢复原任务账户和服务来源后继续。', executionMode: 'remote' }, { label: '打开账户设置', deepLink: '#/settings?tab=ai-services' });+ return { templateId: job.templateId, templateVersion: job.templateVersion, stageId: stage.id, executionMode: mode, canStart: false, ready, warning, blocked, checkedAt: new Date().toISOString() };+ }const config = await input.configStore.read();- await checkProviderConfig(job, stage, config, input.readCapabilities(), add, input.readCodexImageStatus);const inputSnapshot = options.inputResultVersion === undefined? undefined: creatorResultSnapshotForVersion(job, options.inputResultVersion);@@ -133,6 +141,7 @@ export function createCreatorPreflight(input: {inputSnapshot?.artifactRefs,inputSnapshot?.state);+ await checkProviderConfig(job, stage, config, resolvedInputs.artifacts, input.readCapabilities(), add, input.readCodexImageStatus);if (job.templateId === 'image-generation' && stage.id === 'generate'&& typeof inputState.prompt === 'string' && imagePromptRequiresReference(inputState.prompt)&& !resolvedInputs.artifacts.some(artifact => artifact.kind === 'reference_image'@@ -298,6 +307,7 @@ async function checkProviderConfig(job: CreatorJob,stage: CreatorTemplateStage,config: CreatorServicesConfig,+ inputArtifacts: CreatorArtifact[],capabilities: CreatorServicesCapabilitiesResponse,add: (status: 'ready' | 'warning' | 'blocked', item: Omit<CreatorPreflightCheck, 'executionMode'> & { executionMode?: CreatorPreflightExecutionMode }, repair?: CreatorPreflightCheck['repair']) => void,readCodexImageStatus?: () => Promise<CodexImageStatus>@@ -340,6 +350,10 @@ async function checkProviderConfig(}}if (needs.has('tts')) {+ const gateway = gatewayCreatorBinding(config);+ if (gateway && (stage.executor === 'smart-dubbing' || (typeof job.state.speed === 'number' && job.state.speed !== 1))) {+ add('blocked', { id: 'tts-style-capability', title: '配音参数不受支持', message: '当前官方语音模型未提供已验证的样式或语速控制,请选择其他配音服务。', executionMode: 'remote' }, { label: '打开配音设置', deepLink: '#/settings?tab=ai-services§ion=tts' });+ }const provider = readTtsProvider(job, config);if (provider === 'edge-tts') add('ready', { id: 'tts', title: '配音服务', message: 'Edge TTS 不需要 API Key。', executionMode: 'remote' });else checkTts(config, provider, add);@@ -347,7 +361,7 @@ async function checkProviderConfig(if (needs.has('image')) {const settings = resolveCreatorImageSettings({config,- provider: job.state.provider,+ provider: gatewayCreatorBinding(config) ? 'openai' : job.state.provider,candidateCount: job.state.candidateCount,fallbackCandidateCount: job.templateId === 'image-generation' ? 2 : 1,maxCandidateCount: job.templateId === 'image-generation' ? 4 : 8@@ -376,18 +390,39 @@ async function checkProviderConfig(const hasReference = stage.executor === 'stickman-image'|| (stage.inputArtifacts.some(item => item.kind === 'reference_image')&& typeof job.state.referenceImageArtifactId === 'string');- if (hasReference && !settings.supportsReferenceImage) add('blocked', {+ const gateway = gatewayCreatorBinding(config);+ const supportsReference = gateway ? gateway.capabilities?.image?.includes('edit') === true : settings.supportsReferenceImage;+ if (gateway && stage.executor === 'stickman-image') {+ let multiple = inputArtifacts.some(artifact => artifact.kind === 'style_reference');+ const shotSpec = inputArtifacts.find(artifact => artifact.kind === 'shot_spec');+ if (shotSpec?.path) {+ try {+ const spec = stickmanShotSpecSchema.parse(JSON.parse(await readFile(shotSpec.path, 'utf8')));+ multiple ||= spec.shots.some(shouldUsePreviousShotReference);+ } catch {+ add('blocked', { id: 'shot-spec-invalid', title: '分镜数据不可用', message: '无法检查分镜的参考图要求,请重新生成分镜。', executionMode: 'local' });+ }+ }+ if (multiple) add('blocked', { id: 'reference-image-count', title: '参考图数量不支持', message: '当前官方图像服务仅验证了 1 张参考图,此任务需要多张参考图。', executionMode: 'remote' });+ }+ if (hasReference && !supportsReference) add('blocked', {id: 'reference-image-capability', title: '参考图能力不匹配', message: `${provider} 不支持当前阶段的参考图编辑。`, executionMode: 'remote'}, { label: '选择支持参考图的服务', deepLink: '#/settings?tab=ai-services§ion=image' });}if (needs.has('video')) {- const provider = readVideoProvider(job, config);- const settings = config.video[provider];- const hasKey = providerCredentials(settings, provider);- if (!hasKey || !settings.model.trim() || !settings.baseUrl.trim()) add('blocked', {- id: 'video-provider', title: '视频服务配置不完整', message: `请配置 ${provider} 的 Base URL、模型和凭据。`, executionMode: 'remote'- }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=video' });- else add('ready', { id: 'video-provider', title: '视频服务', message: `${provider} / ${settings.model} 已配置。`, executionMode: 'remote' });+ const gateway = gatewayCreatorBinding(config);+ if (gateway) {+ add(gateway.models.video ? 'ready' : 'blocked', { id: 'video-provider', title: '官方视频服务', message: gateway.models.video ? `${gateway.models.video} 已配置。` : '当前官方服务没有可用的视频模型', executionMode: 'remote' });+ if (job.artifacts.some(artifact => artifact.kind === 'reference_image' && artifact.status === 'completed') && !gateway.capabilities?.video?.includes('image_to_video')) add('blocked', { id:'reference-image-capability',title:'参考图能力不匹配',message:'当前官方视频模型不支持参考图。',executionMode:'remote' });+ } else {+ const provider = readVideoProvider(job, config);+ const settings = config.video[provider];+ const hasKey = providerCredentials(settings, provider);+ if (!hasKey || !settings.model.trim() || !settings.baseUrl.trim()) add('blocked', {+ id: 'video-provider', title: '视频服务配置不完整', message: `请配置 ${provider} 的 Base URL、模型和凭据。`, executionMode: 'remote'+ }, { label: '打开 AI 服务设置', deepLink: '#/settings?tab=ai-services§ion=video' });+ else add('ready', { id: 'video-provider', title: '视频服务', message: `${provider} / ${settings.model} 已配置。`, executionMode: 'remote' });+ }}if (stage.executor === 'krillinai' && stage.id === 'subtitle' && (job.state.sourceType === 'file' || job.state.preferPlatformCaptions === false)) {const provider = capabilities.transcription.providers.find(candidate => candidate.provider === config.transcription.provider);@@ -409,13 +444,13 @@ function checkOpenAi(id: string,title: string,deepLink: string,- add: Parameters<typeof checkProviderConfig>[4]+ add: Parameters<typeof checkProviderConfig>[5]) {if (!value.baseUrl.trim() || !value.model.trim() || !value.apiKey.trim()) add('blocked', { id, title: `${title}配置不完整`, message: `请补全 ${title} 的 Base URL、模型和 API Key。`, executionMode: 'remote' }, { label: '打开 AI 服务设置', deepLink });else add('ready', { id, title, message: `${value.model} 已配置。`, executionMode: 'remote' });}-function checkTts(config: CreatorServicesConfig, provider: Exclude<CreatorServicesConfig['tts']['provider'], 'edge-tts'>, add: Parameters<typeof checkProviderConfig>[4]) {+function checkTts(config: CreatorServicesConfig, provider: Exclude<CreatorServicesConfig['tts']['provider'], 'edge-tts'>, add: Parameters<typeof checkProviderConfig>[5]) {const credentialsReady = provider === 'volcengine'? Boolean(config.tts.volcengine.appId.trim() && config.tts.volcengine.accessToken.trim()): Boolean(config.tts[provider].apiKey.trim());@@ -428,7 +463,7 @@ async function checkInputs(stage: CreatorTemplateStage,artifacts: Array<CreatorJob['artifacts'][number]>,missing: string[],- add: Parameters<typeof checkProviderConfig>[4]+ add: Parameters<typeof checkProviderConfig>[5]): Promise<void> {for (const kind of missing) {add('blocked', { id: `input-artifact:${kind}`, title: '前置产物缺失', message: `请先生成 ${kind},再启动 ${stage.id}。`, executionMode: 'local' }, { label: '返回上一步', deepLink: '#/settings?tab=diagnostics' });@@ -448,6 +483,7 @@ async function checkInputs(}function readTtsProvider(job: CreatorJob, config: CreatorServicesConfig): CreatorServicesConfig['tts']['provider'] {+ if (gatewayCreatorBinding(config)) return 'openai';const value = job.state.ttsProvider;return value === 'openai' || value === 'aliyun' || value === 'edge-tts' || value === 'minimax' || value === 'volcengine' ? value : config.tts.provider;}diff --git a/apps/daemon/src/creator/provider-requests.ts b/apps/daemon/src/creator/provider-requests.tsindex 4cbd7e34..868705cb 100644--- a/apps/daemon/src/creator/provider-requests.ts+++ b/apps/daemon/src/creator/provider-requests.ts@@ -37,7 +37,16 @@ export class CreatorProviderRequestLedger {private readonly issueService?: CreatorIssueService) {}+ findLatest(provider: string, requestKey: string) {+ return this.repository.getLatestProviderRequest(provider, requestKey);+ }++ findByRemoteTaskId(jobId: string, remoteTaskId: string) {+ return this.repository.listProviderRequests(jobId).filter(request => request.remoteTaskId === remoteTaskId);+ }+registerBeforeSubmit(input: {+ gateway?: CreatorProviderRequest['gateway'];jobId: string;provider: string;stageRunId: string;@@ -46,11 +55,12 @@ export class CreatorProviderRequestLedger {request: Record<string, CreatorJson>;billingSideEffect?: boolean;}): CreatorProviderRequest {- const requestHash = hashRequest(input.request);+ const requestHash = hashRequest(input.gateway ? { request: input.request, gateway: input.gateway } : input.request);return this.repository.transaction(() => {const latest = this.repository.getLatestProviderRequest(input.provider, input.requestKey);if (latest === undefined) {return this.repository.createProviderRequest({+ ...(input.gateway ? { gateway: input.gateway } : {}),jobId: input.jobId,provider: input.provider,stageRunId: input.stageRunId,@@ -81,6 +91,7 @@ export class CreatorProviderRequestLedger {);}return this.repository.createProviderRequest({+ ...(input.gateway ? { gateway: input.gateway } : {}),jobId: input.jobId,provider: input.provider,stageRunId: input.stageRunId,@@ -195,6 +206,7 @@ export class CreatorProviderRequestLedger {'abandoned_unknown');return this.repository.createProviderRequest({+ ...(current.gateway ? { gateway: current.gateway } : {}),jobId: current.jobId,provider: current.provider,stageRunId: current.stageRunId,@@ -319,7 +331,27 @@ export class CreatorProviderRequestLedger {result: 'succeeded' | 'failed' | 'canceled' | 'unknown',error?: unknown): boolean {- const issue = this.findProviderIssue(request, 'resolving');+ let issue = this.findProviderIssue(request, 'resolving');+ if (issue === undefined && result === 'succeeded' && !this.repository.listProviderRequests(request.jobId).some(other => (+ other.id !== request.id && other.provider === request.provider && other.stageRunId === request.stageRunId+ && other.scopeKey === request.scopeKey && isPendingRemote(other.status)+ ))) {+ issue = this.issueService?.list(request.jobId).find(candidate => (+ candidate.source === 'provider' && candidate.code === 'creator_provider_resolution_required'+ && candidate.status === 'open' && candidate.stageRunId === request.stageRunId+ && candidate.scopeKey === (request.scopeKey ?? undefined) && candidate.publicFacts?.provider === request.provider+ ));+ if (issue !== undefined) {+ this.issueService?.beginResolution({+ jobId: request.jobId,+ issueId: issue.id,+ resolutionAttemptId: request.id,+ associationKind: 'provider-request',+ associationId: request.id,+ stageRunId: request.stageRunId+ });+ }+ }if (issue === undefined) return false;this.issueService?.finishResolution({jobId: request.jobId,diff --git a/apps/daemon/src/creator/repository.ts b/apps/daemon/src/creator/repository.tsindex e9250840..ec22b07c 100644--- a/apps/daemon/src/creator/repository.ts+++ b/apps/daemon/src/creator/repository.ts@@ -31,10 +31,16 @@ import type {import { parseSrt } from './validators/srt.js';type RepositoryOptions = {+ serviceBinding?(): CreatorServiceBinding;idFactory?(prefix: string): string;now?(): string;};+export type CreatorServiceBinding = { source: 'manual' } | {+ source: 'gateway'; accountId: string; bindingVersion: string;+ models: Record<string, string>; capabilities: Record<string, string[]>;+};+export const CREATOR_ISSUE_UPSERT_SQL = `INSERT INTO creator_issues (id, job_id, diagnostic_id, code, source, category, severity, status,@@ -133,6 +139,7 @@ type CreateStageRunInput = {};type CreateProviderRequestInput = {+ gateway?: CreatorProviderRequest['gateway'];jobId: string;provider: string;stageRunId: string;@@ -146,6 +153,7 @@ type CreateProviderRequestInput = {};export type CreatorRepository = {+ getServiceBinding(jobId: string): CreatorServiceBinding;transaction<T>(operation: () => T): T;createJob(input: CreateJobInput): CreatorJob;getJob(id: string): CreatorJob | undefined;@@ -347,7 +355,7 @@ export function createCreatorRepository(const listProviderRequests = (jobId: string): CreatorProviderRequest[] => (db.prepare(`- SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash,+ SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash, gateway_binding_json,remote_task_id, billing_side_effect, status, result_artifact_id,generation, resubmission_of, created_at, updated_atFROM creator_provider_requests@@ -453,12 +461,16 @@ export function createCreatorRepository(createJob(input: CreateJobInput): CreatorJob {const id = idFactory('creator_job');const timestamp = now();+ const serviceBinding = options.serviceBinding?.() ?? { source: 'manual' as const };+ const state = serviceBinding.source === 'gateway'+ ? { ...input.state, officialModels: { ...serviceBinding.models, ...(isRecord(input.state.officialModels) ? input.state.officialModels : {}) } }+ : input.state;db.prepare(`INSERT INTO creator_jobs (id, creation_key, creation_fingerprint, project_id, template_id,template_version, status, revision, state_json, preset_origin_json,- agent_thread_id, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)+ agent_thread_id, created_at, updated_at, service_binding_json+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`).run(id,input.creationKey ?? null,@@ -467,17 +479,23 @@ export function createCreatorRepository(input.templateId,input.templateVersion,input.status,- JSON.stringify(input.state),+ JSON.stringify(state),input.presetOrigin === undefined || input.presetOrigin === null? null: JSON.stringify(input.presetOrigin),input.agentThreadId ?? null,timestamp,- timestamp+ timestamp,+ JSON.stringify(serviceBinding));return getJob(id)!;},getJob,+ getServiceBinding(jobId) {+ const row = db.prepare('SELECT service_binding_json FROM creator_jobs WHERE id = ?').get(jobId) as { service_binding_json: string } | undefined;+ if (!row) throw new Error('Creator job was not found');+ return JSON.parse(row.service_binding_json) as CreatorServiceBinding;+ },getJobByCreationKey(creationKey: string): CreatorJob | undefined {const row = db.prepare(`SELECT id@@ -697,8 +715,8 @@ export function createCreatorRepository(INSERT INTO creator_provider_requests (id, job_id, provider, stage_run_id, scope_key, request_key, request_hash,remote_task_id, billing_side_effect, status, result_artifact_id,- generation, resubmission_of, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?, ?)+ generation, resubmission_of, created_at, updated_at, gateway_binding_json+ ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, NULL, ?, ?, ?, ?, ?)`).run(id,providerInput.jobId,@@ -712,13 +730,14 @@ export function createCreatorRepository(providerInput.generation ?? 1,providerInput.resubmissionOf ?? null,timestamp,- timestamp+ timestamp,+ providerInput.gateway === undefined ? null : JSON.stringify(providerInput.gateway));return listProviderRequests(providerInput.jobId).find(item => item.id === id)!;},getProviderRequest(id): CreatorProviderRequest | undefined {const row = db.prepare(`- SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash,+ SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash, gateway_binding_json,remote_task_id, billing_side_effect, status, result_artifact_id,generation, resubmission_of, created_at, updated_atFROM creator_provider_requests@@ -728,7 +747,7 @@ export function createCreatorRepository(},getLatestProviderRequest(provider, requestKey): CreatorProviderRequest | undefined {const row = db.prepare(`- SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash,+ SELECT id, job_id, provider, stage_run_id, scope_key, request_key, request_hash, gateway_binding_json,remote_task_id, billing_side_effect, status, result_artifact_id,generation, resubmission_of, created_at, updated_atFROM creator_provider_requests@@ -1519,6 +1538,7 @@ type ArtifactRow = {};type ProviderRequestRow = {+ gateway_binding_json: string | null;id: string;job_id: string;provider: string;@@ -1538,6 +1558,7 @@ type ProviderRequestRow = {function hydrateProviderRequest(row: ProviderRequestRow): CreatorProviderRequest {return {+ ...(row.gateway_binding_json === null ? {} : { gateway: JSON.parse(row.gateway_binding_json) as NonNullable<CreatorProviderRequest['gateway']> }),id: row.id,jobId: row.job_id,provider: row.provider,diff --git a/apps/daemon/src/creator/service.ts b/apps/daemon/src/creator/service.tsindex 347b0192..f29ebffa 100644--- a/apps/daemon/src/creator/service.ts+++ b/apps/daemon/src/creator/service.ts@@ -1148,6 +1148,9 @@ export function createCreatorService(input: {if (stage === undefined) {throw new CreatorServiceError('creator_stage_not_found', 'Creator stage was not found');}+ if (current.templateId === 'image-generation' && providerRequestLedger.unresolvedForStage({ jobId, stageId, scopeKey: typeof parsedInput.scopeKey === 'string' ? parsedInput.scopeKey : null }).length > 0) {+ throw new CreatorServiceError('creator_provider_resolution_required', 'Resolve the previous paid image request before starting another generation');+ }for (const field of ['baseResultVersion', 'inputResultVersion', 'targetResultVersion'] as const) {readResultVersion(current, parsedInput[field], field);}diff --git a/apps/daemon/src/creator/smart-dubbing/executor.ts b/apps/daemon/src/creator/smart-dubbing/executor.tsindex 14525239..e783b412 100644--- a/apps/daemon/src/creator/smart-dubbing/executor.ts+++ b/apps/daemon/src/creator/smart-dubbing/executor.ts@@ -18,25 +18,29 @@ import { CreatorExecutorError } from '../executor.js';export function createSmartDubbingExecutor(input: {ttsService: Pick<KrillinTtsService, 'synthesize'>;+ isOfficial?(): boolean;}): CreatorExecutor {return {id: 'smart-dubbing',async run(stage) {stage.reportProgress({ phase: 'validating', percent: 5 });const request = readRequest(stage.job.state);+ const official = input.isOfficial?.() === true;+ if (official && (request.style !== 'natural' || request.speed !== 1)) throw new CreatorExecutorError('unsupported_capability', '当前官方语音模型只支持自然表达和默认语速');if (stage.signal.aborted) {throw new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled');}stage.reportProgress({ phase: 'generating_voice', percent: 20 });try {const synthesis = await input.ttsService.synthesize({+ logicalId:stage.stageRun.id,text: request.text,...(request.provider === undefined ? {} : { provider: request.provider }),...(request.model === undefined ? {} : { model: request.model }),...(request.voiceCode === undefined ? {} : { voiceId: request.voiceCode }),format: request.format,speed: request.speed,- instructions: smartDubbingInstructions(request.style),+ instructions: official ? undefined : smartDubbingInstructions(request.style),signal: stage.signal});if (stage.signal.aborted) {diff --git a/apps/daemon/src/creator/stickman/audio-executor.ts b/apps/daemon/src/creator/stickman/audio-executor.tsindex 20c0299a..eb2e37aa 100644--- a/apps/daemon/src/creator/stickman/audio-executor.ts+++ b/apps/daemon/src/creator/stickman/audio-executor.ts@@ -14,6 +14,7 @@ import {stickmanScriptManifestSchema} from './contracts.js';import { stickmanEdgeTtsVoiceForLanguage } from './tts.js';+import { gatewayCreatorBinding } from '../../gateway/creator-service-source.js';type Synthesize = Pick<KrillinTtsService, 'synthesize'>['synthesize'];type EdgeTtsSynthesisResult = {@@ -106,9 +107,11 @@ async function synthesizeSegment(const segmentIndex = script.segments.findIndex(candidate => candidate.id === scopeKey);const segmentCount = script.segments.length;const config = await input.configStore.read();+ const gateway = gatewayCreatorBinding(config);const selection = resolveTtsSelection(stage, config);const requestKey = `${stage.job.id}:narration:${scopeKey}:${fingerprint}`;- const ledger = input.ledger.registerBeforeSubmit({+ let ledger = input.ledger.registerBeforeSubmit({+ ...(gateway ? { gateway:{ accountId:gateway.accountId, bindingVersion:gateway.bindingVersion, logicalId:requestKey } } : {}),jobId: stage.job.id,provider: selection.provider,stageRunId: stage.stageRun.id,@@ -122,7 +125,7 @@ async function synthesizeSegment(format: selection.provider === 'edge-tts' ? 'mp3' : 'wav'}});- input.ledger.markSubmitting(ledger.id);+ ledger = input.ledger.markSubmitting(ledger.id);stage.reportProgress({phase: 'synthesizing',percent: Math.round(((segmentIndex + 0.1) / segmentCount) * 100),@@ -144,11 +147,14 @@ async function synthesizeSegment(: await synthesize({text: segment.narration,provider: selection.provider,+ logicalId: ledger.gateway?.logicalId ?? ledger.id,+ ...(gateway ? { onGatewayRequest: (id: string) => { ledger = input.ledger.markWaitingRemote(ledger.id, id); } } : {}),model: selection.model,voiceId: selection.voiceId,format: 'wav',signal: stage.signal});+ if (gateway) ledger = input.ledger.markSucceeded(ledger.id);const path = join(stage.workdir, `${scopeKey}.${result.format}`);await writeFile(path, result.content);const media = await probe(path, input.ffprobePath);@@ -158,7 +164,7 @@ async function synthesizeSegment(`Narration for ${scopeKey} is not a valid audio file`);}- input.ledger.markSucceeded(ledger.id);+ if (!gateway) ledger = input.ledger.markSucceeded(ledger.id);return {outputs: [{kind: 'narration_audio',@@ -189,7 +195,10 @@ async function synthesizeSegment(}};} catch (error) {- input.ledger.markFailed(ledger.id, error);+ if (['submitting', 'waiting_remote'].includes(ledger.status)) {+ if (gateway) input.ledger.markUnknownRemoteAcceptance(ledger.id);+ else input.ledger.markFailed(ledger.id, error);+ }if (error instanceof CreatorExecutorError) throw error;if (hasErrorCode(error)) {throw new CreatorExecutorError(error.code, error.message);@@ -278,7 +287,8 @@ async function buildAudioTiming(}function resolveTtsSelection(stage: CreatorExecutorInput, config: CreatorServicesConfig) {- const provider = stage.job.state.ttsProvider === 'openai'+ const gateway = gatewayCreatorBinding(config);+ const provider = gateway ? 'openai' : stage.job.state.ttsProvider === 'openai'|| stage.job.state.ttsProvider === 'aliyun'|| stage.job.state.ttsProvider === 'edge-tts'|| stage.job.state.ttsProvider === 'minimax'@@ -301,7 +311,7 @@ function resolveTtsSelection(stage: CreatorExecutorInput, config: CreatorService};}const providerConfig = config.tts[provider];- const model = typeof stage.job.state.ttsModel === 'string' && stage.job.state.ttsModel.trim()+ const model = !gateway && typeof stage.job.state.ttsModel === 'string' && stage.job.state.ttsModel.trim()? stage.job.state.ttsModel.trim(): providerConfig.model;const voiceId = typeof stage.job.state.voiceCode === 'string' && stage.job.state.voiceCode.trim()diff --git a/apps/daemon/src/creator/stickman/image-executor.ts b/apps/daemon/src/creator/stickman/image-executor.tsindex 041cdf59..bb125cd8 100644--- a/apps/daemon/src/creator/stickman/image-executor.ts+++ b/apps/daemon/src/creator/stickman/image-executor.ts@@ -18,6 +18,7 @@ import {type CodexNativeImageRuntime} from '../../image-generation/provider.js';import { resolveCreatorImageSettings } from '../image-settings.js';+import { gatewayCreatorBinding } from '../../gateway/creator-service-source.js';import type { CreatorExecutor } from '../executor.js';import { CreatorExecutorError } from '../executor.js';import { CreatorProviderRequestLedger } from '../provider-requests.js';@@ -246,16 +247,21 @@ export function createStickmanImageExecutor(input: {...(previousShotImage === undefined ? [] : [previousShotImage.id])])];const config = await input.configStore.read();+ const gateway = gatewayCreatorBinding(config);const imageSettings = resolveCreatorImageSettings({config,- provider: stage.job.state.provider,+ provider: gateway ? 'openai' : stage.job.state.provider,candidateCount: 1,fallbackCandidateCount: 1,maxCandidateCount: 1});const { provider } = imageSettings;const quality = readQuality(stage.job.state.quality);- assertReferenceImageSupport(provider, referenceImages.length);+ if (gateway) {+ if (!gateway.capabilities?.image?.includes('edit') || referenceImages.length > 1) {+ throw new CreatorExecutorError('creator_stickman_image_provider_unsupported', '当前官方图像服务仅支持 1 张参考图,无法执行此镜头');+ }+ } else assertReferenceImageSupport(provider, referenceImages.length);const model = imageSettings.model;if (promptPackArtifact.metadata.contract !== STICKMAN_IMAGE_PROMPT_CONTRACT@@ -289,7 +295,8 @@ export function createStickmanImageExecutor(input: {].join('\n');const candidateRequest = { ...request, prompt: candidatePrompt };const requestKey = `${stage.job.id}:images:${scopeKey}:${inputFingerprint}:candidate:${candidateAttempt}`;- const ledger = input.ledger.registerBeforeSubmit({+ let ledger = input.ledger.registerBeforeSubmit({+ ...(gateway ? { gateway: { accountId: gateway.accountId, bindingVersion: gateway.bindingVersion, logicalId: requestKey } } : {}),jobId: stage.job.id,provider,stageRunId: stage.stageRun.id,@@ -316,7 +323,7 @@ export function createStickmanImageExecutor(input: {imagePromptContract: STICKMAN_IMAGE_PROMPT_CONTRACT}});- input.ledger.markSubmitting(ledger.id);+ ledger = input.ledger.markSubmitting(ledger.id);stage.reportProgress({phase: candidateAttempt === 1 ? 'submitting' : 'retrying_candidate',percent: Math.round((@@ -330,6 +337,7 @@ export function createStickmanImageExecutor(input: {let result: Awaited<ReturnType<typeof generate>>;try {result = await generate(candidateRequest, config, {+ ...(gateway ? { logicalId: requestKey, onGatewayRequest: (id: string) => { ledger = input.ledger.markWaitingRemote(ledger.id, id); } } : {}),signal: stage.signal,onProgress: progress => stage.reportProgress({...progress, completed: shotIndex, failed: candidateAttempt - 1, total: shotCount@@ -342,9 +350,12 @@ export function createStickmanImageExecutor(input: {? {}: { codexNative: input.codexNative })});- input.ledger.markSucceeded(ledger.id);+ ledger = input.ledger.markSucceeded(ledger.id);} catch (error) {- input.ledger.markFailed(ledger.id, error);+ if (['submitting', 'waiting_remote'].includes(ledger.status)) {+ if (gateway) input.ledger.markUnknownRemoteAcceptance(ledger.id);+ else input.ledger.markFailed(ledger.id, error);+ }throw error;}const image = result.contents[0];diff --git a/apps/daemon/src/creator/templates/image-generation.ts b/apps/daemon/src/creator/templates/image-generation.tsindex 7138a78a..b1432fde 100644--- a/apps/daemon/src/creator/templates/image-generation.ts+++ b/apps/daemon/src/creator/templates/image-generation.ts@@ -48,6 +48,8 @@ function createImageGenerationTemplateDefinition(actions: [{ id: 'update-settings', inputSchema: record, allowedStages: ['generate'] },{ id: 'run-stage', inputSchema: record, allowedStages: ['generate'] },+ { id: 'retry-stage', inputSchema: record, allowedStages: ['generate'] },+ { id: 'resolve-provider-request', inputSchema: record, allowedStages: ['generate'] },{ id: 'undo-action', inputSchema: record, allowedStages: ['generate'] }],outputs: [{ kind: 'generated_image', required: true }],diff --git a/apps/daemon/src/creator/templates/video-generation.ts b/apps/daemon/src/creator/templates/video-generation.tsindex 90c82728..2711829e 100644--- a/apps/daemon/src/creator/templates/video-generation.ts+++ b/apps/daemon/src/creator/templates/video-generation.ts@@ -1,4 +1,4 @@-import { creatorPromptMaxLength } from '@opencreator/protocol';+import { creatorPromptMaxLength, videoGenerationSizes, videoGenerationDurations } from '@opencreator/protocol';import { z } from 'zod';import type { CreatorTemplateDefinition } from './types.js';@@ -13,17 +13,15 @@ export function createVideoGenerationTemplate(): CreatorTemplateDefinition {prompt: z.string().max(creatorPromptMaxLength).default(''),provider: z.enum(['seedance', 'kling', 'veo']).default('seedance'),model: z.string().trim().min(1).max(200).optional(),- size: z.enum(['1280x720', '720x1280', '1024x1024']).default('1280x720'),- duration: z.union([- z.literal(4),- z.literal(5),- z.literal(6),- z.literal(8),- z.literal(10)- ]).default(5),+ size: z.string().regex(/^(?:\d+x\d+|[A-Za-z0-9._-]+@\d+:\d+)$/).default('1280x720'),+ duration: z.number().int().positive().max(600).default(5),referenceImageArtifactId: z.string().nullable().default(null),currentStage: z.string().nullable().default(null)- }).passthrough() as never,+ }).passthrough().superRefine((value, context) => {+ if (value.officialModels !== undefined) return;+ if (!(videoGenerationSizes as readonly string[]).includes(value.size)) context.addIssue({ code: 'custom', path: ['size'], message: 'Unsupported custom video size' });+ if (!(videoGenerationDurations as readonly number[]).includes(value.duration)) context.addIssue({ code: 'custom', path: ['duration'], message: 'Unsupported custom video duration' });+ }) as never,stages: [{id: 'generate',executor: 'video',diff --git a/apps/daemon/src/creator/video/executor.ts b/apps/daemon/src/creator/video/executor.tsindex 77ad3f38..ea79d9c7 100644--- a/apps/daemon/src/creator/video/executor.ts+++ b/apps/daemon/src/creator/video/executor.ts@@ -2,6 +2,7 @@ import type {CreateVideoGenerationRequest,CreatorArtifact,CreatorJson,+ CreatorProviderRequest,VideoGenerationDuration,VideoGenerationProvider,VideoGenerationResult,@@ -12,6 +13,7 @@ import { extname, join } from 'node:path';import type { MediaProbe } from '../validators/media.js';import type { CreatorExecutor, CreatorExecutorInput } from '../executor.js';import { CreatorExecutorError } from '../executor.js';+import type { CreatorProviderRequestLedger } from '../provider-requests.js';import {VideoGenerationError,type VideoGenerationService@@ -21,6 +23,7 @@ type ProbeVideo = (path: string) => Promise<MediaProbe>;const MAX_CONSECUTIVE_REFRESH_FAILURES = 3;export function createVideoExecutor(input: {+ ledger?: CreatorProviderRequestLedger;service: VideoGenerationService;probeVideo: ProbeVideo;pollIntervalMs?: number;@@ -32,6 +35,7 @@ export function createVideoExecutor(input: {return {id: 'video',async run(stage) {+ let providerRequest: CreatorProviderRequest | undefined;try {stage.reportProgress({status: 'running',@@ -60,6 +64,14 @@ export function createVideoExecutor(input: {}result = await input.service.create(request, {signal: stage.signal,+ logicalId: stage.stageRun.id,+ onGatewayBinding: gateway => {+ providerRequest = input.ledger?.registerBeforeSubmit({ jobId:stage.job.id, stageRunId:stage.stageRun.id, provider:'opencreator-gateway-video', requestKey:gateway.logicalId, gateway,+ request:{prompt:request.prompt,duration:request.duration,size:request.size,reference:request.referenceImage?.data ?? null} });+ if (providerRequest) providerRequest = input.ledger!.markSubmitting(providerRequest.id);+ },+ onGatewayRequest: id => { if (providerRequest) providerRequest = input.ledger!.markWaitingRemote(providerRequest.id,id); },+ onPending: id => stage.reportProgress({ phase: 'submitting', videoGenerationResultId: id }),onDownloadStart: () => reportDownloading(stage)});stage.reportProgress({@@ -69,6 +81,10 @@ export function createVideoExecutor(input: {upstreamModel: result.model});} else {+ const binding = await input.service.getGatewayBinding?.(resumedResultId);+ providerRequest = binding ? stage.job.providerRequests.find(value => value.provider === 'opencreator-gateway-video'+ && value.gateway?.logicalId === binding.logicalId && value.gateway.accountId === binding.accountId) : undefined;+ if (providerRequest && binding?.requestId && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(providerRequest.status)) providerRequest = input.ledger!.markWaitingRemote(providerRequest.id, binding.requestId);result = await input.service.get(resumedResultId);stage.reportProgress({...remoteProgress(result),@@ -85,6 +101,7 @@ export function createVideoExecutor(input: {try {result = await input.service.refresh(result.id, {signal: stage.signal,+ onGatewayRequest: id => { if (providerRequest && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(providerRequest.status)) providerRequest = input.ledger!.markWaitingRemote(providerRequest.id, id); },onDownloadStart: () => reportDownloading(stage)});consecutiveRefreshFailures = 0;@@ -117,6 +134,7 @@ export function createVideoExecutor(input: {}if (result.status === 'failed') {+ if (providerRequest && input.ledger && ['submitting', 'waiting_remote'].includes(providerRequest.status)) providerRequest = input.ledger.markFailed(providerRequest.id);throw new CreatorExecutorError('creator_video_generation_failed',result.error || 'The video provider failed to generate a video',@@ -125,6 +143,11 @@ export function createVideoExecutor(input: {);}+ if (providerRequest && input.ledger && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(providerRequest.status)) {+ if (providerRequest.status === 'unknown_remote_acceptance' && providerRequest.remoteTaskId) providerRequest = input.ledger.markWaitingRemote(providerRequest.id, providerRequest.remoteTaskId);+ providerRequest = input.ledger.markSucceeded(providerRequest.id);+ }+stage.reportProgress({status: 'running',phase: 'collecting_output',@@ -192,6 +215,7 @@ export function createVideoExecutor(input: {}};} catch (error) {+ if (providerRequest && input.ledger && ['submitting', 'waiting_remote'].includes(providerRequest.status)) input.ledger.markUnknownRemoteAcceptance(providerRequest.id);throw creatorVideoError(error);}}@@ -209,11 +233,14 @@ async function videoRequest();}const reference = stage.inputArtifacts.find(artifact => artifact.kind === 'reference_image');+ const officialModels = stage.job.state.officialModels;+ const model = officialModels && typeof officialModels === 'object' && !Array.isArray(officialModels)+ ? readString(officialModels.video) : readString(stage.job.state.model);return {prompt,provider: readProvider(stage.job.state.provider),- ...(readString(stage.job.state.model)- ? { model: readString(stage.job.state.model) }+ ...(model+ ? { model }: {}),size: readSize(stage.job.state.size),duration: readDuration(stage.job.state.duration),@@ -357,10 +384,12 @@ function readProvider(value: CreatorJson | undefined): VideoGenerationProvider {}function readSize(value: CreatorJson | undefined): VideoGenerationSize {+ if (typeof value === 'string' && /^(?:\d+x\d+|[A-Za-z0-9._-]+@\d+:\d+)$/.test(value)) return value as VideoGenerationSize;return value === '720x1280' || value === '1024x1024' ? value : '1280x720';}function readDuration(value: CreatorJson | undefined): VideoGenerationDuration {+ if (typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 600) return value;return value === 4 || value === 6 || value === 8 || value === 10 ? value : 5;}diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.tsnew file mode 100644index 00000000..e4d8515f--- /dev/null+++ b/apps/daemon/src/gateway/account-service.ts@@ -0,0 +1,388 @@+import type { GatewayAccountState, GatewayBalanceSnapshot, GatewayBalanceState, ServiceSource } from '@opencreator/protocol';+import { z } from 'zod';+import { createGatewayConfigStore, type GatewayCredentials } from './config-store.js';+import { accountSchema, bootstrapSchema, catalogSchema, GatewayError, type GatewayBootstrap, type GatewayClient, type GatewayDeviceGrant } from './client.js';+import { officialModelPolicy, withModelCatalog, type OfficialModelAccess } from './model-access.js';++export function createGatewayAccountService(input: {+ dataDir: string; client: GatewayClient;+ activateRuntime(bootstrap: GatewayBootstrap): Promise<void>;+ closeRuntime(): Promise<void>;+ hasActiveTasks(): boolean;+ hasPendingTasks?(): boolean;+ automaticPolling?: boolean;+ modelAccess?: OfficialModelAccess;+}) {+ 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 generation = 0;+ let pollTimer: NodeJS.Timeout | undefined;+ let initialization: Promise<void> | undefined;+ let refreshWork: Promise<void> | undefined;+ let profileWork: Promise<void> | undefined;+ let profileUpdatedAt = 0;+ let catalogWork: Promise<void> | undefined;+ let catalogUpdatedAt = 0;+ let balance: GatewayBalanceSnapshot | null = null;+ let mutation = Promise.resolve();+ let selectedModels: Record<string, string> = {};+ let localUses = 0;+ let probeUses = 0;+ let accessWork: Promise<void> | undefined;+ let accessController: AbortController | undefined;+ let accessUpdatedAt = 0;+ let accessBlocked = false;+ let runtimeTextModel: string | undefined;+ let accessPaused = false;+ let closing = false;+ let usageMutation = Promise.resolve();+ let usageTimer: NodeJS.Timeout | undefined;+ const saveConfiguration = () => store.writeConfiguration({ source: state.source, bindingVersion: state.bindingVersion, selectedModels });+ function serialize<T>(work: () => Promise<T>): Promise<T> { const result = mutation.then(work); mutation = result.then(() => undefined, () => undefined); return result; }+ function fail(error: unknown) { state.activationState = 'blocked'; state.activationError = { code: error instanceof GatewayError ? error.code : 'services_not_ready', message: '官方服务尚未就绪,请重试' }; }+ function assertIdle() { if (localUses > 0 || input.hasActiveTasks()) throw new GatewayError('active_tasks', 409); }+ function assertSignedIn() { if (!credentials || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401); return credentials; }+ async function visibleBootstrap(bootstrap: GatewayBootstrap) {+ const eligible = withModelCatalog(bootstrap, officialModelPolicy(bootstrap.models));+ return input.modelAccess && eligible.transport === 'openrouter-direct' ? input.modelAccess.prepare(eligible) : eligible;+ }+ function needsAccessibleRuntime() {+ return input.modelAccess && credentials?.transport === 'openrouter-direct' && state.authState === 'signed_in'+ && state.source === 'gateway' && !closing && !accessPaused && (state.activationState === 'ready' || accessBlocked)+ && (!credentials.defaults?.text || accessBlocked || runtimeTextModel !== credentials.defaults.text);+ }+ async function synchronizeAccessibleRuntime() {+ if (!needsAccessibleRuntime() || !credentials) return;+ if (!credentials.defaults?.text) { accessBlocked = true; fail(new GatewayError('services_not_ready')); return; }+ if ((!accessBlocked && runtimeTextModel === credentials.defaults.text) || localUses > 0 || input.hasActiveTasks() || input.hasPendingTasks?.()) return;+ const next = { ...bootstrapSchema.parse(credentials), models: state.models };+ try {+ await input.activateRuntime(next);+ runtimeTextModel = next.defaults.text; accessBlocked = false;+ state.bindingVersion = next.bindingVersion; state.activationState = 'ready'; state.activationError = null;+ await saveConfiguration();+ } catch (error) { accessBlocked = true; runtimeTextModel = undefined; fail(error); await input.closeRuntime(); }+ }+ function scheduleModelAccess() {+ if (!input.modelAccess || closing || accessPaused || accessWork || credentials?.transport !== 'openrouter-direct' || state.authState !== 'signed_in'+ || (state.activationState !== 'ready' && !accessBlocked) || Date.now() - accessUpdatedAt < 30_000) return;+ accessUpdatedAt = Date.now();+ const controller = new AbortController(); accessController = controller;+ accessWork = (async () => {+ const use = await acquireModelUse(true);+ try {+ const original = bootstrapSchema.parse(assertSignedIn()); const expected = generation;+ await input.modelAccess!.refresh(original, controller.signal, async () => {+ await serialize(async () => {+ if (controller.signal.aborted || closing || generation !== expected || state.authState !== 'signed_in'+ || credentials?.account?.id !== original.account.id || credentials.keyVersion !== original.keyVersion) return;+ const next = input.modelAccess!.filter(withModelCatalog(bootstrapSchema.parse(credentials), officialModelPolicy(credentials.models ?? [])));+ if (JSON.stringify(state.models) !== JSON.stringify(next.models) || JSON.stringify(state.selectedModels) !== JSON.stringify(next.defaults)) {+ credentials = { ...credentials, defaults: next.defaults };+ selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels }; state.models = next.models;+ await store.writeCredentials(credentials); await saveConfiguration();+ }+ await synchronizeAccessibleRuntime();+ });+ });+ } finally { await use.release(); }+ })().catch(() => undefined).finally(() => { if (accessController === controller) accessController = undefined; accessWork = undefined; });+ }+ function initialize(): Promise<void> {+ initialization ??= load();+ return initialization;+ }+ async function load() {+ try {+ const config = await store.readConfiguration();+ selectedModels = config.selectedModels ?? {};+ state.selectedModels = { ...selectedModels };+ credentials = await store.readCredentials();+ state.source = credentials ? 'gateway' : 'manual';+ await saveConfiguration();+ if (!credentials) return;+ state.account = credentials.account ?? null; state.authState = 'signed_in'; state.models = credentials.models ?? [];+ await refresh();+ await activateCurrent();+ } catch (error) { fail(error); }+ }+ async function refresh() {+ if (refreshWork) return refreshWork;+ refreshWork = (async () => {+ const original = assertSignedIn(); const expected = generation;+ if (Date.parse(original.accessExpiresAt) > Date.now() + 60_000) return;+ try {+ const tokens = await input.client.refresh(original.refreshToken);+ if (generation !== expected || credentials !== original || state.authState !== 'signed_in') return;+ credentials = { ...original, ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };+ await store.writeCredentials(credentials);+ } catch (error) {+ if (error instanceof GatewayError && error.status === 401) { state.authState = 'expired'; await input.closeRuntime(); }+ throw error;+ }+ })();+ try { await refreshWork; } finally { refreshWork = undefined; }+ }+ async function activateCurrent() {+ 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');+ for (const [modality, model] of Object.entries(selectedModels)) {+ if (bootstrap.models.some(candidate => candidate.modality === modality && candidate.id === model)) bootstrap.defaults[modality] = model;+ }+ const visible = await visibleBootstrap(bootstrap);+ if (generation !== expected || state.authState !== 'signed_in') return;+ selectedModels = { ...visible.defaults }; state.selectedModels = { ...selectedModels };+ credentials = { ...original, ...bootstrap, defaults: visible.defaults };+ await store.writeCredentials(credentials);+ state.account = bootstrap.account; state.models = visible.models;+ accessBlocked = !visible.defaults.text;+ if (accessBlocked) throw new GatewayError('services_not_ready');+ await input.activateRuntime(visible);+ runtimeTextModel = visible.defaults.text;+ if (generation !== expected || state.authState !== 'signed_in') { await input.closeRuntime(); return; }+ state.bindingVersion = bootstrap.bindingVersion;+ catalogUpdatedAt = Date.now();+ await saveConfiguration();+ state = { ...state, source: 'gateway', activationState: 'ready', account: bootstrap.account, models: visible.models, bindingVersion: bootstrap.bindingVersion, activationError: null };+ await reportUsage();+ startUsageHeartbeat();+ } catch (error) { runtimeTextModel = undefined; fail(error); await input.closeRuntime(); }+ scheduleModelAccess();+ }+ async function readProfile() {+ if (!credentials || state.authState !== 'signed_in') return;+ if (profileWork) return profileWork;+ if (Date.now() - profileUpdatedAt < 30_000) return;+ profileUpdatedAt = Date.now();+ profileWork = (async () => {+ await refresh();+ const original = assertSignedIn(); const expected = generation;+ const profile = z.object({ account: accountSchema }).parse(await input.client.request('/api/v1/me', original.accessToken));+ await serialize(async () => {+ if (expected !== generation || credentials !== original || state.authState !== 'signed_in') return;+ if (original.account && profile.account.id !== original.account.id) throw new GatewayError('account_mismatch');+ const next = { ...original, account: profile.account };+ await store.writeCredentials(next);+ credentials = next; state.account = profile.account;+ });+ })().catch(() => undefined);+ try { await profileWork; }+ finally { profileWork = undefined; }+ }+ async function readCatalog() {+ if (!credentials || state.authState !== 'signed_in' || state.source !== 'gateway' || state.activationState !== 'ready') return;+ if (catalogWork) return catalogWork;+ if (input.hasActiveTasks() || input.hasPendingTasks?.() || Date.now() - catalogUpdatedAt < 30_000) return;+ catalogUpdatedAt = Date.now();+ catalogWork = (async () => {+ await refresh();+ const original = assertSignedIn(); const expected = generation;+ const catalog = catalogSchema.parse(await input.client.request('/api/v1/client/models', original.accessToken));+ await serialize(async () => {+ if (generation !== expected || credentials !== original || state.source !== 'gateway' || state.authState !== 'signed_in' || input.hasActiveTasks() || input.hasPendingTasks?.()) return;+ if (original.rotationPending || JSON.stringify(catalog.models) !== JSON.stringify(original.models)) await activateCurrent();+ });+ })().catch(() => undefined);+ try { await catalogWork; } finally { catalogWork = undefined; }+ }+ function schedulePoll(id: string, seconds: number) {+ if (input.automaticPolling === false) return;+ clearTimeout(pollTimer);+ pollTimer = setTimeout(() => { void pollAuthorization(id).catch(() => undefined); }, Math.max(5, seconds) * 1000); pollTimer.unref();+ }+ async function cancelAuthorization() {+ clearTimeout(pollTimer); const old = attempt; attempt = undefined; generation++;+ if (old) await input.client.cancelDevice(old.attemptId, old.deviceSecret).catch(() => undefined);+ if (state.authState === 'authorizing') {+ state.authState = old?.previousAuthState ?? (credentials ? 'expired' : 'signed_out');+ state.source = credentials ? 'gateway' : 'manual';+ state.activationState = credentials ? 'blocked' : 'inactive';+ await saveConfiguration();+ }+ }+ async function startAuthorization() {+ await initialize(); assertIdle();+ 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 };+ state.source = 'gateway'; state.authState = 'authorizing'; state.activationState = 'loading'; state.activationError = null;+ await saveConfiguration();+ schedulePoll(grant.attemptId, grant.interval);+ return { attemptId: grant.attemptId, authorizationUrl: grant.authorizationUrl, expiresAt: new Date(attempt.expiresAt).toISOString() };+ }+ async function pollAuthorization(id: string) {+ const current = attempt; if (!current || current.attemptId !== id) return;+ if (current.expiresAt <= Date.now()) { await cancelAuthorization(); state.activationError = { code: 'device_expired', message: '登录授权已过期,请重新登录' }; return; }+ try {+ const tokens = await input.client.pollDevice(id, current.deviceSecret);+ if (generation !== current.generation || attempt !== current) { await input.client.logout(tokens.accessToken).catch(() => undefined); return; }+ await serialize(async () => {+ if (generation !== current.generation || attempt !== current) return;+ if (credentials?.account && input.hasPendingTasks?.()) {+ const profile = z.object({ account: accountSchema }).parse(await input.client.request('/api/v1/me', tokens.accessToken));+ if (profile.account.id !== credentials.account.id) {+ await input.client.logout(tokens.accessToken).catch(() => undefined);+ throw new GatewayError('account_mismatch', 409);+ }+ }+ credentials = { ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };+ await store.writeCredentials(credentials);+ 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; }+ fail(error); await cancelAuthorization();+ }+ }+ async function readModelCredentials(probing = false): Promise<{ accountId: string; modelKey: string; keyVersion: string; bindingVersion: string; baseUrl: string; transport?: GatewayBootstrap['transport']; models: GatewayBootstrap['models']; defaults: Record<string, string> }> {+ await initialize(); await refresh();+ const value = assertSignedIn();+ if (state.source !== 'gateway' || (!probing && state.activationState !== 'ready') || !value.account || !value.modelKey || !value.keyVersion || !value.bindingVersion || !value.baseUrl || !value.models || !value.defaults) throw new GatewayError('services_not_ready');+ return { accountId: value.account.id, modelKey: value.modelKey, keyVersion: value.keyVersion, bindingVersion: value.bindingVersion, baseUrl: value.baseUrl, transport: value.transport, models: structuredClone(state.models), defaults: { ...value.defaults } };+ }+ const modelCredentials = () => readModelCredentials();+ function reportUsage() {+ const result = usageMutation.then(async () => {+ if (!credentials?.keyRotation || !credentials.keyVersion || state.authState !== 'signed_in') return undefined;+ await refresh();+ const current = assertSignedIn(); const expected = generation;+ const value = z.object({ keyVersion: z.string().min(1) }).parse(await input.client.request('/api/v1/client/usage', current.accessToken, {+ keyVersion: current.keyVersion, installationId: await store.readDeviceID(), busy: localUses > 0 || probeUses > 0 || input.hasActiveTasks(), pending: input.hasPendingTasks?.() === true+ }));+ if (generation !== expected || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);+ return value.keyVersion;+ });+ usageMutation = result.then(() => undefined, () => undefined);+ return result;+ }+ function startUsageHeartbeat() {+ if (usageTimer || !credentials?.keyRotation || input.automaticPolling === false) return;+ usageTimer = setInterval(() => { void reportUsage().catch(() => undefined); }, 10_000);+ usageTimer.unref();+ }+ async function synchronizeBinding() {+ const current = assertSignedIn(); const expected = generation;+ const bootstrap = await input.client.bootstrap(current.accessToken, { rotate: false });+ if (generation !== expected || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);+ if (bootstrap.account.id !== current.account?.id) throw new GatewayError('account_mismatch');+ for (const [modality, model] of Object.entries(selectedModels)) {+ if (bootstrap.models.some(candidate => candidate.modality === modality && candidate.id === model)) bootstrap.defaults[modality] = model;+ }+ const visible = await visibleBootstrap(bootstrap);+ credentials = { ...assertSignedIn(), ...bootstrap, defaults: visible.defaults };+ await store.writeCredentials(credentials);+ state.bindingVersion = bootstrap.bindingVersion; state.models = visible.models;+ selectedModels = { ...visible.defaults }; state.selectedModels = { ...selectedModels };+ await saveConfiguration();+ }+ async function acquireModelUse(probing = false) {+ await readModelCredentials(probing);+ if (probing) probeUses++; else localUses++;+ let released = false;+ const release = async () => {+ if (released) return;+ released = true; if (probing) probeUses--; else localUses--;+ await reportUsage().catch(() => undefined);+ };+ try {+ let version: string | undefined;+ try { version = await reportUsage(); }+ catch (error) {+ if (!(error instanceof GatewayError) || error.code !== 'binding_rotation_pending') throw error;+ await synchronizeBinding();+ version = await reportUsage();+ }+ if (version && version !== credentials?.keyVersion) await synchronizeBinding();+ return { credentials: await readModelCredentials(probing), release };+ } catch (error) { await release(); throw error; }+ }+ const beginModelUse = () => acquireModelUse();+ async function logout() {+ await initialize();+ accessPaused = true;+ accessController?.abort(); await accessWork;+ await serialize(async () => {+ assertIdle();+ if (input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);+ await reportUsage();+ state.authState = 'signing_out'; state.activationState = 'inactive';+ clearInterval(usageTimer); usageTimer = undefined;+ await cancelAuthorization();+ await refreshWork?.catch(() => undefined);+ await input.closeRuntime();+ runtimeTextModel = undefined;+ if (credentials) await input.client.logout(credentials.accessToken).catch(() => undefined);+ await store.deleteCredentials(); state.source = 'manual'; state.bindingVersion = null; await saveConfiguration();+ credentials = undefined; balance = null; profileUpdatedAt = 0; catalogUpdatedAt = 0; accessUpdatedAt = 0; accessBlocked = false;+ state = { ...state, authState: 'signed_out', activationState: 'inactive', account: null, models: [], bindingVersion: null, activationError: null };+ }).finally(() => { accessPaused = false; });+ }+ async function billing(path: string, body?: unknown) { await initialize(); await refresh(); return input.client.request(path, assertSignedIn().accessToken, body); }+ async function readBalance(): Promise<GatewayBalanceState> {+ try {+ const value = z.object({ balance: z.object({ availableUnits: z.string().regex(/^\d+$/), reservedUnits: z.string().regex(/^\d+$/), periodEnd: z.string().nullable(), asOf: z.string() }) }).parse(await billing('/api/v1/billing/summary'));+ balance = value.balance; return { status: 'ready', value: balance };+ } catch (error) { return { status: 'unavailable', lastKnown: balance, code: error instanceof GatewayError ? error.code : 'gateway_unavailable' }; }+ }+ return {+ peekState() { return structuredClone(state); },+ startAuthorization, cancelAuthorization, pollAuthorization, refresh, logout, modelCredentials, beginModelUse, readBalance, billing,+ readPlans() { return input.client.request('/api/v1/plans', ''); },+ async readAvatar(accountId: string) {+ await initialize(); await refresh();+ const current = assertSignedIn(); const expected = generation;+ if (!current.account?.avatarUrl || current.account.id !== accountId) throw new GatewayError('avatar_unavailable', 404);+ const image = await input.client.avatar(current.accessToken, accountId);+ if (expected !== generation || state.authState !== 'signed_in' || credentials?.account?.id !== accountId) throw new GatewayError('avatar_unavailable', 404);+ 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 setSource(source: ServiceSource) {+ await initialize(); await serialize(async () => {+ if (source === 'manual' && (credentials || state.authState !== 'signed_out')) throw new GatewayError('logout_required', 409);+ if (source === 'gateway') { assertSignedIn(); assertIdle(); await activateCurrent(); return; }+ state.source = 'manual'; await saveConfiguration();+ });+ },+ async selectModel(modality: import('@opencreator/protocol').GatewayModel['modality'], model: string) {+ await initialize(); await serialize(async () => {+ assertIdle(); const current = assertSignedIn();+ if (state.source !== 'gateway' || state.activationState !== 'ready' || !current.defaults || !state.models.some(candidate => candidate.modality === modality && candidate.id === model && (modality !== 'text' || candidate.capabilities.includes('responses')))) throw new GatewayError('invalid_model', 400);+ if (input.hasPendingTasks?.()) throw new GatewayError('active_tasks', 409);+ const next = { ...current, defaults: { ...current.defaults, [modality]: model } };+ if (modality === 'text') { await input.activateRuntime(bootstrapSchema.parse(next)); runtimeTextModel = model; }+ credentials = next; selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels };+ await store.writeCredentials(next); await saveConfiguration();+ });+ return structuredClone(state);+ },+ async close() { closing = true; accessController?.abort(); await accessWork; clearTimeout(pollTimer); clearInterval(usageTimer); usageTimer = undefined; await profileWork; await catalogWork; await mutation; await refreshWork?.catch(() => undefined); await input.closeRuntime(); await reportUsage().catch(() => undefined); await usageMutation; generation++; }+ };+}+export type GatewayAccountService = ReturnType<typeof createGatewayAccountService>;diff --git a/apps/daemon/src/gateway/client.ts b/apps/daemon/src/gateway/client.tsnew file mode 100644index 00000000..c4b65313--- /dev/null+++ b/apps/daemon/src/gateway/client.ts@@ -0,0 +1,109 @@+import { z } from 'zod';+import type { GatewayModel } from '@opencreator/protocol';++const tokenSchema = z.object({ accessToken: z.string().min(12), refreshToken: z.string().min(12), expiresIn: z.number().int().positive() });+const modelSchema = z.object({+ id: z.string().min(1), name: z.string().optional(),+ modality: z.enum(['text', 'image', 'video', 'speech', 'transcription']),+ capabilities: z.array(z.string()), voices: z.array(z.string().min(1)).optional(),+ sizes: z.array(z.string().regex(/^\d+x\d+$/)).optional(),+ durations: z.array(z.number().int().positive()).optional(),+ resolutions: z.array(z.string().min(1)).optional(),+ aspectRatios: z.array(z.string().min(1)).optional(),+ imageOptions: z.object({+ aspectRatios: z.array(z.string()).optional(), resolutions: z.array(z.string()).optional(),+ qualities: z.array(z.string()).optional(), outputFormats: z.array(z.string()).optional(),+ maxImages: z.number().int().min(1).max(10), maxReferences: z.number().int().nonnegative()+ }).optional()+});+export const catalogSchema = z.object({ models: z.array(modelSchema).min(1) });+export const accountSchema = z.object({ id: z.string().min(1), email: z.string(), verified: z.boolean(), avatarUrl: z.string().url().max(2048).optional() });+export const bootstrapSchema = z.object({+ schemaVersion: z.literal(1), account: accountSchema,+ transport: z.enum(['gateway', 'openrouter-direct']).optional(),+ keyRotation: z.boolean().optional(), rotationPending: z.boolean().optional(),+ modelKey: z.string().min(1), keyVersion: z.string().min(1), bindingVersion: z.string().min(1), baseUrl: z.string().url(),+ models: z.array(modelSchema), defaults: z.record(z.string())+});+export type GatewayBootstrap = z.infer<typeof bootstrapSchema>;+export type GatewayTokens = z.infer<typeof tokenSchema>;+export type GatewayDeviceGrant = { attemptId: string; deviceSecret: string; authorizationUrl: string; interval: number; expiresIn: number };+export type GatewayClient = {+ origin: string;+ startDevice(): Promise<GatewayDeviceGrant>;+ pollDevice(id: string, secret: string): Promise<GatewayTokens>;+ cancelDevice(id: string, secret: string): Promise<void>;+ refresh(refresh: string): Promise<GatewayTokens>;+ bootstrap(access: string, options?: { rotate: boolean }): Promise<GatewayBootstrap>;+ avatar(access: string, accountId: string): Promise<{ data: Uint8Array; contentType: string }>;+ logout(access: string): Promise<void>;+ request(path: string, access: string, body?: unknown): Promise<unknown>;+};+export class GatewayError extends Error {+ constructor(readonly code: string, readonly status = 503) { super('OpenCreator 网关请求未完成'); }+}+export function validateGatewayOrigin(origin: string) {+ const u = new URL(origin);+ const local = u.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(u.hostname);+ if ((!local && u.protocol !== 'https:') || u.username || u.password || u.search || u.hash || u.pathname !== '/') throw new GatewayError('invalid_gateway_origin');+ return u.origin;+}+export function createGatewayClient(origin: string, fetcher: typeof fetch = fetch): GatewayClient {+ origin = validateGatewayOrigin(origin);+ async function readResponse(path: string, access: string, body?: unknown) {+ if (!path.startsWith('/api/v1/') || path.includes('..')) throw new GatewayError('invalid_gateway_path');+ let res: Response;+ try {+ res = await fetcher(`${origin}${path}`, { method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),+ headers: { 'Content-Type': 'application/json', ...(access ? { Authorization: `Bearer ${access}` } : {}) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ } catch { throw new GatewayError('gateway_unavailable'); }+ const reader = res.body?.getReader();+ if (!reader) throw new GatewayError('invalid_gateway_response');+ const chunks: Uint8Array[] = []; let size = 0;+ try {+ while (true) {+ const item = await reader.read(); if (item.done) break;+ size += item.value.byteLength;+ if (size > 1024 * 1024) { await reader.cancel(); throw new GatewayError('invalid_gateway_response'); }+ chunks.push(item.value);+ }+ } catch (error) { if (error instanceof GatewayError) throw error; throw new GatewayError('gateway_unavailable'); }+ return { res, data: Buffer.concat(chunks) };+ }+ function responseError(data: Uint8Array, status: number): never {+ let value: unknown;+ try { value = JSON.parse(Buffer.from(data).toString('utf8')); } catch { throw new GatewayError('invalid_gateway_response'); }+ const parsed = z.object({ error: z.object({ code: z.string().regex(/^[a-z_]{1,64}$/) }) }).safeParse(value);+ throw new GatewayError(parsed.success ? parsed.data.error.code : 'gateway_unavailable', status);+ }+ async function request(path: string, access: string, body?: unknown): Promise<unknown> {+ const { res, data } = await readResponse(path, access, body);+ if (!res.ok) responseError(data, res.status);+ const text = data.toString('utf8');+ let value: unknown; try { value = JSON.parse(text); } catch { throw new GatewayError('invalid_gateway_response'); }+ return value;+ }+ return {+ origin, request,+ async startDevice() { return z.object({ attemptId: z.string().min(1), deviceSecret: z.string().min(12), authorizationUrl: z.string().url(), interval: z.number().positive(), expiresIn: z.number().positive() }).parse(await request('/api/v1/auth/device/start', '', { label: 'OpenCreator' })); },+ async pollDevice(attemptId, deviceSecret) { return tokenSchema.parse(await request('/api/v1/auth/device/token', '', { attemptId, deviceSecret })); },+ async cancelDevice(attemptId, deviceSecret) { await request('/api/v1/auth/device/cancel', '', { attemptId, deviceSecret }); },+ async refresh(refreshToken) { return tokenSchema.parse(await request('/api/v1/auth/refresh', '', { refreshToken })); },+ async bootstrap(access, options) {+ const value = bootstrapSchema.parse(await request('/api/v1/client/bootstrap' + (options ? `?rotate=${options.rotate ? '1' : '0'}` : ''), access));+ const expected = value.transport === 'openrouter-direct' ? 'https://openrouter.ai/api/v1' : `${origin}/v1`;+ if (value.baseUrl !== expected) throw new GatewayError('invalid_gateway_response');+ return value;+ },+ async avatar(access, accountId) {+ const { res, data } = await readResponse('/api/v1/me/avatar?accountId=' + encodeURIComponent(accountId), access);+ if (!res.ok) responseError(data, res.status);+ const contentType = res.headers.get('content-type')?.split(';')[0] ?? '';+ if (!['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(contentType)) throw new GatewayError('invalid_gateway_response');+ return { data, contentType };+ },+ async logout(access) { await request('/api/v1/auth/logout', access, {}); }+ };+}++export function gatewayModel(models: GatewayModel[], modality: GatewayModel['modality']) { return models.find(model => model.modality === modality); }diff --git a/apps/daemon/src/gateway/config-store.ts b/apps/daemon/src/gateway/config-store.tsnew file mode 100644index 00000000..9b5fea56--- /dev/null+++ b/apps/daemon/src/gateway/config-store.ts@@ -0,0 +1,28 @@+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { z } from 'zod';+import { deletePrivateJsonFile, readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';+import { bootstrapSchema, type GatewayBootstrap, type GatewayTokens } from './client.js';+export type GatewayCredentials = Partial<GatewayBootstrap> & GatewayTokens & { accessExpiresAt: string };+export function createGatewayConfigStore(dataDir: string) {+ const secretPath = join(dataDir, 'config', 'gateway-credentials.json');+ const publicPath = join(dataDir, 'config', 'gateway.json');+ const devicePath = join(dataDir, 'config', 'gateway-device.json');+ let deviceID: Promise<string> | undefined;+ const credentials = bootstrapSchema.partial().extend({ accessToken: z.string(), refreshToken: z.string(), expiresIn: z.number(), accessExpiresAt: z.string() });+ const configuration = z.object({ source: z.enum(['manual', 'gateway']), bindingVersion: z.string().nullable(), explicitlySelected: z.boolean().optional(), selectedModels: z.record(z.string()).optional() });+ return {+ readDeviceID(): Promise<string> {+ return deviceID ??= (async () => {+ const value = await readPrivateJsonFile(devicePath);+ if (value !== undefined) return z.object({ id: z.string().uuid() }).parse(value).id;+ const id = randomUUID(); await writePrivateJsonFile(devicePath, { id }); return id;+ })();+ },+ async readCredentials(): Promise<GatewayCredentials | undefined> { const value = await readPrivateJsonFile(secretPath); return value === undefined ? undefined : credentials.parse(value); },+ writeCredentials(value: GatewayCredentials) { return writePrivateJsonFile(secretPath, value); },+ deleteCredentials() { return deletePrivateJsonFile(secretPath); },+ async readConfiguration() { const value = await readPrivateJsonFile(publicPath); return value === undefined ? { source: 'manual' as const, bindingVersion: null } : configuration.parse(value); },+ writeConfiguration(value: z.infer<typeof configuration>) { return writePrivateJsonFile(publicPath, value); }+ };+}diff --git a/apps/daemon/src/gateway/creator-service-source.ts b/apps/daemon/src/gateway/creator-service-source.tsnew file mode 100644index 00000000..9b9f2a2f--- /dev/null+++ b/apps/daemon/src/gateway/creator-service-source.ts@@ -0,0 +1,265 @@+import { createDefaultCreatorServicesConfig, gatewayDefaultVoiceId, type CreatorServicesConfig, type CreatorProviderRequest, type CreatorStageRun, type CreatorJob, type GatewayModel } from '@opencreator/protocol';+import type { FastifyInstance } from 'fastify';+import { createHash, randomBytes, randomUUID } from 'node:crypto';+import { AsyncLocalStorage } from 'node:async_hooks';+import { Readable } from 'node:stream';+import type { CreatorServicesConfigStore } from '../creator-services/config-store.js';+import { KRILLIN_LLM_ROUTE_PREFIX } from '../creator/krillin/codex-llm-gateway.js';+import type { GatewayAccountService } from './account-service.js';+import { GatewayError } from './client.js';+import type { CreatorServiceBinding } from '../creator/repository.js';+import type { CreatorProviderRequestLedger } from '../creator/provider-requests.js';+import { createDirectTransport } from './direct-transport.js';+import { createOfficialFetch } from './official-fetch.js';++export type GatewayCreatorBinding = { accountId: string; bindingVersion: string; baseUrl: string; apiKey: string; models: Record<string, string>; catalog?: GatewayModel[]; capabilities?: Record<string, string[]>; speechVoices?: string[]; logicalId?: string; stageRunId?: string };+const bindings = new WeakMap<CreatorServicesConfig, GatewayCreatorBinding>();+export function gatewayCreatorBinding(config: CreatorServicesConfig) { return bindings.get(config); }++export function createGatewayCreatorSource(input: {+ account: Pick<GatewayAccountService, 'peekState' | 'modelCredentials'> & Partial<Pick<GatewayAccountService, 'beginModelUse'>>;+ manual: CreatorServicesConfigStore;+ getLocalOrigin(): string | undefined;+ fetcher?: typeof fetch;+ readJobBinding?(jobId: string): CreatorServiceBinding;+ readJobState?(jobId: string): CreatorJob['state'] | undefined;+ readStageRun?(stageRunId: string): CreatorStageRun | undefined;+ ledger?: CreatorProviderRequestLedger;+ directRequestsRoot?: string;+}) {+ const capabilities = new Map<string, { token: string; accountId: string; bindingVersion: string; logicalId?: string; jobId?: string }>();+ const context = new AsyncLocalStorage<{ snapshot: CreatorServiceBinding; logicalId: string; stageRunId: string; jobId: string }>();+ const inFlight = new Map<AbortController, Promise<void>>();+ const remoteTasks = new Set<string>();+ const prefix = `${KRILLIN_LLM_ROUTE_PREFIX}/gateway/v1`;+ const direct = input.directRequestsRoot ? createDirectTransport(input.directRequestsRoot,+ input.fetcher ?? createOfficialFetch({ readProxy: async () => (await input.manual.read()).proxy })) : undefined;+ function snapshot(): CreatorServiceBinding {+ const state = input.account.peekState();+ if (state.source === 'manual') return { source: 'manual' };+ if (state.authState !== 'signed_in' || state.activationState !== 'ready' || !state.account || !state.bindingVersion) throw new GatewayError('services_not_ready');+ const models: Record<string, string> = {};+ const caps: Record<string, string[]> = {};+ for (const model of state.models) {+ if (!models[model.modality] || state.selectedModels?.[model.modality] === model.id) {+ models[model.modality] = model.id; caps[model.modality] = [...model.capabilities];+ }+ }+ return { source: 'gateway', accountId: state.account.id, bindingVersion: state.bindingVersion, models, capabilities: caps };+ }+ function assertSnapshot(value: CreatorServiceBinding) {+ const state = input.account.peekState();+ if (value.source === 'gateway' && (state.authState !== 'signed_in' || state.activationState !== 'ready')) throw new GatewayError('services_not_ready');+ if (value.source !== state.source || (value.source === 'gateway' && value.accountId !== state.account?.id)) throw new GatewayError('task_source_mismatch', 409);+ }+ function assertJob(jobId: string) { if (input.readJobBinding) assertSnapshot(input.readJobBinding(jobId)); }+ async function binding(): Promise<GatewayCreatorBinding | undefined> {+ const scope = context.getStore();+ if (scope) assertSnapshot(scope.snapshot);+ if (input.account.peekState().source === 'manual') return undefined;+ const credentials = await input.account.modelCredentials();+ const local = input.getLocalOrigin();+ if (!local) throw new GatewayError('services_not_ready');+ const original = scope?.snapshot.source === 'gateway' ? scope.snapshot : undefined;+ const bindingVersion = original?.bindingVersion ?? credentials.bindingVersion;+ let capability = [...capabilities.values()].find(value => value.accountId === credentials.accountId && value.bindingVersion === bindingVersion && value.logicalId === scope?.logicalId);+ if (!capability) {+ capability = { accountId: credentials.accountId, bindingVersion, logicalId: scope?.logicalId, jobId: scope?.jobId, token: `oclocal_${randomBytes(32).toString('base64url')}` };+ capabilities.set(capability.token, capability);+ }+ const speechModel = original?.models?.speech ?? credentials.defaults.speech;+ const speechVoices = credentials.models.find(model => model.modality === 'speech' && model.id === speechModel)?.voices;+ return { accountId: credentials.accountId, bindingVersion, baseUrl: `${local}${prefix}`, apiKey: capability.token, models: original?.models ?? credentials.defaults, catalog: credentials.models, capabilities: original?.capabilities ?? Object.fromEntries(credentials.models.filter(model => credentials.defaults[model.modality] === model.id).map(model => [model.modality, model.capabilities])), speechVoices, logicalId: scope?.logicalId, stageRunId: scope?.stageRunId };+ }+ const store: CreatorServicesConfigStore = {+ async read() {+ const source = await binding(); if (!source) return input.manual.read();+ const config = createDefaultCreatorServicesConfig();+ const model = (modality: string) => ({ baseUrl: source.baseUrl, apiKey: source.apiKey, model: source.models[modality] ?? '' });+ config.proxy = (await input.manual.read()).proxy;+ config.llm = { ...model('text'), source: 'custom', jsonMode: true };+ config.image.provider = 'openai'; config.image.openai = model('image');+ config.tts.provider = 'openai'; config.tts.openai = { ...config.tts.openai, ...model('speech') };+ if (source.speechVoices?.length) config.tts.openai.defaultVoiceId = source.speechVoices[0]!;+ else if (source.capabilities?.speech?.includes('default_voice')) config.tts.openai.defaultVoiceId = gatewayDefaultVoiceId;+ config.transcription.provider = 'openai'; config.transcription.openai = model('transcription');+ bindings.set(config, source); return config;+ },+ async write(config) { if (input.account.peekState().source !== 'manual') throw new GatewayError('official_config_read_only', 409); return input.manual.write(config); },+ async reset() { if (input.account.peekState().source !== 'manual') throw new GatewayError('official_config_read_only', 409); return input.manual.reset(); }+ };+ return {+ store, binding, snapshot, assertJob,+ async runForJob<T>(jobId: string, stageRunId: string, work: () => Promise<T>): Promise<T> {+ let original = input.readJobBinding?.(jobId) ?? snapshot();+ assertSnapshot(original);+ if (original.source === 'gateway') {+ const choices = input.readJobState?.(jobId)?.officialModels;+ if (choices !== undefined) {+ if (!choices || typeof choices !== 'object' || Array.isArray(choices)) throw new GatewayError('invalid_model', 400);+ original = { ...original, models: { ...original.models }, capabilities: { ...original.capabilities } };+ const catalog = input.account.peekState().models;+ for (const [modality, id] of Object.entries(choices)) {+ const selected = catalog.find(candidate => candidate.modality === modality && candidate.id === id && (modality !== 'text' || candidate.capabilities.includes('responses')));+ if (!selected) throw new GatewayError('invalid_model', 400);+ original.models[modality] = selected.id; original.capabilities[modality] = [...selected.capabilities];+ }+ }+ }+ let logicalId = stageRunId;+ if (original.source === 'gateway' && input.readStageRun) {+ let stage = input.readStageRun(stageRunId);+ const visited = new Set<string>();+ while (stage && typeof stage.progress.resumedFromStageRunId === 'string') {+ visited.add(stage.id);+ const parent = input.readStageRun(stage.progress.resumedFromStageRunId);+ if (!parent || parent.jobId !== jobId || parent.stageId !== stage.stageId || parent.scopeKey !== stage.scopeKey || visited.has(parent.id)) throw new GatewayError('request_identity_unavailable', 409);+ logicalId = parent.id; stage = parent;+ }+ }+ return context.run({ snapshot: original, logicalId, stageRunId, jobId }, work);+ },+ async revoke() {+ capabilities.clear(); remoteTasks.clear();+ const pending = [...inFlight.values()];+ for (const controller of inFlight.keys()) controller.abort();+ await direct?.close();+ await Promise.all(pending);+ },+ isBusy() { return inFlight.size > 0 || remoteTasks.size > 0 || direct?.isBusy() === true; },+ async register(server: FastifyInstance) {+ await server.register(async scoped => {+ scoped.addContentTypeParser('multipart/form-data', { parseAs: 'buffer', bodyLimit: 64 * 1024 * 1024 }, (_r, body, done) => done(null, body));+ scoped.route({ method: ['GET', 'POST'], url: `${prefix}/*`, bodyLimit: 64 * 1024 * 1024, async handler(request, reply) {+ const token = request.headers.authorization?.replace(/^Bearer /, '');+ const original = token ? capabilities.get(token) : undefined;+ if (!original || token !== original.token) return reply.code(401).send({ error: { code: 'auth_required', message: 'Local authorization has expired' } });+ const resource = (request.params as { '*': string })['*'];+ if (!/^(chat\/completions|responses|images\/(generations|edits)|audio\/(speech|transcriptions)|video\/jobs(\/[A-Za-z0-9_-]{12,128}(\/result)?)?|videos\/tasks|requests\/[A-Za-z0-9_-]{12,128}(\/result)?)$/.test(resource)) return reply.code(404).send({ error: { code: 'capability_unsupported', message: 'Operation is unavailable' } });+ const controller = new AbortController();+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(180_000)]);+ let complete!: () => void;+ inFlight.set(controller, new Promise<void>(resolve => { complete = resolve; }));+ let streaming = false;+ let releaseUse: (() => Promise<void>) | undefined;+ const finish = () => { inFlight.delete(controller); void releaseUse?.(); releaseUse = undefined; complete(); };+ let receipt: CreatorProviderRequest | undefined;+ let reconcile = async () => {};+ const markUnknown = () => {+ if (!receipt || !input.ledger) return;+ receipt = input.ledger.findLatest(receipt.provider, receipt.requestKey);+ if (receipt && ['submitting', 'waiting_remote'].includes(receipt.status)) receipt = input.ledger.markUnknownRemoteAcceptance(receipt.id);+ };+ try {+ const use = await input.account.beginModelUse?.(); releaseUse = use?.release;+ const credentials = use?.credentials ?? await input.account.modelCredentials();+ if (capabilities.get(original.token) !== original || credentials.accountId !== original.accountId) throw new GatewayError('auth_required', 401);+ const headers: Record<string,string> = { Authorization: `Bearer ${credentials.modelKey}`, 'Content-Type': request.headers['content-type'] ?? 'application/json' };+ const identity = request.headers['idempotency-key'];+ const body = request.method === 'GET' ? undefined : Buffer.isBuffer(request.body) ? new Uint8Array(request.body) : JSON.stringify(request.body);+ const digest = request.method === 'POST' && (credentials.transport === 'openrouter-direct' || (original.logicalId && typeof identity !== 'string')) ? await requestDigest(request.body, headers['Content-Type']!) : undefined;+ if (request.method === 'POST') headers['Idempotency-Key'] = typeof identity === 'string' ? identity : original.logicalId+ ? `creator:${createHash('sha256').update(JSON.stringify([original.logicalId, resource, digest])).digest('hex')}`+ : randomUUID();+ if (input.ledger && original.logicalId && original.jobId && digest && /^(chat\/completions|responses|images\/(generations|edits)|audio\/(speech|transcriptions))$/.test(resource)) {+ const provider = `opencreator-gateway-${resource}`;+ const requestKey = headers['Idempotency-Key']!;+ receipt = input.ledger.findLatest(provider, requestKey) ?? input.ledger.registerBeforeSubmit({ jobId: original.jobId, stageRunId: original.logicalId, provider, requestKey, request: { operation: resource, fingerprint: digest }, gateway: { accountId: original.accountId, bindingVersion: original.bindingVersion, logicalId: requestKey } });+ if (receipt.status === 'registered') receipt = input.ledger.markSubmitting(receipt.id);+ reconcile = async () => {+ try {+ await input.ledger!.recover(receipt!.id, { lookupByRequestKey: false, async lookup({ remoteTaskId }) {+ if (!remoteTaskId) return { status: 'not_found' };+ const response = credentials.transport === 'openrouter-direct' && direct+ ? await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource: `requests/${remoteTaskId}`, method: 'GET', body: undefined, contentType: 'application/json', identity: '', fingerprint: '', signal })+ : await (input.fetcher ?? fetch)(`${credentials.baseUrl}/requests/${encodeURIComponent(remoteTaskId)}`, { method: 'GET', headers: { Authorization: `Bearer ${credentials.modelKey}` }, redirect: 'error', signal });+ if (!response.ok) throw new GatewayError('gateway_unavailable');+ const result = await response.json() as { requestId?: string; state?: string };+ if (result.requestId !== remoteTaskId) throw new GatewayError('invalid_gateway_response');+ if (result.state === 'succeeded') return { status: 'succeeded', remoteTaskId };+ if (result.state === 'failed' || result.state === 'canceled') return { status: 'failed', remoteTaskId };+ return result.state === 'outcome_unknown' ? { status: 'not_found' } : { status: 'waiting_remote', remoteTaskId };+ } });+ } catch { markUnknown(); }+ };+ }+ signal.throwIfAborted();+ let response: Response;+ if (credentials.transport === 'openrouter-direct') {+ if (!direct) throw new GatewayError('services_not_ready');+ let modelMetadata: GatewayModel | undefined;+ if (request.method === 'POST') {+ const modality = resource.startsWith('images/') ? 'image' : resource === 'audio/speech' ? 'speech' : resource === 'audio/transcriptions' ? 'transcription' : resource.startsWith('video') ? 'video' : 'text';+ const model = Buffer.isBuffer(request.body)+ ? (await new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': headers['Content-Type']! }, body: new Uint8Array(request.body) }).formData()).get('model')+ : (request.body as { model?: unknown })?.model;+ modelMetadata = credentials.models.find(candidate => candidate.modality === modality && candidate.id === model);+ if (!modelMetadata) throw new GatewayError('invalid_model', 400);+ }+ response = await direct.request({ account: credentials.accountId, key: credentials.modelKey, resource, method: request.method, body: request.body, contentType: headers['Content-Type']!, identity: headers['Idempotency-Key'] ?? '', fingerprint: digest ?? '', signal, model: modelMetadata, asyncImage: request.headers.prefer === 'respond-async' });+ } else response = await (input.fetcher ?? fetch)(`${credentials.baseUrl}/${resource}`, { method: request.method, headers, body, redirect: 'error', signal });+ signal.throwIfAborted();+ reply.code(response.status).header('Cache-Control', 'no-store');+ reply.header('Content-Type', response.headers.get('content-type') ?? 'application/json');+ const id = response.headers.get('x-request-id'); if (id) reply.header('X-Request-ID', id);+ if (receipt && input.ledger) {+ receipt = input.ledger.findLatest(receipt.provider, receipt.requestKey);+ if (receipt && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(receipt.status)) {+ if (id && /^[A-Za-z0-9_-]{12,128}$/.test(id)) receipt = input.ledger.markWaitingRemote(receipt.id, id);+ else if (!response.ok && response.status >= 400 && response.status < 500 && receipt.status !== 'unknown_remote_acceptance') receipt = input.ledger.markFailed(receipt.id);+ else markUnknown();+ }+ }+ if (resource === 'video/jobs' || resource === 'videos/tasks' || (response.status === 202 && resource.startsWith('images/')) || /^(requests|video\/jobs)\/[A-Za-z0-9_-]+$/.test(resource)) {+ const value = await response.json() as { requestId?: string; state?: string };+ if (value.requestId) {+ if (['succeeded','failed','canceled','outcome_unknown'].includes(value.state ?? '')) remoteTasks.delete(value.requestId);+ else if (resource === 'video/jobs' || resource === 'videos/tasks' || remoteTasks.has(value.requestId)) remoteTasks.add(value.requestId);+ if (request.method === 'GET' && original.jobId && input.ledger && /^requests\//.test(resource)) {+ for (const entry of input.ledger.findByRemoteTaskId(original.jobId, value.requestId).filter(item => item.provider.startsWith('opencreator-gateway-images/'))) {+ await input.ledger.recover(entry.id, { lookupByRequestKey: false, async lookup() {+ if (value.state === 'succeeded') return { status: 'succeeded' };+ if (value.state === 'failed') return { status: 'failed' };+ if (value.state === 'outcome_unknown') return { status: 'not_found' };+ return { status: 'waiting_remote', remoteTaskId: value.requestId! };+ } });+ }+ }+ }+ return value;+ }+ if (!response.body) return reply.send();+ const stream = Readable.fromWeb(response.body as import('node:stream/web').ReadableStream);+ streaming = true;+ stream.once('close', () => { void reconcile().finally(finish); });+ const abort = () => stream.destroy(new Error('Official service forwarding was interrupted'));+ signal.addEventListener('abort', abort, { once: true });+ stream.once('close', () => signal.removeEventListener('abort', abort));+ return reply.send(stream);+ } catch (error) {+ if (receipt && input.ledger && error instanceof GatewayError && [400, 401, 402, 403, 404, 422, 429].includes(error.status) && ['submitting', 'waiting_remote'].includes(receipt.status)) receipt = input.ledger.markFailed(receipt.id);+ else markUnknown();+ return reply.code(error instanceof GatewayError ? error.status : 503).send({ error: { code: error instanceof GatewayError ? error.code : 'gateway_unavailable', message: 'Official service request could not be completed' } });+ } finally { if (!streaming) finish(); }+ } });+ });+ }+ };+}++async function requestDigest(body: unknown, contentType: string): Promise<string> {+ let value = body;+ if (Buffer.isBuffer(body) && contentType.startsWith('multipart/form-data')) {+ const form = await new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': contentType }, body: new Uint8Array(body) }).formData();+ const fields = await Promise.all([...form.entries()].map(async ([name, item]) => [name, typeof item === 'string' ? item : {+ mime: item.type, size: item.size, digest: createHash('sha256').update(new Uint8Array(await item.arrayBuffer())).digest('hex')+ }]));+ value = fields.sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));+ }+ return createHash('sha256').update(JSON.stringify(canonicalValue(value))).digest('hex');+}+function canonicalValue(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(canonicalValue);+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([name, item]) => [name, canonicalValue(item)]));+ return value;+}diff --git a/apps/daemon/src/gateway/direct-runtime.ts b/apps/daemon/src/gateway/direct-runtime.tsnew file mode 100644index 00000000..0cfaca53--- /dev/null+++ b/apps/daemon/src/gateway/direct-runtime.ts@@ -0,0 +1,46 @@+import { createServer } from 'node:http';+import { randomBytes } from 'node:crypto';+import { Readable } from 'node:stream';+import { pipeline } from 'node:stream/promises';+import { statelessResponses } from './direct-transport.js';+import { officialEventStream } from './official-stream.js';++export async function createDirectRuntime(key: string, fetcher: typeof fetch = fetch, beginUse?: () => Promise<{ key: string; release(): Promise<void> }>) {+ const token = `oclocal_${randomBytes(32).toString('base64url')}`;+ const active = new Set<AbortController>();+ const handlers = new Set<Promise<void>>();+ const server = createServer(async (req, res) => {+ if (req.method !== 'POST' || req.url !== '/v1/responses' || req.headers.authorization !== `Bearer ${token}`) { res.writeHead(401).end(); return; }+ const controller = new AbortController(); active.add(controller);+ let complete!: () => void;+ const done = new Promise<void>(resolve => { complete = resolve; }); handlers.add(done);+ const abort = () => controller.abort(); res.once('close', abort);+ let release: (() => Promise<void>) | undefined;+ try {+ const chunks: Buffer[] = []; let size = 0;+ for await (const chunk of req) { size += chunk.length; if (size > 64 * 1024 * 1024) throw new Error('Request too large'); chunks.push(Buffer.from(chunk)); }+ const body = statelessResponses(JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>);+ const use = await beginUse?.(); release = use?.release;+ const response = await fetcher('https://openrouter.ai/api/v1/responses', { method: 'POST', redirect: 'error', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(180_000)]), headers: { Authorization: `Bearer ${use?.key ?? key}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ if (!response.ok || !response.body) {+ await response.body?.cancel();+ res.writeHead(response.status === 402 ? 402 : 503, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: response.status === 402 ? '积分不足' : '官方模型服务暂不可用' } })); return;+ }+ res.writeHead(200, { 'Content-Type': response.headers.get('content-type') ?? 'text/event-stream', 'Cache-Control': 'no-store' });+ const bodyStream = response.headers.get('content-type')?.includes('text/event-stream') ? officialEventStream(response.body) : response.body;+ await pipeline(Readable.fromWeb(bodyStream as import('node:stream/web').ReadableStream), res);+ } catch {+ if (!res.headersSent) res.writeHead(503, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: '官方模型服务暂不可用' } }));+ else res.destroy();+ } finally {+ try { await release?.(); }+ finally { active.delete(controller); res.removeListener('close', abort); handlers.delete(done); complete(); }+ }+ });+ server.headersTimeout = 10_000;+ await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });+ const address = server.address(); if (!address || typeof address === 'string') throw new Error('Local service unavailable');+ return { baseUrl: `http://127.0.0.1:${address.port}/v1`, token,+ async close() { for (const controller of active) controller.abort(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); await Promise.all(handlers); key = ''; }+ };+}diff --git a/apps/daemon/src/gateway/direct-transport.ts b/apps/daemon/src/gateway/direct-transport.tsnew file mode 100644index 00000000..7d278861--- /dev/null+++ b/apps/daemon/src/gateway/direct-transport.ts@@ -0,0 +1,269 @@+import { createHash } from 'node:crypto';+import { gatewayDefaultVoiceId, gatewayVideoSizeParameters, type GatewayModel } from '@opencreator/protocol';+import { join } from 'node:path';+import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';+import { GatewayError } from './client.js';+import { officialEventStream } from './official-stream.js';++type Receipt = { account: string; fingerprint: string; state: 'submitting' | 'waiting_upstream' | 'succeeded' | 'failed' | 'outcome_unknown'; remoteId?: string; status?: number; mime?: string; content?: string; errorCode?: string; errorStatus?: number };+const base = 'https://openrouter.ai/api/v1';+export const DIRECT_IMAGE_TIMEOUT_MS = 10 * 60_000;++function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {+ signal.throwIfAborted();+ return new Promise((resolve, reject) => {+ const abort = () => reject(signal.reason);+ signal.addEventListener('abort', abort, { once: true });+ work.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));+ });+}++function completeImageResponse(content: Buffer): boolean {+ try {+ const value = JSON.parse(content.toString('utf8')) as { data?: Array<{ b64_json?: unknown }> };+ return Array.isArray(value.data) && value.data.length > 0+ && value.data.every(image => typeof image?.b64_json === 'string' && image.b64_json.length > 0);+ } catch { return false; }+}++function completeEventStream(content: Buffer, resource?: string): boolean {+ let completed = false;+ for (const frame of content.toString('utf8').replace(/\r\n/g, '\n').split('\n\n').slice(0, -1)) {+ const data = frame.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');+ if (data === '[DONE]' && resource !== 'responses') { completed = true; continue; }+ try {+ const event = JSON.parse(data) as { type?: string; error?: unknown; response?: { status?: string; error?: unknown } };+ if (event.error || event.response?.error || ['error', 'response.failed', 'response.incomplete'].includes(event.type ?? '')+ || ['failed', 'incomplete', 'cancelled'].includes(event.response?.status ?? '')) return false;+ if (event.type === 'response.completed' && resource !== 'chat/completions') completed = true;+ } catch {}+ }+ return completed;+}++function pixelAspectRatio(size: unknown) {+ const match = typeof size === 'string' ? /^(\d+)x(\d+)$/.exec(size) : null;+ if (!match) return undefined;+ const width = Number(match[1]); const height = Number(match[2]);+ if (!width || !height) throw new GatewayError('invalid_media_size', 400);+ const gcd = (a: number, b: number): number => b ? gcd(b, a % b) : a;+ const divisor = gcd(width, height);+ return `${width / divisor}:${height / divisor}`;+}++export function statelessResponses(body: Record<string, unknown>) {+ if (body.previous_response_id) throw new GatewayError('capability_unsupported', 400);+ const { previous_response_id: _previous, store: _store, ...rest } = body;+ return { ...rest, store: false };+}++export function createDirectTransport(root: string, fetcher: typeof fetch = fetch) {+ const pending = new Map<string, Promise<Response>>();+ const fingerprints = new Map<string, string>();+ const workers = new Map<string, AbortController>();+ const path = (id: string) => join(root, `${id}.json`);+ const read = async (id: string) => {+ const record = await readPrivateJsonFile(path(id)) as Receipt | undefined;+ // Older callers could cancel after completion and overwrite the terminal state.+ if (record?.state === 'outcome_unknown' && record.status !== undefined && record.status >= 200 && record.status < 300+ && record.mime?.includes('text/event-stream') && record.content && completeEventStream(Buffer.from(record.content, 'base64'))) {+ record.state = 'succeeded';+ await write(id, record);+ }+ return record;+ };+ const write = (id: string, record: Receipt) => writePrivateJsonFile(path(id), record);+ const response = (id: string, record: Receipt) => new Response(Buffer.from(record.content ?? '', 'base64'), { status: record.status ?? 200, headers: { 'Content-Type': record.mime ?? 'application/json', 'X-Request-ID': id } });+ const accepted = (id: string) => Response.json({ requestId: id, state: 'waiting_upstream' }, { status: 202, headers: { 'X-Request-ID': id } });+ async function call(resource: string, options: RequestInit, key: string) {+ const work = fetcher(`${base}/${resource}`, { ...options, redirect: 'error', headers: { ...options.headers, Authorization: `Bearer ${key}` } });+ let result: Response;+ try { result = options.signal ? await abortable(work, options.signal) : await work; }+ catch (error) {+ void work.then(value => value.body?.cancel()).catch(() => undefined);+ throw error;+ }+ if (!result.ok) {+ let limitExceeded = false;+ if (result.status === 403) {+ try {+ const payload = await abortable(result.json() as Promise<{ error?: { message?: unknown } }>, options.signal!);+ limitExceeded = typeof payload.error?.message === 'string' && /^Key limit exceeded\b/i.test(payload.error.message);+ } catch {}+ } else void result.body?.cancel().catch(() => undefined);+ throw new GatewayError(result.status === 402 || limitExceeded ? 'credits_insufficient' : 'official_service_unavailable', result.status >= 400 && result.status < 500 ? result.status : 503);+ }+ return result;+ }+ return {+ isBusy() { return workers.size > 0; },+ async close() {+ const work = [...workers.keys()].map(id => pending.get(id));+ for (const controller of workers.values()) controller.abort();+ await Promise.allSettled(work);+ },+ async request(input: { account: string; key: string; resource: string; method: string; body: unknown; contentType: string; identity: string; fingerprint: string; signal: AbortSignal; model?: GatewayModel; asyncImage?: boolean }): Promise<Response> {+ const { account, key, resource } = input;+ const asyncImage = input.asyncImage === true && /^images\/(generations|edits)$/.test(resource) && input.method === 'POST';+ const controller = asyncImage ? new AbortController() : undefined;+ const signal = controller ? AbortSignal.any([controller.signal, AbortSignal.timeout(DIRECT_IMAGE_TIMEOUT_MS)]) : input.signal;+ const lookup = /^(?:requests|video\/jobs)\/(ocdir_[a-f0-9]{48})(\/result)?$/.exec(resource);+ if (lookup) {+ const id = lookup[1]!; const record = await read(id);+ if (!record || record.account !== account) throw new GatewayError('request_not_found', 404);+ if (!record.remoteId && ['submitting', 'waiting_upstream'].includes(record.state) && !pending.has(id)) {+ record.state = 'outcome_unknown'; await write(id, record);+ }+ if (record.remoteId) {+ if (lookup[2]) {+ if (record.state !== 'succeeded') throw new GatewayError('request_outcome_unknown', 409);+ return call(`videos/${encodeURIComponent(record.remoteId)}/content?index=0`, { method: 'GET', signal }, key);+ }+ const remote = await (await call(`videos/${encodeURIComponent(record.remoteId)}`, { method: 'GET', signal }, key)).json() as { status?: string };+ record.state = remote.status === 'completed' ? 'succeeded' : ['failed', 'cancelled', 'expired'].includes(remote.status ?? '') ? 'failed' : 'waiting_upstream';+ await write(id, record);+ }+ if (lookup[2]) { if (record.state !== 'succeeded') throw new GatewayError('request_outcome_unknown', 409); return response(id, record); }+ return Response.json({ requestId: id, state: record.state, ...(record.errorCode ? { error: { code: record.errorCode, status: record.errorStatus } } : {}) }, { headers: { 'X-Request-ID': id } });+ }+ if (input.method !== 'POST') throw new GatewayError('capability_unsupported', 404);+ const id = 'ocdir_' + createHash('sha256').update(JSON.stringify([account, input.identity])).digest('hex').slice(0, 48);+ const existing = pending.get(id);+ if (existing) {+ if (fingerprints.get(id) !== input.fingerprint) throw new GatewayError('operation_conflict', 409);+ if (asyncImage) return accepted(id);+ await existing; return this.request(input);+ }+ let registered!: () => void;+ const ready = new Promise<void>(resolve => { registered = resolve; });+ const work = (async () => {+ const saved = await read(id);+ if (saved && (saved.account !== account || saved.fingerprint !== input.fingerprint)) throw new GatewayError('operation_conflict', 409);+ if (saved?.remoteId) return Response.json({ requestId: id, state: saved.state }, { status: 202, headers: { 'X-Request-ID': id } });+ if (saved?.state === 'succeeded') return response(id, saved);+ if (saved && saved.state !== 'failed') throw new GatewayError('request_outcome_unknown', 409);+ let body = input.body;+ let endpoint = resource;+ let contentType = input.contentType;+ if (resource === 'responses') body = statelessResponses(body as Record<string, unknown>);+ if (resource === 'images/edits') {+ const form = await new Request('http://localhost', { method: 'POST', headers: { 'Content-Type': contentType }, body: new Uint8Array(body as Buffer) }).formData();+ const fields: Record<string, unknown> = {}; const references: unknown[] = [];+ for (const [name, value] of form.entries()) {+ if (typeof value === 'string') fields[name] = name === 'n' ? Number(value) : value;+ else if (name === 'image' || name === 'image[]') references.push({ type: 'image_url', image_url: { url: `data:${value.type || 'image/png'};base64,${Buffer.from(await value.arrayBuffer()).toString('base64')}` } });+ }+ body = { ...fields, input_references: references }; contentType = 'application/json'; endpoint = 'images';+ }+ if (resource === 'images/generations') endpoint = 'images';+ if (endpoint === 'images') {+ const { response_format: _format, size, quality, aspect_ratio, resolution, ...fields } = body as Record<string, unknown>;+ const options = input.model?.imageOptions;+ const aspectRatio = aspect_ratio || pixelAspectRatio(size);+ const valid = (value: unknown, allowed?: string[]) => value === undefined || value === '' || (typeof value === 'string' && !!allowed?.includes(value));+ if (options && (!valid(aspect_ratio, options.aspectRatios) || !valid(resolution, options.resolutions) || !valid(quality, options.qualities)+ || (Number(fields.n ?? 1) > options.maxImages) || (Array.isArray(fields.input_references) && fields.input_references.length > options.maxReferences))) throw new GatewayError('capability_unsupported', 400);+ const selectedRatio = options?.aspectRatios?.length && !options.aspectRatios.includes(String(aspectRatio)) ? options.aspectRatios[0] : aspectRatio;+ const outputFormat = ['png', 'jpeg', 'webp'].find(format => !options?.outputFormats?.length || options.outputFormats.includes(format));+ if (!outputFormat) throw new GatewayError('capability_unsupported', 400);+ body = { ...fields, ...(selectedRatio ? { aspect_ratio: selectedRatio } : {}), ...(resolution ? { resolution } : {}), ...(quality ? { quality } : {}), output_format: outputFormat };+ }+ if (resource === 'audio/speech') {+ const { voice, ...fields } = body as Record<string, unknown>;+ if (input.model?.capabilities.includes('default_voice')) {+ if (voice && voice !== gatewayDefaultVoiceId) throw new GatewayError('capability_unsupported', 400);+ body = { ...fields, response_format: 'mp3' };+ } else body = { ...fields, voice, response_format: 'mp3' };+ }+ if (resource === 'video/jobs' || resource === 'videos/tasks') {+ const value = body as { model: string; prompt: string; duration?: number; size?: string; image?: string };+ const sizeParams = input.model ? gatewayVideoSizeParameters(input.model, value.size ?? '') : value.size ? { size: value.size } : {};+ if (!sizeParams || (input.model?.durations && !input.model.durations.includes(value.duration!))) throw new GatewayError('capability_unsupported', 400);+ body = { model: value.model, prompt: value.prompt, duration: value.duration, ...sizeParams, ...(value.image ? { frame_images: [{ type: 'image_url', image_url: { url: value.image }, frame_type: 'first_frame' }] } : {}) };+ endpoint = 'videos';+ }+ const record: Receipt = { account, fingerprint: input.fingerprint, state: asyncImage ? 'waiting_upstream' : 'submitting' };+ await write(id, record);+ registered();+ try {+ const remote = await call(endpoint, { method: 'POST', signal, headers: { 'Content-Type': contentType }, body: Buffer.isBuffer(body) ? new Uint8Array(body) : JSON.stringify(body) }, key);+ if (endpoint === 'videos') {+ const value = await remote.json() as { id?: string };+ if (!value.id || !/^[A-Za-z0-9_-]{1,200}$/.test(value.id)) throw new GatewayError('invalid_gateway_response');+ record.remoteId = value.id; record.state = 'waiting_upstream'; await write(id, record);+ return Response.json({ requestId: id, state: record.state }, { status: 202, headers: { 'X-Request-ID': id } });+ }+ record.status = remote.status; record.mime = remote.headers.get('content-type') ?? 'application/json';+ await write(id, record);+ const reader = (record.mime.includes('text/event-stream') && remote.body ? officialEventStream(remote.body) : remote.body)?.getReader(); if (!reader) throw new GatewayError('invalid_gateway_response');+ const chunks: Uint8Array[] = []; let size = 0;+ if (!record.mime.includes('text/event-stream')) {+ try {+ for (;;) {+ const item = await abortable(reader.read(), signal); if (item.done) break;+ size += item.value.length; if (size > 64 * 1024 * 1024) throw new GatewayError('invalid_gateway_response');+ chunks.push(item.value);+ // Buffered image JSON can be complete before the upstream closes its HTTP stream.+ if (endpoint === 'images' && Buffer.from(item.value).toString('utf8').trimEnd().endsWith('}') && completeImageResponse(Buffer.concat(chunks))) break;+ }+ } finally { void reader.cancel().catch(() => undefined); }+ if (endpoint === 'images' && !completeImageResponse(Buffer.concat(chunks))) throw new GatewayError('invalid_gateway_response');+ record.content = Buffer.concat(chunks).toString('base64'); record.state = 'succeeded'; await write(id, record);+ return response(id, record);+ }+ let settlement = Promise.resolve();+ const settleStream = (content?: Buffer) => {+ settlement = settlement.then(async () => {+ if (record.state === 'succeeded') return;+ record.state = content ? 'succeeded' : 'outcome_unknown';+ if (content) record.content = content.toString('base64');+ await write(id, record);+ });+ return settlement;+ };+ const stream = new ReadableStream<Uint8Array>({+ async pull(controller) {+ try {+ const item = await reader.read();+ if (item.done) {+ const content = Buffer.concat(chunks);+ if (!completeEventStream(content, resource)) throw new GatewayError('request_outcome_unknown', 409);+ await settleStream(content); controller.close(); return;+ }+ size += item.value.length; if (size > 64 * 1024 * 1024) throw new GatewayError('invalid_gateway_response');+ chunks.push(item.value);+ if (completeEventStream(Buffer.from(item.value), resource)) {+ const content = Buffer.concat(chunks);+ if (!completeEventStream(content, resource)) throw new GatewayError('request_outcome_unknown', 409);+ await settleStream(content);+ controller.enqueue(item.value); controller.close();+ void reader.cancel().catch(() => undefined);+ return;+ }+ controller.enqueue(item.value);+ } catch {+ await settleStream(); await reader.cancel().catch(() => undefined);+ if (record.state !== 'succeeded') controller.error(new GatewayError('request_outcome_unknown', 409));+ }+ },+ async cancel() {+ const content = Buffer.concat(chunks);+ await settleStream(completeEventStream(content, resource) ? content : undefined);+ await reader.cancel();+ }+ });+ return new Response(stream, { status: remote.status, headers: { 'Content-Type': record.mime, 'X-Request-ID': id } });+ } catch (error) {+ record.state = error instanceof GatewayError && [400, 401, 402, 403, 404, 422, 429].includes(error.status) ? 'failed' : 'outcome_unknown';+ if (error instanceof GatewayError) { record.errorCode = error.code; record.errorStatus = error.status; }+ await write(id, record); throw error;+ }+ })();+ pending.set(id, work);+ fingerprints.set(id, input.fingerprint);+ if (controller) workers.set(id, controller);+ void work.finally(() => { pending.delete(id); fingerprints.delete(id); workers.delete(id); }).catch(() => undefined);+ return asyncImage ? Promise.race([ready.then(() => accepted(id)), work]) : work;+ }+ };+}diff --git a/apps/daemon/src/gateway/model-access.ts b/apps/daemon/src/gateway/model-access.tsnew file mode 100644index 00000000..7d262e44--- /dev/null+++ b/apps/daemon/src/gateway/model-access.ts@@ -0,0 +1,167 @@+import { createHash } from 'node:crypto';+import { isIP } from 'node:net';+import { join } from 'node:path';+import { z } from 'zod';+import type { GatewayModel } from '@opencreator/protocol';+import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';+import type { GatewayBootstrap } from './client.js';++const allowedTTL = 24 * 60 * 60_000;+const blockedTTL = 60 * 60_000;+const retryTTL = 5 * 60_000;+const entrySchema = z.object({+ status: z.enum(['allowed', 'blocked', 'unknown']),+ nextCheck: z.number(), representative: z.string(), alternate: z.boolean().optional()+});+const cacheSchema = z.object({ version: z.literal(1), base: z.string(), network: z.string(), groups: z.record(entrySchema) });+type AccessCache = z.infer<typeof cacheSchema>;+const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');++export function modelAccessGroup(model: GatewayModel): string | undefined {+ const [vendor, slug] = model.id.replace(/^~/, '').split('/');+ if (!slug) return undefined;+ if (vendor === 'openai') return slug.startsWith('gpt-oss') ? 'openai-oss' : 'openai';+ if (vendor === 'google') return slug.startsWith('gemma') ? 'google-gemma' : 'google-gemini';+ return vendor;+}++export function officialModelPolicy(models: GatewayModel[]) {+ return models.filter(model => modelAccessGroup(model) !== 'anthropic'+ && !model.id.endsWith(':batch')+ && !(model.modality === 'text' && modelAccessGroup(model) === 'openrouter'));+}++export function withModelCatalog(bootstrap: GatewayBootstrap, models: GatewayModel[]): GatewayBootstrap {+ const defaults: Record<string, string> = {};+ for (const model of models) {+ if (model.modality === 'text' && !model.capabilities.includes('responses')) continue;+ if (!defaults[model.modality] || bootstrap.defaults[model.modality] === model.id) defaults[model.modality] = model.id;+ }+ return { ...bootstrap, models, defaults };+}++const preferred: Record<string, string[]> = {+ openai: ['openai/gpt-4.1-mini', 'openai/gpt-6-sol', 'openai/gpt-4o-mini'],+ 'google-gemini': ['google/gemini-2.5-flash-lite', 'google/gemini-2.5-flash'],+ deepseek: ['deepseek/deepseek-v3.2', 'deepseek/deepseek-chat'],+ qwen: ['qwen/qwen3-coder', 'qwen/qwen3-max'],+ 'openai-oss': ['openai/gpt-oss-20b', 'openai/gpt-oss-120b'],+ 'google-gemma': ['google/gemma-3-12b-it', 'google/gemma-3-27b-it']+};++export function createOfficialModelAccess(input: { dataDir: string; fetcher: typeof fetch; readProxy(): Promise<string> }) {+ const path = join(input.dataDir, 'config', 'gateway-model-access.json');+ let cache: AccessCache = { version: 1, base: '', network: '', groups: {} };+ let loaded: Promise<void> | undefined;+ let saving = Promise.resolve();+ let networkCheckedAt = 0;+ async function prepare(bootstrap: GatewayBootstrap) {+ loaded ??= (async () => {+ try {+ const parsed = cacheSchema.safeParse(await readPrivateJsonFile(path));+ if (parsed.success) cache = parsed.data;+ } catch { /* A broken availability cache must not prevent sign-in. */ }+ })();+ await loaded;+ const base = digest([bootstrap.account.id, bootstrap.keyVersion, await input.readProxy()]);+ if (cache.base !== base) {+ cache = { version: 1, base, network: '', groups: {} };+ networkCheckedAt = 0;+ }+ return filter(bootstrap);+ }+ function filter(bootstrap: GatewayBootstrap) {+ const eligible = officialModelPolicy(bootstrap.models);+ const status = (model: GatewayModel) => cache.groups[modelAccessGroup(model) ?? '']?.status;+ const text = eligible.filter(model => model.modality === 'text' && model.capabilities.includes('responses'));+ const selected = text.find(model => model.id === bootstrap.defaults.text);+ const fallback = (selected && status(selected) !== 'blocked' ? selected : undefined)+ ?? text.find(model => status(model) === 'allowed')+ ?? text.find(model => status(model) !== 'blocked');+ const fallbackGroup = fallback && modelAccessGroup(fallback);+ return withModelCatalog(bootstrap, eligible.filter(model => {+ const group = modelAccessGroup(model);+ if (group === undefined) return true;+ if (cache.groups[group]?.status === 'blocked') return false;+ return model.modality !== 'text' || cache.groups[group]?.status === 'allowed' || group === fallbackGroup;+ }));+ }+ function save() {+ const snapshot = structuredClone(cache);+ saving = saving.catch(() => undefined).then(() => writePrivateJsonFile(path, snapshot));+ return saving;+ }+ async function check(model: GatewayModel, key: string, signal: AbortSignal): Promise<{ status: 'allowed' | 'blocked' | 'unknown'; alternate?: boolean }> {+ try {+ const response = await input.fetcher('https://openrouter.ai/api/v1/responses', {+ method: 'POST', redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(8000)]),+ headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: model.id, input: 'Call oc_access_check with ready true.', store: false, stream: false, max_output_tokens: 512,+ tools: [{ type: 'function', name: 'oc_access_check', description: 'Confirm model access.', parameters: { type: 'object', properties: { ready: { type: 'boolean' } }, required: ['ready'], additionalProperties: false } }],+ tool_choice: { type: 'function', name: 'oc_access_check' } })+ });+ const value = await response.json() as { status?: string; error?: { message?: unknown }; output?: Array<{ type?: string; name?: string; arguments?: string }> };+ const message = typeof value.error?.message === 'string' ? value.error.message : '';+ if (response.status === 403 && /provider terms of service|(?:country|region|location).{0,80}(?:not supported|restricted|not allowed|unavailable|prohibited)|(?:not available|unavailable|unsupported|restricted).{0,80}(?:country|region|location)/i.test(message)) return { status: 'blocked' };+ if (!response.ok) return { status: 'unknown', alternate: response.status === 400 || response.status === 404 };+ const call = value.output?.find(item => item.type === 'function_call' && item.name === 'oc_access_check');+ return value.status === 'completed' && call && JSON.parse(call.arguments ?? '{}').ready === true ? { status: 'allowed' } : { status: 'unknown', alternate: true };+ } catch { return { status: 'unknown' }; }+ }+ async function refresh(bootstrap: GatewayBootstrap, signal: AbortSignal, onChange: () => Promise<void>) {+ await prepare(bootstrap);+ if (signal.aborted) return;+ if (Date.now() - networkCheckedAt > 60_000) {+ networkCheckedAt = Date.now();+ try {+ const response = await input.fetcher('https://openrouter.ai/cdn-cgi/trace', { redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(4000)]) });+ const fields = new URLSearchParams((await response.text()).replace(/\r?\n/g, '&'));+ const ip = fields.get('ip') ?? ''; const country = fields.get('loc') ?? '';+ if (response.ok && isIP(ip) && /^[A-Z]{2}$/.test(country)) {+ const network = digest([ip, country]);+ if (cache.network !== network) {+ cache = { ...cache, network, groups: {} };+ await save(); await onChange();+ }+ }+ } catch { /* Keep prior results when the network identity endpoint is unavailable. */ }+ }+ const groups = new Map<string, GatewayModel[]>();+ for (const model of officialModelPolicy(bootstrap.models)) {+ const group = modelAccessGroup(model);+ if (model.modality !== 'text' || !model.capabilities.includes('responses') || !group) continue;+ groups.set(group, [...(groups.get(group) ?? []), model]);+ }+ const priority = ['openai', 'google-gemini', 'deepseek', 'qwen', 'openai-oss', 'google-gemma'];+ const pending = [...groups].filter(([group]) => (cache.groups[group]?.nextCheck ?? 0) <= Date.now())+ .sort(([a], [b]) => {+ const rank = (group: string) => priority.includes(group) ? priority.indexOf(group) : priority.length;+ return rank(a) - rank(b);+ }).slice(0, 12);+ const expectedBase = cache.base;+ const deadline = Date.now() + 20_000;+ async function worker() {+ while (pending.length && !signal.aborted && Date.now() < deadline && cache.base === expectedBase) {+ const [group, models] = pending.shift()!;+ const previous = cache.groups[group];+ const choices = [...models].sort((a, b) => {+ const rank = (id: string) => { const index = preferred[group]?.indexOf(id) ?? -1; return index < 0 ? 100 : index; };+ return rank(a.id) - rank(b.id);+ });+ const representative = (previous?.alternate ? choices.find(model => model.id !== previous.representative) : undefined) ?? choices[0]!;+ const result = await check(representative, bootstrap.modelKey, signal);+ if (signal.aborted || cache.base !== expectedBase) return;+ cache.groups[group] = {+ status: result.status === 'unknown' ? previous?.status ?? 'unknown' : result.status,+ representative: representative.id, alternate: result.alternate,+ nextCheck: Date.now() + (result.status === 'allowed' ? allowedTTL : result.status === 'blocked' ? blockedTTL : retryTTL)+ };+ await save(); await onChange();+ }+ }+ await Promise.all([worker(), worker()]);+ }+ return { prepare, filter, refresh };+}++export type OfficialModelAccess = ReturnType<typeof createOfficialModelAccess>;diff --git a/apps/daemon/src/gateway/official-fetch.ts b/apps/daemon/src/gateway/official-fetch.tsnew file mode 100644index 00000000..7d0a64c0--- /dev/null+++ b/apps/daemon/src/gateway/official-fetch.ts@@ -0,0 +1,70 @@+import { execFile } from 'node:child_process';+import { request as httpsRequest } from 'node:https';+import { Readable } from 'node:stream';+import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib';+import { HttpsProxyAgent } from 'https-proxy-agent';++export function createOfficialFetch(input: {+ readProxy?(): Promise<string>;+ platform?: NodeJS.Platform;+} = {}): typeof fetch {+ let systemProxy: Promise<string> | undefined;+ let proxyCheckedAt = 0;+ async function proxy() {+ const configured = (await input.readProxy?.())?.trim();+ if (configured) return configured;+ if ((input.platform ?? process.platform) !== 'darwin') return '';+ if (!systemProxy || Date.now() - proxyCheckedAt > 30_000) {+ proxyCheckedAt = Date.now();+ systemProxy = new Promise<string>(resolve => {+ execFile('/usr/sbin/scutil', ['--proxy'], { encoding: 'utf8', timeout: 1_000 }, (error, stdout) => {+ if (error) { resolve(''); return; }+ const field = (name: string) => new RegExp(`^\\s*${name}\\s*:\\s*(\\S+)\\s*$`, 'm').exec(stdout)?.[1];+ const host = field('HTTPSProxy');+ const port = Number(field('HTTPSPort'));+ resolve(field('HTTPSEnable') === '1' && host && /^[a-zA-Z0-9.-]+$/.test(host)+ && Number.isInteger(port) && port > 0 && port <= 65535 ? `http://${host}:${port}` : '');+ });+ });+ }+ return systemProxy;+ }+ return async (target, options) => {+ const request = new Request(target, options);+ request.headers.set('Accept-Encoding', 'identity');+ const address = await proxy();+ request.signal.throwIfAborted();+ if (!address || new URL(request.url).protocol !== 'https:') return fetch(request);+ const content = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;+ const headers = Object.fromEntries(request.headers);+ if (content) headers['content-length'] = String(content.length);+ // Return the stream as soon as headers arrive; image persistence owns its deadline.+ return new Promise<Response>((resolve, reject) => {+ const remote = httpsRequest(request.url, {+ method: request.method, headers, agent: new HttpsProxyAgent(address), signal: request.signal+ }, response => {+ const responseHeaders = new Headers();+ for (const [name, value] of Object.entries(response.headers)) {+ if (value !== undefined) responseHeaders.set(name, Array.isArray(value) ? value.join(', ') : value);+ }+ const encoding = responseHeaders.get('content-encoding')?.toLowerCase();+ const decoder = encoding === 'gzip' ? createGunzip()+ : encoding === 'br' ? createBrotliDecompress()+ : encoding === 'deflate' ? createInflate() : undefined;+ const body = decoder ? response.pipe(decoder) : response;+ if (decoder) {+ response.once('error', error => decoder.destroy(error));+ decoder.once('close', () => response.destroy());+ responseHeaders.delete('content-encoding');+ }+ responseHeaders.delete('content-length');+ responseHeaders.delete('transfer-encoding');+ const status = response.statusCode ?? 502;+ resolve(new Response([204, 205, 304].includes(status) ? null+ : Readable.toWeb(body) as ReadableStream<Uint8Array>, { status, headers: responseHeaders }));+ });+ remote.once('error', reject);+ remote.end(content);+ });+ };+}diff --git a/apps/daemon/src/gateway/official-stream.ts b/apps/daemon/src/gateway/official-stream.tsnew file mode 100644index 00000000..838925be--- /dev/null+++ b/apps/daemon/src/gateway/official-stream.ts@@ -0,0 +1,26 @@+// Preserve model output while replacing upstream operational errors with product-facing text.+export function officialEventStream(stream: ReadableStream<Uint8Array>) {+ const decoder = new TextDecoder(); const encoder = new TextEncoder(); let buffered = '';+ function sanitize(frame: string) {+ return frame.split('\n').map(line => {+ if (!line.startsWith('data:')) return line;+ try {+ const value = JSON.parse(line.slice(5)) as { type?: string; message?: string; error?: unknown; response?: { error?: unknown; status?: string } };+ if (value.type === 'error') return `data: ${JSON.stringify({ type: 'error', error: { code: 'official_service_unavailable', message: '官方模型服务暂不可用' } })}`;+ if (value.error) value.error = { code: 'official_service_unavailable', message: '官方模型服务暂不可用' };+ if (value.response?.error) value.response.error = { code: 'official_service_unavailable', message: '官方模型服务暂不可用' };+ return `data: ${JSON.stringify(value)}`;+ } catch { return line; }+ }).join('\n');+ }+ return stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ buffered += decoder.decode(chunk, { stream: true });+ buffered = buffered.replace(/\r\n/g, '\n');+ let boundary: number;+ while ((boundary = buffered.indexOf('\n\n')) >= 0) { controller.enqueue(encoder.encode(sanitize(buffered.slice(0, boundary)) + '\n\n')); buffered = buffered.slice(boundary + 2); }+ if (buffered.length > 1024 * 1024) throw new Error('Official event exceeds the supported size');+ },+ flush(controller) { buffered += decoder.decode(); if (buffered) controller.enqueue(encoder.encode(sanitize(buffered))); }+ }));+}diff --git a/apps/daemon/src/gateway/runtime-bindings.ts b/apps/daemon/src/gateway/runtime-bindings.tsnew file mode 100644index 00000000..0e43d33d--- /dev/null+++ b/apps/daemon/src/gateway/runtime-bindings.ts@@ -0,0 +1,137 @@+import { randomUUID } from 'node:crypto';+import { chmodSync, existsSync, lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { isAbsolute, join } from 'node:path';+import { createDirectRuntime } from './direct-runtime.js';+import { createOfficialFetch } from './official-fetch.js';++export type GatewayRuntimeBindingsInput = {+ codexHome: string;+ baseUrl: string;+ model: string;+ readCredentials(): Promise<{ accountId: string; modelKey: string; keyVersion: string }>;+ closeRuntime(): Promise<void>;+ parentEnvironment?: NodeJS.ProcessEnv;+ direct?: boolean;+ readProxy?(): Promise<string>;+ beginUse?(): Promise<{ key: string; release(): Promise<void> }>;+};++export type GatewayRuntimePreparation = {+ codexHome: string;+ env: Record<string, string>;+ generation: number;+};++export function createGatewayRuntimeBindings(input: GatewayRuntimeBindingsInput) {+ if (!isAbsolute(input.codexHome)) throw new Error('Official Runtime home must be absolute');+ const baseUrl = new URL(input.baseUrl);+ const localTest = baseUrl.protocol === 'http:'+ && ['127.0.0.1', '[::1]'].includes(baseUrl.hostname);+ if ((baseUrl.protocol !== 'https:' && !localTest) || baseUrl.username || baseUrl.password+ || baseUrl.search || baseUrl.hash) throw new Error('Invalid official gateway URL');+ if (!input.model.trim()) throw new Error('Official Runtime model is required');+ let admitting = true;+ let generation = 1;+ let preparation: Promise<GatewayRuntimePreparation> | undefined;+ let closeWork: Promise<void> | undefined;+ let connection: Awaited<ReturnType<typeof createDirectRuntime>> | undefined;+ const environments = new Set<Record<string, string>>();++ function assertOpen(expectedGeneration = generation) {+ if (!admitting || generation !== expectedGeneration) throw new Error('Official Runtime is signed out');+ }++ async function prepare(): Promise<GatewayRuntimePreparation> {+ assertOpen();+ if (preparation !== undefined) return preparation;+ const preparingGeneration = generation;+ preparation = (async () => {+ const credentials = await input.readCredentials();+ assertOpen(preparingGeneration);+ if (!credentials.accountId || !credentials.modelKey || !credentials.keyVersion) {+ throw new Error('Official Runtime credentials are unavailable');+ }+ if (input.direct) {+ if (input.baseUrl !== 'https://openrouter.ai/api/v1') throw new Error('Invalid official endpoint');+ connection ??= await createDirectRuntime(credentials.modelKey, createOfficialFetch({ readProxy: input.readProxy }), input.beginUse);+ assertOpen(preparingGeneration);+ }+ mkdirSync(input.codexHome, { recursive: true, mode: 0o700 });+ if (lstatSync(input.codexHome).isSymbolicLink()) throw new Error('Official Runtime home cannot be a symlink');+ if (existsSync(join(input.codexHome, 'auth.json'))) {+ throw new Error('Official Runtime home contains a persisted credential');+ }+ if (process.platform !== 'win32') chmodSync(input.codexHome, 0o700);+ const config = [+ `model = ${JSON.stringify(input.model)}`,+ 'model_provider = "opencreator_gateway"',+ 'cli_auth_credentials_store = "file"',+ '[shell_environment_policy]',+ 'inherit = "core"',+ 'exclude = ["OC_GATEWAY_MODEL_KEY"]',+ '[model_providers.opencreator_gateway]',+ 'name = "OpenCreator Gateway"',+ `base_url = ${JSON.stringify(connection?.baseUrl ?? baseUrl.href.replace(/\/$/, ''))}`,+ 'env_key = "OC_GATEWAY_MODEL_KEY"',+ 'wire_api = "responses"',+ 'requires_openai_auth = false',+ 'request_max_retries = 0',+ 'stream_max_retries = 0',+ 'supports_websockets = false',+ '[features]',+ 'shell_snapshot = false',+ 'responses_websockets = false',+ 'responses_websockets_v2 = false',+ 'apps = false',+ 'plugins = false',+ 'hooks = false',+ ''+ ].join('\n');+ const temporary = join(input.codexHome, `.config-${randomUUID()}.tmp`);+ try {+ writeFileSync(temporary, config, { flag: 'wx', mode: 0o600 });+ renameSync(temporary, join(input.codexHome, 'config.toml'));+ } finally {+ rmSync(temporary, { force: true });+ }+ const env: Record<string, string> = {};+ const parent = input.parentEnvironment ?? process.env;+ for (const name of ['PATH', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ']) {+ if (parent[name] !== undefined) env[name] = parent[name];+ }+ env.HOME = input.codexHome;+ env.OC_GATEWAY_MODEL_KEY = connection?.token ?? credentials.modelKey;+ environments.add(env);+ return { codexHome: input.codexHome, env, generation: preparingGeneration };+ })();+ try {+ return await preparation;+ } catch (error) {+ await connection?.close(); connection = undefined;+ preparation = undefined;+ throw error;+ }+ }++ function beginLogout() {+ if (!admitting) return;+ admitting = false;+ generation += 1;+ }++ return {+ prepare,+ beginLogout,+ async close() {+ beginLogout();+ closeWork ??= (async () => {+ await input.closeRuntime();+ await connection?.close(); connection = undefined;+ for (const env of environments) delete env.OC_GATEWAY_MODEL_KEY;+ environments.clear();+ preparation = undefined;+ })();+ await closeWork;+ }+ };+}diff --git a/apps/daemon/src/gateway/runtime-source.ts b/apps/daemon/src/gateway/runtime-source.tsnew file mode 100644index 00000000..079c25e0--- /dev/null+++ b/apps/daemon/src/gateway/runtime-source.ts@@ -0,0 +1,39 @@+import type { GatewayAccountState } from '@opencreator/protocol';+import type { AppServerRuntimeManager, AppServerRuntimeTurnInput } from '../codex/app-server-runtime-manager.js';+import { GatewayError } from './client.js';++export function createRuntimeSource(manual: AppServerRuntimeManager, readState: () => GatewayAccountState, readOfficial: () => AppServerRuntimeManager | undefined): AppServerRuntimeManager {+ const officialThreads = new Map<string, string>();+ function current() {+ const state = readState();+ if (state.source === 'manual') return manual;+ const official = readOfficial();+ if (state.authState !== 'signed_in' || state.activationState !== 'ready' || !official) throw new GatewayError('services_not_ready');+ return official;+ }+ function turn(input: AppServerRuntimeTurnInput) {+ const state = readState();+ const manager = current();+ const model = state.models.find(model => model.modality === 'text' && model.id === input.model) ?? state.models.find(model => model.modality === 'text' && model.id === state.selectedModels?.text) ?? state.models.find(model => model.modality === 'text');+ if (state.source === 'manual') return manager.startTurn(input);+ const identity = JSON.stringify([state.account?.id, state.bindingVersion, input.scope.kind, input.scope.id, input.thread.id]);+ return manager.startTurn({ ...input, profile: 'default', model: model?.id, codexThreadId: officialThreads.get(identity), runtimeInjection: undefined,+ async onThreadStarted(id) { officialThreads.set(identity, id); await input.onThreadStarted?.(id); }+ });+ }+ return {+ startTurn: turn,+ acquireScope(scope) {+ const manager = current();+ const acquired = manager.acquireScope(scope);+ return { ...acquired, startTurn(input) { return turn({ ...input, scope }); } };+ },+ closeScope(scope, reason) { return current().closeScope(scope, reason); },+ async closeScopes(predicate, reason) { await manual.closeScopes(predicate, reason); await readOfficial()?.closeScopes(predicate, reason); },+ invalidate(reason) { return manual.invalidate(reason); },+ isScopeBusy(scope) { return manual.isScopeBusy(scope) || readOfficial()?.isScopeBusy(scope) === true; },+ listScopes() { return [...manual.listScopes(), ...(readOfficial()?.listScopes() ?? [])]; },+ async sweepIdle() { await manual.sweepIdle(); await readOfficial()?.sweepIdle(); },+ async close() { await manual.close(); await readOfficial()?.close(); }+ };+}diff --git a/apps/daemon/src/image-generation/provider.ts b/apps/daemon/src/image-generation/provider.tsindex 84585da6..952c480c 100644--- a/apps/daemon/src/image-generation/provider.ts+++ b/apps/daemon/src/image-generation/provider.ts@@ -10,6 +10,8 @@ import {type LocalCodexProvider} from '../codex/local-provider.js';import type { startCodexExec } from '../codex/runner.js';+import { setTimeout as delay } from 'node:timers/promises';+import { DIRECT_IMAGE_TIMEOUT_MS } from '../gateway/direct-transport.js';import { generateCodexNativeImage, type NativeImageProgress } from './codex-native.js';import { inspectCodexImageRuntime, readCodexImageConfiguration } from './codex-runtime.js';import { createKlingAuthorization } from '../creator-services/kling-auth.js';@@ -22,6 +24,7 @@ import {openAiCompatibleEndpoint} from '../creator-services/upstream-fetch.js';import { publicFactsFromFailure } from '../creator/public-error-facts.js';+import { gatewayCreatorBinding } from '../gateway/creator-service-source.js';const MAX_IMAGE_BYTES = 30 * 1024 * 1024;const MAX_RESPONSE_BYTES = 120 * 1024 * 1024;@@ -81,13 +84,17 @@ export async function generateImageContents(referenceImages?: GeneratedImageContent[];codexNative?: CodexNativeImageRuntime;onProgress?(progress: NativeImageProgress): void;+ logicalId?: string;+ onGatewayRequest?(id: string): void;} = {}): Promise<{ model: string; contents: GeneratedImageContent[] }> {+ if (gatewayCreatorBinding(config)) request = { ...request, provider: 'openai' };const referenceImages = options.referenceImages?? (options.referenceImage === undefined ? [] : [options.referenceImage]);- const capabilities = imageGenerationCapabilities(request.provider);+ const gateway = gatewayCreatorBinding(config);+ const capabilities = gateway ? { supportsReferenceImage: gateway.capabilities?.image?.includes('edit') === true, maxReferenceImages: gateway.capabilities?.image?.includes('edit') ? 1 : 0 } : imageGenerationCapabilities(request.provider);const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(new DOMException('图片生成超时,请重试', 'TimeoutError')), REQUEST_TIMEOUT_MS);+ const timeout = setTimeout(() => controller.abort(new DOMException(gateway ? '图片生成等待超时,请先查询请求状态,避免重复扣费' : '图片生成超时,请重试', 'TimeoutError')), gateway ? DIRECT_IMAGE_TIMEOUT_MS + 30_000 : REQUEST_TIMEOUT_MS);const abort = () => controller.abort(options.signal?.reason);timeout.unref();if (options.signal?.aborted) abort();@@ -167,14 +174,19 @@ export async function generateImageContents(config,controller.signal,referenceImages,- options.fetchImpl+ options.fetchImpl,+ undefined,+ options.logicalId,+ options.onGatewayRequest,+ gateway !== undefined);} catch (error) {if (error instanceof ImageGenerationProviderError) throw error;if (options.signal?.aborted) throw error;if (controller.signal.reason instanceof DOMException && controller.signal.reason.name === 'TimeoutError') {- throw new ImageGenerationProviderError('upstream_error', '图片生成超时,请稍后重试',- { kind: 'timeout', provider: request.provider, upstreamMessage: '图片生成超过等待时间,请稍后重试。' }, { cause: error });+ const message = gateway ? '图片生成等待超时,请先查询请求状态,避免重复扣费' : '图片生成超时,请稍后重试';+ throw new ImageGenerationProviderError('upstream_error', message,+ { kind: 'timeout', provider: request.provider, upstreamMessage: message }, { cause: error });}if (nativeExecution && error instanceof Error) {throw new ImageGenerationProviderError('upstream_error', error.message,@@ -200,7 +212,10 @@ async function generateOpenAiImages(signal: AbortSignal,referenceImages: GeneratedImageContent[],fetchImpl?: typeof fetch,- providerOverride?: LocalCodexProvider+ providerOverride?: LocalCodexProvider,+ logicalId?: string,+ onGatewayRequest?: (id: string) => void,+ official = false) {const provider = providerOverride?? (request.provider === 'jimeng' ? config.image.jimeng : config.image.openai);@@ -219,20 +234,23 @@ async function generateOpenAiImages(size: request.size,quality: request.quality,count: request.count,- images: referenceImages+ images: referenceImages,+ ...(official ? { official: true, aspectRatio: request.aspectRatio, resolution: request.resolution, officialQuality: request.officialQuality } : {})});- const response = await fetchCreatorService({+ let response = await fetchCreatorService({endpoint,method: 'POST',headers: {Authorization: `Bearer ${provider.apiKey}`,'Content-Type': multipart?.contentType ?? 'application/json'+ ,...(logicalId ? { 'Idempotency-Key': logicalId } : {})+ ,...(official ? { Prefer: 'respond-async' } : {})},body: multipart?.body ?? JSON.stringify({model,prompt: request.prompt.trim(),size: request.size,- ...(request.provider === 'jimeng' ? {} : { quality: request.quality }),+ ...(official ? { aspect_ratio: request.aspectRatio, resolution: request.resolution, quality: request.officialQuality } : request.provider === 'jimeng' ? {} : { quality: request.quality }),n: request.count}),proxy: config.proxy.trim(),@@ -240,6 +258,39 @@ async function generateOpenAiImages(maxResponseBytes: MAX_RESPONSE_BYTES,fetchImpl});+ const gatewayRequest = response.headers.get('x-request-id');+ if (gatewayRequest && /^[A-Za-z0-9_-]{12,128}$/.test(gatewayRequest)) onGatewayRequest?.(gatewayRequest);+ if (official && response.status === 202) {+ const accepted = await response.json() as { requestId?: string };+ if (!accepted.requestId || accepted.requestId !== gatewayRequest || !/^ocdir_[a-f0-9]{48}$/.test(accepted.requestId)) {+ throw new ImageGenerationProviderError('upstream_error', '图片生成请求回执无效');+ }+ const statusUrl = openAiCompatibleEndpoint(provider.baseUrl, `requests/${accepted.requestId}`);+ for (;;) {+ signal.throwIfAborted();+ const status = await fetchCreatorService({ endpoint: statusUrl, method: 'GET', headers: { Authorization: `Bearer ${provider.apiKey}` }, proxy: config.proxy.trim(), signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]), maxResponseBytes: 16_384, fetchImpl });+ if (!status.ok) {+ void status.body?.cancel().catch(() => undefined);+ throw new ImageGenerationProviderError('upstream_error', '暂时无法查询图片生成结果,请保留任务,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ }+ const receipt = await status.json() as { state?: string; error?: { code?: string; status?: number } };+ if (receipt.state === 'succeeded') {+ response = await fetchCreatorService({ endpoint: appendEndpointPath(statusUrl, 'result'), method: 'GET', headers: { Authorization: `Bearer ${provider.apiKey}` }, proxy: config.proxy.trim(), signal, maxResponseBytes: MAX_RESPONSE_BYTES, fetchImpl });+ if (!response.ok) {+ void response.body?.cancel().catch(() => undefined);+ throw new ImageGenerationProviderError('upstream_error', '图片结果暂时无法下载,请保留任务,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ }+ break;+ }+ if (receipt.state === 'failed') {+ response = Response.json({ error: { code: receipt.error?.code ?? 'official_service_unavailable', message: receipt.error?.code === 'credits_insufficient' ? '积分不足,请补充积分后再试' : '图片生成请求被拒绝' } }, { status: receipt.error?.status ?? 503 });+ break;+ }+ if (receipt.state === 'outcome_unknown') throw new ImageGenerationProviderError('upstream_error', '图片生成结果尚未确认,请先查询请求状态,避免重复扣费', { kind: 'provider-failed', upstreamCode: 'request_outcome_unknown', requestId: accepted.requestId });+ if (!['submitting', 'waiting_upstream'].includes(receipt.state ?? '')) throw new ImageGenerationProviderError('upstream_error', '图片生成请求状态无效');+ await delay(1_000, undefined, { signal });+ }+ }if (!response.ok) {const failure = await creatorServiceErrorInfo(response, 'Image generation', request.provider);throw new ImageGenerationProviderError(@@ -356,6 +407,10 @@ function createImageEditBody(input: {quality: string;count: number;images: GeneratedImageContent[];+ aspectRatio?: string;+ resolution?: string;+ officialQuality?: string;+ official?: boolean;}): { contentType: string; body: Buffer } {const boundary = `opencreator-${crypto.randomUUID()}`;const parts: Buffer[] = [];@@ -371,7 +426,10 @@ function createImageEditBody(input: {addField('model', input.model);addField('prompt', input.prompt);addField('size', input.size);- addField('quality', input.quality);+ if (!input.official) addField('quality', input.quality);+ if (input.aspectRatio) addField('aspect_ratio', input.aspectRatio);+ if (input.resolution) addField('resolution', input.resolution);+ if (input.officialQuality) addField('quality', input.officialQuality);addField('n', String(input.count));for (const [index, image] of input.images.entries()) {const fieldName = input.images.length === 1 ? 'image' : 'image[]';diff --git a/apps/daemon/src/startup.ts b/apps/daemon/src/startup.tsindex 1dd086d5..6dc6590d 100644--- a/apps/daemon/src/startup.ts+++ b/apps/daemon/src/startup.ts@@ -46,8 +46,10 @@ export function resolveProductionServerEnvironment(| 'defaultCwd'| 'defaultProjectRoot'| 'creatorYtDlpPath'+ | 'gatewayOrigin'> {return {+ gatewayOrigin: env.OPENCREATOR_GATEWAY_ORIGIN?.trim() || 'https://www.open-creator.ai',...optionalEnvironmentValue('appHome', env.OPENCREATOR_HOME),...optionalEnvironmentValue('dataDir', env.OPENCREATOR_DATA_DIR),...optionalEnvironmentValue('configFile', env.OPENCREATOR_CONFIG_FILE),diff --git a/apps/daemon/src/storage/migrations.ts b/apps/daemon/src/storage/migrations.tsindex a35e01d3..ab4ff730 100644--- a/apps/daemon/src/storage/migrations.ts+++ b/apps/daemon/src/storage/migrations.ts@@ -717,6 +717,7 @@ export function migrate(db: Database.Database): void {ensureColumn(db, 'creator_artifacts', 'input_fingerprint', 'input_fingerprint TEXT');ensureColumn(db, 'creator_artifacts', 'sha256', 'sha256 TEXT');ensureColumn(db, 'creator_jobs', 'creation_key', 'creation_key TEXT');+ ensureColumn(db, 'creator_jobs', 'service_binding_json', `service_binding_json TEXT NOT NULL DEFAULT '{"source":"manual"}'`);ensureColumn(db,'creator_jobs',@@ -725,6 +726,7 @@ export function migrate(db: Database.Database): void {);ensureColumn(db, 'creator_jobs', 'creation_fingerprint', 'creation_fingerprint TEXT');ensureColumn(db, 'creator_issues', 'public_facts_json', 'public_facts_json TEXT');+ ensureColumn(db, 'creator_provider_requests', 'gateway_binding_json', 'gateway_binding_json TEXT');backfillCreatorCreationFingerprints(db);db.prepare(`UPDATE schedulesdiff --git a/apps/daemon/src/video-generation/service.ts b/apps/daemon/src/video-generation/service.tsindex 34c05007..46aae8f7 100644--- a/apps/daemon/src/video-generation/service.ts+++ b/apps/daemon/src/video-generation/service.ts@@ -1,5 +1,6 @@import {defaultVideoGenerationModels,+ gatewayVideoSizes,videoGenerationDurations,videoGenerationSizes,type CreateVideoGenerationRequest,@@ -24,6 +25,7 @@ import {isRecord} from '../creator-services/upstream-fetch.js';import { publicFactsFromFailure } from '../creator/public-error-facts.js';+import type { GatewayCreatorBinding } from '../gateway/creator-service-source.js';const MAX_PROMPT_LENGTH = 4_000;const MAX_REFERENCE_IMAGE_BYTES = 5 * 1024 * 1024;@@ -38,11 +40,16 @@ type StoredVideoGeneration = {result: VideoGenerationResult;upstreamId: string;generationMode?: 'text-to-video' | 'image-to-video';+ gateway?: { accountId: string; bindingVersion: string; logicalId: string; params: Record<string, unknown> };};export type VideoGenerationOperationOptions = {signal?: AbortSignal;onDownloadStart?(): void;+ logicalId?: string;+ onPending?(id: string): void;+ onGatewayBinding?(binding: { accountId: string; bindingVersion: string; logicalId: string }): void;+ onGatewayRequest?(id: string): void;};export type VideoGenerationService = {@@ -51,6 +58,7 @@ export type VideoGenerationService = {options?: VideoGenerationOperationOptions): Promise<VideoGenerationResult>;get(id: string): Promise<VideoGenerationResult>;+ getGatewayBinding?(id: string): Promise<{ accountId: string; bindingVersion: string; logicalId: string; requestId?: string } | undefined>;refresh(id: string, options?: VideoGenerationOperationOptions): Promise<VideoGenerationResult>;read(id: string): Promise<{ result: VideoGenerationResult; content: Buffer }>;copyTo(id: string, destination: string): Promise<VideoGenerationResult>;@@ -80,6 +88,7 @@ export function createVideoGenerationService(input: {fetchImpl?: typeof fetch;now?: () => Date;createId?: () => string;+ gatewaySource?: { binding(): Promise<GatewayCreatorBinding | undefined> };}): VideoGenerationService {const rootDir = resolve(input.dataDir, 'video-generation');const now = input.now ?? (() => new Date());@@ -109,6 +118,44 @@ export function createVideoGenerationService(input: {}}+ async function gatewayCall(binding: GatewayCreatorBinding, resource: string, options: VideoGenerationOperationOptions, params?: Record<string, unknown>, logicalId?: string) {+ const response = await (input.fetchImpl ?? fetch)(`${binding.baseUrl}/${resource}`, {+ method: params ? 'POST' : 'GET', redirect: 'error', signal: options.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ headers: { Authorization: `Bearer ${binding.apiKey}`, 'Content-Type': 'application/json', ...(logicalId ? { 'Idempotency-Key': logicalId } : {}) },+ ...(params ? { body: JSON.stringify(params) } : {})+ });+ if (!response.ok) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频请求未完成,请查询原任务', response.status);+ return response;+ }+ async function refreshGateway(stored: StoredVideoGeneration, options: VideoGenerationOperationOptions) {+ const source = await input.gatewaySource?.binding();+ if (!source || source.accountId !== stored.gateway?.accountId) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', '请登录原任务账户后查询视频', 403);+ if (stored.result.status === 'completed' || stored.result.status === 'failed') return stored.result;+ const response = stored.upstreamId+ ? await gatewayCall(source, `requests/${encodeURIComponent(stored.upstreamId)}`, options)+ : await gatewayCall(source, 'video/jobs', options, stored.gateway.params, stored.gateway.logicalId);+ const payload = await response.json() as { requestId?: string; state?: string };+ if (!payload.requestId || !/^[A-Za-z0-9_-]{12,128}$/.test(payload.requestId)) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频回执无效', 502);+ stored.upstreamId = payload.requestId;+ options.onGatewayRequest?.(payload.requestId);+ const completed = payload.state === 'succeeded';+ stored.result = { ...stored.result, status: completed ? 'in_progress' : ['failed','canceled'].includes(payload.state ?? '') ? 'failed' : 'in_progress', progress: completed ? 90 : 0, progressKnown: false, updatedAt: now().toISOString() };+ await writeStored(stored);+ if (completed) {+ options.onDownloadStart?.();+ const response = await gatewayCall(source, `requests/${encodeURIComponent(stored.upstreamId)}/result`, options);+ const reader = response.body?.getReader(); const chunks: Buffer[] = []; let size = 0;+ if (!reader) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频结果为空', 502);+ for (;;) { const chunk = await reader.read(); if (chunk.done) break; size += chunk.value.length; if (size > MAX_VIDEO_BYTES) { await reader.cancel(); throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '视频结果过大', 502); } chunks.push(Buffer.from(chunk.value)); }+ const content = Buffer.concat(chunks);+ if (!content.length) throw new VideoGenerationError('VIDEO_GENERATION_UPSTREAM_ERROR', '官方视频结果为空', 502);+ await writeFile(videoPath(stored.result.id), content, { mode: 0o600 });+ stored.result = { ...stored.result, status: 'completed', progress: 100, progressKnown: true, fileName: `OpenCreator-video-${stored.result.id}.mp4`, mime: 'video/mp4', size: content.length };+ await writeStored(stored);+ }+ return stored.result;+ }+async function completeFromPayload(stored: StoredVideoGeneration,payload: Record<string, unknown>,@@ -173,7 +220,20 @@ export function createVideoGenerationService(input: {return {async create(request, options = {}) {- validateRequest(request);+ const gateway = await input.gatewaySource?.binding();+ validateRequest(request, gateway === undefined);+ if (gateway) {+ if (!gateway.models.video || (request.referenceImage && !gateway.capabilities?.video?.includes('image_to_video'))) throw new VideoGenerationError('VIDEO_GENERATION_CONFIG_REQUIRED', '当前官方路由未提供此视频能力', 400);+ if (request.model && request.model !== gateway.models.video) throw new VideoGenerationError('VALIDATION_FAILED', '请选择当前任务的官方视频模型', 400);+ const model = gateway.catalog?.find(candidate => candidate.modality === 'video' && candidate.id === gateway.models.video);+ if (!model || !gatewayVideoSizes(model).includes(request.size) || !model.durations?.includes(request.duration)) throw new VideoGenerationError('VALIDATION_FAILED', '当前官方视频模型不支持所选尺寸或时长', 400);+ const id = createId(); validateResultId(id);+ const logicalId = gateway.logicalId ?? options.logicalId ?? id;+ options.onGatewayBinding?.({accountId:gateway.accountId,bindingVersion:gateway.bindingVersion,logicalId});+ const stored: StoredVideoGeneration = { upstreamId: '', gateway: { accountId: gateway.accountId, bindingVersion: gateway.bindingVersion, logicalId, params: { model: gateway.models.video, prompt: request.prompt.trim(), duration: request.duration, size: request.size, ...(request.referenceImage ? { image: referenceImageDataUrl(request.referenceImage) } : {}) } }, result: { id, prompt: request.prompt.trim(), provider: request.provider, model: gateway.models.video, videoSize: request.size, duration: request.duration, status: 'queued', progress: 0, progressKnown: false, createdAt: now().toISOString(), updatedAt: now().toISOString() } };+ await writeStored(stored); options.onPending?.(id);+ return refreshGateway(stored, options);+ }const config = await input.configStore.read();const operation = operationSignal(options.signal, REQUEST_TIMEOUT_MS);let remote: RemoteVideoJob;@@ -225,8 +285,13 @@ export function createVideoGenerationService(input: {async get(id) {return (await readStored(id)).result;},+ async getGatewayBinding(id) {+ const { gateway, upstreamId } = await readStored(id);+ return gateway ? { accountId: gateway.accountId, bindingVersion: gateway.bindingVersion, logicalId: gateway.logicalId, ...(upstreamId ? { requestId: upstreamId } : {}) } : undefined;+ },async refresh(id, options = {}) {let stored = await readStored(id);+ if (stored.gateway) return refreshGateway(stored, options);if (stored.result.status === 'completed' || stored.result.status === 'failed') return stored.result;const config = await input.configStore.read();const operation = operationSignal(options.signal, REQUEST_TIMEOUT_MS);@@ -701,7 +766,7 @@ function readJobError(facts: PublicErrorFacts): string {+ (facts.upstreamMessage === undefined ? '' : `: ${facts.upstreamMessage}`);}-function validateRequest(request: CreateVideoGenerationRequest) {+function validateRequest(request: CreateVideoGenerationRequest, validateProvider = true) {if (!isRecord(request)) {throw new VideoGenerationError('VALIDATION_FAILED', 'request body must be an object', 400);}@@ -726,14 +791,14 @@ function validateRequest(request: CreateVideoGenerationRequest) {400);}- if (!(videoGenerationSizes as readonly unknown[]).includes(request.size)) {+ if (validateProvider && !(videoGenerationSizes as readonly unknown[]).includes(request.size)) {throw new VideoGenerationError('VALIDATION_FAILED', 'video size is invalid', 400);}- if (!(videoGenerationDurations as readonly unknown[]).includes(request.duration)) {+ if (validateProvider && !(videoGenerationDurations as readonly unknown[]).includes(request.duration)) {throw new VideoGenerationError('VALIDATION_FAILED', 'video duration is invalid', 400);}const validDurations = request.provider === 'veo' ? [4, 6, 8] : [5, 10];- if (!validDurations.includes(request.duration)) {+ if (validateProvider && !validDurations.includes(request.duration)) {throw new VideoGenerationError('VALIDATION_FAILED', `video duration is not supported by ${request.provider}`, 400);}validateReferenceImage(request.referenceImage);@@ -779,17 +844,17 @@ function isStoredVideoGeneration(value: unknown): value is StoredVideoGeneration|| value.generationMode === 'text-to-video'|| value.generationMode === 'image-to-video')- && isVideoGenerationResult(value.result);+ && isVideoGenerationResult(value.result, isRecord(value.gateway));}-function isVideoGenerationResult(value: unknown): value is VideoGenerationResult {+function isVideoGenerationResult(value: unknown, official = false): value is VideoGenerationResult {return isRecord(value)&& typeof value.id === 'string'&& typeof value.prompt === 'string'&& (videoProviders as readonly unknown[]).includes(value.provider)&& typeof value.model === 'string'- && (videoGenerationSizes as readonly unknown[]).includes(value.videoSize)- && (videoGenerationDurations as readonly unknown[]).includes(value.duration)+ && (official ? typeof value.videoSize === 'string' && /^(?:\d+x\d+|[A-Za-z0-9._-]+@\d+:\d+)$/.test(value.videoSize) : (videoGenerationSizes as readonly unknown[]).includes(value.videoSize))+ && (official ? typeof value.duration === 'number' && Number.isInteger(value.duration) && value.duration > 0 && value.duration <= 600 : (videoGenerationDurations as readonly unknown[]).includes(value.duration))&& (value.status === 'queued' || value.status === 'in_progress' || value.status === 'completed' || value.status === 'failed')&& typeof value.progress === 'number'&& (value.progressKnown === undefined || typeof value.progressKnown === 'boolean')diff --git a/apps/daemon/test/integration/creator-api.test.ts b/apps/daemon/test/integration/creator-api.test.tsindex a200f550..69350e15 100644--- a/apps/daemon/test/integration/creator-api.test.ts+++ b/apps/daemon/test/integration/creator-api.test.ts@@ -14,6 +14,7 @@ import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';import { buildServer } from '../../src/api/server.js';import type { AgentRuntimeAdapter } from '../../src/creator/agent/runtime-adapter.js';import type { CreatorExecutor } from '../../src/creator/executor.js';+import { createGatewayConfigStore } from '../../src/gateway/config-store.js';let server: FastifyInstance | undefined;let tempDir = '';@@ -300,6 +301,45 @@ describe('creator api', () => {});});+ it('allows signed-out gateway users to browse presets without granting model access', async () => {+ await setupServer({ gatewayMode: true });+ const account = await request('GET', '/gateway/account');+ expect(account.json()).toMatchObject({+ source: 'gateway', authState: 'signed_out', activationState: 'inactive'+ });++ const catalog = await request('GET', '/creator/presets?locale=zh-CN');+ expect(catalog.statusCode).toBe(200);+ const imagePreset = catalog.json().presets.find(+ (preset: { module: string }) => preset.module === 'image-generation'+ );+ expect(imagePreset).toMatchObject({+ title: expect.any(String),+ coverUrl: expect.stringMatching(/^\/creator-presets\/[a-f0-9]{64}\.(?:jpg|png|webp)$/)+ });+ const cover = await server!.inject({+ method: 'GET',+ url: imagePreset.coverUrl,+ headers: { authorization: 'Bearer secret' }+ });+ expect(cover.statusCode).toBe(200);+ expect(cover.headers['content-type']).toMatch(/^image\//);+ expect(cover.rawPayload.byteLength).toBeGreaterThan(1_000);++ const modelConfig = await request('GET', '/creator-services/config');+ expect(modelConfig.statusCode).toBe(401);+ const created = await request('POST', '/creator/jobs', {+ projectId: 'project_signed_out',+ preset: { module: imagePreset.module, id: imagePreset.id, version: imagePreset.version },+ locale: 'zh-CN',+ creationKey: 'signed-out-preset-creation'+ });+ expect(created.statusCode).toBe(401);+ expect(created.json().code).toBe('auth_required');+ expect((await request('GET', '/creator/jobs?projectId=project_signed_out')).json().jobs)+ .toHaveLength(0);+ });+it('lists localized presets and creates a real preset job', async () => {await setupServer();const catalog = await request('GET', '/creator/presets?locale=en-US');@@ -920,6 +960,7 @@ describe('creator api', () => {async function setupServer(options: {llmConfigured?: boolean;+ gatewayMode?: boolean;agentRuntime?: AgentRuntimeAdapter;creatorSourceMediaProbe?(path: string): Promise<{duration: number;@@ -931,6 +972,11 @@ async function setupServer(options: {creatorExecutors?: CreatorExecutor[];} = {}): Promise<void> {tempDir = mkdtempSync(join(tmpdir(), 'creator-api-'));+ if (options.gatewayMode) {+ await createGatewayConfigStore(tempDir).writeConfiguration({+ source: 'gateway', bindingVersion: null+ });+ }const config = createDefaultCreatorServicesConfig();config.llm.source = 'custom';if (options.llmConfigured !== false) {diff --git a/apps/daemon/test/integration/creator-gateway-services.test.ts b/apps/daemon/test/integration/creator-gateway-services.test.tsnew file mode 100644index 00000000..cbfe20fa--- /dev/null+++ b/apps/daemon/test/integration/creator-gateway-services.test.ts@@ -0,0 +1,220 @@+import Fastify from 'fastify';+import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';+import { afterEach, expect, it, vi } from 'vitest';+import * as module from '../../src/gateway/creator-service-source.js';+import { createVideoGenerationService } from '../../src/video-generation/service.js';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { openRuntimeDatabase } from '../../src/storage/database.js';+import { createCreatorRepository } from '../../src/creator/repository.js';+import { CreatorProviderRequestLedger } from '../../src/creator/provider-requests.js';++const close: Array<() => Promise<void>> = [];+afterEach(async () => { for (const callback of close.splice(0)) await callback(); });+it('reuses the persisted legacy request identity after acceptance loss and Daemon restart', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-gateway-restart-'));+ const upstream = Fastify();+ const identities: string[] = [];+ const accepted = new Set<string>();+ upstream.post('/v1/chat/completions', async (request, reply) => {+ const identity = request.headers['idempotency-key'] as string;+ identities.push(identity); accepted.add(identity);+ if (identities.length === 1) { reply.hijack(); reply.raw.destroy(); return; }+ return reply.header('X-Request-ID', 'gateway_original_receipt').send({ choices: [{ message: { content: 'original result' } }] });+ });+ upstream.get('/v1/requests/gateway_original_receipt', async () => ({ requestId: 'gateway_original_receipt', state: 'succeeded' }));+ const origin = await upstream.listen({ host: '127.0.0.1', port: 0 });+ let db = openRuntimeDatabase(join(root, 'runtime.sqlite'));+ let repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'wechat-article', templateVersion: 1, status: 'running', state: {} });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'article', executor: 'wechat-article', status: 'running' });+ let currentStage = stage.id;+ const manual = createDefaultCreatorServicesConfig();+ const buildSource = () => module.createGatewayCreatorSource({+ ledger: new CreatorProviderRequestLedger(repository),+ readJobBinding: () => ({ source: 'gateway', accountId: 'a', bindingVersion: 'a:1', models: { text: 'text' }, capabilities: { text: ['chat'] } }),+ readStageRun: (id: string) => repository.getStageRun(id),+ account: { peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null }), modelCredentials: async () => ({ accountId: 'a', modelKey: 'cloud-secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: `${origin}/v1`, defaults: { text: 'text' }, models: [] }) },+ manual: { read: async () => manual, write: async c => c, reset: async () => manual }, getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ let server = Fastify();+ let source = buildSource();+ const submit = () => source.runForJob(job.id, currentStage, async () => {+ const config = await source.store.read();+ return server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions', headers: { Authorization: `Bearer ${config.llm.apiKey}` }, payload: { model: 'text', messages: [{ role: 'user', content: 'write article' }] } });+ });+ try {+ await source.register(server);+ expect((await submit()).statusCode).toBe(503);+ expect(repository.getJob(job.id)!.providerRequests).toHaveLength(1);+ expect(repository.getJob(job.id)!.providerRequests[0]!.status).toBe('unknown_remote_acceptance');+ await source.revoke(); await server.close(); db.close();+ db = openRuntimeDatabase(join(root, 'runtime.sqlite')); repository = createCreatorRepository(db);+ currentStage = repository.createStageRun({ jobId: job.id, stageId: 'article', executor: 'wechat-article', status: 'running', progress: { resumedFromStageRunId: stage.id } }).id;+ server = Fastify(); source = buildSource(); await source.register(server);+ expect((await submit()).statusCode).toBe(200);+ await vi.waitFor(() => expect(repository.getJob(job.id)!.providerRequests[0]).toMatchObject({ status: 'succeeded', remoteTaskId: 'gateway_original_receipt' }));+ expect(repository.getJob(job.id)!.providerRequests).toHaveLength(1);+ expect(identities).toHaveLength(2);+ expect(identities[1]).toBe(identities[0]);+ expect(accepted.size).toBe(1);+ } finally {+ await source.revoke(); await server.close(); db.close(); await upstream.close(); await rm(root, { recursive: true, force: true });+ }+});+it('stores one original gateway receipt for managed legacy model retries', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-gateway-receipt-')); close.push(() => rm(root, { recursive: true, force: true }));+ const db = openRuntimeDatabase(join(root, 'runtime.sqlite')); close.push(async () => { db.close(); });+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'wechat-article', templateVersion: 1, status: 'running', state: {} });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'article', executor: 'wechat-article', status: 'running' });+ const manual = createDefaultCreatorServicesConfig();+ const server = Fastify(); close.push(() => server.close());+ const state = { source: 'gateway' as const, authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null };+ const source = module.createGatewayCreatorSource({ ledger: new CreatorProviderRequestLedger(repository),+ readJobBinding: () => ({ source: 'gateway', accountId: 'a', bindingVersion: 'a:1', models: { text: 'text' }, capabilities: { text: ['chat'] } }),+ account: { peekState: () => state, modelCredentials: async () => ({ accountId: 'a', modelKey: 'cloud-secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { text: 'text' }, models: [] }) },+ manual: { read: async () => manual, write: async c => c, reset: async () => manual }, getLocalOrigin: () => 'http://127.0.0.1:39999',+ fetcher: vi.fn(async (_url, options) => options?.method === 'GET'+ ? Response.json({ requestId: 'gateway_original_receipt', state: 'succeeded' })+ : Response.json({ choices: [{ message: { content: 'article' } }] }, { headers: { 'X-Request-ID': 'gateway_original_receipt' } }))+ });+ await source.register(server);+ await source.runForJob(job.id, stage.id, async () => {+ const config = await source.store.read();+ for (let retry = 0; retry < 2; retry++) {+ expect((await server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions', headers: { Authorization: `Bearer ${config.llm.apiKey}` }, payload: { model: 'text', messages: [{ role: 'user', content: 'write article' }] } })).statusCode).toBe(200);+ }+ });+ await vi.waitFor(() => expect(repository.getJob(job.id)!.providerRequests).toHaveLength(1));+ await vi.waitFor(() => expect(repository.getJob(job.id)!.providerRequests[0]).toMatchObject({ gateway: { accountId: 'a', bindingVersion: 'a:1' }, remoteTaskId: 'gateway_original_receipt', status: 'succeeded' }));+ await source.revoke();+});+it('official services share one local capability and inject the cloud Key only during forwarding', async () => {+ expect(module).toHaveProperty('createGatewayCreatorSource', expect.any(Function));+ const manual = createDefaultCreatorServicesConfig(); manual.llm.apiKey = 'personal-key';+ let active = true;+ let coordinatedUses = 0;+ const state = { source: 'gateway' as const, authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null };+ const credentials = { accountId: 'a', modelKey: 'cloud-secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { text: 'text', image: 'image', speech: 'speech', transcription: 'transcription', video: 'video' }, models: ['text','image','speech','transcription','video'].map(id => ({ id, modality: id as 'text', capabilities: [] })) };+ const server = Fastify(); close.push(() => server.close());+ const fetcher = vi.fn(async (_url, options) => {+ expect(coordinatedUses).toBe(1);+ return new Response(JSON.stringify({ usage: {}, text: 'ok' }), { status: 200, headers: { 'Content-Type': 'application/json', 'X-Request-ID': 'owned-request' } });+ }) as typeof fetch;+ const source = module.createGatewayCreatorSource({+ account: { peekState: () => state, modelCredentials: async () => { if (!active) throw new Error('signed out'); return credentials; },+ beginModelUse: async () => { if (!active) throw new Error('signed out'); coordinatedUses++; return { credentials, async release() { coordinatedUses--; } }; } },+ manual: { read: async () => structuredClone(manual), write: async config => config, reset: async () => manual },+ getLocalOrigin: () => 'http://127.0.0.1:39999', fetcher,+ readJobBinding: () => ({ source: 'gateway', accountId: 'a', bindingVersion: 'a:1', models: credentials.defaults, capabilities: {} })+ });+ await source.register(server);+ const config = await source.store.read();+ expect(config.llm.apiKey).not.toBe('cloud-secret');+ expect(config.image.openai.apiKey).toBe(config.llm.apiKey);+ expect(config.tts.openai.apiKey).toBe(config.llm.apiKey);+ expect(config.transcription.openai.apiKey).toBe(config.llm.apiKey);+ for (const operation of ['chat/completions','images/generations','audio/speech','audio/transcriptions']) {+ const res = await server.inject({ method: 'POST', url: `/internal/krillin-llm/gateway/v1/${operation}`, headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Idempotency-Key': `stable-${operation}` }, payload: { model: credentials.defaults.text, input: 'hello' } });+ expect(res.statusCode).toBe(200);+ const options = vi.mocked(fetcher).mock.lastCall?.[1];+ expect(new Headers(options?.headers).get('Authorization')).toBe('Bearer cloud-secret');+ expect(new Headers(options?.headers).get('Idempotency-Key')).toBe(`stable-${operation}`);+ await vi.waitFor(() => expect(coordinatedUses).toBe(0));+ }+ await source.runForJob('job-original', 'stage-original', async () => {+ const scoped = await source.store.read();+ const call = () => server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions', headers: { Authorization: `Bearer ${scoped.llm.apiKey}` }, payload: { model: 'text', messages: [{ role: 'user', content: 'retry the same work' }] } });+ await call();+ const first = new Headers(vi.mocked(fetcher).mock.lastCall?.[1]?.headers).get('Idempotency-Key');+ await call();+ expect(new Headers(vi.mocked(fetcher).mock.lastCall?.[1]?.headers).get('Idempotency-Key')).toBe(first);+ const multipart = async () => {+ const form = new FormData(); form.set('model', 'transcription'); form.set('file', new Blob(['same audio'], { type: 'audio/wav' }), 'audio.wav');+ const request = new Request('http://localhost', { method: 'POST', body: form });+ await server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/audio/transcriptions', headers: { Authorization: `Bearer ${scoped.llm.apiKey}`, 'Content-Type': request.headers.get('Content-Type')! }, payload: Buffer.from(await request.arrayBuffer()) });+ return new Headers(vi.mocked(fetcher).mock.lastCall?.[1]?.headers).get('Idempotency-Key');+ };+ expect(await multipart()).toBe(await multipart());+ });+ const originalAccount = state.account;+ state.account = { ...originalAccount, id: 'b' };+ await expect(source.runForJob('job-original', 'stage-original', async () => source.store.read())).rejects.toThrow();+ state.account = originalAccount;+ let forwardingSignal: AbortSignal | undefined;+ let release!: () => void;+ vi.mocked(fetcher).mockImplementationOnce(async (_url, options) => new Promise<Response>((_resolve, reject) => {+ forwardingSignal = options!.signal!;+ release = () => reject(new Error('request closed'));+ forwardingSignal.addEventListener('abort', release, { once: true });+ }));+ const pending = server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions', headers: { Authorization: `Bearer ${config.llm.apiKey}` }, payload: { model: 'text' } });+ await vi.waitFor(() => expect(forwardingSignal).toBeDefined());+ await source.revoke();+ try { expect(forwardingSignal!.aborted).toBe(true); } finally { release(); await pending; }+ active = false; await source.revoke();+ expect((await server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions', headers: { Authorization: `Bearer ${config.llm.apiKey}` }, payload: {} })).statusCode).toBe(401);+ expect(manual.llm.apiKey).toBe('personal-key');+});++it('uses a task-specific official model without changing account defaults and rejects custom choices before execution', async () => {+ const models = [{ id: 'official/text', modality: 'text' as const, capabilities: ['responses'] }, { id: 'official/image-first', modality: 'image' as const, capabilities: [] }, { id: 'official/image-second', modality: 'image' as const, capabilities: ['edit'] }];+ const state = { source: 'gateway' as const, authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', selectedModels: { text: 'official/text', image: 'official/image-first' }, models, activationError: null };+ const credentials = { accountId: 'a', modelKey: 'cloud-secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { ...state.selectedModels }, models };+ let choices = { image: 'official/image-second' };+ const manual = createDefaultCreatorServicesConfig();+ const fetcher = vi.fn<typeof fetch>(async () => Response.json({ data: [] }));+ const source = module.createGatewayCreatorSource({+ account: { peekState: () => state, modelCredentials: async () => credentials },+ manual: { read: async () => manual, write: async c => c, reset: async () => manual },+ getLocalOrigin: () => 'http://127.0.0.1:39999', fetcher,+ readJobBinding: () => ({ source: 'gateway', accountId: 'a', bindingVersion: 'a:1', models: { ...credentials.defaults }, capabilities: { text: ['responses'], image: [] } }),+ readJobState: () => ({ officialModels: choices })+ });+ const server = Fastify(); close.push(() => server.close());+ await source.register(server);+ await source.runForJob('job', 'stage', async () => {+ const config = await source.store.read();+ expect(config.image.openai.model).toBe('official/image-second');+ expect(module.gatewayCreatorBinding(config)?.capabilities?.image).toEqual(['edit']);+ expect((await server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/images/generations', headers: { Authorization: `Bearer ${config.image.openai.apiKey}` }, payload: { model: config.image.openai.model, prompt: 'draw' } })).statusCode).toBe(200);+ });+ expect(JSON.parse(String(fetcher.mock.lastCall?.[1]?.body))).toMatchObject({ model: 'official/image-second' });+ expect(credentials.defaults.image).toBe('official/image-first');+ expect(state.selectedModels.image).toBe('official/image-first');+ choices = { image: 'personal-model' };+ const execute = vi.fn();+ await expect(source.runForJob('job', 'stage', execute)).rejects.toMatchObject({ code: 'invalid_model' });+ expect(execute).not.toHaveBeenCalled();+ expect(fetcher).toHaveBeenCalledOnce();+ await source.revoke();+});++it('video uses the unified gateway task and preserves its account for query and download', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-gateway-video-')); close.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async (url: URL | RequestInfo, options?: RequestInit) => {+ if (String(url).endsWith('/video/jobs')) return Response.json({ requestId: 'gateway_request_original', state: 'waiting_upstream' }, { status: 202 });+ if (String(url).endsWith('/result')) return new Response(new Uint8Array([1,2,3]), { headers: { 'Content-Type': 'video/mp4' } });+ return Response.json({ requestId: 'gateway_request_original', state: 'succeeded' });+ }) as typeof fetch;+ const binding = { accountId: 'a', bindingVersion: 'a:1', baseUrl: 'http://127.0.0.1:39999/internal/krillin-llm/gateway/v1', apiKey: 'local-token', models: { video: 'gateway-video' }, catalog: [{ id: 'gateway-video', modality: 'video' as const, capabilities: [], sizes: ['1280x720', '720x1280'], durations: [4, 5] }] };+ const service = createVideoGenerationService({ dataDir: root, configStore: { read: async () => createDefaultCreatorServicesConfig(), write: async c => c, reset: async () => createDefaultCreatorServicesConfig() }, fetchImpl: fetcher, gatewaySource: { binding: async () => binding } });+ await expect(service.create({ prompt: 'test', provider: 'seedance', model: 'personal-model', size: '1280x720', duration: 5 })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ await expect(service.create({ prompt: 'test', provider: 'seedance', size: '1024x1024', duration: 5 })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ await expect(service.create({ prompt: 'test', provider: 'seedance', size: '1280x720', duration: 8 })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ expect(fetcher).not.toHaveBeenCalled();+ const result = await service.create({ prompt: 'test', provider: 'seedance', size: '1280x720', duration: 5 }, { logicalId: 'stage-original' });+ expect(result.status).toBe('in_progress');+ expect(String(vi.mocked(fetcher).mock.calls[0]?.[0])).toContain('/video/jobs');+ expect(JSON.parse(String(vi.mocked(fetcher).mock.calls[0]?.[1]?.body))).toMatchObject({ model: 'gateway-video', size: '1280x720', duration: 5 });+ expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get('Idempotency-Key')).toBe('stage-original');+ const completed = await service.refresh(result.id);+ expect(completed.status).toBe('completed');+ expect((await service.read(result.id)).content).toEqual(Buffer.from([1,2,3]));+ binding.accountId = 'other';+ await expect(service.refresh(result.id)).rejects.toThrow();+ binding.accountId = 'a';+ await expect(service.create({ prompt: 'official model duration', provider: 'veo', size: '720x1280', duration: 5 })).resolves.toMatchObject({ status: 'in_progress', videoSize: '720x1280' });+});diff --git a/apps/daemon/test/integration/creator-network-settings.test.ts b/apps/daemon/test/integration/creator-network-settings.test.tsnew file mode 100644index 00000000..af394f8c--- /dev/null+++ b/apps/daemon/test/integration/creator-network-settings.test.ts@@ -0,0 +1,43 @@+import Fastify from 'fastify';+import { afterEach, expect, it, vi } from 'vitest';+import { createDefaultCreatorServicesConfig, type GatewayAccountState } from '@opencreator/protocol';+import { registerCreatorServicesRoutes } from '../../src/api/routes.creator-services.js';+import { createGatewayCreatorSource } from '../../src/gateway/creator-service-source.js';++const servers: ReturnType<typeof Fastify>[] = [];+afterEach(async () => { for (const server of servers.splice(0)) await server.close(); });++it('edits shared networking while signed in and preserves all custom settings across sign-out', async () => {+ let custom = createDefaultCreatorServicesConfig();+ custom.llm = { source: 'custom', baseUrl: 'https://custom.test/v1', apiKey: 'private-key', model: 'custom-model', jsonMode: false };+ const original = structuredClone(custom);+ const network = { read: async () => structuredClone(custom), write: async (config: typeof custom) => { custom = config; return config; }, reset: async () => { custom = createDefaultCreatorServicesConfig(); return custom; } };+ const models = [{ id: 'official/text', modality: 'text' as const, capabilities: ['responses'] }];+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: '1', models, activationError: null };+ const source = createGatewayCreatorSource({ manual: network, getLocalOrigin: () => 'http://127.0.0.1:1234', account: {+ peekState: () => state, modelCredentials: async () => ({ accountId: 'a', bindingVersion: '1', keyVersion: '1', baseUrl: 'https://official.test', modelKey: 'official-key', models, defaults: { text: 'official/text' } })+ } });+ const server = Fastify(); servers.push(server);+ await registerCreatorServicesRoutes(server, source.store, undefined, undefined, undefined, undefined, undefined, network);+ const proxy = 'http://127.0.0.1:7897';+ expect((await server.inject({ method: 'PATCH', url: '/creator-services/network', payload: { proxy } })).json()).toEqual({ proxy });+ expect((await server.inject('/creator-services/network')).body).not.toContain('private-key');+ expect(await source.store.read()).toMatchObject({ proxy, llm: { model: 'official/text' } });+ expect(custom).toEqual({ ...original, proxy });+ state.source = 'manual'; state.authState = 'signed_out';+ expect(await source.store.read()).toEqual({ ...original, proxy });+ const staleForm = { ...original, proxy: '', llm: { ...original.llm, apiKey: '', model: 'edited-model' } };+ expect((await server.inject({ method: 'PATCH', url: '/creator-services/config', payload: staleForm })).statusCode).toBe(200);+ expect(custom.proxy).toBe(proxy); expect(custom.llm.apiKey).toBe('private-key'); expect(custom.llm.model).toBe('edited-model');+ expect((await server.inject({ method: 'DELETE', url: '/creator-services/config' })).statusCode).toBe(200);+ expect(custom.proxy).toBe(proxy);+ expect((await server.inject({ method: 'PATCH', url: '/creator-services/network', payload: { proxy: '' } })).json()).toEqual({ proxy: '' });+});++it.each([{ proxy: 'socks5://127.0.0.1:1080' }, { proxy: 'http://127.0.0.1:7897/path' }, { proxy: '', llm: {} }])('rejects invalid or unrelated network fields: %j', async payload => {+ const config = createDefaultCreatorServicesConfig();+ const store = { read: async () => config, write: vi.fn(async () => config), reset: async () => config };+ const server = Fastify(); servers.push(server); await registerCreatorServicesRoutes(server, store);+ expect((await server.inject({ method: 'PATCH', url: '/creator-services/network', payload })).statusCode).toBe(400);+ expect(store.write).not.toHaveBeenCalled();+});diff --git a/apps/daemon/test/integration/direct-services.test.ts b/apps/daemon/test/integration/direct-services.test.tsnew file mode 100644index 00000000..880ac091--- /dev/null+++ b/apps/daemon/test/integration/direct-services.test.ts@@ -0,0 +1,307 @@+import Fastify from 'fastify';+import { mkdtemp, rm } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { afterEach, expect, it, vi } from 'vitest';+import { createDefaultCreatorServicesConfig, gatewayDefaultVoiceId, type GatewayModel } from '@opencreator/protocol';+import { createGatewayCreatorSource } from '../../src/gateway/creator-service-source.js';+import { createDirectTransport } from '../../src/gateway/direct-transport.js';+import { createDirectRuntime } from '../../src/gateway/direct-runtime.js';+import { registerCreatorServicesRoutes } from '../../src/api/routes.creator-services.js';+import { createVideoGenerationService } from '../../src/video-generation/service.js';+import { officialEventStream } from '../../src/gateway/official-stream.js';+import { createKrillinTtsService } from '../../src/creator/krillin/tts-service.js';+import { generateImageContents } from '../../src/image-generation/provider.js';+import { readPrivateJsonFile } from '../../src/config/private-json-file.js';+import { openRuntimeDatabase } from '../../src/storage/database.js';+import { createCreatorRepository } from '../../src/creator/repository.js';+import { CreatorProviderRequestLedger } from '../../src/creator/provider-requests.js';+import { createCreatorIssueService } from '../../src/creator/issues.js';+import { createImageExecutor } from '../../src/creator/image/executor.js';++const cleanup: Array<() => Promise<void>> = [];+afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); });+it('redacts provider errors from fragmented events while preserving model text', async () => {+ const encoder = new TextEncoder();+ const source = new ReadableStream<Uint8Array>({ start(controller) {+ controller.enqueue(encoder.encode('data: {"type":"response.output_text.delta","delta":"hello"}\n\ndata: {"type":"error","error":{"message":"OpenRou'));+ controller.enqueue(encoder.encode('ter private service failure"}}\n\n')); controller.close();+ } });+ const text = await new Response(officialEventStream(source)).text();+ expect(text).toContain('hello'); expect(text).not.toContain('OpenRouter'); expect(text).toContain('official_service_unavailable');+});+async function fixture(ledger?: CreatorProviderRequestLedger) {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const manual = createDefaultCreatorServicesConfig(); manual.llm = { source: 'custom', baseUrl: 'https://personal.test/v1', apiKey: 'personal-key', model: 'personal-model', jsonMode: true };+ const models: GatewayModel[] = [+ { id: 'vendor/text', modality: 'text' as const, capabilities: ['responses', 'chat'] },+ { id: 'vendor/image', modality: 'image' as const, capabilities: ['edit'] },+ { id: 'vendor/video', modality: 'video' as const, capabilities: ['image_to_video'], sizes: ['1280x720', '720x1280'], durations: [5, 10] },+ { id: 'vendor/speech', modality: 'speech' as const, capabilities: [], voices: ['tested_voice'] },+ { id: 'vendor/transcription', modality: 'transcription' as const, capabilities: [] }+ ];+ const defaults = Object.fromEntries(models.map(model => [model.modality, model.id]));+ const state = { source: 'gateway' as 'gateway' | 'manual', authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: 'a:1', models, selectedModels: defaults, activationError: null };+ const fetcher = vi.fn(async (url: URL | RequestInfo, options?: RequestInit) => {+ if (String(url).endsWith('/videos')) return Response.json({ id: 'video_upstream', status: 'pending' });+ if (String(url).includes('/videos/video_upstream/content')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'Content-Type': 'video/mp4' } });+ if (String(url).endsWith('/videos/video_upstream')) return Response.json({ status: 'completed' });+ if (String(url).endsWith('/audio/speech')) return new Response('audio', { headers: { 'Content-Type': 'audio/mpeg' } });+ if (String(url).endsWith('/audio/transcriptions')) return Response.json({ text: 'recognized' });+ if (String(url).endsWith('/images')) return Response.json({ data: [{ b64_json: 'aW1hZ2U=' }] });+ return Response.json({ choices: [{ message: { content: 'text result' } }] });+ }) as typeof fetch;+ const source = createGatewayCreatorSource({ directRequestsRoot: join(root, 'receipts'), ledger,+ account: { peekState: () => state, modelCredentials: async () => ({ accountId: 'a', bindingVersion: 'a:1', keyVersion: '1', modelKey: 'private-user-key', baseUrl: 'https://openrouter.ai/api/v1', transport: 'openrouter-direct', models, defaults }) },+ manual: { read: async () => structuredClone(manual), write: async config => config, reset: async () => manual }, getLocalOrigin: () => 'http://127.0.0.1:39999', fetcher+ });+ const server = Fastify(); cleanup.push(() => server.close()); cleanup.push(() => source.revoke());+ await source.register(server); await registerCreatorServicesRoutes(server, source.store);+ return { server, source, fetcher, state, manual, root };+}+it('reconciles a streamed chat result without creating an unknown-acceptance issue', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-chat-ledger-'));+ const db = openRuntimeDatabase(join(root, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const issues = createCreatorIssueService(repository);+ const f = await fixture(new CreatorProviderRequestLedger(repository, issues));+ const job = repository.createJob({ projectId: 'project', templateId: 'video-translation', templateVersion: 1, status: 'running', state: {} });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'subtitle', executor: 'krillinai', status: 'running' });+ vi.mocked(f.fetcher).mockImplementation(async () => new Response(new ReadableStream<Uint8Array>({+ start(controller) { controller.enqueue(new TextEncoder().encode('data: {"choices":[{"delta":{"content":"translated"}}]}\n\ndata: [DONE]\n\n')); }+ }), { headers: { 'Content-Type': 'text/event-stream' } }));+ try {+ await f.source.runForJob(job.id, stage.id, async () => {+ const config = await f.source.store.read();+ const response = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/chat/completions',+ headers: { Authorization: 'Bearer ' + config.llm.apiKey }, payload: { model: 'vendor/text', messages: [], stream: true } });+ expect(response.statusCode).toBe(200);+ expect(response.body).toContain('[DONE]');+ });+ await vi.waitFor(() => expect(repository.listProviderRequests(job.id)).toMatchObject([{ status: 'succeeded' }]));+ expect(issues.list(job.id)).toHaveLength(0);+ expect(f.fetcher).toHaveBeenCalledOnce();+ } finally { await f.source.revoke(); db.close(); await rm(root, { recursive: true, force: true }); }+});+it('hides official addresses and credentials, preserving custom configuration across source switches', async () => {+ const f = await fixture();+ const official = (await f.server.inject('/creator-services/config')).json();+ expect(JSON.stringify(official)).not.toMatch(/openrouter|oclocal_|private-user-key|personal-key|39999/i);+ expect(official.config.llm.baseUrl).toBe('');+ f.state.source = 'manual'; const custom = await f.source.store.read();+ expect(custom.llm).toMatchObject({ baseUrl: 'https://personal.test/v1', apiKey: 'personal-key', model: 'personal-model' });+ f.state.source = 'gateway'; expect((await f.source.store.read()).llm.model).toBe('vendor/text');+ expect(f.manual.llm.apiKey).toBe('personal-key');+});+it('sends multimodal requests directly, translates image edits, and replays a paid result locally', async () => {+ const f = await fixture(); const config = await f.source.store.read();+ const submit = (operation: string, payload: Record<string, unknown>, key = operation) => f.server.inject({ method: 'POST', url: `/internal/krillin-llm/gateway/v1/${operation}`, headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Idempotency-Key': key }, payload });+ expect((await submit('chat/completions', { model: 'vendor/text', messages: [{ role: 'user', content: 'hello' }] })).statusCode).toBe(200);+ expect((await submit('images/generations', { model: 'vendor/image', prompt: 'image', n: 1, size: '1536x1024', response_format: 'b64_json' })).statusCode).toBe(200);+ const imageBody = JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body));+ expect(imageBody).toMatchObject({ aspect_ratio: '3:2', output_format: 'png' });+ expect(imageBody).not.toHaveProperty('size'); expect(imageBody).not.toHaveProperty('response_format');+ expect((await submit('audio/speech', { model: 'vendor/speech', input: 'hello', voice: 'alloy', response_format: 'wav' })).headers['content-type']).toBe('audio/mpeg');+ expect(JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body)).response_format).toBe('mp3');+ const form = new FormData(); form.set('model', 'vendor/image'); form.set('prompt', 'edit'); form.set('image[]', new Blob(['image'], { type: 'image/png' }), 'image.png');+ const request = new Request('http://localhost', { method: 'POST', body: form });+ const edited = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/images/edits', headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Content-Type': request.headers.get('content-type')!, 'Idempotency-Key': 'edit' }, payload: Buffer.from(await request.arrayBuffer()) });+ expect(edited.statusCode).toBe(200);+ expect(vi.mocked(f.fetcher).mock.lastCall?.[0]).toBe('https://openrouter.ai/api/v1/images');+ expect(JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body))).toMatchObject({ input_references: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,aW1hZ2U=' } }] });+ const transcription = new FormData(); transcription.set('model', 'vendor/transcription'); transcription.set('file', new Blob(['audio'], { type: 'audio/wav' }), 'audio.wav');+ const audioRequest = new Request('http://localhost', { method: 'POST', body: transcription });+ expect((await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/audio/transcriptions', headers: { Authorization: `Bearer ${config.llm.apiKey}`, 'Content-Type': audioRequest.headers.get('content-type')!, 'Idempotency-Key': 'asr' }, payload: Buffer.from(await audioRequest.arrayBuffer()) })).json()).toEqual({ text: 'recognized' });+ const count = vi.mocked(f.fetcher).mock.calls.length;+ await submit('images/generations', { model: 'vendor/image', prompt: 'image', n: 1, size: '1536x1024', response_format: 'b64_json' });+ expect(vi.mocked(f.fetcher).mock.calls).toHaveLength(count);+ expect(vi.mocked(f.fetcher).mock.calls.every(([url, options]) => String(url).startsWith('https://openrouter.ai/api/v1/') && new Headers(options?.headers).get('Authorization') === 'Bearer private-user-key')).toBe(true);+ expect((await submit('images/generations', { model: 'unauthorized', prompt: 'image' }, 'bad-model')).statusCode).toBe(400);+});+it('retains an async video receipt and downloads content locally without exposing upstream URLs', async () => {+ const f = await fixture(); const origin = await f.server.listen({ host: '127.0.0.1', port: 0 });+ const service = createVideoGenerationService({ dataDir: f.root, configStore: f.source.store, gatewaySource: { async binding() { const binding = await f.source.binding(); return binding ? { ...binding, baseUrl: `${origin}/internal/krillin-llm/gateway/v1` } : undefined; } } });+ const task = await service.create({ provider: 'seedance', prompt: 'video', size: '1280x720', duration: 5 });+ expect(task.status).toBe('in_progress');+ expect(JSON.parse(String(vi.mocked(f.fetcher).mock.calls[0]?.[1]?.body))).toMatchObject({ size: '1280x720' });+ expect((await service.refresh(task.id)).status).toBe('completed');+ expect((await service.read(task.id)).content).toEqual(Buffer.from([1, 2, 3]));+});++it('persists and resumes a video using dynamic official options beyond custom presets', async () => {+ const f = await fixture();+ const model = f.state.models.find(model => model.modality === 'video')!;+ model.sizes = []; model.resolutions = ['1080p']; model.aspectRatios = ['1:1']; model.durations = [12];+ const origin = await f.server.listen({ host: '127.0.0.1', port: 0 });+ const service = createVideoGenerationService({ dataDir: f.root, configStore: f.source.store, gatewaySource: { async binding() { const binding = await f.source.binding(); return binding ? { ...binding, baseUrl: `${origin}/internal/krillin-llm/gateway/v1` } : undefined; } } });+ const task = await service.create({ provider: 'seedance', prompt: 'test', size: '1080p@1:1', duration: 12 });+ expect(await service.get(task.id)).toMatchObject({ videoSize: '1080p@1:1', duration: 12 });+ expect((await service.refresh(task.id)).status).toBe('completed');+ expect((await service.read(task.id)).content).toEqual(Buffer.from([1, 2, 3]));+ await expect(service.create({ provider: 'seedance', prompt: 'test', size: '720p@1:1', duration: 12 })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ f.state.source = 'manual';+ await expect(service.create({ provider: 'seedance', prompt: 'test', size: '1080p@1:1', duration: 12 })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+});+it('uses the selected official speech model voice catalog and rejects incompatible voices', async () => {+ const f = await fixture();+ const synthesize = vi.fn(async () => ({ content: Buffer.from('audio'), format: 'mp3' as const }));+ const service = createKrillinTtsService({ resourceRoot: f.root, workRoot: f.root, configStore: f.source.store, executeSynthesis: synthesize });+ expect(await service.listVoices('openai')).toMatchObject({ model: 'vendor/speech', voices: [{ id: 'tested_voice' }] });+ expect(await service.synthesize({ text: 'Hello' })).toMatchObject({ voiceId: 'tested_voice', model: 'vendor/speech', format: 'mp3' });+ await expect(service.synthesize({ text: 'Hello', voiceId: 'alloy' })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ expect(synthesize).toHaveBeenCalledOnce();+});+it.each(['cancelled', 'expired', 'failed'])('terminates video jobs with upstream status %s', async status => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-video-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async (url: URL | RequestInfo) => Response.json(String(url).endsWith('/videos') ? { id: 'remote-video' } : { status }));+ const transport = createDirectTransport(root, fetcher);+ const input = { account: 'a', key: 'private', resource: 'video/jobs', method: 'POST', body: { model: 'video', prompt: 'test' }, contentType: 'application/json', identity: 'video', fingerprint: 'video', signal: AbortSignal.timeout(3000) };+ const { requestId } = await (await transport.request(input)).json();+ expect(await (await transport.request({ ...input, resource: `requests/${requestId}`, method: 'GET' })).json()).toMatchObject({ state: 'failed' });+ await expect(transport.request({ ...input, resource: `requests/${requestId}/result`, method: 'GET' })).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(fetcher).toHaveBeenCalledTimes(2);+});+it('never resubmits an ambiguous accepted request after transport recreation', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-loss-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async () => { throw new Error('lost after acceptance'); });+ const input = { account: 'a', key: 'private', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'same' }, contentType: 'application/json', identity: 'same', fingerprint: 'same', signal: AbortSignal.timeout(3000) };+ await expect(createDirectTransport(root, fetcher).request(input)).rejects.toThrow();+ await expect(createDirectTransport(root, fetcher).request(input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(fetcher).toHaveBeenCalledOnce();+});++it('uses image model parameters and raster formats, and rejects invalid options before a paid request', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-image-options-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ data: [{ b64_json: 'aW1hZ2U=' }] }));+ const transport = createDirectTransport(root, fetcher);+ const model: GatewayModel = { id: 'image', modality: 'image', capabilities: [], imageOptions: { aspectRatios: ['16:9'], resolutions: ['2K'], qualities: [], outputFormats: ['jpeg'], maxImages: 1, maxReferences: 0 } };+ const input = { account: 'a', key: 'test', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'test', n: 1, size: '1024x1024', aspect_ratio: '16:9', resolution: '2K' }, contentType: 'application/json', identity: 'image', fingerprint: 'image', signal: AbortSignal.timeout(3_000), model };+ await transport.request(input);+ expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'image', prompt: 'test', n: 1, aspect_ratio: '16:9', resolution: '2K', output_format: 'jpeg' });+ await expect(transport.request({ ...input, identity: 'invalid', fingerprint: 'invalid', body: { ...input.body, quality: 'high' } })).rejects.toMatchObject({ code: 'capability_unsupported' });+ expect(fetcher).toHaveBeenCalledOnce();+});++it('passes normalized resolution and ratio when the video catalog has no pixel sizes', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-video-options-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ id: 'remote' }));+ const model: GatewayModel = { id: 'video', modality: 'video', capabilities: [], resolutions: ['1080p'], aspectRatios: ['1:1'], durations: [12] };+ await createDirectTransport(root, fetcher).request({ account: 'a', key: 'test', resource: 'video/jobs', method: 'POST', body: { model: 'video', prompt: 'test', size: '1080p@1:1', duration: 12 }, contentType: 'application/json', identity: 'video', fingerprint: 'video', signal: AbortSignal.timeout(3_000), model });+ expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ model: 'video', prompt: 'test', resolution: '1080p', aspect_ratio: '1:1', duration: 12 });+});++it('omits the voice for official models that supply a default, preserving custom speech behavior', async () => {+ const f = await fixture();+ const speech = f.state.models.find(model => model.modality === 'speech')!;+ speech.capabilities = ['default_voice']; speech.voices = [];+ const service = createKrillinTtsService({ resourceRoot: f.root, workRoot: f.root, configStore: f.source.store, executeSynthesis: vi.fn(async () => ({ content: Buffer.from('audio'), format: 'mp3' as const })) });+ expect(await service.listVoices('openai')).toMatchObject({ voices: [{ id: gatewayDefaultVoiceId }] });+ expect(await service.synthesize({ text: 'hello' })).toMatchObject({ voiceId: gatewayDefaultVoiceId });+ const config = await f.source.store.read();+ const response = await f.server.inject({ method: 'POST', url: '/internal/krillin-llm/gateway/v1/audio/speech', headers: { Authorization: `Bearer ${config.llm.apiKey}` }, payload: { model: 'vendor/speech', input: 'hello', voice: gatewayDefaultVoiceId } });+ expect(response.statusCode).toBe(200);+ expect(JSON.parse(String(vi.mocked(f.fetcher).mock.lastCall?.[1]?.body))).not.toHaveProperty('voice');+});+it('keeps an image request alive after the caller disconnects and replays its durable result', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-image-async-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ let release!: (response: Response) => void;+ const fetcher = vi.fn((_url: URL | RequestInfo, _options?: RequestInit) => new Promise<Response>(resolve => { release = resolve; }));+ const transport = createDirectTransport(root, fetcher); cleanup.push(() => transport.close());+ const caller = new AbortController();+ const input = { account: 'a', key: 'private', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'same' }, contentType: 'application/json', identity: 'same', fingerprint: 'same', signal: caller.signal, asyncImage: true };+ const accepted = await transport.request(input);+ const { requestId } = await accepted.json();+ expect(accepted.status).toBe(202);+ expect(transport.isBusy()).toBe(true);+ caller.abort();+ expect(fetcher.mock.calls[0]![1]?.signal?.aborted).toBe(false);+ expect((await transport.request({ ...input, signal: AbortSignal.timeout(3_000) })).status).toBe(202);+ await expect(transport.request({ ...input, fingerprint: 'different' })).rejects.toMatchObject({ code: 'operation_conflict' });+ release(Response.json({ data: [{ b64_json: 'aW1hZ2U=' }] }));+ const lookup = { ...input, resource: `requests/${requestId}`, method: 'GET', signal: AbortSignal.timeout(3_000) };+ await vi.waitFor(async () => expect(await (await transport.request(lookup)).json()).toMatchObject({ state: 'succeeded' }));+ const restarted = createDirectTransport(root, fetcher);+ expect(await (await restarted.request({ ...lookup, resource: `${lookup.resource}/result` })).json()).toEqual({ data: [{ b64_json: 'aW1hZ2U=' }] });+ expect((await restarted.request({ ...input, signal: AbortSignal.timeout(3_000) })).status).toBe(200);+ expect(fetcher).toHaveBeenCalledOnce();+});+it('saves complete image JSON without waiting for a stuck upstream stream to close', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-image-open-stream-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const cancel = vi.fn();+ const fetcher = vi.fn(async () => new Response(new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(new TextEncoder().encode(JSON.stringify({ data: [{ b64_json: 'aW1hZ2U=' }] }))); }, cancel }), { headers: { 'Content-Type': 'application/json' } }));+ const transport = createDirectTransport(root, fetcher);+ const result = await transport.request({ account: 'a', key: 'private', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'same' }, contentType: 'application/json', identity: 'same', fingerprint: 'same', signal: AbortSignal.timeout(1_000) });+ expect(await result.json()).toMatchObject({ data: [{ b64_json: 'aW1hZ2U=' }] });+ expect(cancel).toHaveBeenCalledOnce();+});+it('finishes image worker shutdown even when the upstream ignores abort and never returns headers', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-image-abort-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(() => new Promise<Response>(() => {}));+ const transport = createDirectTransport(root, fetcher);+ const input = { account: 'a', key: 'private', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'same' }, contentType: 'application/json', identity: 'same', fingerprint: 'same', signal: AbortSignal.timeout(1_000), asyncImage: true };+ const { requestId } = await (await transport.request(input)).json();+ await transport.close();+ expect(await (await transport.request({ ...input, resource: `requests/${requestId}`, method: 'GET' })).json()).toMatchObject({ state: 'outcome_unknown' });+ await expect(createDirectTransport(root, fetcher).request(input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(fetcher).toHaveBeenCalledOnce();+});+it('polls an official image receipt and downloads a cached image without making another paid request', async () => {+ const f = await fixture();+ const origin = await f.server.listen({ host: '127.0.0.1', port: 0 });+ const image = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aC1sAAAAASUVORK5CYII=', 'base64');+ vi.mocked(f.fetcher).mockImplementation(async () => Response.json({ data: [{ b64_json: image.toString('base64') }] }));+ const config = await f.source.store.read(); config.image.openai.baseUrl = `${origin}/internal/krillin-llm/gateway/v1`;+ const onGatewayRequest = vi.fn();+ const result = await generateImageContents({ provider: 'openai', prompt: 'test', size: '1024x1024', quality: 'medium', count: 1 }, config, { logicalId: 'paid-once', onGatewayRequest });+ expect(result.contents[0]?.content).toEqual(image);+ expect(onGatewayRequest).toHaveBeenCalledWith(expect.stringMatching(/^ocdir_/));+ expect(await readPrivateJsonFile(join(f.root, 'receipts', `${onGatewayRequest.mock.calls[0]![0]}.json`))).toMatchObject({ state: 'succeeded' });+ await generateImageContents({ provider: 'openai', prompt: 'test', size: '1024x1024', quality: 'medium', count: 1 }, config, { logicalId: 'paid-once' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});+it('recognizes a zero-limit 403 as insufficient credits without exposing upstream details', async () => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-image-quota-')); cleanup.push(() => rm(root, { recursive: true, force: true }));+ const fetcher = vi.fn(async () => Response.json({ error: { message: 'Key limit exceeded (total limit). Manage it using https://openrouter.ai/private' } }, { status: 403 }));+ const transport = createDirectTransport(root, fetcher);+ const input = { account: 'a', key: 'private', resource: 'images/generations', method: 'POST', body: { model: 'image', prompt: 'same' }, contentType: 'application/json', identity: 'same', fingerprint: 'same', signal: AbortSignal.timeout(3_000), asyncImage: true };+ const { requestId } = await (await transport.request(input)).json();+ await vi.waitFor(async () => {+ const result = await (await transport.request({ ...input, resource: `requests/${requestId}`, method: 'GET' })).json();+ expect(result).toMatchObject({ state: 'failed', error: { code: 'credits_insufficient', status: 403 } });+ expect(JSON.stringify(result)).not.toContain('openrouter');+ });+});+it.each([true, false])('reconciles both image ledgers and records usable progress (success=%s)', async success => {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-image-ledger-'));+ const db = openRuntimeDatabase(join(root, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const ledger = new CreatorProviderRequestLedger(repository);+ const f = await fixture(ledger);+ const origin = await f.server.listen({ host: '127.0.0.1', port: 0 });+ const image = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aC1sAAAAASUVORK5CYII=', 'base64');+ vi.mocked(f.fetcher).mockImplementation(async () => success ? Response.json({ data: [{ b64_json: image.toString('base64') }] }) : Response.json({ error: { message: 'Key limit exceeded (total limit)' } }, { status: 403 }));+ const job = repository.createJob({ projectId: 'project', templateId: 'image-generation', templateVersion: 2, status: 'running', state: { prompt: 'test', provider: 'openai', candidateCount: 1, size: '1024x1024', quality: 'medium' } });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'running' });+ const executor = createImageExecutor({ ledger, configStore: { async read() { const config = await f.source.store.read(); config.image.openai.baseUrl = `${origin}/internal/krillin-llm/gateway/v1`; return config; } } });+ const reportProgress = vi.fn();+ try {+ const run = f.source.runForJob(job.id, stage.id, () => executor.run({ job, stageRun: stage, workdir: root, inputArtifacts: [], signal: AbortSignal.timeout(3_000), reportProgress }));+ if (success) expect((await run).outputs).toHaveLength(1);+ else {+ await expect(run).rejects.toMatchObject({ code: 'image_generation_failed' });+ expect(reportProgress.mock.lastCall?.[0]).toMatchObject({ status: 'failed', completed: 0, failed: 1, percent: 10 });+ }+ const receipts = repository.getJob(job.id)!.providerRequests;+ expect(receipts).toHaveLength(2);+ expect(receipts.every(receipt => receipt.status === (success ? 'succeeded' : 'failed'))).toBe(true);+ expect(f.source.isBusy()).toBe(false);+ } finally { await f.source.revoke(); db.close(); await rm(root, { recursive: true, force: true }); }+});+it('uses a local Runtime capability and stateless Responses with safe upstream errors', async () => {+ const fetcher = vi.fn(async (_url: URL | RequestInfo, _options?: RequestInit) => Response.json({ error: { message: 'OpenRouter private error' } }, { status: 402 }));+ const runtime = await createDirectRuntime('private-user-key', fetcher); cleanup.push(() => runtime.close());+ const result = await fetch(`${runtime.baseUrl}/responses`, { method: 'POST', headers: { Authorization: `Bearer ${runtime.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'vendor/text', input: [], store: true }) });+ expect(result.status).toBe(402); expect(await result.text()).not.toContain('OpenRouter');+ expect(JSON.parse(String(fetcher.mock.lastCall?.[1]?.body))).toMatchObject({ store: false });+ expect((await fetch(`${runtime.baseUrl}/responses`, { method: 'POST', body: '{}' })).status).toBe(401);+});diff --git a/apps/daemon/test/integration/direct-stream-receipts.test.ts b/apps/daemon/test/integration/direct-stream-receipts.test.tsnew file mode 100644index 00000000..b44aca3b--- /dev/null+++ b/apps/daemon/test/integration/direct-stream-receipts.test.ts@@ -0,0 +1,80 @@+import { createHash } from 'node:crypto';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it, vi } from 'vitest';+import { createDirectTransport } from '../../src/gateway/direct-transport.js';+import { readPrivateJsonFile, writePrivateJsonFile } from '../../src/config/private-json-file.js';++const cleanup: Array<() => Promise<void>> = [];+afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); });+const encoder = new TextEncoder();+const delta = 'data: {"choices":[{"delta":{"content":"hello"}}]}\n\n';+const done = 'data: [DONE]\n\n';++async function fixture(content: string) {+ const root = await mkdtemp(join(tmpdir(), 'oc-direct-stream-'));+ cleanup.push(() => rm(root, { recursive: true, force: true }));+ const cancel = vi.fn();+ const fetcher = vi.fn<typeof fetch>(async () => new Response(new ReadableStream<Uint8Array>({+ start(controller) { controller.enqueue(encoder.encode(content)); }, cancel+ }), { headers: { 'Content-Type': 'text/event-stream' } }));+ const transport = createDirectTransport(root, fetcher);+ cleanup.push(() => transport.close());+ const input = { account: 'account', key: 'test-key', resource: 'chat/completions', method: 'POST',+ body: { model: 'text', messages: [], stream: true }, contentType: 'application/json',+ identity: 'same-request', fingerprint: 'same-payload', signal: AbortSignal.timeout(3000) };+ const id = 'ocdir_' + createHash('sha256').update(JSON.stringify([input.account, input.identity])).digest('hex').slice(0, 48);+ return { root, input, id, transport, fetcher, cancel };+}++it('persists completion before forwarding DONE and survives immediate caller cancellation', async () => {+ const f = await fixture(delta + done);+ const response = await f.transport.request(f.input);+ const reader = response.body!.getReader();+ for (;;) {+ const chunk = await reader.read();+ if (chunk.done || new TextDecoder().decode(chunk.value).includes('[DONE]')) break;+ }+ await reader.cancel();+ await vi.waitFor(async () => expect(await readPrivateJsonFile(join(f.root, f.id + '.json'))).toMatchObject({ state: 'succeeded' }));+ const restarted = createDirectTransport(f.root, f.fetcher);+ expect(await (await restarted.request(f.input)).text()).toBe(delta + done);+ expect(f.fetcher).toHaveBeenCalledOnce();+ expect(f.cancel).toHaveBeenCalledOnce();+});++it('completes Responses at its terminal event even while upstream HTTP remains open', async () => {+ const completed = 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n';+ const f = await fixture(completed);+ const response = await f.transport.request({ ...f.input, resource: 'responses' });+ expect(await response.text()).toBe(completed);+ expect(await readPrivateJsonFile(join(f.root, f.id + '.json'))).toMatchObject({ state: 'succeeded' });+ expect(f.cancel).toHaveBeenCalledOnce();+});++it.each([+ delta,+ 'data: {"choices":[{"delta":{"content":"the literal [DONE] is model text"}}]}\n\n',+ 'data: {"type":"error","error":{"message":"failed"}}\n\n' + done,+ 'data: {"type":"response.completed","response":{"status":"failed"}}\n\n' + done+])('preserves unknown acceptance when the caller cancels an incomplete or failed stream (%s)', async content => {+ const f = await fixture(content);+ const reader = (await f.transport.request(f.input)).body!.getReader();+ await reader.read();+ await reader.cancel();+ expect(await readPrivateJsonFile(join(f.root, f.id + '.json'))).toMatchObject({ state: 'outcome_unknown' });+ await expect(createDirectTransport(f.root, f.fetcher).request(f.input)).rejects.toMatchObject({ code: 'request_outcome_unknown' });+ expect(f.fetcher).toHaveBeenCalledOnce();+});++it.each([true, false])('recovers only a cached stream with verified completion (complete=%s)', async complete => {+ const f = await fixture('');+ await writePrivateJsonFile(join(f.root, f.id + '.json'), {+ account: f.input.account, fingerprint: f.input.fingerprint, state: 'outcome_unknown', status: 200,+ mime: 'text/event-stream', content: Buffer.from(delta + (complete ? done : '')).toString('base64')+ });+ const result = await f.transport.request({ ...f.input, resource: 'requests/' + f.id, method: 'GET' });+ expect(await result.json()).toMatchObject({ state: complete ? 'succeeded' : 'outcome_unknown' });+ expect(f.fetcher).not.toHaveBeenCalled();+});diff --git a/apps/daemon/test/integration/gateway-account-api.test.ts b/apps/daemon/test/integration/gateway-account-api.test.tsnew file mode 100644index 00000000..3732ba50--- /dev/null+++ b/apps/daemon/test/integration/gateway-account-api.test.ts@@ -0,0 +1,45 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { expect, it } 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';++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!;+ const root = await mkdtemp(join(tmpdir(),'oc-gateway-api-'));+ const service = createGatewayAccountService({ dataDir:root, client:createGatewayClient(origin), activateRuntime:async()=>{ throw new Error('no test model'); }, closeRuntime:async()=>undefined, hasActiveTasks:()=>false, automaticPolling:false });+ try {+ const csrfResponse = await fetch(`${origin}/api/v1/auth/csrf`);+ const csrf = await csrfResponse.json() as {csrfToken:string};+ let cookies = csrfResponse.headers.getSetCookie().map(value=>value.split(';')[0]).join('; ');+ const login = await fetch(`${origin}/api/v1/auth/login`,{method:'POST',headers:{Origin:origin,Cookie:cookies,'Content-Type':'application/json','X-CSRF-Token':csrf.csrfToken},body:JSON.stringify({email:'[email protected]',password:process.env.GATEWAY_DEMO_PASSWORD})});+ expect(login.status).toBe(200);+ cookies += '; '+login.headers.getSetCookie().map(value=>value.split(';')[0]).join('; ');+ const grant=await service.startAuthorization();+ const approve=await fetch(`${origin}/api/v1/auth/device/approve`,{method:'POST',headers:{Origin:origin,Cookie:cookies,'Content-Type':'application/json','X-CSRF-Token':csrf.csrfToken},body:JSON.stringify({attemptId:grant.attemptId,decision:'approve'})});+ expect(approve.status).toBe(200);+ await service.pollAuthorization(grant.attemptId);+ expect(await service.readState()).toMatchObject({authState:'signed_in',activationState:'blocked',account:{email:'[email protected]'}});+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, service);+ const response = await server.inject({ method: 'GET', url: '/gateway/billing/summary' });+ expect(response.statusCode).toBe(200);+ expect(response.headers['cache-control']).toBe('no-store');+ expect(response.json()).toMatchObject({ balance: { availableUnits: '0', reservedUnits: '0' }, subscription: null, billingAvailable: false });+ } finally { await server.close(); }+ await service.logout();+ const guestServer = Fastify();+ try {+ await registerGatewayAccountRoutes(guestServer, service);+ const plans = await guestServer.inject({ method: 'GET', url: '/gateway/plans' });+ expect(plans.statusCode).toBe(200);+ expect(plans.json()).toMatchObject({ plans: [], billingAvailable: false });+ const privateSummary = await guestServer.inject({ method: 'GET', url: '/gateway/billing/summary' });+ expect(privateSummary.statusCode).toBe(401);+ } finally { await guestServer.close(); }+ } finally { await service.close();await rm(root,{recursive:true,force:true}); }+});diff --git a/apps/daemon/test/integration/gateway-runtime-protocol.test.ts b/apps/daemon/test/integration/gateway-runtime-protocol.test.tsnew file mode 100644index 00000000..c324be92--- /dev/null+++ b/apps/daemon/test/integration/gateway-runtime-protocol.test.ts@@ -0,0 +1,172 @@+import { createHash } from 'node:crypto';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { createServer, type ServerResponse } from 'node:http';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createCodexAppServerHost, type CodexAppServerHost } from '../../src/codex/app-server-host-2026-07-28.js';+import { createGatewayRuntimeBindings } from '../../src/gateway/runtime-bindings.js';+import { createDirectRuntime } from '../../src/gateway/direct-runtime.js';++const codexBin = resolve('../../apps/desktop/.pack/codex-runtime/bin/codex');+const manifest = JSON.parse(readFileSync(resolve('../../resources/codex-runtime/darwin-arm64/manifest.json'), 'utf8'));+const cleanup: Array<() => Promise<void> | void> = [];+afterEach(async () => {+ for (const close of cleanup.splice(0).reverse()) await close();+ vi.unstubAllEnvs();+});++type ModelRequest = { headers: Record<string, string | string[] | undefined>; body: Record<string, unknown> };++async function fixture(reply: (res: ServerResponse, requests: ModelRequest[]) => void, directMode = false) {+ expect(existsSync(codexBin), 'bundled Runtime is required for this integration gate').toBe(true);+ expect(createHash('sha256').update(readFileSync(codexBin)).digest('hex')).toBe(manifest.binary.sha256);+ const root = mkdtempSync(join(tmpdir(), 'oc-real-gateway-'));+ cleanup.push(() => rmSync(root, { recursive: true, force: true }));+ const requests: ModelRequest[] = [];+ const server = createServer(async (req, res) => {+ if (req.url !== '/v1/responses') {+ res.writeHead(404).end();+ return;+ }+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ requests.push({ headers: req.headers, body: JSON.parse(Buffer.concat(chunks).toString()) });+ reply(res, requests);+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ cleanup.push(() => new Promise<void>((resolve, reject) => {+ server.closeAllConnections();+ server.close(error => error ? reject(error) : resolve());+ }));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Missing fixture address');+ const bridge = directMode ? await createDirectRuntime('test-official-key-a', async (_url, options) => fetch(`http://127.0.0.1:${address.port}/v1/responses`, options)) : undefined;+ if (bridge) cleanup.push(() => bridge.close());+ let host: CodexAppServerHost | undefined;+ const binding = createGatewayRuntimeBindings({+ codexHome: join(root, 'official'),+ baseUrl: bridge?.baseUrl ?? `http://127.0.0.1:${address.port}/v1`, model: 'gpt-5.2',+ readCredentials: async () => ({ accountId: 'a', modelKey: bridge?.token ?? 'test-official-key-a', keyVersion: '1' }),+ closeRuntime: async () => { await host?.close('device_logout', 100); }+ });+ cleanup.push(() => binding.close());+ vi.stubEnv('OPENAI_API_KEY', 'test-personal-key-must-not-be-used');+ const prepared = await binding.prepare();+ host = createCodexAppServerHost({+ codexBin, codexHome: prepared.codexHome, cwd: root, profile: 'default',+ baseEnvironment: prepared.env, spawnTimeoutMs: 10_000, forceKillGraceMs: 100+ });+ const run = () => host!.run({+ cwd: root, sandbox: 'danger-full-access', model: 'gpt-5.2',+ prompt: 'Report the current directory and then say gateway ready.', timeoutMs: 15_000+ });+ return { binding, prepared, host, requests, run };+}++function event(res: ServerResponse, type: string, value: Record<string, unknown>) {+ res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...value })}\n\n`);+}++function complete(res: ServerResponse, output: Record<string, unknown>[]) {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ const response = {+ id: 'resp_test', object: 'response', created_at: 1, model: 'gpt-5.2',+ status: 'in_progress', output: [],+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 }+ };+ event(res, 'response.created', { response });+ output.forEach((item, output_index) => {+ event(res, 'response.output_item.added', { output_index, item });+ if (item.type === 'message') {+ event(res, 'response.output_text.delta', {+ output_index, item_id: item.id, content_index: 0, delta: 'gateway ready'+ });+ }+ event(res, 'response.output_item.done', { output_index, item });+ });+ event(res, 'response.completed', { response: { ...response, status: 'completed', output } });+ res.end();+}++const message = {+ id: 'msg_test', type: 'message', role: 'assistant', status: 'completed',+ content: [{ type: 'output_text', text: 'gateway ready', annotations: [] }]+};++describe('bundled Runtime official gateway boundary', () => {+ it('preserves complete tool history through the direct stateless connection', async () => {+ const f = await fixture((res, requests) => {+ if (requests.length === 1) complete(res, [{ id: 'fc_direct', type: 'function_call', call_id: 'call_direct', name: 'exec_command', arguments: JSON.stringify({ cmd: 'pwd', max_output_tokens: 100 }), status: 'completed' }]);+ else complete(res, [message]);+ }, true);+ expect((await f.run().result).turnStatus).toBe('completed');+ expect(f.requests).toHaveLength(2);+ expect(f.requests.every(request => request.body.store === false && !request.body.previous_response_id && request.headers.authorization === 'Bearer test-official-key-a')).toBe(true);+ expect(JSON.stringify(f.requests[1]!.body.input)).toContain('function_call_output');+ expect(JSON.stringify(f.requests[1]!.body.input)).toContain('call_direct');+ }, 30_000);+ it('uses only the official key for Responses streaming and leaves no auth.json', async () => {+ const f = await fixture(res => complete(res, [message]));+ const result = await f.run().result;+ expect(result.turnStatus).toBe('completed');+ expect(f.requests).toHaveLength(1);+ expect(f.requests[0]!.headers.authorization).toBe('Bearer test-official-key-a');+ expect(f.requests[0]!.body.stream).toBe(true);+ expect(existsSync(join(f.prepared.codexHome, 'auth.json'))).toBe(false);+ await f.binding.close();+ expect(() => process.kill(f.host.pid!, 0)).toThrow();+ await expect(f.binding.prepare()).rejects.toThrow('signed out');+ expect(() => f.run()).toThrow();+ expect(f.requests).toHaveLength(1);+ }, 30_000);++ it('keeps the native tool call and submits its result as a second model operation', async () => {+ const f = await fixture((res, requests) => {+ if (requests.length === 1) {+ const tools = requests[0]!.body.tools as Array<{ name?: string }>;+ expect(tools.some(tool => tool.name === 'exec_command')).toBe(true);+ complete(res, [{+ id: 'fc_test', type: 'function_call', call_id: 'call_test', name: 'exec_command',+ arguments: JSON.stringify({ cmd: 'if test -n "$OC_GATEWAY_MODEL_KEY"; then echo CLOUD_KEY_PRESENT; else echo CLOUD_KEY_ABSENT; fi', max_output_tokens: 100 }), status: 'completed'+ }]);+ } else complete(res, [message]);+ });+ expect((await f.run().result).turnStatus).toBe('completed');+ expect(f.requests).toHaveLength(2);+ expect(JSON.stringify(f.requests[1]!.body.input)).toContain('function_call_output');+ const output = (f.requests[1]!.body.input as Array<{ type: string; output?: string }>).find(item => item.type === 'function_call_output')?.output;+ expect(output).toContain('CLOUD_KEY_ABSENT');+ expect(output).not.toContain('CLOUD_KEY_PRESENT');+ expect(f.requests.every(request => request.headers.authorization === 'Bearer test-official-key-a')).toBe(true);+ }, 30_000);++ it.each(['rejected', 'stream_lost'] as const)('does not blindly resubmit after %s', async mode => {+ const f = await fixture(res => {+ if (mode === 'rejected') {+ res.writeHead(503, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: { message: 'test unavailable' } }));+ } else {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ event(res, 'response.created', { response: { id: 'resp_accepted', status: 'in_progress', output: [] } });+ res.end();+ }+ });+ expect((await f.run().result).turnStatus).toBe('failed');+ expect(f.requests).toHaveLength(1);+ }, 30_000);++ it('kills a live credential-holding process before logout succeeds', async () => {+ const f = await fixture(res => {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ event(res, 'response.created', { response: { id: 'resp_still_running', status: 'in_progress', output: [] } });+ });+ const running = f.run();+ const result = running.result.catch(error => error);+ await expect.poll(() => f.requests.length, { timeout: 10_000 }).toBe(1);+ await f.binding.close();+ await result;+ expect(() => process.kill(f.host.pid!, 0)).toThrow();+ await expect(f.binding.prepare()).rejects.toThrow('signed out');+ expect(f.requests).toHaveLength(1);+ }, 30_000);+});diff --git a/apps/daemon/test/unit/creator-command-dispatcher.test.ts b/apps/daemon/test/unit/creator-command-dispatcher.test.tsindex 9739afb0..8570bd5d 100644--- a/apps/daemon/test/unit/creator-command-dispatcher.test.ts+++ b/apps/daemon/test/unit/creator-command-dispatcher.test.ts@@ -116,6 +116,61 @@ describe('creator command dispatcher', () => {fixture.db.close();});+ it('queues an image retry once and preserves the failed attempt', () => {+ const fixture = setup();+ try {+ const job = fixture.service.createJob({+ projectId: 'project-1',+ templateId: 'image-generation',+ state: { prompt: 'test' }+ });+ const failed = fixture.repository.createStageRun({+ jobId: job.id,+ stageId: 'generate',+ executor: 'image',+ status: 'failed'+ });+ const wake = vi.fn();+ const dispatcher = createCreatorCommandDispatcher({+ service: fixture.service,+ repository: fixture.repository,+ receipts: fixture.receipts,+ onQueuedStage: wake+ });+ const request = {+ action: 'retry-stage',+ expectedRevision: job.revision,+ idempotencyKey: 'retry-image-1',+ input: { stageId: 'generate' }+ };++ const first = dispatcher.dispatch(job.id, request, 'user');+ const replay = dispatcher.dispatch(job.id, request, 'user');+ const restored = fixture.service.getJob(job.id)!;++ expect(first.commandReceipt).toMatchObject({+ status: 'committed',+ stageRunId: expect.any(String)+ });+ expect(replay.commandReceipt).toMatchObject({+ id: first.commandReceipt.id,+ status: 'replayed',+ stageRunId: first.commandReceipt.stageRunId+ });+ expect(restored.status).toBe('running');+ expect(restored.revision).toBe(job.revision + 1);+ expect(restored.stages).toHaveLength(2);+ expect(restored.stages.find(stage => stage.id === failed.id)?.status).toBe('failed');+ expect(restored.stages.find(stage => stage.id === first.commandReceipt.stageRunId)).toMatchObject({+ stageId: 'generate',+ status: 'queued',+ dispatchStatus: 'queued',+ idempotencyKey: 'retry-image-1:stage'+ });+ expect(wake).toHaveBeenCalledTimes(1);+ } finally { fixture.db.close(); }+ });+it('rejects reuse of an idempotency key with a different payload', () => {const fixture = setup();const dispatcher = createCreatorCommandDispatcher({diff --git a/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts b/apps/daemon/test/unit/creator-krillin-cli-protocol.test.tsindex 1900dc63..c0a2ff10 100644--- a/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts+++ b/apps/daemon/test/unit/creator-krillin-cli-protocol.test.ts@@ -10,9 +10,13 @@ import {resolveKrillinCliSource} from '../../src/creator/krillin/cli-runner.js';import { createKrillinConfigToml } from '../../src/creator/krillin/config-bridge.js';-import { buildKrillinStageOptions } from '../../src/creator/krillin/adapter.js';+import { buildKrillinStageOptions, normalizeKrillinFailure } from '../../src/creator/krillin/adapter.js';describe('KrillinAI CLI protocol', () => {+ it.each(['audio_no_speech', 'audio_transcription_empty', 'audio_transcription_invalid_response', 'audio_transcription_timestamps_missing', 'audio_transcription_api_failed'])('preserves %s through usage-error normalization', code => {+ const message = 'OpenAI transcription response was classified by the runtime';+ expect(normalizeKrillinFailure({ code, kind: 'usage', message })).toEqual({ code, message });+ });it.each([true, false])('never prepares video in the translation subtitle stage, even when composeVideo=%s', composeVideo => {const stage = { job: { templateId: 'video-translation', state: { sourceUrl: 'https://youtu.be/demo', sourceLanguage: 'en', targetLanguage: 'zh_cn', composeVideo } }, stageRun: { stageId: 'subtitle', id: 'stage' }, workdir: '/job/stage' };const options = buildKrillinStageOptions(stage as never);diff --git a/apps/daemon/test/unit/creator-preflight.test.ts b/apps/daemon/test/unit/creator-preflight.test.tsindex c3e6de70..64d09edd 100644--- a/apps/daemon/test/unit/creator-preflight.test.ts+++ b/apps/daemon/test/unit/creator-preflight.test.ts@@ -11,6 +11,7 @@ import { createCoverTemplate } from '../../src/creator/templates/cover.js';import { createSmartDubbingTemplate } from '../../src/creator/templates/smart-dubbing.js';import { createVideoTranslationTemplate } from '../../src/creator/templates/video-translation.js';import { createKrillinCreatorServicesCapabilities } from '../../src/creator/krillin/capabilities.js';+import { createGatewayCreatorSource } from '../../src/gateway/creator-service-source.js';let root = '';@@ -20,6 +21,32 @@ afterEach(async () => {});describe('creator preflight', () => {+ it('blocks multiple official Stickman references before submitting any generation', async () => {+ root = await mkdtemp(join(tmpdir(), 'creator-official-references-'));+ const config = createDefaultCreatorServicesConfig();+ const source = createGatewayCreatorSource({+ account: { peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null }), modelCredentials: async () => ({ accountId: 'a', modelKey: 'secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { image: 'image' }, models: [{ id: 'image', modality: 'image', capabilities: ['edit'] }] }) },+ manual: { read: async () => config, write: async c => c, reset: async () => config }, getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ const job = fakeJob('stickman-video', { provider: 'gemini' });+ job.artifacts = ['character_reference', 'style_reference'].map((kind, i) => ({ id: `ref-${i}`, jobId: job.id, kind, version: 1, scopeKey: null, inputFingerprint: null, sourceArtifactIds: [], path: join(root, `${i}.png`), status: 'completed', metadata: {}, sha256: 'hash', producerStageRunId: null, createdAt: job.createdAt, updatedAt: job.updatedAt }));+ const result = await createCreatorPreflight({ configStore: source.store, readCapabilities: () => createKrillinCreatorServicesCapabilities('darwin', 'arm64'), resourceRoot: root, jobsRoot: join(root, 'jobs'), validateRuntimeAssets: false }).check(job, createStickmanVideoTemplate().stages.find(stage => stage.executor === 'stickman-image')!);+ expect(result.blocked).toContainEqual(expect.objectContaining({ id: 'reference-image-count', message: expect.stringContaining('1 张') }));+ });+ it.each(['reference', 'speech-style'])('blocks unverified official %s before executing', async feature => {+ root = await mkdtemp(join(tmpdir(), 'creator-official-capability-'));+ const config = createDefaultCreatorServicesConfig();+ const source = createGatewayCreatorSource({+ account: { peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null }), modelCredentials: async () => ({ accountId: 'a', modelKey: 'secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { image: 'image', speech: 'speech' }, models: [] }) },+ manual: { read: async () => config, write: async c => c, reset: async () => config }, getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ const job = feature === 'reference'+ ? fakeJob('image-generation', { provider: 'openai', prompt: 'draw', referenceImageArtifactId: 'reference' })+ : fakeJob('smart-dubbing', { text: 'hello', speed: 1 });+ const template = feature === 'reference' ? createImageGenerationTemplate() : createSmartDubbingTemplate();+ const result = await createCreatorPreflight({ configStore: source.store, readCapabilities: () => createKrillinCreatorServicesCapabilities('darwin', 'arm64'), resourceRoot: root, jobsRoot: join(root, 'jobs'), validateRuntimeAssets: false }).check(job, template.stages[0]!);+ expect(result.blocked.map(item => item.id)).toContain(feature === 'reference' ? 'reference-image-capability' : 'tts-style-capability');+ });it.each(['openai', 'codex-native'])('blocks missing reference input for %s before starting a task', async provider => {root = await mkdtemp(join(tmpdir(), 'creator-preflight-reference-'));const check = createCreatorPreflight({diff --git a/apps/daemon/test/unit/creator-provider-requests.test.ts b/apps/daemon/test/unit/creator-provider-requests.test.tsindex 13f45251..a06743c1 100644--- a/apps/daemon/test/unit/creator-provider-requests.test.ts+++ b/apps/daemon/test/unit/creator-provider-requests.test.ts@@ -13,6 +13,7 @@ import { createCreatorRepository } from '../../src/creator/repository.js';import { CreatorServiceError, createCreatorService } from '../../src/creator/service.js';import {createCreatorTemplateRegistry,+ createDefaultCreatorTemplateRegistry,createStickmanVideoTemplate} from '../../src/creator/templates/registry.js';import { openRuntimeDatabase } from '../../src/storage/database.js';@@ -46,6 +47,74 @@ function setup(path = join(tempDir, 'runtime.sqlite')) {}describe('creator provider request ledger', () => {+ it('closes the matching unknown-receipt issue only after all requests in its scope are recovered', async () => {+ tempDir = mkdtempSync(join(tmpdir(), 'creator-provider-stream-recovery-'));+ const { db, repository, job, stage } = setup();+ const issues = createCreatorIssueService(repository);+ const ledger = new CreatorProviderRequestLedger(repository, issues);+ try {+ const requests = ['first', 'second'].map(requestKey => {+ const request = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, scopeKey: stage.scopeKey,+ provider: 'opencreator-gateway-chat/completions', requestKey, request: { prompt: requestKey } });+ ledger.markSubmitting(request.id); ledger.markWaitingRemote(request.id, 'remote-' + requestKey);+ return ledger.markUnknownRemoteAcceptance(request.id);+ });+ const failedIssue = issues.capture({ jobId: job.id, stageRunId: stage.id, stageId: stage.stageId,+ scopeKey: stage.scopeKey ?? undefined, source: 'provider', code: 'creator_provider_request_failed',+ publicFacts: { kind: 'unknown', provider: requests[0]!.provider } });+ const lookup = { lookupByRequestKey: false, lookup: async () => ({ status: 'succeeded' as const }) };+ await ledger.recover(requests[0]!.id, lookup);+ expect(issues.list(job.id)).toHaveLength(2);+ expect(issues.list(job.id).every(issue => issue.status === 'open')).toBe(true);+ await ledger.recover(requests[1]!.id, lookup);+ expect(issues.list(job.id).find(issue => issue.code === 'creator_provider_resolution_required')!.status).toBe('resolved');+ expect(issues.get(job.id, failedIssue.id)!.status).toBe('open');+ expect(repository.listProviderRequests(job.id).every(request => request.status === 'succeeded')).toBe(true);+ } finally { db.close(); }+ });+ it('blocks fresh image runs and retries until a previous paid request is explicitly resolved', () => {+ tempDir = mkdtempSync(join(tmpdir(), 'creator-image-recovery-'));+ const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));+ const repository = createCreatorRepository(db);+ const service = createCreatorService({ repository, templates: createDefaultCreatorTemplateRegistry() });+ const job = service.createJob({ projectId: 'project', templateId: 'image-generation', state: { prompt: 'test' } });+ const stage = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'image', status: 'failed' });+ const ledger = new CreatorProviderRequestLedger(repository);+ const request = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: stage.id, provider: 'opencreator-gateway-image', requestKey: 'paid-image', request: { prompt: 'test' } });+ ledger.markSubmitting(request.id); ledger.markUnknownRemoteAcceptance(request.id);+ try {+ for (const action of ['run-stage', 'retry-stage']) {+ expect(() => service.applyAction(job.id, { actor: 'user', action, expectedRevision: job.revision, input: { stageId: 'generate' } })).toThrowError(expect.objectContaining({ code: 'creator_provider_resolution_required' }));+ }+ const resolved = service.applyAction(job.id, { actor: 'user', action: 'resolve-provider-request', expectedRevision: job.revision, input: { ledgerId: request.id, decision: 'cancel-scope' } });+ expect(repository.getProviderRequest(request.id)?.status).toBe('canceled');+ expect(() => service.applyAction(job.id, { actor: 'user', action: 'retry-stage', expectedRevision: resolved.job.revision, input: { stageId: 'generate' } })).not.toThrow();+ } finally { db.close(); }+ });+ it('preserves the service source of an existing job after an account switch and database reopen', () => {+ tempDir = mkdtempSync(join(tmpdir(), 'creator-service-binding-'));+ const path = join(tempDir, 'runtime.sqlite');+ let current = { source: 'gateway' as const, accountId: 'a', bindingVersion: 'a:1', models: { image: 'original-image' }, capabilities: { image: ['image_count'] } };+ const db = openRuntimeDatabase(path);+ const repository = createCreatorRepository(db, { serviceBinding: () => current });+ const job = repository.createJob({ projectId: 'project', templateId: 'image-generation', templateVersion: 1, status: 'draft', state: {} });+ current = { ...current, accountId: 'b', bindingVersion: 'b:1' };+ expect(repository.getServiceBinding(job.id)).toMatchObject({ accountId: 'a', bindingVersion: 'a:1' });+ db.close();+ const reopened = openRuntimeDatabase(path);+ expect(createCreatorRepository(reopened).getServiceBinding(job.id)).toMatchObject({ accountId: 'a', models: { image: 'original-image' } });+ reopened.close();+ });+ it('persists the original gateway account and logical identity for recovery', () => {+ tempDir = mkdtempSync(join(tmpdir(), 'creator-gateway-ledger-'));+ const { db, job, stage, repository, ledger } = setup();+ const gateway = { accountId:'account-a', bindingVersion:'account-a:1', logicalId:'stable-stage-image' };+ const original = ledger.registerBeforeSubmit({jobId:job.id,provider:'opencreator-gateway',stageRunId:stage.id,requestKey:gateway.logicalId,request:{prompt:'draw'},gateway});+ ledger.markSubmitting(original.id); ledger.markWaitingRemote(original.id,'gateway-original-request');+ expect(repository.getProviderRequest(original.id)).toMatchObject({gateway,remoteTaskId:'gateway-original-request'});+ expect(JSON.stringify(repository.getProviderRequest(original.id))).not.toMatch(/modelKey|apiKey|accessToken/);+ db.close();+ });it('keeps unknown paid acceptance non-retryable and resolves the same issue after explicit resubmit', () => {tempDir = mkdtempSync(join(tmpdir(), 'creator-provider-ledger-'));const { db, job, stage, repository } = setup();diff --git a/apps/daemon/test/unit/creator-video-executor.test.ts b/apps/daemon/test/unit/creator-video-executor.test.tsindex 6fb497bc..9f368e9e 100644--- a/apps/daemon/test/unit/creator-video-executor.test.ts+++ b/apps/daemon/test/unit/creator-video-executor.test.ts@@ -10,6 +10,9 @@ import { join } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import type { CreatorExecutorInput } from '../../src/creator/executor.js';import { createVideoExecutor } from '../../src/creator/video/executor.js';+import { CreatorProviderRequestLedger } from '../../src/creator/provider-requests.js';+import { createCreatorRepository } from '../../src/creator/repository.js';+import { openRuntimeDatabase } from '../../src/storage/database.js';import {VideoGenerationError,type VideoGenerationService@@ -23,6 +26,53 @@ afterEach(async () => {});describe('creator video executor', () => {+ it('recovers exactly the original video ledger entry among multiple pending requests', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-video-recover-ledger-'));+ const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));+ try {+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'video-generation', templateVersion: 1, status: 'running', state: stageInput({}, []).job.state });+ const original = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'interrupted', progress: { videoGenerationResultId: 'video_original' } });+ const resumed = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'running', progress: { resumedFromStageRunId: original.id } });+ const ledger = new CreatorProviderRequestLedger(repository);+ const register = (logicalId: string) => {+ const record = ledger.registerBeforeSubmit({ jobId: job.id, stageRunId: original.id, provider: 'opencreator-gateway-video', requestKey: logicalId, request: { prompt: logicalId }, gateway: { accountId: 'a', bindingVersion: 'a:1', logicalId } });+ return ledger.markSubmitting(record.id);+ };+ const other = register('another-video');+ const expected = register('original-video');+ const stage = stageInput({}, []); stage.job = repository.getJob(job.id)!; stage.stageRun = resumed;+ const service = videoService({+ create: vi.fn(async () => { throw new Error('must not create another video'); }),+ getGatewayBinding: async () => ({ accountId: 'a', bindingVersion: 'a:1', logicalId: 'original-video', requestId: 'original_gateway_request' }),+ get: async () => videoResult({ id: 'video_original', status: 'completed' })+ });+ const executor = createVideoExecutor({ ledger, service, probeVideo: async () => ({ duration: 5, width: 1280, height: 720, hasVideo: true, hasAudio: false }) });+ await executor.run(stage);+ const requests = repository.getJob(job.id)!.providerRequests;+ expect(requests.find(record => record.id === expected.id)).toMatchObject({ status: 'succeeded', remoteTaskId: 'original_gateway_request' });+ expect(requests.find(record => record.id === other.id)).toMatchObject({ status: 'submitting', remoteTaskId: null });+ expect(service.create).not.toHaveBeenCalled();+ } finally { db.close(); }+ });+ it('keeps a completed paid request successful when local output processing fails', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-video-ledger-'));+ const db = openRuntimeDatabase(join(tempDir, 'runtime.sqlite'));+ try {+ const repository = createCreatorRepository(db);+ const job = repository.createJob({ projectId: 'project', templateId: 'video-generation', templateVersion: 1, status: 'running', state: {} });+ const stageRun = repository.createStageRun({ jobId: job.id, stageId: 'generate', executor: 'video', status: 'running' });+ const stage = stageInput({}, []); stage.job.id = job.id; stage.stageRun.id = stageRun.id;+ const executor = createVideoExecutor({ ledger: new CreatorProviderRequestLedger(repository),+ service: videoService({ create: vi.fn(async (_request, options) => {+ options!.onGatewayBinding!({ accountId: 'a', bindingVersion: 'a:1', logicalId: stageRun.id });+ options!.onGatewayRequest!('original_gateway_request');+ return videoResult({ status: 'completed' });+ }) }), probeVideo: vi.fn(async () => { throw new Error('Local video validation failed'); }) });+ await expect(executor.run(stage)).rejects.toThrow('Local video validation failed');+ expect(repository.getJob(job.id)!.providerRequests[0]!.status).toBe('succeeded');+ } finally { db.close(); }+ });it('preserves upstream facts and the cause when a generation request is rejected', async () => {const publicFacts = {kind: 'http-rejected' as const, provider: 'seedance', httpStatus: 400,diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.tsnew file mode 100644index 00000000..0502e74e--- /dev/null+++ b/apps/daemon/test/unit/gateway-account-service.test.ts@@ -0,0 +1,481 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it, vi } from 'vitest';+import * as module from '../../src/gateway/account-service.js';+import { GatewayError, type GatewayBootstrap } from '../../src/gateway/client.js';+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';++const roots: string[] = [];+afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });+async function setup(activate = vi.fn(async () => undefined), close = vi.fn(async () => undefined), hasPendingTasks = () => false, hasActiveTasks = () => false, modelAccess?: (root: string) => OfficialModelAccess) {+ expect(module).toHaveProperty('createGatewayAccountService', expect.any(Function));+ const root = await mkdtemp(join(tmpdir(), 'oc-gateway-account-')); roots.push(root);+ let attempt = 0;+ const client = {+ origin: 'https://gateway.example',+ async startDevice() { const id = String(++attempt); return { attemptId: id, deviceSecret: `private-${id}`, authorizationUrl: `https://gateway.example/device?attempt=${id}`, interval: 5, expiresIn: 600 }; },+ pollDevice: vi.fn(async (id: string) => ({ accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresIn: 900 })),+ async cancelDevice() {},+ refresh: vi.fn(async () => ({ accessToken: 'new-access', refreshToken: 'new-refresh', expiresIn: 900 })),+ async logout() {},+ avatar: vi.fn(async () => ({ data: new Uint8Array([1, 2, 3]), contentType: 'image/png' })),+ bootstrap: vi.fn(async (access: string): Promise<GatewayBootstrap> => { const id = access.split('-').at(-1)!; return { schemaVersion: 1 as const, account: { id, email: `${id}@example.test`, verified: true }, modelKey: `cloud-${id}`, keyVersion: '1', bindingVersion: `${id}:1`, baseUrl: 'https://gateway.example/v1', models: [{ id: 'gateway-text', modality: 'text' as const, capabilities: ['responses'] }], defaults: { text: 'gateway-text' } }; }),+ async request() { return {}; }+ };+ const service = module.createGatewayAccountService({ dataDir: root, client, activateRuntime: activate, closeRuntime: close, hasActiveTasks, hasPendingTasks, automaticPolling: false, modelAccess: modelAccess?.(root) });+ return { service, root, client, activate, 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; });+ const requests: string[] = [];+ const f = await setup(undefined, undefined, undefined, undefined, root => createOfficialModelAccess({+ dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {+ if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ const model = JSON.parse(String(options?.body)).model; requests.push(model);+ await waiting;+ return model.startsWith('openai/') ? Response.json({ error: { message: 'The request is prohibited due to a violation of provider Terms Of Service.' } }, { status: 403 })+ : Response.json({ status: 'completed', output: [{ type: 'function_call', name: 'oc_access_check', arguments: '{"ready":true}' }] });+ }+ }));+ const raw = { ...await f.client.bootstrap('access-1'), transport: 'openrouter-direct' as const, baseUrl: 'https://openrouter.ai/api/v1', keyRotation: true,+ models: ['deepseek/deepseek-v3.2', 'deepseek/deepseek-r1', 'openai/gpt-4.1-mini', 'openai/gpt-6-sol', 'qwen/qwen3-coder', 'anthropic/claude-sonnet-4.6'].map(id => ({ id, modality: 'text' as const, capabilities: ['responses'] })), defaults: { text: 'deepseek/deepseek-v3.2' } };+ f.client.bootstrap.mockResolvedValue(raw);+ const usage: Array<{ busy: boolean }> = [];+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string, _access?: string, body?: unknown) => {+ if (path === '/api/v1/client/usage') { usage.push(body as { busy: boolean }); return { keyVersion: raw.keyVersion }; }+ return path === '/api/v1/client/models' ? { models: raw.models } : { account: raw.account };+ });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ await expect.poll(() => requests.length).toBeGreaterThan(0);+ expect(f.service.peekState().activationState).toBe('ready');+ await f.service.selectModel('text', 'deepseek/deepseek-r1');+ finishProbe();+ await expect.poll(() => f.service.peekState().models.some(model => model.id === 'qwen/qwen3-coder')).toBe(true);+ expect(f.service.peekState().models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'deepseek/deepseek-r1', 'qwen/qwen3-coder']);+ expect(f.service.peekState().selectedModels?.text).toBe('deepseek/deepseek-r1');+ await expect(f.service.selectModel('text', 'openai/gpt-6-sol')).rejects.toMatchObject({ code: 'invalid_model' });+ expect((await f.service.modelCredentials()).models).toEqual(f.service.peekState().models);+ expect((await createGatewayConfigStore(f.root).readCredentials())?.models).toHaveLength(6);+ expect(usage.some(value => value.busy)).toBe(true);+ await f.service.close();+ expect(usage.at(-1)?.busy).toBe(false);+});++it('defers a blocked default replacement until idle and recovers after every family was denied', async () => {+ let active = true; let denyFallback = false; let recover = false;+ let finishProbe!: () => void;+ const waiting = new Promise<void>(resolve => { finishProbe = resolve; });+ const f = await setup(undefined, undefined, undefined, () => active, root => createOfficialModelAccess({+ dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {+ if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ await waiting;+ const model = JSON.parse(String(options?.body)).model;+ return !recover && (model.startsWith('openai/') || denyFallback)+ ? Response.json({ error: { message: 'Model unavailable in this country' } }, { status: 403 })+ : Response.json({ status: 'completed', output: [{ type: 'function_call', name: 'oc_access_check', arguments: '{"ready":true}' }] });+ }+ }));+ active = false;+ const raw = { ...await f.client.bootstrap('access-1'), transport: 'openrouter-direct' as const, baseUrl: 'https://openrouter.ai/api/v1',+ models: ['openai/gpt-4.1-mini', 'deepseek/deepseek-v3.2'].map(id => ({ id, modality: 'text' as const, capabilities: ['responses'] })), defaults: { text: 'openai/gpt-4.1-mini' } };+ f.client.bootstrap.mockResolvedValue(raw);+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string) => path === '/api/v1/client/models' ? { models: raw.models } : { account: raw.account });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ active = true; finishProbe();+ await expect.poll(() => f.service.peekState().selectedModels?.text).toBe('deepseek/deepseek-v3.2');+ expect(f.activate).toHaveBeenCalledOnce();+ active = false;+ expect(await f.service.readState()).toMatchObject({ activationState: 'ready', selectedModels: { text: 'deepseek/deepseek-v3.2' } });+ expect(f.activate).toHaveBeenLastCalledWith(expect.objectContaining({ defaults: { text: 'deepseek/deepseek-v3.2' } }));+ const start = Date.now(); const clock = vi.spyOn(Date, 'now').mockReturnValue(start + 24 * 60 * 60_000 + 1);+ try {+ denyFallback = true;+ await f.service.readState();+ await expect.poll(() => f.service.peekState().activationState).toBe('blocked');+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });+ recover = true; clock.mockReturnValue(start + 25 * 60 * 60_000 + 2);+ await f.service.readState();+ await expect.poll(() => f.service.peekState().activationState).toBe('ready');+ expect(f.service.peekState().bindingVersion).toBe(raw.bindingVersion);+ expect((await f.service.modelCredentials()).defaults.text).toBeTruthy();+ expect(f.activate).toHaveBeenCalledTimes(3);+ } finally { clock.mockRestore(); await f.service.close(); }+});++it('aborts an in-flight availability check on logout without applying a late result', async () => {+ let started = false; let aborted = false;+ const f = await setup(undefined, undefined, undefined, undefined, root => createOfficialModelAccess({+ dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {+ if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');+ started = true;+ return new Promise<Response>(resolve => options!.signal!.addEventListener('abort', () => {+ aborted = true;+ resolve(Response.json({ status: 'completed', output: [{ type: 'function_call', name: 'oc_access_check', arguments: '{"ready":true}' }] }));+ }, { once: true }));+ }+ }));+ const raw = { ...await f.client.bootstrap('access-1'), transport: 'openrouter-direct' as const,+ models: [{ id: 'deepseek/deepseek-v3.2', modality: 'text' as const, capabilities: ['responses'] }], defaults: { text: 'deepseek/deepseek-v3.2' } };+ f.client.bootstrap.mockResolvedValue(raw);+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ await expect.poll(() => started).toBe(true);+ await f.service.logout();+ expect(aborted).toBe(true);+ expect(f.service.peekState()).toMatchObject({ authState: 'signed_out', activationState: 'inactive', models: [] });+ expect(await createGatewayConfigStore(f.root).readCredentials()).toBeUndefined();+ expect(f.activate).toHaveBeenCalledOnce();+ await f.service.close();+});++it('login overrides a saved manual mode and logout restores custom services', async () => {+ const f = await setup();+ await createGatewayConfigStore(f.root).writeConfiguration({ source: 'manual', bindingVersion: null, explicitlySelected: true });+ const authorization = await f.service.startAuthorization(); await f.service.pollAuthorization(authorization.attemptId);+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ expect(f.activate).toHaveBeenCalledOnce();+ await expect(f.service.setSource('manual')).rejects.toMatchObject({ code: 'logout_required' });+ await f.service.logout();+ expect(await f.service.readState()).toMatchObject({ source: 'manual', authState: 'signed_out', activationState: 'inactive' });+ await expect(f.service.setSource('gateway')).rejects.toMatchObject({ status: 401 });+ await f.service.close();+});++it('coordinates concurrent direct uses and refreshes a replaced user key privately', async () => {+ const f = await setup();+ const original = await f.client.bootstrap('access-1');+ let binding = { ...original, keyRotation: true };+ let currentVersion = binding.keyVersion;+ const states: Array<{ busy: boolean; pending: boolean }> = [];+ f.client.bootstrap.mockImplementation(async () => binding);+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string, _access?: string, body?: unknown) => {+ if (path === '/api/v1/client/usage') { states.push(body as { busy: boolean; pending: boolean }); return { keyVersion: currentVersion }; }+ if (path === '/api/v1/client/models') return { models: binding.models };+ return { account: binding.account };+ });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ binding = { ...binding, modelKey: 'replacement-private-key', keyVersion: '2', bindingVersion: '1:2' }; currentVersion = '2';+ const first = await f.service.beginModelUse();+ const second = await f.service.beginModelUse();+ expect(first.credentials.modelKey).toBe('replacement-private-key');+ expect(f.client.bootstrap).toHaveBeenLastCalledWith('access-1', { rotate: false });+ expect(states.at(-1)).toMatchObject({ busy: true });+ await first.release(); expect(states.at(-1)).toMatchObject({ busy: true });+ await second.release(); expect(states.at(-1)).toMatchObject({ busy: false });+ await second.release(); expect(states.at(-1)).toMatchObject({ busy: false });+ expect(f.activate).toHaveBeenCalledOnce();+ expect((await createGatewayConfigStore(f.root).readCredentials())?.modelKey).toBe('replacement-private-key');+ expect(JSON.stringify(await f.service.readState())).not.toContain('replacement-private-key');+ await f.service.close();+});++it('automatically requests migration on restart and defers it for pending supplier work', async () => {+ const f = await setup();+ const original = { ...await f.client.bootstrap('access-1'), keyRotation: true };+ f.client.bootstrap.mockResolvedValue(original);+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string) => path === '/api/v1/client/usage'+ ? { keyVersion: original.keyVersion } : path === '/api/v1/client/models' ? { models: original.models } : { account: original.account });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ await f.service.close();+ for (const pending of [true, false]) {+ const restored = module.createGatewayAccountService({ dataDir: f.root, client: f.client, activateRuntime: f.activate, closeRuntime: f.close, hasActiveTasks: () => false, hasPendingTasks: () => pending, automaticPolling: false });+ expect(await restored.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready' });+ expect(f.client.bootstrap).toHaveBeenLastCalledWith('access-1', { rotate: !pending });+ await restored.close();+ }+});++it('does not admit direct use when control-plane coordination fails', 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'));+ await expect(f.service.beginModelUse()).rejects.toMatchObject({ code: 'gateway_unavailable' });+ request.mockResolvedValue({ keyVersion: binding.keyVersion });+ const use = await f.service.beginModelUse(); await use.release();+ await f.service.close();+});++it('persists official model choices and validates the catalog', async () => {+ const f = await setup();+ const original = f.client.bootstrap;+ original.mockImplementation(async () => ({ schemaVersion: 1 as const, account: { id: '1', email: '[email protected]', verified: true }, modelKey: 'cloud-1', keyVersion: '1', bindingVersion: '1:1', baseUrl: 'https://gateway.example/v1', models: [{ id: 'first', modality: 'text' as const, capabilities: ['responses'] }, { id: 'second', modality: 'text' as const, capabilities: ['responses'] }], defaults: { text: 'first' } }));+ const authorization = await f.service.startAuthorization(); await f.service.pollAuthorization(authorization.attemptId);+ await f.service.selectModel('text', 'second');+ expect((await f.service.modelCredentials()).defaults.text).toBe('second');+ expect(f.activate).toHaveBeenLastCalledWith(expect.objectContaining({ defaults: { text: 'second' } }));+ await expect(f.service.selectModel('text', 'unknown')).rejects.toMatchObject({ code: 'invalid_model' });+ await f.service.logout();+ const second = await f.service.startAuthorization(); await f.service.pollAuthorization(second.attemptId);+ expect((await f.service.readState()).selectedModels?.text).toBe('second');+ await f.service.close();+});++it('refreshes the official catalog when idle, preserving choices and deferring pending tasks', async () => {+ let pending = false;+ const f = await setup(undefined, undefined, () => pending);+ const first = { id: 'first', modality: 'text' as const, capabilities: ['responses'] };+ const second = { ...first, id: 'second' };+ const image = { id: 'image', modality: 'image' as const, capabilities: ['edit'] };+ let catalog: GatewayBootstrap['models'] = [first, second];+ f.client.bootstrap.mockImplementation(async () => ({ schemaVersion: 1, account: { id: '1', email: '[email protected]', verified: true }, modelKey: 'private-key', keyVersion: '1', bindingVersion: 'catalog-version', baseUrl: 'https://gateway.example/v1', models: catalog, defaults: { text: 'first' } }));+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string) => path === '/api/v1/client/models' ? { models: catalog } : { account: { id: '1', email: '[email protected]', verified: true } });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ await f.service.selectModel('text', 'second');+ const start = Date.now(); const clock = vi.spyOn(Date, 'now').mockReturnValue(start + 31_000);+ try {+ catalog = [first, second, image];+ pending = true;+ expect((await f.service.readState()).models).toHaveLength(2);+ pending = false;+ expect(await f.service.readState()).toMatchObject({ models: catalog, selectedModels: { text: 'second' } });+ expect(f.activate).toHaveBeenLastCalledWith(expect.objectContaining({ models: catalog, defaults: { text: 'second', image: 'image' } }));+ const calls = f.client.bootstrap.mock.calls.length;+ clock.mockReturnValue(start + 62_000); await f.service.readState();+ expect(f.client.bootstrap.mock.calls).toHaveLength(calls);+ catalog = [first]; clock.mockReturnValue(start + 93_000);+ expect((await f.service.readState()).selectedModels?.text).toBe('first');+ await f.service.logout(); clock.mockReturnValue(start + 124_000);+ await f.service.readState(); expect((await f.service.readState()).source).toBe('manual');+ } finally { clock.mockRestore(); await f.service.close(); }+});++it('clears an expired device session before starting reauthorization', async () => {+ const f = await setup();+ const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 16 * 60_000);+ try {+ f.client.refresh.mockRejectedValueOnce(new GatewayError('auth_required', 401));+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ status: 401 });+ expect((await f.service.readState()).authState).toBe('expired');+ const next = await f.service.startAuthorization();+ await f.service.pollAuthorization(next.attemptId);+ expect(await f.service.readState()).toMatchObject({ authState: 'signed_in', activationState: 'ready', account: { id: '2' } });+ } finally { clock.mockRestore(); await f.service.close(); }+});++it('reads only the public plan catalog without signing in or changing account state', async () => {+ const f = await setup();+ const request = vi.spyOn(f.client, 'request').mockResolvedValue({ plans: [], billingAvailable: true });+ expect(await f.service.readPlans()).toEqual({ plans: [], billingAvailable: true });+ expect(request).toHaveBeenCalledExactlyOnceWith('/api/v1/plans', '');+ expect(await f.service.readState()).toMatchObject({ source: 'manual', authState: 'signed_out' });+ await expect(f.service.billing('/api/v1/billing/summary')).rejects.toMatchObject({ status: 401 });+ await f.service.close();+});++it('blocks logout with pending requests but permits same-account reauthorization after expiry', 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));+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ status: 401 });+ vi.spyOn(f.client, 'request').mockResolvedValue({ account: { id: '1', email: '[email protected]', verified: true } });+ const next = await f.service.startAuthorization();+ f.client.pollDevice.mockResolvedValueOnce({ accessToken: 'access-1', refreshToken: 'refresh-1', expiresIn: 900 });+ await f.service.pollAuthorization(next.attemptId);+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ pending = false; await f.service.logout();+ expect((await f.service.readState()).source).toBe('manual');+ } finally { clock.mockRestore(); 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);+ const first = await f.service.startAuthorization(); await f.service.pollAuthorization(first.attemptId);+ pending = true;+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 16 * 60_000);+ try {+ f.client.refresh.mockRejectedValueOnce(new GatewayError('auth_required', 401));+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ status: 401 });+ vi.spyOn(f.client, 'request').mockResolvedValue({ account: { id: '2', email: '[email protected]', verified: true } });+ const revoke = vi.spyOn(f.client, 'logout');+ const next = await f.service.startAuthorization();+ await f.service.pollAuthorization(next.attemptId);+ expect(revoke).toHaveBeenCalledWith('access-2');+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'expired', account: { id: '1' }, activationState: 'blocked', activationError: { code: 'account_mismatch' } });+ expect((await createGatewayConfigStore(f.root).readCredentials())?.accessToken).toBe('access-1');+ } finally { clock.mockRestore(); await f.service.close(); }+});++it('canceling guest authorization restores custom services', async () => {+ const f = await setup();+ await f.service.startAuthorization();+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'authorizing' });+ await f.service.cancelAuthorization();+ expect(await f.service.readState()).toMatchObject({ source: 'manual', authState: 'signed_out', activationState: 'inactive' });+ await f.service.close();+});++it('late authorization cannot replace a newer account', async () => {+ const f = await setup();+ let release!: (value: { accessToken: string; refreshToken: string; expiresIn: number }) => void;+ f.client.pollDevice.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));+ const first = await f.service.startAuthorization();+ const delayed = f.service.pollAuthorization(first.attemptId);+ const second = await f.service.startAuthorization();+ await f.service.pollAuthorization(second.attemptId);+ release({ accessToken: 'access-1', refreshToken: 'refresh-1', expiresIn: 900 });+ await delayed;+ const state = await f.service.readState();+ expect(state.account?.id).toBe('2');+ expect(state.activationState).toBe('ready');+ expect(JSON.stringify(state)).not.toMatch(/cloud-|access-|refresh-|private-/);+ await f.service.close();+});++it('bootstrap or Runtime failure leaves a signed-in account unready', async () => {+ const f = await setup(vi.fn(async () => { throw new Error('test-cloud-secret'); }));+ const attempt = await f.service.startAuthorization();+ await f.service.pollAuthorization(attempt.attemptId);+ const state = await f.service.readState();+ expect(state.authState).toBe('signed_in');+ expect(state.source).toBe('gateway');+ expect(state.activationState).toBe('blocked');+ expect(JSON.stringify(state)).not.toContain('test-cloud-secret');+ const privateFile = await readFile(join(f.root, 'config/gateway-credentials.json'), 'utf8');+ expect(privateFile).toContain('cloud-1');+ const publicFile = await readFile(join(f.root, 'config/gateway.json'), 'utf8');+ expect(publicFile).not.toContain('cloud-1');+ expect(publicFile).not.toContain('access-1');+ expect(JSON.parse(publicFile)).toMatchObject({ source: 'gateway', bindingVersion: null });+ await f.service.close();+});++it('logout closes Runtime before clearing credentials or reporting completion', async () => {+ let exited!: () => void;+ const f = await setup(undefined, vi.fn(() => new Promise<void>(resolve => { exited = resolve; })));+ const attempt = await f.service.startAuthorization(); await f.service.pollAuthorization(attempt.attemptId);+ const logout = f.service.logout();+ await vi.waitFor(async () => expect((await f.service.readState()).authState).toBe('signing_out'));+ await expect(f.service.modelCredentials()).rejects.toThrow();+ expect((await readFile(join(f.root, 'config/gateway-credentials.json'), 'utf8'))).toContain('cloud-1');+ exited(); await logout;+ expect((await f.service.readState()).authState).toBe('signed_out');+ await expect(readFile(join(f.root, 'config/gateway-credentials.json'))).rejects.toThrow();+});++it('keeps the device session when bootstrap fails and can activate without another authorization', async () => {+ const f = await setup();+ f.client.bootstrap.mockRejectedValueOnce(new Error('bootstrap unavailable'));+ const attempt = await f.service.startAuthorization(); await f.service.pollAuthorization(attempt.attemptId);+ expect((await f.service.readState()).authState).toBe('signed_in');+ expect((await f.service.readState()).activationState).toBe('blocked');+ expect(await readFile(join(f.root, 'config/gateway-credentials.json'), 'utf8')).toContain('refresh-1');+ await f.service.activate();+ expect((await f.service.readState()).activationState).toBe('ready');+ await f.service.close();+});++it('concurrent reads wait for the same persisted account initialization', 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: () => false, automaticPolling: false });+ const [first, second] = await Promise.all([restored.readState(), restored.readState()]);+ expect(second).toEqual(first);+ expect(second.account?.id).toBe('1');+ expect(second.activationState).toBe('ready');+ await restored.close();+});++it('restores a failed activation on restart from a fresh bootstrap without signing in again', async () => {+ const f = await setup();+ f.client.bootstrap.mockRejectedValueOnce(new GatewayError('services_not_ready'));+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ expect(await f.service.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'blocked' });+ await expect(f.service.modelCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });+ await f.service.close();+ const restored = module.createGatewayAccountService({ dataDir: f.root, client: f.client, activateRuntime: f.activate, closeRuntime: f.close, hasActiveTasks: () => false, automaticPolling: false });+ try {+ expect(await restored.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: '1' } });+ expect(f.client.pollDevice).toHaveBeenCalledOnce();+ expect(f.activate).toHaveBeenCalledOnce();+ } finally { await restored.close(); }+});++it('blocks 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();+ await f.service.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();+ await createGatewayConfigStore(f.root).writeConfiguration({ source: 'manual', bindingVersion: null });+ const restored = module.createGatewayAccountService({ dataDir: f.root, client: f.client, activateRuntime: f.activate, closeRuntime: f.close, hasActiveTasks: () => false, automaticPolling: false });+ expect(await restored.readState()).toMatchObject({ source: 'gateway', authState: 'signed_in', activationState: 'ready' });+ await restored.logout(); await restored.close();+ await createGatewayConfigStore(f.root).writeConfiguration({ source: 'gateway', bindingVersion: null });+ const guest = module.createGatewayAccountService({ dataDir: f.root, client: f.client, activateRuntime: f.activate, closeRuntime: f.close, hasActiveTasks: () => false, automaticPolling: false });+ expect(await guest.readState()).toMatchObject({ source: 'manual', authState: 'signed_out' });+ await guest.close();+});++it('blocks logout before changing account state while tasks are active', async () => {+ let active = false;+ const f = await setup(undefined, undefined, undefined, () => active);+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ 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();+});++it('syncs profile photos independently of unavailable model services and protects the avatar route', async () => {+ const f = await setup();+ f.client.bootstrap.mockRejectedValueOnce(new GatewayError('services_not_ready'));+ const request = vi.spyOn(f.client, 'request').mockResolvedValue({ account: { id: '1', email: '[email protected]', verified: true, avatarUrl: 'https://lh3.googleusercontent.com/photo' } });+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ const [first, second] = await Promise.all([f.service.readState(), f.service.readState()]);+ expect(first).toEqual(second);+ expect(first).toMatchObject({ authState: 'signed_in', activationState: 'blocked', account: { id: '1', avatarUrl: 'https://lh3.googleusercontent.com/photo' } });+ expect(request).toHaveBeenCalledExactlyOnceWith('/api/v1/me', 'access-1');+ expect(f.activate).not.toHaveBeenCalled();+ const server = Fastify();+ try {+ await registerGatewayAccountRoutes(server, f.service);+ const image = await server.inject({ method: 'GET', url: '/gateway/avatar?accountId=1' });+ expect(image.statusCode).toBe(200);+ expect(image.headers['content-type']).toBe('image/png');+ expect(image.headers['cache-control']).toBe('no-store');+ expect(image.rawPayload).toEqual(Buffer.from([1, 2, 3]));+ expect((await server.inject({ method: 'GET', url: '/gateway/avatar?accountId=2' })).statusCode).toBe(404);+ expect(f.client.avatar).toHaveBeenCalledExactlyOnceWith('access-1', '1');+ await f.service.logout();+ expect((await server.inject({ method: 'GET', url: '/gateway/avatar?accountId=1' })).statusCode).toBe(401);+ } finally { await server.close(); await f.service.close(); }+});++it('ignores a profile response that arrives after signing out', async () => {+ const f = await setup();+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);+ let resolve!: (value: object) => void;+ vi.spyOn(f.client, 'request').mockImplementation(() => new Promise<object>(complete => { resolve = complete; }));+ const pending = f.service.readState();+ await vi.waitFor(() => expect(resolve).toBeDefined());+ await f.service.logout();+ resolve({ account: { id: '1', email: '[email protected]', verified: true, avatarUrl: 'https://lh3.googleusercontent.com/photo' } });+ expect(await pending).toMatchObject({ authState: 'signed_out', account: null });+ await expect(readFile(join(f.root, 'config/gateway-credentials.json'))).rejects.toThrow();+ await f.service.close();+});diff --git a/apps/daemon/test/unit/gateway-client.test.ts b/apps/daemon/test/unit/gateway-client.test.tsnew file mode 100644index 00000000..09bf5b9a--- /dev/null+++ b/apps/daemon/test/unit/gateway-client.test.ts@@ -0,0 +1,34 @@+import { expect, it, vi } from 'vitest';+import { accountSchema, createGatewayClient } from '../../src/gateway/client.js';++it('accepts only the explicit direct transport endpoint for official credentials', async () => {+ const value = { schemaVersion: 1, transport: 'openrouter-direct', account: { id: 'a', email: 'a@test', verified: true }, modelKey: 'private', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://openrouter.ai/api/v1', models: [], defaults: {} };+ const fetcher = vi.fn(async () => Response.json(value));+ const client = createGatewayClient('https://gateway.example', fetcher);+ expect((await client.bootstrap('device-access')).transport).toBe('openrouter-direct');+ value.baseUrl = 'https://other.test/v1';+ await expect(client.bootstrap('device-access')).rejects.toMatchObject({ code: 'invalid_gateway_response' });+});++it('keeps optional profile pictures while accepting old accounts', () => {+ const account = { id: 'a', email: '[email protected]', verified: true };+ expect(accountSchema.parse(account)).toEqual(account);+ const photo = { ...account, avatarUrl: 'https://lh3.googleusercontent.com/photo' };+ expect(accountSchema.parse(photo)).toEqual(photo);+});++it('retrieves bounded avatar bytes using the device session', async () => {+ const fetcher = vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { headers: { 'Content-Type': 'image/png' } }));+ const client = createGatewayClient('https://gateway.example', fetcher);+ expect(await client.avatar('private-device-token', 'a')).toEqual({ data: Buffer.from([1, 2, 3]), contentType: 'image/png' });+ expect(fetcher).toHaveBeenCalledWith('https://gateway.example/api/v1/me/avatar?accountId=a', expect.objectContaining({ redirect: 'error', headers: expect.objectContaining({ Authorization: 'Bearer private-device-token' }) }));+});++it('rejects oversized and non-image avatar responses and preserves account errors', async () => {+ for (const response of [new Response('<html>unavailable</html>', { headers: { 'Content-Type': 'text/html' } }), new Response(new Uint8Array(1024 * 1024 + 1), { headers: { 'Content-Type': 'image/png' } })]) {+ const client = createGatewayClient('https://gateway.example', vi.fn(async () => response));+ await expect(client.avatar('private-device-token', 'a')).rejects.toMatchObject({ code: 'invalid_gateway_response' });+ }+ const client = createGatewayClient('https://gateway.example', vi.fn(async () => Response.json({ error: { code: 'auth_required' } }, { status: 401 })));+ await expect(client.avatar('private-device-token', 'a')).rejects.toMatchObject({ code: 'auth_required', status: 401 });+});diff --git a/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.ts b/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.tsnew file mode 100644index 00000000..dfe50c31--- /dev/null+++ b/apps/daemon/test/unit/gateway-direct-runtime-rotation.test.ts@@ -0,0 +1,35 @@+import { expect, it, vi } from 'vitest';+import { createDirectRuntime } from '../../src/gateway/direct-runtime.js';++it('uses the current coordinated supplier key for each request in the same Runtime', async () => {+ let key = 'first-user-key'; let busy = 0;+ const keys: string[] = [];+ const fetcher = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ expect(String(url)).toBe('https://openrouter.ai/api/v1/responses');+ expect(busy).toBe(1);+ keys.push(new Headers(init?.headers).get('Authorization')!);+ return Response.json({ output: [] });+ }) as typeof fetch;+ const runtime = await createDirectRuntime('stale-cached-key', fetcher, async () => {+ busy++; return { key, async release() { busy--; } };+ });+ try {+ for (const next of ['first-user-key', 'replacement-user-key']) {+ key = next;+ const response = await fetch(`${runtime.baseUrl}/responses`, { method: 'POST', headers: { Authorization: `Bearer ${runtime.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'test/text', input: 'test' }) });+ expect(response.status).toBe(200); await response.json();+ await vi.waitFor(() => expect(busy).toBe(0));+ }+ expect(keys).toEqual(['Bearer first-user-key', 'Bearer replacement-user-key']);+ } finally { await runtime.close(); }+});++it('does not submit a supplier request when coordination denies admission', async () => {+ const fetcher = vi.fn() as typeof fetch;+ const runtime = await createDirectRuntime('user-key', fetcher, async () => { throw new Error('Coordination unavailable'); });+ try {+ const response = await fetch(`${runtime.baseUrl}/responses`, { method: 'POST', headers: { Authorization: `Bearer ${runtime.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: 'test' }) });+ expect(response.status).toBe(503); await response.json();+ expect(fetcher).not.toHaveBeenCalled();+ } finally { await runtime.close(); }+});diff --git a/apps/daemon/test/unit/gateway-model-access.test.ts b/apps/daemon/test/unit/gateway-model-access.test.tsnew file mode 100644index 00000000..a9cdaf92--- /dev/null+++ b/apps/daemon/test/unit/gateway-model-access.test.ts@@ -0,0 +1,147 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it, vi } from 'vitest';+import type { GatewayModel } from '@opencreator/protocol';+import type { GatewayBootstrap } from '../../src/gateway/client.js';+import { createOfficialModelAccess, modelAccessGroup, officialModelPolicy } from '../../src/gateway/model-access.js';++const roots: string[] = [];+afterEach(async () => { vi.restoreAllMocks(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });+const text = (id: string): GatewayModel => ({ id, modality: 'text', capabilities: ['responses'] });+const bootstrap = (models: GatewayModel[]): GatewayBootstrap => ({+ schemaVersion: 1, transport: 'openrouter-direct', account: { id: 'account-a', email: 'a@test', verified: true },+ modelKey: 'private-model-key', keyVersion: 'key-v1', bindingVersion: 'binding-v1', baseUrl: 'https://openrouter.ai/api/v1',+ models, defaults: { text: models.find(model => model.modality === 'text')!.id }+});+const success = () => Response.json({ status: 'completed', output: [{ type: 'function_call', name: 'oc_access_check', arguments: '{"ready":true}' }] });+const denied = () => Response.json({ error: { message: 'The request is prohibited due to a violation of provider Terms Of Service.' } }, { status: 403 });+async function fixture(models: GatewayModel[], reply: (id: string) => Response | Promise<Response> = success) {+ const root = await mkdtemp(join(tmpdir(), 'oc-model-access-')); roots.push(root);+ let proxy = 'http://127.0.0.1:7897'; let ip = '203.0.113.1';+ const calls: string[] = [];+ const fetcher = vi.fn<typeof fetch>(async (target, options) => {+ if (String(target).endsWith('/cdn-cgi/trace')) return new Response(`ip=${ip}\nloc=JP\n`);+ const body = JSON.parse(String(options?.body)); calls.push(body.model);+ expect(body).toMatchObject({ store: false, stream: false, max_output_tokens: 512 });+ expect(new Headers(options?.headers).get('authorization')).toBe('Bearer private-model-key');+ return reply(body.model);+ });+ const input = { dataDir: root, fetcher, readProxy: async () => proxy };+ const access = createOfficialModelAccess(input); const value = bootstrap(models);+ const run = (target = value) => access.refresh(target, new AbortController().signal, async () => undefined);+ return { root, input, access, value, run, calls, fetcher, setIP(value: string) { ip = value; }, setProxy(value: string) { proxy = value; } };+}++it('keeps hosted GPT and Gemini separate from open weight models and removes unsupported catalog entries', () => {+ expect(modelAccessGroup(text('openai/gpt-6-sol'))).toBe('openai');+ expect(modelAccessGroup(text('~openai/gpt-6-sol'))).toBe('openai');+ expect(modelAccessGroup(text('openai/gpt-oss-20b'))).toBe('openai-oss');+ expect(modelAccessGroup(text('google/gemma-3-12b-it'))).toBe('google-gemma');+ expect(modelAccessGroup(text('google/gemini-2.5-flash'))).toBe('google-gemini');+ expect(officialModelPolicy(['anthropic/claude-sonnet-4.6', '~anthropic/claude-opus-4.6', 'openai/gpt-4.1:batch', 'openrouter/auto', 'deepseek/deepseek-v3.2'].map(text)).map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+});++it('checks one representative per family and filters all explicitly denied family members', async () => {+ const image: GatewayModel = { id: 'openai/gpt-image-1', modality: 'image', capabilities: [] };+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-6-sol'), text('openai/gpt-4.1-mini'), image, text('google/gemini-2.5-flash'), text('google/gemini-2.5-flash-lite'), text('openai/gpt-oss-20b'), text('google/gemma-3-12b-it'), text('anthropic/claude-sonnet-4.6')], id => /gpt-4.1-mini|gemini/.test(id) ? denied() : success());+ expect((await f.access.prepare(f.value)).models.filter(model => model.modality === 'text').map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+ await f.run();+ expect(f.calls).toHaveLength(5);+ expect(f.calls).toContain('openai/gpt-4.1-mini');+ expect(f.calls).not.toContain('openai/gpt-6-sol');+ expect(f.calls).toContain('google/gemini-2.5-flash-lite');+ expect(f.calls).not.toContain(image.id);+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2', 'openai/gpt-oss-20b', 'google/gemma-3-12b-it']);+ const saved = await readFile(join(f.root, 'config/gateway-model-access.json'), 'utf8');+ expect(saved).not.toMatch(/private-model-key|203\.0\.113|a@test/);+});++it('preserves the selected family while another family finishes its check first', async () => {+ let finishSelected!: () => void;+ const waiting = new Promise<void>(resolve => { finishSelected = resolve; });+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], async id => {+ if (id.startsWith('deepseek/')) await waiting;+ return success();+ });+ const work = f.run();+ await expect.poll(() => f.access.filter(f.value).models.length).toBe(2);+ expect(f.access.filter(f.value).defaults.text).toBe('deepseek/deepseek-v3.2');+ finishSelected(); await work;+ expect(f.access.filter(f.value).defaults.text).toBe('deepseek/deepseek-v3.2');+});++it.each([429, 503, 403])('retains a previously accessible family for a transient or unrelated HTTP %s failure', async status => {+ let failure = false;+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], () => failure+ ? Response.json({ error: { message: status === 403 ? 'Key limit exceeded' : 'Temporarily unavailable' } }, { status }) : success());+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run(); failure = true; clock.mockReturnValue(Date.now() + 24 * 60 * 60_000 + 1);+ await f.run();+ expect(f.access.filter(f.value).models).toHaveLength(2);+});++it('keeps success across a network exception without caching a secret error message', async () => {+ let failed = false;+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('qwen/qwen3-coder')], () => {+ if (failed) throw new Error('private-model-key');+ return success();+ });+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run(); failed = true; clock.mockReturnValue(Date.now() + 24 * 60 * 60_000 + 1); await f.run();+ expect(f.access.filter(f.value).models).toHaveLength(2);+ expect(await readFile(join(f.root, 'config/gateway-model-access.json'), 'utf8')).not.toContain('private-model-key');+});++it('preserves cached results when the network identity endpoint is unavailable', async () => {+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], id => id.startsWith('openai/') ? denied() : success());+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run(); const count = f.calls.length;+ clock.mockReturnValue(Date.now() + 60_001);+ f.fetcher.mockRejectedValueOnce(new Error('trace unavailable'));+ await f.run();+ expect(f.calls).toHaveLength(count);+ expect(f.access.filter(f.value).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+});++it('reuses persisted results and retries a blocked family after one hour', async () => {+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')], id => id.startsWith('openai/') ? denied() : success());+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run(); const count = f.calls.length;+ const restored = createOfficialModelAccess(f.input);+ expect((await restored.prepare(f.value)).models.map(model => model.id)).toEqual(['deepseek/deepseek-v3.2']);+ await restored.refresh(f.value, new AbortController().signal, async () => undefined);+ expect(f.calls).toHaveLength(count);+ clock.mockReturnValue(Date.now() + 60 * 60_000 + 1); await f.run();+ expect(f.calls.slice(count)).toEqual(['openai/gpt-4.1-mini']);+});++it('invalidates results for account, key, proxy and exit changes', async () => {+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini')]);+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run();+ const key = { ...f.value, keyVersion: 'key-v2' };+ expect((await f.access.prepare(key)).models).toHaveLength(1); await f.run(key);+ const account = { ...key, account: { ...key.account, id: 'account-b' } };+ expect((await f.access.prepare(account)).models).toHaveLength(1); await f.run(account);+ f.setProxy('http://127.0.0.1:8888'); expect((await f.access.prepare(account)).models).toHaveLength(1); await f.run(account);+ f.setIP('203.0.113.2'); clock.mockReturnValue(Date.now() + 60_001); await f.run(account);+ expect(f.calls).toHaveLength(10);+});++it('tries another representative after a model-specific parameter or missing-model error', async () => {+ const f = await fixture([text('deepseek/deepseek-v3.2'), text('openai/gpt-4.1-mini'), text('openai/gpt-6-sol')], id => id === 'openai/gpt-4.1-mini'+ ? Response.json({ error: { message: 'Model is unavailable' } }, { status: 404 }) : success());+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now());+ await f.run(); clock.mockReturnValue(Date.now() + 5 * 60_000 + 1); await f.run();+ expect(f.calls.filter(id => id.startsWith('openai/'))).toEqual(['openai/gpt-4.1-mini', 'openai/gpt-6-sol']);+ expect(f.access.filter(f.value).models).toHaveLength(3);+});++it('bounds each background pass and stops starting probes after cancellation', async () => {+ const f = await fixture(Array.from({ length: 20 }, (_, i) => text(`vendor-${i}/model`)));+ await f.run(); expect(f.calls).toHaveLength(12);+ const controller = new AbortController(); controller.abort();+ await f.access.refresh(f.value, controller.signal, async () => undefined);+ expect(f.calls).toHaveLength(12);+});diff --git a/apps/daemon/test/unit/gateway-official-fetch.test.ts b/apps/daemon/test/unit/gateway-official-fetch.test.tsnew file mode 100644index 00000000..b1a73524--- /dev/null+++ b/apps/daemon/test/unit/gateway-official-fetch.test.ts@@ -0,0 +1,89 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { gzipSync } from 'node:zlib';+import { afterEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ request: vi.fn(), execFile: vi.fn() }));+vi.mock('node:https', () => ({ request: mocks.request }));+vi.mock('node:child_process', () => ({ execFile: mocks.execFile }));++import { createOfficialFetch } from '../../src/gateway/official-fetch.js';++afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); mocks.request.mockReset(); mocks.execFile.mockReset(); });++function upstream(headers: Record<string, string> = {}) {+ const response = Object.assign(new PassThrough(), { statusCode: 200, headers });+ const end = vi.fn();+ const request = Object.assign(new EventEmitter(), { end });+ mocks.request.mockImplementation((_url, _options, callback) => {+ end.mockImplementation(() => callback(response));+ return request;+ });+ return { response, request, end };+}++it('uses the macOS HTTPS proxy and exposes response bytes before upstream closes', async () => {+ mocks.execFile.mockImplementation((_file, _args, _options, callback) => {+ callback(null, '<dictionary> {\n HTTPSEnable : 1\n HTTPSProxy : 127.0.0.1\n HTTPSPort : 7897\n}\n');+ });+ const remote = upstream({ 'content-type': 'application/json' });+ const fetcher = createOfficialFetch({ platform: 'darwin' });+ const result = await fetcher('https://openrouter.ai/api/v1/images', {+ method: 'POST', headers: { Authorization: 'Bearer test-key' }, body: '{"prompt":"test"}'+ });+ const options = mocks.request.mock.calls[0]![1];+ expect(options.agent.proxy.href).toBe('http://127.0.0.1:7897/');+ expect(options.headers['accept-encoding']).toBe('identity');+ expect(remote.end).toHaveBeenCalledWith(Buffer.from('{"prompt":"test"}'));+ remote.response.write('first');+ const reader = result.body!.getReader();+ expect(Buffer.from((await reader.read()).value!).toString()).toBe('first');+ await reader.cancel();+ expect(remote.response.destroyed).toBe(true);+});++it('prefers a configured proxy and decodes gzip if the upstream still compresses', async () => {+ const remote = upstream({ 'content-type': 'application/json', 'content-encoding': 'gzip' });+ const fetcher = createOfficialFetch({ readProxy: async () => 'http://127.0.0.1:8888', platform: 'darwin' });+ const result = await fetcher('https://openrouter.ai/api/v1/images');+ remote.response.end(gzipSync('{"data":[{"b64_json":"image"}]}'));+ expect(await result.json()).toEqual({ data: [{ b64_json: 'image' }] });+ expect(result.headers.has('content-encoding')).toBe(false);+ expect(mocks.request.mock.calls[0]![1].agent.proxy.port).toBe('8888');+ expect(mocks.execFile).not.toHaveBeenCalled();+});++it('uses the direct connection when no proxy is available', async () => {+ const direct = vi.fn(async () => Response.json({ data: [] }));+ vi.stubGlobal('fetch', direct);+ const result = await createOfficialFetch({ platform: 'linux' })('https://openrouter.ai/api/v1/images');+ expect(await result.json()).toEqual({ data: [] });+ expect(direct).toHaveBeenCalledOnce();+ expect(mocks.request).not.toHaveBeenCalled();+});++it('reads shared proxy changes for each request without restarting the transport', async () => {+ let proxy = 'http://127.0.0.1:7897';+ const fetcher = createOfficialFetch({ readProxy: async () => proxy, platform: 'linux' });+ let remote = upstream();+ const first = await fetcher('https://www.open-creator.ai/api/v1/client/models');+ remote.response.end('{}'); await first.text();+ expect(mocks.request.mock.lastCall![1].agent.proxy.port).toBe('7897');+ proxy = 'http://127.0.0.1:8888'; remote = upstream();+ const second = await fetcher('https://openrouter.ai/api/v1/images');+ remote.response.end('{}'); await second.text();+ expect(mocks.request.mock.lastCall![1].agent.proxy.port).toBe('8888');+ proxy = ''; const direct = vi.fn(async () => Response.json({})); vi.stubGlobal('fetch', direct);+ await fetcher('https://openrouter.ai/api/v1/images'); expect(direct).toHaveBeenCalledOnce();+});++it('does not repeat a paid POST on another route when the proxy fails', async () => {+ const remote = upstream();+ remote.end.mockImplementation(() => queueMicrotask(() => remote.request.emit('error', new Error('lost after acceptance'))));+ mocks.request.mockImplementation(() => remote.request);+ const direct = vi.fn(); vi.stubGlobal('fetch', direct);+ const fetcher = createOfficialFetch({ readProxy: async () => 'http://127.0.0.1:7897' });+ await expect(fetcher('https://openrouter.ai/api/v1/images', { method: 'POST', body: '{}' })).rejects.toThrow('lost after acceptance');+ expect(mocks.request).toHaveBeenCalledOnce();+ expect(direct).not.toHaveBeenCalled();+});diff --git a/apps/daemon/test/unit/gateway-runtime-bindings.test.ts b/apps/daemon/test/unit/gateway-runtime-bindings.test.tsnew file mode 100644index 00000000..7315b5dd--- /dev/null+++ b/apps/daemon/test/unit/gateway-runtime-bindings.test.ts@@ -0,0 +1,130 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import * as bindings from '../../src/gateway/runtime-bindings.js';+import type { GatewayRuntimeBindingsInput } from '../../src/gateway/runtime-bindings.js';+import { createCodexAppServerHost } from '../../src/codex/app-server-host-2026-07-28.js';+import { runCodexExec } from '../../src/codex/runner.js';+import { spawnCodexProcess } from '../../src/codex/process.js';++vi.mock('../../src/codex/process.js', () => ({+ spawnCodexProcess: vi.fn(() => { throw new Error('test spawn stopped'); }),+ terminateCodexProcess: vi.fn()+}));++const roots: string[] = [];+afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })));++function setup(overrides: Partial<GatewayRuntimeBindingsInput> = {}) {+ expect(bindings).toHaveProperty('createGatewayRuntimeBindings', expect.any(Function));+ const root = mkdtempSync(join(tmpdir(), 'oc-gateway-runtime-'));+ roots.push(root);+ return bindings.createGatewayRuntimeBindings({+ codexHome: join(root, 'official'),+ baseUrl: 'https://gateway.example/v1',+ model: 'gateway-text',+ readCredentials: async () => ({ accountId: 'account-a', modelKey: 'test-cloud-secret', keyVersion: '1' }),+ closeRuntime: async () => undefined,+ parentEnvironment: {+ PATH: process.env.PATH,+ HOME: '/personal-home',+ OPENAI_API_KEY: 'test-personal-secret',+ OPENAI_BASE_URL: 'https://personal.example',+ ANTHROPIC_API_KEY: 'test-other-secret',+ CODEX_HOME: '/personal-codex',+ HTTP_PROXY: 'http://personal-proxy',+ NODE_OPTIONS: '--require /personal-hook.js'+ },+ ...overrides+ });+}++describe('official Runtime bindings', () => {+ it('respects an explicit base environment at both subprocess boundaries', async () => {+ vi.stubEnv('OPENAI_API_KEY', 'test-parent-secret');+ try {+ const input = {+ codexBin: 'codex', codexHome: '/official-home', cwd: '/work',+ profile: 'default', args: ['exec'], prompt: 'hello',+ baseEnvironment: { PATH: '/test-path' },+ env: { OC_GATEWAY_MODEL_KEY: 'test-cloud-secret' }+ };+ expect(() => createCodexAppServerHost(input)).toThrow('test spawn stopped');+ const expected = {+ PATH: '/test-path', OC_GATEWAY_MODEL_KEY: 'test-cloud-secret', CODEX_HOME: '/official-home'+ };+ const hostEnvironment = vi.mocked(spawnCodexProcess).mock.lastCall?.[2]?.env;+ expect(Object.keys(hostEnvironment ?? {}).sort()).toEqual(Object.keys(expected).sort());+ expect(hostEnvironment).toMatchObject(expected);+ await expect(runCodexExec(input)).rejects.toThrow('test spawn stopped');+ const execEnvironment = vi.mocked(spawnCodexProcess).mock.lastCall?.[2]?.env;+ expect(Object.keys(execEnvironment ?? {}).sort()).toEqual(Object.keys(expected).sort());+ expect(execEnvironment).toMatchObject(expected);+ } finally {+ vi.unstubAllEnvs();+ }+ });++ it('isolates credentials and never persists the cloud key in Runtime config', async () => {+ const runtime = setup();+ const prepared = await runtime.prepare();+ expect(prepared.env.OC_GATEWAY_MODEL_KEY).toBe('test-cloud-secret');+ expect(prepared.env).not.toHaveProperty('OPENAI_API_KEY');+ expect(prepared.env).not.toHaveProperty('ANTHROPIC_API_KEY');+ expect(prepared.env).not.toHaveProperty('OPENAI_BASE_URL');+ expect(prepared.env).not.toHaveProperty('HTTP_PROXY');+ expect(prepared.env).not.toHaveProperty('NODE_OPTIONS');+ expect(prepared.env.HOME).toBe(prepared.codexHome);+ const config = readFileSync(join(prepared.codexHome, 'config.toml'), 'utf8');+ expect(config).toContain('env_key = "OC_GATEWAY_MODEL_KEY"');+ expect(config).toContain('wire_api = "responses"');+ expect(config).toContain('request_max_retries = 0');+ expect(config).toContain('stream_max_retries = 0');+ expect(config).not.toContain('test-cloud-secret');+ expect(config).not.toContain('test-personal-secret');+ expect(existsSync(join(prepared.codexHome, 'auth.json'))).toBe(false);+ if (process.platform !== 'win32') {+ expect(statSync(prepared.codexHome).mode & 0o777).toBe(0o700);+ expect(statSync(join(prepared.codexHome, 'config.toml')).mode & 0o777).toBe(0o600);+ }+ await runtime.close();+ expect(prepared.env).not.toHaveProperty('OC_GATEWAY_MODEL_KEY');+ });++ it('rejects new and delayed preparations after logout begins', async () => {+ let release!: (value: { accountId: string; modelKey: string; keyVersion: string }) => void;+ const runtime = setup({ readCredentials: () => new Promise(resolve => { release = resolve; }) });+ const preparing = runtime.prepare();+ runtime.beginLogout();+ release({ accountId: 'account-a', modelKey: 'late-secret', keyVersion: '1' });+ await expect(preparing).rejects.toThrow('signed out');+ await expect(runtime.prepare()).rejects.toThrow('signed out');+ await runtime.close();+ });++ it('does not report logout complete before credential-holding processes exit', async () => {+ let exited!: () => void;+ const closeRuntime = vi.fn(() => new Promise<void>(resolve => { exited = resolve; }));+ const runtime = setup({ closeRuntime });+ const prepared = await runtime.prepare();+ let completed = false;+ const closing = runtime.close().then(() => { completed = true; });+ await expect(runtime.prepare()).rejects.toThrow('signed out');+ expect(completed).toBe(false);+ expect(prepared.env.OC_GATEWAY_MODEL_KEY).toBe('test-cloud-secret');+ exited();+ await closing;+ await runtime.close();+ expect(completed).toBe(true);+ expect(closeRuntime).toHaveBeenCalledOnce();+ expect(prepared.env).not.toHaveProperty('OC_GATEWAY_MODEL_KEY');+ });++ it('fails closed when credential shutdown fails', async () => {+ const runtime = setup({ closeRuntime: async () => { throw new Error('process did not exit'); } });+ await runtime.prepare();+ await expect(runtime.close()).rejects.toThrow('process did not exit');+ await expect(runtime.prepare()).rejects.toThrow('signed out');+ });+});diff --git a/apps/daemon/test/unit/krillin-official-config.test.ts b/apps/daemon/test/unit/krillin-official-config.test.tsnew file mode 100644index 00000000..07c9d934--- /dev/null+++ b/apps/daemon/test/unit/krillin-official-config.test.ts@@ -0,0 +1,14 @@+import { parse } from '@iarna/toml';+import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';+import { expect, it } from 'vitest';+import { createKrillinConfigToml } from '../../src/creator/krillin/config-bridge.js';++it('emits the selected ASR marker only for an official runtime and keeps custom configuration unchanged', () => {+ const config = createDefaultCreatorServicesConfig(); config.proxy = 'http://127.0.0.1:7897'; config.transcription.openai.model = 'custom-asr';+ expect(parse(createKrillinConfigToml(config))).toMatchObject({ app: { proxy: config.proxy }, transcribe: { openai: { model: 'custom-asr' } } });+ expect(createKrillinConfigToml(config)).not.toContain('official_model');+ const official = parse(createKrillinConfigToml(config, undefined, 'official-asr'));+ expect(official).toMatchObject({ transcribe: { openai: { official_model: 'official-asr' } } });+ expect(official.app).not.toHaveProperty('proxy');+ expect(config.transcription.openai.model).toBe('custom-asr');+});diff --git a/apps/daemon/test/unit/krillin-tts-service.test.ts b/apps/daemon/test/unit/krillin-tts-service.test.tsindex 61e9e527..2b644f0a 100644--- a/apps/daemon/test/unit/krillin-tts-service.test.ts+++ b/apps/daemon/test/unit/krillin-tts-service.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import type { CreatorServicesConfigStore } from '../../src/creator-services/config-store.js';+import { createGatewayCreatorSource } from '../../src/gateway/creator-service-source.js';import {createKrillinTtsService,KrillinTtsServiceError@@ -18,6 +19,30 @@ describe('KrillinTtsService', () => {await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));});+ it('rejects personal models and lists voices for the selected official speech model', async () => {+ const root = await temporaryRoot();+ const executeUtility = vi.fn();+ const source = createGatewayCreatorSource({+ account: { peekState: () => ({ source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null }), modelCredentials: async () => ({ accountId: 'a', modelKey: 'secret', keyVersion: '1', bindingVersion: 'a:1', baseUrl: 'https://gateway.example/v1', defaults: { speech: 'official-first' }, models: [{ id: 'official-first', modality: 'speech', capabilities: [], voices: ['first-voice'] }, { id: 'official-second', modality: 'speech', capabilities: [], voices: ['second-voice'] }] }) },+ manual: createConfigStore(createDefaultCreatorServicesConfig()), getLocalOrigin: () => 'http://127.0.0.1:39999'+ });+ const service = createKrillinTtsService({ resourceRoot: join(root, 'runtime'), workRoot: join(root, 'work'), configStore: source.store, executeUtility });+ await expect(service.listVoices('aliyun', 'personal-model')).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ const result = await service.listVoices('openai', 'official-second');+ expect(result).toMatchObject({ provider: 'openai', model: 'official-second', voices: [{ id: 'second-voice', provider: 'openai' }] });+ expect((await service.listVoices('openai')).voices.map(voice => voice.id)).toEqual(['first-voice']);+ expect(executeUtility).not.toHaveBeenCalled();+ const fetchMock = vi.fn<typeof fetch>(async () => new Response(new Uint8Array([1, 2, 3]), { headers: { 'Content-Type': 'audio/mpeg' } }));+ vi.stubGlobal('fetch', fetchMock);+ const audio = await service.synthesize({ text: 'hello', provider: 'openai', model: 'official-second', format: 'mp3' });+ expect(audio).toMatchObject({ model: 'official-second', voiceId: 'second-voice' });+ expect(JSON.parse(String(fetchMock.mock.lastCall?.[1]?.body))).toMatchObject({ model: 'official-second', voice: 'second-voice' });+ await expect(service.synthesize({ text: 'hello', model: 'personal-model' })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ await expect(service.synthesize({ text: 'hello', model: 'official-second', voiceId: 'first-voice' })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ await expect(source.runForJob('job', 'stage', () => service.synthesize({ text: 'hello', model: 'official-second' }))).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });+ expect(fetchMock).toHaveBeenCalledOnce();+ });+it('lists the bundled Qwen3 voice catalog without calling an outdated Runtime', async () => {const root = await temporaryRoot();const config = createDefaultCreatorServicesConfig();diff --git a/apps/daemon/test/unit/startup.test.ts b/apps/daemon/test/unit/startup.test.tsindex 15ebf332..63e6b75e 100644--- a/apps/daemon/test/unit/startup.test.ts+++ b/apps/daemon/test/unit/startup.test.ts@@ -50,6 +50,7 @@ describe('daemon production startup', () => {OPENCREATOR_DEFAULT_PROJECT_ROOT: ' /tmp/Documents ',OPENCREATOR_YT_DLP_PATH: ' /tmp/yt-dlp '})).toEqual({+ gatewayOrigin: 'https://www.open-creator.ai',dataDir: '/tmp/opencreator-data',codexBin: '/tmp/fake-codex',codexHome: '/tmp/opencreator-codex-home',@@ -67,7 +68,16 @@ describe('daemon production startup', () => {OPENCREATOR_DEFAULT_CWD: '\n',OPENCREATOR_DEFAULT_PROJECT_ROOT: ' ',OPENCREATOR_YT_DLP_PATH: ''- })).toEqual({});+ })).toEqual({ gatewayOrigin: 'https://www.open-creator.ai' });+ });++ it('uses the production gateway by default and allows an explicit local gateway', () => {+ expect(resolveProductionServerEnvironment({+ OPENCREATOR_GATEWAY_ORIGIN: ' '+ }).gatewayOrigin).toBe('https://www.open-creator.ai');+ expect(resolveProductionServerEnvironment({+ OPENCREATOR_GATEWAY_ORIGIN: ' http://127.0.0.1:8787 '+ }).gatewayOrigin).toBe('http://127.0.0.1:8787');});it('prefers standard CODEX_HOME and keeps the legacy variable as a fallback', () => {diff --git a/apps/desktop/e2e/desktop.spec.ts b/apps/desktop/e2e/desktop.spec.tsindex afb2735e..0bdaae08 100644--- a/apps/desktop/e2e/desktop.spec.ts+++ b/apps/desktop/e2e/desktop.spec.ts@@ -1136,6 +1136,77 @@ test('@package-smoke 启动 Codex app-server 后在 3 秒内退出', async () =>}});+test('@package-smoke 关闭后隐藏保留本地服务,重新打开后可以正常退出', async () => {+ test.skip(process.platform !== 'darwin', 'Custom window controls are macOS only');+ const fixture = await launchPackagedDesktop('success');+ try {+ await waitForRuntimeReady(fixture.page, false);+ await fixture.page.evaluate(async () => {+ await window.opencreatorDesktop?.updateDesktopPreferences({ closeBehavior: 'hide' });+ });+ await fixture.page.getByRole('button', { name: '关闭窗口', exact: true }).click();+ expect(fixture.process.exitCode).toBeNull();+ expect((await runtimeRequest(fixture.page, 'GET', '/healthz')).status).toBe(200);++ await launchSecondInstance(fixture);+ await expect(fixture.page.getByRole('button', { name: '关闭窗口', exact: true })).toBeVisible();+ await requestPackagedAppQuit(fixture);+ expect(await waitForProcessExit(fixture.process, 3_000)).toBe(true);+ expect(fixture.process.exitCode).toBe(0);+ } finally {+ await closeFixture(fixture);+ }+});++test('@package-smoke 创作模块连接内嵌 Runtime 并使用默认项目', async ({}, testInfo) => {+ const fixture = await launchPackagedDesktop('success');+ try {+ await waitForWorkspace(fixture.page);+ expect(await fixture.page.evaluate(() => window.opencreatorDesktop?.readConnectionConfig()))+ .toEqual({ baseUrl: '/.opencreator/runtime' });+ await expect.poll(async () => {+ const response = await runtimeRequest<{ projects: Array<{ name: string }> }>(+ fixture.page, 'GET', '/projects?status=all'+ );+ return response.body.projects.filter(project => project.name === '默认项目').length;+ }).toBe(1);+ expect((await runtimeRequest(fixture.page, 'GET', '/creator/templates')).status).toBe(200);++ for (const [tool, title] of [+ ['video-translation', '视频翻译配音'],+ ['video-download', '视频下载'],+ ['image-generation', '图像生成'],+ ['video-generation', '视频生成'],+ ['smart-dubbing', '智能配音'],+ ['cover-generator', '封面生成'],+ ['stickman-video', '火柴人动画']+ ]) {+ await navigateToAppRoute(fixture.page, `#/workbench?tool=${tool}`);+ await expect(fixture.page.getByRole('heading', { name: title, exact: true })).toBeVisible();+ await expect(fixture.page.getByRole('heading', { name: '本地创作服务未连接' })).toHaveCount(0);+ await fixture.page.screenshot({ path: testInfo.outputPath(`${tool}.png`) });+ }+ } 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');+ try {+ await waitForRuntimeReady(fixture.page, false);+ await fixture.page.evaluate(async () => {+ await window.opencreatorDesktop?.updateDesktopPreferences({ closeBehavior: 'quit' });+ });+ await fixture.page.getByRole('button', { name: '关闭窗口', exact: true }).click();+ expect(await waitForProcessExit(fixture.process, 3_000)).toBe(true);+ expect(fixture.process.exitCode).toBe(0);+ } finally {+ await closeFixture(fixture);+ }+});+type DesktopFixture = PackagedApp & {root: string;stateDir: string;@@ -1330,9 +1401,11 @@ async function waitForRuntimeReady(page: Page, confirmSetup = true): Promise<voiif (!confirmSetup) return;const confirmed = await page.evaluate(() => window.localStorage.getItem('opencreator.agent-setup-confirmed.v1') !== null);if (confirmed) return;- 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()) return;+ const localMode = page.getByRole('button', { name: '本地模式', exact: true });+ if (await localMode.isVisible()) await localMode.click();const useLocalCodex = page.getByRole('button', { name: '使用本机 Codex,继续' });if (await useLocalCodex.isVisible()) await useLocalCodex.click();await setup.waitFor({ state: 'hidden', timeout: 3_000 }).catch(() => undefined);diff --git a/apps/desktop/src/main/main.ts b/apps/desktop/src/main/main.tsindex 99fb58b4..d03a5a06 100644--- a/apps/desktop/src/main/main.ts+++ b/apps/desktop/src/main/main.ts@@ -301,6 +301,9 @@ async function launchDesktop(): Promise<void> {telemetry.resume();notifications.start();},+ beforeQuitForInstall() {+ windowManager?.beginQuit();+ },setAllowQuit(value) {allowQuit = value;}@@ -311,10 +314,14 @@ async function launchDesktop(): Promise<void> {// The tray and Runtime intentionally remain active.});app.on('before-quit', event => {- if (allowQuit) return;+ if (allowQuit) {+ windowManager?.beginQuit();+ return;+ }event.preventDefault();if (shutdownStarted) return;shutdownStarted = true;+ logger.info('OpenCreator Desktop quitting');windowManager?.beginQuit();protocolController.suspendRuntime();notifications.stop();diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.tsindex 82e5a7dd..3c5271cd 100644--- a/apps/desktop/src/main/updater.ts+++ b/apps/desktop/src/main/updater.ts@@ -1,4 +1,4 @@-import { app, dialog } from 'electron';+import { app, autoUpdater as nativeAutoUpdater, dialog } from 'electron';import electronUpdater from 'electron-updater';import type { DesktopLogger } from './logger.js';@@ -34,14 +34,17 @@ export function startUpdater(input: {logger: DesktopLogger;isPackaged?: boolean;updater?: UpdaterLike;+ nativeUpdater?: Pick<Electron.AutoUpdater, 'on' | 'removeListener'>;showMessageBox?: typeof dialog.showMessageBox;prepareInstall?(): Promise<void>;+ beforeQuitForInstall?(): void;recoverAfterInstallFailure?(): Promise<void>;setAllowQuit?(allowed: boolean): void;platform?: NodeJS.Platform;arch?: string;}): DesktopUpdaterController {const updater = input.updater ?? electronUpdater.autoUpdater;+ const nativeUpdater = input.nativeUpdater ?? nativeAutoUpdater;const isPackaged = input.isPackaged ?? app.isPackaged;let state: DesktopUpdaterState = 'idle';let disposed = false;@@ -108,6 +111,12 @@ export function startUpdater(input: {const onNotAvailable = () => {if (state === 'checking') state = 'idle';};+ const onBeforeQuitForUpdate = () => {+ if (disposed || state !== 'installing') return;+ // On macOS this precedes window closing; before-quit arrives afterwards.+ input.logger.info('Desktop updater is quitting for installation');+ input.beforeQuitForInstall?.();+ };const onAvailable = (info: { version: string }) => {if (disposed || state === 'downloading' || state === 'installing') return;state = 'available';@@ -148,6 +157,9 @@ export function startUpdater(input: {});if (choice.response !== 0 || disposed) return;state = 'preparing_install';+ input.logger.info('Desktop update installation preparing', {+ version: info.version+ });await input.prepareInstall?.();input.setAllowQuit?.(true);state = 'installing';@@ -164,6 +176,7 @@ export function startUpdater(input: {updater.on('update-not-available', onNotAvailable);updater.on('update-available', onAvailable);updater.on('update-downloaded', onDownloaded);+ nativeUpdater.on('before-quit-for-update', onBeforeQuitForUpdate);const checkNow = async () => {if (@@ -195,6 +208,7 @@ export function startUpdater(input: {updater.removeListener('update-not-available', onNotAvailable);updater.removeListener('update-available', onAvailable);updater.removeListener('update-downloaded', onDownloaded);+ nativeUpdater.removeListener('before-quit-for-update', onBeforeQuitForUpdate);},checkNow,getState: () => statediff --git a/apps/desktop/test/updater.test.ts b/apps/desktop/test/updater.test.tsindex 20607f2a..f4b88e1b 100644--- a/apps/desktop/test/updater.test.ts+++ b/apps/desktop/test/updater.test.ts@@ -1,9 +1,22 @@import { EventEmitter } from 'node:events';-import { describe, expect, it, vi } from 'vitest';+import { autoUpdater as nativeUpdater } from 'electron';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { startUpdater } from '../src/main/updater.js';import type { DesktopLogger } from '../src/main/logger.js';+vi.mock('electron', async () => {+ const { EventEmitter } = await import('node:events');+ return {+ app: { isPackaged: false },+ dialog: {},+ autoUpdater: new EventEmitter()+ };+});+describe('Desktop updater', () => {+ beforeEach(() => {+ nativeUpdater.removeAllListeners();+ });it('uses a separate update channel for Intel macOS releases', () => {const updater = new FakeUpdater();const controller = startUpdater({@@ -96,6 +109,57 @@ describe('Desktop updater', () => {controller.dispose();});+ it('allows native update window closing before the ordinary quit event', async () => {+ const steps: string[] = [];+ const updater = new FakeUpdater();+ updater.quitAndInstall = vi.fn(() => {+ nativeUpdater.emit('before-quit-for-update');+ steps.push('native-window-close');+ });+ const controller = startUpdater({+ logger: fakeLogger(),+ isPackaged: true,+ updater,+ showMessageBox: vi.fn(async () => ({ response: 0, checkboxChecked: false })),+ async prepareInstall() {+ steps.push('stop-runtime');+ },+ beforeQuitForInstall() {+ steps.push('allow-window-close');+ }+ });++ updater.emit('update-downloaded', { version: '1.2.3' });+ await vi.waitFor(() => expect(updater.quitAndInstall).toHaveBeenCalledOnce());++ expect(steps).toEqual(['stop-runtime', 'allow-window-close', 'native-window-close']);+ controller.dispose();+ });++ it('keeps the window available until the native installer actually quits', async () => {+ const beforeQuitForInstall = vi.fn();+ const updater = new FakeUpdater();+ const controller = startUpdater({+ logger: fakeLogger(),+ isPackaged: true,+ updater,+ beforeQuitForInstall,+ showMessageBox: vi.fn(async () => ({ response: 0, checkboxChecked: false }))+ });++ nativeUpdater.emit('before-quit-for-update');+ expect(beforeQuitForInstall).not.toHaveBeenCalled();+ updater.emit('update-downloaded', { version: '1.2.3' });+ await vi.waitFor(() => expect(controller.getState()).toBe('installing'));+ expect(beforeQuitForInstall).not.toHaveBeenCalled();++ updater.emit('error', new Error('native download failed'));+ nativeUpdater.emit('before-quit-for-update');+ expect(controller.getState()).toBe('error');+ expect(beforeQuitForInstall).not.toHaveBeenCalled();+ controller.dispose();+ });+it('keeps the current runtime running when the user postpones installation', async () => {const prepareInstall = vi.fn(async () => undefined);const recover = vi.fn(async () => undefined);@@ -151,6 +215,7 @@ describe('Desktop updater', () => {controller.dispose();expect(updater.eventNames()).toEqual([]);+ expect(nativeUpdater.eventNames()).toEqual([]);});});diff --git a/apps/web/e2e/fixtures/runtime.ts b/apps/web/e2e/fixtures/runtime.tsindex b1b4d97b..7ece5273 100644--- a/apps/web/e2e/fixtures/runtime.ts+++ b/apps/web/e2e/fixtures/runtime.ts@@ -335,6 +335,7 @@ export const test = base.extend<TestFixtures>({if (await page.evaluate(() => localStorage.getItem('opencreator.agent-setup-confirmed.v1') === null)) {const setup = page.getByRole('region', { name: '开始使用 Agent' });await expect(setup).toBeVisible();+ await setup.getByRole('button', { name: '本地模式', exact: true }).click();await setup.getByRole('button', { name: '使用本机 Codex,继续' }).click();await expect(setup).not.toBeVisible();}diff --git a/apps/web/e2e/gateway-account.spec.ts b/apps/web/e2e/gateway-account.spec.tsnew file mode 100644index 00000000..6a3c45fe--- /dev/null+++ b/apps/web/e2e/gateway-account.spec.ts@@ -0,0 +1,198 @@+import { test, expect } from './fixtures/runtime.js';+import type { GatewayAccountState } from '@opencreator/protocol';++test('独立订阅页面支持游客选套餐、登录后继续购买并返回个人中心', async ({ page, runtime }, testInfo) => {+ const guest: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };+ let state = guest;+ let paid = false;+ let portalRequests = 0;+ const checkoutRequests: Array<{ planId: string }> = [];+ const plans = [+ { id: 'personal', name: '个人版', amountUnits: '3900', currency: 'cny', creditUnits: '1000000000' },+ { id: 'creator', name: '创作版', amountUnits: '9900', currency: 'cny', creditUnits: '3000000000' }+ ];+ await page.route('**/gateway/**', async route => {+ const path = new URL(route.request().url()).pathname;+ let value: unknown;+ if (path.endsWith('/gateway/account')) value = state;+ else if (path.endsWith('/gateway/plans')) value = { plans, billingAvailable: true };+ else if (path.endsWith('/gateway/auth/start')) {+ state = { ...guest, authState: 'signed_in', account: { id: 'a', email: '[email protected]', verified: true } };+ value = { attemptId: 'mock', authorizationUrl: `${runtime.origin}/#/account`, expiresAt: '2026-10-06T00:00:00Z' };+ } else if (path.endsWith('/gateway/auth/logout')) { state = guest; value = state; }+ else if (path.endsWith('/gateway/billing/summary')) value = {+ balance: { availableUnits: paid ? '2860000000' : '0', reservedUnits: '0', periodEnd: null, asOf: '2026-10-05T01:00:00Z' },+ subscription: paid ? { id: 'sub-1', status: 'active', periodStart: '2026-10-05T00:00:00Z', periodEnd: '2026-11-05T00:00:00Z', cancelAtPeriodEnd: false, nextPlanId: null, plan: plans[1] } : null,+ billingAvailable: true+ };+ else if (path.endsWith('/gateway/billing/checkout')) {+ checkoutRequests.push(route.request().postDataJSON());+ value = { url: `${runtime.origin}/#/account` };+ } else if (path.endsWith('/gateway/billing/portal')) { portalRequests++; value = { url: `${runtime.origin}/#/account` }; }+ else { await route.continue(); return; }+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify(value) });+ });+ await runtime.openApp(page);+ const navigation = page.getByRole('navigation', { name: 'OpenCreator', exact: true });+ const openNavigation = page.getByRole('button', { name: '打开导航', exact: true });+ if (await openNavigation.isVisible()) await openNavigation.click();+ await navigation.getByRole('button', { name: '个人中心', exact: true }).click();+ if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator 导航', { exact: true })).toHaveCSS('visibility', 'hidden');+ const center = page.getByRole('main', { name: '个人中心', exact: true });+ await expect(center.getByRole('button', { name: '登录 / 注册' })).toBeVisible();+ await expect(center.getByRole('heading', { name: '订阅套餐', exact: true })).toHaveCount(0);+ await page.screenshot({ path: testInfo.outputPath('personal-center.png'), fullPage: true });+ await center.getByRole('button', { name: '查看订阅套餐', exact: true }).click();+ await expect(page).toHaveURL(/#\/subscription$/);+ const subscriptionPage = page.getByRole('main', { name: '订阅', exact: true });+ await expect(subscriptionPage).toBeVisible();+ await expect(subscriptionPage.getByRole('button', { name: '登录并订阅' })).toHaveCount(2);+ await page.goBack();+ await expect(center).toBeVisible();+ await page.goForward();+ await expect(subscriptionPage).toBeVisible();+ await expect(subscriptionPage.getByRole('button', { name: '登录并订阅' })).toHaveCount(2);+ await page.reload();+ await expect(subscriptionPage).toBeVisible();+ const subscription = subscriptionPage.getByRole('region', { name: '订阅与积分' });+ await expect(subscription.getByRole('heading', { name: '可用积分', exact: true })).toHaveCount(0);+ await expect(subscriptionPage.getByText('登录后可查看')).toHaveCount(0);+ await expect(subscriptionPage.getByRole('button', { name: '刷新订阅' })).toHaveCount(0);+ await expect(subscription.getByText(/39.00/)).toBeVisible();+ await expect(subscription.getByRole('button', { name: '登录并订阅', exact: true })).toHaveCount(2);+ await page.screenshot({ path: testInfo.outputPath('subscription-public-plans.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ const creatorPlan = subscription.getByRole('article').filter({ has: page.getByRole('heading', { name: '创作版', exact: true }) });+ await creatorPlan.getByRole('button', { name: '登录并订阅' }).click();+ await expect(subscriptionPage.getByRole('heading', { name: '[email protected]', exact: true })).toBeVisible();+ await expect(subscription.getByText('未订阅', { exact: true })).toBeVisible();+ await expect.poll(() => checkoutRequests.length).toBe(1);+ expect(checkoutRequests[0].planId).toBe('creator');+ await expect(subscription.getByText('等待支付确认', { exact: true })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath('subscription-before-payment.png'), fullPage: true });+ paid = true;+ await page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await expect(subscription.getByText('生效中', { exact: true })).toBeVisible();+ await expect(subscription.locator('.gateway-subscription__credit-value')).toHaveText('2860 积分');+ await expect(subscription.locator('.gateway-subscription__current').getByText('创作版', { exact: true })).toBeVisible();+ await expect(subscription.locator('.gateway-subscription__current').getByText(/99.00.*3000/)).toBeVisible();+ await expect(subscription.getByRole('heading', { name: '订阅套餐', exact: true })).toBeVisible();+ await expect(creatorPlan.getByRole('button', { name: '当前套餐' })).toBeDisabled();+ await expect(subscription.locator('.gateway-subscription__current').getByRole('button', { name: '管理订阅' })).toBeEnabled();+ await expect(subscription.getByRole('button', { name: '订阅', exact: true })).toHaveCount(0);+ await page.screenshot({ path: testInfo.outputPath('subscription-subscribed.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ const otherPlan = subscription.getByRole('article').filter({ has: page.getByRole('heading', { name: '个人版', exact: true }) });+ await otherPlan.getByRole('button', { name: '管理订阅' }).click();+ await expect.poll(() => portalRequests).toBe(1);+ expect(checkoutRequests).toHaveLength(1);+ await page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await expect(subscription.getByRole('link', { name: '打开订阅管理' })).toBeVisible();+ await subscriptionPage.getByRole('button', { name: '返回', exact: true }).click();+ await expect(page).toHaveURL(/#\/account$/);+ await expect(center.getByText('生效中', { exact: true })).toBeVisible();+ await expect(center.getByRole('heading', { name: '订阅套餐', exact: true })).toHaveCount(0);+ await center.getByRole('button', { name: '查看订阅套餐', exact: true }).click();+ await subscriptionPage.getByRole('button', { name: '退出登录' }).click();+ await expect(subscriptionPage.getByRole('button', { name: '登录 / 注册' })).toBeVisible();+ await expect(subscription.getByRole('heading', { name: '可用积分', exact: true })).toHaveCount(0);+ await expect(subscription.getByRole('button', { name: '登录并订阅' })).toHaveCount(2);+ await subscriptionPage.getByRole('button', { name: '返回', exact: true }).click();+ await center.getByRole('button', { name: '返回', exact: true }).click();+ await expect(page).toHaveURL(/#\/new$/);+ await page.evaluate(() => localStorage.removeItem('opencreator.agent-setup-confirmed.v1'));+ await page.goto(`${runtime.origin}/#/subscription`);+ await expect(subscriptionPage).toBeVisible();+ await expect(subscription.getByRole('button', { name: '登录并订阅' })).toHaveCount(2);+ await expect(page.getByRole('region', { name: '开始使用 Agent' })).toHaveCount(0);+});++test('浏览器完成真实网关设备授权,缺少模型配置时保留登录并准确显示未就绪', async ({ page, runtime }, testInfo) => {+ test.skip(!process.env.GATEWAY_BROWSER_TEST_ORIGIN || !process.env.GATEWAY_DEMO_PASSWORD, 'Requires isolated local Go gateway');+ await page.addInitScript(() => {+ localStorage.setItem('opencreator.preferences.language', 'zh-CN');+ localStorage.setItem('opencreator.preferences.dynamicBackground', 'false');+ });+ await page.goto(`${runtime.origin}/#/new`);+ const setup = page.getByRole('region', { name: '开始使用 Agent' });+ await expect(setup.getByRole('button', { name: '本地模式', exact: true })).toBeVisible();+ await expect(setup.getByRole('button', { name: '登录模式', exact: true })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath('gateway-startup.png'), fullPage: true });+ await setup.getByRole('button', { name: '登录模式', exact: true }).click();+ await expect(setup.getByLabel('API Key')).toHaveCount(0);+ await expect(setup.getByLabel('Base URL')).toHaveCount(0);+ const account = page.getByRole('region', { name: 'OpenCreator 账户' });+ await account.getByRole('button', { name: '登录 OpenCreator' }).click();+ const link = account.getByRole('link', { name: '打开登录页面' });+ await expect(link).toBeVisible();+ const device = await page.context().newPage();+ await device.goto((await link.getAttribute('href'))!);+ await device.getByRole('link', { name: /Sign in/ }).click();+ await device.getByLabel('Email', { exact: true }).fill('[email protected]');+ await device.getByLabel('Password', { exact: true }).fill(process.env.GATEWAY_DEMO_PASSWORD!);+ await device.getByRole('button', { name: 'Sign in', exact: true }).last().click();+ await device.getByRole('button', { name: 'Authorize', exact: true }).click();+ await expect(device.getByText('Device authorized.', { exact: true })).toBeVisible();+ await page.bringToFront();+ await expect.poll(async () => (await runtime.api<{ authState: string }>('GET', '/gateway/account')).authState).toBe('signed_in');+ await expect(setup).not.toBeVisible();+ const navigation = page.getByRole('navigation', { name: 'OpenCreator', exact: true });+ const openNavigation = page.getByRole('button', { name: '打开导航', exact: true });+ if (await openNavigation.isVisible()) await openNavigation.click();+ await navigation.getByRole('button', { name: '个人中心', exact: true }).click();+ if (await openNavigation.isVisible()) await expect(page.getByLabel('OpenCreator 导航', { exact: true })).toHaveCSS('visibility', 'hidden');+ await expect(page).toHaveURL(/#\/account$/);+ await expect(navigation.getByRole('button', { name: '个人中心', exact: true })).toHaveAttribute('aria-current', 'page');+ await expect(navigation.getByRole('button', { name: '首页', exact: true })).not.toHaveAttribute('aria-current', 'page');+ const center = page.getByRole('main', { name: '个人中心', exact: true });+ await expect(center.getByRole('heading', { name: '[email protected]', exact: true })).toBeVisible({ timeout: 20_000 });+ await expect(account.getByText('已登录', { exact: true })).toBeVisible();+ await expect(account.getByRole('group', { name: '使用模式' })).toHaveCount(0);+ await account.getByRole('button', { name: '重新连接', exact: true }).click();+ await expect(account.getByText('已登录', { exact: true })).toBeVisible();+ expect(await page.evaluate(() => JSON.stringify({ html: document.body.innerText, storage: { ...localStorage }, session: { ...sessionStorage } }))).not.toMatch(/ocg_[A-Za-z0-9_-]{32}|accessToken|refreshToken|modelKey/);+ await page.screenshot({ path: testInfo.outputPath('gateway-account.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ await center.getByRole('button', { name: '查看订阅套餐', exact: true }).click();+ await expect(page).toHaveURL(/#\/subscription$/);+ const subscriptionPage = page.getByRole('main', { name: '订阅', exact: true });+ const subscription = subscriptionPage.getByRole('region', { name: '订阅与积分' });+ await expect(subscription.getByText('暂未开放订阅', { exact: true })).toBeVisible();+ await expect(subscription.getByText('可用积分', { exact: true })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath('gateway-subscription.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ await account.getByRole('button', { name: '退出登录', exact: true }).click();+ await expect(account.getByRole('button', { name: '登录 / 注册' })).toBeVisible();+ await expect(subscription.getByRole('heading', { name: '可用积分', exact: true })).toHaveCount(0);+ await expect(subscription.getByText('登录后可查看', { exact: true })).toHaveCount(0);+ await expect(navigation.getByText('[email protected]', { exact: true })).toHaveCount(0);+ await expect(subscriptionPage.getByRole('button', { name: '登录 / 注册' })).toHaveCount(1);+ await page.screenshot({ path: testInfo.outputPath('personal-center-guest.png'), fullPage: true });+ await subscriptionPage.getByRole('button', { name: '返回', exact: true }).click();+ await expect(page).toHaveURL(/#\/account$/);+ await center.getByRole('button', { name: '返回', exact: true }).click();+ await expect(page).toHaveURL(/#\/new$/);+ if (await openNavigation.isVisible()) await openNavigation.click();+ await navigation.getByRole('button', { name: '设置', exact: true }).click();+ const settings = page.getByRole('navigation', { name: '设置分类' });+ await expect(settings.getByRole('button', { name: '账户', exact: true })).toHaveCount(0);+ await expect(settings.getByRole('button', { name: '订阅与积分', exact: true })).toHaveCount(0);+ await device.close();+});++test('网关账户和管理员页面展示真实零余额并限制未配置支付', async ({ page }, testInfo) => {+ test.skip(!process.env.GATEWAY_BROWSER_TEST_ORIGIN || !process.env.GATEWAY_DEMO_PASSWORD, 'Requires isolated local Go gateway');+ await page.goto(`${process.env.GATEWAY_BROWSER_TEST_ORIGIN}/auth`);+ await page.getByLabel('Email', { exact:true }).fill('[email protected]');+ await page.getByLabel('Password', { exact:true }).fill(process.env.GATEWAY_DEMO_PASSWORD!);+ await page.getByRole('button', { name:'Sign in',exact:true }).last().click();+ await expect(page.getByRole('heading',{name:'Account',exact:true})).toBeVisible();+ await expect(page.locator('#available')).toHaveText('0');+ await expect(page.locator('#subscribe button')).toBeDisabled();+ await page.screenshot({path:testInfo.outputPath('go-account.png'),fullPage:true});+ expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);+ await page.goto(`${process.env.GATEWAY_BROWSER_TEST_ORIGIN}/admin`);+ await expect(page.getByRole('heading',{name:'Administration',exact:true})).toBeVisible();+ await page.screenshot({path:testInfo.outputPath('go-admin.png'),fullPage:true});+ expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);+});diff --git a/apps/web/e2e/gateway-web-desktop-parity.spec.ts b/apps/web/e2e/gateway-web-desktop-parity.spec.tsnew file mode 100644index 00000000..c3d4d968--- /dev/null+++ b/apps/web/e2e/gateway-web-desktop-parity.spec.ts@@ -0,0 +1,27 @@+import { test, expect } from './fixtures/runtime.js';++test('账户入口在同尺寸 Browser/Desktop Bridge 下读取同一个 Daemon 并显示一致', 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(); }+ }+ expect(states[1]).toEqual(states[0]);+});diff --git a/apps/web/e2e/official-services.spec.ts b/apps/web/e2e/official-services.spec.tsnew file mode 100644index 00000000..81fbb1d8--- /dev/null+++ b/apps/web/e2e/official-services.spec.ts@@ -0,0 +1,75 @@+import { test, expect } from './fixtures/runtime.js';+import { createDefaultCreatorServicesConfig, type GatewayAccountState } from '@opencreator/protocol';++test('登录只显示官方模型,退出登录后恢复用户配置', async ({ page, runtime }, testInfo) => {+ const custom = createDefaultCreatorServicesConfig();+ custom.llm = { source: 'custom', baseUrl: 'https://personal.example.test/v1', apiKey: 'personal-test-key', model: 'personal-model', jsonMode: true };+ custom.transcription.provider = 'openai';+ await runtime.api('PATCH', '/creator-services/config', custom);+ let state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'official-test', email: '[email protected]', verified: true }, bindingVersion: 'official-test:1', selectedModels: { text: 'vendor/text-first' }, models: [+ { id: 'vendor/text-first', modality: 'text', capabilities: ['responses'] },+ { id: 'vendor/text-second', modality: 'text', capabilities: ['responses'] },+ ...Array.from({ length: 12 }, (_, index) => ({ id: `vendor/text-extra-${index}`, modality: 'text' as const, capabilities: ['responses'] })),+ { id: 'vendor/image', modality: 'image', capabilities: ['edit'] },+ { id: 'vendor/video', modality: 'video', capabilities: [] },+ { id: 'vendor/speech', modality: 'speech', capabilities: [] },+ { id: 'vendor/transcription', modality: 'transcription', capabilities: [] }+ ], activationError: null };+ await page.route('**/gateway/**', async route => {+ const path = new URL(route.request().url()).pathname;+ if (path.endsWith('/gateway/billing/summary')) {+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ balance: { availableUnits: '1000000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-08T00:00:00Z' }, subscription: null, billingAvailable: false }) });+ return;+ } else if (path.endsWith('/gateway/model')) {+ const body = route.request().postDataJSON(); state = { ...state, selectedModels: { ...state.selectedModels, [body.modality]: body.model } };+ } else if (path.endsWith('/gateway/auth/logout')) {+ state = { ...state, source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [] };+ } else if (path.endsWith('/gateway/auth/start')) {+ state = { ...state, source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'official-test', email: '[email protected]', verified: true }, bindingVersion: 'official-test:1', models: [{ id: 'vendor/text-first', modality: 'text', capabilities: ['responses'] }, { id: 'vendor/text-second', modality: 'text', capabilities: ['responses'] }] };+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ attemptId: 'mock', authorizationUrl: `${runtime.origin}/#/account`, expiresAt: '2099-01-01T00:00:00Z' }) });+ return;+ } else if (!path.endsWith('/gateway/account')) { await route.continue(); return; }+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify(state) });+ });+ await page.addInitScript(() => localStorage.setItem('opencreator.agent-setup-confirmed.v1', '1'));+ await runtime.openApp(page);+ await page.goto(`${runtime.origin}/#/settings?tab=ai-services`);+ const model = page.getByRole('combobox', { name: '文本模型' });+ await expect(model).toHaveValue('text-first');+ await expect(page.getByLabel('Base URL', { exact: true })).toHaveCount(0);+ await expect(page.getByLabel('API Key', { exact: true })).toHaveCount(0);+ await expect(page.getByText(/OpenRouter/i)).toHaveCount(0);+ await model.click();+ await model.fill('text-second');+ await expect(page.getByRole('listbox', { name: '文本模型' }).getByRole('option')).toHaveCount(1);+ await page.getByRole('option', { name: 'text-second', exact: true }).click();+ await expect(model).toHaveValue('text-second');+ await page.screenshot({ path: testInfo.outputPath('official-models.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ await expect(page.getByRole('button', { name: '自定义配置', exact: true })).toHaveCount(0);+ await page.getByRole('button', { name: '常规', exact: true }).click();+ const proxy = page.getByRole('textbox', { name: '网络代理', exact: true });+ await expect(proxy).toBeEnabled();+ await proxy.fill('http://127.0.0.1:8888');+ await page.getByRole('button', { name: '保存网络代理', exact: true }).click();+ await expect(page.getByRole('button', { name: '保存网络代理', exact: true })).toBeDisabled();+ expect(await runtime.api('GET', '/creator-services/network')).toEqual({ proxy: 'http://127.0.0.1:8888' });+ await page.screenshot({ path: testInfo.outputPath('general-network.png'), fullPage: true });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ await page.goto(`${runtime.origin}/#/account`);+ await page.getByRole('button', { name: '退出登录', exact: true }).click();+ await page.goto(`${runtime.origin}/#/settings?tab=ai-services`);+ await expect(page.getByLabel('Base URL', { exact: true })).toHaveValue('https://personal.example.test/v1');+ await expect(page.getByLabel('API Key', { exact: true })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath('custom-services.png'), fullPage: true });+ await page.goto(`${runtime.origin}/#/account`);+ await page.getByRole('button', { name: '登录 / 注册', exact: true }).click();+ await expect(page.getByRole('button', { name: '退出登录', exact: true })).toBeVisible();+ await page.goto(`${runtime.origin}/#/settings?tab=ai-services`);+ await expect(model).toHaveValue('text-second');+ await expect(page.getByLabel('Base URL', { exact: true })).toHaveCount(0);+ const saved = await runtime.api<{ config: typeof custom; configuredCredentials: string[] }>('GET', '/creator-services/config');+ expect(saved.config.llm.baseUrl).toBe(custom.llm.baseUrl);+ expect(saved.configuredCredentials).toContain('llm.apiKey');+ expect(saved.config.proxy).toBe('http://127.0.0.1:8888');+});diff --git a/apps/web/package.json b/apps/web/package.jsonindex f564585a..806d1efb 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -29,6 +29,7 @@"@codemirror/search": "^6.7.1","@codemirror/state": "^6.7.1","@codemirror/view": "^6.43.6",+ "fuse.js": "^7.1.0","lucide-react": "^0.468.0","react": "^18.3.1","react-dom": "^18.3.1",diff --git a/apps/web/src/app/App.test.tsx b/apps/web/src/app/App.test.tsxindex 10285199..17fb378b 100644--- a/apps/web/src/app/App.test.tsx+++ b/apps/web/src/app/App.test.tsx@@ -14,6 +14,7 @@ import type {CreatorJson,CreatorJob,CreatorPresetSummary,+ GatewayAccountState,CreateScheduleRequest,ProjectResponse,RunDiagnosticsResponse,@@ -147,23 +148,25 @@ describe('App', () => {};render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);- expect(await screen.findByRole('heading', { name: '开始使用 Agent' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'OpenCreator' })).toBeInTheDocument();expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '暂时跳过' }));+ await user.click(screen.getByRole('button', { name: '稍后配置,进入本地模式' }));expect(await screen.findByText('Agent 尚未配置,暂时无法发送任务。')).toBeInTheDocument();await user.click(screen.getByRole('button', { name: '配置 Agent' }));+ await user.click(screen.getByRole('button', { name: '本地模式' }));expect(await screen.findByRole('combobox', { name: '供应商' })).toBeInTheDocument();expect(screen.queryByRole('button', { name: '使用 ChatGPT 登录' })).not.toBeInTheDocument();- await user.click(screen.getByRole('button', { name: '暂时跳过' }));+ await user.click(screen.getByRole('button', { name: '稍后配置,进入本地模式' }));await user.click(screen.getByRole('button', { name: '设置' }));await user.click(await screen.findByRole('button', { name: /AI 服务/ }));await user.click(screen.getByRole('button', { name: '配置 Agent' }));+ await user.click(screen.getByRole('button', { name: '本地模式' }));await user.selectOptions(await screen.findByRole('combobox', { name: '供应商' }), 'openai');expect(screen.getByLabelText('模型名称')).toHaveValue('gpt-5.6-sol');await user.type(screen.getByLabelText('API Key'), 'secret');await user.click(screen.getByRole('button', { name: '保存并开始使用' }));await waitFor(() => {- expect(screen.queryByRole('heading', { name: '开始使用 Agent' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();expect(window.location.hash).toBe('#/new');});expect(screen.queryByText('Agent 尚未配置,暂时无法发送任务。')).not.toBeInTheDocument();@@ -174,10 +177,56 @@ describe('App', () => {expect(screen.queryByText('正在检查 Agent 配置…')).not.toBeInTheDocument();expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument();});- expect(screen.queryByRole('heading', { name: '开始使用 Agent' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();});+ it.each(['ready', 'blocked'] as const)('enters the application after gateway sign-in with %s activation and never asks for provider credentials', async activationState => {+ window.localStorage.clear();+ writeCachedModelCatalog({ models: [{ ...createCodexModelListResponse().models[0]!, id: 'personal-model', model: 'personal-model', displayName: 'Personal cached model', isDefault: true }] });+ const user = userEvent.setup();+ const hostBridge = createHostBridge();+ hostBridge.readConnectionConfig = async () => ({ baseUrl: 'http://127.0.0.1:60764', token: 'runtime-token' });+ let gateway: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };+ const runtimeFetch = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const projectResponse = handleDefaultProjectApiRequest(url, init);+ if (projectResponse !== undefined) return projectResponse;+ if (url.endsWith('/healthz')) return jsonResponse({ ok: true });+ if (url.endsWith('/codex/status')) return jsonResponse(createCodexStatusResponse());+ if (url.endsWith('/codex/readiness')) return jsonResponse({ state: 'degraded', account: { status: 'not_authenticated', accountStatus: 'signed_out' }, binary: { status: 'ready' }, protocol: { status: 'ready' }, models: { status: 'ready' }, diagnostics: [] });+ if (url.endsWith('/codex/provider')) return jsonResponse({ baseUrl: '', model: '', apiKeyConfigured: false, authentication: 'none' });+ if (url.endsWith('/gateway/account')) return jsonResponse(gateway);+ if (url.endsWith('/gateway/auth/start') && init?.method === 'POST') {+ gateway = { ...gateway, source: 'gateway', authState: 'signed_in', activationState, bindingVersion: activationState === 'ready' ? 'a:1' : null, account: { id: 'a', email: '[email protected]', verified: true }, models: [{ id: 'gateway-text', modality: 'text', capabilities: ['responses'] }, { id: 'chat-only', modality: 'text', capabilities: ['chat'] }] };+ return jsonResponse({ attemptId: 'a', authorizationUrl: 'https://gateway.example/device?attempt=a', expiresAt: '2026-10-05T01:00:00Z' });+ }+ if (url.endsWith('/codex/models')) return jsonResponse({ models: gateway.models.map(model => ({ id: model.id, model: model.id, displayName: model.id, description: '', supportedReasoningEfforts: [], defaultReasoningEffort: null, inputModalities: ['text'], isDefault: true })) });+ if (url.includes('/threads?')) return jsonResponse({ threads: [] });+ throw new Error(`Unexpected request ${url}`);+ };+ render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch}/>);+ await user.click(await screen.findByRole('button', { name: '登录模式' }));+ await waitFor(() => expect(screen.getByRole('button', { name: '登录 OpenCreator' })).toBeEnabled());+ expect(screen.queryByLabelText('Base URL')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: '登录 OpenCreator' }));+ await waitFor(() => expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument());+ expect(screen.queryByRole('region', { name: '开始使用 Agent' })).not.toBeInTheDocument();+ expect(screen.queryByText('Agent 尚未配置,暂时无法发送任务。')).not.toBeInTheDocument();+ if (activationState === 'ready') {+ await waitFor(() => expect(screen.getByRole('textbox', { name: '输入任务' })).toBeEnabled());+ await user.click(await screen.findByRole('button', { name: '选择模型 gateway-text' }));+ expect(screen.queryByText('Personal cached model')).not.toBeInTheDocument();+ expect(screen.queryByText('chat-only')).not.toBeInTheDocument();+ }+ if (activationState === 'blocked') {+ expect(screen.getByText('已登录,模型服务暂不可用。')).toBeInTheDocument();+ await user.click(within(screen.getByText('已登录,模型服务暂不可用。').parentElement!).getByRole('button', { name: '个人中心' }));+ await waitFor(() => expect(window.location.hash).toBe('#/account'));+ }+ });+it('asks to confirm an existing ChatGPT login on first run, then remembers that choice while it remains valid', async () => {window.localStorage.clear();const user = userEvent.setup();@@ -203,20 +252,22 @@ describe('App', () => {};render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);+ await user.click(await screen.findByRole('button', { name: '本地模式' }));expect(await screen.findByText('已找到本机 Codex')).toBeInTheDocument();expect(screen.queryByLabelText('OpenCreator 导航')).not.toBeInTheDocument();await user.click(screen.getByRole('button', { name: '使用本机 Codex,继续' }));- await waitFor(() => expect(screen.queryByRole('heading', { name: '开始使用 Agent' })).not.toBeInTheDocument());+ await waitFor(() => expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument());cleanup();render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);await waitFor(() => expect(screen.getByLabelText('OpenCreator 导航')).toBeInTheDocument());- expect(screen.queryByRole('heading', { name: '开始使用 Agent' })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'OpenCreator' })).not.toBeInTheDocument();cleanup();signedIn = false;render(<App hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);- expect(await screen.findByRole('heading', { name: '开始使用 Agent' })).toBeInTheDocument();+ expect(await screen.findByRole('heading', { name: 'OpenCreator' })).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: '本地模式' }));expect(screen.getByRole('combobox', { name: '供应商' })).toBeInTheDocument();});diff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsxindex 7338824d..2c2a0dd2 100644--- a/apps/web/src/app/AppController.tsx+++ b/apps/web/src/app/AppController.tsx@@ -133,6 +133,8 @@ import { createAttachmentService } from '../services/attachment-service.js';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 type { GatewayAccountState } from '@opencreator/protocol';import { createCreatorService } from '../services/creator-service.js';import { createCleanupService } from '../services/cleanup-service.js';import { createDiagnosticsService } from '../services/diagnostics-service.js';@@ -267,6 +269,7 @@ const ScheduleThreadHeader = lazy(async () => {const SchedulesPage = lazy(() => import('../features/schedules/SchedulesPage.js'));const SearchPage = lazy(() => import('../features/search/SearchPage.js'));const SettingsPage = lazy(() => import('../features/settings/SettingsPage.js'));+const PersonalCenterPage = lazy(() => import('../features/account/PersonalCenterPage.js'));const TaskCenterPage = lazy(() => import('../features/tasks/TaskCenterPage.js'));const DetailPanel = lazy(async () => {const module = await import('../features/details/DetailPanel.js');@@ -368,6 +371,7 @@ export function AppController(props: AppControllerProps) {const [historyLoadedThreadId, setHistoryLoadedThreadId] = useState<string>();const [threadConfigUpdateError, setThreadConfigUpdateError] = useState<string>();const [agentSetup, setAgentSetup] = useState<'checking' | 'ready' | 'needed' | 'skipped'>('checking');+ const [agentSetupRequested, setAgentSetupRequested] = useState(false);const [agentSetupSnapshot, setAgentSetupSnapshot] = useState<AgentSetupSnapshot>();const [runDiagnosticsById, setRunDiagnosticsById] = useState<Record<string, RunDiagnosticsResponse | undefined>>({});const [runAttachmentsById, setRunAttachmentsById] = useState<Record<string, AttachmentResponse[] | undefined>>({});@@ -512,6 +516,9 @@ export function AppController(props: AppControllerProps) {const settingsReturnRouteRef = useRef<AppRoute>(props.route.view === 'settings' ? { view: 'home' } : props.route);+ const accountReturnRouteRef = useRef<AppRoute>(+ props.route.view === 'account' || props.route.view === 'subscription' ? { view: 'home' } : props.route+ );const skipNextHistoryLoadForThreadRef = useRef<string>();const skillMarketMutationInFlightRef = useRef(false);const skillMarketUseInFlightRef = useRef(false);@@ -610,6 +617,31 @@ export function AppController(props: AppControllerProps) {() => runtimeClient === null ? null : createCreatorServicesService(runtimeClient),[runtimeClient]);+ const gatewayAccountService = useMemo(() => runtimeClient === null ? null : createGatewayAccountService(runtimeClient), [runtimeClient]);+ const [gatewayAccountState, setGatewayAccountState] = useState<GatewayAccountState>();+ const officialTextModels = useMemo(() => {+ if (!gatewayAccountState || (gatewayAccountState.source === 'manual' && gatewayAccountState.authState === 'signed_out')) return undefined;+ return { models: gatewayAccountState.models.filter(model => model.modality === 'text' && model.capabilities.includes('responses')).map((model, index) => ({+ id: model.id, model: model.id, displayName: model.id.split('/').pop()!, description: '',+ supportedReasoningEfforts: [], defaultReasoningEffort: null, inputModalities: ['text' as const],+ isDefault: gatewayAccountState.selectedModels?.text ? gatewayAccountState.selectedModels.text === model.id : index === 0+ })) } satisfies CodexModelListResponse;+ }, [gatewayAccountState]);+ const previousGatewaySource = useRef<'manual' | 'gateway'>('manual');+ const onGatewayStateChange = useCallback((next: GatewayAccountState) => {+ setGatewayAccountState(previous => JSON.stringify(previous) === JSON.stringify(next) ? previous : next);+ if (next.source === 'gateway') setAgentSetup(next.authState === 'signed_in' && next.activationState === 'ready' ? 'ready' : 'skipped');+ else if (previousGatewaySource.current === 'gateway') setAgentSetup('checking');+ previousGatewaySource.current = next.source;+ }, []);+ useEffect(() => {+ if (connectionState.status !== 'connected' || !gatewayAccountService) return;+ let canceled = false;+ const refresh = () => { void gatewayAccountService.getState().then(next => { if (!canceled) onGatewayStateChange(next); }).catch(() => undefined); };+ refresh();+ const timer = setInterval(() => { if (previousGatewaySource.current === 'gateway') refresh(); }, 3000);+ return () => { canceled = true; clearInterval(timer); };+ }, [gatewayAccountService, connectionState.status, onGatewayStateChange]);const openCreatorSettingsService = useMemo(() => runtimeClient === null ? null : createOpenCreatorSettingsService(runtimeClient),[runtimeClient]@@ -1191,6 +1223,14 @@ export function AppController(props: AppControllerProps) {useEffect(() => {let canceled = false;+ if (officialTextModels) {+ setCodexModels(officialTextModels);+ setCodexModelsLoading(false);+ setCodexModelsLoadError(undefined);+ setCodexModelsNotice(undefined);+ return;+ }+if (connectionState.status !== 'connected' || modelService === null) {setCodexModels(current => current ?? readCachedModelCatalog());setCodexModelsLoading(false);@@ -1234,7 +1274,7 @@ export function AppController(props: AppControllerProps) {return () => {canceled = true;};- }, [connectionState.status, modelService]);+ }, [connectionState.status, modelService, officialTextModels]);useEffect(() => {let canceled = false;@@ -1260,9 +1300,10 @@ export function AppController(props: AppControllerProps) {if (connectionState.status !== 'connected' || connectionService === null || agentSetup !== 'checking') return;let canceled = false;void Promise.all([- connectionService.getCodexReadiness(), connectionService.getCodexProvider()- ]).then(([readiness, provider]) => {+ connectionService.getCodexReadiness(), connectionService.getCodexProvider(), gatewayAccountService?.getState().catch(() => undefined)+ ]).then(([readiness, provider, gateway]) => {if (canceled) return;+ if (gateway?.source === 'gateway') { onGatewayStateChange(gateway); return; }const snapshot = { readiness, provider };setAgentSetupSnapshot(snapshot);setAgentSetup(isAgentSetupConfirmed(snapshot) ? 'ready' : 'needed');@@ -1270,7 +1311,7 @@ export function AppController(props: AppControllerProps) {if (!canceled) setAgentSetup('needed');});return () => { canceled = true; };- }, [agentSetup, connectionService, connectionState.status]);+ }, [agentSetup, connectionService, connectionState.status, gatewayAccountService, onGatewayStateChange]);useEffect(() => {let canceled = false;@@ -2924,6 +2965,8 @@ export function AppController(props: AppControllerProps) {case 'dashboard':case 'plugins':case 'settings':+ case 'account':+ case 'subscription':closeMobileSidebar();dispatch({type: 'set_active_view',@@ -2947,6 +2990,7 @@ export function AppController(props: AppControllerProps) {}function openPrimaryView(activeView: ActiveView) {+ if ((activeView === 'account' || activeView === 'subscription') && props.route.view !== 'account' && props.route.view !== 'subscription') accountReturnRouteRef.current = props.route;closeMobileSidebar();if (activeView === 'files') {followedFileWorkspaceThreadIdRef.current = undefined;@@ -4174,7 +4218,7 @@ export function AppController(props: AppControllerProps) {const composerDisabledReason = connectionState.status !== 'connected'? t('conversation.connectingRuntime'): agentSetup === 'skipped'- ? l('请先配置 Agent 模型服务', 'Configure the Agent model service first')+ ? gatewayAccountState?.source === 'gateway' ? l('请在个人中心连接模型服务', 'Connect model services from your personal center') : l('请先配置 Agent 模型服务', 'Configure the Agent model service first'): projectLoadError !== undefined? t('conversation.checkingTask'): conversationNeedsProject && currentProject === undefined@@ -4190,7 +4234,7 @@ export function AppController(props: AppControllerProps) {&& !sidebarCollapsed&& workspaceNeedsCompactSidebar;const effectiveSidebarCollapsed = sidebarCollapsed || sidebarAutoCollapsed;- const effectiveComposerConfig = selectedThread === undefined+ const savedComposerConfig = selectedThread === undefined? composerRunConfig ?? defaultComposerRunConfig(currentProject,defaultPermission,@@ -4202,6 +4246,14 @@ export function AppController(props: AppControllerProps) {model: selectedThread.model ?? null,reasoning: (selectedThread.reasoning ?? null) as ComposerRunConfig['reasoning']};+ const effectiveComposerConfig = officialTextModels ? {+ ...savedComposerConfig,+ profile: 'default',+ model: officialTextModels.models.find(model => model.id === savedComposerConfig.model)?.id+ ?? officialTextModels.models.find(model => model.isDefault)?.id+ ?? officialTextModels.models[0]?.id ?? null,+ reasoning: null+ } : savedComposerConfig;const conversationFileLayoutStyle = conversationPaneWidth === undefined? undefined: ({ '--conversation-pane-width': `${conversationPaneWidth}px` } as CSSProperties);@@ -4292,7 +4344,7 @@ export function AppController(props: AppControllerProps) {profile={effectiveComposerConfig.profile}model={effectiveComposerConfig.model}reasoning={effectiveComposerConfig.reasoning}- models={codexModels?.models}+ models={officialTextModels?.models ?? codexModels?.models}modelsLoading={codexModelsLoading}modelsError={codexModelsLoadError}modelsNotice={codexModelsNotice}@@ -4469,9 +4521,13 @@ export function AppController(props: AppControllerProps) {) : null}{agentSetup === 'skipped' ? (<div className="startup-agent-banner" role="status">- {l('Agent 尚未配置,暂时无法发送任务。', 'Agent is not configured; you cannot send tasks yet.')}- <button type="button" onClick={() => setAgentSetup('needed')}>- {l('配置 Agent', 'Set up Agent')}+ {gatewayAccountState?.source === 'gateway'+ ? gatewayAccountState.authState === 'signed_in'+ ? gatewayAccountState.activationState === 'loading' ? l('已登录,正在连接模型服务…', 'Signed in; connecting to model service…') : l('已登录,模型服务暂不可用。', 'Signed in; model service is unavailable.')+ : l('请登录 OpenCreator 后继续创作。', 'Sign in to OpenCreator to continue creating.')+ : l('Agent 尚未配置,暂时无法发送任务。', 'Agent is not configured; you cannot send tasks yet.')}+ <button type="button" onClick={() => gatewayAccountState?.source === 'gateway' ? openPrimaryView('account') : setAgentSetup('needed')}>+ {gatewayAccountState?.source === 'gateway' ? l('个人中心', 'Personal center') : l('配置 Agent', 'Set up Agent')}</button></div>) : null}@@ -4516,6 +4572,8 @@ export function AppController(props: AppControllerProps) {/></section>) : conversationPage;+ const accountPageActive = state.activeView === 'account' || state.activeView === 'subscription';+ const configurationPageActive = accountPageActive || (state.activeView === 'settings' && !agentSetupRequested);const main = props.capabilitiesView !== undefined ? (<CapabilitiesPage {...props.capabilitiesView} />) : state.activeView === 'projects' ? (@@ -4544,6 +4602,7 @@ export function AppController(props: AppControllerProps) {creatorService={creatorService}runtimeDependencies={runtimeDependencies}creatorServicesService={creatorServicesService}+ gatewayState={gatewayAccountState ?? (gatewayAccountService ? null : undefined)}videoMetadataService={videoMetadataService}workspace={props.route.view === 'workbench' ? props.route.tool : undefined}jobId={props.route.view === 'workbench' ? props.route.jobId : undefined}@@ -4636,6 +4695,21 @@ export function AppController(props: AppControllerProps) {handleScheduleChanged(updated);}}/>+ ) : state.activeView === 'account' || state.activeView === 'subscription' ? (+ <PersonalCenterPage+ key={state.activeView}+ view={state.activeView}+ service={gatewayAccountService}+ accountState={gatewayAccountState}+ onStateChange={onGatewayStateChange}+ openExternal={url => hostBridge.openExternal(url)}+ onOpenSubscription={() => openPrimaryView('subscription')}+ onBack={() => {+ if (state.activeView === 'subscription') { openPrimaryView('account'); return; }+ applyRouteFromLocation(accountReturnRouteRef.current);+ navigateToRoute(accountReturnRouteRef.current);+ }}+ />) : state.activeView === 'settings' ? (<SettingsPageruntimeStatus={runtimeStatus}@@ -4695,9 +4769,14 @@ export function AppController(props: AppControllerProps) {onProfileDataChange={setCodexProfiles}cleanupService={cleanupService}creatorServicesService={creatorServicesService}+ gatewayAccountService={gatewayAccountService}+ gatewayAccountState={gatewayAccountState}+ onGatewayStateChange={onGatewayStateChange}+ onOpenPersonalCenter={() => openPrimaryView('account')}+ openExternal={url => hostBridge.openExternal(url)}codexRuntimeService={connectionService}- agentSetupNeeded={agentSetup === 'skipped'}- onOpenAgentSetup={() => setAgentSetup('needed')}+ agentSetupNeeded={agentSetup === 'skipped' || agentSetup === 'needed'}+ onOpenAgentSetup={() => { setAgentSetupRequested(true); setAgentSetup('needed'); }}memoryService={memoryService}memoryProjects={memoryProjectOptions}memoryThreads={memoryThreadOptions}@@ -4782,7 +4861,7 @@ export function AppController(props: AppControllerProps) {}aria-live="polite"/>- {agentSetup === 'needed' ? null : <AppLayout+ {agentSetup === 'needed' && !configurationPageActive ? null : <AppLayoutsidebar={<OpenCreatorSidebarprojects={projects}@@ -4792,7 +4871,9 @@ export function AppController(props: AppControllerProps) {currentProjectId={state.currentProjectId}selectedConversationId={state.selectedThreadId}activeView={state.activeView}- homeActive={props.route.view === 'home'}+ gatewayAccountState={gatewayAccountState}+ loadAccountAvatar={gatewayAccountService?.getAvatar}+ homeActive={state.activeView === 'conversation' && props.route.view === 'home'}projectNavigationMode={props.projectNavigationMode}collapsed={effectiveSidebarCollapsed}autoCollapsed={sidebarAutoCollapsed}@@ -4856,22 +4937,27 @@ export function AppController(props: AppControllerProps) {onOpenMobileSidebar={openMobileSidebar}onCloseMobileSidebar={dismissMobileSidebar}/>}- {agentSetup === 'checking' && connectionState.status === 'connected' ? (+ {agentSetup === 'checking' && connectionState.status === 'connected' && !configurationPageActive ? (<main className="startup-agent-setup" role="status">{l('正在检查 Agent 配置…', 'Checking Agent configuration…')}</main>) : null}- {agentSetup === 'needed' && connectionService !== null ? (+ {agentSetup === 'needed' && connectionService !== null && !configurationPageActive ? (<StartupAgentSetupservice={connectionService}+ gatewayService={gatewayAccountService}+ gatewayState={gatewayAccountState}+ onGatewayStateChange={onGatewayStateChange}+ openExternal={url => hostBridge.openExternal(url)}initialSnapshot={agentSetupSnapshot}onReady={snapshot => {+ setAgentSetupRequested(false);confirmAgentSetup(snapshot);setAgentSetupSnapshot(snapshot);setAgentSetup('ready');startNewConversation({ destination: 'home' });}}- onSkip={() => setAgentSetup('skipped')}+ onSkip={() => { setAgentSetupRequested(false); setAgentSetup('skipped'); }}/>) : null}{projectDropActive ? (@@ -5117,6 +5203,8 @@ function createInitialState(case 'dashboard':case 'plugins':case 'settings':+ case 'account':+ case 'subscription':return {...persistedState,activeView: route.view,@@ -5154,6 +5242,10 @@ function routeForActiveView(activeView: ActiveView, selectedThreadId?: string):return { view: 'plugins' };case 'settings':return { view: 'settings' };+ case 'account':+ return { view: 'account' };+ case 'subscription':+ return { view: 'subscription' };case 'files':return {view: 'files',diff --git a/apps/web/src/app/app-state.ts b/apps/web/src/app/app-state.tsindex cd7a60af..292e0b74 100644--- a/apps/web/src/app/app-state.ts+++ b/apps/web/src/app/app-state.ts@@ -10,6 +10,8 @@ export type ActiveView =| 'dashboard'| 'plugins'| 'settings'+ | 'account'+ | 'subscription'| 'files';export type AppState = {diff --git a/apps/web/src/app/routes.test.ts b/apps/web/src/app/routes.test.tsindex 117f549e..d7d2ac4c 100644--- a/apps/web/src/app/routes.test.ts+++ b/apps/web/src/app/routes.test.ts@@ -2,6 +2,17 @@ import { describe, expect, it } from 'vitest';import { formatRoute, parseRoute } from './routes.js';describe('app routes', () => {+ it('round-trips the personal center route', () => {+ expect(formatRoute({ view: 'account' })).toBe('#/account');+ expect(parseRoute('#/account')).toEqual({ view: 'account' });+ });+ it('round-trips the subscription page route', () => {+ expect(formatRoute({ view: 'subscription' })).toBe('#/subscription');+ expect(parseRoute('#/subscription')).toEqual({ view: 'subscription' });+ });+ it.each(['account', 'subscription'] as const)('opens the independent %s page for the old settings link', tab => {+ expect(parseRoute(`#/settings?tab=${tab}`)).toEqual({ view: tab });+ });it('round-trips a Remotion component settings target', () => {const route = { view: 'settings' as const, tab: 'local-components' as const, component: 'remotion' as const };expect(parseRoute(formatRoute(route))).toEqual(route);@@ -96,7 +107,7 @@ describe('app routes', () => {expect(parseRoute('#/assets')).toEqual({ view: 'dashboard' });expect(parseRoute('#/knowledge')).toEqual({ view: 'dashboard' });expect(parseRoute('#/drive')).toEqual({ view: 'dashboard' });- expect(parseRoute('#/account')).toEqual({ view: 'dashboard' });+ expect(parseRoute('#/account')).toEqual({ view: 'account' });expect(parseRoute('#/activity')).toEqual({ view: 'dashboard' });});diff --git a/apps/web/src/app/routes.ts b/apps/web/src/app/routes.tsindex fb5c19ac..7b558588 100644--- a/apps/web/src/app/routes.ts+++ b/apps/web/src/app/routes.ts@@ -18,6 +18,8 @@ export type AppRoute =| { view: 'schedules'; scheduleId?: string }| { view: 'tasks' }| { view: 'dashboard' }+ | { view: 'account' }+ | { view: 'subscription' }| {view: 'plugins';tab?: 'connections';@@ -77,6 +79,8 @@ 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 === '#/subscription') return { view: 'subscription' };if (path === '#/plugins') {const fields = parseQuery(query);return {@@ -89,6 +93,8 @@ export function parseRoute(hash: string): AppRoute {if (path === '#/settings') {const params = new URLSearchParams(query);const tab = params.get('tab');+ if (tab === 'account') return { view: 'account' };+ if (tab === 'subscription') return { view: 'subscription' };const section = parseAiServicesSection(params.get('section'));const component = params.get('component');const returnPath = params.get('returnPath');@@ -98,7 +104,7 @@ export function parseRoute(hash: string): AppRoute {return {view: 'settings',...(tab === 'local-components'- ? { tab: 'local-components' as const }+ ? { tab }: tab === 'ai-services' || section !== undefined? { tab: 'ai-services' as const }: {}),@@ -154,6 +160,10 @@ export function formatRoute(route: AppRoute): string {return '#/tasks';case 'dashboard':return '#/dashboard';+ case 'account':+ return '#/account';+ case 'subscription':+ return '#/subscription';case 'plugins': {const query = new URLSearchParams();if (route.tab === 'connections') query.set('tab', route.tab);diff --git a/apps/web/src/components/forms/OfficialModelSelect.test.tsx b/apps/web/src/components/forms/OfficialModelSelect.test.tsxnew file mode 100644index 00000000..5d4d5ad1--- /dev/null+++ b/apps/web/src/components/forms/OfficialModelSelect.test.tsx@@ -0,0 +1,114 @@+import { fireEvent, render, screen, within } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';+import { expect, it, vi } from 'vitest';+import OfficialModelSelect from './OfficialModelSelect.js';++function catalog() {+ const models = Array.from({ length: 12 }, (_, index) => ({ id: `vendor/model-${index}`, name: `Model ${index}`, modality: 'text' as const, capabilities: ['responses'] }));+ models.push({ id: 'openrouter/auto', name: 'OpenRouter Automatic', modality: 'text', capabilities: ['responses'] });+ return models;+}++it('shows search results immediately in the same control without retaining unrelated selected models', async () => {+ const models = catalog(); const change = vi.fn();+ const view = render(<OfficialModelSelect label="文本模型" models={models} value="vendor/model-0" onChange={change} />);+ const user = userEvent.setup(); const input = screen.getByRole('combobox', { name: '文本模型' });+ expect(input).toHaveValue('Model 0');+ expect(screen.queryByRole('searchbox')).not.toBeInTheDocument();+ await user.click(input);+ expect(screen.getByRole('option', { name: 'Model 0' })).toHaveAttribute('aria-selected', 'true');+ expect(screen.queryByText(/OpenRouter/i)).not.toBeInTheDocument();+ await user.type(input, 'Model 11');+ const list = screen.getByRole('listbox', { name: '文本模型' });+ expect(within(list).getAllByRole('option')).toHaveLength(1);+ expect(screen.getByText('1 个匹配模型')).toBeInTheDocument();+ expect(change).not.toHaveBeenCalled();+ await user.click(within(list).getByRole('option', { name: 'Model 11' }));+ expect(change).toHaveBeenCalledWith('vendor/model-11');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ view.rerender(<OfficialModelSelect label="文本模型" models={models} value="vendor/model-11" onChange={change} />);+ expect(input).toHaveValue('Model 11');+});++it('matches names, provider IDs, punctuation and multiple keywords, with typo tolerance', async () => {+ const models = [+ { id: 'openai/gpt-4o-mini', name: 'OpenAI: GPT-4o Mini', modality: 'text' as const, capabilities: ['responses'] },+ { id: 'deepseek/deepseek-v3.2', name: 'DeepSeek V3.2', modality: 'text' as const, capabilities: ['responses'] },+ ...catalog(),+ ];+ render(<OfficialModelSelect label="文本模型" models={models} value="vendor/model-0" onChange={vi.fn()} />);+ const user = userEvent.setup(); const input = screen.getByRole('combobox');+ await user.click(input);+ for (const query of ['MINI gPt 4.o', 'openai/gpt_4o_mini']) {+ await user.clear(input); await user.type(input, query);+ expect(screen.getAllByRole('option')).toHaveLength(1);+ expect(screen.getByRole('option', { name: 'OpenAI: GPT-4o Mini' })).toBeInTheDocument();+ }+ await user.clear(input); await user.type(input, 'depseek');+ expect(screen.getAllByRole('option')[0]).toHaveAccessibleName('DeepSeek V3.2');+});++it('preserves the selection when no model matches or the user cancels and resets search on reopening', async () => {+ const change = vi.fn();+ render(<><OfficialModelSelect label="文本模型" models={catalog()} value="vendor/model-0" onChange={change} /><button>外部操作</button></>);+ const user = userEvent.setup(); const input = screen.getByRole('combobox');+ await user.click(input); await user.type(input, 'zzzzzzzzzzzz');+ expect(screen.queryByRole('option')).not.toBeInTheDocument();+ expect(screen.getByText('未找到匹配模型')).toBeInTheDocument();+ await user.keyboard('{Enter}'); expect(change).not.toHaveBeenCalled();+ await user.click(screen.getByRole('button', { name: '外部操作' }));+ expect(input).toHaveValue('Model 0');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ await user.click(input);+ expect(screen.getAllByRole('option')).toHaveLength(13);+ expect(input).toHaveValue('');+ await user.type(input, 'Model 11'); await user.keyboard('{Escape}');+ expect(input).toHaveValue('Model 0'); expect(change).not.toHaveBeenCalled();+});++it('supports keyboard navigation, selection and tab dismissal without moving focus into the menu', async () => {+ const change = vi.fn();+ render(<><OfficialModelSelect label="文本模型" models={catalog()} value="vendor/model-0" onChange={change} /><button>下一个控件</button></>);+ const user = userEvent.setup(); const input = screen.getByRole('combobox');+ await user.tab();+ expect(input).toHaveFocus(); expect(input).toHaveAttribute('aria-expanded', 'true');+ await user.keyboard('{ArrowDown}');+ expect(input).toHaveAttribute('aria-activedescendant', screen.getByRole('option', { name: 'Model 1' }).id);+ await user.keyboard('{Enter}'); expect(change).toHaveBeenCalledWith('vendor/model-1');+ expect(input).toHaveFocus(); expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ await user.keyboard('{ArrowDown}');+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ await user.tab();+ expect(screen.getByRole('button', { name: '下一个控件' })).toHaveFocus();+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+});++it('clears a query without changing the selection and does not resubmit the selected model', async () => {+ const change = vi.fn(); render(<OfficialModelSelect label="文本模型" models={catalog()} value="vendor/model-0" onChange={change} />);+ const user = userEvent.setup(); const input = screen.getByRole('combobox');+ await user.click(input); await user.type(input, 'Model 11');+ await user.click(screen.getByRole('button', { name: '清空模型搜索' }));+ expect(input).toHaveFocus(); expect(input).toHaveValue('');+ expect(screen.getAllByRole('option')).toHaveLength(13);+ await user.click(screen.getByRole('option', { name: 'Model 0' }));+ expect(change).not.toHaveBeenCalled(); expect(input).toHaveValue('Model 0');+});++it('does not select a model when Enter confirms an IME composition', async () => {+ const change = vi.fn(); render(<OfficialModelSelect label="文本模型" models={catalog()} value="vendor/model-0" onChange={change} />);+ const input = screen.getByRole('combobox');+ await userEvent.setup().click(input); fireEvent.change(input, { target: { value: 'Model 11' } });+ fireEvent.keyDown(input, { key: 'Enter', isComposing: true });+ expect(change).not.toHaveBeenCalled(); expect(screen.getByRole('listbox')).toBeInTheDocument();+ fireEvent.keyDown(input, { key: 'Enter' }); expect(change).toHaveBeenCalledWith('vendor/model-11');+});++it('closes when disabled and retains accessibility descriptions and the selected model', async () => {+ const change = vi.fn(); const models = catalog();+ const view = render(<OfficialModelSelect label="文本模型" describedBy="model-count" models={models} value="vendor/model-0" onChange={change} />);+ const input = screen.getByRole('combobox'); await userEvent.setup().click(input);+ view.rerender(<OfficialModelSelect label="文本模型" describedBy="model-count" models={models} value="vendor/model-0" disabled onChange={change} />);+ expect(input).toBeDisabled(); expect(input).toHaveValue('Model 0');+ expect(input).toHaveAttribute('aria-describedby', 'model-count');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); expect(change).not.toHaveBeenCalled();+});diff --git a/apps/web/src/components/forms/OfficialModelSelect.tsx b/apps/web/src/components/forms/OfficialModelSelect.tsxnew file mode 100644index 00000000..e3c9056a--- /dev/null+++ b/apps/web/src/components/forms/OfficialModelSelect.tsx@@ -0,0 +1,183 @@+import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';+import { createPortal } from 'react-dom';+import { Check, ChevronDown, Search, X } from 'lucide-react';+import Fuse from 'fuse.js';+import type { GatewayModel } from '@opencreator/protocol';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import './official-model-select.css';++export function officialModelLabel(model: GatewayModel, automatic: string): string {+ if (/openrouter/i.test(model.id)) return automatic;+ return (model.name || model.id.split('/').pop() || model.id).replace(/OpenRouter\s*:?\s*/gi, '').trim();+}++export default function OfficialModelSelect(props: {+ label: string; describedBy?: string; models: GatewayModel[]; value: string;+ disabled?: boolean; onChange(value: string): void;+}) {+ const l = useLocalizedCopy();+ const id = useId();+ const rootRef = useRef<HTMLSpanElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState('');+ const [activeIndex, setActiveIndex] = useState(0);+ const [position, setPosition] = useState<{ left: number; top: number; width: number; maxHeight: number; above: boolean }>();+ const automatic = l('自动选择', 'Automatic');+ const choices = useMemo(() => props.models.map(model => {+ const label = officialModelLabel(model, automatic);+ return { model, label, nameSearch: normalizeSearch(label), idSearch: normalizeSearch(model.id) };+ }), [props.models, automatic]);+ const search = useMemo(() => new Fuse(choices, {+ keys: [{ name: 'nameSearch', weight: 0.7 }, { name: 'idSearch', weight: 0.3 }],+ threshold: 0.3, ignoreLocation: true,+ }), [choices]);+ const filtered = useMemo(() => {+ if (!query.trim()) {+ return [...choices.filter(choice => choice.model.id === props.value), ...choices.filter(choice => choice.model.id !== props.value)];+ }+ const terms = query.trim().split(/\s+/).map(normalizeSearch).filter(Boolean);+ if (terms.length === 0) return [];+ const results = search.search({+ $and: terms.map(term => ({ $or: ['nameSearch', 'idSearch'].map(key => ({ [key]: term })) })),+ }).map(result => result.item);+ const exact = new Set(choices.filter(choice => terms.every(term => choice.nameSearch.includes(term) || choice.idSearch.includes(term))));+ return exact.size ? results.filter(choice => exact.has(choice)) : results;+ }, [choices, search, query, props.value]);+ const selected = choices.find(choice => choice.model.id === props.value);+ const selectedLabel = selected?.label ?? (props.models.length === 0 ? l('暂不可用', 'Unavailable') : l('选择模型', 'Select model'));+ const expanded = open && !props.disabled;+ const currentIndex = Math.min(activeIndex, filtered.length - 1);+ const optionId = (index: number) => `${id}-option-${index}`;++ function close() { setOpen(false); setQuery(''); setActiveIndex(0); }+ function show() {+ if (props.disabled || open) return;+ setQuery(''); setActiveIndex(0); setOpen(true);+ }+ function select(value: string) {+ inputRef.current?.focus();+ close();+ if (value !== props.value) props.onChange(value);+ }++ useEffect(() => { if (props.disabled) close(); }, [props.disabled]);+ useEffect(() => {+ if (!expanded) return;+ const onOutsidePointer = (event: PointerEvent) => {+ if (!rootRef.current?.contains(event.target as Node) && !menuRef.current?.contains(event.target as Node)) close();+ };+ document.addEventListener('pointerdown', onOutsidePointer);+ window.addEventListener('blur', close);+ return () => { document.removeEventListener('pointerdown', onOutsidePointer); window.removeEventListener('blur', close); };+ }, [expanded]);++ useLayoutEffect(() => {+ if (!expanded) return;+ // Keep the menu outside scrolling containers and within the visible viewport.+ const place = () => {+ const rect = rootRef.current?.getBoundingClientRect();+ if (!rect) return;+ const viewport = window.visualViewport;+ const viewportTop = viewport?.offsetTop ?? 0;+ const viewportLeft = viewport?.offsetLeft ?? 0;+ const viewportWidth = viewport?.width ?? window.innerWidth;+ const viewportBottom = viewportTop + (viewport?.height ?? window.innerHeight);+ const below = viewportBottom - rect.bottom - 14;+ const above = rect.top - viewportTop - 14;+ const opensAbove = below < 300 && above > below;+ const width = Math.min(rect.width, viewportWidth - 16);+ const next = {+ width, left: Math.max(viewportLeft + 8, Math.min(rect.left, viewportLeft + viewportWidth - width - 8)),+ top: opensAbove ? rect.top - 6 : rect.bottom + 6,+ maxHeight: Math.max(0, Math.min(360, opensAbove ? above : below)), above: opensAbove,+ };+ setPosition(previous => previous && Object.keys(next).every(key => previous[key as keyof typeof next] === next[key as keyof typeof next]) ? previous : next);+ };+ place();+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(place);+ if (rootRef.current) observer?.observe(rootRef.current);+ window.addEventListener('resize', place);+ window.addEventListener('scroll', place, true);+ window.visualViewport?.addEventListener('resize', place);+ window.visualViewport?.addEventListener('scroll', place);+ return () => {+ observer?.disconnect();+ window.removeEventListener('resize', place); window.removeEventListener('scroll', place, true);+ window.visualViewport?.removeEventListener('resize', place); window.visualViewport?.removeEventListener('scroll', place);+ };+ }, [expanded]);++ useEffect(() => {+ if (expanded && currentIndex >= 0) document.getElementById(optionId(currentIndex))?.scrollIntoView?.({ block: 'nearest' });+ }, [expanded, currentIndex, query]);++ function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {+ if (event.nativeEvent.isComposing) return;+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {+ event.preventDefault();+ if (!expanded) { show(); return; }+ if (filtered.length) setActiveIndex((currentIndex + (event.key === 'ArrowDown' ? 1 : -1) + filtered.length) % filtered.length);+ } else if (event.key === 'Enter') {+ event.preventDefault();+ if (!expanded) show();+ else if (filtered[currentIndex]) select(filtered[currentIndex].model.id);+ } else if (event.key === 'Escape' && expanded) {+ event.preventDefault(); event.stopPropagation(); close();+ } else if (event.key === 'Tab') close();+ }++ return <span className="official-model-select" ref={rootRef}>+ <span className={`official-model-control${expanded ? ' is-open' : ''}`}>+ <Search size={15} className="official-model-search-icon" aria-hidden="true" />+ <input ref={inputRef} type="text" role="combobox" aria-label={props.label} aria-describedby={props.describedBy}+ aria-autocomplete="list" aria-haspopup="listbox" aria-expanded={expanded}+ aria-controls={expanded ? `${id}-listbox` : undefined}+ aria-activedescendant={expanded && currentIndex >= 0 ? optionId(currentIndex) : undefined}+ value={expanded ? query : selectedLabel} disabled={props.disabled} autoComplete="off" spellCheck={false}+ placeholder={l('搜索模型', 'Search models')} title={expanded ? undefined : selectedLabel}+ onFocus={show} onClick={show} onKeyDown={onKeyDown}+ onBlur={event => { if (!rootRef.current?.contains(event.relatedTarget) && !menuRef.current?.contains(event.relatedTarget)) close(); }}+ onChange={event => { setQuery(event.target.value); setActiveIndex(0); setOpen(true); }} />+ {expanded && query ? <button className="official-model-clear" type="button" tabIndex={-1}+ aria-label={l('清空模型搜索', 'Clear model search')} title={l('清空搜索', 'Clear search')}+ onMouseDown={event => event.preventDefault()} onClick={() => { setQuery(''); setActiveIndex(0); inputRef.current?.focus(); }}>+ <X size={14} aria-hidden="true" />+ </button> : null}+ <button className="official-model-toggle" type="button" tabIndex={-1} disabled={props.disabled}+ aria-label={expanded ? l('收起模型列表', 'Close model list') : l('展开模型列表', 'Open model list')}+ title={expanded ? l('收起模型列表', 'Close model list') : l('展开模型列表', 'Open model list')}+ onMouseDown={event => event.preventDefault()}+ onClick={() => { inputRef.current?.focus(); if (expanded) close(); else show(); }}>+ <ChevronDown size={16} aria-hidden="true" />+ </button>+ </span>+ {expanded && position ? createPortal(<div ref={menuRef} className="official-model-menu" style={{+ left: position.left, top: position.top, width: position.width, maxHeight: position.maxHeight,+ transform: position.above ? 'translateY(-100%)' : undefined,+ }}>+ <div className="official-model-menu-count" role="status">+ {query.trim() ? l(`${filtered.length} 个匹配模型`, `${filtered.length} matches`) : l(`${filtered.length} 个模型`, `${filtered.length} models`)}+ </div>+ <div id={`${id}-listbox`} className="official-model-options" role="listbox" aria-label={props.label}>+ {filtered.map((choice, index) => <button key={choice.model.id} id={optionId(index)} type="button" role="option" tabIndex={-1}+ aria-label={choice.label} aria-selected={choice.model.id === props.value}+ className={`official-model-option${index === currentIndex ? ' is-active' : ''}`}+ title={choice.label} onMouseDown={event => event.preventDefault()}+ onPointerMove={event => { if (event.pointerType === 'mouse') setActiveIndex(index); }}+ onClick={() => select(choice.model.id)}>+ <span className="official-model-option-text"><span className="official-model-option-name">{choice.label}</span>+ {!/openrouter/i.test(choice.model.id) ? <span className="official-model-option-id">{choice.model.id}</span> : null}+ </span>+ {choice.model.id === props.value ? <Check size={16} aria-hidden="true" /> : <span className="official-model-check-space" />}+ </button>)}+ {filtered.length === 0 ? <div className="official-model-empty" role="status">{l('未找到匹配模型', 'No matching models')}</div> : null}+ </div>+ </div>, document.body) : null}+ </span>;+}++function normalizeSearch(value: string): string {+ return value.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');+}diff --git a/apps/web/src/components/forms/official-model-select.css b/apps/web/src/components/forms/official-model-select.cssnew file mode 100644index 00000000..34b002d5--- /dev/null+++ b/apps/web/src/components/forms/official-model-select.css@@ -0,0 +1,91 @@+.official-model-select { display: block; width: 100%; min-width: 0; }+.official-model-control { position: relative; display: block; height: 40px; min-width: 0; }++.official-model-control input {+ width: 100%;+ min-width: 0;+ height: 40px;+ padding: 0 64px 0 34px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: var(--surface-2);+ color: var(--text);+ font-family: inherit;+ font-size: 13px;+ text-overflow: ellipsis;+ cursor: pointer;+}+.official-model-control input:hover:not(:disabled) { border-color: var(--border-strong); }+.official-model-control.is-open input { cursor: text; }+.official-model-control input:focus-visible {+ border-color: var(--border-strong);+ outline: 2px solid var(--state-focus-ring);+ outline-offset: 2px;+}+.official-model-control input:disabled { opacity: var(--state-disabled-opacity); cursor: default; }+.official-model-search-icon { position: absolute; z-index: 1; top: 12px; left: 11px; color: var(--subtle); pointer-events: none; }++.official-model-control button {+ position: absolute;+ top: 4px;+ width: 28px;+ height: 32px;+ min-height: 0;+ display: grid;+ place-items: center;+ padding: 0;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--muted);+}+.official-model-control button:hover:not(:disabled) { background: var(--state-hover-bg); color: var(--text); }+.official-model-clear { right: 32px; }+.official-model-toggle { right: 4px; }+.official-model-control.is-open .official-model-toggle svg { transform: rotate(180deg); }++.official-model-menu {+ position: fixed;+ z-index: 500;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ background: var(--surface-popover);+ box-shadow: var(--shadow-popover);+ color: var(--text);+ font-family: var(--font);+ font-size: 13px;+}+.official-model-menu-count { flex-shrink: 0; padding: 10px 12px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: 11px; line-height: 16px; }+.official-model-options { min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 4px; scrollbar-width: thin; }+.official-model-option {+ width: 100%;+ min-height: 52px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 9px 8px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.official-model-option.is-active { background: var(--state-hover-bg); }+.official-model-option[aria-selected='true'] > svg { flex-shrink: 0; color: var(--accent-strong); }+.official-model-option-text { display: grid; gap: 3px; min-width: 0; }+.official-model-option-name { font-weight: 500; line-height: 1.4; overflow-wrap: anywhere; }+.official-model-option-id { color: var(--subtle); font-size: 11px; line-height: 1.4; overflow-wrap: anywhere; }+.official-model-check-space { flex-shrink: 0; width: 16px; }+.official-model-empty { padding: 24px 12px; color: var(--muted); text-align: center; line-height: 1.5; }++@media (pointer: coarse) {+ .official-model-control, .official-model-control input { height: 44px; }+ .official-model-control button { height: 36px; }+ .official-model-search-icon { top: 14px; }+}diff --git a/apps/web/src/features/account/AccountAvatar.test.tsx b/apps/web/src/features/account/AccountAvatar.test.tsxnew file mode 100644index 00000000..52adf4e0--- /dev/null+++ b/apps/web/src/features/account/AccountAvatar.test.tsx@@ -0,0 +1,47 @@+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { AccountAvatar } from './AccountAvatar.js';++const NativeURL = URL;+beforeEach(() => {+ class TestURL extends NativeURL {+ static createObjectURL = vi.fn(() => 'blob:account-photo');+ static revokeObjectURL = vi.fn();+ }+ vi.stubGlobal('URL', TestURL);+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });++it('renders the account photo and falls back after an image error', async () => {+ const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:account-photo');+ const revoke = vi.spyOn(URL, 'revokeObjectURL');+ const loader = vi.fn(async () => new Blob(['image'], { type: 'image/png' }));+ const view = render(<AccountAvatar email="[email protected]" accountId="a" avatarUrl="https://lh3.googleusercontent.com/photo" loadAvatar={loader}/>);+ await waitFor(() => expect(view.container.querySelector('img')).toHaveAttribute('src', 'blob:account-photo'));+ expect(loader).toHaveBeenCalledWith('a', 'https://lh3.googleusercontent.com/photo');+ fireEvent.error(view.container.querySelector('img')!);+ expect(view.container.querySelector('img')).toBeNull();+ expect(view.container).toHaveTextContent('O');+ view.unmount();+ expect(create).toHaveBeenCalledOnce();+ expect(revoke).toHaveBeenCalledWith('blob:account-photo');+});++it('ignores a previous account photo after signing out', async () => {+ const create = vi.spyOn(URL, 'createObjectURL');+ let resolve!: (image: Blob) => void;+ const loader = vi.fn(() => new Promise<Blob>(complete => { resolve = complete; }));+ const view = render(<AccountAvatar email="[email protected]" accountId="a" avatarUrl="https://lh3.googleusercontent.com/photo" loadAvatar={loader}/>);+ view.rerender(<AccountAvatar/>);+ await act(async () => resolve(new Blob(['image'], { type: 'image/png' })));+ expect(view.container.querySelector('img')).toBeNull();+ expect(create).not.toHaveBeenCalled();+});++it('keeps the initial visible when a picture request fails', async () => {+ const loader = vi.fn(async () => { throw new Error('Unavailable'); });+ const view = render(<AccountAvatar email="[email protected]" accountId="a" avatarUrl="https://lh3.googleusercontent.com/photo" loadAvatar={loader}/>);+ await waitFor(() => expect(loader).toHaveBeenCalledOnce());+ expect(view.container).toHaveTextContent('A');+ expect(view.container.querySelector('img')).toBeNull();+});diff --git a/apps/web/src/features/account/AccountAvatar.tsx b/apps/web/src/features/account/AccountAvatar.tsxnew file mode 100644index 00000000..c06813d3--- /dev/null+++ b/apps/web/src/features/account/AccountAvatar.tsx@@ -0,0 +1,26 @@+import { useEffect, useState } from 'react';+import { UserRound } from 'lucide-react';+import './personal-center.css';++export function AccountAvatar(props: {+ email?: string; accountId?: string; avatarUrl?: string; large?: boolean;+ loadAvatar?(accountId: string, revision: string): Promise<Blob>;+}) {+ const [image, setImage] = useState<{ key: string; url: string }>();+ const key = `${props.accountId ?? ''}:${props.avatarUrl ?? ''}`;+ useEffect(() => {+ if (!props.email || !props.accountId || !props.avatarUrl || !props.loadAvatar) return;+ let active = true;+ let objectURL: string | undefined;+ void props.loadAvatar(props.accountId, props.avatarUrl).then(blob => {+ if (!active) return;+ objectURL = URL.createObjectURL(blob);+ setImage({ key, url: objectURL });+ }).catch(() => undefined);+ return () => { active = false; if (objectURL) URL.revokeObjectURL(objectURL); };+ }, [props.email, props.accountId, props.avatarUrl, props.loadAvatar, key]);+ return <span className={`account-avatar${props.large ? ' account-avatar--large' : ''}`} aria-hidden="true">+ {props.email ? props.email.trim().charAt(0).toUpperCase() : <UserRound size={props.large ? 28 : 18}/>}+ {props.email && props.avatarUrl && image?.key === key ? <img src={image.url} alt="" onError={() => setImage(undefined)}/> : null}+ </span>;+}diff --git a/apps/web/src/features/account/PersonalCenterPage.test.tsx b/apps/web/src/features/account/PersonalCenterPage.test.tsxnew file mode 100644index 00000000..199d3245--- /dev/null+++ b/apps/web/src/features/account/PersonalCenterPage.test.tsx@@ -0,0 +1,83 @@+import { act, cleanup, render, screen, waitFor, within } 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 type { GatewayAccountSettingsService, GatewayBillingSummary } from '../../services/gateway-account-service.js';+import PersonalCenterPage from './PersonalCenterPage.js';++afterEach(cleanup);+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() };+}+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>;+}+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));+ 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();+ expect(service.getSummary).not.toHaveBeenCalled();+});+it('links guests to website plans from the recharge page', 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(service.checkout).not.toHaveBeenCalled();+ expect(service.getSummary).not.toHaveBeenCalled();+});+it('shows account and credits and returns to the previous view', async () => {+ const back = vi.fn();+ render(page(createService(), signedIn, back));+ expect(await screen.findByText('123')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: '[email protected]' })).toBeInTheDocument();+ expect(screen.getByText('已登录', { exact: true })).toBeInTheDocument();+ expect(screen.queryByText('未订阅')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '返回' }));+ expect(back).toHaveBeenCalledOnce();+});+it('loads credits immediately after login', async () => {+ const service = createService(signedOut); const open = vi.fn();+ vi.mocked(service.start).mockImplementation(async () => { vi.mocked(service.getState).mockResolvedValue(signedIn); return { attemptId: 'attempt', authorizationUrl: 'https://gateway.example/device', expiresAt: '2026-10-08T00:00:00Z' }; });+ 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');+});+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.getByRole('button', { name: '退出登录' }));+ expect(await screen.findByRole('button', { name: '登录 / 注册' })).toBeInTheDocument();+ expect(screen.queryByText('123')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: '充值积分' })).not.toBeInTheDocument();+});+it('ignores a previous account balance response after switching accounts', async () => {+ const service = createService(); let complete!: (result: GatewayBillingSummary) => void;+ vi.mocked(service.getSummary).mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));+ const view = render(page(service, signedIn));+ await waitFor(() => expect(service.getSummary).toHaveBeenCalledOnce());+ const next = { ...signedIn, account: { id: 'b', email: '[email protected]', verified: true } };+ vi.mocked(service.getState).mockResolvedValue(next);+ vi.mocked(service.getSummary).mockResolvedValue({ ...summary, balance: { ...summary.balance, availableUnits: '8000000' } });+ view.rerender(page(service, next));+ expect(await screen.findByText('8')).toBeInTheDocument();+ await act(async () => complete(summary));+ expect(screen.queryByText('123')).not.toBeInTheDocument();+});+it('shows unavailable login without an enabled action', () => {+ render(page(null));+ expect(within(screen.getByRole('region', { name: 'OpenCreator 账户' })).getByText('登录服务暂不可用')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: '登录 / 注册' })).toBeDisabled();+});diff --git a/apps/web/src/features/account/PersonalCenterPage.tsx b/apps/web/src/features/account/PersonalCenterPage.tsxnew file mode 100644index 00000000..40b11aba--- /dev/null+++ b/apps/web/src/features/account/PersonalCenterPage.tsx@@ -0,0 +1,53 @@+import { useEffect, useState } from 'react';+import { ArrowLeft } from 'lucide-react';+import type { GatewayAccountState } from '@opencreator/protocol';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';+import { GatewayAccountSettingsView } from '../settings/GatewayAccountSettingsView.js';+import { GatewaySubscriptionSettingsView } from '../settings/GatewaySubscriptionSettingsView.js';+import { AccountAvatar } from './AccountAvatar.js';+import './personal-center.css';++export default function PersonalCenterPage(props: {+ view?: 'account' | 'subscription';+ service: GatewayAccountSettingsService | null;+ accountState?: GatewayAccountState;+ onStateChange?(state: GatewayAccountState): void;+ openExternal?(url: string): Promise<void> | void;+ onBack(): void;+ onOpenSubscription(): void;+}) {+ const l = useLocalizedCopy();+ const [state, setState] = useState(props.accountState);+ 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 & Recharge') : l('个人中心', 'Personal center');++ return <main className="opencreator-scroll-page personal-center" aria-label={title}>+ <div className="personal-center__content">+ <header className="personal-center__heading">+ <button type="button" onClick={props.onBack} title={l('返回', 'Back')} aria-label={l('返回', 'Back')}><ArrowLeft size={20}/></button>+ <h1>{title}</h1>+ </header>+ <section className="personal-center__identity" aria-label={l('账户信息', 'Account information')}>+ <AccountAvatar email={email} accountId={state?.account?.id} avatarUrl={state?.account?.avatarUrl} loadAvatar={props.service?.getAvatar} large/>+ <GatewayAccountSettingsView+ variant="profile"+ service={props.service}+ accountState={state}+ openExternal={props.openExternal}+ onStateChange={next => {+ setState(next); props.onStateChange?.(next);+ }}+ />+ </section>+ <GatewaySubscriptionSettingsView+ variant={subscriptionPage ? 'subscription' : 'overview'}+ key={`${state?.authState}:${state?.account?.id ?? ''}`}+ service={props.service} embedded accountState={state} openExternal={props.openExternal}+ onOpenSubscription={props.onOpenSubscription}+ />+ </div>+ </main>;+}diff --git a/apps/web/src/features/account/personal-center.css b/apps/web/src/features/account/personal-center.cssnew file mode 100644index 00000000..297ac176--- /dev/null+++ b/apps/web/src/features/account/personal-center.css@@ -0,0 +1,31 @@+.account-avatar { position: relative; overflow: hidden; display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; flex: 0 0 32px; border-radius: 50%; background: var(--surface-3, var(--surface-2)); color: var(--muted); font-size: 14px; font-weight: 600; letter-spacing: 0; }+.account-avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }+.account-avatar--large { width: 56px; height: 56px; flex-basis: 56px; font-size: 22px; }+.sidebar-account { display: flex; align-items: center; gap: 10px; width: 100%; min-width: 0; padding: 8px; border: 0; border-radius: 6px; background: transparent; color: var(--text); text-align: left; cursor: pointer; }+.sidebar-account:hover, .sidebar-account[aria-current=page] { background: var(--surface-2); }+.sidebar-account:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.sidebar-account__copy { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; }+.sidebar-account__copy strong { font-size: 13px; font-weight: 500; }+.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__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); }+.personal-center__identity { display: flex; align-items: center; gap: 16px; padding-bottom: 24px; border-bottom: 1px solid var(--border); }+.personal-center .gateway-account--profile { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px 16px; padding: 0; flex: 1; }+.gateway-account__identity { min-width: 0; }+.gateway-account__identity h2 { font-size: 16px; font-weight: 500; overflow-wrap: anywhere; }+.gateway-account__identity > [role=status] { color: var(--muted); margin: 5px 0 0; font-size: 12px; }+.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; }+@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); }+ .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/DashboardPage.tsx b/apps/web/src/features/dashboard/DashboardPage.tsxindex f218bc27..f45b72a5 100644--- a/apps/web/src/features/dashboard/DashboardPage.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.tsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';-import type { CreatorJob, CreatorJson, OpenCreatorIssue } from '@opencreator/protocol';+import type { CreatorJob, CreatorJson, GatewayAccountState, OpenCreatorIssue } from '@opencreator/protocol';+import { OfficialServicesContext } from './official-services.js';import { useAppLanguage } from '../../i18n/LanguageProvider.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import {@@ -215,6 +216,7 @@ export default function DashboardPage(props: {onWorkspaceModeChange?(active: boolean): void;skillLaunch?: CreatorSkillLaunch;creatorServicesService?: CreatorServicesSettingsService | null;+ gatewayState?: GatewayAccountState | null;videoMetadataService?: VideoMetadataService;workspace?: CreatorWorkspace;jobId?: string;@@ -340,7 +342,7 @@ export default function DashboardPage(props: {onAskIssue={props.onAskIssue}onBack={closeWorkspace}>- {content}+ <OfficialServicesContext.Provider value={props.gatewayState}>{content}</OfficialServicesContext.Provider></CreatorWorkspaceSession>);};diff --git a/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx b/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsxindex 11bf89c4..21243236 100644--- a/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/ImageGenerationWorkspace.test.tsx@@ -3,15 +3,50 @@ import type {CreatorActionRequest,CreatorArtifact,CreatorJob,- CreatorJson+ CreatorJson,+ GatewayAccountState} from '@opencreator/protocol';import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';import ImageGenerationWorkspace from './ImageGenerationWorkspace.js';import { CreatorSessionProvider, useOptionalCreatorSession, type CreatorSessionContextValue } from './creator-session-store.js';+import { OfficialServicesContext } from './official-services.js';describe('ImageGenerationWorkspace', () => {+ it('uses official image metadata without changing the custom quality presets or candidate count', async () => {+ const fixture = createFixture();+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: '1', models: [{ id: 'vendor/image', modality: 'image', capabilities: [], imageOptions: { aspectRatios: ['16:9', '9:16'], resolutions: ['1K', '2K'], qualities: ['standard', 'hd'], outputFormats: ['jpeg'], maxImages: 1, maxReferences: 0 } }], activationError: null };+ renderWorkspace(fixture, { ...fixture.currentJob(), state: { prompt: 'city', currentStep: 1, furthestStep: 1 } }, { getConfig: vi.fn() }, state);+ expect(screen.getByRole('combobox', { name: '图片画幅' })).toHaveValue('16:9');+ fireEvent.change(screen.getByRole('combobox', { name: '分辨率' }), { target: { value: '2K' } });+ fireEvent.change(screen.getByRole('combobox', { name: '图片质量' }), { target: { value: 'hd' } });+ fireEvent.click(screen.getByRole('radio', { name: '4 张' }));+ fireEvent.click(screen.getByRole('button', { name: '继续' }));+ fireEvent.click(screen.getByRole('button', { name: '开始生成' }));+ await waitFor(() => expect(fixture.applyAction).toHaveBeenCalled());+ const update = fixture.applyAction.mock.calls.find(([, request]) => request.action === 'update-settings');+ expect(update?.[1].input.patch).toMatchObject({ aspectRatio: '16:9', resolution: '2K', officialQuality: 'hd', candidateCount: 4 });+ });+ it('allows only official image choices and submits the task choice without changing defaults', async () => {+ const fixture = createFixture();+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', selectedModels: { image: 'official/first' }, models: [{ id: 'official/first', modality: 'image', capabilities: [] }, { id: 'official/second', modality: 'image', capabilities: ['edit'] }], activationError: null };+ const getConfig = vi.fn();+ renderWorkspace(fixture, { ...fixture.currentJob(), state: { prompt: 'city skyline', provider: 'codex-native', currentStep: 1, furthestStep: 1 } }, { getConfig }, state);+ const model = screen.getByRole('combobox', { name: '图片模型' });+ fireEvent.click(model);+ expect(within(screen.getByRole('listbox', { name: '图片模型' })).getAllByRole('option').map(option => option.getAttribute('aria-label'))).toEqual(['first', 'second']);+ expect(screen.queryByRole('radio', { name: '本机 Codex 生图' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('option', { name: 'second' }));+ fireEvent.click(screen.getByRole('button', { name: '继续' }));+ fireEvent.click(screen.getByRole('button', { name: '开始生成' }));+ await waitFor(() => expect(fixture.applyAction).toHaveBeenCalledWith('creator_job_image_ui', expect.objectContaining({ action: 'run-stage', input: { stageId: 'generate' } })));+ const update = fixture.applyAction.mock.calls.find(([, request]) => request.action === 'update-settings');+ expect(update?.[1].input.patch).toMatchObject({ provider: 'openai', officialModels: { image: 'official/second' } });+ expect(state.selectedModels?.image).toBe('official/first');+ expect(getConfig).not.toHaveBeenCalled();+ });+beforeEach(() => {Object.defineProperty(URL, 'createObjectURL', {configurable: true,@@ -287,7 +322,8 @@ describe('ImageGenerationWorkspace', () => {function renderWorkspace(fixture: ReturnType<typeof createFixture>,initialJob = fixture.currentJob(),- creatorServicesService?: { getConfig(): Promise<unknown> }+ creatorServicesService?: { getConfig(): Promise<unknown> },+ gatewayState?: GatewayAccountState) {let currentSession: CreatorSessionContextValue | null = null;const view = render(@@ -302,11 +338,13 @@ function renderWorkspace(runAgentTurn: vi.fn()} as never}>+ <OfficialServicesContext.Provider value={gatewayState}><SessionObserver onSession={session => { currentSession = session; }} /><ImageGenerationWorkspaceonBack={vi.fn()}creatorServicesService={creatorServicesService as never}/>+ </OfficialServicesContext.Provider></CreatorSessionProvider></LanguageProvider>);diff --git a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsxindex 433c1799..6c8ef0e9 100644--- a/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx+++ b/apps/web/src/features/dashboard/ImageGenerationWorkspace.tsx@@ -10,6 +10,7 @@ import {type ImageGenerationQuality,type ImageGenerationSize} from '@opencreator/protocol';+import { OfficialModelField, useOfficialServices } from './official-services.js';import {Check,Download,@@ -75,6 +76,7 @@ export default function ImageGenerationWorkspace(props: {}) {const l = useLocalizedCopy();const session = useOptionalCreatorSession();+ const official = useOfficialServices('image');const restoredResults = session?.job.artifacts.some(artifact => artifact.kind === 'generated_image') === true;const restoredStep = restoredResults? 2@@ -92,6 +94,20 @@ export default function ImageGenerationWorkspace(props: {const [size, setSize] = useState<ImageGenerationSize>(() => readSize(session?.state.size));const [quality, setQuality] = useState<ImageGenerationQuality>(() => readQuality(session?.state.quality));const [count, setCount] = useState(() => readCount(session?.state.candidateCount));+ const [aspectRatio, setAspectRatio] = useState(() => readString(session?.state.aspectRatio));+ const [resolution, setResolution] = useState(() => readString(session?.state.resolution));+ const [officialQuality, setOfficialQuality] = useState(() => readString(session?.state.officialQuality));+ const imageOptions = official.official ? official.model?.imageOptions : undefined;+ useEffect(() => {+ if (!imageOptions || official.taskRunning) return;+ const nextRatio = imageOptions.aspectRatios?.includes(aspectRatio) ? aspectRatio : imageOptions.aspectRatios?.[0] ?? '';+ const nextResolution = imageOptions.resolutions?.includes(resolution) ? resolution : imageOptions.resolutions?.[0] ?? '';+ const nextQuality = imageOptions.qualities?.includes(officialQuality) ? officialQuality : imageOptions.qualities?.[0] ?? '';+ setAspectRatio(nextRatio); setResolution(nextResolution); setOfficialQuality(nextQuality);+ if (nextRatio !== aspectRatio || nextResolution !== resolution || nextQuality !== officialQuality) {+ session?.updateDraft({ aspectRatio: nextRatio, resolution: nextResolution, officialQuality: nextQuality });+ }+ }, [official.model?.id, imageOptions, official.taskRunning, aspectRatio, resolution, officialQuality]);const [referenceFile, setReferenceFile] = useState<File | null>(null);const [referencePreview, setReferencePreview] = useState('');const resultVersion = session?.job.state.resultVersion;@@ -100,9 +116,9 @@ export default function ImageGenerationWorkspace(props: {const [error, setError] = useState('');const [notice, setNotice] = useState('');const characterCount = useMemo(() => [...prompt.trim()].length, [prompt]);- const selectedSize = sizes.find(item => item.value === size) ?? sizes[0]!;- const selectedQuality = qualities.find(item => item.value === quality) ?? qualities[1]!;- const selectedProvider = providers.find(item => item.value === provider) ?? providers[0]!;+ const selectedSize = imageOptions ? { value: resolution, zh: aspectRatio, en: aspectRatio, ratio: aspectRatio } : sizes.find(item => item.value === size) ?? sizes[0]!;+ const selectedQuality = imageOptions ? { zh: officialQuality || resolution || '默认', en: officialQuality || resolution || 'Default' } : qualities.find(item => item.value === quality) ?? qualities[1]!;+ const selectedProvider = official.official ? { zh: '官方服务', en: 'Official service' } : providers.find(item => item.value === provider) ?? providers[0]!;const resultVersions = useMemo(() => createImageResultVersions(session?.job.artifacts ?? [], session?.state.resultSnapshots),[session?.job.artifacts, session?.state.resultSnapshots]@@ -121,11 +137,14 @@ export default function ImageGenerationWorkspace(props: {const visibleError = error || runtimeError || previewError;const resultSettings = selectedResult?.state;const resultSize = readSize(resultSettings?.size);- const resultSizeOption = sizes.find(item => item.value === resultSize) ?? sizes[0]!;- const resultProvider = providers.find(item => item.value === readProvider(resultSettings?.provider))+ const resultSizeOption = resultSettings?.officialModels && typeof resultSettings.aspectRatio === 'string'+ ? { value: readString(resultSettings.resolution), zh: resultSettings.aspectRatio, en: resultSettings.aspectRatio, ratio: resultSettings.aspectRatio }+ : sizes.find(item => item.value === resultSize) ?? sizes[0]!;+ const resultProvider = resultSettings?.officialModels ? { zh: '官方服务', en: 'Official service' } : providers.find(item => item.value === readProvider(resultSettings?.provider))?? providers[0]!;- const resultQuality = qualities.find(item => item.value === readQuality(resultSettings?.quality))- ?? qualities[1]!;+ const resultQuality = resultSettings?.officialModels && typeof resultSettings.officialQuality === 'string' && resultSettings.officialQuality+ ? { zh: resultSettings.officialQuality, en: resultSettings.officialQuality }+ : qualities.find(item => item.value === readQuality(resultSettings?.quality)) ?? qualities[1]!;const supportsReferenceImage = session === null|| session.job.id.startsWith('pending:')|| session.job.templateVersion >= 2;@@ -163,6 +182,7 @@ export default function ImageGenerationWorkspace(props: {);useEffect(() => {+ if (official.official) return;if (session === null || !shouldLoadDefaultProvider) return;let active = true;void props.creatorServicesService?.getConfig().then(response => {@@ -181,7 +201,7 @@ export default function ImageGenerationWorkspace(props: {);}).catch(() => undefined);return () => { active = false; };- }, [count, props.creatorServicesService, session, shouldLoadDefaultProvider]);+ }, [count, props.creatorServicesService, session, shouldLoadDefaultProvider, official.official]);useEffect(() => {const { session, l } = previewContext.current;@@ -302,6 +322,7 @@ export default function ImageGenerationWorkspace(props: {}function updateProvider(value: ImageGenerationProvider) {+ if (official.official) return;setProvider(value);const nextCount = value === 'codex-native' ? 1 : count;if (nextCount !== count) setCount(nextCount);@@ -326,7 +347,7 @@ export default function ImageGenerationWorkspace(props: {}function updateCount(value: number) {- if (provider === 'codex-native' && value !== 1) return;+ if (!official.official && provider === 'codex-native' && value !== 1) return;setCount(value);session?.updateDraft({ candidateCount: value });setError('');@@ -351,6 +372,7 @@ export default function ImageGenerationWorkspace(props: {async function generate() {if (generating) return;+ if (official.official && !official.ready) { setError(l('官方图片服务暂不可用,请在个人中心检查连接状态', 'Official image service is unavailable. Check the connection in your personal center.')); return; }if (session === null) {setError(l('图像生成服务暂不可用,请检查 Runtime 连接',@@ -372,10 +394,11 @@ export default function ImageGenerationWorkspace(props: {setNotice('');session.updateDraft({prompt: prompt.trim(),- provider,+ provider: official.official ? 'openai' : provider,size,quality,- candidateCount: count+ candidateCount: count,+ ...(official.official ? { ...official.draftPatch, aspectRatio, resolution, officialQuality } : {})}, { semantic: true });try {await session.flush();@@ -596,7 +619,7 @@ export default function ImageGenerationWorkspace(props: {<p>{l('设置图片画幅、质量和一次生成数量', 'Set the image format, quality, and number of outputs')}</p></div></div>- <div className="media-generation-control">+ {official.official ? <OfficialModelField label={l('图片模型', 'Image model')} service={official} disabled={generating} /> : <div className="media-generation-control"><span>{l('图像服务', 'Image provider')}</span><div className="creator-tool-segmented" role="radiogroup" aria-label={l('图像服务', 'Image provider')}>{providers.map(item => (@@ -613,8 +636,20 @@ export default function ImageGenerationWorkspace(props: {)}</p>) : null}- </div>- <div className="media-generation-control">+ </div>}+ {imageOptions ? <>+ {[+ { key: 'aspectRatio', label: l('图片画幅', 'Image format'), values: imageOptions.aspectRatios, value: aspectRatio, set: setAspectRatio },+ { key: 'resolution', label: l('分辨率', 'Resolution'), values: imageOptions.resolutions, value: resolution, set: setResolution },+ { key: 'officialQuality', label: l('图片质量', 'Image quality'), values: imageOptions.qualities, value: officialQuality, set: setOfficialQuality }+ ].filter(option => option.values?.length).map(option => <label className="creator-tool-field" key={option.key}>+ <span>{option.label}</span>+ <select aria-label={option.label} value={option.value} disabled={official.taskRunning || !official.ready}+ onChange={event => { option.set(event.target.value); session?.updateDraft({ [option.key]: event.target.value }); }}>+ {option.values?.map(value => <option key={value} value={value}>{value}</option>)}+ </select>+ </label>)}+ </> : <><div className="media-generation-control"><span>{l('画幅', 'Format')}</span><div className="media-generation-option-grid" role="radiogroup" aria-label={l('图片画幅', 'Image format')}>{sizes.map(item => (@@ -635,11 +670,11 @@ export default function ImageGenerationWorkspace(props: {</button>))}</div>- </div>+ </div></>}<div className="media-generation-control"><span>{l('生成数量', 'Number of images')}</span><div className="creator-tool-segmented" role="radiogroup" aria-label={l('生成数量', 'Number of images')}>- {(provider === 'codex-native' ? [1] : [1, 2, 4]).map(value => (+ {(!official.official && provider === 'codex-native' ? [1] : [1, 2, 4]).map(value => (<button type="button" role="radio" aria-checked={count === value} aria-selected={count === value} key={value} onClick={() => updateCount(value)}>{value} {l('张', value === 1 ? 'image' : 'images')}</button>@@ -696,7 +731,7 @@ export default function ImageGenerationWorkspace(props: {))}</div><div className="media-generation-result-actions">- <button type="button" onClick={() => void generate()} disabled={generating}>+ <button type="button" onClick={() => void generate()} disabled={generating || (official.official && !official.ready)}>{generating ? <LoaderCircle className="smart-dubbing-spinner" size={15} /> : <RotateCcw size={15} />}{generating ? l('正在生成', 'Generating') : l('重新生成', 'Regenerate')}</button>@@ -710,7 +745,7 @@ export default function ImageGenerationWorkspace(props: {`${l(selectedProvider.zh, selectedProvider.en)} · ${count} 张 ${selectedSize.ratio} 图片 · ${l(selectedQuality.zh, selectedQuality.en)}质量`,`${selectedProvider.en} · ${count} ${selectedSize.ratio} images · ${selectedQuality.en} quality`)}</p>- <button className="creator-tool-primary" type="button" onClick={() => void generate()} disabled={generating}>+ <button className="creator-tool-primary" type="button" onClick={() => void generate()} disabled={generating || (official.official && !official.ready)}>{generating ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <Sparkles size={16} />}{generating ? l('正在生成', 'Generating') : l('开始生成', 'Generate')}</button>@@ -730,7 +765,7 @@ export default function ImageGenerationWorkspace(props: {] : [{ label: l('图像服务', 'Provider'), value: l(selectedProvider.zh, selectedProvider.en) },{ label: l('画幅', 'Format'), value: `${l(selectedSize.zh, selectedSize.en)} · ${selectedSize.ratio}` },- { label: l('分辨率', 'Resolution'), value: size },+ { label: l('分辨率', 'Resolution'), value: imageOptions ? resolution || l('默认', 'Default') : size },{ label: l('质量', 'Quality'), value: l(selectedQuality.zh, selectedQuality.en) },{ label: l('生成数量', 'Images'), value: String(count) }]}diff --git a/apps/web/src/features/dashboard/SmartDubbingWorkspace.tsx b/apps/web/src/features/dashboard/SmartDubbingWorkspace.tsxindex f2fbff69..4eaba7e6 100644--- a/apps/web/src/features/dashboard/SmartDubbingWorkspace.tsx+++ b/apps/web/src/features/dashboard/SmartDubbingWorkspace.tsx@@ -24,6 +24,7 @@ import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';import CreatorTaskSummary from './CreatorTaskSummary.js';import CreatorToolShell from './CreatorToolShell.js';+import { OfficialModelField, useOfficialServices } from './official-services.js';import {createCreatorArtifactObjectUrl,useOptionalCreatorSession@@ -64,6 +65,7 @@ export default function SmartDubbingWorkspace(props: {}) {const l = useLocalizedCopy();const session = useOptionalCreatorSession();+ const official = useOfficialServices('speech');const restoredResult = session?.job.artifacts.some(artifact => (artifact.kind === 'dubbed_audio' && artifact.status === 'completed')) === true;@@ -107,6 +109,12 @@ export default function SmartDubbingWorkspace(props: {) ? '#/settings?tab=ai-services§ion=tts' : undefined;useEffect(() => {+ if (official.official) {+ setProvider('openai'); setModel(official.model?.id ?? ''); setStyle('natural'); setSpeed(1);+ const voices = official.model?.voices ?? [];+ if (!voices.includes(voice)) { setVoice(voices[0] ?? ''); setVoiceName(voices[0] ?? ''); }+ return;+ }let active = true;if (props.creatorServicesService === null || props.creatorServicesService === undefined) {return () => { active = false; };@@ -138,7 +146,7 @@ export default function SmartDubbingWorkspace(props: {);});return () => { active = false; };- }, [props.creatorServicesService, session?.job.id]);+ }, [props.creatorServicesService, session?.job.id, official.official, official.model?.id]);useEffect(() => {if (session === null || result === undefined) {@@ -220,6 +228,7 @@ export default function SmartDubbingWorkspace(props: {}async function generate() {+ if (official.official && !official.ready) { setError(l('官方语音服务暂不可用,请在个人中心检查连接状态', 'Official speech service is unavailable. Check your personal center.')); return; }if (generating) return;if (session === null) {setError(l('智能配音服务暂不可用,请检查 Runtime 连接', 'Smart dubbing is unavailable. Check the Runtime connection.'));@@ -247,13 +256,14 @@ export default function SmartDubbingWorkspace(props: {setNotice('');session.updateDraft({text: text.trim(),- ttsProvider: provider,- ttsModel: model,+ ttsProvider: official.official ? 'openai' : provider,+ ttsModel: official.official ? official.model?.id ?? '' : model,voiceCode: voice,voiceName: voiceName || voice,style,speed,- format+ format,+ ...(official.official ? official.draftPatch : {})}, { semantic: true });try {await session.flush();@@ -427,10 +437,11 @@ export default function SmartDubbingWorkspace(props: {<div className="creator-tool-panel-heading"><div><h2 id="smart-dubbing-voice-title">{l('音色与表达', 'Voice and delivery')}</h2><p>{l('选择基础音色,再设置表达风格和语速', 'Choose a voice, delivery style, and speaking rate')}</p></div></div><div className="smart-dubbing-control-group"><span>{l('基础音色', 'Voice')}</span>+ {official.official ? <OfficialModelField label={l('语音合成模型', 'Speech model')} service={official} disabled={generating} /> :<div className="smart-dubbing-provider-row"><strong>{providerLabel(provider, l)}</strong><small>{model || l('本地语音服务', 'Local speech service')}</small>- </div>+ </div>}<TtsVoicePickerid="smart-dubbing-voice"provider={provider}@@ -450,7 +461,7 @@ export default function SmartDubbingWorkspace(props: {onVoiceResolved={selectedVoice => setVoiceName(selectedVoice.name)}/></div>- <div className="smart-dubbing-control-group">+ {!official.official ? <><div className="smart-dubbing-control-group"><span>{l('表达风格', 'Delivery style')}</span><div className="creator-tool-segmented smart-dubbing-style-options" role="radiogroup" aria-label={l('表达风格', 'Delivery style')}>{styles.map(item => <button type="button" role="radio" aria-checked={style === item.value} aria-selected={style === item.value} key={item.value} onClick={() => updateStyle(item.value)}>{l(item.zh, item.en)}</button>)}@@ -461,6 +472,7 @@ export default function SmartDubbingWorkspace(props: {<input type="range" min="0.75" max="1.25" step="0.05" value={speed} onChange={event => updateSpeed(Number(event.target.value))} /><small><span>0.75x</span><span>1.00x</span><span>1.25x</span></small></label>+ </> : null}<div className="smart-dubbing-control-group"><span>{l('音频格式', 'Audio format')}</span><div className="creator-tool-segmented smart-dubbing-format-options" role="radiogroup" aria-label={l('音频格式', 'Audio format')}>@@ -482,7 +494,7 @@ export default function SmartDubbingWorkspace(props: {<div><strong>{result.fileName}</strong><small>{formatBytes(result.size)} · {result.model}</small></div><audio controls src={audioUrl} aria-label={l('智能配音试听', 'AI dubbing preview')} /><div className="smart-dubbing-result-actions">- <button type="button" onClick={() => void generate()} disabled={generating}><RotateCcw size={15} strokeWidth={1.8} aria-hidden="true" />{l('重新生成', 'Regenerate')}</button>+ <button type="button" onClick={() => void generate()} disabled={generating || (official.official && !official.ready)}><RotateCcw size={15} strokeWidth={1.8} aria-hidden="true" />{l('重新生成', 'Regenerate')}</button><button className="creator-tool-primary" type="button" onClick={download}><Download size={15} strokeWidth={1.8} aria-hidden="true" />{l('下载音频', 'Download audio')}</button></div></div>@@ -491,7 +503,7 @@ export default function SmartDubbingWorkspace(props: {<span><Sparkles size={24} strokeWidth={1.6} aria-hidden="true" /></span><strong>{generating ? l('正在生成配音', 'Generating dubbing') : l('准备生成配音', 'Ready to generate dubbing')}</strong><p>{l('文案、音色和输出格式已经就绪', 'The script, voice, and output format are ready')}</p>- <button className="creator-tool-primary" type="button" onClick={() => void generate()} disabled={generating}>+ <button className="creator-tool-primary" type="button" onClick={() => void generate()} disabled={generating || (official.official && !official.ready)}>{generating ? <LoaderCircle className="smart-dubbing-spinner" size={16} strokeWidth={1.8} aria-hidden="true" /> : <Mic2 size={16} strokeWidth={1.8} aria-hidden="true" />}{generating ? l('正在生成', 'Generating') : l('开始生成', 'Generate')}</button>diff --git a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsxindex 9729d178..d12ca2ac 100644--- a/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx+++ b/apps/web/src/features/dashboard/StickmanVideoWorkspace.tsx@@ -33,6 +33,7 @@ import {} from 'lucide-react';import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';import { TtsVoicePicker } from '../../components/tts/TtsVoicePicker.js';+import { useOfficialServices } from './official-services.js';import NativeSelect from '../../components/forms/NativeSelect.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';@@ -161,6 +162,8 @@ export default function StickmanVideoWorkspace(props: {}) {const l = useLocalizedCopy();const session = useCreatorSession();+ const officialSpeech = useOfficialServices('speech');+ const officialImage = useOfficialServices('image');const { job, state } = session;const [activeStep, setActiveStep] = useState(0);const [notice, setNotice] = useState('');@@ -216,8 +219,8 @@ export default function StickmanVideoWorkspace(props: {const targetDurationSeconds = typeof state.targetDurationSeconds === 'number'? state.targetDurationSeconds: 30;- const ttsProvider = isTtsProvider(state.ttsProvider) ? state.ttsProvider : 'openai';- const ttsModel = typeof state.ttsModel === 'string' ? state.ttsModel : '';+ const ttsProvider = officialSpeech.official ? 'openai' : isTtsProvider(state.ttsProvider) ? state.ttsProvider : 'openai';+ const ttsModel = officialSpeech.official ? officialSpeech.model?.id ?? '' : typeof state.ttsModel === 'string' ? state.ttsModel : '';const voiceCode = typeof state.voiceCode === 'string' ? state.voiceCode : '';const voiceName = typeof state.voiceName === 'string' ? state.voiceName : voiceCode;const targetLanguage = typeof state.targetLanguage === 'string' ? state.targetLanguage : 'zh-CN';@@ -288,6 +291,15 @@ export default function StickmanVideoWorkspace(props: {}, [job.id, props.creatorService]);useEffect(() => {+ if (officialSpeech.official) {+ setTtsConfigurationStatus(officialSpeech.ready ? 'configured' : 'unavailable');+ setImageConfigurationStatus(!officialImage.ready ? 'unavailable' : officialImage.model?.capabilities.includes('edit') ? 'configured' : 'unsupported');+ if (scriptArtifact === undefined) {+ const voices = officialSpeech.model?.voices ?? [];+ session.updateDraft({ ttsProvider: 'openai', ttsModel: officialSpeech.model?.id ?? '', voiceCode: voices.includes(voiceCode) ? voiceCode : voices[0] ?? '', voiceName: voices.includes(voiceCode) ? voiceName : voices[0] ?? '' });+ }+ return;+ }let active = true;const service = props.creatorServicesService;if (service === null || service === undefined) {@@ -343,7 +355,7 @@ export default function StickmanVideoWorkspace(props: {return () => {active = false;};- }, [job.id, props.creatorServicesService, scriptArtifact?.id]);+ }, [job.id, props.creatorServicesService, scriptArtifact?.id, officialSpeech.official, officialSpeech.ready, officialSpeech.model?.id, officialImage.ready, officialImage.model?.id]);useEffect(() => {setActiveStep(current => (@@ -800,7 +812,7 @@ export default function StickmanVideoWorkspace(props: {ratio: '9:16',targetDurationSeconds: 30,targetLanguage: 'en-US',- ttsProvider: 'edge-tts'+ ttsProvider: officialSpeech.official ? 'openai' : 'edge-tts'}: { outputPreset: preset, ratio: '16:9' },{ semantic: true }diff --git a/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsxindex 065d8319..035ca7de 100644--- a/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx+++ b/apps/web/src/features/dashboard/VideoGenerationWorkspace.test.tsx@@ -5,7 +5,8 @@ import type {CreatorJob,CreatorJson,CreatorServicesConfigResponse,- CreatorStageRun+ CreatorStageRun,+ GatewayAccountState} from '@opencreator/protocol';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ReactNode } from 'react';@@ -13,8 +14,36 @@ import { LanguageProvider } from '../../i18n/LanguageProvider.js';import { LanguageSwitchControls } from '../../test/LanguageSwitchControls.js';import VideoGenerationWorkspace from './VideoGenerationWorkspace.js';import { CreatorSessionProvider, useCreatorSession } from './creator-session-store.js';+import { OfficialServicesContext } from './official-services.js';describe('VideoGenerationWorkspace', () => {+ it('shows model-native video sizes and durations beyond the custom provider presets', () => {+ const gatewayState: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: '1', models: [{ id: 'vendor/video', modality: 'video', capabilities: [], resolutions: ['1080p', '720p'], aspectRatios: ['16:9', '9:16'], durations: [3, 12] }], activationError: null };+ renderWorkspace(creatorJob({ state: { prompt: 'city', currentStep: 1, furthestStep: 1 } }), { gatewayState });+ const size = screen.getByRole('combobox', { name: '画幅' }) as HTMLSelectElement;+ expect([...size.options].map(option => option.value)).toEqual(['1080p@16:9', '1080p@9:16', '720p@16:9', '720p@9:16']);+ const duration = screen.getByRole('combobox', { name: '视频时长' }) as HTMLSelectElement;+ expect([...duration.options].map(option => option.value)).toEqual(['3', '12']);+ });+ it('shows only the official video model and supported parameters while signed in', async () => {+ const gatewayState: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', selectedModels: { video: 'bytedance/seedance-1-5-pro' }, models: [{ id: 'bytedance/seedance-1-5-pro', modality: 'video', capabilities: ['image_to_video'], sizes: ['1280x720', '720x1280'], durations: [4, 5] }], activationError: null };+ const getConfig = vi.fn();+ renderWorkspace(creatorJob({ state: { prompt: 'city skyline', provider: 'veo', model: 'veo-3.1-generate-preview', size: '1024x1024', duration: 10, currentStep: 1, furthestStep: 1 } }), { gatewayState, creatorServicesService: { getConfig } });+ expect(screen.getByLabelText('视频模型')).toHaveTextContent('seedance-1-5-pro');+ expect(screen.queryByRole('combobox', { name: '视频服务' })).not.toBeInTheDocument();+ expect(screen.queryByRole('combobox', { name: '模型版本' })).not.toBeInTheDocument();+ const durations = screen.getByRole('combobox', { name: '视频时长' }) as HTMLSelectElement;+ expect([...durations.options].map(option => option.value)).toEqual(['4', '5']);+ expect(screen.queryByRole('option', { name: /1024/ })).not.toBeInTheDocument();+ expect(getConfig).not.toHaveBeenCalled();+ });++ it('blocks official generation when account activation is unavailable', () => {+ renderWorkspace(creatorJob({ state: { prompt: 'city skyline', currentStep: 2, furthestStep: 2 } }), { gatewayState: null });+ expect(screen.getByRole('button', { name: '开始生成' })).toBeDisabled();+ expect(screen.queryByRole('combobox', { name: '视频服务' })).not.toBeInTheDocument();+ });+it('leaves the running screen and shows the true failure through read-only reconciliation without an SSE event', async () => {vi.useFakeTimers();const running = runningVideoJob({ phase: 'submitting', percent: 8 });@@ -692,6 +721,7 @@ function renderWorkspace(creatorServicesService?: { getConfig(): Promise<CreatorServicesConfigResponse> };language?: 'zh-CN' | 'en-US' | 'sv-SE';children?: ReactNode;+ gatewayState?: GatewayAccountState | null;} = {}) {const workspace = (options: typeof overrides) => (@@ -708,11 +738,13 @@ function renderWorkspace(runAgentTurn: vi.fn()} as never}>+ <OfficialServicesContext.Provider value={options.gatewayState}><VideoGenerationWorkspacecreatorServicesService={options.creatorServicesService as never}onBack={vi.fn()}/>{options.children}+ </OfficialServicesContext.Provider></CreatorSessionProvider></LanguageProvider>);diff --git a/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx b/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsxindex 372ad628..ad57bdd6 100644--- a/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoGenerationWorkspace.tsx@@ -1,6 +1,7 @@import {creatorPromptMaxLength,defaultVideoGenerationModels,+ gatewayVideoSizes,isPublicErrorFacts,readCreatorResultSnapshots,videoGenerationModelIds,@@ -28,6 +29,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { useLocalizedCopy, type LocalizeCopy } from '../../i18n/useLocalizedCopy.js';import { publicErrorReason } from '../issues/issue-catalog.js';import NativeSelect from '../../components/forms/NativeSelect.js';+import { OfficialModelField, useOfficialServices } from './official-services.js';import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';import CreatorResultVersionMenu from './CreatorResultVersionMenu.js';import { CreatorTaskProgressNotice } from './CreatorCollaborationPanel.js';@@ -92,6 +94,7 @@ export default function VideoGenerationWorkspace(props: {}) {const l = useLocalizedCopy();const session = useOptionalCreatorSession();+ const official = useOfficialServices('video');const mediaPreviewContextRef = useRef({ session, localize: l });mediaPreviewContextRef.current = { session, localize: l };const mediaPreviewJobId = session?.job.id;@@ -120,9 +123,9 @@ export default function VideoGenerationWorkspace(props: {initialProvider));const [model, setModel] = useState(() => readModel(session?.state.model, initialProvider));- const [size, setSize] = useState<VideoGenerationSize>(() => readSize(session?.state.size));+ const [size, setSize] = useState<VideoGenerationSize>(() => readSize(session?.state.size, official.official));const [duration, setDuration] = useState<VideoGenerationDuration>(() => (- readDuration(session?.state.duration, readProvider(session?.state.provider))+ readDuration(session?.state.duration, readProvider(session?.state.provider), official.official)));const resultVersion = session?.job.state.resultVersion;const [videoUrl, setVideoUrl] = useState('');@@ -131,14 +134,17 @@ export default function VideoGenerationWorkspace(props: {const [notice, setNotice] = useState('');const [taskControlPending, setTaskControlPending] = useState<'canceling' | 'resuming'>();const characterCount = useMemo(() => [...prompt.trim()].length, [prompt]);- const selectedSize = sizes.find(item => item.value === size) ?? sizes[0]!;- const selectedProvider = providers.find(item => item.value === provider) ?? providers[0]!;+ const selectedProvider = official.official ? { zh: '官方服务', en: 'Official service' } : providers.find(item => item.value === provider) ?? providers[0]!;const modelOptions = useMemo(() => createVideoModelOptions(provider, modelDefaults[provider], model),[model, modelDefaults, provider]);- const selectedModelLabel = videoModelLabel(model);- const durations = providerDurations[provider];+ const activeModel = official.official ? official.model?.id ?? '' : model;+ const selectedModelLabel = videoModelLabel(activeModel);+ const availableSizes = official.official ? gatewayVideoSizes(official.model).map(videoSizeOption) : sizes;+ const selectedSize = availableSizes.find(item => item.value === size) ?? videoSizeOption(size);+ const durations = official.official ? official.model?.durations ?? [] : providerDurations[provider];+ const serviceReady = !official.official || (official.ready && availableSizes.length > 0 && durations.length > 0);const resultVersions = useMemo(() => createVideoResultVersions(session?.job.artifacts ?? [], session?.state.resultSnapshots),[session?.job.artifacts, session?.state.resultSnapshots]@@ -184,13 +190,13 @@ export default function VideoGenerationWorkspace(props: {const referencePreviewArtifactId = referenceImageFile === undefined? activeReferenceArtifact?.id: undefined;- const followsReferenceRatio = provider === 'seedance' && Boolean(currentReferenceName);+ const followsReferenceRatio = !official.official && provider === 'seedance' && Boolean(currentReferenceName);const resultSettings = selectedResult?.state;- const resultProvider = providers.find(item => (+ const resultProvider = resultSettings?.officialModels ? { value: 'seedance' as const, zh: '官方服务', en: 'Official service' } : providers.find(item => (item.value === readProvider(resultSettings?.provider))) ?? providers[0]!;- const resultSize = readSize(resultSettings?.size);- const resultSizeOption = sizes.find(item => item.value === resultSize) ?? sizes[0]!;+ const resultSize = readSize(resultSettings?.size, !!resultSettings?.officialModels);+ const resultSizeOption = videoSizeOption(resultSize);const resultWidth = readArtifactNumber(selectedResult?.artifact, 'width');const resultHeight = readArtifactNumber(selectedResult?.artifact, 'height');const resultRatio = resultWidth !== undefined && resultHeight !== undefined@@ -198,13 +204,13 @@ export default function VideoGenerationWorkspace(props: {: resultSizeOption.ratio;const resultResolution = resultWidth !== undefined && resultHeight !== undefined? `${resultWidth}x${resultHeight}`- : resultSize;+ : videoSizeDisplay(resultSize);const resultFormatLabel = resultWidth !== undefined && resultHeight !== undefined? videoFormatLabel(resultWidth, resultHeight, l): l(resultSizeOption.zh, resultSizeOption.en);const resultArtifactDuration = readVideoDuration(selectedResult?.artifact.metadata.duration);const resultDuration = resultArtifactDuration === undefined- ? readDuration(resultSettings?.duration, resultProvider.value)+ ? readDuration(resultSettings?.duration, resultProvider.value, !!resultSettings?.officialModels): Math.round(resultArtifactDuration * 100) / 100;const resultModel = readArtifactString(selectedResult?.artifact, 'model')?? readOptionalModel(resultSettings?.model)@@ -212,6 +218,7 @@ export default function VideoGenerationWorkspace(props: {const resultModelLabel = videoModelLabel(resultModel);useEffect(() => {+ if (official.official) return;if (props.creatorServicesService === null || props.creatorServicesService === undefined) {return undefined;}@@ -248,7 +255,13 @@ export default function VideoGenerationWorkspace(props: {return () => {active = false;};- }, [props.creatorServicesService, session?.job.id]);+ }, [props.creatorServicesService, session?.job.id, official.official]);++ useEffect(() => {+ if (!official.official) return;+ if (availableSizes.length && !availableSizes.some(item => item.value === size)) setSize(availableSizes[0]!.value);+ if (durations.length && !durations.includes(duration)) setDuration(durations[0]!);+ }, [official.official, activeModel, size, duration, availableSizes.map(item => item.value).join(','), durations.join(',')]);useEffect(() => {const { session, localize } = mediaPreviewContextRef.current;@@ -358,6 +371,7 @@ export default function VideoGenerationWorkspace(props: {}function updateProvider(nextProvider: VideoGenerationProvider) {+ if (official.official) return;settingsRevision.current += 1;const nextDurations = providerDurations[nextProvider];const nextDuration = nextDurations.includes(duration) ? duration : nextDurations[0]!;@@ -374,6 +388,7 @@ export default function VideoGenerationWorkspace(props: {}function updateModel(nextModel: string) {+ if (official.official) { official.selectModel(nextModel); return; }settingsRevision.current += 1;setModel(nextModel);session?.updateDraft({ model: nextModel });@@ -420,6 +435,7 @@ export default function VideoGenerationWorkspace(props: {async function generate() {if (generating) return;+ if (!serviceReady) { setError(l('官方视频服务暂不可用,请在个人中心检查连接状态', 'Official video service is unavailable. Check the connection in your personal center.')); return; }if (session === null) {setError(l('视频生成服务暂不可用,请检查 Runtime 连接',@@ -436,10 +452,11 @@ export default function VideoGenerationWorkspace(props: {setNotice('');session.updateDraft({prompt: prompt.trim(),- provider,- model,+ provider: official.official ? 'seedance' : provider,+ model: activeModel,size,- duration+ duration,+ ...(official.official ? official.draftPatch : {})}, { semantic: true });try {await session.flush();@@ -707,7 +724,8 @@ export default function VideoGenerationWorkspace(props: {<p>{l('设置视频服务、模型版本、画幅、分辨率和时长', 'Set the video provider, model version, format, resolution, and duration')}</p></div></div>- <div className="video-generation-settings-grid">+ <div className={`video-generation-settings-grid${official.official ? ' is-official' : ''}`}>+ {official.official ? <OfficialModelField label={l('视频模型', 'Video model')} service={official} disabled={generating} /> : <><label className="creator-tool-field"><span>{l('视频服务', 'Video provider')}</span><NativeSelect value={provider} onChange={event => updateProvider(event.target.value as VideoGenerationProvider)}>@@ -722,11 +740,12 @@ export default function VideoGenerationWorkspace(props: {))}</NativeSelect></label>+ </>}<label className="creator-tool-field"><span>{l('画幅', 'Format')}</span><NativeSelectvalue={size}- disabled={followsReferenceRatio}+ disabled={followsReferenceRatio || !serviceReady}title={followsReferenceRatio? l('Seedance 参考图模式会跟随参考图画幅', 'Seedance matches the reference image aspect ratio'): undefined}@@ -734,13 +753,13 @@ export default function VideoGenerationWorkspace(props: {>{followsReferenceRatio ? (<option value={size}>{l('跟随参考图', 'Match reference image')}</option>- ) : sizes.map(item => <option key={item.value} value={item.value}>{l(item.zh, item.en)} · {item.ratio} · {item.value}</option>)}+ ) : availableSizes.length ? availableSizes.map(item => <option key={item.value} value={item.value}>{item.value.includes('@') ? videoSizeDisplay(item.value) : `${l(item.zh, item.en)} · ${item.ratio} · ${item.value}`}</option>) : <option value="">{l('暂不可用', 'Unavailable')}</option>}</NativeSelect></label><label className="creator-tool-field"><span>{l('视频时长', 'Video duration')}</span>- <NativeSelect value={duration} onChange={event => updateDuration(Number(event.target.value) as VideoGenerationDuration)}>- {durations.map(value => <option key={value} value={value}>{value} {l('秒', 'seconds')}</option>)}+ <NativeSelect value={duration} disabled={!serviceReady} onChange={event => updateDuration(Number(event.target.value) as VideoGenerationDuration)}>+ {durations.length ? durations.map(value => <option key={value} value={value}>{value} {l('秒', 'seconds')}</option>) : <option value="">{l('暂不可用', 'Unavailable')}</option>}</NativeSelect></label></div>@@ -808,7 +827,7 @@ export default function VideoGenerationWorkspace(props: {</small></span><div>- <button type="button" onClick={() => void generate()} disabled={generating}>+ <button type="button" onClick={() => void generate()} disabled={generating || !serviceReady}>{generating? <LoaderCircle className="smart-dubbing-spinner" size={15} />: <RotateCcw size={15} />}@@ -833,10 +852,10 @@ export default function VideoGenerationWorkspace(props: {<p>{l(`${l(selectedProvider.zh, selectedProvider.en)} · ${selectedModelLabel} · ${followsReferenceRatio? l('跟随参考图', 'Match reference image')- : selectedSize.ratio} · ${duration} 秒${followsReferenceRatio ? '' : ` · ${size}`}`,+ : selectedSize.ratio} · ${duration} 秒${followsReferenceRatio ? '' : ` · ${videoSizeDisplay(size)}`}`,`${selectedProvider.en} · ${selectedModelLabel} · ${followsReferenceRatio? 'Match reference image'- : selectedSize.ratio} · ${duration} seconds${followsReferenceRatio ? '' : ` · ${size}`}`+ : selectedSize.ratio} · ${duration} seconds${followsReferenceRatio ? '' : ` · ${videoSizeDisplay(size)}`}`)}</p>{resumable ? (<button className="creator-tool-primary" type="button" onClick={() => void resumeTask()} disabled={taskControlPending !== undefined}>@@ -901,12 +920,12 @@ export default function VideoGenerationWorkspace(props: {{currentStep === 0 ? l('返回', 'Back') : l('上一步', 'Back')}</button>{currentStep < 2 ? (- <button className="video-translation-primary-action" type="button" onClick={nextStep}>+ <button className="video-translation-primary-action" type="button" disabled={currentStep === 1 && !serviceReady} onClick={nextStep}>{l('继续', 'Continue')}</button>) : null}{currentStep === 2 && selectedResult === undefined && !generating && !resumable ? (- <button className="video-translation-primary-action" type="button" onClick={() => void generate()}>+ <button className="video-translation-primary-action" type="button" disabled={!serviceReady} onClick={() => void generate()}><Sparkles size={16} />{l('开始生成', 'Generate')}</button>@@ -1069,14 +1088,30 @@ function videoModelLabel(model: string): string {return modelLabels[model] ?? model;}-function readSize(value: CreatorJson | undefined): VideoGenerationSize {+function videoSizeOption(value: string): typeof sizes[number] {+ const known = sizes.find(item => item.value === value);+ if (known) return known;+ const [resolution, ratio] = value.split('@');+ const match = /^(\d+)x(\d+)$/.exec(value);+ const width = Number(match?.[1]), height = Number(match?.[2]);+ const gcd = (a: number, b: number): number => b ? gcd(b, a % b) : a;+ const divisor = gcd(width, height);+ return { value: value as VideoGenerationSize, zh: resolution!, en: resolution!, ratio: ratio ?? (divisor ? `${width / divisor}:${height / divisor}` : '') };+}++function videoSizeDisplay(value: string): string { return value.replace('@', ' · '); }++function readSize(value: CreatorJson | undefined, official = false): VideoGenerationSize {+ if (official && typeof value === 'string' && /^(?:\d+x\d+|[A-Za-z0-9._-]+@\d+:\d+)$/.test(value)) return value as VideoGenerationSize;return value === '720x1280' || value === '1024x1024' ? value : '1280x720';}function readDuration(value: CreatorJson | undefined,- provider: VideoGenerationProvider+ provider: VideoGenerationProvider,+ official = false): VideoGenerationDuration {+ if (official && typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 600) return value;const allowed = providerDurations[provider];return typeof value === 'number' && allowed.includes(value as VideoGenerationDuration)? value as VideoGenerationDurationdiff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsxindex 064cb3db..24df5dd0 100644--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx@@ -21,6 +21,7 @@ import {Square} from 'lucide-react';import { TtsVoicePicker } from '../../components/tts/TtsVoicePicker.js';+import { OfficialModelField, useOfficialServices } from './official-services.js';import type { RuntimeDependenciesController } from '../../app/use-runtime-dependencies.js';import { LocalTranscriptionNotice } from './LocalTranscriptionNotice.js';import { useLocalizedCopy, type LocalizeCopy } from '../../i18n/useLocalizedCopy.js';@@ -1495,6 +1496,7 @@ export default function VideoTranslationWorkspace(props: {}) {const l = useLocalizedCopy();const creatorSession = useOptionalCreatorSession();+ const officialSpeech = useOfficialServices('speech');const mediaPreviewContextRef = useRef({ session: creatorSession, localize: l });mediaPreviewContextRef.current = { session: creatorSession, localize: l };const mediaPreviewJobId = creatorSession?.job.id;@@ -1719,6 +1721,12 @@ export default function VideoTranslationWorkspace(props: {}, [creatorSession?.job.id, creatorSession?.job.revision]);useEffect(() => {+ if (officialSpeech.official) {+ setTtsProvider('openai'); setTtsModel(officialSpeech.model?.id ?? '');+ const voices = officialSpeech.model?.voices ?? [];+ if (!voices.includes(voiceCode)) { setVoiceCode(voices[0] ?? ''); setVoiceName(voices[0] ?? ''); }+ return;+ }let active = true;if (props.creatorServicesService === null || props.creatorServicesService === undefined) {return () => {@@ -1758,7 +1766,7 @@ export default function VideoTranslationWorkspace(props: {return () => {active = false;};- }, [creatorSession?.job.id, props.creatorServicesService]);+ }, [creatorSession?.job.id, props.creatorServicesService, officialSpeech.official, officialSpeech.model?.id]);useEffect(() => {if (creatorSession === null) return;@@ -3513,10 +3521,10 @@ export default function VideoTranslationWorkspace(props: {</div>{dubbing ? (<div className="video-translation-option-content">- <div className="video-translation-voice-source">+ {officialSpeech.official ? <OfficialModelField label={l('语音合成模型', 'Speech model')} service={officialSpeech} /> : <div className="video-translation-voice-source"><strong>{ttsProviderLabel(ttsProvider, l)}</strong><small>{ttsModel || l('本地语音服务', 'Local speech service')}</small>- </div>+ </div>}<TtsVoicePickerid="video-translation-voice"provider={ttsProvider}diff --git a/apps/web/src/features/dashboard/official-services.css b/apps/web/src/features/dashboard/official-services.cssnew file mode 100644index 00000000..9ec082da--- /dev/null+++ b/apps/web/src/features/dashboard/official-services.css@@ -0,0 +1,22 @@+.official-model-value {+ width: 100%;+ min-width: 0;+ min-height: 40px;+ display: flex;+ align-items: center;+ padding: 8px 12px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: var(--surface-2);+ color: var(--text);+ font-size: 13px;+ overflow-wrap: anywhere;+}++.video-generation-settings-grid.is-official {+ grid-template-columns: repeat(3, minmax(0, 1fr));+}++@media (max-width: 760px) {+ .video-generation-settings-grid.is-official { grid-template-columns: minmax(0, 1fr); }+}diff --git a/apps/web/src/features/dashboard/official-services.tsx b/apps/web/src/features/dashboard/official-services.tsxnew file mode 100644index 00000000..6a871bcc--- /dev/null+++ b/apps/web/src/features/dashboard/official-services.tsx@@ -0,0 +1,48 @@+import { createContext, useContext, useEffect } from 'react';+import type { CreatorJson, GatewayAccountState, GatewayModel } from '@opencreator/protocol';+import OfficialModelSelect, { officialModelLabel } from '../../components/forms/OfficialModelSelect.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import { useOptionalCreatorSession } from './creator-session-store.js';+import './official-services.css';++export const OfficialServicesContext = createContext<GatewayAccountState | null | undefined>(undefined);++export function useOfficialServices(modality: GatewayModel['modality']) {+ const state = useContext(OfficialServicesContext);+ const session = useOptionalCreatorSession();+ const official = state === null || (state !== undefined && (state.source === 'gateway' || state.authState !== 'signed_out'));+ const models = state?.models.filter(model => model.modality === modality && (modality !== 'text' || model.capabilities.includes('responses'))) ?? [];+ const choices = session?.state.officialModels;+ const saved = choices && typeof choices === 'object' && !Array.isArray(choices) ? choices[modality] : undefined;+ const taskRunning = session?.job.status === 'running' || session?.job.stages.some(stage => stage.status === 'queued' || stage.status === 'running');+ const taskChoices: Record<string, CreatorJson> = {};+ for (const candidate of state?.models ?? []) {+ if (candidate.modality === 'text' && !candidate.capabilities.includes('responses')) continue;+ const taskChoice = choices && typeof choices === 'object' && !Array.isArray(choices) ? choices[candidate.modality] : undefined;+ if (!(candidate.modality in taskChoices) || candidate.id === state?.selectedModels?.[candidate.modality] || candidate.id === taskChoice) taskChoices[candidate.modality] = candidate.id;+ }+ if (choices && typeof choices === 'object' && !Array.isArray(choices)) Object.assign(taskChoices, choices);+ const selected = saved ?? state?.selectedModels?.[modality];+ const model = models.find(candidate => candidate.id === selected) ?? models[0];+ const ready = state?.authState === 'signed_in' && state.activationState === 'ready' && model !== undefined;+ useEffect(() => {+ if (ready && official && !taskRunning && model && saved !== model.id) selectModel(model.id);+ }, [official, ready, saved, model?.id, session?.job.id, taskRunning]);+ function selectModel(id: string) {+ if (!ready || taskRunning || !models.some(candidate => candidate.id === id)) return;+ session?.updateDraft({ officialModels: { ...taskChoices, [modality]: id } });+ }+ const draftPatch: Record<string, CreatorJson> = model ? { officialModels: { ...taskChoices, [modality]: model.id } } : {};+ return { official, ready, models, model, selectModel, draftPatch, taskRunning };+}++export function OfficialModelField(props: { label: string; service: ReturnType<typeof useOfficialServices>; disabled?: boolean }) {+ const l = useLocalizedCopy();+ const { models, model, ready } = props.service;+ const label = model ? officialModelLabel(model, l('自动选择', 'Automatic')) : l('暂不可用', 'Unavailable');+ return <label className="creator-tool-field">+ <span>{props.label}</span>+ {models.length === 1 && ready ? <output className="official-model-value" aria-label={props.label}>{label}</output> :+ <OfficialModelSelect label={props.label} models={models} value={model?.id ?? ''} disabled={!ready || props.disabled || props.service.taskRunning} onChange={props.service.selectModel} />}+ </label>;+}diff --git a/apps/web/src/features/issues/issue-catalog.test.ts b/apps/web/src/features/issues/issue-catalog.test.tsindex 199b80a4..c74eb250 100644--- a/apps/web/src/features/issues/issue-catalog.test.ts+++ b/apps/web/src/features/issues/issue-catalog.test.ts@@ -6,6 +6,31 @@ const raw = '后台原文:操作无法完成';const issue = normalizePageIssue('runtime', 'creator.prepare', new Error(raw), raw);describe('localized issue copy', () => {+ it.each([+ ['audio_no_speech', '音频为静音或音量过低', '检查原音频和音量'],+ ['audio_transcription_empty', '尚不能确认音频是否含有语音', '换一个语音识别模型核验'],+ ['audio_transcription_invalid_response', '返回了无效结果', '检查服务返回的错误'],+ ['audio_transcription_timestamps_missing', '未提供可用的字幕时间戳', '支持字幕时间戳'],+ ['audio_transcription_api_failed', '语音识别服务调用失败', '检查连接、模型权限或配额']+ ])('explains %s using the classified evidence', (code, summary, guidance) => {+ const next = { ...issue, code };+ const conversation = issueConversationText(next, 'zh-CN');+ expect(conversation.message).toContain(summary);+ expect(conversation.nextStep).toContain(guidance);+ if (code === 'audio_transcription_empty') {+ expect(conversation.message).not.toContain('音频为静音');+ expect(conversation.message).not.toContain('未提供可用的字幕时间戳');+ expect(conversation.message).not.toContain('服务调用失败');+ }+ });+ it('preserves transcription guidance through a generic stage error', () => {+ const next = { ...issue, code: 'creator_stage_failed', publicFacts: {+ kind: 'unknown' as const, upstreamCode: 'audio_transcription_empty'+ } };+ expect(issueConversationText(next, 'zh-CN').nextStep).toContain('换一个语音识别模型核验');+ expect(presentIssue(next, 'en-US').description).toContain('whether the audio contains speech is still unconfirmed');+ expect(presentIssue(next, 'sv-SE').description).not.toMatch(/\p{Script=Han}/u);+ });it('shows the filesystem failure code and actual cause with relevant retry guidance', () => {const next = { ...issue, source: 'stage' as const, code: 'ERR_FS_FILE_TOO_LARGE', publicFacts: {kind: 'storage' as const, upstreamCode: 'ERR_FS_FILE_TOO_LARGE',diff --git a/apps/web/src/features/issues/issue-catalog.ts b/apps/web/src/features/issues/issue-catalog.tsindex 0bea070b..a4a35183 100644--- a/apps/web/src/features/issues/issue-catalog.ts+++ b/apps/web/src/features/issues/issue-catalog.ts@@ -65,6 +65,8 @@ function issuePublicFacts(issue: OpenCreatorIssue): PublicErrorFacts | undefined}function localizedIssueSummary(issue: OpenCreatorIssue, localize: LocalizeCopy): string {+ const transcription = transcriptionIssueCopy(issue.code, localize) ?? transcriptionIssueCopy(issue.publicFacts?.upstreamCode, localize);+ if (transcription !== undefined) return transcription.message;if (issue.code === 'ERR_FS_FILE_TOO_LARGE' || issue.publicFacts?.upstreamCode === 'ERR_FS_FILE_TOO_LARGE') return localize('本地文件读取超过大小限制。', 'The local file exceeded the read-size limit.', 'Den lokala filen överskred storleksgränsen för läsning.');if (issue.stageId === 'prepare-source-video') return localize('原视频准备失败,已有字幕不受影响。', 'Source video preparation failed; existing subtitles are unchanged.', 'Förberedelsen av originalvideon misslyckades; befintliga undertexter är oförändrade.');if (issue.operation === 'creator.agent-turn') return localize('Agent 未能完成诊断,请查看问题详情后重试。', 'The Agent could not complete the diagnosis. Review the issue details and retry.', 'Agent kunde inte slutföra diagnostiken. Läs probleminformationen och försök igen.');@@ -77,6 +79,38 @@ function localizedIssueSummary(issue: OpenCreatorIssue, localize: LocalizeCopy):return localize(entry.zh, entry.en);}+function transcriptionIssueCopy(code: string | undefined, localize: LocalizeCopy): { message: string; nextStep: string } | undefined {+ switch (code) {+ case 'audio_no_speech':+ return {+ message: localize('音频为静音或音量过低,未识别到可用语音。', 'The audio is silent or extremely quiet; no usable speech was transcribed.', 'Ljudet är tyst eller mycket svagt; inget användbart tal transkriberades.'),+ nextStep: localize('请检查原音频和音量,或改用已有字幕。', 'Check the source audio and volume, or use existing subtitles.', 'Kontrollera originalljudet och volymen, eller använd befintliga undertexter.')+ };+ case 'audio_transcription_empty':+ return {+ message: localize('转录服务返回了空结果,尚不能确认音频是否含有语音。', 'The transcription service returned an empty result; whether the audio contains speech is still unconfirmed.', 'Transkriptionstjänsten returnerade ett tomt resultat; det är ännu oklart om ljudet innehåller tal.'),+ nextStep: localize('请先确认原音频是否有讲话;若有,可换一个语音识别模型核验。音乐或噪声可能没有可翻译的文字。', 'Check whether the source audio contains speech. If it does, verify with another recognition model. Music or noise may have no text to translate.', 'Kontrollera om originalljudet innehåller tal. Prova i så fall en annan taligenkänningsmodell. Musik eller brus kan sakna text att översätta.')+ };+ case 'audio_transcription_invalid_response':+ return {+ message: localize('语音识别服务返回了无效结果。', 'The speech recognition service returned an invalid response.', 'Taligenkänningstjänsten returnerade ett ogiltigt svar.'),+ nextStep: localize('请检查服务返回的错误,或更换语音识别模型后重试。', 'Review the provider error, or choose another speech recognition model and retry.', 'Kontrollera leverantörens fel, eller välj en annan taligenkänningsmodell och försök igen.')+ };+ case 'audio_transcription_timestamps_missing':+ return {+ message: localize('已识别到文字,但当前模型未提供可用的字幕时间戳。', 'Text was recognized, but the current model did not provide usable subtitle timestamps.', 'Text identifierades, men den aktuella modellen gav inga användbara tidsstämplar för undertexter.'),+ nextStep: localize('请选择支持字幕时间戳的语音识别模型后重试。', 'Choose a speech recognition model that supports subtitle timestamps and retry.', 'Välj en taligenkänningsmodell som stöder tidsstämplar för undertexter och försök igen.')+ };+ case 'audio_transcription_api_failed':+ return {+ message: localize('语音识别服务调用失败。', 'The speech recognition request failed.', 'Anropet till taligenkänningstjänsten misslyckades.'),+ nextStep: localize('请根据服务返回的原因检查连接、模型权限或配额后重试。', 'Use the provider reason to check the connection, model access or quota, then retry.', 'Kontrollera anslutningen, modellbehörigheten eller kvoten utifrån leverantörens felorsak och försök igen.')+ };+ default:+ return undefined;+ }+}+export function publicErrorReason(input: PublicErrorFacts, language: AppLanguage | LocalizeCopy): string {const facts = sanitizePublicErrorFacts(input);const localize = typeof language === 'function' ? language : createLocalizedCopy(language);@@ -143,7 +177,9 @@ export function issueConversationText(const detail = presentIssue(issue, language).description;const localize = createLocalizedCopy(language);const facts = issuePublicFacts(issue);- const nextStep = issue.code === 'ERR_FS_FILE_TOO_LARGE' || facts?.upstreamCode === 'ERR_FS_FILE_TOO_LARGE'+ const transcription = transcriptionIssueCopy(issue.code, localize) ?? transcriptionIssueCopy(facts?.upstreamCode, localize);+ const nextStep = transcription !== undefined ? transcription.nextStep+ : issue.code === 'ERR_FS_FILE_TOO_LARGE' || facts?.upstreamCode === 'ERR_FS_FILE_TOO_LARGE'? localize('请重试当前步骤;如果仍然失败,可先切分视频,并向 Agent 提供文件大小和诊断编号。', 'Retry the current step. If it still fails, split the video and provide the file size and diagnostic ID to the Agent.', 'Försök igen. Om det fortfarande misslyckas, dela videon och ge filstorleken och diagnostik-ID till Agent.'): issue.publicFacts?.upstreamCode === 'IMAGE_REFERENCE_MISSING'? localize('请先上传参考图;如需纯文字生图,请移除对上传图片或原图的要求后重试。', 'Upload a reference image, or remove the uploaded/original image requirements for text-only generation, then retry.', 'Ladda upp en referensbild, eller ta bort kraven på en uppladdad eller ursprunglig bild för textgenerering och försök igen.')diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsxindex 81f94bc6..35892fae 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.test.tsx@@ -181,15 +181,12 @@ describe('CreatorServicesSettingsView', () => {await user.clear(screen.getByLabelText('Base URL'));await user.type(screen.getByLabelText('Base URL'), 'not-a-url');await user.clear(screen.getByLabelText('模型'));- await user.type(screen.getByLabelText('代理地址'), 'socks5://127.0.0.1:1080');await user.click(screen.getByRole('button', { name: '保存配置' }));expect(screen.getByLabelText('Base URL')).toHaveAttribute('aria-invalid', 'true');expect(screen.getByText('请输入有效的 HTTP 或 HTTPS 地址')).toBeInTheDocument();expect(screen.getByLabelText('模型')).toHaveAttribute('aria-invalid', 'true');expect(screen.getByText('模型不能为空')).toBeInTheDocument();- expect(screen.getByLabelText('代理地址')).toHaveAttribute('aria-invalid', 'true');- expect(screen.getByText('请输入有效的 HTTP 或 HTTPS 代理地址')).toBeInTheDocument();expect(modelService.updateCodexProvider).not.toHaveBeenCalled();});diff --git a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx b/apps/web/src/features/settings/CreatorServicesSettingsView.tsxindex e1d87c36..2657f9f5 100644--- a/apps/web/src/features/settings/CreatorServicesSettingsView.tsx+++ b/apps/web/src/features/settings/CreatorServicesSettingsView.tsx@@ -615,22 +615,6 @@ function TextModelSettings(props: SettingsGroupProps & {</p>)}</SettingsFieldset>- <SettingsFieldset- title={l('网络', 'Network')}- description={l('可选。为模型和媒体请求指定 HTTP 代理。', 'Optional. Route model and media requests through an HTTP proxy.')}- >- <TextField- id="creator-services-proxy"- label={l('代理地址', 'Proxy URL')}- value={props.config.proxy}- placeholder="http://127.0.0.1:7890"- error={props.fieldErrors.proxy}- onChange={value => props.update(config => {- config.proxy = value;- })}- wide- />- </SettingsFieldset></>);}diff --git a/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsx b/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsxnew file mode 100644index 00000000..04bb2bed--- /dev/null+++ b/apps/web/src/features/settings/GatewayAccountSettingsView.test.tsx@@ -0,0 +1,87 @@+import { act, render, screen, cleanup, waitFor } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';+import { afterEach, expect, it, vi } from 'vitest';+import { LanguageProvider } from '../../i18n/LanguageProvider.js';+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);+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() };+}+it('shows an expired session explicitly and keeps reauthorization available', async () => {+ const value = service();+ vi.mocked(value.getState).mockResolvedValue({ ...state, authState: 'expired', activationState: 'inactive' });+ render(<LanguageProvider initialPreference="zh-CN"><GatewayAccountSettingsView service={value}/></LanguageProvider>);+ expect(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 () => {+ 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(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');+});+it('shows refund review and prevents new recharge', 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();+});+it('keeps the last balance marked stale on failure and recovers through retry', async () => {+ const value = service();+ render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value}/></LanguageProvider>);+ 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(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());+});+it('refreshes the purchased balance on application focus', async () => {+ const value = service();+ render(<LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value}/></LanguageProvider>);+ expect(await screen.findByText('123')).toBeInTheDocument();+ vi.mocked(value.getSummary).mockResolvedValue({ balance: { availableUnits: '2500000000', reservedUnits: '0', periodEnd: null, asOf: '2026-10-07T01:00:00Z' }, subscription: null, billingAvailable: true });+ await act(async () => window.dispatchEvent(new Event('focus')));+ expect(await screen.findByText('2500')).toBeInTheDocument();+});+it('rejects invalid recharge 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();+});+it('reconnects a signed-in account without manual provider fields', async () => {+ const value = service(); const changed = vi.fn();+ vi.mocked(value.getState).mockResolvedValue({ ...state, activationState: 'blocked' });+ vi.mocked(value.activate).mockResolvedValue(state);+ render(<LanguageProvider initialPreference="zh-CN"><GatewayAccountSettingsView variant="login" service={value} onStateChange={changed}/></LanguageProvider>);+ expect(await screen.findByText('已登录,模型服务暂不可用')).toBeInTheDocument();+ expect(screen.queryByText('Base URL')).not.toBeInTheDocument();+ expect(screen.queryByText('API Key')).not.toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '重新连接' }));+ await waitFor(() => expect(changed).toHaveBeenLastCalledWith(state));+});diff --git a/apps/web/src/features/settings/GatewayAccountSettingsView.tsx b/apps/web/src/features/settings/GatewayAccountSettingsView.tsxnew file mode 100644index 00000000..fd2db4b1--- /dev/null+++ b/apps/web/src/features/settings/GatewayAccountSettingsView.tsx@@ -0,0 +1,113 @@+import { useEffect, useRef, useState } from 'react';+import { CreditCard, ExternalLink, LogIn, LogOut, 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';+import { ApiClientError } from '../../runtime/errors.js';+import './gateway-account-settings.css';++export function formatGatewayCredits(units: string) {+ if (!/^\d+$/.test(units)) return '?';+ const value = BigInt(units);+ const fraction = (value % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '');+ return `${value / 1_000_000n}${fraction ? `.${fraction}` : ''}`;+}++export function GatewayAccountSettingsView(props: {+ service: GatewayAccountSettingsService | null;+ variant?: 'settings' | 'login' | 'profile';+ accountState?: GatewayAccountState;+ signInRequest?: number;+ onSignInCanceled?(): void;+ openExternal?(url: string): Promise<void> | void;+ onStateChange?(state: GatewayAccountState): void;+ onBusyChange?(busy: boolean): void;+ onOpenSubscription?(): void;+}) {+ const l = useLocalizedCopy();+ const [state, setState] = useState<GatewayAccountState | undefined>(props.accountState);+ const [authorization, setAuthorization] = useState<GatewayAuthorization>();+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const callback = useRef(props.onStateChange); callback.current = props.onStateChange;+ const alive = useRef(true);+ const busyRef = useRef(false);+ const refreshSequence = useRef(0);+ const lastSignInRequest = useRef(0);+ 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]);++ function update(next: GatewayAccountState) {+ if (!alive.current) return;+ refreshSequence.current++;+ setState(next); callback.current?.(next);+ if (next.authState !== 'authorizing') setAuthorization(undefined);+ }+ async function refresh() {+ const request = ++refreshSequence.current;+ if (service) {+ const next = await service.getState();+ 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); };+ }, [service]);++ 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.')); }+ finally { busyRef.current = false; if (alive.current) { setBusy(false); props.onBusyChange?.(false); } }+ }+ async function signIn() {+ if (!service) return;+ 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');+ if (!alive.current) return;+ setAuthorization(value); await refresh(); await props.openExternal?.(value.authorizationUrl);+ } catch (cause) { props.onSignInCanceled?.(); throw cause; }+ }+ useEffect(() => {+ if (!props.signInRequest || props.signInRequest === lastSignInRequest.current) return;+ lastSignInRequest.current = props.signInRequest;+ void action(signIn);+ }, [props.signInRequest]);+ 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('等待浏览器确认登录', 'Waiting for browser authorization')+ : state.authState === 'signing_out' ? l('正在退出', 'Signing out')+ : state.authState === 'expired' ? l('登录已过期,请重新登录', 'Session expired; sign in again')+ : signedIn && profile ? l('已登录', 'Signed in')+ : signedIn ? state.activationState === 'ready' && state.source === 'gateway' ? l('已登录,可以开始创作', 'Signed in and ready to create')+ : state.activationState === 'loading' ? l('已登录,正在连接模型服务…', 'Signed in; connecting to model service…')+ : l('已登录,模型服务暂不可用', 'Signed in; model service is unavailable')+ : l('未登录', 'Signed out')}</p>;+ return <section className={`gateway-account${compact ? ' gateway-account--login' : profile ? ' gateway-account--profile' : ''}`} aria-label={l('OpenCreator 账户', 'OpenCreator Account')}>+ {!compact && !profile ? <div className="gateway-account__heading">+ <h2>{l('OpenCreator 账户', 'OpenCreator Account')}</h2>+ <button type="button" className="gateway-account__icon" title={l('刷新账户', 'Refresh account')} aria-label={l('刷新账户', 'Refresh account')} disabled={busy || !service} onClick={() => void action(refresh)}><RefreshCw size={16}/></button>+ </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">+ {(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 & Recharge')}</button> : null}+ <button type="button" disabled={busy || !service} onClick={() => void action(async () => update(await service!.logout()))}><LogOut size={16}/>{l('退出登录', 'Sign out')}</button>+ </div> : state?.authState === 'authorizing' ? <button type="button" disabled={busy} onClick={() => void action(async () => { update(await service!.cancel()); props.onSignInCanceled?.(); })}>{l('取消登录', 'Cancel sign-in')}</button>+ : <button type="button" className="gateway-account__primary" disabled={busy || !service || !state || state.authState === 'signing_out' || state.authState === 'disabled'} onClick={() => void action(signIn)}><LogIn size={16}/>{busy ? l('正在登录…', 'Signing in…') : profile ? l('登录 / 注册', 'Sign in / Register') : l('登录 OpenCreator', 'Sign in to OpenCreator')}</button>}+ {authorization ? <a href={authorization.authorizationUrl} target="_blank" rel="noreferrer">{l('打开登录页面', 'Open sign-in page')} <ExternalLink size={14}/></a> : null}+ {error ? <p role="alert">{error}</p> : null}+ {(compact || profile) && error && !state && service ? <button type="button" disabled={busy} onClick={() => void action(refresh)}><RefreshCw size={16}/>{l('重试', 'Retry')}</button> : null}+ </section>;+}diff --git a/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsxnew file mode 100644index 00000000..6dd145e1--- /dev/null+++ b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx@@ -0,0 +1,101 @@+import { useEffect, useRef, useState } from 'react';+import { ArrowRight, CreditCard, ExternalLink, LoaderCircle, RefreshCw } from 'lucide-react';+import type { GatewayAccountState } from '@opencreator/protocol';+import type { GatewayAccountSettingsService, GatewayBillingSummary } from '../../services/gateway-account-service.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import { useAppLanguage } from '../../i18n/LanguageProvider.js';+import { formatGatewayCredits, GatewayAccountSettingsView } from './GatewayAccountSettingsView.js';+import './gateway-account-settings.css';++export function GatewaySubscriptionSettingsView(props: {+ service: GatewayAccountSettingsService | null;+ embedded?: boolean;+ variant?: 'overview' | 'subscription';+ accountState?: GatewayAccountState;+ onOpenSubscription?(): void;+ openExternal?(url: string): Promise<void> | void;+ onStateChange?(state: GatewayAccountState): void;+}) {+ const l = useLocalizedCopy();+ const { language } = useAppLanguage();+ const [state, setState] = useState<GatewayAccountState>();+ 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 service = props.service;+ const overview = props.variant === 'overview';+ const account = props.embedded ? props.accountState : state;+ const signedIn = account?.authState === 'signed_in';++ async function refresh() {+ const request = ++sequence.current;+ if (!service) { setLoading(false); return; }+ 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); }+ }+ useEffect(() => {+ alive.current = true; setLoading(true); setSummary(undefined); setBusy(false); setError('');+ 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; }+ })();++ async function recharge() {+ if (!plansURL) return;+ const id = owner.current;+ setBusy(true); setError('');+ 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); }+ }++ return <section className={`gateway-account gateway-subscription${props.embedded ? ' gateway-subscription--embedded' : ''}`} aria-label={l('积分与充值', 'Credits & Recharge')}>+ {!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}+ </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('官方额度已暂停,付款需要审核,请联系支持', 'Official credits are paused pending payment review. 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('充值暂未开放', 'Purchases are not open yet')}</p> : null}+ </div>+ </div> : !loading && !overview ? <p className="gateway-subscription__detail">{l('登录后可使用官方模型与积分充值', 'Sign in for official models and credit purchases')}</p> : null}+ {overview && props.onOpenSubscription ? <button type="button" className="gateway-subscription__entry" onClick={props.onOpenSubscription}><span>{l('积分与充值', 'Credits & Recharge')}</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}+ </section>;+}diff --git a/apps/web/src/features/settings/NetworkSettings.test.tsx b/apps/web/src/features/settings/NetworkSettings.test.tsxnew file mode 100644index 00000000..684cf744--- /dev/null+++ b/apps/web/src/features/settings/NetworkSettings.test.tsx@@ -0,0 +1,30 @@+import { render, screen } from '@testing-library/react';+import { userEvent } from '@testing-library/user-event';+import { expect, it, vi } from 'vitest';+import { NetworkSettings } from './NetworkSettings.js';+import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';++function service() {+ return { getNetwork: vi.fn(async () => ({ proxy: 'http://127.0.0.1:7897' })), saveNetwork: vi.fn(async (value: { proxy: string }) => value), getConfig: vi.fn(), saveConfig: vi.fn() } as unknown as CreatorServicesSettingsService;+}++it('saves and clears a proxy through the independent network API', async () => {+ const api = service(); const user = userEvent.setup();+ render(<NetworkSettings connected service={api} />);+ const input = await screen.findByDisplayValue('http://127.0.0.1:7897');+ await user.clear(input); await user.type(input, 'http://127.0.0.1:8888');+ await user.click(screen.getByRole('button', { name: '保存网络代理' }));+ expect(api.saveNetwork).toHaveBeenCalledWith({ proxy: 'http://127.0.0.1:8888' });+ await user.clear(input); await user.click(screen.getByRole('button', { name: '保存网络代理' }));+ expect(api.saveNetwork).toHaveBeenLastCalledWith({ proxy: '' });+ expect(api.getConfig).not.toHaveBeenCalled(); expect(api.saveConfig).not.toHaveBeenCalled();+});++it('rejects an unsupported proxy without changing any configuration', async () => {+ const api = service(); const user = userEvent.setup(); render(<NetworkSettings connected service={api} />);+ const input = await screen.findByDisplayValue('http://127.0.0.1:7897');+ await user.clear(input); await user.type(input, 'socks5://127.0.0.1:1080');+ await user.click(screen.getByRole('button', { name: '保存网络代理' }));+ expect(screen.getByRole('alert')).toHaveTextContent('请输入有效的 HTTP 或 HTTPS 代理地址');+ expect(api.saveNetwork).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/settings/NetworkSettings.tsx b/apps/web/src/features/settings/NetworkSettings.tsxnew file mode 100644index 00000000..96fdcd3e--- /dev/null+++ b/apps/web/src/features/settings/NetworkSettings.tsx@@ -0,0 +1,52 @@+import { useEffect, useState } from 'react';+import { Save } from 'lucide-react';+import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';++export function NetworkSettings(props: { service?: CreatorServicesSettingsService | null; connected: boolean }) {+ const l = useLocalizedCopy();+ const [saved, setSaved] = useState<string>();+ const [draft, setDraft] = useState('');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ useEffect(() => {+ let canceled = false;+ void props.service?.getNetwork?.().then(value => {+ if (!canceled) { setSaved(value.proxy); setDraft(value.proxy); }+ }).catch(() => { if (!canceled) setError(l('无法读取代理配置', 'Unable to load proxy settings')); });+ return () => { canceled = true; };+ }, [props.service, l]);+ if (!props.service?.getNetwork || !props.service.saveNetwork) return null;+ async function save() {+ setError('');+ const proxy = draft.trim();+ if (proxy) {+ try {+ const url = new URL(proxy);+ if (!['http:', 'https:'].includes(url.protocol) || !url.hostname || url.search || url.hash+ || (url.pathname !== '/' && url.pathname !== '')) throw new Error('invalid');+ } catch { setError(l('请输入有效的 HTTP 或 HTTPS 代理地址', 'Enter a valid HTTP or HTTPS proxy URL')); return; }+ }+ setBusy(true);+ try {+ const value = await props.service!.saveNetwork!({ proxy });+ setSaved(value.proxy); setDraft(value.proxy);+ } catch { setError(l('无法保存代理配置', 'Unable to save proxy settings')); }+ finally { setBusy(false); }+ }+ const disabled = !props.connected || busy || saved === undefined;+ return <>+ <div className="settings-row settings-control-row settings-directory-row">+ <label htmlFor="settings-network-proxy">{l('网络代理', 'Network proxy')}</label>+ <input id="settings-network-proxy" className="settings-directory-input" aria-invalid={!!error}+ aria-describedby={error ? 'settings-network-error' : undefined} value={draft} disabled={disabled}+ placeholder="http://127.0.0.1:7890" autoComplete="off"+ onChange={event => setDraft(event.target.value)}+ onKeyDown={event => { if (event.key === 'Enter' && draft.trim() !== saved) void save(); }} />+ <span className="settings-directory-actions"><button type="button" className="icon-button"+ aria-label={l('保存网络代理', 'Save network proxy')} title={l('保存网络代理', 'Save network proxy')}+ disabled={disabled || draft.trim() === saved} onClick={() => void save()}><Save size={17} aria-hidden="true" /></button></span>+ </div>+ {error ? <p id="settings-network-error" role="alert">{error}</p> : null}+ </>;+}diff --git a/apps/web/src/features/settings/OfficialServicesSettingsView.tsx b/apps/web/src/features/settings/OfficialServicesSettingsView.tsxnew file mode 100644index 00000000..6c389444--- /dev/null+++ b/apps/web/src/features/settings/OfficialServicesSettingsView.tsx@@ -0,0 +1,50 @@+import { useState } from 'react';+import { AudioLines, Image, LoaderCircle, Mic, TextCursorInput, Video, type LucideIcon } from 'lucide-react';+import type { GatewayAccountState, GatewayModel } from '@opencreator/protocol';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';+import OfficialModelSelect from '../../components/forms/OfficialModelSelect.js';+import './official-services-settings.css';++export function OfficialServicesSettingsView(props: { state: GatewayAccountState; service: GatewayAccountSettingsService; onChange(state: GatewayAccountState): void }) {+ const l = useLocalizedCopy();+ const [pendingModality, setPendingModality] = useState<GatewayModel['modality'] | null>(null);+ const [error, setError] = useState('');+ const modalities: Array<{ id: GatewayModel['modality']; label: string; icon: LucideIcon }> = [+ { id: 'text', label: l('文本模型', 'Text model'), icon: TextCursorInput },+ { id: 'image', label: l('图片模型', 'Image model'), icon: Image },+ { id: 'video', label: l('视频模型', 'Video model'), icon: Video },+ { id: 'speech', label: l('语音合成模型', 'Speech model'), icon: AudioLines },+ { id: 'transcription', label: l('语音识别模型', 'Transcription model'), icon: Mic }+ ];+ return <div className="official-services-models">+ {modalities.map(modality => {+ const models = props.state.models.filter(model => model.modality === modality.id && (modality.id !== 'text' || model.capabilities.includes('responses')));+ const Icon = modality.icon;+ const saving = pendingModality === modality.id;+ return <label className="official-services-model-row" key={modality.id} aria-busy={saving}>+ <span className="official-services-model-label">+ <Icon size={19} strokeWidth={1.7} aria-hidden="true" />+ <span>+ <span className="official-services-model-name">{modality.label}</span>+ <span className="official-services-model-count" id={`official-${modality.id}-count`}>+ {models.length === 0 ? l('暂不可用', 'Unavailable') : l(`${models.length} 个模型`, `${models.length} ${models.length === 1 ? 'model' : 'models'}`)}+ </span>+ </span>+ </span>+ <span className="official-services-model-select">+ <OfficialModelSelect label={modality.label} describedBy={`official-${modality.id}-count`} models={models} disabled={pendingModality !== null || props.state.activationState !== 'ready' || models.length === 0}+ value={props.state.selectedModels?.[modality.id] ?? models[0]?.id ?? ''}+ onChange={id => {+ setPendingModality(modality.id); setError('');+ void props.service.selectModel(modality.id, id).then(props.onChange)+ .catch(() => setError(l('模型切换失败,请等待当前任务结束后重试', 'Could not switch models. Wait for the current task to finish and try again.')))+ .finally(() => setPendingModality(null));+ }} />+ {saving ? <LoaderCircle className="official-services-spinner" size={16} aria-hidden="true" /> : null}+ </span>+ </label>;+ })}+ {error ? <p className="official-services-error" role="alert">{error}</p> : null}+ </div>;+}diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsxindex d7f0b029..f29a1a99 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.test.tsx@@ -5,6 +5,10 @@ import { ConfirmDialogProvider } from '../../components/dialogs/ConfirmDialogProimport { LanguageProvider } from '../../i18n/LanguageProvider.js';import { languagePreferenceStorageKey } from '../../i18n/language.js';import { OpenCreatorSettingsView } from './OpenCreatorSettingsView.js';+import type { GatewayAccountState } from '@opencreator/protocol';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';+import { createGatewayAccountService } from '../../services/gateway-account-service.js';+import type { CreatorServicesSettingsService } from '../../services/creator-services-service.js';const runtimeStatus = {connected: true,@@ -17,6 +21,62 @@ const runtimeStatus = {};describe('OpenCreatorSettingsView', () => {+ it('keeps the general proxy editable while signed in without reading custom credentials', async () => {+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: '1', models: [], activationError: null };+ const getConfig = vi.fn(); const saveNetwork = vi.fn(async (value: { proxy: string }) => value);+ const creatorServicesService = { getNetwork: vi.fn(async () => ({ proxy: 'http://127.0.0.1:7897' })), saveNetwork, getConfig } as unknown as CreatorServicesSettingsService;+ render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountState={state} creatorServicesService={creatorServicesService} onBack={vi.fn()} />);+ const user = userEvent.setup(); const input = await screen.findByDisplayValue('http://127.0.0.1:7897');+ await user.clear(input); await user.type(input, 'http://127.0.0.1:8888');+ await user.click(screen.getByRole('button', { name: '保存网络代理' }));+ expect(saveNetwork).toHaveBeenCalledWith({ proxy: 'http://127.0.0.1:8888' });+ expect(getConfig).not.toHaveBeenCalled();+ });+ it('shows only official model controls and changes the model without exposing connection settings', async () => {+ const state: GatewayAccountState = { source: 'gateway', authState: 'signed_in', activationState: 'ready', account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: 'a:1', models: [{ id: 'vendor/first', modality: 'text', capabilities: ['responses'] }, { id: 'vendor/second', modality: 'text', capabilities: ['responses'] }], selectedModels: { text: 'vendor/first' }, activationError: null };+ const next = { ...state, selectedModels: { text: 'vendor/second' } };+ const client = { get: vi.fn(), post: vi.fn(), patch: vi.fn().mockResolvedValue(next) };+ const service = createGatewayAccountService(client);+ const changed = vi.fn();+ render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={state} onGatewayStateChange={changed} initialTab="ai-services" onBack={vi.fn()} />);+ expect(screen.getByRole('combobox', { name: '文本模型' })).toHaveValue('first');+ expect(screen.queryByText(/OpenRouter|base_url|api_key|Base URL|API Key/i)).not.toBeInTheDocument();+ expect(screen.queryByRole('tab', { name: '模型服务' })).not.toBeInTheDocument();+ const user = userEvent.setup();+ await user.click(screen.getByRole('combobox', { name: '文本模型' }));+ await user.click(screen.getByRole('option', { name: 'second' }));+ await waitFor(() => expect(changed).toHaveBeenCalledWith(next));+ expect(client.patch).toHaveBeenCalledWith('/gateway/model', { modality: 'text', model: 'vendor/second' });+ });+ 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 onOpenPersonalCenter = vi.fn();+ render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={gateway} initialTab="ai-services" onOpenPersonalCenter={onOpenPersonalCenter} onBack={vi.fn()}/>);+ expect(await screen.findByText('自定义配置')).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '登录 OpenCreator' }));+ expect(onOpenPersonalCenter).toHaveBeenCalledOnce();+ expect(service.setSource).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: '官方服务' })).not.toBeInTheDocument();+ });+ 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 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();+ expect(screen.queryByRole('button', { name: '自定义配置' })).not.toBeInTheDocument();+ expect(screen.queryByRole('tab', { name: '模型服务' })).not.toBeInTheDocument();+ expect(service.setSource).not.toHaveBeenCalled();+ view.rerender(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} gatewayAccountService={service} gatewayAccountState={local} initialTab="ai-services" onBack={vi.fn()}/>);+ expect(await screen.findByRole('tab', { name: '模型服务' })).toBeInTheDocument();+ });+ it('keeps account and subscription management out of settings', () => {+ render(<OpenCreatorSettingsView runtimeStatus={{ connected: false }} onBack={vi.fn()}/>);+ expect(screen.queryByRole('button', { name: '账户' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: '订阅与积分' })).not.toBeInTheDocument();+ });it('renders default navigation and general settings without old work mode copy', () => {render(<OpenCreatorSettingsView runtimeStatus={runtimeStatus} onBack={vi.fn()} />);diff --git a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx b/apps/web/src/features/settings/OpenCreatorSettingsView.tsxindex dc8bca63..698bf775 100644--- a/apps/web/src/features/settings/OpenCreatorSettingsView.tsx+++ b/apps/web/src/features/settings/OpenCreatorSettingsView.tsx@@ -1,5 +1,5 @@import { lazy, Suspense, useEffect, useRef, useState, type CSSProperties } from 'react';-import { Check, FolderOpen, Moon, Save, Sun } from 'lucide-react';+import { Check, CircleCheck, CircleAlert, FolderOpen, Moon, Save, Sun, UserRound } from 'lucide-react';import type {CodexProfileListResponse,CodexStatusResponse,@@ -34,6 +34,12 @@ import './settings-management.css';import type { OpenCreatorSettingsService } from '../../services/opencreator-settings-service.js';import { IssueList } from '../issues/IssuePresenter.js';import { usePageIssueState } from '../issues/page-issue-state.js';+import './gateway-account-settings.css';+import type { SettingsRouteTab } from '../../app/routes.js';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';+import type { GatewayAccountState } from '@opencreator/protocol';+import { OfficialServicesSettingsView } from './OfficialServicesSettingsView.js';+import { NetworkSettings } from './NetworkSettings.js';const CreatorServicesSettingsView = lazy(async () => {const module = await import('./CreatorServicesSettingsView.js');@@ -72,6 +78,11 @@ export type OpenCreatorSettingsViewProps = {onProfileDataChange?(data: CodexProfileListResponse): void;cleanupService?: CleanupSettingsService | null;creatorServicesService?: CreatorServicesSettingsService | null;+ gatewayAccountService?: GatewayAccountSettingsService | null;+ gatewayAccountState?: GatewayAccountState;+ onGatewayStateChange?(state: GatewayAccountState): void;+ onOpenPersonalCenter?(): void;+ openExternal?(url: string): Promise<void> | void;codexRuntimeService?: CodexRuntimeSettingsService | null;agentSetupNeeded?: boolean;onOpenAgentSetup?(): void;@@ -82,7 +93,7 @@ export type OpenCreatorSettingsViewProps = {storageSettingsService?: Pick<OpenCreatorSettingsService, 'getStorageSettings' | 'updateStorageSettings'> | null;onSelectStorageDirectory?(purpose: 'default-project-root' | 'output-root'): Promise<string | null>;codexStatus?: CodexStatusResponse;- initialTab?: 'general' | 'ai-services' | 'local-components';+ initialTab?: 'general' | SettingsRouteTab;initialSection?: CreatorServicesSection;componentId?: string;returnToTranslation?: boolean;@@ -102,8 +113,10 @@ type SettingsTab =export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {const [activeTab, setActiveTab] = useState<SettingsTab>(() => props.initialTab ?? 'general');+ const [gatewayState, setGatewayState] = useState<GatewayAccountState>();const { t } = useAppLanguage();const l = useLocalizedCopy();+ const officialMode = gatewayState !== undefined && (gatewayState.source === 'gateway' || gatewayState.authState !== 'signed_out');const tabs: Array<{ id: SettingsTab; label: string }> = [{ id: 'general', label: t('settings.tab.general') },{ id: 'ai-services', label: t('settings.tab.aiServices') },@@ -120,6 +133,13 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {if (props.initialTab !== undefined) setActiveTab(props.initialTab);}, [props.initialTab]);+ useEffect(() => {+ if (props.gatewayAccountState) { setGatewayState(props.gatewayAccountState); return; }+ let canceled = false;+ void props.gatewayAccountService?.getState().then(next => { if (!canceled) setGatewayState(next); }).catch(() => undefined);+ return () => { canceled = true; };+ }, [props.gatewayAccountService, props.gatewayAccountState]);+return (<div className="settings-page"><aside className="settings-sidebar" aria-label={t('settings.navigation')}>@@ -136,7 +156,7 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {><span className="settings-nav-label">{tab.label}- {tab.id === 'ai-services' ? (+ {tab.id === 'ai-services' && !officialMode ? (<small className="settings-nav-required">{t('settings.required')}</small>) : null}{tab.id === 'local-components'@@ -154,6 +174,8 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {<main className="opencreator-scroll-page settings-content">{activeTab === 'general' ? (<GeneralSettings+ creatorServicesService={props.creatorServicesService}+ connected={props.runtimeStatus.connected}defaultPermission={props.defaultPermission ?? 'follow-project'}defaultPermissionError={props.defaultPermissionError}onDefaultPermissionChange={props.onDefaultPermissionChange}@@ -173,7 +195,25 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {) : null}{activeTab === 'ai-services' ? (<>- {props.agentSetupNeeded && props.onOpenAgentSetup !== undefined ? (+ {props.gatewayAccountService && gatewayState ? <div className={`gateway-account ai-services-mode${officialMode ? ' ai-services-mode--official' : ''}`}>+ <span className="ai-services-mode__label">{l('使用模式', 'Usage mode')}</span>+ <strong>{officialMode ? l('官方服务', 'Official service') : l('自定义配置', 'Custom configuration')}</strong>+ {!officialMode && props.onOpenPersonalCenter ? <button type="button" onClick={props.onOpenPersonalCenter}><UserRound size={15} aria-hidden="true"/>{l('登录 OpenCreator', 'Sign in to OpenCreator')}</button> : null}+ </div> : null}+ {officialMode && gatewayState ? <section className="gateway-account official-services-settings" aria-labelledby="official-services-title">+ <header className="official-services-heading">+ <div>+ <h1 id="official-services-title">{l('AI 服务', 'AI services')}</h1>+ <p className={`official-services-status${gatewayState.activationState === 'ready' ? ' is-ready' : ''}`} role="status">+ {gatewayState.activationState === 'ready' ? <CircleCheck size={14} aria-hidden="true" /> : <CircleAlert size={14} aria-hidden="true" />}+ {gatewayState.authState === 'authorizing' ? l('正在登录', 'Signing in') : gatewayState.activationState === 'loading' ? l('正在连接', 'Connecting') : gatewayState.activationState === 'ready' ? l('已连接', 'Connected') : gatewayState.authState === 'expired' ? l('登录已过期', 'Session expired') : l('暂不可用', 'Unavailable')}+ </p>+ </div>+ {props.onOpenPersonalCenter ? <button type="button" onClick={props.onOpenPersonalCenter}><UserRound size={15} aria-hidden="true"/>{l('个人中心', 'Personal center')}</button> : null}+ </header>+ {props.gatewayAccountService ? <OfficialServicesSettingsView state={gatewayState} service={props.gatewayAccountService} onChange={next => { setGatewayState(next); props.onGatewayStateChange?.(next); }} /> : null}+ </section> : null}+ {props.agentSetupNeeded && !officialMode && props.onOpenAgentSetup !== undefined ? (<div className="settings-inline-warning" role="status">{l('Agent 尚未配置,无法发送任务。', 'Agent is not configured; tasks cannot be sent.')}{' '}@@ -185,12 +225,12 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {<Suspense fallback={<p role="status">{l('正在加载 AI 服务设置…', 'Loading AI service settings…')}</p>}>- <CreatorServicesSettingsView+ {props.gatewayAccountService && gatewayState === undefined ? <p role="status">{l('正在检查使用模式…', 'Checking usage mode…')}</p> : !officialMode ? <CreatorServicesSettingsViewconnected={props.runtimeStatus.connected}service={props.creatorServicesService ?? null}modelService={props.codexRuntimeService ?? null}initialSection={props.initialSection}- />+ /> : null}</Suspense></>) : null}@@ -239,6 +279,8 @@ export function OpenCreatorSettingsView(props: OpenCreatorSettingsViewProps) {}function GeneralSettings(props: {+ creatorServicesService?: CreatorServicesSettingsService | null;+ connected: boolean;defaultPermission: DefaultPermissionPreference;defaultPermissionError?: string;onDefaultPermissionChange?(permission: DefaultPermissionPreference): void;@@ -388,6 +430,7 @@ function GeneralSettings(props: {<p>{t('settings.general.description')}</p></header><div className="settings-card">+ <NetworkSettings service={props.creatorServicesService} connected={props.connected} />{storage === undefined || storageDraft === undefined ? null : (<><StorageDirectoryRowdiff --git a/apps/web/src/features/settings/StartupAgentSetup.test.tsx b/apps/web/src/features/settings/StartupAgentSetup.test.tsxindex ba5d4717..f823c555 100644--- a/apps/web/src/features/settings/StartupAgentSetup.test.tsx+++ b/apps/web/src/features/settings/StartupAgentSetup.test.tsx@@ -1,8 +1,9 @@-import type { CodexProviderConfig, CodexRuntimeReadiness } from '@opencreator/protocol';+import type { CodexProviderConfig, CodexRuntimeReadiness, GatewayAccountState } from '@opencreator/protocol';import { cleanup, render, screen, waitFor } from '@testing-library/react';import { userEvent } from '@testing-library/user-event';import { afterEach, describe, expect, it, vi } from 'vitest';import { LanguageProvider } from '../../i18n/LanguageProvider.js';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';import {availableAgentMode, confirmAgentSetup, isAgentSetupConfirmed,StartupAgentSetup, type AgentSetupService, type AgentSetupSnapshot@@ -63,6 +64,7 @@ describe('StartupAgentSetup', () => {const snapshot = { readiness: readiness('signed_in'), provider };const { onReady } = mount(service, snapshot);expect(isAgentSetupConfirmed(snapshot)).toBe(false);+ await userEvent.setup().click(screen.getByRole('button', { name: '本地模式' }));expect(screen.getByText('已找到本机 Codex')).toBeInTheDocument();expect(screen.getByText(/ChatGPT 登录 · gpt-test/)).toBeInTheDocument();expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();@@ -80,6 +82,7 @@ describe('StartupAgentSetup', () => {} };const { onReady } = mount(service, snapshot);const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: '本地模式' }));await user.click(screen.getByRole('button', { name: '自定义模型服务' }));expect(screen.getByRole('combobox', { name: '供应商' })).toBeInTheDocument();await user.selectOptions(screen.getByRole('combobox', { name: '供应商' }), 'deepseek');@@ -98,6 +101,7 @@ describe('StartupAgentSetup', () => {const provider: CodexProviderConfig = { baseUrl: 'https://gateway.example.test/v1', model: 'model-1', apiKeyConfigured: true, authentication: 'api_key' };const snapshot = { readiness: readiness('signed_out', 'degraded'), provider };const { onReady } = mount(service, snapshot);+ await userEvent.setup().click(screen.getByRole('button', { name: '本地模式' }));expect(screen.getByText(/API Key 已配置 · model-1/)).toBeInTheDocument();expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();await userEvent.setup().click(screen.getByRole('button', { name: '使用本机 Codex,继续' }));@@ -110,10 +114,12 @@ describe('StartupAgentSetup', () => {expect(isAgentSetupConfirmed({ ...snapshot, provider: { ...provider, apiKeyConfigured: false } })).toBe(false);});- it('shows provider and API key fields immediately without credentials, never a login action', async () => {+ it('shows provider configuration only after choosing local mode', async () => {const service = createService();const { onReady } = mount(service);const user = userEvent.setup();+ expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: '本地模式' }));const providerSelect = await screen.findByRole('combobox', { name: '供应商' });expect(providerSelect).toHaveValue('openai');expect(screen.getByLabelText('Base URL')).toHaveValue('https://api.openai.com/v1');@@ -136,6 +142,7 @@ describe('StartupAgentSetup', () => {const snapshot = { readiness: readiness('signed_out', 'degraded'), provider };const { onReady } = mount(service, snapshot);const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: '本地模式' }));await user.click(screen.getByRole('button', { name: '自定义模型服务' }));await user.clear(screen.getByLabelText('模型名称'));await user.type(screen.getByLabelText('模型名称'), 'new-model');@@ -152,6 +159,7 @@ describe('StartupAgentSetup', () => {vi.mocked(service.getCodexReadiness).mockResolvedValue(readiness('signed_out', 'blocked'));const { onReady } = mount(service);const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: '本地模式' }));await user.selectOptions(await screen.findByRole('combobox', { name: '供应商' }), 'openai');await user.type(screen.getByLabelText('API Key'), 'secret');await user.click(screen.getByRole('button', { name: '保存并开始使用' }));@@ -164,6 +172,7 @@ describe('StartupAgentSetup', () => {const service = createService();const { onReady } = mount(service);const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: '本地模式' }));await screen.findByRole('combobox', { name: '供应商' });await user.clear(screen.getByLabelText('Base URL'));await user.type(screen.getByLabelText('API Key'), 'secret');@@ -178,6 +187,7 @@ describe('StartupAgentSetup', () => {baseUrl: 'https://gateway.example.test/v1', model: 'model-1', apiKeyConfigured: true, authentication: 'api_key'});const { onReady } = mount(service);+ await userEvent.setup().click(screen.getByRole('button', { name: '本地模式' }));expect(await screen.findByRole('alert')).toHaveTextContent('暂时无法读取');await userEvent.setup().click(screen.getByRole('button', { name: '重新检测' }));expect(await screen.findByText('已找到本机 Codex')).toBeInTheDocument();@@ -188,8 +198,38 @@ describe('StartupAgentSetup', () => {it('supports skipping without changing local Codex', async () => {const service = createService();const { onSkip } = mount(service);- await userEvent.setup().click(screen.getByRole('button', { name: '暂时跳过' }));+ await userEvent.setup().click(screen.getByRole('button', { name: '稍后配置,进入本地模式' }));expect(onSkip).toHaveBeenCalledOnce();expect(service.updateCodexProvider).not.toHaveBeenCalled();});++ it('offers both modes and never exposes provider fields in sign-in mode', async () => {+ mount(createService());+ expect(screen.getByRole('heading', { name: 'OpenCreator' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: '本地模式' })).toBeInTheDocument();+ await userEvent.setup().click(screen.getByRole('button', { name: '登录模式' }));+ expect(screen.getByRole('button', { name: '登录 OpenCreator' })).toBeDisabled();+ expect(screen.queryByLabelText('Base URL')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();+ });++ it('cancels browser authorization before returning to the local mode selector', async () => {+ let state: GatewayAccountState = { source: 'manual', authState: 'signed_out', activationState: 'inactive', account: null, bindingVersion: null, models: [], activationError: null };+ const gateway: GatewayAccountSettingsService = {+ 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()+ };+ render(<LanguageProvider initialPreference="zh-CN"><StartupAgentSetup service={createService()} gatewayService={gateway} onReady={vi.fn()} onSkip={vi.fn()}/></LanguageProvider>);+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: '登录模式' }));+ await waitFor(() => expect(screen.getByRole('button', { name: '登录 OpenCreator' })).toBeEnabled());+ await user.click(screen.getByRole('button', { name: '登录 OpenCreator' }));+ expect(await screen.findByText('等待浏览器确认登录')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: '返回' }));+ expect(gateway.cancel).toHaveBeenCalledOnce();+ await user.click(screen.getByRole('button', { name: '本地模式' }));+ expect(await screen.findByLabelText('API Key')).toBeInTheDocument();+ });});diff --git a/apps/web/src/features/settings/StartupAgentSetup.tsx b/apps/web/src/features/settings/StartupAgentSetup.tsxindex 7455b823..e60fe037 100644--- a/apps/web/src/features/settings/StartupAgentSetup.tsx+++ b/apps/web/src/features/settings/StartupAgentSetup.tsx@@ -1,10 +1,15 @@import { creatorProviderCatalogById, type CodexProviderConfig, type CodexRuntimeReadiness } from '@opencreator/protocol';import { useEffect, useRef, useState } from 'react';+import { ArrowLeft, LogIn, Monitor } from 'lucide-react';+import OpenCreatorMark from '../../components/brand/OpenCreatorMark.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import type { ConnectionService } from '../../services/connection-service.js';import { readJsonFromStorage, writeJsonToStorage } from '../../storage/browser-storage.js';import { inferLlmProviderId, llmProviderOptions } from './llm-provider-selection.js';import './startup-agent-setup.css';+import { GatewayAccountSettingsView } from './GatewayAccountSettingsView.js';+import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';+import type { GatewayAccountState } from '@opencreator/protocol';export type AgentSetupSnapshot = { readiness: CodexRuntimeReadiness; provider: CodexProviderConfig };type AgentSetupMode = 'codex' | 'custom';@@ -57,10 +62,16 @@ export function StartupAgentSetup(props: {initialSnapshot?: AgentSetupSnapshot;onReady(snapshot: AgentSetupSnapshot): void;onSkip(): void;+ gatewayService?: GatewayAccountSettingsService | null;+ gatewayState?: GatewayAccountState;+ onGatewayStateChange?(state: GatewayAccountState): void;+ openExternal?(url: string): Promise<void> | void;}) {const l = useLocalizedCopy();const activeRef = useRef(true);+ const gateway = useRef(props.gatewayState);const [snapshot, setSnapshot] = useState(props.initialSnapshot);+ const [entry, setEntry] = useState<'choose' | 'local' | 'login'>('choose');const [mode, setMode] = useState<AgentSetupMode>(props.initialSnapshot !== undefined && availableAgentMode(props.initialSnapshot) !== null ? 'codex' : 'custom');@@ -74,6 +85,7 @@ export function StartupAgentSetup(props: {const [retryCount, setRetryCount] = useState(0);const [busy, setBusy] = useState(false);const [error, setError] = useState<string>();+ const [modeError, setModeError] = useState<string>();useEffect(() => {activeRef.current = true;@@ -107,6 +119,7 @@ export function StartupAgentSetup(props: {setBusy(true);setError(undefined);try {+ await selectLocalSource();if (reusableKey && apiKey.trim().length === 0 && snapshot !== undefined && existingMode !== null) {props.onReady(snapshot);return;@@ -143,16 +156,58 @@ export function StartupAgentSetup(props: {setError(undefined);}- function skip() {- activeRef.current = false;- props.onSkip();+ function updateGateway(next: GatewayAccountState) {+ gateway.current = next;+ props.onGatewayStateChange?.(next);+ }++ async function selectLocalSource() {+ if (!props.gatewayService) return;+ if (gateway.current?.authState === 'authorizing') updateGateway(await props.gatewayService.cancel());+ if (gateway.current?.source === 'gateway') updateGateway(await props.gatewayService.setSource('manual'));+ }++ async function skip() {+ setBusy(true);+ setModeError(undefined);+ try {+ await selectLocalSource();+ activeRef.current = false;+ props.onSkip();+ } catch { setModeError(l('无法切换本地模式,请稍后重试', 'Could not switch to local mode. Try again later.')); }+ finally { if (activeRef.current) setBusy(false); }+ }++ async function back() {+ setBusy(true);+ setModeError(undefined);+ try {+ if (gateway.current?.authState === 'authorizing' && props.gatewayService) updateGateway(await props.gatewayService.cancel());+ setEntry('choose');+ } catch { setModeError(l('无法取消登录,请重试', 'Could not cancel sign-in. Try again.')); }+ finally { if (activeRef.current) setBusy(false); }+ }++ async function login() {+ setEntry('login'); setModeError(undefined);+ if (!props.gatewayService || gateway.current?.authState !== 'signed_in') return;+ setBusy(true);+ try { updateGateway(await props.gatewayService.activate()); }+ catch { if (activeRef.current) setModeError(l('模型服务暂不可用,请重试', 'Model service is unavailable. Try again.')); }+ finally { if (activeRef.current) setBusy(false); }}return (<main className="startup-agent-setup">- <section className="startup-agent-setup__card" aria-labelledby="startup-agent-title">- <span className="startup-agent-setup__eyebrow">OpenCreator · Agent</span>- <h1 id="startup-agent-title">{l('开始使用 Agent', 'Get started with Agent')}</h1>+ <section className="startup-agent-setup__card" aria-label={l('开始使用 Agent', 'Get started with Agent')}>+ <OpenCreatorMark size={48} aria-hidden="true" />+ <h1>OpenCreator</h1>+ {entry === 'choose' ? <div className="startup-agent-setup__entry">+ <button type="button" className="startup-agent-setup__primary" disabled={busy} onClick={() => void login()}><LogIn size={18}/>{l('登录模式', 'Sign-in mode')}</button>+ <button type="button" disabled={busy} onClick={() => setEntry('local')}><Monitor size={18}/>{l('本地模式', 'Local mode')}</button>+ </div> : <button type="button" className="startup-agent-setup__back" disabled={busy} onClick={() => void back()}><ArrowLeft size={16}/>{l('返回', 'Back')}</button>}+ {entry === 'login' ? <GatewayAccountSettingsView variant="login" service={props.gatewayService ?? null} openExternal={props.openExternal} onStateChange={updateGateway} onBusyChange={setBusy}/> : null}+ {entry === 'local' ? <>{loading ? <p role="status">{l('正在检查本机 Codex…', 'Checking local Codex…')}</p> : null}{!loading && existingMode !== null ? (<>@@ -177,7 +232,7 @@ export function StartupAgentSetup(props: {<p>{l('配置模型服务后即可开始使用 Agent。', 'Set up a model provider to start using Agent.')}</p>) : null}{!loading && mode === 'codex' && existingMode !== null && snapshot !== undefined ? (- <button type="button" className="startup-agent-setup__primary" onClick={() => props.onReady(snapshot)}>+ <button type="button" className="startup-agent-setup__primary" disabled={busy} onClick={() => void selectLocalSource().then(() => props.onReady(snapshot)).catch(() => setError(l('无法切换本地模式,请重试', 'Could not switch to local mode. Try again.')))}>{l('使用本机 Codex,继续', 'Use local Codex and continue')}</button>) : !loading && snapshot !== undefined ? (@@ -214,8 +269,10 @@ export function StartupAgentSetup(props: {{l('重新检测', 'Retry detection')}</button>) : null}- <button className="startup-agent-setup__skip" type="button" onClick={skip}>- {l('暂时跳过', 'Skip for now')}+ </> : null}+ {modeError ? <p className="startup-agent-setup__error" role="alert">{modeError}</p> : null}+ <button className="startup-agent-setup__skip" type="button" disabled={busy} onClick={() => void skip()}>+ {l('稍后配置,进入本地模式', 'Continue locally and set up later')}</button></section></main>diff --git a/apps/web/src/features/settings/gateway-account-settings.css b/apps/web/src/features/settings/gateway-account-settings.cssnew file mode 100644index 00000000..3575f713--- /dev/null+++ b/apps/web/src/features/settings/gateway-account-settings.css@@ -0,0 +1,56 @@+.gateway-account { padding: 20px 0; font-size: 14px; min-width: 0; color: var(--text); }+.gateway-account__heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }+.gateway-account h2 { margin: 0; font-size: 18px; letter-spacing: 0; }+.gateway-account button, .gateway-account select { font: inherit; color: inherit; background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 8px 12px; cursor: pointer; }+.gateway-account button { display: inline-flex; align-items: center; justify-content: center; gap: 8px; }+.gateway-account button:disabled { opacity: .5; cursor: default; }+.gateway-account__icon { width: 34px; height: 34px; padding: 0 !important; flex-shrink: 0; }+.gateway-account__source { display: flex; margin: 16px 0; gap: 6px; flex-wrap: wrap; }+.gateway-account button[aria-pressed=true], .gateway-account button.gateway-account__primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }+.gateway-account__actions, .gateway-account__plans { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0; }+.gateway-account__balance { display: flex; gap: 32px; margin: 16px 0; flex-wrap: wrap; }+.gateway-account__balance dt { opacity: .7; font-size: 12px; }+.gateway-account__balance dd { margin: 6px 0 0; font-size: 22px; font-variant-numeric: tabular-nums; }+.gateway-account__email, .gateway-account a { overflow-wrap: anywhere; }+.gateway-account__models { padding: 0; list-style: none; margin: 14px 0; }+.gateway-account__models li { display: flex; gap: 16px; padding: 6px 0; overflow-wrap: anywhere; }+.gateway-account__models span { opacity: .6; min-width: 100px; }+.gateway-account a { display: inline-flex; align-items: center; gap: 8px; color: var(--accent-strong); margin: 10px 0; }+.gateway-account__plans select { max-width: 100%; min-width: 0; }+.gateway-account--login { padding: 0; }+.gateway-account--login > .gateway-account__primary { width: 100%; }+.gateway-account p { line-height: 1.6; overflow-wrap: anywhere; }+.gateway-account [role=alert] { color: var(--danger); }+.gateway-subscription__plans { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 16px; }+.gateway-subscription__plan { padding: 20px; border: 1px solid var(--border); border-radius: 8px; min-width: 0; }+.gateway-subscription__plan h3 { margin: 0; font-size: 16px; font-weight: 500; letter-spacing: 0; overflow-wrap: anywhere; }+.gateway-subscription__price { margin: 20px 0 12px; font-size: 26px; font-variant-numeric: tabular-nums; }+.gateway-subscription__price small { color: var(--muted); font-size: 13px; }+.gateway-subscription__plan button { width: 100%; margin-top: 24px; }+.gateway-subscription__overview { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 32px; padding: 28px 0; border-bottom: 1px solid var(--border); }+.gateway-subscription__overview h2 { font-size: 12px; font-weight: 400; color: var(--muted); }+.gateway-subscription p.gateway-subscription__credit-value { font-size: 30px; line-height: 1.3; font-variant-numeric: tabular-nums; margin: 10px 0 6px; }+.gateway-subscription__credit-value small { font-size: 12px; color: var(--muted); }+.gateway-subscription__current-name { display: flex; align-items: baseline; flex-wrap: wrap; gap: 10px; margin: 12px 0 8px; }+.gateway-subscription__current-name strong { font-size: 18px; font-weight: 500; overflow-wrap: anywhere; }+.gateway-subscription__current-name span { font-size: 12px; color: var(--muted); }+.gateway-subscription__current-name span.is-active { color: var(--success, #62bc8b); }+.gateway-subscription__detail { font-size: 12px; color: var(--muted); margin: 5px 0; }+.gateway-subscription__current button { margin-top: 14px; }+.gateway-subscription__catalog { padding: 28px 0; }+.gateway-subscription button.gateway-subscription__entry { display: flex; justify-content: flex-start; width: 100%; margin: 24px 0 0; padding: 16px 0; background: transparent; border: 0; border-bottom: 1px solid var(--border); border-radius: 0; text-align: left; }+.gateway-subscription__entry span { flex: 1; min-width: 0; overflow-wrap: anywhere; }+.gateway-subscription__entry svg { flex-shrink: 0; color: var(--muted); }+.gateway-subscription button.gateway-subscription__entry:hover { color: var(--accent-strong); }+.gateway-subscription__catalog-heading { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 8px 16px; margin-bottom: 18px; }+.gateway-subscription__catalog-heading h2 { font-size: 17px; font-weight: 500; }+.gateway-subscription__catalog-heading p, .gateway-subscription__empty { font-size: 12px; color: var(--muted); margin: 0; }+.gateway-subscription__allowance { margin: 0; }+.gateway-subscription__loading { display: flex; align-items: center; gap: 8px; color: var(--muted); }+.gateway-subscription__loading svg { animation: gateway-loading-spin 1s linear infinite; flex-shrink: 0; }+.gateway-subscription__credit-value, .gateway-subscription__price { overflow-wrap: anywhere; }+.gateway-subscription__error { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin: 14px 0; }+.gateway-subscription__error p { margin: 0; }+@keyframes gateway-loading-spin { to { transform: rotate(360deg); } }+@media (max-width: 640px) { .gateway-subscription__overview { grid-template-columns: minmax(0, 1fr); gap: 26px; } }+@media (prefers-reduced-motion: reduce) { .gateway-subscription__loading svg { animation: none; } }diff --git a/apps/web/src/features/settings/official-services-settings.css b/apps/web/src/features/settings/official-services-settings.cssnew file mode 100644index 00000000..dbb6f935--- /dev/null+++ b/apps/web/src/features/settings/official-services-settings.css@@ -0,0 +1,213 @@+.ai-services-mode {+ width: min(1160px, 100%);+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 12px 24px;+ margin: 0 auto 24px;+ padding: 0 0 20px;+ border-bottom: 1px solid var(--border);+}++.ai-services-mode--official,+.official-services-settings {+ width: min(820px, 100%);+}++.ai-services-mode__label {+ color: var(--muted);+ font-size: 13px;+}++.ai-services-mode .gateway-account__source {+ gap: 3px;+ margin: 0;+ padding: 3px;+ border: 1px solid var(--border);+ border-radius: 7px;+ background: var(--surface-2);+}++.ai-services-mode .gateway-account__source button {+ min-height: 32px;+ padding: 5px 14px;+ border-color: transparent;+ background: transparent;+ color: var(--muted);+ font-size: 13px;+}++.ai-services-mode .gateway-account__source button[aria-pressed='true'] {+ border-color: var(--border-strong);+ background: var(--surface);+ color: var(--text);+}++.ai-services-mode .gateway-account__source button:hover:not(:disabled) {+ color: var(--text);+}++.ai-services-mode > [role='alert'] {+ flex-basis: 100%;+ margin: 0;+ font-size: 13px;+}++.official-services-settings {+ margin: 0 auto;+ padding: 0;+}++.official-services-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 16px;+ padding-bottom: 24px;+}++.official-services-heading > div {+ display: grid;+ gap: 10px;+}++.official-services-heading h1 {+ margin: 0;+ font-size: 24px;+ font-weight: 600;+ line-height: 1.3;+}++.official-services-heading p.official-services-status {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0;+ color: var(--warning);+ font-size: 12px;+ line-height: 1.4;+}++.official-services-heading p.official-services-status.is-ready {+ color: var(--success);+}++.official-services-heading button {+ min-height: 32px;+ padding: 6px 10px;+ font-size: 12px;+}++.official-services-models {+ border-top: 1px solid var(--border);+}++.official-services-model-row {+ min-width: 0;+ min-height: 86px;+ display: grid;+ grid-template-columns: minmax(160px, 1fr) minmax(0, 380px);+ align-items: center;+ gap: 16px 24px;+ padding: 18px 0;+ border-bottom: 1px solid var(--border);+}++.official-services-model-label {+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 12px;+}++.official-services-model-label > svg {+ flex-shrink: 0;+ color: var(--muted);+}++.official-services-model-label > span {+ min-width: 0;+ display: grid;+ gap: 5px;+}++.official-services-model-name {+ color: var(--text);+ font-size: 13px;+ font-weight: 500;+ overflow-wrap: anywhere;+}++.official-services-model-count {+ color: var(--muted);+ font-size: 12px;+}++.official-services-model-select {+ position: relative;+ min-width: 0;+ display: flex;+ align-items: center;+}++.official-services-model-select select {+ appearance: none;+ width: 100%;+ min-width: 0;+ height: 40px;+ padding: 0 36px 0 12px;+ color: var(--text);+ font-size: 13px;+ text-overflow: ellipsis;+}++.official-services-model-select select:hover:not(:disabled) {+ border-color: var(--border-strong);+}++.official-services-model-select select:disabled {+ opacity: 0.5;+ cursor: default;+}++.official-services-model-select > svg {+ position: absolute;+ right: 12px;+ color: var(--muted);+ pointer-events: none;+}++.official-services-error {+ margin: 16px 0 0;+ font-size: 13px;+}++.ai-services-mode button:focus-visible,+.official-services-settings button:focus-visible,+.official-services-model-select select:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.official-services-spinner {+ animation: official-services-spin 1s linear infinite;+}++.official-services-model-row[aria-busy='true'] .official-model-toggle { visibility: hidden; }++@keyframes official-services-spin {+ to { transform: rotate(360deg); }+}++@media (max-width: 960px) {+ .official-services-model-row {+ grid-template-columns: minmax(0, 1fr);+ gap: 12px;+ padding: 18px 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .official-services-spinner { animation: none; }+}diff --git a/apps/web/src/features/settings/startup-agent-setup.css b/apps/web/src/features/settings/startup-agent-setup.cssindex cfdb4bee..f443ae50 100644--- a/apps/web/src/features/settings/startup-agent-setup.css+++ b/apps/web/src/features/settings/startup-agent-setup.css@@ -13,14 +13,15 @@width: min(100%, 480px);display: grid;gap: 18px;- padding: 32px;- border: 1px solid var(--border);- border-radius: 16px;- background: var(--surface);+ padding: 24px;}.startup-agent-setup__eyebrow { color: var(--accent-strong); font-size: 13px; font-weight: 700; }.startup-agent-setup__card h1 { margin: 0; font-size: 27px; }+.startup-agent-setup__card > .opencreator-mark { color: var(--accent-strong); }+.startup-agent-setup__entry { display: grid; gap: 12px; margin: 16px 0; }+.startup-agent-setup__entry button, .startup-agent-setup__back { display: flex; align-items: center; justify-content: center; gap: 10px; }+.startup-agent-setup__card .startup-agent-setup__back { justify-self: start; padding-left: 0; border: 0; background: transparent; }.startup-agent-setup__card p { margin: 0; color: var(--muted); line-height: 1.6; }.startup-agent-setup__card .startup-agent-setup__detected {display: grid;diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsxindex 8aae060e..2200e280 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.test.tsx@@ -64,6 +64,30 @@ function renderSidebar(overrides: Partial<ComponentProps<typeof OpenCreatorSideb}describe('OpenCreatorSidebar', () => {+ it.each([+ { collapsed: false, activeView: 'account' as const },+ { collapsed: true, activeView: 'account' as const },+ { collapsed: false, activeView: 'subscription' as const },+ { collapsed: true, activeView: 'subscription' as const }+ ])('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: '个人中心' });+ expect(button.parentElement).toHaveClass('sidebar-bottom');+ expect(button).toHaveAttribute('aria-current', 'page');+ expect(button).toHaveAttribute('title', '个人中心');+ fireEvent.click(button);+ expect(onOpenView).toHaveBeenCalledWith('account');+ });+ it('updates the footer identity when the user signs out', () => {+ const props = { source: 'gateway' as const, authState: 'signed_in' as const, activationState: 'ready' as const, account: { id: 'a', email: '[email protected]', verified: true }, bindingVersion: 'a:1', models: [], activationError: null };+ const view = renderSidebar({ gatewayAccountState: props });+ expect(screen.getByText('[email protected]')).toBeInTheDocument();+ view.unmount();+ renderSidebar({ gatewayAccountState: { ...props, authState: 'signed_out', account: null } });+ expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();+ expect(screen.getByText('未登录')).toBeInTheDocument();+ });it('renders global actions, projects with nested conversations, and the settings footer action', () => {renderSidebar();diff --git a/apps/web/src/features/shell/OpenCreatorSidebar.tsx b/apps/web/src/features/shell/OpenCreatorSidebar.tsxindex fd556038..b6a5d6cd 100644--- a/apps/web/src/features/shell/OpenCreatorSidebar.tsx+++ b/apps/web/src/features/shell/OpenCreatorSidebar.tsx@@ -29,6 +29,9 @@ import {type LucideIcon} from 'lucide-react';import type { ActiveView } from '../../app/app-state.js';+import type { GatewayAccountState } from '@opencreator/protocol';+import { AccountAvatar } from '../account/AccountAvatar.js';+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';import OpenCreatorMark from '../../components/brand/OpenCreatorMark.js';import { ConfirmDialog } from '../../components/dialogs/ConfirmDialog.js';import type { ColorMode } from '../../styles/color-mode.js';@@ -48,6 +51,7 @@ const SIDEBAR_ACTION_MENU_VIEWPORT_MARGIN = 8;const SIDEBAR_ACTION_MENU_GAP = 4;export function OpenCreatorSidebar(props: {+ loadAccountAvatar?(accountId: string, revision: string): Promise<Blob>;projects: OpenCreatorProject[];conversations: OpenCreatorConversation[];tasks: SidebarTaskSummary[];@@ -55,6 +59,7 @@ export function OpenCreatorSidebar(props: {currentProjectId?: string;selectedConversationId?: string;activeView: ActiveView;+ gatewayAccountState?: GatewayAccountState;homeActive?: boolean;projectNavigationMode?: 'library' | 'tree';collapsed?: boolean;@@ -83,6 +88,8 @@ export function OpenCreatorSidebar(props: {onDeleteTask?(task: SidebarTaskSummary): void | Promise<void>;}) {const { t } = useAppLanguage();+ const l = useLocalizedCopy();+ const accountEmail = props.gatewayAccountState?.authState === 'signed_in' ? props.gatewayAccountState.account?.email : undefined;const [expandedProjectId, setExpandedProjectId] = useState<string | undefined>(props.currentProjectId);const [projectMenuId, setProjectMenuId] = useState<string>();const [archivingConversationId, setArchivingConversationId] = useState<string>();@@ -805,6 +812,13 @@ export function OpenCreatorSidebar(props: {</section>)}+ <div className="sidebar-bottom">+ <button type="button" className="sidebar-account" aria-label={l('个人中心', 'Personal center')} title={l('个人中心', 'Personal center')} 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('个人中心', 'Personal center')}</strong><small>{accountEmail ?? (props.gatewayAccountState?.authState === 'expired' ? l('登录已过期', 'Session expired') : l('未登录', 'Signed out'))}</small></span> : null}+ </button>+ </div>+<ConfirmDialogopen={conversationPendingDeletion !== undefined}title="删除任务"diff --git a/apps/web/src/services/creator-services-service.ts b/apps/web/src/services/creator-services-service.tsindex 23d30ff4..46a320cf 100644--- a/apps/web/src/services/creator-services-service.ts+++ b/apps/web/src/services/creator-services-service.ts@@ -12,13 +12,17 @@ import type { RuntimeClient } from '../runtime/client.js';type ClientLike = Pick<RuntimeClient, 'get' | 'patch' | 'delete' | 'rawRequest'>;-export type CreatorServicesSettingsService = Omit<ReturnType<typeof createCreatorServicesService>, 'getCodexImageStatus' | 'getCodexModelStatus'> & {+export type CreatorServicesSettingsService = Omit<ReturnType<typeof createCreatorServicesService>, 'getCodexImageStatus' | 'getCodexModelStatus' | 'getNetwork' | 'saveNetwork'> & {getCodexImageStatus?: () => Promise<CodexImageStatus>;getCodexModelStatus?: () => Promise<CodexProviderConfig>;+ getNetwork?: () => Promise<{ proxy: string }>;+ saveNetwork?: (network: { proxy: string }) => Promise<{ proxy: string }>;};export function createCreatorServicesService(client: ClientLike) {return {+ getNetwork(): Promise<{ proxy: string }> { return client.get('/creator-services/network'); },+ saveNetwork(network: { proxy: string }): Promise<{ proxy: string }> { return client.patch('/creator-services/network', network); },getCodexModelStatus(): Promise<CodexProviderConfig> {return client.get('/creator-services/model/codex/status');},diff --git a/apps/web/src/services/gateway-account-service.test.ts b/apps/web/src/services/gateway-account-service.test.tsnew file mode 100644index 00000000..ef23b69e--- /dev/null+++ b/apps/web/src/services/gateway-account-service.test.ts@@ -0,0 +1,28 @@+import { expect, it, vi } from 'vitest';+import { RuntimeClient } from '../runtime/client.js';+import { createGatewayAccountService } from './gateway-account-service.js';++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)) });+ await expect(createGatewayAccountService(client).getState()).resolves.toEqual(snapshot);+});++it('reads the subscription summary through the shared Daemon', async () => {+ const client = new RuntimeClient({ baseUrl: 'http://localhost', fetchImpl: vi.fn(async () => Response.json({})) });+ const read = vi.spyOn(client, 'get');+ await createGatewayAccountService(client).getSummary();+ expect(read).toHaveBeenCalledWith('/gateway/billing/summary');+});++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' } }));+ const client = new RuntimeClient({ baseUrl: 'http://localhost', token: 'runtime-token', fetchImpl: fetcher });+ const service = createGatewayAccountService(client);+ const [first, second] = await Promise.all([service.getAvatar!('a', 'picture-1'), service.getAvatar!('a', 'picture-1')]);+ expect(first).toBe(second);+ expect(first.type).toBe('image/png');+ expect(fetcher).toHaveBeenCalledExactlyOnceWith('http://localhost/gateway/avatar?accountId=a', expect.objectContaining({ headers: { Authorization: 'Bearer runtime-token' } }));+ await service.getAvatar!('b', 'picture-2');+ expect(fetcher).toHaveBeenCalledTimes(2);+});diff --git a/apps/web/src/services/gateway-account-service.ts b/apps/web/src/services/gateway-account-service.tsnew file mode 100644index 00000000..0f820b14--- /dev/null+++ b/apps/web/src/services/gateway-account-service.ts@@ -0,0 +1,40 @@+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 GatewayBillingSummary = {+ balance: GatewayBalanceSnapshot;+ subscription: { id: string; status: string; periodStart: string; periodEnd: string; cancelAtPeriodEnd: boolean; nextPlanId: string | null; plan?: GatewayPlan } | null;+ billingAvailable: boolean;+ purchaseMode?: 'credits';+ plansUrl?: string;+ paymentReview?: boolean;+};+export function createGatewayAccountService(client: Pick<RuntimeClient, 'get' | 'post' | 'patch'> & Partial<Pick<RuntimeClient, 'rawGet'>>) {+ const rawGet = client.rawGet?.bind(client);+ let avatarCache: { key: string; work: Promise<Blob> } | undefined;+ return {+ ...(rawGet ? { getAvatar(accountId: string, revision: string): Promise<Blob> {+ const key = `${accountId}:${revision}`;+ if (avatarCache?.key === key) return avatarCache.work;+ const work = rawGet('/gateway/avatar?accountId=' + encodeURIComponent(accountId)).then(response => {+ if (!['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(response.headers.get('content-type')?.split(';')[0] ?? '')) throw new Error('Account picture is unavailable');+ return response.blob();+ }).catch(error => { if (avatarCache?.key === key) avatarCache = undefined; throw error; });+ avatarCache = { key, work };+ return work;+ } } : {}),+ getState(): Promise<GatewayAccountState> { return client.get('/gateway/account'); },+ start(): Promise<GatewayAuthorization> { return client.post('/gateway/auth/start', {}); },+ 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', {}); },+ setSource(source: ServiceSource): Promise<GatewayAccountState> { return client.patch('/gateway/source', { source }); },+ 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 }); },+ portal(): Promise<{ url: string }> { return client.post('/gateway/billing/portal', {}); }+ };+}+export type GatewayAccountSettingsService = ReturnType<typeof createGatewayAccountService>;diff --git "a/docs/plans/OpenCreator\347\273\237\344\270\200\347\275\221\345\205\263\347\231\273\345\275\225\350\256\242\351\230\205\344\270\216\347\247\257\345\210\206-\345\256\236\346\226\275\350\256\241\345\210\222-2026-10-05.md" "b/docs/plans/OpenCreator\347\273\237\344\270\200\347\275\221\345\205\263\347\231\273\345\275\225\350\256\242\351\230\205\344\270\216\347\247\257\345\210\206-\345\256\236\346\226\275\350\256\241\345\210\222-2026-10-05.md"new file mode 100644index 00000000..4ba11f85--- /dev/null+++ "b/docs/plans/OpenCreator\347\273\237\344\270\200\347\275\221\345\205\263\347\231\273\345\275\225\350\256\242\351\230\205\344\270\216\347\247\257\345\210\206-\345\256\236\346\226\275\350\256\241\345\210\222-2026-10-05.md"@@ -0,0 +1,452 @@+# OpenCreator 统一网关、登录、订阅与积分实施计划++> 状态:已授权执行;2026-10-05 开始实施。+> 体量判断:复杂,但保持一个交付。Go 网关与共享客户端需要共同完成登录、付款、积分及真实模型调用,不能按语言或目录拆成互相等待核心契约的独立 Plan。+> 来源方案:[已批准方案](../specs/OpenCreator统一网关登录订阅与积分-方案-2026-10-05.md)。+> 方案批准:2026-10-05,用户在一期简化结果之后回复“继续”。方案流程为 PASS(用户知情批准);不是本计划的执行授权。+> 原始审核:方案独立 Reviewer 未执行;主 Agent 原始结论 REVISE。MA-1/MA-3 已移出一期,MA-2 收敛为同一订阅 Invoice 只发一次积分,MA-4 风险保留并由 TASK-1 优先验证。+> Plan Reviewer 原始结论:未执行;当前会话无 spawn_agent、wait_agent、close_agent,未启动、无 agent_id。+> 流程结论:PASS(用户知情授权执行);独立审核未执行及 MA-4 遗留风险继续保留。+> 执行授权:2026-10-05,用户在看到计划与审核状态后明确回复“开始执行”。++## 1. 契约快照++交付一个 Go 网关和 OpenCreator 的共享客户端接入,用户流程为“登录 -> 月订阅付款 -> 积分到账 -> 使用多模态模型”。每个用户只有一把当前有效的云模型 Key,网关可以连接其他中转站,用户不填写各模态地址与密钥。账户与模型调用凭证分离,后续权益可在账户上扩展。++一期不交付套餐停售、历史套餐迁移、退款/拒付自动处理、跨 Invoice 权益合并、补充账单、团队、年付、充值包、优惠券、自动充值、免费试用积分或项目/文件云同步。不新建独立认证后端、第二套 Desktop 页面、模板专属 Agent Panel、Redis 或独立消息队列。不创建远程仓库、执行远程更名、推送、公开部署或真实生产付款。++### 1.1 功能与规则++| ID | 优先级 | 必须交付的行为 |+|---|---|---|+| FR-1 | P0 | 邮箱注册、验证、密码登录、找回,以及 Google、GitHub 登录 |+| FR-2 | P0 | 浏览器设备授权、可刷新会话、取消/超时/退出及重启恢复 |+| FR-3 | P0 | 同账户、全部模态及设备共享一把当前有效模型 Key;重新登录复用 |+| FR-4 | P0 | 登录后自动取得官方配置,配置和 Runtime 真正就绪后启用 |+| FR-5 | P0 | 文本、图片、视频、TTS、转写,以及 Agent 工具调用与流式协议;仅开放验证能力 |+| FR-6 | P0 | Stripe 个人月订阅、自动续费、取消/恢复续订及下一周期套餐变更 |+| FR-7 | P0 | 确认付款后发积分,模态共用余额,不足时拦截新生成 |+| FR-8 | P1 | 账户页面展示订阅、有效期、可用/预占积分、使用记录及订单 |+| FR-9 | P0 | 最小管理:套餐/模型价格、渠道、用户停用、待核对结算及带原因的账本调整;有权限和审计 |+| FR-10 | P0 | 原手动配置、本机能力及 BYOK 保留,旧用户不自动换模式,直连不扣网关积分 |+| FR-11 | P0 | 请求有稳定身份、可查询恢复状态;查询、重连和重启不重复提交 |+| FR-12 | P0 | 登录、配置、支付、余额和网关故障准确呈现;失败不伪装为零余额,不自动换服务 |+| BR-1 | P0 | 身份归属验证;同邮箱不自动合并;未验证身份不能获得模型凭证或购买 |+| BR-2 | P0 | 模型 Key 只用于模型及所属请求查询;不能管理账户/付款;重置旧值立即失效 |+| BR-3 | P0 | 同一已付款月订阅 Invoice 只发一次;当期积分不结转;取消保留当期,失败续费不发放,套餐下期变更;新账户零积分 |+| BR-4 | P0 | 同账户、操作、逻辑 ID 与参数复用原请求;参数冲突拒绝;只结算一次,查询和下载不重复收费 |+| BR-5 | P0 | 服务端以价格快照、可信用量和可执行消费上界原子预占、整数结算 |+| BR-6 | P0 | 受理或用量未知时持久化核对,无安全重试证据不重发,确认无消费才全部释放 |+| BR-7 | P0 | 已预占请求跨周期仍用原批次,过期部分释放后不恢复可用余额 |+| BR-9 | P0 | 活跃任务绑定原账户/模式;切换等其结束;退出拦截新请求,已提交任务继续结算,恢复需原账户 |+| NFR-1 | P0 | 原始凭证不进入页面、浏览器存储、授权 URL 或日志;本机和服务端的实际访问控制有证据 |+| NFR-2 | P0 | 登录、绑定、付款、结果和转发校验主体/来源/归属;不把上游凭证发送给用户指定主机 |+| NFR-3 | P0 | PostgreSQL 是计费事实来源,发放、预占、结算和恢复在并发及崩溃下保持一致 |+| NFR-4 | P0 | 官方 Runtime 和配置来源隔离,不覆盖个人 Codex 或手动凭证 |+| NFR-5 | P0 | 共享 Web/Daemon、唯一 Panel、规范进度及风险匹配的 Web/Desktop 门禁 |++BR-8 为后续事项,不是本期实现或验收任务;保留编号用于追溯。++### 1.2 不可替换的决策++| ID | 执行约束 |+|---|---|+| DEC-1 | Go 模块化单体、PostgreSQL、持久化后台处理;账户和最小管理页面由该 Go 服务托管 |+| DEC-2 | 浏览器会话、Daemon 设备会话、云模型 Key 分用途;浏览器一次性设备授权 |+| DEC-3 | Stripe 托管结账/管理;回调验签,Invoice 发放标记与积分同事务 |+| DEC-4 | 随机高熵模型 Key,摘要鉴权、独立主密钥加密副本;数据库限制每用户一个当前有效值 |+| DEC-5 | 网关对外稳定文本/图片/语音 API 和统一视频任务;渠道及 Adapter 隔离厂商协议 |+| DEC-6 | 整数最小积分单位、批次、原子预占和不可改写记录;受理时固定模型/渠道/价格/消费上界 |+| DEC-7 | 请求与计费状态分离,稳定逻辑 ID,未知受理/用量持久化核对及人工关闭 |+| DEC-8 | 共享 Daemon 解析官方来源,唯一模型 Key 单一私有存储、按调用注入;官方 Runtime 与原配置分离 |+| DEC-9 | 共享账户界面和现有 openExternal;沿用 Panel/Adapter/预检/错误;不把共享 Web 改动自动升级为 Desktop 打包 |++### 1.3 接口、状态与金额++网关账户路径和模型路径不能互认凭证。接口的管理对象从当前身份解析,禁止客户端指定任意 Customer/Subscription 或上游地址。++| 网关接口 | 输入、鉴权与输出 |+|---|---|+| POST /api/v1/auth/register、/verify-email、/login、/forgot-password、/reset-password | 浏览器账户流程;邮箱/密码或单次令牌;公共响应不泄露账户存在性;返回受验证会话或公开错误 |+| GET /api/v1/auth/oauth/{provider}/start、/callback | provider 只允许 google/github;state、适用 PKCE/nonce、身份验证;已有邮箱要求登录原账户后绑定 |+| POST /api/v1/auth/device/start、/approve、/cancel、/token | start 返回秘密、定位链接、10 分钟期限和初始 5 秒轮询间隔;approve 需要浏览器登录及 CSRF;token 仅发起端凭秘密单次领取设备会话 |+| POST /api/v1/auth/refresh、/logout | 设备账户会话;15 分钟访问凭证、30 天刷新凭证;刷新串行轮换和重放检测;退出只撤销当前设备 |+| GET /api/v1/me、/client/bootstrap | me 返回脱敏账户;bootstrap 只接受服务端确认 kind=daemon 的会话,返回 schemaVersion=1、账户、Key/版本、目录、默认模型和接口能力;不接受普通浏览器 Cookie 下发 Key |+| POST /api/v1/model-key/rotate | 所属账户与近期身份验证;事务停用旧值,建立唯一新值;其他设备重新 bootstrap |+| GET /api/v1/plans;POST /api/v1/billing/checkout | 配置套餐;checkout 需要已验证账户、planId 和 operationId;服务端解析金额、Price、Customer,返回原订单和托管 URL |+| POST /api/v1/billing/portal、/subscription/cancel、/subscription/resume、/subscription/change | 所属账户;portal 返回所属 Customer 的托管管理 URL,平台配置不能开放即时套餐变更;change 仅选择下期 planId;禁止立即补差价或新建第二份有效订阅 |+| GET /api/v1/billing/summary、/orders、/ledger | 所属账户与游标分页;订阅状态、到期时间、金额字符串、时间戳、原订单及消费明细 |+| POST /api/v1/webhooks/stripe | SDK 验证原始 body 签名,接收记录落库;月订阅创建/续费的已付款 Invoice 发放一次,其他支付事件不触发本期积分调整 |+| /api/v1/admin/plans、/models、/channels、/users、/requests、/ledger-adjustments | 独立管理员权限;有效配置、停用、带证据结算/释放/调整及审计;不包含停售/退款流程 |+| GET /v1/models;POST /v1/responses、/chat/completions | 模型 Key;合法模型与真实能力;Responses 保留工具、终态与流式事件,不能用未验证的 Chat 转换冒充 |+| POST /v1/images/generations、/images/edits、/audio/speech、/audio/transcriptions | 模型 Key;能力、大小和输入上限;图片结构、音频二进制及 multipart 转写保留协议 |+| POST /v1/video/jobs;GET /v1/video/jobs/{id}、/result | 模型 Key;稳定任务、归属、进度和可下载结果;创建收费,查询及下载不重复收费 |+| GET /v1/requests/{requestId} | 所属模型 Key;原请求状态、用量、计费状态及有效结果引用,不创建新生成 |++公共错误为 `{error:{code,message,requestId,recovery}}`,不含原始私有上游响应。401 表示凭证失效,403 表示停用/越权,402 表示有效积分不足,409 表示 request_id_conflict 或原请求进行中,400 表示参数/能力/版本不匹配。进入流式后使用相应协议的错误事件,原 requestId 仍可查询。++上述结构是云网关响应,不替换现有本地 ApiError。Daemon 使用 apiError,把网关错误分别映射为 GATEWAY_AUTH_REQUIRED、GATEWAY_ACCOUNT_DISABLED、GATEWAY_CREDITS_INSUFFICIENT、GATEWAY_REQUEST_CONFLICT、GATEWAY_SERVICES_NOT_READY、GATEWAY_UNAVAILABLE;保留经校验的 gatewayCode/requestId/recovery 于 details。PublicErrorFacts 分别使用 unauthorized、http-rejected、http-rejected、conflict、configuration、unavailable,附可信 httpStatus,避免把公开错误类型扩大为原始响应透传。++共享公开协议的最小类型如下;raw bootstrap 仅在 Daemon 内部解码,不能在此接口新增秘密字段:++```ts+export type ServiceSource = 'manual' | 'gateway';+export type GatewayAccountState = {+ source: ServiceSource;+ authState: 'signed_out' | 'authorizing' | 'signed_in' | 'signing_out' | 'expired' | 'disabled';+ activationState: 'inactive' | 'loading' | 'ready' | 'blocked';+ account: { id: string; email: string; verified: boolean } | null;+ bindingVersion: string | null;+ models: Array<{+ id: string;+ modality: 'text' | 'image' | 'video' | 'speech' | 'transcription';+ capabilities: string[];+ }>;+ activationError: { code: string; message: string } | null;+};+export type GatewayBalanceSnapshot = {+ availableUnits: string;+ reservedUnits: string;+ periodEnd: string | null;+ asOf: string;+};+export type GatewayBalanceState =+ | { status: 'ready'; value: GatewayBalanceSnapshot }+ | { status: 'unavailable'; lastKnown: GatewayBalanceSnapshot | null; code: string };+```++请求状态为 accepted/submitting/waiting_upstream/succeeded/failed/outcome_unknown/canceled;计费状态为 reserved/settled/released/reconciling/manual_review。设备状态为 pending/approved/consumed 或 denied/canceled/expired。同一请求结算、释放均受条件状态及唯一业务键约束。++积分 JSON 用十进制整数字符串:1 积分等于 1,000,000 最小单位。Go 用受溢出检查的整数/有理数,前端用字符串和 BigInt 处理,禁止浮点扣费。按价格快照计算 `reserve=ceil(sum(maxUnits*rate))`、`charge=ceil(sum(verifiedUnits*rate))`,只在请求总额处向上取整。缓存量是输入量的分类,不能再重复计入普通输入。超上界消费不向用户隐式透支,保留真实成本、暂停问题路由并核对。++### 1.4 数据约束与最小 Runtime 边界++Go 迁移按账户/支付/请求三个行为任务增加,不一次创建所有未来表。核心约束如下,所有时间用 UTC,积分有效期为半开区间 [start,end):++| 数据 | 必须存在的约束 |+|---|---|+| users、identities、sessions、email_tokens、device_grants | 标准化邮箱唯一,provider+subject 唯一;会话 kind 明确;秘密只保存摘要;单次令牌领取和撤销原子化 |+| model_keys | account_id 上 current=true 的部分唯一索引;key_hash 唯一;key_ciphertext、nonce、master_key_version;停用旧 Key 和创建新值同事务 |+| plans、subscriptions、payment_operations、invoices、webhook_events | 使用订单/Price 快照;账户最多一个有效订阅;操作 ID、Stripe 标识唯一;Invoice 发放标记唯一;未付款不创建有效积分 |+| credit_batches、balances、credit_ledger | 批次保留 Invoice/周期来源;余额行锁与批次分配;账本业务键唯一且应用角色不得改写历史记录;投影与记录同事务 |+| model_routes、requests、reservations | 对外模型、能力、价格与渠道版本;requestId 稳定;account_id+operation+logical_id 唯一,指纹包含规范参数和媒体摘要;预占记录原批次 |+| 审计及结果 | 管理操作保留操作者、原因、相关账本/请求;媒体私有暂存、到期引用可识别,不作为长期云文件库 |++迁移使用明确唯一约束,不能只在 handler 内先查再写:++```sql+CREATE UNIQUE INDEX model_key_one_current+ ON model_keys (account_id) WHERE current = true;+CREATE UNIQUE INDEX invoice_identity ON invoices (stripe_invoice_id);+CREATE UNIQUE INDEX ledger_business_once ON credit_ledger (business_key);+CREATE UNIQUE INDEX request_logical_identity+ ON requests (account_id, operation, logical_id) WHERE logical_id IS NOT NULL;+```++grant 的 business_key 为 `invoice:<Stripe Invoice ID>`,结算为 `settle:<requestId>`,单独全部释放为 `release:<requestId>`;Settle 内的消费及未用预占释放仍属同一次事务,不允许通过分别重试造成二次释放。应用数据库角色可写余额投影和新账本,不能 UPDATE/DELETE 历史账本。++请求先事务受理及预占,再执行上游。worker 对 accepted 的状态转换只能成功一次;提交后崩溃转 unknown,不把过期租约当成可以重新收费提交的证据。已受理时固定 route/price/model/maxUnits,调价不改变原请求。到期仅过期未预占余额;已预占请求用原批次结算,剩余过期部分不得成为新余额。核对超期转 manual_review,不能按 TTL 自动释放。++MA-4 采用最小实现候选并优先实测:官方 Runtime 使用专用 home 和 provider env_key,云 Key 只从 Daemon 私有存储读入进程内存,不写入第二份 auth.json。官方配置不能复制个人 auth/config/provider;官方进程使用明确的基础环境,排除个人模型地址和凭证来源。Runtime 无稳定调用 ID 时关闭不安全的自动重发。++设备退出先关闭 Daemon 的新请求准入并撤销本机调用资格,再关闭所有持有该官方凭证的本机 Runtime;确认其退出后才返回退出成功。退出进行中显示状态,不提前宣告成功。已受理的云端请求保留身份和预占,云端继续核对/结算;停止本机等待不等于远端无消费。其他设备和账户级云 Key 不撤销。只用 invalidate 标记进程 stale 不足以证明退出权限已撤销。++该候选仅落实 BR-9/DEC-8,不增加独立本机代理服务。若实际 Runtime 不能满足环境凭证、重试或退出后的发起边界,TASK-1 停止官方模式启用并报告差异,不能自行切换架构或降低 AC。原生第三方进程的凭证行为尚未实测,这是已接受的方案遗留风险。++## 2. 基线、文件地图与公共命令++### 2.1 工作根目录和已核对事实++- OC:/Users/leggett/develop/github/open-creator;分支 feat-user-login,commit c4a21c0202478118d5501188b11d61b186cfb431,生成计划时工作区无业务 diff;遵守其 AGENTS.md。+- GW:执行时的本地目标目录 /Users/leggett/develop/github/open-creator-gateway,当前尚未创建或检查。2026-10-05 gh 查询 open-creator-gateway 不能解析,open-creator-auth 为私有空仓库、无默认分支。+- TASK-0 优先查询目标仓库;仍只有旧仓库时,以已授权的 [email protected]:wulien/open-creator-auth.git 克隆到 GW 本地目录。Go module 使用 github.com/wulien/open-creator-gateway;保留当时实际 origin,不擅自执行远程更名或推送。目录已有内容时先只读检查,禁止覆盖。+- Go 使用标准 net/http、html/template、crypto/aes、crypto/rand、pgx/v5、成熟 OAuth/OIDC 与密码哈希库及 Stripe 官方 Go SDK;依赖锁定 go.mod/go.sum。仅新增本行为所需依赖,不增加第三个业务后端。++| 已有文件/符号 | 已核对行为与任务影响 |+|---|---|+| packages/protocol/src/creator-services.ts、index.ts、errors.ts、issues.ts | 已有各模态配置、公开错误和导出;gateway 来源/公开账户类型应单独定义,不把云 Key 放进浏览器类型;沿用 apiError/PublicErrorFacts |+| apps/daemon/src/config/private-json-file.ts:readPrivateJsonFile、createPrivateJsonDocumentEntry | 原子私有文件能力;gateway 独立凭证文件避免覆盖原凭证;Windows 权限仍须实测 |+| apps/daemon/src/creator-services/config-store.ts:createOpenCreatorCreatorServicesConfigStore、createCreatorServicesConfigStoreWithTextModelFallback | 读取手动设置及个人 Codex fallback;官方源必须先于 fallback 解析,保存手动源仍走旧逻辑 |+| apps/daemon/src/codex/probe-home.ts:createCodexIsolatedHome;creator/agent/bootstrap.ts:bootstrapCreatorAgentRuntime | 当前会复制个人 auth/config;官方 bootstrap 必须另走隔离路径,不能据目录独立推断凭证独立 |+| apps/daemon/src/codex/app-server-runtime-manager.ts:createAppServerRuntimeManager、invalidate、closeScope、closeScopes、close | invalidate 对活跃进程只记 stale;设备退出必须真正关闭持有官方凭证的进程及待启动队列 |+| apps/daemon/src/codex/app-server-host-2026-07-28.ts:createCodexAppServerHost;runner.ts:startCodexExec | 当前继承 process.env;新增受控环境只能影响官方源,原手动源保持兼容 |+| apps/daemon/src/api/server.ts:buildServer、creatorAgentBootstrapInput、creatorAppServerRuntimeManager、creatorServicesConfigStore | 集中注入配置/Runtime;避免调用 personal provider 更新路径重启不相关任务 |+| apps/daemon/src/creator/provider-requests.ts:CreatorProviderRequestLedger | 已有 requestKey、指纹及未知受理状态;加入网关身份关联,沿用原恢复机制 |+| image-generation/provider.ts:generateImageContents;video-generation/service.ts:createVideoGenerationService;creator/article/model.ts:createWechatArticleModel;creator/krillin/config-bridge.ts:createKrillinConfigToml;creator/krillin/tts-service.ts:createKrillinTtsService | 图片/视频和 Krillin 的协议不同,视频需要统一网关分支;Krillin TOML 当前会写 Key,不能直接将云 Key 落入每任务配置 |+| creator/krillin/codex-llm-gateway.ts:createKrillinCodexLlmGateway | 已有 Daemon 本机调用通道和临时 token;可复用其边界供旧执行器按调用注入,不能另起认证/计费服务 |+| apps/web/src/app/AppController.tsx、features/settings/StartupAgentSetup.tsx、CreatorServicesSettingsView.tsx、SettingsPage.tsx | 实际共享入口和设置页;账户服务使用 RuntimeClient,不使用 hostBridge.kind 分叉 |+| apps/web/src/runtime/client.ts、services/creator-services-service.ts、host/bridge.ts | 现有 API/公开错误与 openExternal;账户服务沿用模式,授权链接始终可点击 |+| apps/web/e2e/web-desktop-parity.spec.ts、fixtures/runtime.ts;playwright.config.ts | 已有 Fake Daemon 和双 Bridge;浏览器内容视口固定,Desktop 实包验证按实际 diff 决定 |++以上路径除 packages 和 apps/web 前缀外,Daemon 相对路径均位于 OC/apps/daemon/src。新建文件在 TASK 中列出;新路径不表示当前已有实现。++### 2.2 命令++命令只在这里定义一次。DTEST/WTEST/PTEST 后追加任务列出的测试路径,路径相对于表中工作目录;退出 0 才算通过。现有 scripts 的 pretest/pretypecheck 会构建依赖包,这是已有编译边界,不能因此运行全仓测试或 Desktop 打包。++| 名称 | 工作目录 | 命令与用途 |+|---|---|---|+| PREP | OC | 依次执行 pnpm --filter @opencreator/protocol build、pnpm --filter @opencreator/config build、pnpm --filter @opencreator/skill-market build、pnpm --filter @opencreator/writing-templates build;只准备实际工作区编译依赖 |+| DTEST | OC/apps/daemon | pnpm exec vitest run;仅运行任务明确列出的测试 |+| WTEST | OC/apps/web | pnpm exec vitest run;仅运行任务明确列出的测试 |+| PTEST | OC/packages/protocol | pnpm exec vitest run;协议定向测试 |+| PTYPES | OC | pnpm --filter @opencreator/protocol typecheck |+| DTYPES | OC | pnpm --filter @opencreator/daemon typecheck |+| WTYPES | OC | pnpm --filter @opencreator/web typecheck |+| DBUILD | OC | pnpm --filter @opencreator/daemon build;Runtime/协议编译边界变化后运行 |+| GWTEST | GW | go test;追加相应包、-run 和 -count=1;并发测试另使用 -race |+| GWBUILD | GW | go build -o .local/open-creator-gateway ./cmd/gateway |+| GWDB | GW | docker compose up -d postgres;仅用于隔离本地 PostgreSQL,不启 Redis/队列 |+| GWSTART | GW | go run ./cmd/gateway;配置读取私有 .local/gateway.env,缺生产前置配置时保持对应能力关闭 |+| GWAC | GW | go test ./test/acceptance -run TestPublic -count=1;真实 HTTP 与 PostgreSQL,外部替身不替换业务逻辑 |+| UIAC | OC | pnpm exec playwright test apps/web/e2e/gateway-account.spec.ts --project=chromium-desktop;另以 chromium-mobile 运行账户入口/状态布局 |+| PARITY | OC | pnpm exec playwright test apps/web/e2e/gateway-web-desktop-parity.spec.ts --project=chromium-desktop |++先执行 PREP,再执行 DTEST/WTEST;协议变动后刷新对应编译依赖。每个新测试套件必须确认被发现且至少运行一项,不能把 passWithNoTests 当成通过。GW 使用 Go 1.24 或以上及 PostgreSQL 16 或以上;工具版本不满足时仅阻塞其依赖任务,不修复无关环境。++本地网关默认监听 127.0.0.1:19871,数据库测试端口 55432;启动前确认端口,已占用时在隔离配置中选择空闲端口。生产账户和 OAuth 对外使用 HTTPS;本地浏览器验收通过受信任测试 HTTPS 来源或测试夹具 TLS,不放宽生产 Cookie/证书规则。密钥不进入命令行参数、仓库或验收记录。++## 3. 追踪矩阵++| 任务 | 需求/规则 | 决策 | 自动化测试位置 | 功能验收 |+|---|---|---|---|---|+| TASK-1 | FR-4、FR-10、BR-9、NFR-1、NFR-4 | DEC-8 | gateway-runtime-bindings.test.ts、gateway-runtime-protocol.test.ts | AC-4、AC-10、AC-12 |+| TASK-2 | FR-1、BR-1、NFR-2 | DEC-1、DEC-2 | GW/internal/server/auth_test.go | AC-1 |+| TASK-3 | FR-2、FR-3、BR-2、NFR-1、NFR-2 | DEC-2、DEC-4 | GW/internal/server/device_test.go、modelkey_test.go | AC-2、AC-3、AC-12 |+| TASK-4 | FR-6、FR-7、BR-3、NFR-3 | DEC-1、DEC-3、DEC-6 | GW/internal/server/billing_test.go | AC-6 |+| TASK-5 | FR-5、FR-7、FR-11、BR-4、BR-5、BR-6、BR-7、NFR-2、NFR-3 | DEC-5、DEC-6、DEC-7 | GW/internal/server/requests_test.go | AC-5、AC-7、AC-11、AC-12 |+| TASK-6 | FR-5、FR-11、FR-12、BR-4、BR-6、NFR-2、NFR-3 | DEC-5、DEC-7 | GW/internal/server/modalities_test.go、recovery_test.go | AC-5、AC-11、AC-12 |+| TASK-7 | FR-2、FR-4、FR-10、FR-12、BR-9、NFR-1、NFR-4 | DEC-2、DEC-8 | gateway-account-contract.test.ts、gateway-account-service.test.ts、gateway-account-api.test.ts、creator-services-config-store.test.ts | AC-2、AC-4、AC-10、AC-12 |+| TASK-8 | FR-5、FR-10、FR-11、FR-12、BR-4、BR-9、NFR-4、NFR-5 | DEC-5、DEC-7、DEC-8、DEC-9 | creator-gateway-services.test.ts、creator-provider-requests.test.ts、krillin-codex-llm-gateway.test.ts | AC-5、AC-10、AC-11、AC-13 |+| TASK-9 | FR-4、FR-8、FR-12、NFR-5 | DEC-8、DEC-9 | GatewayAccountSettingsView.test.tsx、gateway-account-service.test.ts、StartupAgentSetup.test.tsx | AC-4、AC-8、AC-13 |+| TASK-10 | FR-8、FR-9、NFR-1、NFR-2 | DEC-1、DEC-3、DEC-6、DEC-7 | GW/internal/server/admin_test.go、account_pages_test.go | AC-8、AC-9、AC-12 |+| TASK-11 | FR-12、NFR-1、NFR-3、NFR-4、NFR-5 | DEC-1、DEC-8、DEC-9 | GW/internal/server/config_test.go、gateway-account-api.test.ts | AC-4、AC-6、AC-11、AC-12、AC-13 |+| TASK-12 | FR-1 至 FR-12、BR-1 至 BR-7、BR-9、NFR-1 至 NFR-5 | DEC-1 至 DEC-9 | GW/test/acceptance/public_test.go、gateway-account.spec.ts、gateway-web-desktop-parity.spec.ts | AC-1 至 AC-13 |++## 4. 行为任务++### TASK-0:确认 Plan 仍然有效++核对 OC 的分支/commit、上述文件、符号、命令和批准记录;运行 git status --short,保留已有用户改动。无关变化或不改变契约的路径/命名变化记录后继续;职责、接口、数据、DEC 或 AC 失效则停止,不静默重设计。++只读核对 GW 目标:gh repo view wulien/open-creator-gateway --json nameWithOwner,isEmpty,defaultBranchRef;不可解析时查询 open-creator-auth。本地目录不存在且仍只有空的旧仓库时,执行 git clone [email protected]:wulien/open-creator-auth.git /Users/leggett/develop/github/open-creator-gateway。已有目录先检查,不覆写,也不为本任务扫描父目录。克隆后读取 GW 自身 AGENTS.md(若存在),记录真实 origin、分支及 commit/空仓事实。++确认 PostgreSQL、Go、Node/pnpm 和实际 bundled Codex 路径;核对 OAuth、邮件、Stripe 测试环境、域名及各模态配置的可用性,不虚构值。缺外部凭证仍可进行替身下的实现和局部测试,但其真实验收标记 BLOCKED,不宣称完整交付。TDD 豁免:仅基线/环境检查,不改变产品行为。++### TASK-1:优先验证官方 Runtime 的隔离、重试与退出++依赖 TASK-0;在收费路由开放之前完成。++文件:创建 OC/apps/daemon/src/gateway/runtime-bindings.ts;修改 codex/app-server-host-2026-07-28.ts 和 codex/runner.ts 的官方环境输入边界;测试 OC/apps/daemon/test/unit/gateway-runtime-bindings.test.ts、test/integration/gateway-runtime-protocol.test.ts。这些 Daemon 路径均相对 apps/daemon/src 或 test。++代码边界:`createGatewayRuntimeBindings(input)` 返回 `prepare(): Promise<{codexHome:string; env:Record<string,string>; generation:number}>`、`beginLogout(): void`、`close(): Promise<void>`。prepare 从私有凭证 callback 获取 Key,写仅含官方 provider 配置的 home,provider env_key=OC_GATEWAY_MODEL_KEY,wire_api=responses;该 Key 只放入受控子进程环境。官方参数禁止从个人 home、process.env 模型字段或原 provider credential fallback 读取。给进程启动接口增加显式 baseEnvironment,缺省保持旧 manual 行为,官方使用基础环境 allowlist。++先对实际 bundled Runtime 验证该配置、零不安全自动重发及工具/流式协议。beginLogout 原子关闭发起 gate;close 关闭官方 manager 和待启动队列、等待进程退出并清除内存;只有 close 完成才允许退出 API 返回成功。普通 invalidate 不作为退出实现。进程 close 的已有超时/强制终止逻辑复用,不新增通用进程框架。++TDD 必须:namespace/dynamic import 新边界,断言缺少 createGatewayRuntimeBindings 的业务能力为 RED,不能把模块加载失败当 RED。TestRuntimeCannotStartAfterLogout 用两账户、带个人 Key 的父环境和可暂停的真实测试上游:首个请求受理后退出,再触发下一模型调用,期望成功退出后无新调用、无个人 Key、云 requestId 仍可查询。基线为现有 codex-app-server-client-shutdown.test.ts。GREEN 仅补受控环境、官方 home 与实际关闭 gate;DTEST 运行新两文件及上述基线。若 bundled Runtime 无法满足任一边界则本任务 BLOCKED,报告所需方案变化,不能自动引入第二种认证架构。++完成门:针对实际 Runtime 的结果满足 AC-4/AC-10/AC-12 对应部分;本任务不声称网关计费已完成。++### TASK-2:提供账户注册与三种浏览器登录++依赖 TASK-0,和 TASK-1 可独立开展,官方启用仍等待 TASK-1。++GW 创建 go.mod、cmd/gateway/main.go、internal/server/server.go、internal/auth/service.go、internal/auth/oauth.go、internal/storage/store.go、internal/storage/migrations/001_accounts.sql、web/templates/auth.html;测试 internal/server/auth_test.go,公共夹具 internal/testkit/harness.go。超过五个文件是空仓库中一个真实登录行为所需的启动、持久化、页面与外部身份边界,不按层另建交付。++先搭能运行的 NewServer(Dependencies) http.Handler、GET /healthz 和测试数据库夹具,再写认证 RED。用 pgx、标准模板、成熟 OAuth/OIDC 库及 bcrypt;浏览器 Cookie Secure/HttpOnly/SameSite、CSRF/origin;邮箱令牌单次和到期,邮件发送边界可替身但领取走真实路由。身份只认验证后的 provider/subject,同邮箱先证明原账户归属。注册硬编码普通用户角色;管理员不经公开注册授予。++TDD 必须:TestRegisterRequiresVerifiedEmail 经公开注册/验证/登录路由创建账户,验证前购买和模型凭证访问拒绝,消费验证令牌一次后登录成功;TestOAuthSameEmailDoesNotMerge 用受控 OAuth 声明证实需原账户绑定;错误 state、过期/重放令牌及重复回调均拒绝。RED 为真实路由尚未提供该行为,不是 Go 编译或依赖失败。GREEN 完成 auth handler 和事务,不 mock 账户判断。GWTEST ./internal/server -run 'TestRegister|TestOAuth|TestPasswordReset' -count=1;回归健康和迁移测试。++完成门:AC-1 的确定性 API/页面流程;真实 OAuth/邮件另在 TASK-12 验收。++### TASK-3:设备授权后下发用户唯一模型 Key++依赖 TASK-2。GW 修改 internal/auth/service.go、internal/server/server.go;创建 internal/modelkey/service.go、internal/storage/migrations/002_device_model_key.sql、web/templates/device.html;测试 internal/server/device_test.go、modelkey_test.go。++实现设备状态、频率/轮询约束与原子单次领取。sessions 用 kind 区分浏览器/Daemon;bootstrap 在服务端验证会话种类,返回完整 schemaVersion=1 快照。Key 使用 32 随机字节,摘要鉴权及 AES-GCM 加密副本、独立主密钥和 key version;并发领取在账户锁和唯一索引下取得同一当前值。rotate 在同事务替换旧值。刷新串行轮换,重放撤销相应设备令牌族;失效公开提示重新授权,迟到结果不能覆盖新尝试。++TDD 必须:TestDeviceConsumedOnce 并发领取只有一次得到会话;TestModelKeySharedAcrossDevices 两个 A 设备并发 bootstrap 得同一 Key,B 不同;TestModelKeyCannotManageAccount 尝试账单和管理接口被拒绝,rotate 后旧 Key 401,新 Key 仍能查询 A 原任务。浏览器 Cookie bootstrap 返回拒绝而不是 Key。GREEN 只实现用途隔离和持久化约束;GWTEST ./internal/server -run 'TestDevice|TestModelKey' -count=1,另以 -race 运行两项并发测试,回归 auth。++完成门:AC-2/AC-3 的网关部分和 AC-12 凭证响应边界。++### TASK-4:月订阅付款后发放一次当期积分++依赖 TASK-3。GW 创建 internal/billing/service.go、internal/billing/stripe.go、internal/credits/service.go、internal/storage/migrations/003_subscription_credits.sql;修改 internal/server/server.go;测试 internal/server/billing_test.go。++加入套餐/订单快照、账户唯一有效订阅及 payment operation 幂等。调用 Stripe 官方 SDK 托管 Checkout,服务端选择 Price/Customer;下期套餐变更、取消/恢复作用于同一订阅。验签接收记录落库后处理合法已付款月订阅 Invoice:事务检查 Invoice 发放标记,创建批次、grant 账本并更新余额;并发冲突返回原发放结果。新续费 Invoice 创建新一期;网页跳回、订阅创建或未付款 Invoice 不发放。保留持久化接收/重试状态,不建立外部队列。++TDD 必须:TestPaidInvoiceGrantsOnlyOnce 用真实 PostgreSQL,20 个并发已验签付款通知指向同一 Invoice,expect 批次/发放记录各一条、余额只增加套餐额度;TestCheckoutReturnDoesNotGrant 访问成功页面余额仍零;TestRenewalAndPeriodEnd 成功新 Invoice 发放、失败续费零增量、旧未用余额过期、取消保留当期、下期变更符合新快照。Stripe 外部调用可替身,签名及业务处理不 mock。GWTEST ./internal/server -run 'TestPaidInvoice|TestCheckout|TestRenewal' -count=1;并发用 -race;回归 device/modelkey。++完成门:AC-6 的确定性公开 API/数据库部分,不新增退款、停售或跨 Invoice 合并。++### TASK-5:带积分预占与结算的文本模型请求++依赖 TASK-4;官方 Runtime 联调另依赖 TASK-1。GW 创建 internal/models/adapter.go、internal/models/compatible.go、internal/requests/service.go、internal/storage/migrations/004_model_requests.sql;修改 internal/credits/service.go、internal/server/server.go;测试 internal/server/requests_test.go。多文件是同一“余额约束下的真实模型请求”事务与传输边界。++定义 Adapter 的 Capabilities、Quote、Submit、Query 边界,输入携带 operation、外部 model ID、规范参数/媒体摘要和限制;Quote 返回可信输入量及可执行最大量,Submit 返回受理身份/状态/可信用量。JSON、multipart、SSE 与 Token 计量采用结构化解析及适用的成熟协议/计量实现。先实现原生 Responses 和 Chat-compatible 路由,不将无工具/Responses 的渠道标记可用。内部接口定义片段:++```go+type ModelCall struct {+ Operation, Model, MediaDigest string+ Params json.RawMessage+ Media io.ReadSeeker+ MaxUnits map[string]int64+}+type Channel struct { ID, BaseURL, APIKey string }+type Receipt struct {+ UpstreamID, State, ContentType string+ Usage map[string]int64+ Result json.RawMessage+ Body io.ReadCloser+}+type Adapter interface {+ Capabilities() map[string]bool+ Quote(context.Context, ModelCall) (map[string]int64, error)+ Submit(context.Context, ModelCall, Channel) (Receipt, error)+ Query(context.Context, string, Channel) (Receipt, error)+}+```++Quote 的单位集合与固定价格快照对应;媒体先在受限私有暂存中计算摘要,Quote 后 rewind,恢复时重新打开同一原始媒体,不能重用已耗尽的输入流。Channel 仅由服务器解密构造,不参与公开 JSON。Receipt 的 Body 由请求 worker 消费并关闭,边转发边用结构化协议解析终态/usage,客户端断开不丢弃后台记录。++统一 Admit(ctx,account,operation,logicalID,payload) 返回稳定 requestId、请求快照及原子预占;无 external logicalID 的原生调用每次实际请求新建 ID。相同逻辑 ID/指纹读原结果,冲突 409。数据库 commit 前禁止 Submit。输入计量、输出 Token 或媒体上限由已验证 Adapter 与真实发送参数约束,不能证明上界的路由拒绝启用。后台读完可信终态/usage,再 Settle(ctx,requestId,usage) 单次消费与释放;不因客户端断开直接退回预占。++TDD 必须:TestConcurrentAdmissionNeverOverspends 余额只够一个上界请求,两个并发请求只有一个触达假上游;TestLogicalRequestReused 相同 ID/参数重放只一次提交和结算,改参数 409;TestPriceSnapshotAndExpiry 请求后调价/跨期仍用旧快照,过期释放不回可用;TestUnknownUsageKeepsReservation 流中断且无 usage 时为 reconciling。GREEN 保持 SQL 事务、状态与计量核心真实;GWTEST ./internal/server -run 'TestConcurrentAdmission|TestLogicalRequest|TestPriceSnapshot|TestUnknownUsage|TestResponses' -count=1,并发项 -race;回归 billing。++完成门:AC-5 文本/工具/流式、AC-7、AC-11 核心路径。++### TASK-6:其余模态、视频任务与重启恢复++依赖 TASK-5。GW 创建 internal/models/media.go、internal/models/video.go、internal/requests/worker.go、internal/requests/results.go;修改 internal/server/server.go;测试 internal/server/modalities_test.go、recovery_test.go。++兼容图像和音频路由保留请求/响应协议,适用编辑按能力开放;服务端解析媒体时长/规格及大小,不信客户端声明。视频 Adapter 首条使用现有 Seedance 协议事实映射统一 Create/Query/Result,后续可配置其他中转站。所有模态走同一 Admit/Settle,只有实际请求收费。返回网关稳定结果引用或标准协议内容,下载验证归属/来源、解析地址、重定向、大小及有效期,禁止把鉴权头带去任意媒体主机。++worker 从 PostgreSQL 恢复 accepted/query/reconciling 状态;提交开始后失去回执转 unknown,安全查询或幂等证据成立才允许下一动作。lease 不授权盲重发,核对期限到后转人工。模型进度映射标准字段,无远程取消能力时区分停止本地等待与实际远端取消。++TDD 必须:TestAllModalitiesUseSameBalance 对一账户完成图像、TTS、转写和视频,检查同一积分账户和请求账本;TestRestartDoesNotResubmitAcceptedVideo 在提交后/回执落库前两处注入崩溃,重启只恢复原身份或 unknown;TestResultOwnershipAndRedirect B 查 A 结果拒绝,内部地址/重定向不泄漏上游 token,过期不自动生成。GREEN 只增加这四类适配和持久化恢复;GWTEST ./internal/server -run 'TestAllModalities|TestRestart|TestResult' -count=1;回归 requests。++完成门:AC-5 其余模态、AC-11/AC-12;真实能力在 TASK-12 小样本验证。++### TASK-7:Daemon 登录、自动配置及官方 Runtime 激活++依赖 TASK-1/TASK-3,付款状态依赖 TASK-4。OC 创建 packages/protocol/src/gateway-account.ts;在 index.ts 导出并扩展 errors.ts 的公开网关错误;创建 apps/daemon/src/gateway/client.ts、account-service.ts、config-store.ts、apps/daemon/src/api/routes.gateway-account.ts;修改 api/server.ts、creator/agent/bootstrap.ts;测试 packages/protocol/test/gateway-account-contract.test.ts、Daemon 的 gateway-account-service.test.ts、gateway-account-api.test.ts 及 creator-services-config-store.test.ts。多文件连接一次设备授权到实际 Runtime 激活,不按协议/页面另拆交付。++公开协议定义 ServiceSource='manual'|'gateway';GatewayAccountState 含 account、authState、activationState、公开模型目录及错误;所有金额为 string,公开类型没有 modelKey/accessToken/refreshToken。私有 GatewayCredentials 含账户会话、模型 Key/version/bindingVersion,仅存在 Daemon 文件与内存;public bootstrap 单独由 secret 快照脱敏。++createGatewayAccountService 提供 startAuthorization、cancelAuthorization、readState、refresh、activate、logout;API 使用现有 requireAuth。共享本地路径为 GET /gateway/account、POST /gateway/auth/start、/cancel、/logout、/activate,PATCH /gateway/source,GET /gateway/billing,POST /gateway/billing/checkout、/portal。start 返回公开授权 URL/尝试 ID,秘密只在 Daemon。轮询慢退避/过期、attempt generation 与刷新队列避免迟到覆盖。++私有文件 dataDir/config/gateway-credentials.json,公开模式/快照 dataDir/config/gateway.json;复用私有原子文件 helper,不合写或覆盖手动凭证。用 bindingVersion 检查两个快照一致,最后提交 activation ready;写入或 Runtime 失败保持已登录/未就绪。manual 默认兼容旧数据。只给官方 home 写 provider/env 配置,不调用个人 provider config/batchWrite。logout 顺序按 TASK-1,重启仅在私有会话有效且快照一致时恢复,失败不 fallback 到个人 Key。++TDD 必须:TestLateAuthorizationCannotReplaceAccount 暂停旧尝试后新授权成功,迟到结果不覆盖;TestBootstrapFailureDoesNotActivate 注入文件/Runtime 失败,模式不假就绪、手动文件哈希不变、Web 响应无秘密;TestLogoutClosesOfficialRuntimeButNotOtherDevice 用存活 host、排队请求和第二设备证明退出完成后新请求拒绝;协议测试验证六类错误映射、公开状态及金额字符串,没有秘密字段。新公开导出通过 namespace import 判断行为,不制造加载失败。PTEST 运行 test/gateway-account-contract.test.ts、test/error-facts.test.ts;DTEST 运行新两测试和 creator-services-config-store.test.ts,PTYPES/DTYPES;回归 creator-services-api.test.ts 和 codex-provider-config.test.ts 的旧路径。++完成门:AC-2/AC-4/AC-10/AC-12 的 Daemon 部分,MA-4 实现证据由最终真实边界验收确认。++### TASK-8:现有创作调用使用同一官方来源并保留 BYOK++依赖 TASK-5/TASK-6/TASK-7。OC 创建 apps/daemon/src/gateway/creator-service-source.ts;修改 creator-services/config-store.ts、image-generation/provider.ts、video-generation/service.ts、creator/provider-requests.ts、creator/krillin/config-bridge.ts、creator/krillin/codex-llm-gateway.ts、api/server.ts;测试 test/integration/creator-gateway-services.test.ts、test/unit/creator-provider-requests.test.ts、krillin-codex-llm-gateway.test.ts。跨文件是同一配置来源在五模态既有调用方的接入,保持原实现职责。++resolveCreatorServiceSource 为每个新任务取得 immutable {source,accountId,bindingVersion,models,capabilities},绑定原来源后再执行。文本/图片/OpenAI 语音沿用现有接口,注入 gateway endpoint/model 和按调用读取的 Key,不保存到手动配置。视频增加统一网关 Create/Query/Result 分支,不伪造 Seedance/Kling 的旧认证字段。源选择位于共享 Daemon,Workspace 不拥有账户或第二套 SSE。++Krillin 复用已有本机调用通道,任务配置只持有可撤销的本机 capability token;实际云 Key 由 Daemon 校验原账户后注入上游请求。扩展既有通道的 Chat/语音必要路径,供 config-bridge 输出兼容 TOML;不得在每任务 TOML 复制云 Key。该 token 不是第二把用户云 Key,不承载新计费后端。继承的工具调用/子阶段各自计量,不能用单个预估覆盖整个 Agent 链。++受控调用保存稳定 logicalID、gateway requestId/accountId/模式快照与原 CreatorProviderRequestLedger 的关联。相同账户 Key 更新只换鉴权不换任务;切账户/来源前检查活跃任务,结束后再切。保留手动 fallback 只用于 manual;gateway 能力失效准确预检,不静默选择个人源。登录/余额等 UI 变化不写 Activity。++TDD 必须:TestGatewaySourceReachesAllModalities 通过真实 Creator API 发各模态,观察假网关请求、稳定身份和本地产物,原手动文件不变;TestManualSourceBypassesGateway 相同操作走原服务且网关账本无变化;TestModeSwitchWaitsForActiveTask 暂停任务后切换拒绝/等待,不重启当前消费者;TestKrillinConfigDoesNotContainCloudKey 检查 TOML,实际转发才携带 Key,注销本机资格后新调用拒绝。DTEST 新集成及两回归、DTYPES,实际编译边界变化运行 DBUILD。++完成门:AC-5/AC-10/AC-11/AC-13 对应调用方部分。++### TASK-9:共享客户端登录、订阅与账户视图++依赖 TASK-7/TASK-8。OC 创建 apps/web/src/services/gateway-account-service.ts、features/settings/GatewayAccountSettingsView.tsx、gateway-account-settings.css;修改 app/AppController.tsx、features/settings/StartupAgentSetup.tsx、CreatorServicesSettingsView.tsx、SettingsPage.tsx;测试 GatewayAccountSettingsView.test.tsx、services/gateway-account-service.test.ts、StartupAgentSetup.test.tsx。统一入口/账户视图是同一用户流程;不复制 Desktop UI。++沿用 RuntimeClient 和现有 localized copy。服务来源用官方/自带服务的 segmented control;登录、订阅、重试为明确命令。账户显示身份、订阅时间、可用/预占积分及入口;金额不可损失精度。authState 与 activationState 分开;过期、零积分、付款处理中、查询故障及退出进行中均对应后台事实。查询失败保留上一成功时间,不以 0 替代。打开授权/付款 URL 调用 openExternal,同时始终给可点击链接,不以 Promise<void> 宣告浏览器已打开。++登录入口不必先填 Key/地址;原本机 Codex 和自带服务保留。登录成功不能单靠 UI 切到 ready,必须使用 Daemon 激活结果。Bootstrap/Key 不进入页面 props、浏览器存储或截图。沿用 quiet settings 布局与 lucide 图标,不新建营销页、另一个 Panel 或平台分叉。++TDD 必须:未登录点击登录会发公开 API;已登录但激活失败显示未就绪且可重试;余额查询失败不显示零;待确认订单不显示到账;退出进行中按钮状态稳定;原配置用户升级保持 manual。WTEST 新两测试及 StartupAgentSetup.test.tsx、CreatorServicesSettingsView.test.tsx;WTYPES。真实交互由 UIAC 和 PARITY,不因纯页面改动构建或重启 Vite。++完成门:AC-4/AC-8/AC-13 对应页面部分。++### TASK-10:网关账户网站和最小管理员操作++依赖 TASK-4/TASK-6。GW 创建 internal/admin/service.go、web/templates/account.html、web/templates/admin.html;修改 internal/server/server.go;测试 internal/server/admin_test.go、account_pages_test.go。++账户页读 summary/orders/ledger,Stripe 托管管理入口仅开放取消/恢复和允许的下期变更,不绕过 BR-3。配置管理只处理当前计划所需的套餐、模型价格与渠道;不增加停售工作流。普通账户/模型 Key 无管理权限;管理员启用能力须通过参数、协议和计量校验。待核对请求仅凭证据单次结算/释放;任意余额修正写独立 adjustmentId/reason/actor,不能 UPDATE 历史消费。++TDD 必须:TestUserCannotAdmin 三类凭证越权拒绝;TestManualReconciliationIsAudited 同 requestId 和 adjustmentId 重复操作仍只写一次且有原记录引用;TestAccountPageFailureDoesNotShowZero 查询故障准确呈现。GWTEST ./internal/server -run 'TestUserCannotAdmin|TestManualReconciliation|TestAccountPage' -count=1;回归账本和结果归属。++完成门:AC-8/AC-9/AC-12;不增加退款页面或后台退款状态机。++### TASK-11:测试环境、能力开关与可回滚运行++依赖 TASK-2 至 TASK-10。GW 创建 internal/config/config.go、compose.yaml、.env.example、README.md;修改 cmd/gateway/main.go;测试 internal/server/config_test.go。OC 的 gateway client/origin 配置只在共享 Daemon 来源读取,测试 gateway-account-api.test.ts。数据库迁移只新增必要表,不模拟空仓库不存在的旧云账户迁移。++私有 .local/gateway.env 提供数据库、加密主密钥、HTTPS/OAuth/邮件/Stripe 测试环境、套餐/模型/渠道及各限制。公开 .env.example 只放变量名和非敏感说明,不虚构商户/域名/模型。生产启动验证环境隔离,缺能力配置只关闭该能力并给稳定状态;凭证和数据库核心配置缺失则服务不进入 ready。compose 默认仅 PostgreSQL,Go worker 同服务运行,模型结果临时目录挂载独立私有 volume。++发放/结算和后台核对可保持运行,生成路由有总开关。测试回滚:关闭新官方调用,保留账本/inbox/预占和已受理查询/worker,客户端仍能显式切回旧源;禁止删账本或重新发周期积分。所有服务操作先查 PID/命令/端口;仅重启本次改变的服务及直接依赖,健康检查 GET /healthz(Go)和 /healthz(Daemon)。Vite 正常热更新不重启。++TDD 必须:TestInvalidProductionConfigDoesNotBecomeReady、TestDisabledGenerationKeepsRecovery;前者给测试商户/缺密钥/非法能力组合,后者关闭调用但旧任务可查询并结算。GWTEST ./internal/server -run 'TestInvalidProductionConfig|TestDisabledGeneration' -count=1,GWBUILD;OC 回归 gateway-account-api.test.ts、DTYPES/DBUILD。配置部署操作可豁免 RED,但以上业务准入测试不可豁免。++完成门:相关 AC-4/AC-6/AC-11/AC-12/AC-13;只准备测试环境,不擅自公开部署。++### TASK-12:执行完整功能验收++依赖所有前置任务;先完成主 Agent 本地实现差异自审,不启动 Reviewer。查看两个仓库 git diff --stat 和相关 diff,对照快照/追踪/TASK 检查漏项、范围扩张、接口漂移、过度抽象、权限、兼容及测试质量。只修本次相关问题,按 TDD 重跑受影响验证;最后一次相关修改后重新检查差异和相关验收。++创建 GW/test/acceptance/public_test.go、OC/apps/web/e2e/gateway-account.spec.ts、gateway-web-desktop-parity.spec.ts。这些验收从真实网络 API、Go 页面和 OpenCreator 页面进入真实认证/计费/Daemon 业务,不能重命名单元测试充当交付证据。采用既有 Fake Daemon 的双 Bridge 夹具;真实联调另用测试网关及实际 Daemon。++按第 5 节执行 GWAC、UIAC、PARITY、真实 OAuth/邮件/Stripe/模型小样本及条件命中的 Desktop 门禁;记录 PASS/FAIL/BLOCKED、时间、命令、目录、退出状态与输出摘要。保留既有 Playwright 截图/trace 产物,其他结果留在执行会话,不额外新建实施报告或流程日志文件。++## 5. 最终功能验收矩阵++公共准备:隔离 PostgreSQL、A/B 两账户及两个 A 设备、可控制的 clock/假上游、Stripe 测试商户、真实 OAuth 应用/邮件、实际 bundled Runtime、原手动配置快照。假上游仅替换外部服务,真实 SQL/账本/HTTP/Daemon/页面不 mock。真实渠道用专用账户和受控小样本,禁止生产账户/大规模消费。++| AC | 优先级 | 前置条件与操作 | 独立预期及证据 |+|---|---|---|---|+| AC-1 | P0 | 经 Go 页面及 API 完成邮箱验证、登录/找回和 Google/GitHub;尝试同邮箱绑定、错 state、重放及未验证购买 | 三种真实登录成立;单次令牌一次有效;绑定证明原归属;无未验证凭证/购买。HTTP/邮件领取与实际 OAuth 回调证据,缺配置标 BLOCKED |+| AC-2 | P0 | OpenCreator 发起/取消/过期设备授权、重复领取,刷新并重启 Daemon;在旧尝试延迟时开新尝试 | 发起端单次得到会话,旧响应不覆盖;刷新/重启恢复;退出仅撤销当前设备。页面与真实 API/session 记录 |+| AC-3 | P0 | 两个 A 设备并发首次领取/重登,B 登录;重置后用旧值、模型 Key 调账户/管理和 B 任务 | A 共用唯一当前值、B 不同;旧值立即失效,模型 Key 无管理权,归属拒绝;Key 不在浏览器。并发 SQL/API 与脱敏观测 |+| AC-4 | P0 | 新用户登录,已配个人 Codex/手动源的老用户登录;注入 bootstrap/文件/Runtime 失败后恢复与切回 | 真正就绪后无需手填可调用;失败显示已登录未就绪;原文件哈希不变,升级仍 manual。真实 Runtime/API、前后文件哈希和页面 |+| AC-5 | P0 | 每模态至少一个真实启用路由;Agent 工具/流式、业务文本、图片及适用编辑、视频创建查询下载、TTS、转写;尝试不支持能力 | 全流程/产物/可信用量完整;不支持拒绝;无不安全自动重发。每模态受控真实请求与本地产物,替身不证明厂商能力 |+| AC-6 | P0 | Stripe 测试环境购买;重放/并发同 Invoice 付款通知;正常新月 Invoice、失败/补缴、取消/恢复、下期变更和到期 | 同 Invoice 一次 grant,新合法 Invoice 新一期;未付款/跳回页面不给积分;规则正确、旧余额不结转。真实 Checkout/回调/周期与 SQL 账本证据,无退款/停售用例 |+| AC-7 | P0 | 已知余额/价格,公开模型 API 并发;不足提交、重复结算、执行后调价、超上界、跨期完成/释放 | 无超支,不足不触达上游;一次结算、原价格,过期释放不回余额,无隐式债务;投影可核对。真实 PostgreSQL/上游收件与公开查询 |+| AC-8 | P1 | 账户页有消费/预占/订单;模拟付款处理中及 summary 故障,随后恢复 | 正确归属和金额,预占区别消费;待确认非到账;故障非零、保留更新时间、入口可操作。Go/OpenCreator 真实页面和 API |+| AC-9 | P0 | 普通用户、模型 Key 和管理员;修改配置、停用用户、带证据核对/调整并重复提交 | 权限拒绝、非法能力不开;停用拦截新请求;核对/调整一次及完整审计,历史不可改写。真实管理 API 和 SQL |+| AC-10 | P0 | 有活跃任务和两设备;切账户/模式、退出,任务结束后切回,并调用 manual | 切换不换当前任务身份;成功退出后持凭证进程结束且无新调用,其他设备正常;原服务恢复,直连不扣网关积分。实际进程/上游收件/API/页面,不以 stale 标志证明退出 |+| AC-11 | P0 | 稳定 ID、远端回执与暂停/崩溃点;冲突、重复/重连/查询下载、流中断、回执前崩溃、worker 重启、超期及同账户恢复 | 原任务只提交/结算一次;未知不盲重发/释放,后台恢复及人工关闭;B 不能恢复;无 ID 原生调用不猜幂等。真实 HTTP/SQL/实际 Runtime 故障注入 |+| AC-12 | P0 | 带标记的测试秘密、恶意来源/媒体/重定向及目标 OS;检查 Web 响应、页面/storage/URL/日志和文件权限,尝试 CSRF/越权/SSRF | 标记不进入禁止位置;实际访问控制成立;错误拒绝且认证头不随重定向泄漏。公开 API/浏览器/文件边界;Windows 无证据不宣称该平台通过 |+| AC-13 | P0 | 同 Fake Daemon、账户/任务/偏好,内容视口 1280x800;Browser/Desktop Bridge 执行账户、登录入口、模式、模型及模板预检 | 文案/DOM/关键尺寸/状态/请求/持久化一致;现有 Bridge 真调用;唯一 Panel、标准 Activity/进度。PARITY 证据;Desktop 包按下面条件另验 |++AC-12 表中操作与预期应按同一公开边界记录,不将安全检查泛化成无关审计。每个 AC 的实际证据包括本次执行时间、环境、命令/操作和观察结果;未执行不能写 PASS。++运行真实 API 验收时用独立网关/Daemon 数据目录与测试账户。验收后只清理测试夹具及专用数据库 schema/账号,不删除用户数据、订阅事实或未知上游任务。外部请求未知先核对后清理,不能靠删库隐藏预占。主 Agent 自审和最终 AC 必须在最后一次相关代码修改后进行。++Desktop 升级门:只有实际 diff 触及 apps/desktop、Host Bridge、Preload/IPC、Daemon 启动/代理、打包资源,或交付目标包含 Desktop 包时,才执行当前 Web 重建、实际 desktop:package、packaged App E2E 和内嵌 Web 文件/哈希一致性。若命中,读取仓库当时实际打包脚本及验证入口并运行其真实命令;不创建第二套实现。未命中只验相关双 Bridge 与共享调用,不能宣称实际 App 已验证。++## 6. 偏差、失败熔断及最终报告++执行必须先写行为 RED,确认失败来自业务缺失,再最小 GREEN、相关回归;已有兼容基线可先绿但不能当 RED。新公开模块不能用静态具名 import 的加载错误冒充行为失败。Go 先具备可编译的 handler/夹具,RED 从真实路由或断言产生,不以编译失败代替。++GREEN 后每次修复先记录失败证据、根因假设、最小改动。同一根因经过两次有实质差异的修复仍失败,立即停止该 TASK 标为 BLOCKED,报告实现/测试/环境/契约分类和下一步;预期 RED 不计次数。禁止盲试、放宽断言、改 AC、自动启动子 Agent 或修复无关历史问题。++允许不改变契约的局部路径/命名调整,记录原因和影响;需要改变 FR/BR/NFR/DEC/AC、权限/账本/架构则停止并更新方案。缺真实凭证可以完成不依赖它的工作,但最终 P0 真实边界仍 BLOCKED。任何 P0 FAIL/BLOCKED 不宣称交付完成或可发布。++最终回复报告:完成/未完成任务、契约不变的偏差、主 Agent 差异自审及相关修复、实际 RED/GREEN/回归命令结果、AC 的本次证据/状态、测试环境与回滚状态及遗留风险。无提交、推送、tag、公开部署任务,除非用户另行明确授权。++## 7. 风险与审核记录++| ID | 原始状态/证据 | 处理与完成边界 |+|---|---|---|+| PLAN-ENV-1 | NOT_AVAILABLE;工具清单无三个 Agent 生命周期工具;无 spawn/agent_id/输出 | 独立 Plan 审核未执行,不冒充已审核;用户知情执行授权可推进,但保留风险 |+| MA-4 | 方案保留的 OPEN/Major,已知个人 auth 复制、进程继承环境及 invalidate 延迟关闭行为 | TASK-1 优先测实际 Runtime,TASK-7/TASK-8 实现,AC-4/AC-10/AC-12 验收;达不到则不启用官方收费调用 |+| PLAN-EXT-1 | 目标新仓库名当前不可查询,旧仓库为空;域名/商户/OAuth/邮件/渠道尚未实测 | TASK-0 定位,外部缺失只阻塞其真实验收;不凭文档或替身声称已上线 |++第一版 Plan 审核范围:本计划列出的 FR-1 至 FR-12、BR-1 至 BR-7/BR-9、NFR-1 至 NFR-5、DEC-1 至 DEC-9、AC-1 至 AC-13,以及 TASK-0 至 TASK-12。直接证据为第 2 节的具体路径/符号/命令及任务测试,允许仅检查一层直接调用影响。用户原文为来源方案第 2 节五条输入,分段确认是 D-1 至 D-4,最终方案批准原话为“继续”。原文未由摘要替代,独立审核恢复时将该章节连同上述审核包提交。++明确排除:BR-8、停售/退款/扩展发票模型、未变化模板业务、项目/文件云同步、系统窗口/托盘/通知、插件/市场、无关历史问题,以及 TASK 中未触及的旧能力。不得扩展成全库审查。++2026-10-05:当前会话未提供 spawn_agent、wait_agent、close_agent,尚不能调用 zhiyu-reviewer;没有 unknown agent_type,因此不启动默认 Agent 回退。不使用 Codex CLI 或子进程模拟 Reviewer。主 Agent 对路径、追踪、任务依赖、TDD 和验收进行文档一致性自查;这不是独立审核,也不是功能验证。++本轮文档检查已通过:25 条一期需求、9 项决策、13 项 AC 的任务映射;TASK-0 至 TASK-12 定义与依赖;表格、文档链接、编号和尾随空白。该结果不证明 Go/Runtime/支付/真实渠道或任何 Desktop 包已经通过。++用户在看到本 Plan 和上述状态后明确说“开始执行”或等价指令,记录授权和日期;仍有风险时流程记 PASS(用户知情授权执行),原始 Reviewer 状态不改。随后从 TASK-0 原生执行,不再增加豁免或重复确认。diff --git a/packages/protocol/src/creator.ts b/packages/protocol/src/creator.tsindex 9d12aebb..adff03ed 100644--- a/packages/protocol/src/creator.ts+++ b/packages/protocol/src/creator.ts@@ -229,6 +229,7 @@ export type CreatorResultSnapshot = {};export type CreatorProviderRequest = {+ gateway?: { accountId: string; bindingVersion: string; logicalId: string };id: string;jobId: string;provider: string;diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.tsindex d558f79f..455e2ce4 100644--- a/packages/protocol/src/errors.ts+++ b/packages/protocol/src/errors.ts@@ -1,6 +1,12 @@import type { OpenCreatorIssue, PublicErrorFacts } from './issues.js';export type RuntimeErrorCode =+ | 'GATEWAY_AUTH_REQUIRED'+ | 'GATEWAY_ACCOUNT_DISABLED'+ | 'GATEWAY_CREDITS_INSUFFICIENT'+ | 'GATEWAY_REQUEST_CONFLICT'+ | 'GATEWAY_SERVICES_NOT_READY'+ | 'GATEWAY_UNAVAILABLE'| 'VALIDATION_FAILED'| 'UNAUTHORIZED'| 'RUN_NOT_FOUND'@@ -168,6 +174,14 @@ export type RuntimeErrorCode =export function publicErrorKindForCode(code: string): PublicErrorFacts['kind'] | undefined {const normalized = code.toUpperCase();+ if (normalized === 'AUDIO_NO_SPEECH') return 'validation';+ if (normalized === 'AUDIO_TRANSCRIPTION_INVALID_RESPONSE') return 'invalid-response';+ if (normalized === 'AUDIO_TRANSCRIPTION_TIMESTAMPS_MISSING') return 'unsupported';+ if (normalized === 'AUDIO_TRANSCRIPTION_API_FAILED') return 'provider-failed';+ if (normalized === 'GATEWAY_AUTH_REQUIRED') return 'unauthorized';+ if (normalized === 'GATEWAY_ACCOUNT_DISABLED' || normalized === 'GATEWAY_CREDITS_INSUFFICIENT') return 'http-rejected';+ if (normalized === 'GATEWAY_SERVICES_NOT_READY') return 'configuration';+ if (normalized === 'GATEWAY_UNAVAILABLE') return 'unavailable';if (normalized === 'ENOTFOUND' || normalized === 'EAI_AGAIN') return 'dns';if (normalized === 'ECONNREFUSED') return 'connection-refused';if (normalized === 'ECONNRESET' || normalized === 'EPIPE') return 'connection-reset';diff --git a/packages/protocol/src/gateway-account.ts b/packages/protocol/src/gateway-account.tsnew file mode 100644index 00000000..638c83a6--- /dev/null+++ b/packages/protocol/src/gateway-account.ts@@ -0,0 +1,49 @@+export type ServiceSource = 'manual' | 'gateway';+export const gatewayDefaultVoiceId = '__default__';+export type GatewayModel = {+ id: string;+ name?: string;+ modality: 'text' | 'image' | 'video' | 'speech' | 'transcription';+ capabilities: string[];+ voices?: string[];+ sizes?: string[];+ durations?: number[];+ resolutions?: string[];+ aspectRatios?: string[];+ imageOptions?: {+ aspectRatios?: string[];+ resolutions?: string[];+ qualities?: string[];+ outputFormats?: string[];+ maxImages: number;+ maxReferences: number;+ };+};+export type GatewayAccountState = {+ source: ServiceSource;+ authState: 'signed_out' | 'authorizing' | 'signed_in' | 'signing_out' | 'expired' | 'disabled';+ activationState: 'inactive' | 'loading' | 'ready' | 'blocked';+ account: { id: string; email: string; verified: boolean; avatarUrl?: string } | null;+ bindingVersion: string | null;+ models: GatewayModel[];+ selectedModels?: Partial<Record<GatewayModel['modality'], string>>;+ activationError: { code: string; message: string } | null;+};++export function gatewayVideoSizes(model: GatewayModel | undefined): string[] {+ if (model?.sizes?.length) return model.sizes;+ return (model?.resolutions ?? []).flatMap(resolution =>+ (model?.aspectRatios ?? []).filter(ratio => /^\d+:\d+$/.test(ratio)).map(ratio => `${resolution}@${ratio}`));+}++export function gatewayVideoSizeParameters(model: GatewayModel, value: string): { size: string } | { resolution: string; aspect_ratio: string } | undefined {+ if (!gatewayVideoSizes(model).includes(value)) return undefined;+ if (model.sizes?.includes(value)) return { size: value };+ const [resolution, aspect_ratio] = value.split('@');+ return resolution && aspect_ratio ? { resolution, aspect_ratio } : undefined;+}+export type GatewayAuthorization = { attemptId: string; authorizationUrl: string; expiresAt: string };+export type GatewayBalanceSnapshot = { availableUnits: string; reservedUnits: string; periodEnd: string | null; asOf: string };+export type GatewayBalanceState =+ | { status: 'ready'; value: GatewayBalanceSnapshot }+ | { status: 'unavailable'; lastKnown: GatewayBalanceSnapshot | null; code: string };diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 971d8ef9..3d118d44 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -15,3 +15,4 @@ export * from './smart-dubbing.js';export * from './video-metadata.js';export * from './wechat-article.js';export * from './stickman.js';+export * from './gateway-account.js';diff --git a/packages/protocol/src/media-generation.ts b/packages/protocol/src/media-generation.tsindex fc6a5b3b..33e7133f 100644--- a/packages/protocol/src/media-generation.ts+++ b/packages/protocol/src/media-generation.ts@@ -30,6 +30,9 @@ export type CreateImageGenerationRequest = {size: ImageGenerationSize;quality: ImageGenerationQuality;count: number;+ aspectRatio?: string;+ resolution?: string;+ officialQuality?: string;};/** Detect explicit references to an existing image, rather than ordinary photo styles. */@@ -66,8 +69,8 @@ export type ImageGenerationResultResponse = {export const videoGenerationSizes = ['1280x720', '720x1280', '1024x1024'] as const;export const videoGenerationDurations = [4, 5, 6, 8, 10] as const;-export type VideoGenerationSize = typeof videoGenerationSizes[number];-export type VideoGenerationDuration = typeof videoGenerationDurations[number];+export type VideoGenerationSize = typeof videoGenerationSizes[number] | `${number}x${number}` | `${string}@${number}:${number}`;+export type VideoGenerationDuration = number;export type VideoGenerationStatus = 'queued' | 'in_progress' | 'completed' | 'failed';export type VideoGenerationProvider = 'seedance' | 'kling' | 'veo';diff --git a/packages/protocol/test/error-facts.test.ts b/packages/protocol/test/error-facts.test.tsindex 1d00da71..66d0cefa 100644--- a/packages/protocol/test/error-facts.test.ts+++ b/packages/protocol/test/error-facts.test.ts@@ -14,6 +14,11 @@ describe('public error kind for business code', () => {['krillin_auth_failed', 'unauthorized'],['ENOTFOUND', 'dns'],['ERR_FS_FILE_TOO_LARGE', 'storage'],+ ['audio_no_speech', 'validation'],+ ['audio_transcription_invalid_response', 'invalid-response'],+ ['audio_transcription_timestamps_missing', 'unsupported'],+ ['audio_transcription_api_failed', 'provider-failed'],+ ['audio_transcription_empty', undefined],['creator_provider_request_failed', undefined]])('classifies %s conservatively', (code, expected) => {expect(publicErrorKindForCode(code)).toBe(expected);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 15fdffea..3ea60516 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -236,6 +236,9 @@ importers:'@opencreator/writing-templates':specifier: workspace:*version: link:../../packages/writing-templates+ fuse.js:+ specifier: ^7.1.0+ version: 7.5.0lucide-react:specifier: ^0.468.0version: 0.468.0([email protected])@@ -2701,6 +2704,10 @@ packages:resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}+ resolution: {integrity: sha512-sQtrEfA+ez/3G0cCZecF70oqpCRttCexYUG4mUrtWL49ULUzUyxokt5kyqwtKzj1270RaKih+hcP3qLcumccow==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}engines: {node: '>=6.9.0'}@@ -6804,6 +6811,8 @@ snapshots:+ [email protected]: {}+diff --git a/runtime/krillinai/config/config.go b/runtime/krillinai/config/config.goindex 42e14aea..35b4385b 100644--- a/runtime/krillinai/config/config.go+++ b/runtime/krillinai/config/config.go@@ -36,9 +36,10 @@ type Server struct {}type OpenaiCompatibleConfig struct {- BaseUrl string `toml:"base_url"`- ApiKey string `toml:"api_key"`- Model string `toml:"model"`+ BaseUrl string `toml:"base_url"`+ ApiKey string `toml:"api_key"`+ Model string `toml:"model"`+ OfficialModel string `toml:"official_model"`}type LocalModelConfig struct {diff --git a/runtime/krillinai/internal/pipeline/subtitle.go b/runtime/krillinai/internal/pipeline/subtitle.goindex ac3c4f63..68a41090 100644--- a/runtime/krillinai/internal/pipeline/subtitle.go+++ b/runtime/krillinai/internal/pipeline/subtitle.go@@ -7,7 +7,8 @@ import ("krillin-ai/internal/service"subtitlestyle "krillin-ai/internal/subtitle_style""krillin-ai/internal/types"- "net/url"+ "krillin-ai/pkg/util"+ "krillin-ai/pkg/whisper""os""strings")@@ -155,7 +156,19 @@ func GenerateSubtitles(ctx context.Context, svc StageService, req SubtitleRequeserr,)}- return failSubtitleStage(req, manifest, ErrorKindRetryable, "audio_transcription_failed", err)+ code, retryable := "audio_transcription_failed", true+ var classified *whisper.TranscriptionError+ if errors.As(err, &classified) {+ code, retryable = classified.Code, classified.Retryable()+ }+ kind := ErrorKindRetryable+ if !retryable {+ kind = ErrorKindUsage+ if code == "audio_transcription_invalid_response" {+ kind = ErrorKindInternal+ }+ }+ return failSubtitleStage(req, manifest, kind, code, err)}manifest.CaptionSource = string(CaptionSourceWhisper)reportSubtitleProgress(req, "collecting_outputs", 95, "正在整理字幕产物")@@ -368,14 +381,5 @@ func subtitleResponse(ok bool, req SubtitleRequest, manifest *Manifest, captionS}func IsYouTubeInput(input string) bool {- parsed, err := url.Parse(strings.TrimSpace(input))- if err != nil {- return false- }- hostname := strings.ToLower(strings.TrimSuffix(parsed.Hostname(), "."))- return hostname == "youtu.be" ||- hostname == "youtube.com" ||- strings.HasSuffix(hostname, ".youtube.com") ||- hostname == "youtube-nocookie.com" ||- strings.HasSuffix(hostname, ".youtube-nocookie.com")+ return util.IsYouTubeURL(input)}diff --git a/runtime/krillinai/internal/pipeline/subtitle_test.go b/runtime/krillinai/internal/pipeline/subtitle_test.goindex a1325f2b..638566bd 100644--- a/runtime/krillinai/internal/pipeline/subtitle_test.go+++ b/runtime/krillinai/internal/pipeline/subtitle_test.go@@ -3,11 +3,13 @@ package pipelineimport ("context""errors"+ "fmt""krillin-ai/internal/service"subtitlestyle "krillin-ai/internal/subtitle_style""krillin-ai/internal/types"pkgimage "krillin-ai/pkg/image""krillin-ai/pkg/util"+ "krillin-ai/pkg/whisper""os""path/filepath""reflect"@@ -211,6 +213,26 @@ func TestGenerateSubtitlesPreservesPlatformAndAudioFallbackErrors(t *testing.T)}}+func TestGenerateSubtitlesPreservesTranscriptionClassification(t *testing.T) {+ for _, code := range []string{"audio_no_speech", "audio_transcription_empty", "audio_transcription_invalid_response", "audio_transcription_timestamps_missing", "audio_transcription_api_failed"} {+ for _, fallback := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/fallback=%v", code, fallback), func(t *testing.T) {+ classified := &whisper.TranscriptionError{Code: code, Message: "fixture reason"}+ fake := &fakeStageService{audioErr: fmt.Errorf("service wrapper: %w", classified)}+ req := SubtitleRequest{Input: "local:fixture.mp4", Workdir: t.TempDir(), CaptionSource: CaptionSourceWhisper}+ if fallback {+ req.Input, req.CaptionSource = "https://youtu.be/1_iv-S02hJ0", CaptionSourceAny+ fake.downloadErr = errors.New("no captions")+ }+ response, err := GenerateSubtitles(context.Background(), fake, req)+ if !errors.Is(err, classified) || response.Error == nil || response.Error.Code != code || response.Error.Retryable != classified.Retryable() {+ t.Fatalf("response = %+v, error = %v", response.Error, err)+ }+ })+ }+ }+}+func TestGenerateSubtitlesPassesSubtitleStyleToStepParam(t *testing.T) {dir := t.TempDir()fake := &fakeStageService{}diff --git a/runtime/krillinai/internal/service/audio2subtitle.go b/runtime/krillinai/internal/service/audio2subtitle.goindex 44bf51c9..fb44b034 100644--- a/runtime/krillinai/internal/service/audio2subtitle.go+++ b/runtime/krillinai/internal/service/audio2subtitle.go@@ -10,6 +10,7 @@ import ("krillin-ai/internal/types""krillin-ai/log""krillin-ai/pkg/util"+ "krillin-ai/pkg/whisper""os""path/filepath""runtime"@@ -124,6 +125,10 @@ func (s Service) audioToOriginSubtitle(ctx context.Context, stepParam *types.Subif err == nil {break}+ var classified *whisper.TranscriptionError+ if errors.As(err, &classified) && !classified.Retryable() {+ break+ }}if err != nil {return fmt.Errorf("transcribe audio segment %d: %w", segmentIndex, err)@@ -772,7 +777,8 @@ func (s Service) startTranscribeWorkers(ctx context.Context, eg *errgroup.Group,)log.GetLogger().Info("Begin transcribe", zap.Any("taskId", stepParam.TaskId), zap.Any("splitId", audioFileItem.Id))// 语音转文字- for range config.Conf.App.TranscribeMaxAttempts {+ attempts := max(1, config.Conf.App.TranscribeMaxAttempts)+ for range attempts {transcriptionData, err = s.transcribeAudio(audioFileItem.Id,audioFileItem.Data,@@ -791,6 +797,10 @@ func (s Service) startTranscribeWorkers(ctx context.Context, eg *errgroup.Group,if err == nil {break}+ var classified *whisper.TranscriptionError+ if errors.As(err, &classified) && !classified.Retryable() {+ break+ }}if err != nil {return fmt.Errorf("audioToSubtitle audioToSrt Transcription err: %w", err)diff --git a/runtime/krillinai/internal/service/init.go b/runtime/krillinai/internal/service/init.goindex 639dd04f..1177542d 100644--- a/runtime/krillinai/internal/service/init.go+++ b/runtime/krillinai/internal/service/init.go@@ -37,6 +37,9 @@ func NewService() *Service {switch config.Conf.Transcribe.Provider {case "openai":transcriber = whisper.NewClient(config.Conf.Transcribe.Openai.BaseUrl, config.Conf.Transcribe.Openai.ApiKey, config.Conf.App.Proxy)+ if model := config.Conf.Transcribe.Openai.OfficialModel; model != "" {+ transcriber = whisper.NewOfficialClient(config.Conf.Transcribe.Openai.BaseUrl, config.Conf.Transcribe.Openai.ApiKey, config.Conf.App.Proxy, model)+ }case "funasr":transcriber = funasr.NewClient(config.Conf.Transcribe.FunASR.BaseUrl, config.Conf.Transcribe.FunASR.ApiKey, config.Conf.Transcribe.FunASR.Model, config.Conf.Transcribe.FunASR.TimeoutMs, config.Conf.App.Proxy)case "fasterwhisper":diff --git a/runtime/krillinai/internal/service/transcription_retry_test.go b/runtime/krillinai/internal/service/transcription_retry_test.gonew file mode 100644index 00000000..b4c3c350--- /dev/null+++ b/runtime/krillinai/internal/service/transcription_retry_test.go@@ -0,0 +1,59 @@+package service++import (+ "context"+ "errors"+ "testing"++ "krillin-ai/config"+ "krillin-ai/internal/types"+ "krillin-ai/log"+ "krillin-ai/pkg/whisper"++ "golang.org/x/sync/errgroup"+)++type failingTranscriber struct {+ calls int+ err error+}++func (f *failingTranscriber) Transcription(_, _, _ string) (*types.TranscriptionData, error) {+ f.calls+++ return nil, f.err+}++func TestTranscriptionRetriesOnlyRetryableFailures(t *testing.T) {+ log.InitLogger()+ previous := config.Conf.App+ t.Cleanup(func() { config.Conf.App = previous })+ config.Conf.App.TranscribeParallelNum = 1+ for _, test := range []struct {+ code string+ attempts int+ calls int+ }{+ {"audio_transcription_empty", 3, 1},+ {"audio_no_speech", 3, 1},+ {"audio_transcription_invalid_response", 3, 1},+ {"audio_transcription_timestamps_missing", 3, 1},+ {"audio_transcription_api_failed", 3, 3},+ {"audio_transcription_api_failed", 0, 1},+ } {+ t.Run(test.code, func(t *testing.T) {+ config.Conf.App.TranscribeMaxAttempts = test.attempts+ transcriber := &failingTranscriber{err: &whisper.TranscriptionError{Code: test.code, Message: "fixture failure"}}+ pending := make(chan DataWithId[string], 1)+ pending <- DataWithId[string]{Data: "fixture.wav"}+ close(pending)+ group, ctx := errgroup.WithContext(context.Background())+ (Service{Transcriber: transcriber}).startTranscribeWorkers(ctx, group, &types.SubtitleTaskStepParam{TaskBasePath: t.TempDir()},+ pending, make(chan DataWithId[float64], 1), make(chan DataWithId[*types.TranscriptionData], 1))+ err := group.Wait()+ var classified *whisper.TranscriptionError+ if !errors.As(err, &classified) || classified.Code != test.code || transcriber.calls != test.calls {+ t.Fatalf("calls = %d, error = %v", transcriber.calls, err)+ }+ })+ }+}diff --git a/runtime/krillinai/internal/service/youtube_caption_text_test.go b/runtime/krillinai/internal/service/youtube_caption_text_test.gonew file mode 100644index 00000000..daafa47a--- /dev/null+++ b/runtime/krillinai/internal/service/youtube_caption_text_test.go@@ -0,0 +1,45 @@+package service++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "krillin-ai/config"+)++func TestCleanVttTextDecodesSpeakerMarkersBeforeFiltering(t *testing.T) {+ s := &YouTubeSubtitleService{}+ for _, input := range []string{">> Mhm.", ">> Mhm.", ">> Mhm."} {+ if got := s.cleanVttText(input); got != "Mhm." {+ t.Fatalf("cleanVttText(%q) = %q", input, got)+ }+ }+}++func TestProcessYouTubeMusicCaptionsPreservesBriefUtterance(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "captions.vtt")+ content := "WEBVTT\n\n00:00:20.305 --> 00:00:25.535\n[music]\n\n00:04:30.400 --> 00:04:32.520\n>> Mhm.\n"+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ previous := config.Conf.App.MaxSentenceLength+ config.Conf.App.MaxSentenceLength = 50+ t.Cleanup(func() { config.Conf.App.MaxSentenceLength = previous })+ s := &YouTubeSubtitleService{}+ words, err := s.ExtractWordsFromVtt(path)+ if err != nil || len(words) != 1 || words[0].Text != "Mhm." {+ t.Fatalf("words = %v, error = %v", words, err)+ }+ output, err := s.processYouTubeSubtitle(context.Background(), &YoutubeSubtitleReq{VttFile: path, TaskBasePath: dir, SourceOnly: true})+ if err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(output)+ if err != nil || !strings.Contains(string(data), "Mhm.") || strings.Contains(string(data), "music") {+ t.Fatalf("subtitle = %s, error = %v", data, err)+ }+}diff --git a/runtime/krillinai/internal/service/youtube_short_url_test.go b/runtime/krillinai/internal/service/youtube_short_url_test.gonew file mode 100644index 00000000..e5b3084a--- /dev/null+++ b/runtime/krillinai/internal/service/youtube_short_url_test.go@@ -0,0 +1,90 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "krillin-ai/internal/storage"+ "krillin-ai/log"+)++func TestDownloadYouTubeSubtitleAcceptsShortURL(t *testing.T) {+ log.InitLogger()+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ previousPath, previousPrefix := storage.YtdlpPath, storage.YtdlpPrefixArgs+ storage.YtdlpPath = executable+ storage.YtdlpPrefixArgs = []string{"-test.run=^TestYouTubeShortURLHelper$", "--"}+ t.Cleanup(func() { storage.YtdlpPath, storage.YtdlpPrefixArgs = previousPath, previousPrefix })+ dir := t.TempDir()+ callPath := filepath.Join(dir, "calls.jsonl")+ t.Setenv("KRILLIN_TEST_YOUTUBE_CALLS", callPath)+ req := &YoutubeSubtitleReq{+ URL: "https://youtu.be/1_iv-S02hJ0?si=example", OriginLanguage: "auto", TaskBasePath: dir,+ }+ path, err := (&YouTubeSubtitleService{}).downloadYouTubeSubtitle(context.Background(), req)+ if err != nil {+ t.Fatal(err)+ }+ if req.OriginLanguage != "en" || filepath.Base(path) != "1_iv-S02hJ0.en-orig.vtt" {+ t.Fatalf("language = %s, caption = %s", req.OriginLanguage, path)+ }+ calls, err := os.ReadFile(callPath)+ if err != nil {+ t.Fatal(err)+ }+ lines := strings.Split(strings.TrimSpace(string(calls)), "\n")+ if len(lines) != 2 || !strings.Contains(lines[0], "--dump-single-json") || !strings.Contains(lines[1], "--write-auto-subs") {+ t.Fatalf("expected metadata and caption download calls, got %s", calls)+ }+ for _, line := range lines {+ if !strings.Contains(line, req.URL) {+ t.Fatalf("short URL was lost: %s", line)+ }+ }+}++func TestYouTubeShortURLHelper(t *testing.T) {+ callPath := os.Getenv("KRILLIN_TEST_YOUTUBE_CALLS")+ if callPath == "" {+ return+ }+ args := os.Args+ for i, arg := range args {+ if arg == "--" {+ args = args[i+1:]+ break+ }+ }+ file, err := os.OpenFile(callPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)+ if err != nil {+ t.Fatal(err)+ }+ if err := json.NewEncoder(file).Encode(args); err != nil {+ t.Fatal(err)+ }+ _ = file.Close()+ for _, arg := range args {+ if arg == "--dump-single-json" {+ fmt.Print(`{"language":"en","automatic_captions":{"en-orig":[{"url":"https://example.test/caption?lang=en","name":"English (Original)"}]}}`)+ os.Exit(0)+ }+ }+ for i, arg := range args {+ if arg == "-o" && i+1 < len(args) {+ path := strings.ReplaceAll(args[i+1], "%(ext)s", "en-orig.vtt")+ if err := os.WriteFile(path, []byte("WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nHello\n"), 0600); err != nil {+ t.Fatal(err)+ }+ os.Exit(0)+ }+ }+ t.Fatal("missing output path")+}diff --git a/runtime/krillinai/internal/service/youtube_subtitle.go b/runtime/krillinai/internal/service/youtube_subtitle.goindex 28b60132..14bcd262 100644--- a/runtime/krillinai/internal/service/youtube_subtitle.go+++ b/runtime/krillinai/internal/service/youtube_subtitle.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "html""net/url""os""os/exec"@@ -140,7 +141,7 @@ func (s *YouTubeSubtitleService) parseVttTime(timeStr string) (float64, error) {// 使用yt-dlp下载YouTube视频的字幕文件func (s *YouTubeSubtitleService) downloadYouTubeSubtitle(ctx context.Context, req *YoutubeSubtitleReq) (string, error) {- if !strings.Contains(req.URL, "youtube.com") {+ if !util.IsYouTubeURL(req.URL) {return "", fmt.Errorf("downloadYouTubeSubtitle: not a YouTube link")}@@ -538,6 +539,9 @@ func (s *YouTubeSubtitleService) processYouTubeSubtitle(ctx context.Context, reqreturn "", fmt.Errorf("failed to extract VTT words: %w", 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")+ }// 更新进度:提取完成if req.TaskPtr != nil {@@ -820,6 +824,8 @@ func (s *YouTubeSubtitleService) cleanVttText(text string) string {if text == "" {return text}+ text = html.UnescapeString(text)+ text = strings.NewReplacer("\u200b", "", "\u200c", "", "\u200d", "", "\u00a0", " ").Replace(text)// 先过滤音乐和其他提示标记(方括号内容)// 匹配 [music], [applause], [laughter], [inaudible] 等标记@@ -842,28 +848,6 @@ func (s *YouTubeSubtitleService) cleanVttText(text string) string {fillerWordsRegex := regexp.MustCompile(`(?i)^\s*(um|uh|er|ah|oh|mm|hmm|hm|eh)\s*[,,]?\s*`)cleanedText = fillerWordsRegex.ReplaceAllString(cleanedText, "")- // HTML实体解码映射- htmlEntities := map[string]string{- ">>": "", // 大于号双引号 - 直接过滤掉- ">": ">", // 大于号- "<<": "<<", // 小于号双引号- "<": "<", // 小于号- "&": "&", // &符号- """: "\"", // 双引号- "'": "'", // 单引号- " ": " ", // 不间断空格- "'": "'", // 单引号的数字实体- """: "\"", // 双引号的数字实体- "​": "", // 零宽度空格- "‌": "", // 零宽度非连接符- "‍": "", // 零宽度连接符- }-- // 替换HTML实体- for entity, replacement := range htmlEntities {- cleanedText = strings.ReplaceAll(cleanedText, entity, replacement)- }-// 移除多余的空格cleanedText = strings.TrimSpace(cleanedText)diff --git a/runtime/krillinai/pkg/util/youtube_url.go b/runtime/krillinai/pkg/util/youtube_url.gonew file mode 100644index 00000000..26a4a43a--- /dev/null+++ b/runtime/krillinai/pkg/util/youtube_url.go@@ -0,0 +1,17 @@+package util++import (+ "net/url"+ "strings"+)++func IsYouTubeURL(input string) bool {+ parsed, err := url.Parse(strings.TrimSpace(input))+ if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") {+ return false+ }+ hostname := strings.ToLower(strings.TrimSuffix(parsed.Hostname(), "."))+ return hostname == "youtu.be" ||+ hostname == "youtube.com" || strings.HasSuffix(hostname, ".youtube.com") ||+ hostname == "youtube-nocookie.com" || strings.HasSuffix(hostname, ".youtube-nocookie.com")+}diff --git a/runtime/krillinai/pkg/util/youtube_url_test.go b/runtime/krillinai/pkg/util/youtube_url_test.gonew file mode 100644index 00000000..99877b22--- /dev/null+++ b/runtime/krillinai/pkg/util/youtube_url_test.go@@ -0,0 +1,28 @@+package util++import "testing"++func TestIsYouTubeURL(t *testing.T) {+ for _, test := range []struct {+ input string+ want bool+ }{+ {"https://youtu.be/1_iv-S02hJ0?si=example", true},+ {"https://www.youtube.com/watch?v=1_iv-S02hJ0", true},+ {"https://m.youtube.com/shorts/1_iv-S02hJ0", true},+ {" https://YOUTU.BE./1_iv-S02hJ0 ", true},+ {"https://www.youtube-nocookie.com/embed/1_iv-S02hJ0", true},+ {"https://youtube.com.example.test/watch?v=demo", false},+ {"https://example.test/youtube.com/watch?v=demo", false},+ {"https://example.test/?url=https://youtube.com", false},+ {"file://youtube.com/demo", false},+ {"local:youtube.com.mp4", false},+ {"invalid", false},+ } {+ t.Run(test.input, func(t *testing.T) {+ if got := IsYouTubeURL(test.input); got != test.want {+ t.Fatalf("IsYouTubeURL(%q) = %v, want %v", test.input, got, test.want)+ }+ })+ }+}diff --git a/runtime/krillinai/pkg/whisper/audio_signal.go b/runtime/krillinai/pkg/whisper/audio_signal.gonew file mode 100644index 00000000..81b83685--- /dev/null+++ b/runtime/krillinai/pkg/whisper/audio_signal.go@@ -0,0 +1,67 @@+package whisper++import (+ "context"+ "fmt"+ "krillin-ai/internal/storage"+ "math"+ "os/exec"+ "regexp"+ "strconv"+ "time"+)++type audioSignal struct {+ known bool+ silent bool+ maxDB float64+ meanDB float64+}++var volumePattern = regexp.MustCompile(`(?m)(mean|max)_volume:\s*(-?inf|[-+0-9.]+)\s*dB`)++func inspectAudioSignal(audioFile string) audioSignal {+ if storage.FfmpegPath == "" {+ return audioSignal{}+ }+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ output, err := exec.CommandContext(ctx, storage.FfmpegPath,+ "-hide_banner", "-nostdin", "-i", audioFile, "-vn", "-af", "volumedetect", "-f", "null", "-",+ ).CombinedOutput()+ if err != nil {+ return audioSignal{}+ }+ return parseAudioSignal(output)+}++func parseAudioSignal(output []byte) audioSignal {+ levels := make(map[string]float64)+ for _, match := range volumePattern.FindAllSubmatch(output, -1) {+ value, err := strconv.ParseFloat(string(match[2]), 64)+ if err != nil || math.IsNaN(value) {+ return audioSignal{}+ }+ levels[string(match[1])] = value+ }+ maxDB, maxFound := levels["max"]+ meanDB, meanFound := levels["mean"]+ if !maxFound || !meanFound {+ return audioSignal{}+ }+ // Sound level can confirm near silence, but cannot distinguish speech from music.+ return audioSignal{known: true, silent: maxDB <= -60 && meanDB <= -60, maxDB: maxDB, meanDB: meanDB}+}++func emptyTranscriptionError(signal audioSignal) *TranscriptionError {+ if signal.known && signal.silent {+ return &TranscriptionError{Code: "audio_no_speech", Message: "transcription returned no words; local audio is silent or extremely quiet; check the source audio and volume"}+ }+ message := "transcription returned empty text and no usable timed words; this alone does not prove that the audio has no speech"+ if signal.known {+ message += fmt.Sprintf("; local audio contains sound (mean %.1f dB, peak %.1f dB), which may be speech, music or noise", signal.meanDB, signal.maxDB)+ } else {+ message += "; local audio analysis was unavailable"+ }+ return &TranscriptionError{Code: "audio_transcription_empty", Message: message + "; check the source audio or verify with another recognition model"}+}diff --git a/runtime/krillinai/pkg/whisper/diagnostics_test.go b/runtime/krillinai/pkg/whisper/diagnostics_test.gonew file mode 100644index 00000000..20621b1d--- /dev/null+++ b/runtime/krillinai/pkg/whisper/diagnostics_test.go@@ -0,0 +1,124 @@+package whisper++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "krillin-ai/internal/storage"+ "krillin-ai/log"+)++func TestTranscriptionResponseClassification(t *testing.T) {+ log.InitLogger()+ previousFFmpeg := storage.FfmpegPath+ storage.FfmpegPath = ""+ t.Cleanup(func() { storage.FfmpegPath = previousFFmpeg })+ for _, test := range []struct {+ name string+ status int+ payload string+ code string+ retryable bool+ }{+ {"empty", 200, `{"text":"","segments":[],"usage":{"seconds":270}}`, "audio_transcription_empty", false},+ {"blank_segment", 200, `{"text":" ","segments":[{"start":0,"end":16,"text":" "}]}`, "audio_transcription_empty", false},+ {"missing_timestamps", 200, `{"text":"Hello"}`, "audio_transcription_timestamps_missing", false},+ {"invalid_timestamps", 200, `{"text":"","segments":[{"start":2,"end":1,"text":"Hello"}]}`, "audio_transcription_timestamps_missing", false},+ {"error_envelope", 200, `{"text":"","error":{"message":"upstream unavailable"}}`, "audio_transcription_invalid_response", false},+ {"missing_text", 200, `{}`, "audio_transcription_invalid_response", false},+ {"null_text", 200, `{"text":null}`, "audio_transcription_invalid_response", false},+ {"wrong_text_type", 200, `{"text":12}`, "audio_transcription_invalid_response", false},+ {"wrong_segments_type", 200, `{"text":"Hello","segments":"bad"}`, "audio_transcription_invalid_response", false},+ {"malformed_json", 200, `<html>upstream error</html>`, "audio_transcription_invalid_response", false},+ {"http_error", 503, `{"error":{"message":"unavailable","type":"server_error"}}`, "audio_transcription_api_failed", true},+ } {+ t.Run(test.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(test.status)+ _, _ = w.Write([]byte(test.payload))+ }))+ defer server.Close()+ dir := t.TempDir()+ audio := filepath.Join(dir, "audio.wav")+ if err := os.WriteFile(audio, []byte("audio"), 0600); err != nil {+ t.Fatal(err)+ }+ _, err := NewOfficialClient(server.URL, "test", "", "chosen-asr").Transcription(audio, "en", dir)+ var classified *TranscriptionError+ if !errors.As(err, &classified) || classified.Code != test.code || classified.Retryable() != test.retryable {+ t.Fatalf("error = %v, want %s (retryable %v)", err, test.code, test.retryable)+ }+ })+ }+}++func TestTranscriptionReconstructsEmptyTextFromTimedSegments(t *testing.T) {+ testTranscription(t, true, `{"text":"","language":"en","segments":[{"start":1.25,"end":3.5,"text":"Hello world"}]}`, false)+}++func TestEmptyTranscriptionAudioEvidence(t *testing.T) {+ for _, test := range []struct {+ name string+ output string+ code string+ }{+ {"silence", "mean_volume: -91.0 dB\nmax_volume: -91.0 dB", "audio_no_speech"},+ {"near_silence", "mean_volume: -70.0 dB\nmax_volume: -61.0 dB", "audio_no_speech"},+ {"infinite_silence", "mean_volume: -inf dB\nmax_volume: -inf dB", "audio_no_speech"},+ {"sound", "mean_volume: -18.0 dB\nmax_volume: 0.0 dB", "audio_transcription_empty"},+ {"quiet_with_peak", "mean_volume: -70.0 dB\nmax_volume: -20.0 dB", "audio_transcription_empty"},+ {"unavailable", "invalid audio", "audio_transcription_empty"},+ } {+ t.Run(test.name, func(t *testing.T) {+ err := emptyTranscriptionError(parseAudioSignal([]byte(test.output)))+ if err.Code != test.code || err.Retryable() {+ t.Fatalf("error = %+v", err)+ }+ if test.code == "audio_transcription_empty" && !strings.Contains(err.Message, "does not prove") {+ t.Fatal("empty response must preserve uncertainty about speech")+ }+ })+ }+}++func TestEmptyTranscriptionWithRealAudio(t *testing.T) {+ ffmpeg := os.Getenv("KRILLIN_TEST_FFMPEG")+ if ffmpeg == "" {+ t.Skip("set KRILLIN_TEST_FFMPEG to verify real silent and non-silent audio")+ }+ previousFFmpeg := storage.FfmpegPath+ storage.FfmpegPath = ffmpeg+ t.Cleanup(func() { storage.FfmpegPath = previousFFmpeg })+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"text":"","segments":[]}`))+ }))+ defer server.Close()+ for _, test := range []struct {+ name, source, code string+ }{+ {"silence", "anullsrc=r=16000:cl=mono", "audio_no_speech"},+ {"tone", "sine=frequency=440:sample_rate=16000", "audio_transcription_empty"},+ } {+ t.Run(test.name, func(t *testing.T) {+ dir := t.TempDir()+ audio := filepath.Join(dir, "audio.wav")+ output, err := exec.Command(ffmpeg, "-hide_banner", "-nostdin", "-f", "lavfi", "-i", test.source, "-t", "0.5", audio).CombinedOutput()+ if err != nil {+ t.Fatalf("generate fixture: %v: %s", err, output)+ }+ _, err = NewOfficialClient(server.URL, "test", "", "chosen-asr").Transcription(audio, "en", dir)+ var classified *TranscriptionError+ if !errors.As(err, &classified) || classified.Code != test.code {+ t.Fatalf("error = %v, want %s", err, test.code)+ }+ })+ }+}diff --git a/runtime/krillinai/pkg/whisper/init.go b/runtime/krillinai/pkg/whisper/init.goindex eff725e7..7e06bf9f 100644--- a/runtime/krillinai/pkg/whisper/init.go+++ b/runtime/krillinai/pkg/whisper/init.go@@ -7,7 +7,9 @@ import ()type Client struct {- client *openai.Client+ client *openai.Client+ model string+ official bool}func NewClient(baseUrl, apiKey, proxyAddr string) *Client {@@ -25,6 +27,13 @@ func NewClient(baseUrl, apiKey, proxyAddr string) *Client {}}+ cfg.HTTPClient = &audioResponseClient{next: cfg.HTTPClient}client := openai.NewClientWithConfig(cfg)- return &Client{client: client}+ return &Client{client: client, model: openai.Whisper1}+}++func NewOfficialClient(baseUrl, apiKey, proxyAddr, model string) *Client {+ c := NewClient(baseUrl, apiKey, proxyAddr)+ c.model, c.official = model, true+ return c}diff --git a/runtime/krillinai/pkg/whisper/response.go b/runtime/krillinai/pkg/whisper/response.gonew file mode 100644index 00000000..6a02a015--- /dev/null+++ b/runtime/krillinai/pkg/whisper/response.go@@ -0,0 +1,69 @@+package whisper++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"++ "github.com/sashabaranov/go-openai"+)++type TranscriptionError struct {+ Code string+ Message string+ Cause error+}++func (e *TranscriptionError) Error() string { return e.Message }+func (e *TranscriptionError) Unwrap() error { return e.Cause }++func (e *TranscriptionError) Retryable() bool {+ return e.Code == "audio_transcription_api_failed"+}++type audioResponseClient struct {+ next interface {+ Do(*http.Request) (*http.Response, error)+ }+}++func (c *audioResponseClient) Do(request *http.Request) (*http.Response, error) {+ response, err := c.next.Do(request)+ if err != nil || !strings.HasSuffix(request.URL.Path, "/audio/transcriptions") || response.StatusCode < 200 || response.StatusCode >= 300 {+ return response, err+ }+ defer response.Body.Close()+ const maxResponseSize = 8 * 1024 * 1024+ body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseSize+1))+ if err != nil {+ return nil, err+ }+ invalid := func(reason string) (*http.Response, error) {+ return nil, &TranscriptionError{Code: "audio_transcription_invalid_response", Message: fmt.Sprintf("transcription service returned HTTP %d but %s", response.StatusCode, reason)}+ }+ if len(body) > maxResponseSize {+ return invalid("the response exceeded the size limit")+ }+ var payload struct {+ Text *string `json:"text"`+ Error json.RawMessage `json:"error"`+ }+ if err := json.Unmarshal(body, &payload); err != nil {+ return invalid("the response was not valid transcription JSON")+ }+ if len(payload.Error) > 0 && string(payload.Error) != "null" {+ return invalid("the response contained an error instead of a transcription")+ }+ if payload.Text == nil {+ return invalid("the required text field was missing")+ }+ var transcript openai.AudioResponse+ if err := json.Unmarshal(body, &transcript); err != nil {+ return invalid("the transcription fields had invalid types")+ }+ response.Body = io.NopCloser(bytes.NewReader(body))+ return response, nil+}diff --git a/runtime/krillinai/pkg/whisper/whisper.go b/runtime/krillinai/pkg/whisper/whisper.goindex 58205b73..77142845 100644--- a/runtime/krillinai/pkg/whisper/whisper.go+++ b/runtime/krillinai/pkg/whisper/whisper.go@@ -2,6 +2,8 @@ package whisperimport ("context"+ "errors"+ "fmt""github.com/sashabaranov/go-openai""go.uber.org/zap""krillin-ai/internal/types"@@ -10,21 +12,29 @@ import ()func (c *Client) Transcription(audioFile, language, workDir string) (*types.TranscriptionData, error) {+ granularity := openai.TranscriptionTimestampGranularityWord+ if c.official {+ granularity = openai.TranscriptionTimestampGranularitySegment+ }resp, err := c.client.CreateTranscription(context.Background(),openai.AudioRequest{- Model: openai.Whisper1,+ Model: c.model,FilePath: audioFile,Format: openai.AudioResponseFormatVerboseJSON,TimestampGranularities: []openai.TranscriptionTimestampGranularity{- openai.TranscriptionTimestampGranularityWord,+ granularity,},Language: language,},)if err != nil {+ var classified *TranscriptionError+ if errors.As(err, &classified) {+ return nil, err+ }log.GetLogger().Error("openai create transcription failed", zap.Error(err))- return nil, err+ return nil, &TranscriptionError{Code: "audio_transcription_api_failed", Message: fmt.Sprintf("transcription service request failed: %v", err), Cause: err}}transcriptionData := &types.TranscriptionData{@@ -34,6 +44,9 @@ func (c *Client) Transcription(audioFile, language, workDir string) (*types.Tran}num := 0for _, word := range resp.Words {+ if strings.TrimSpace(word.Word) == "" || word.Start < 0 || word.End <= word.Start {+ continue+ }if strings.Contains(word.Word, "—") {// 对称切分mid := (word.Start + word.End) / 2@@ -64,5 +77,40 @@ func (c *Client) Transcription(audioFile, language, workDir string) (*types.Tran}}+ if c.official && len(transcriptionData.Words) == 0 {+ for _, segment := range resp.Segments {+ if strings.TrimSpace(segment.Text) != "" && segment.End > segment.Start && segment.Start >= 0 {+ transcriptionData.Words = append(transcriptionData.Words, types.Word{Num: len(transcriptionData.Words), Text: segment.Text, Start: segment.Start, End: segment.End})+ }+ }+ }+ if strings.TrimSpace(transcriptionData.Text) == "" {+ parts := make([]string, len(transcriptionData.Words))+ for i, word := range transcriptionData.Words {+ parts[i] = word.Text+ }+ // Recognized text without valid timing is distinct from an empty result.+ if len(parts) == 0 {+ for _, word := range resp.Words {+ if text := strings.TrimSpace(word.Word); text != "" {+ parts = append(parts, text)+ }+ }+ if len(parts) == 0 {+ for _, segment := range resp.Segments {+ if text := strings.TrimSpace(segment.Text); text != "" {+ parts = append(parts, text)+ }+ }+ }+ }+ if len(parts) == 0 {+ return nil, emptyTranscriptionError(inspectAudioSignal(audioFile))+ }+ transcriptionData.Text = strings.Join(parts, " ")+ }+ if c.official && len(transcriptionData.Words) == 0 {+ return nil, &TranscriptionError{Code: "audio_transcription_timestamps_missing", Message: "transcription returned text but no valid subtitle timestamps; choose a timestamp-capable model"}+ }return transcriptionData, nil}diff --git a/runtime/krillinai/pkg/whisper/whisper_test.go b/runtime/krillinai/pkg/whisper/whisper_test.gonew file mode 100644index 00000000..06fad25f--- /dev/null+++ b/runtime/krillinai/pkg/whisper/whisper_test.go@@ -0,0 +1,62 @@+package whisper++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+)++func TestOfficialSelectedModelUsesReturnedSegmentTimestamps(t *testing.T) {+ testTranscription(t, true, `{"text":"Hello world","language":"en","segments":[{"start":1.25,"end":3.5,"text":"Hello world"}]}`, false)+}++func TestCustomWhisperKeepsWordTimestampsAndLegacyModel(t *testing.T) {+ testTranscription(t, false, `{"text":"Hello world","language":"en","words":[{"start":1.25,"end":3.5,"word":"Hello world"}]}`, false)+}++func TestOfficialTranscriptionRejectsMissingTimestamps(t *testing.T) {+ testTranscription(t, true, `{"text":"Hello world","language":"en"}`, true)+}++func testTranscription(t *testing.T, official bool, payload string, wantError bool) {+ t.Helper()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if err := r.ParseMultipartForm(1 << 20); err != nil {+ t.Error(err)+ }+ model, granularity := "whisper-1", "word"+ if official {+ model, granularity = "vendor/chosen-asr", "segment"+ }+ if r.FormValue("model") != model || r.FormValue("timestamp_granularities[]") != granularity || r.FormValue("response_format") != "verbose_json" {+ t.Errorf("unexpected transcription parameters: %v", r.MultipartForm.Value)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(payload))+ }))+ defer server.Close()+ dir := t.TempDir()+ audio := filepath.Join(dir, "audio.wav")+ if err := os.WriteFile(audio, []byte("audio"), 0600); err != nil {+ t.Fatal(err)+ }+ client := NewClient(server.URL, "test", "")+ if official {+ client = NewOfficialClient(server.URL, "test", "", "vendor/chosen-asr")+ }+ result, err := client.Transcription(audio, "en", dir)+ if wantError {+ if err == nil {+ t.Fatal("missing timestamps were accepted")+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ if len(result.Words) != 1 || result.Words[0].Start != 1.25 || result.Words[0].End != 3.5 || result.Words[0].Text != "Hello world" {+ t.Fatal(result)+ }+}