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
Align model pricing, improve subtitle translation, and streamline releases
Leggettc5e2f2fac8a1
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 89359839..578cefab 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -94,6 +94,7 @@ jobs:environment: releaseenv:OPENCREATOR_DESKTOP_CACHE_DIR: ${{ github.workspace }}/apps/desktop/.cache+ ELECTRON_CACHE: ${{ github.workspace }}/apps/desktop/.cache/electronOPENCREATOR_DESKTOP_BUILD_MANIFEST: ${{ github.workspace }}/apps/desktop/release/opencreator-desktop-build-manifest-${{ matrix.platform }}-${{ matrix.arch }}.jsonOPENCREATOR_DESKTOP_OFFICIAL_BUILD: '1'steps:@@ -149,7 +150,6 @@ jobs:with:go-version-file: runtime/krillinai/go.modcache-dependency-path: runtime/krillinai/go.sum- - run: pnpm install --frozen-lockfile- uses: actions/cache@v4with:path: |@@ -158,20 +158,29 @@ jobs:apps/desktop/.cache/node-gypapps/desktop/.cache/npmkey: desktop-tools-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('pnpm-lock.yaml', 'apps/desktop/package.json', 'apps/desktop/packaging/daemon-runtime/pnpm-lock.yaml') }}+ restore-keys: |+ desktop-tools-${{ runner.os }}-${{ matrix.arch }}-- uses: actions/cache@v4with:path: apps/desktop/.cache/codex-runtimekey: codex-runtime-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('apps/desktop/scripts/prepare-codex-runtime.mjs', 'apps/desktop/scripts/codex-runtime-contract.mjs', 'resources/codex-runtime/**') }}+ restore-keys: |+ codex-runtime-${{ runner.os }}-${{ matrix.arch }}-- uses: actions/cache@v4with:path: |.runtime/vendor/creator-runtime/${{ matrix.platform }}-${{ matrix.arch }}key: creator-runtime-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('apps/desktop/scripts/install-creator-runtime-dependencies.mjs', 'apps/desktop/scripts/creator-runtime-releases.mjs', 'apps/desktop/scripts/prepare-creator-runtime.mjs') }}+ - uses: actions/cache@v4+ with:+ path: .runtime/vendor/stickman-runtime/${{ matrix.platform }}-${{ matrix.arch }}+ key: stickman-browser-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('apps/desktop/scripts/prepare-stickman-runtime.mjs') }}- uses: actions/cache@v4with:path: |.runtime/build/krillinai/${{ matrix.platform }}-${{ matrix.arch }}key: krillinai-build-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('scripts/build-krillinai.mjs', 'runtime/krillinai/**') }}+ - run: pnpm install --frozen-lockfile- name: 生成 macOS 正式签名安装包if: matrix.platform == 'darwin'shell: bash@@ -209,9 +218,7 @@ jobs:OPENCREATOR_DESKTOP_TARGET_PLATFORM: ${{ matrix.platform }}OPENCREATOR_DESKTOP_TARGET_ARCH: ${{ matrix.arch }}- name: 验证实际打包应用- run: >-- pnpm --filter @opencreator/desktop- ${{ matrix.name == 'macos-arm64' && 'e2e:package' || 'e2e:package:smoke' }}+ run: pnpm --filter @opencreator/desktop e2e:package:smoke- name: 生成 KrillinAI Server 与 CLI 独立发布包run: pnpm krillinai:packageenv:@@ -223,12 +230,14 @@ jobs:name: ${{ matrix.artifact }}path: ${{ env.OPENCREATOR_DESKTOP_RELEASE_ASSETS }}/*if-no-files-found: error+ compression-level: 0- name: 上传 KrillinAI Server 与 CLI 发布附件uses: actions/upload-artifact@v4with:name: krillinai-release-${{ matrix.name }}path: ${{ env.OPENCREATOR_KRILLINAI_RELEASE_ASSETS }}/*if-no-files-found: error+ compression-level: 0- name: 保留内部构建诊断if: always()uses: actions/upload-artifact@v4@@ -271,6 +280,7 @@ jobs:name: krillinai-release-linuxpath: .runtime/release/krillinai/*if-no-files-found: error+ compression-level: 0candidate-ready:if: github.event_name == 'workflow_dispatch' && inputs.target == 'all'diff --git a/apps/daemon/src/gateway/client.ts b/apps/daemon/src/gateway/client.tsindex ba088e19..b7ec04db 100644--- a/apps/daemon/src/gateway/client.ts+++ b/apps/daemon/src/gateway/client.ts@@ -8,7 +8,7 @@ const modelSchema = z.object({modality: z.enum(['text', 'image', 'video', 'speech', 'transcription']),capabilities: z.array(z.string()), voices: z.array(z.string().min(1)).optional(),vendor: z.string().optional(), status: z.enum(['ready','temporarily_unavailable','retired']).optional(), statusReason: z.string().optional(), recommended: z.boolean().optional(),- price: z.object({version:z.string(),inputPerMillion:z.number().optional(),outputPerMillion:z.number().optional(),perMinute:z.number().optional(),perMillionCharacters:z.number().optional(),perRequest:z.number().optional(),videoUnitsPerSecond:z.record(z.number().int().positive().max(1_000_000_000_000)).optional()}).optional(),+ price: z.object({version:z.string(),billing:z.literal('usage').optional(),inputPerMillion:z.number().optional(),cachedInputPerMillion:z.number().optional(),cacheWritePerMillion:z.number().optional(),imageInputPerMillion:z.number().optional(),outputPerMillion:z.number().optional(),perMinute:z.number().optional(),perMillionCharacters:z.number().optional(),perRequest:z.number().optional(),videoUnitsPerSecond:z.record(z.number().int().positive().max(1_000_000_000_000)).optional()}).optional(),videoOptions: z.object({ profile:z.string(), maxImages:z.number().int().min(0).max(30), maxVideos:z.number().int().min(0).max(10), maxAudios:z.number().int().min(0).max(10), firstLastFrames:z.boolean(), framesExclusive:z.boolean(), generateAudio:z.boolean(), referenceDuration:z.number().int().positive().optional() }).optional(),sizes: z.array(z.string().regex(/^\d+x\d+$/)).optional(),durations: z.array(z.number().int().positive()).optional(),diff --git a/apps/daemon/test/unit/gateway-client.test.ts b/apps/daemon/test/unit/gateway-client.test.tsindex 351dd359..928c93de 100644--- a/apps/daemon/test/unit/gateway-client.test.ts+++ b/apps/daemon/test/unit/gateway-client.test.ts@@ -1,5 +1,11 @@import { expect, it, vi } from 'vitest';-import { accountSchema, createGatewayClient, GatewayError } from '../../src/gateway/client.js';+import { accountSchema, catalogSchema, createGatewayClient, GatewayError } from '../../src/gateway/client.js';++it('retains fractional retail token prices and image/cache billing categories', () => {+ const price = { version: 'cost-50-v1', billing: 'usage', inputPerMillion: 5229.578, imageInputPerMillion: 10459.156, cachedInputPerMillion: 104.591, cacheWritePerMillion: 2614.789, outputPerMillion: 31377.469 };+ const catalog = catalogSchema.parse({ models: [{ id: 'gpt-image-2.5-flare', modality: 'image', capabilities: ['generate'], price }] });+ expect(catalog.models[0]?.price).toEqual(price);+});it('协商稳定密钥策略并拒绝仍会自动轮换的响应', 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: {}, modelUsePolicy: 'cached-key-v1', keyRotation: false };diff --git a/apps/desktop/scripts/package-release.mjs b/apps/desktop/scripts/package-release.mjsindex f30c6353..d87150fb 100644--- a/apps/desktop/scripts/package-release.mjs+++ b/apps/desktop/scripts/package-release.mjs@@ -27,7 +27,7 @@ import {} from './mac-signing.mjs';import { submitAndWaitForNotarization } from './apple-notarization.mjs';import { prepareElectronBuilderCache } from './electron-builder-cache.mjs';-import { runStage } from './script-utils.mjs';+import { runParallelStages, runStage } from './script-utils.mjs';import { stageReleaseAssets } from './release-assets.mjs';import {hashDirectory as hashStickmanDirectory,@@ -93,27 +93,17 @@ await runStage('构建 Desktop', 'pnpm', ['--filter', '@opencreator/desktop', 'benv,timeoutMs: 5 * 60_000});-await runStage('准备打包 Daemon 与 Web', process.execPath, [- resolve(scriptDir, 'prepare-daemon.mjs')-], {- cwd: rootDir,- env,- timeoutMs: 25 * 60_000-});-await runStage('准备 Creator Runtime', process.execPath, [- resolve(scriptDir, 'prepare-creator-runtime.mjs')-], {- cwd: rootDir,- env,- timeoutMs: 25 * 60_000-});-await runStage('准备 Codex Runtime', process.execPath, [- resolve(scriptDir, 'prepare-codex-runtime.mjs')-], {- cwd: rootDir,- env,- timeoutMs: 10 * 60_000-});+await runParallelStages([+ () => runStage('准备打包 Daemon 与 Web', process.execPath, [+ resolve(scriptDir, 'prepare-daemon.mjs')+ ], { cwd: rootDir, env, timeoutMs: 25 * 60_000 }),+ () => runStage('准备 Creator Runtime', process.execPath, [+ resolve(scriptDir, 'prepare-creator-runtime.mjs')+ ], { cwd: rootDir, env, timeoutMs: 25 * 60_000 }),+ () => runStage('准备 Codex Runtime', process.execPath, [+ resolve(scriptDir, 'prepare-codex-runtime.mjs')+ ], { cwd: rootDir, env, timeoutMs: 10 * 60_000 })+]);const candidates = packageRootCandidates(platform, arch);for (const path of candidates) rmSync(path, { recursive: true, force: true });@@ -132,23 +122,27 @@ const packageWithSigningEnvironment = async builderEnv => {await runStage('构建独立 Remotion 组件与轻量角色资源', process.execPath, [resolve(scriptDir, 'prepare-stickman-runtime.mjs')], { cwd: rootDir, env: builderEnv, timeoutMs: 25 * 60_000 });- if (macSigning.mode === 'developer-id' && mode === 'release') {- const componentNotaryArchive = resolve(desktopDir, '.pack', 'remotion-notarization.zip');- try {- await runStage('准备 Remotion 组件公证', 'ditto', ['-c', '-k', '--keepParent', resolve(desktopDir, '.pack', 'stickman-runtime'), componentNotaryArchive], { cwd: rootDir, env: builderEnv });- await submitAndWaitForNotarization(componentNotaryArchive, notarizationArgs);- } finally { rmSync(componentNotaryArchive, { force: true }); }- }- await runStage(- mode === 'dir' ? '生成可运行目录' : '生成桌面安装包',- 'electron-builder',- args,- {- cwd: desktopDir,- env: builderEnv,- timeoutMs: mode === 'dir' ? 20 * 60_000 : 50 * 60_000- }- );+ // Remotion is distributed separately; its notarization does not modify the App.+ await runParallelStages([+ async () => {+ if (macSigning.mode !== 'developer-id' || mode !== 'release') return;+ const componentNotaryArchive = resolve(desktopDir, '.pack', 'remotion-notarization.zip');+ try {+ await runStage('准备 Remotion 组件公证', 'ditto', ['-c', '-k', '--keepParent', resolve(desktopDir, '.pack', 'stickman-runtime'), componentNotaryArchive], { cwd: rootDir, env: builderEnv });+ await submitAndWaitForNotarization(componentNotaryArchive, notarizationArgs);+ } finally { rmSync(componentNotaryArchive, { force: true }); }+ },+ () => runStage(+ mode === 'dir' ? '生成可运行目录' : '生成桌面安装包',+ 'electron-builder',+ args,+ {+ cwd: desktopDir,+ env: builderEnv,+ timeoutMs: mode === 'dir' ? 20 * 60_000 : 50 * 60_000+ }+ )+ ]);const packageRoot = findFreshPackageRoot(candidates);const artifacts = findFreshArtifacts(packageStartedAt, mode, platform);diff --git a/apps/desktop/scripts/script-utils.mjs b/apps/desktop/scripts/script-utils.mjsindex 118aa882..d8468257 100644--- a/apps/desktop/scripts/script-utils.mjs+++ b/apps/desktop/scripts/script-utils.mjs@@ -1,6 +1,20 @@import { spawn } from 'node:child_process';import { isAbsolute } from 'node:path';+export async function runParallelStages(stages) {+ const results = await Promise.allSettled(+ stages.map(stage => Promise.resolve().then(stage))+ );+ const failures = results+ .filter(result => result.status === 'rejected')+ .map(result => result.reason);+ if (failures.length === 1) throw failures[0];+ if (failures.length > 1) {+ throw new AggregateError(failures, '多个打包阶段失败');+ }+ return results.map(result => result.value);+}+export async function runStage(label, command, args, options = {}) {const timeoutMs = options.timeoutMs ?? 5 * 60_000;const startedAt = Date.now();diff --git a/apps/desktop/test/release-workflow.test.mjs b/apps/desktop/test/release-workflow.test.mjsindex bab42166..3d489548 100644--- a/apps/desktop/test/release-workflow.test.mjs+++ b/apps/desktop/test/release-workflow.test.mjs@@ -105,7 +105,7 @@ describe('Desktop release workflow', () => {expect(releaseWorkflow).toContain("candidate-ready:");expect(releaseWorkflow).toContain("inputs.target == 'all'");expect(releaseWorkflow).toContain('e2e:package:smoke');- expect(releaseWorkflow).toContain("matrix.name == 'macos-arm64'");+ expect(releaseWorkflow).not.toContain("matrix.name == 'macos-arm64'");expect(releaseWorkflow).toContain('opencreator-release-candidate-${{ steps.build-input.outputs.digest }}');});@@ -168,4 +168,29 @@ describe('Desktop release workflow', () => {"'apps/desktop/packaging/daemon-runtime/pnpm-lock.yaml'");});++ it('restores reusable tools and caches the version-bound Chromium download', () => {+ expect(releaseWorkflow).toContain(+ 'ELECTRON_CACHE: ${{ github.workspace }}/apps/desktop/.cache/electron'+ );+ expect(releaseWorkflow.indexOf('key: desktop-tools-')).toBeLessThan(+ releaseWorkflow.indexOf('run: pnpm install --frozen-lockfile')+ );+ expect(releaseWorkflow).toContain(+ 'restore-keys: |\n desktop-tools-${{ runner.os }}-${{ matrix.arch }}-'+ );+ expect(releaseWorkflow).toContain(+ 'restore-keys: |\n codex-runtime-${{ runner.os }}-${{ matrix.arch }}-'+ );+ expect(releaseWorkflow).toContain(+ 'path: .runtime/vendor/stickman-runtime/${{ matrix.platform }}-${{ matrix.arch }}'+ );+ expect(releaseWorkflow).toContain(+ "key: stickman-browser-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('apps/desktop/scripts/prepare-stickman-runtime.mjs') }}"+ );+ });++ it('uploads compressed release archives without recompressing them', () => {+ expect(releaseWorkflow.match(/compression-level: 0/g)).toHaveLength(3);+ });});diff --git a/apps/desktop/test/script-utils.test.mjs b/apps/desktop/test/script-utils.test.mjsnew file mode 100644index 00000000..04698e07--- /dev/null+++ b/apps/desktop/test/script-utils.test.mjs@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { runParallelStages } from '../scripts/script-utils.mjs';++describe('parallel package stages', () => {+ it('starts independent work before waiting and preserves result order', async () => {+ const signing = Promise.withResolvers();+ const notarization = Promise.withResolvers();+ const started = [];+ const result = runParallelStages([+ () => { started.push('signing'); return signing.promise; },+ () => { started.push('notarization'); return notarization.promise; }+ ]);+ await Promise.resolve();+ expect(started).toEqual(['signing', 'notarization']);+ notarization.resolve('accepted');+ signing.resolve('signed');+ await expect(result).resolves.toEqual(['signed', 'accepted']);+ });++ it.each([0, 1])('waits for cleanup before rejecting a failure in stage %i', async failedIndex => {+ const sibling = Promise.withResolvers();+ const failure = new Error('notarization failed');+ let cleanedUp = false;+ let settled = false;+ const stages = [+ () => { throw failure; },+ async () => {+ await sibling.promise;+ cleanedUp = true;+ }+ ];+ if (failedIndex === 1) stages.reverse();+ const result = runParallelStages(stages);+ const checked = expect(result).rejects.toBe(failure);+ void result.catch(() => { settled = true; });+ await new Promise(setImmediate);+ expect(settled).toBe(false);+ sibling.resolve();+ await checked;+ expect(cleanedUp).toBe(true);+ });++ it('preserves errors from every failed stage', async () => {+ const errors = [new Error('signing failed'), new Error('notarization failed')];+ const result = runParallelStages(errors.map(error => async () => { throw error; }));+ await expect(result).rejects.toMatchObject({ errors });+ });+});diff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsxindex 96361a1a..22f185c7 100644--- a/apps/web/src/app/AppController.tsx+++ b/apps/web/src/app/AppController.tsx@@ -334,6 +334,7 @@ export function AppController(props: AppControllerProps) {const [creatorJobs, setCreatorJobs] = useState<CreatorJob[]>([]);const [creatorJobsLoading, setCreatorJobsLoading] = useState(false);const [creatorJobsError, setCreatorJobsError] = useState<string>();+ const [hasActiveCreatorTasks, setHasActiveCreatorTasks] = useState(false);const [creatorPresets, setCreatorPresets] = useState<CreatorPresetSummary[]>([]);const [creatorPresetsLoading, setCreatorPresetsLoading] = useState(false);const [creatorPresetsError, setCreatorPresetsError] = useState<string>();@@ -1526,6 +1527,30 @@ export function AppController(props: AppControllerProps) {};}, [connectionState.status, creatorService, state.activeView]);+ useEffect(() => {+ setHasActiveCreatorTasks(false);+ if (connectionState.status !== 'connected' || creatorService === null+ || (state.activeView !== 'account' && state.activeView !== 'subscription')) return;+ const service = creatorService;+ let canceled = false;+ let working = false;+ async function refreshActiveCreatorTasks() {+ if (working) return;+ working = true;+ try {+ const response = await service.listJobs();+ if (!canceled) setHasActiveCreatorTasks(response.jobs.some(job => job.status === 'running'));+ } catch {+ if (!canceled) setHasActiveCreatorTasks(false);+ } finally {+ working = false;+ }+ }+ void refreshActiveCreatorTasks();+ const timer = window.setInterval(() => void refreshActiveCreatorTasks(), 5_000);+ return () => { canceled = true; window.clearInterval(timer); };+ }, [connectionState.status, creatorService, state.activeView]);+useEffect(() => {let canceled = false;@@ -4737,6 +4762,9 @@ export function AppController(props: AppControllerProps) {view={state.activeView}service={gatewayAccountService}accountState={gatewayAccountState}+ hasActiveTasks={connectionState.status === 'connected' && (+ hasActiveCreatorTasks || runningThreadIds.size > 0 || runtimeTasks.some(task => task.status === 'running')+ )}billingOrderId={props.route.view === 'account' ? props.route.billingOrderId : undefined}billingReturnUrl={hostBridge.billingReturnUrl}prepareExternalNavigation={hostBridge.prepareExternalNavigation}diff --git a/apps/web/src/components/forms/OfficialModelSelect.test.tsx b/apps/web/src/components/forms/OfficialModelSelect.test.tsxindex 5d4d5ad1..e63905d0 100644--- a/apps/web/src/components/forms/OfficialModelSelect.test.tsx+++ b/apps/web/src/components/forms/OfficialModelSelect.test.tsx@@ -2,6 +2,7 @@ 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';+import { gatewayRecommendedModelId, type GatewayModel } from '@opencreator/protocol';function catalog() {const models = Array.from({ length: 12 }, (_, index) => ({ id: `vendor/model-${index}`, name: `Model ${index}`, modality: 'text' as const, capabilities: ['responses'] }));@@ -21,7 +22,7 @@ it('shows search results immediately in the same control without retaining unrelawait user.type(input, 'Model 11');const list = screen.getByRole('listbox', { name: '文本模型' });expect(within(list).getAllByRole('option')).toHaveLength(1);- expect(screen.getByText('1 个匹配模型')).toBeInTheDocument();+ 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');@@ -112,3 +113,48 @@ it('closes when disabled and retains accessibility descriptions and the selectedexpect(input).toHaveAttribute('aria-describedby', 'model-count');expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); expect(change).not.toHaveBeenCalled();});++it('lists the recommended model once and can search its original ID', async () => {+ const recommended: GatewayModel = { id: 'openai/gpt-image-2.5-flare', name: 'GPT Image Flare', vendor: 'OpenAI', modality: 'image', capabilities: [], price: { version: 'v1', billing: 'usage', inputPerMillion: 5229.58, outputPerMillion: 31377.47 } };+ const other: GatewayModel = { ...recommended, id: 'openai/gpt-image-2.5-sunburst', name: 'GPT Image Sunburst' };+ const change = vi.fn();+ render(<OfficialModelSelect label="图片模型" models={[recommended, other]} value={recommended.id} recommendedModel={recommended} followsRecommendation onChange={change} />);+ const user = userEvent.setup();+ const input = screen.getByRole('combobox');+ await user.click(input);+ expect(screen.getByText('2 个模型')).toBeInTheDocument();+ expect(screen.getAllByRole('option')).toHaveLength(2);+ expect(screen.queryByRole('option', { name: 'GPT Image Flare' })).not.toBeInTheDocument();+ const option = screen.getByRole('option', { name: '系统推荐 · GPT Image Flare' });+ expect(option).toHaveAttribute('aria-selected', 'true');+ expect(within(option).getByText('约 64 积分/张')).toBeInTheDocument();+ expect(option.title).toContain('2,000 个图像输出 tokens');+ await user.type(input, recommended.id);+ expect(screen.getAllByRole('option')).toHaveLength(1);+ await user.keyboard('{Enter}');+ expect(change).not.toHaveBeenCalled();+ expect(input).toHaveValue('系统推荐 · GPT Image Flare');+});++it('preserves a manual selection matching the recommendation and can enable future recommendations', async () => {+ const recommended = catalog()[0]!;+ const change = vi.fn();+ const view = render(<OfficialModelSelect label="文本模型" models={catalog()} value={recommended.id} recommendedModel={recommended} followsRecommendation={false} onChange={change} />);+ const input = screen.getByRole('combobox');+ const user = userEvent.setup();+ expect(input).toHaveValue('系统推荐 · Model 0');+ await user.click(input);+ expect(screen.getAllByRole('option')).toHaveLength(13);+ await user.click(screen.getByRole('option', { name: '系统推荐 · Model 0', selected: true }));+ expect(change).toHaveBeenCalledWith(gatewayRecommendedModelId);+ const next = catalog()[1]!;+ view.rerender(<OfficialModelSelect label="文本模型" models={catalog()} value={recommended.id} recommendedModel={next} followsRecommendation={false} onChange={change} />);+ expect(input).toHaveValue('Model 0');+ await user.click(input);+ expect(screen.getByRole('option', { name: 'Model 0' })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getAllByRole('option')).toHaveLength(13);+ expect(screen.queryByRole('option', { name: 'Model 1' })).not.toBeInTheDocument();+ view.rerender(<OfficialModelSelect label="文本模型" models={catalog()} value={next.id} recommendedModel={next} followsRecommendation onChange={change} />);+ await user.keyboard('{Escape}');+ expect(input).toHaveValue('系统推荐 · Model 1');+});diff --git a/apps/web/src/components/forms/OfficialModelSelect.tsx b/apps/web/src/components/forms/OfficialModelSelect.tsxindex 99faf57e..fb1a4cd0 100644--- a/apps/web/src/components/forms/OfficialModelSelect.tsx+++ b/apps/web/src/components/forms/OfficialModelSelect.tsx@@ -4,29 +4,15 @@ import { Check, ChevronDown, Search, X } from 'lucide-react';import Fuse from 'fuse.js';import { gatewayModelReady, gatewayRecommendedModelId, type GatewayModel } from '@opencreator/protocol';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';-import { formatGatewayCreditAmount } from '../../features/account/billing-display.js';+import { officialModelPrice, officialModelPriceDescription } from './official-model-pricing.js';import './official-model-select.css';+export { officialModelPrice } from './official-model-pricing.js';+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 function officialModelPrice(model:GatewayModel,l:(zh:string,en:string)=>string):string {- const p=model.price;if(!p)return '';- if(model.modality==='video'){- const rates=Object.values(p.videoUnitsPerSecond??{});- if(!rates.length)return '';- const amount=formatGatewayCreditAmount(Math.min(...rates)/1_000_000);- return l(`${amount} 积分/秒起`, `From ${amount} credits/second`);- }- if(p.perRequest)return l(`${formatGatewayCreditAmount(p.perRequest)} 积分/次`,`${formatGatewayCreditAmount(p.perRequest)} credits/request`);- const components=[];- if(p.perMinute)components.push(l(`${formatGatewayCreditAmount(p.perMinute)} 积分/分钟`,`${formatGatewayCreditAmount(p.perMinute)} credits/min`));- if(p.perMillionCharacters)components.push(l(`${formatGatewayCreditAmount(p.perMillionCharacters)} 积分/百万字符`,`${formatGatewayCreditAmount(p.perMillionCharacters)} credits/M characters`));- if(components.length)return components.join(' + ');- return l(`输入 ${formatGatewayCreditAmount(p.inputPerMillion)} / 输出 ${formatGatewayCreditAmount(p.outputPerMillion)} 积分/百万 token`,`${formatGatewayCreditAmount(p.inputPerMillion)} in / ${formatGatewayCreditAmount(p.outputPerMillion)} out credits/M tokens`);-}-export default function OfficialModelSelect(props: {label: string; describedBy?: string; models: GatewayModel[]; value: string;recommendedModel?: GatewayModel; followsRecommendation?: boolean;@@ -42,20 +28,24 @@ export default function OfficialModelSelect(props: {const [activeIndex, setActiveIndex] = useState(0);const [position, setPosition] = useState<{ left: number; top: number; width: number; maxHeight: number; above: boolean }>();const automatic = l('自动选择', 'Automatic');- const selectionValue = props.followsRecommendation && props.recommendedModel ? gatewayRecommendedModelId : props.value;- const choices = useMemo(() => [...(props.recommendedModel ? [{ ...props.recommendedModel,- id: gatewayRecommendedModelId, vendor: undefined, name: l(`系统推荐 · ${officialModelLabel(props.recommendedModel, automatic)}`, `Recommended · ${officialModelLabel(props.recommendedModel, automatic)}`), recommended: true }] : []), ...props.models].map(model => {- const label = officialModelLabel(model, automatic);- return { model, label, nameSearch: normalizeSearch(label), idSearch: normalizeSearch(model.id) };- }), [props.models, props.recommendedModel, automatic, l]);+ const selectionValue = props.recommendedModel && (props.followsRecommendation || props.value === props.recommendedModel.id) ? gatewayRecommendedModelId : props.value;+ const choices = useMemo(() => {+ const models = [...new Map(props.models.map(model => [model.id, model])).values()];+ return [...(props.recommendedModel ? [props.recommendedModel] : []), ...models.filter(model => model.id !== props.recommendedModel?.id)].map(model => {+ const recommended = model.id === props.recommendedModel?.id;+ const name = officialModelLabel(model, automatic);+ const label = recommended ? l(`系统推荐 · ${name}`, `Recommended · ${name}`) : name;+ return { model, value: recommended ? gatewayRecommendedModelId : model.id, label, nameSearch: normalizeSearch(label), idSearch: normalizeSearch(model.id) };+ });+ }, [props.models, props.recommendedModel, automatic, l]);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].sort((a,b)=>Number(b.model.id===selectionValue)-Number(a.model.id===selectionValue)- || Number(!!b.model.recommended)-Number(!!a.model.recommended)+ return [...choices].sort((a,b)=>Number(b.value===selectionValue)-Number(a.value===selectionValue)+ || Number(b.value===gatewayRecommendedModelId || !!b.model.recommended)-Number(a.value===gatewayRecommendedModelId || !!a.model.recommended)|| (a.model.vendor??'').localeCompare(b.model.vendor??''));}const terms = query.trim().split(/\s+/).map(normalizeSearch).filter(Boolean);@@ -66,7 +56,7 @@ export default function OfficialModelSelect(props: {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, selectionValue]);- const selected = choices.find(choice => choice.model.id === selectionValue);+ const selected = choices.find(choice => choice.value === selectionValue);const selectedLabel = selected?.label ?? (props.value || (props.models.length === 0 ? l('暂不可用', 'Unavailable') : l('选择模型', 'Select model')));const expanded = open && !props.disabled;const currentIndex = Math.min(activeIndex, filtered.length - 1);@@ -81,7 +71,7 @@ export default function OfficialModelSelect(props: {if (!(value === gatewayRecommendedModelId && props.recommendedModel) && !props.models.some(model=>model.id===value&&gatewayModelReady(model)))return;inputRef.current?.focus();close();- if (value !== selectionValue) props.onChange(value);+ if (value !== selectionValue || (value === gatewayRecommendedModelId && !props.followsRecommendation)) props.onChange(value);}useEffect(() => { if (props.disabled) close(); }, [props.disabled]);@@ -144,7 +134,7 @@ export default function OfficialModelSelect(props: {} else if (event.key === 'Enter') {event.preventDefault();if (!expanded) show();- else if (filtered[currentIndex]) select(filtered[currentIndex].model.id);+ else if (filtered[currentIndex]) select(filtered[currentIndex].value);} else if (event.key === 'Escape' && expanded) {event.preventDefault(); event.stopPropagation(); close();} else if (event.key === 'Tab') close();@@ -180,25 +170,25 @@ export default function OfficialModelSelect(props: {transform: position.above ? 'translateY(-100%)' : undefined,}}><div className="official-model-menu-count" role="status">- {query.trim() ? l(`${filtered.length} 个匹配项`, `${filtered.length} matches`) : l(`${props.models.length} 个模型`, `${props.models.length} models`)}+ {query.trim() ? l(`${filtered.length} 个匹配项`, `${filtered.length} matches`) : l(`${choices.length} 个模型`, `${choices.length} models`)}</div><div id={`${id}-listbox`} className="official-model-options" role="listbox" aria-label={props.label}>{filtered.map((choice, index) => <Fragment key={choice.model.id}>- {choice.model.vendor && choice.model.vendor !== filtered[index-1]?.model.vendor ? <div className="official-model-menu-count" role="presentation">{choice.model.vendor}</div> : null}+ {choice.value !== gatewayRecommendedModelId && choice.model.vendor && (choice.model.vendor !== filtered[index-1]?.model.vendor || filtered[index-1]?.value === gatewayRecommendedModelId) ? <div className="official-model-menu-count" role="presentation">{choice.model.vendor}</div> : null}<button id={optionId(index)} type="button" role="option" tabIndex={-1}- aria-label={choice.label} aria-selected={choice.model.id === selectionValue}+ aria-label={choice.label} aria-selected={choice.value === selectionValue}disabled={!gatewayModelReady(choice.model)} aria-disabled={!gatewayModelReady(choice.model)}className={`official-model-option${index === currentIndex ? ' is-active' : ''}`}- title={choice.label} onMouseDown={event => event.preventDefault()}+ title={[choice.label, officialModelPriceDescription(choice.model, l)].filter(Boolean).join('\n')} onMouseDown={event => event.preventDefault()}onPointerMove={event => { if (event.pointerType === 'mouse') setActiveIndex(index); }}- onClick={() => select(choice.model.id)}>+ onClick={() => select(choice.value)}><span className="official-model-option-text"><span className="official-model-option-name">{choice.label}</span>- {!/openrouter/i.test(choice.model.id) && choice.model.id !== gatewayRecommendedModelId ? <span className="official-model-option-id">{choice.model.vendor ? `${choice.model.vendor} · ` : ''}{choice.model.id}</span> : null}+ {!/openrouter/i.test(choice.model.id) && choice.value !== gatewayRecommendedModelId ? <span className="official-model-option-id">{choice.model.vendor ? `${choice.model.vendor} · ` : ''}{choice.model.id}</span> : null}{choice.model.price?<span className="official-model-option-id">{officialModelPrice(choice.model,l)}</span>:null}- {choice.model.recommended?<span className="official-model-option-id">{l('推荐','Recommended')}</span>:null}+ {choice.model.recommended && choice.value !== gatewayRecommendedModelId ?<span className="official-model-option-id">{l('推荐','Recommended')}</span>:null}{!gatewayModelReady(choice.model)?<span className="official-model-option-id">{l('暂不可用','Temporarily unavailable')}</span>:null}</span>- {choice.model.id === selectionValue ? <Check size={16} aria-hidden="true" /> : <span className="official-model-check-space" />}+ {choice.value === selectionValue ? <Check size={16} aria-hidden="true" /> : <span className="official-model-check-space" />}</button></Fragment>)}{filtered.length === 0 ? <div className="official-model-empty" role="status">{l('未找到匹配模型', 'No matching models')}</div> : null}</div>diff --git a/apps/web/src/components/forms/official-model-pricing.test.ts b/apps/web/src/components/forms/official-model-pricing.test.tsnew file mode 100644index 00000000..01ac0292--- /dev/null+++ b/apps/web/src/components/forms/official-model-pricing.test.ts@@ -0,0 +1,59 @@+import { expect, it } from 'vitest';+import type { GatewayModel } from '@opencreator/protocol';+import { officialModelPrice, officialModelPriceDescription } from './official-model-pricing.js';++const zh = (value: string) => value;+const en = (_: string, value: string) => value;+const model = (modality: GatewayModel['modality'], price: NonNullable<GatewayModel['price']>, extra: Partial<GatewayModel> = {}): GatewayModel => ({ id: 'test', modality, capabilities: [], price, ...extra });+const video = model('video', { version: 'v1', videoUnitsPerSecond: { '480p': 10_000_000, '720p': 37_354_133, '1080p': 44_824_959 } }, { durations: [4, 6, 8], resolutions: ['480p', '720p', '1080p'], aspectRatios: ['9:16', '16:9'] });++it.each([+ [model('text', { version: 'v1', inputPerMillion: 2091.831996, outputPerMillion: 10459.15998 }), '输入 2092 / 输出 10459 积分/百万 token', 'Input 2092 / output 10459 credits/M tokens'],+ [model('text', { version: 'v1', inputPerMillion: 119.533223, outputPerMillion: 478.132891 }), '输入 120 / 输出 478 积分/百万 token', 'Input 120 / output 478 credits/M tokens'],+ [model('image', { version: 'v1', billing: 'usage', inputPerMillion: 5229.57999, imageInputPerMillion: 10459.15998, outputPerMillion: 31377.47994 }), '约 64 积分/张', 'About 64 credits / image'],+ [model('image', { version: 'legacy', perRequest: 10 }), '约 10 积分/张', 'About 10 credits / image'],+ [model('speech', { version: 'v1', perMillionCharacters: 15688.735488 }), '约 16 积分/千字符', 'About 16 credits / 1,000 characters'],+ [model('speech', { version: 'v1', perMillionCharacters: 31377.470976 }), '约 31 积分/千字符', 'About 31 credits / 1,000 characters'],+ [model('speech', { version: 'legacy', perMinute: 20, perMillionCharacters: 4000 }), '约 21 积分/分钟', 'About 21 credits / minute'],+ [model('transcription', { version: 'v1', perMinute: 6.275494 }), '约 6 积分/分钟', 'About 6 credits / minute'],+ [video, '约 37 积分/秒 · 720p', 'About 37 credits/second · 720p'],+] as const)('uses the requested billing unit for %j', (value, chinese, english) => {+ expect(officialModelPrice(value, zh)).toBe(chinese);+ expect(officialModelPrice(value, en)).toBe(english);+});++it('quotes each video second at a supported resolution independently of clip duration', () => {+ expect(officialModelPriceDescription(video, zh)).toContain('720p:约 37 积分/秒');+ const fallback = { ...video, durations: [4, 6], resolutions: ['1080p'], aspectRatios: ['9:16'] };+ expect(officialModelPrice(fallback, zh)).toBe('约 45 积分/秒 · 1080p');+ expect(officialModelPriceDescription(fallback, zh)).toContain('1080p:约 45 积分/秒');+ expect(officialModelPrice({ ...video, durations: [] }, zh)).toBe(officialModelPrice(video, zh));+});++it('retains the workload assumptions and actual tariffs in price descriptions', () => {+ const text = model('text', { version: 'v1', inputPerMillion: 2091.83, cachedInputPerMillion: 104.59, cacheWritePerMillion: 2614.79, outputPerMillion: 10459.16 });+ expect(officialModelPriceDescription(text, zh)).toContain('按上游实际输入、输出');+ expect(officialModelPriceDescription(text, zh)).toContain('缓存输入 105');+ expect(officialModelPriceDescription(text, zh)).toContain('缓存写入 2615');+ expect(officialModelPriceDescription(model('transcription', { version: 'v1', perMinute: 6.275494 }), zh)).toContain('不足一分钟按比例扣积分');+});++it('does not present audio-only estimates for token-priced speech', () => {+ const speech = model('speech', { version: 'v1', inputPerMillion: 14343.986732, perMinute: 17.929983 });+ expect(officialModelPrice(speech, zh)).toBe('暂无法估算');+ expect(officialModelPriceDescription(speech, zh)).toContain('文本输入 14344 积分/百万 token + 18 积分/分钟');+});++it('keeps integer rates and never substitutes a fixed text call or video clip price', () => {+ expect(officialModelPrice(model('text', { version: 'v1', inputPerMillion: 1499.9996, outputPerMillion: 0.0001 }), zh)).toBe('输入 1500 / 输出 <1 积分/百万 token');+ expect(officialModelPrice(model('text', { version: 'v1', inputPerMillion: 150, outputPerMillion: 600 }), zh)).toBe('输入 150 / 输出 600 积分/百万 token');+ expect(officialModelPrice(video, zh)).not.toContain('积分/段');+});++it('does not guess missing or invalid model prices', () => {+ expect(officialModelPrice({ ...video, price: undefined }, zh)).toBe('');+ for (const value of [model('image', { version: 'v1', billing: 'usage', outputPerMillion: 100 }), model('speech', { version: 'v1', perMillionCharacters: NaN })]) {+ expect(officialModelPrice(value, zh)).toBe('暂无法估算');+ }+ expect(officialModelPrice({ ...video, resolutions: [] }, zh)).toBe('价格暂不可用');+});diff --git a/apps/web/src/components/forms/official-model-pricing.ts b/apps/web/src/components/forms/official-model-pricing.tsnew file mode 100644index 00000000..eddb70e4--- /dev/null+++ b/apps/web/src/components/forms/official-model-pricing.ts@@ -0,0 +1,90 @@+import type { GatewayModel } from '@opencreator/protocol';+import type { LocalizeCopy } from '../../i18n/useLocalizedCopy.js';+import { formatGatewayCreditAmount } from '../../features/account/billing-display.js';++const million = 1_000_000;+const positive = (value: number | undefined): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0;++// Keep workload assumptions aligned with the website credit calculator.+const assumptions = { imageInput: 200, imageOutput: 2000, speechCharacters: 1000, speechCharactersPerMinute: 300 };++function videoRate(model: GatewayModel) {+ const rates = model.price?.videoUnitsPerSecond;+ const resolutions = model.resolutions?.filter(resolution => Number.isSafeInteger(rates?.[resolution]) && positive(rates?.[resolution])) ?? [];+ if (!resolutions.length) return undefined;+ const resolution = resolutions.includes('720p') ? '720p' : resolutions[0]!;+ return { resolution, credits: rates![resolution]! / million };+}++function modelEstimate(model: GatewayModel, l: LocalizeCopy) {+ const p = model.price;+ if (!p) return undefined;+ const estimate = (credits: number, unit: string, description: string) => ({ credits: Math.round(credits * million) / million, unit, description });+ switch (model.modality) {+ case 'image':+ if (p.billing === 'usage') {+ if (!positive(p.inputPerMillion) || !positive(p.outputPerMillion)) return undefined;+ return estimate((p.inputPerMillion * assumptions.imageInput + p.outputPerMillion * assumptions.imageOutput) / million,+ l('积分/张', 'credits / image'), l('每张图片按 200 个文本输入 tokens、2,000 个图像输出 tokens 估算,无参考图;实际按 tokens 结算。', 'Per image: 200 text input tokens and 2,000 image output tokens, without a reference image. Actual usage is billed by tokens.'));+ }+ return positive(p.perRequest) ? estimate(p.perRequest, l('积分/张', 'credits / image'), l('按一次纯文生图请求、生成一张图片估算,无参考图。', 'One text-to-image request producing one image, without a reference image.')) : undefined;+ case 'speech':+ if (p.inputPerMillion !== undefined || p.outputPerMillion !== undefined) return undefined;+ if (positive(p.perMinute)) {+ const characters = p.perMillionCharacters ?? 0;+ if (!Number.isFinite(characters) || characters < 0) return undefined;+ return estimate(p.perMinute + characters * assumptions.speechCharactersPerMinute / million,+ l('积分/分钟', 'credits / minute'), l(`按生成 60 秒音频${characters > 0 ? '、输入 300 个字符' : ''}估算;实际按模型计费单位结算。`, `Estimated for 60 seconds of generated audio${characters > 0 ? ' and 300 input characters' : ''}. Actual usage settles in the model's billing units.`));+ }+ return positive(p.perMillionCharacters) ? estimate(p.perMillionCharacters * assumptions.speechCharacters / million,+ l('积分/千字符', 'credits / 1,000 characters'), l('按 1,000 个输入字符估算,实际按字符数结算;音频时长取决于语言和语速。', 'Estimated for 1,000 input characters, billed by actual character count. Audio duration varies with language and speaking speed.')) : undefined;+ case 'transcription':+ if (p.inputPerMillion !== undefined || p.outputPerMillion !== undefined || !positive(p.perMinute)) return undefined;+ return estimate(p.perMinute, l('积分/分钟', 'credits / minute'), l('按 60 秒音频、一次转录估算;按实际音频秒数结算,不足一分钟按比例扣积分。', 'Estimated for 60 seconds of audio and one transcription pass. Actual audio seconds are billed proportionally, including partial minutes.'));+ }+}++export function officialModelPrice(model: GatewayModel, l: LocalizeCopy): string {+ if (!model.price) return '';+ const p = model.price;+ if (model.modality === 'text') {+ if (!positive(p.inputPerMillion) || !positive(p.outputPerMillion)) return l('价格暂不可用', 'Price unavailable');+ return l(`输入 ${formatGatewayCreditAmount(p.inputPerMillion)} / 输出 ${formatGatewayCreditAmount(p.outputPerMillion)} 积分/百万 token`, `Input ${formatGatewayCreditAmount(p.inputPerMillion)} / output ${formatGatewayCreditAmount(p.outputPerMillion)} credits/M tokens`);+ }+ if (model.modality === 'video') {+ const rate = videoRate(model);+ return rate ? l(`约 ${formatGatewayCreditAmount(rate.credits)} 积分/秒 · ${rate.resolution}`, `About ${formatGatewayCreditAmount(rate.credits)} credits/second · ${rate.resolution}`) : l('价格暂不可用', 'Price unavailable');+ }+ const estimate = modelEstimate(model, l);+ return estimate ? l(`约 ${formatGatewayCreditAmount(estimate.credits)} ${estimate.unit}`, `About ${formatGatewayCreditAmount(estimate.credits)} ${estimate.unit}`) : l('暂无法估算', 'Estimate unavailable');+}++export function officialModelPriceDescription(model: GatewayModel, l: LocalizeCopy): string {+ const description = model.modality === 'text'+ ? l('按上游实际输入、输出及适用的缓存 token 用量结算;长上下文和分时费率按请求适用规则计算。显示单价取整,扣费保留内部精度。', 'Billed by actual upstream input, output and applicable cache token usage, with context tiers and time-based rates applied per request. Displayed rates are rounded; settlement retains internal precision.')+ : model.modality === 'video'+ ? l('按所选分辨率的每秒费率乘以请求时长结算。显示单价取整,扣费保留内部精度。', 'Billed at the per-second rate for the selected resolution multiplied by the requested duration. Displayed rates are rounded; settlement retains internal precision.')+ : modelEstimate(model, l)?.description;+ return [description, officialModelTariff(model, l)].filter(Boolean).join('\n');+}++function officialModelTariff(model: GatewayModel, l: LocalizeCopy): string {+ const p = model.price;+ if (!p) return '';+ const amount = formatGatewayCreditAmount;+ if (model.modality === 'video') return (model.resolutions ?? []).filter(resolution => positive(p.videoUnitsPerSecond?.[resolution])).map(resolution => l(`${resolution}:约 ${amount(p.videoUnitsPerSecond![resolution]! / million)} 积分/秒`, `${resolution}: about ${amount(p.videoUnitsPerSecond![resolution]! / million)} credits/second`)).join('\n');+ if (positive(p.perRequest)) return l(`${amount(p.perRequest)} 积分/次`, `${amount(p.perRequest)} credits/request`);+ if (model.modality === 'image' && p.billing === 'usage') return l(`文本输入 ${amount(p.inputPerMillion)} / 图片输入 ${amount(p.imageInputPerMillion)} / 输出 ${amount(p.outputPerMillion)} 积分/百万 token`, `Text ${amount(p.inputPerMillion)} / image ${amount(p.imageInputPerMillion)} in / output ${amount(p.outputPerMillion)} credits/M tokens`);+ const components: string[] = [];+ if (model.modality === 'speech' || model.modality === 'transcription') {+ if (p.inputPerMillion !== undefined) components.push(model.modality === 'speech' ? l(`文本输入 ${amount(p.inputPerMillion)} 积分/百万 token`, `Text input ${amount(p.inputPerMillion)} credits/M tokens`) : l(`输入 ${amount(p.inputPerMillion)} 积分/百万 token`, `Input ${amount(p.inputPerMillion)} credits/M tokens`));+ if (p.outputPerMillion !== undefined) components.push(l(`输出 ${amount(p.outputPerMillion)} 积分/百万 token`, `Output ${amount(p.outputPerMillion)} credits/M tokens`));+ if (positive(p.perMinute)) components.push(l(`${amount(p.perMinute)} 积分/分钟`, `${amount(p.perMinute)} credits/min`));+ if (positive(p.perMillionCharacters)) components.push(l(`${amount(p.perMillionCharacters)} 积分/百万字符`, `${amount(p.perMillionCharacters)} credits/M characters`));+ return components.join(' + ');+ }+ if (p.inputPerMillion !== undefined && p.outputPerMillion !== undefined) components.push(l(`输入 ${amount(p.inputPerMillion)} / 输出 ${amount(p.outputPerMillion)} 积分/百万 token`, `${amount(p.inputPerMillion)} in / ${amount(p.outputPerMillion)} out credits/M tokens`));+ if (p.cachedInputPerMillion !== undefined) components.push(l(`缓存输入 ${amount(p.cachedInputPerMillion)}`, `${amount(p.cachedInputPerMillion)} cached input`));+ if (p.cacheWritePerMillion !== undefined) components.push(l(`缓存写入 ${amount(p.cacheWritePerMillion)}`, `${amount(p.cacheWritePerMillion)} cache write`));+ return components.join(' · ');+}diff --git a/apps/web/src/features/account/PersonalCenterPage.test.tsx b/apps/web/src/features/account/PersonalCenterPage.test.tsxindex d1fd3af1..ce21dfca 100644--- a/apps/web/src/features/account/PersonalCenterPage.test.tsx+++ b/apps/web/src/features/account/PersonalCenterPage.test.tsx@@ -56,6 +56,14 @@ it('shows account and credits and returns to the previous view', async () => {await userEvent.setup().click(screen.getByRole('button', { name: '返回' }));expect(back).toHaveBeenCalledOnce();});+it('forwards active task state to the credit estimate and hides it when work ends', async () => {+ const service = createService();+ vi.mocked(service.getSummary).mockResolvedValue({ ...summary, balance: { ...summary.balance, reservedUnits: '1000000' } });+ const view = render(<LanguageProvider initialPreference="zh-CN"><PersonalCenterPage service={service} accountState={signedIn} hasActiveTasks onBack={vi.fn()} /></LanguageProvider>);+ expect(await screen.findByText('预估消耗', { exact: true })).toBeInTheDocument();+ view.rerender(<LanguageProvider initialPreference="zh-CN"><PersonalCenterPage service={service} accountState={signedIn} hasActiveTasks={false} onBack={vi.fn()} /></LanguageProvider>);+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+});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' }; });diff --git a/apps/web/src/features/account/PersonalCenterPage.tsx b/apps/web/src/features/account/PersonalCenterPage.tsxindex 325fc6a6..007a3c1b 100644--- a/apps/web/src/features/account/PersonalCenterPage.tsx+++ b/apps/web/src/features/account/PersonalCenterPage.tsx@@ -14,6 +14,7 @@ export default function PersonalCenterPage(props: {view?: 'account' | 'subscription';service: GatewayAccountSettingsService | null;accountState?: GatewayAccountState;+ hasActiveTasks?: boolean;billingOrderId?: string;billingReturnUrl?: string;prepareExternalNavigation?(): ExternalNavigation;@@ -62,6 +63,7 @@ export default function PersonalCenterPage(props: {<GatewaySubscriptionSettingsViewkey={`${state?.authState}:${state?.account?.id ?? ''}`}service={props.service} embedded accountState={state} openExternal={props.openExternal}+ hasActiveTasks={props.hasActiveTasks}billingOrderId={props.billingOrderId} billingReturnUrl={props.billingReturnUrl}prepareExternalNavigation={props.prepareExternalNavigation}onRequestSignIn={() => setSignInRequest(value => value + 1)}diff --git a/apps/web/src/features/account/credits.css b/apps/web/src/features/account/credits.cssindex f3f50e42..ccd82cf8 100644--- a/apps/web/src/features/account/credits.css+++ b/apps/web/src/features/account/credits.css@@ -11,6 +11,10 @@.account-credits__balance h2 { font-size: 13px; font-weight: 500; color: var(--muted); }.account-credits__value { margin: 8px 0 0; font-size: 30px; line-height: 1.3; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }.account-credits__value small { font-size: 12px; color: var(--muted); }+.account-credits__breakdown { display: flex; flex-wrap: wrap; gap: 8px 24px; margin: 12px 0 0; font-size: 12px; line-height: 1.6; }+.account-credits__breakdown > div { display: flex; flex-wrap: wrap; gap: 8px; min-width: 0; }+.account-credits__breakdown dt { color: var(--muted); }+.account-credits__breakdown dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }.account-credits__actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }.credit-muted { color: var(--muted); font-size: 12px; line-height: 1.6; margin: 8px 0 0; }.credit-notice { margin: 0 0 18px; padding: 10px 12px; border-left: 3px solid var(--border); background: var(--surface-2); color: var(--muted); font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }diff --git a/apps/web/src/features/account/credits.test.tsx b/apps/web/src/features/account/credits.test.tsxindex 0760d947..37e2e876 100644--- a/apps/web/src/features/account/credits.test.tsx+++ b/apps/web/src/features/account/credits.test.tsx@@ -1,4 +1,4 @@-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+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';@@ -16,10 +16,60 @@ function service(): GatewayAccountSettingsService {return { getState: vi.fn(async () => account), start: vi.fn(), cancel: vi.fn(), logout: vi.fn(), activate: vi.fn(), setSource: vi.fn(), selectModel: vi.fn(), getBalance: vi.fn(), getSummary: vi.fn(async () => summary),openWebAccount: vi.fn(async () => ({ url: handoff })), getPlans: vi.fn(), getOrders: vi.fn(async () => ({ items: [] })), getOrder: vi.fn(async () => ({ order })), getCreditGrants: vi.fn(), checkout: vi.fn(), portal: vi.fn() };}-function page(value: GatewayAccountSettingsService, openExternal = vi.fn(), state = account, billingOrderId?: string) {- return <LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} embedded accountState={state} openExternal={openExternal} billingOrderId={billingOrderId} billingReturnUrl="opencreator://billing/return"/></LanguageProvider>;+function page(value: GatewayAccountSettingsService, openExternal = vi.fn(), state = account, billingOrderId?: string, hasActiveTasks = false) {+ return <LanguageProvider initialPreference="zh-CN"><GatewaySubscriptionSettingsView service={value} embedded accountState={state} hasActiveTasks={hasActiveTasks} openExternal={openExternal} billingOrderId={billingOrderId} billingReturnUrl="opencreator://billing/return"/></LanguageProvider>;}+it('keeps reserved credits in the balance and changes it only when usage settles', async () => {+ const value = service();+ const snapshot = (availableUnits: string, reservedUnits: string) => ({ ...summary, balance: { ...summary.balance, availableUnits, reservedUnits } });+ vi.mocked(value.getSummary).mockResolvedValue(snapshot('2087231437', '0'));+ render(page(value, vi.fn(), account, undefined, true));+ expect(await screen.findByText('2087')).toBeInTheDocument();+ const available = () => screen.getByText('可用积分').closest('div')!;+ const reserved = () => screen.getByText('预估消耗', { exact: true }).closest('div')!;+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+ expect(screen.queryByText('可用积分')).not.toBeInTheDocument();+ expect(screen.queryByText(/多余部分自动解冻/)).not.toBeInTheDocument();+ vi.mocked(value.getSummary).mockResolvedValue(snapshot('1325135419', '762096018'));+ await userEvent.setup().click(screen.getByRole('button', { name: '刷新积分' }));+ expect(screen.getByText('2087')).toBeInTheDocument();+ expect(within(available()).getByText('1325 积分')).toBeInTheDocument();+ expect(within(reserved()).getByText('762 积分')).toBeInTheDocument();+ expect(screen.queryByText(/已冻结|账户积分包含冻结部分|多余部分自动解冻/)).not.toBeInTheDocument();+ vi.mocked(value.getSummary).mockResolvedValue(snapshot('1937558807', '0'));+ await userEvent.setup().click(screen.getByRole('button', { name: '刷新积分' }));+ expect(screen.getByText('1938')).toBeInTheDocument();+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+ expect(screen.queryByText('可用积分')).not.toBeInTheDocument();+ expect(screen.queryByText(/多余部分自动解冻/)).not.toBeInTheDocument();+});++it.each([+ [true, '0'], [true, '1'], [true, '500000'], [true, '999999'],+ [false, '1000000'], [false, '762096018']+] as const)('hides the estimate when tasks are inactive or the reservation is below one credit (%s, %s)', async (hasActiveTasks, reservedUnits) => {+ const value = service();+ vi.mocked(value.getSummary).mockResolvedValue({ ...summary, balance: { ...summary.balance, availableUnits: '1860000000', reservedUnits } });+ render(page(value, vi.fn(), account, undefined, hasActiveTasks));+ await waitFor(() => expect(screen.getByRole('button', { name: '刷新积分' })).toBeEnabled());+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+ expect(screen.queryByText('可用积分')).not.toBeInTheDocument();+});++it('shows an estimate from one credit only while a task is active', async () => {+ const value = service();+ vi.mocked(value.getSummary).mockResolvedValue({ ...summary, balance: { ...summary.balance, reservedUnits: '1000000' } });+ const view = render(page(value));+ expect(await screen.findByText('415')).toBeInTheDocument();+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+ view.rerender(page(value, vi.fn(), account, undefined, true));+ expect(within(screen.getByText('预估消耗', { exact: true }).closest('div')!).getByText('1 积分')).toBeInTheDocument();+ view.rerender(page(value));+ expect(screen.queryByText('预估消耗', { exact: true })).not.toBeInTheDocument();+ expect(screen.getByText('415')).toBeInTheDocument();+});+it('opens the website through a one-time account handoff without an app checkout', async () => {const value = service(); const open = vi.fn(); render(page(value, open));expect(await screen.findByText('414')).toBeInTheDocument();diff --git a/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsxindex 031f1dc8..9c533607 100644--- a/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx+++ b/apps/web/src/features/settings/GatewaySubscriptionSettingsView.tsx@@ -27,6 +27,7 @@ export function GatewaySubscriptionSettingsView(props: {service: GatewayAccountSettingsService | null;embedded?: boolean;accountState?: GatewayAccountState;+ hasActiveTasks?: boolean;billingOrderId?: string;billingReturnUrl?: string;prepareExternalNavigation?(): ExternalNavigation;@@ -55,6 +56,8 @@ export function GatewaySubscriptionSettingsView(props: {const service = props.service;const summary = summaryResult?.service === service && summaryResult.accountId === accountId ? summaryResult.value: accountId ? service?.getCachedSummary?.(accountId) : undefined;+ const totalUnits = summary ? (BigInt(summary.balance.availableUnits) + BigInt(summary.balance.reservedUnits)).toString() : undefined;+ const showEstimatedUsage = props.hasActiveTasks === true && summary !== undefined && BigInt(summary.balance.reservedUnits) >= 1_000_000n;const plansURL = creditPlansURL(summary?.plansUrl, language);function setSummary(value?: GatewayBillingSummary) {@@ -169,9 +172,13 @@ export function GatewaySubscriptionSettingsView(props: {return <section className="account-credits" aria-label={l('积分与充值', 'Credits')}>{!props.embedded ? <GatewayAccountSettingsView service={service} variant="login" signInRequest={signInRequest} openExternal={props.openExternal} onStateChange={value => { setState(value); props.onStateChange?.(value); }}/> : null}<div className="account-credits__balance">- <div><h2>{l('可用积分', 'Available credits')}</h2>- {accountId ? <p className="account-credits__value">{summary ? formatGatewayCredits(summary.balance.availableUnits) : '--'} <small>{l('积分', 'credits')}</small></p>+ <div><h2>{l('账户积分', 'Credit balance')}</h2>+ {accountId ? <p className="account-credits__value">{totalUnits ? formatGatewayCredits(totalUnits) : '--'} <small>{l('积分', 'credits')}</small></p>: <p className="credit-muted">{l('登录后查看积分', 'Sign in to view your credits')}</p>}+ {summary && showEstimatedUsage ? <dl className="account-credits__breakdown">+ <div><dt>{l('可用积分', 'Available credits')}</dt><dd>{`${formatGatewayCredits(summary.balance.availableUnits)} ${l('积分', 'credits')}`}</dd></div>+ <div><dt>{l('预估消耗', 'Estimated usage')}</dt><dd>{`${formatGatewayCredits(summary.balance.reservedUnits)} ${l('积分', 'credits')}`}</dd></div>+ </dl> : null}{accountId && !summary && refreshing ? <p className="credit-loading" role="status"><LoaderCircle size={14}/>{l('正在加载积分', 'Loading credits')}</p> : null}{summary && (refreshing || balanceError) ? <p className="credit-muted">{l('上次更新', 'Last updated')} {new Date(summary.balance.asOf).toLocaleString(language)}</p> : null}</div>diff --git a/apps/web/src/features/settings/OfficialServicesSettingsView.tsx b/apps/web/src/features/settings/OfficialServicesSettingsView.tsxindex fc63ee59..62c75e40 100644--- a/apps/web/src/features/settings/OfficialServicesSettingsView.tsx+++ b/apps/web/src/features/settings/OfficialServicesSettingsView.tsx@@ -3,7 +3,8 @@ import { AudioLines, Image, LoaderCircle, Mic, RefreshCw, TextCursorInput, Videoimport { gatewayModelCompatible, gatewayModelSupports, gatewayModelReady, type GatewayAccountState, type GatewayModelPurpose } from '@opencreator/protocol';import type { GatewayAccountSettingsService } from '../../services/gateway-account-service.js';import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';-import OfficialModelSelect, { officialModelPrice } from '../../components/forms/OfficialModelSelect.js';+import OfficialModelSelect from '../../components/forms/OfficialModelSelect.js';+import { officialModelPrice, officialModelPriceDescription } from '../../components/forms/official-model-pricing.js';import { ApiClientError } from '../../runtime/errors.js';import './official-services-settings.css';@@ -75,7 +76,7 @@ export function OfficialServicesSettingsView(props: { state: GatewayAccountState<span className="official-services-model-count" id={`official-${modality.id}-count`}>{models.some(gatewayModelReady)? l(`${models.filter(gatewayModelReady).length} 个可用模型`, `${models.filter(gatewayModelReady).length} available models`): l('暂不可用', 'Unavailable')}</span>- {selectedModel?.price ? <span className="official-model-availability">{officialModelPrice(selectedModel, l)}</span> : null}+ {selectedModel?.price ? <span className="official-model-availability" title={officialModelPriceDescription(selectedModel, l)}>{officialModelPrice(selectedModel, l)}</span> : null}{selected && (!selectedModel || !gatewayModelReady(selectedModel)) ? <span className="official-model-availability">{l('暂不可用,请选择其他模型', 'Unavailable; select another model')}</span> : null}</span></span><span className="official-services-model-select">diff --git a/docs/operations/opencreator-desktop-release-runbook.md b/docs/operations/opencreator-desktop-release-runbook.mdindex 0a7fb3f3..efdd4167 100644--- a/docs/operations/opencreator-desktop-release-runbook.md+++ b/docs/operations/opencreator-desktop-release-runbook.md@@ -46,13 +46,15 @@ Desktop 使用 `resources/icon.png` 作为各平台统一的应用图标源。ma1. 更新 `apps/desktop/package.json` 的版本。2. 确认 GitHub Release 发布权限、签名凭据和目标版本更新元数据流程可用。3. 先推送版本提交到 `master`,等待同一提交的 CI 通过,再从 `master` 手动运行 `.github/workflows/desktop-release.yml`,并选择 `target=all`。CI 会把纯发布基础设施改动分流到 release checks;产品改动并行执行 unit、compile 和 Web/Desktop parity。-4. 完整候选工作流使用 `macos-15-intel`、`macos-15` 和 `windows-latest` 并行构建三个原生目标平台,任一 matrix job 失败会自动取消 sibling jobs。macOS 使用正式 Developer ID 签名和 Apple 公证。macOS arm64 运行完整 packaged App E2E;macOS x64 和 Windows x64 运行真实 App smoke 与平台能力套件。单平台运行只用于诊断,不能用于正式发布。+4. 完整候选工作流使用 `macos-15-intel`、`macos-15` 和 `windows-latest` 并行构建三个原生目标平台,任一 matrix job 失败会自动取消 sibling jobs。macOS 使用正式 Developer ID 签名和 Apple 公证。完整功能回归在本机对待发布提交完成;远端三个平台统一运行 `e2e:package:smoke`,验证刚生成的真实 App、内嵌 Runtime 和平台能力,不重复 macOS arm64 的完整 packaged App E2E。单平台运行只用于诊断,不能用于正式发布。5. 三个平台和 Linux KrillinAI 附件全部成功后,工作流计算排除发布专用文件的应用构建输入 SHA-256,并写入绑定该指纹、Git commit、workflow run 和仓库的候选身份凭据。候选附件保存于该 workflow run,不允许构建后替换。6. 候选全绿后才创建并推送 `v<version>` Git tag。标签版本必须与 `apps/desktop/package.json` 完全一致。通常 tag 指向候选 commit;候选后只有发布基础设施变化且应用构建输入 SHA-256 不变时,可以复用原候选。7. tag 工作流不再重复构建、签名、公证或 E2E;它按应用构建输入 SHA-256 查找成功的 `target=all` 候选,并确认候选 commit 是 tag commit 的祖先。任何 App、Runtime、依赖或打包输入变化都会产生不同指纹并要求新候选。随后工作流复核 run 与候选身份凭据,下载已验证附件,校验附件白名单并发布 GitHub Release。CI 变更分类始终以最近一次成功的 `master` push CI 为基线,而不是只比较直接父提交。这样,失败的产品提交后即使只修复 workflow,也必须重新执行完整 CI,不会被 release-only 快速路径掩盖。+候选构建在依赖安装前恢复缓存,并通过 `ELECTRON_CACHE` 让安装脚本复用 Electron 下载;新增 Chromium 下载缓存,工具和 Codex 下载缓存允许按平台与架构回退复用。Codex 归档仍须通过固定 integrity 校验,Creator Runtime 下载保持精确缓存键。Daemon/Web、Creator Runtime 与 Codex Runtime 独立并行准备。Remotion 组件公证与主应用打包并行,但全部成功后才允许生成可交付产物清单;App 和 DMG 的签名、公证、Web 资源哈希及包完整性校验继续执行。上传已压缩的发布附件时关闭 Artifact 二次压缩。+示例:```bashdiff --git a/packages/protocol/src/gateway-account.ts b/packages/protocol/src/gateway-account.tsindex 264c7196..820c62cb 100644--- a/packages/protocol/src/gateway-account.ts+++ b/packages/protocol/src/gateway-account.ts@@ -20,7 +20,7 @@ export type GatewayModel = {status?: 'ready' | 'temporarily_unavailable' | 'retired';statusReason?: string;recommended?: boolean;- price?: { version: string; inputPerMillion?: number; outputPerMillion?: number; perMinute?: number; perMillionCharacters?: number; perRequest?: number; videoUnitsPerSecond?: Record<string, number> };+ price?: { version: string; billing?: 'usage'; inputPerMillion?: number; cachedInputPerMillion?: number; cacheWritePerMillion?: number; imageInputPerMillion?: number; outputPerMillion?: number; perMinute?: number; perMillionCharacters?: number; perRequest?: number; videoUnitsPerSecond?: Record<string, number> };videoOptions?: {profile: string;maxImages: number; maxVideos: number; maxAudios: number;diff --git a/runtime/krillinai/docs/paired-subtitle-translation.md b/runtime/krillinai/docs/paired-subtitle-translation.mdindex 7e029297..b51f556f 100644--- a/runtime/krillinai/docs/paired-subtitle-translation.md+++ b/runtime/krillinai/docs/paired-subtitle-translation.md@@ -6,7 +6,7 @@ YouTube 词级字幕、块级字幕、音频转录和原文 SRT 导入统一通输入先按 Unicode 句子边界组织语句,保留既有英文缩写例外。无标点或异常长句在模型调用前确定性拆分,优先 Unicode 词边界,没有自然边界的长词、URL才退到完整字素簇边界。单个输入片段最多 1024 个 UTF-8 字节,显示上限较小时进一步减小输入片段。这个预算与最终字幕显示上限分别控制。-相邻前后各两句作为上下文,每句上下文最多 256 字节,仅供理解,不输出到译文。批次同时限制句数、请求字节预算和预估响应预算,避免预拆之后再次形成超大请求。请求预算包含 Prompt、JSON、上下文和纠错预留;纠错反馈也限长。当前响应上限为 8192 token,预估响应预算为 6500,请求字节预算为 16000。它们是保守估算,不是针对所有模型的精确 tokenizer 或语义扩写上界。异常字素簇或无法满足预算的输入明确报错。+相邻前后各两句作为上下文,每句上下文最多 256 字节,仅供理解,不输出到译文。批次同时限制句数、请求字节预算和预估响应预算,避免预拆之后再次形成超大请求。请求预算包含 Prompt、JSON、上下文和纠错预留;纠错反馈也限长。响应按当前批次的预估输出加 1024 token 余量设置上限,最少 2048、最多 8192;确认截断后在原有三次输出尝试内翻倍扩大预算。未实现预算接口的翻译器保留原调用方式。预估响应预算为 6500,请求字节预算为 16000。它们是保守估算,不是针对所有模型的精确 tokenizer 或语义扩写上界。异常字素簇或无法满足预算的输入明确报错。VTT/SRT 文本读取允许单行最多 4 MiB,之后才进入上述模型输入保护,超过读取上限则明确失败。@@ -14,7 +14,7 @@ VTT/SRT 文本读取允许单行最多 4 MiB,之后才进入上述模型输入原文和译文每段分别满足 `max_sentence_length`,任意一侧超限都要增加成对字幕条数。两侧都放得下时要求保持一对;同一句内允许译文按目标语言习惯调整语序,原文只能顺序切分,完整覆盖检查忽略空白但保留其他字符。-超过原文显示上限的输入附带 `source_segments_hint`,由本地按词及字素边界生成,参考片段均不超限且完整覆盖原文。末尾两段优先选择较均衡的词边界或标点边界,减少孤立短尾句。模型优先采用该参考,也可以为译文长度和语义对应调整边界;最终原译分段仍由同一次回答给出,并进行双侧校验。参考数据计入请求预算。+超过原文显示上限的输入附带 `source_segments_hint`,由本地按词及字素边界生成,参考片段均不超限且完整覆盖原文。末尾两段优先标点及从句边界,避免悬空主语,长度均衡作为次要参考。提示词明确该参考仅证明长度可行,模型应主动按完整意群调整边界;最终原译分段仍由同一次回答给出,并进行双侧校验。参考数据计入请求预算。长度采用字素簇近似显示单位:宽字符或全角字符簇计2,其他基础字素簇计1,组合符、连接符和方向控制符不重复计宽,空格也计入上限。使用 `github.com/clipperhouse/uax29/v2` 的 Unicode 字素、词和句子边界,不按 UTF-8 字节或单个 rune 强行截断。50单位约为25个汉字,包含中文标点;该计数不等同于实际字体的像素宽度。@@ -24,6 +24,8 @@ VTT/SRT 文本读取允许单行最多 4 MiB,之后才进入上述模型输入撤销模型多余切分时,必须两侧完整文本都满足长度上限,并能确认译文边界如何连接;无法确定是否为词内切分时保留原配对,避免引入或删除词间空格。+撤销多余切分后,本地检查明确的中英文悬空主语:英文代词与常见助动词被拆开,或中文逗号后仅有一个人称代词留在上一段。仅在把主语移到下一段仍满足上限时要求模型纠错;不额外增加常规审校调用。此规则不是完整语法分析,其他语义边界和语言仍依赖模型判断。+结构校验失败后附具体问题和上一轮结果,整批最多三次输出纠错。429和5xx使用独立的 `translate_max_attempts` 退避预算,支持取消,不消耗结构纠错次数。失败明确报错,不回填源文冒充译文。并发窗口全部成功后才按原顺序提交检查点。DeepSeek V4 的 `deepseek-flash`、`deepseek-v4-flash` 和 `deepseek-v4-pro` 使用 `temperature=0.2`,减少结构和分段的随机变化,并发送 `reasoning_effort=none`,避免推理耗尽字幕 JSON 的输出预算;实测其低强度推理也可能耗尽预算。其他模型保留默认采样,不附加这些参数。接口返回 `finish_reason=length` 时明确报 `llm_translation_truncated`,不把被截断的内容当成完整译文或普通空响应。diff --git a/runtime/krillinai/internal/service/paired_translation.go b/runtime/krillinai/internal/service/paired_translation.goindex 8547bd58..d71c5eba 100644--- a/runtime/krillinai/internal/service/paired_translation.go+++ b/runtime/krillinai/internal/service/paired_translation.go@@ -85,6 +85,14 @@ const (translationOutputBudget = 6500 // 为 8192 token 响应留出 JSON 和纠错余量。)+type budgetedChatCompleter interface {+ ChatCompletionContextWithMaxTokens(context.Context, string, int) (string, error)+}++func pairedTranslationResponseBudget(text string, limit int) int {+ return 4*len(text) + (3*subtitleTargetLength(text)/limit+1)*48+}+func buildPairedTranslationBatches(texts []string, originLang, targetLang types.StandardLanguageCode, limit, batchSize int) ([]pairedTranslationInput, error) {var batches []pairedTranslationInputfor start := 0; start < len(texts); {@@ -115,7 +123,7 @@ func buildPairedTranslationBatches(texts []string, originLang, targetLang types.source.After = append(source.After, parts[0])}}- estimate := 4*len(texts[i]) + (3*subtitleTargetLength(texts[i])/limit+1)*48+ estimate := pairedTranslationResponseBudget(texts[i], limit)input.Sentences = append(input.Sentences, source)payload, err := json.Marshal(input)if err != nil {@@ -216,12 +224,22 @@ func (t *Translator) translatePairedSentences(ctx context.Context, texts []strinprompt := basePromptvar batch []pairedSentencerequestFailures := 0+ maxTokens := 1024+ for _, sentence := range input.Sentences {+ maxTokens += pairedTranslationResponseBudget(sentence.Text, limit)+ }+ maxTokens = min(8192, max(2048, maxTokens))+ budgeted, supportsBudget := t.chatCompleter.(budgetedChatCompleter)for attempt := 0; attempt < 3; {if err = ctx.Err(); err != nil {return nil, err}var response string- response, err = chatCompletionWithContext(ctx, t.chatCompleter, prompt)+ if supportsBudget {+ response, err = budgeted.ChatCompletionContextWithMaxTokens(ctx, prompt, maxTokens)+ } else {+ response, err = chatCompletionWithContext(ctx, t.chatCompleter, prompt)+ }if ctx.Err() != nil {return nil, ctx.Err()}@@ -240,6 +258,11 @@ func (t *Translator) translatePairedSentences(ctx context.Context, texts []strincontinue}attempt+++ if supportsBudget && err != nil && strings.Contains(err.Error(), "llm_translation_truncated") && maxTokens < 8192 {+ maxTokens = min(8192, maxTokens*2)+ log.GetLogger().Warn("字幕翻译响应截断,增加输出预算后重试", zap.Int("max_tokens", maxTokens), zap.Int("attempt", attempt))+ continue+ }if err == nil {batch, err = t.parsePairedTranslation(response, input, originLang, targetLang)if err == nil {@@ -384,6 +407,17 @@ func (t *Translator) parsePairedTranslation(response string, input pairedTranslaresult[i].Target = []string{target}}}+ for _, sentence := range result {+ for j := 0; j+1 < len(sentence.Source); j++ {+ if subtitleBoundarySplitsSubject(sentence.Source[j], sentence.Source[j+1], input.MaxTargetChars) ||+ subtitleBoundarySplitsSubject(sentence.Target[j], sentence.Target[j+1], input.MaxTargetChars) {+ issues = append(issues, fmt.Errorf("句子%s第%d与%d段拆开了主语和谓语;请将悬在上一段末尾的主语移到下一段,并同步调整原译配对。优先完整意群,不要为了均衡长度保留生硬边界", sentence.ID, j+1, j+2))+ }+ }+ }+ if len(issues) > 0 {+ return nil, errors.Join(issues...)+ }return result, nil}diff --git a/runtime/krillinai/internal/service/paired_translation_prompt.txt b/runtime/krillinai/internal/service/paired_translation_prompt.txtindex f48a9014..62ccf298 100644--- a/runtime/krillinai/internal/service/paired_translation_prompt.txt+++ b/runtime/krillinai/internal/service/paired_translation_prompt.txt@@ -9,7 +9,7 @@5. 每段禁止实际换行、Unicode 换行控制符、字面量反斜杠加 N 或 n 等会被字幕解释为换行的转义。禁止通过 ASS 标签或 HTML 标签插入换行。保留 Emoji连接序列、重音组合和语言的书写方向。6. 短小但有实际含义的词也必须保留,包括独立 Yes/No、转折词和 may/might。um、uh 等用于演示卡壳、犹豫或引语时具有实际意义,译文必须体现。上下文仅供理解,不翻译进结果。7. 输入可能已为模型预算切成相邻片段,结合 context_before/context_after 理解,但只输出当前 text。检查每个 sentence_id 按输入顺序恰好出现一次、每条字幕两侧均有实际内容且不超限、字素边界安全、原文和完整译文均覆盖后返回。-8. source_segments_hint 是本地按词边界生成、每段已满足原文长度上限的参考分段。优先直接采用这些原文片段并生成等量译文;如果译文超限或需要改善语义对应,可继续细分或调整边界,但调整后的两侧仍须满足上限。参考分段不是额外内容,不要重复翻译。不要把多个参考片段合并成超长原文。+8. source_segments_hint 只是本地按词边界生成的长度可行性参考,不是必须采用的语义边界。先按完整意群确定原译配对,再参考它检查长度;发现生硬边界应主动调整。优先在标点、从句和完整短语之间停顿,不要为均衡字数拆开主语和谓语、修饰语和中心词、介词和宾语、助动词和主要动词。禁止将“而有意思的是,它 / 不只是……”或“that it / isn't …”作为分段,应将主语保留在下一段,如“And the interesting part is / that it isn't just a giant database of titles.”对应“而有意思的是,/ 它不只是一个庞大的书名数据库。”。两侧不必等长,完整语义优先于长度均衡,但都必须满足硬上限。参考分段不是额外内容,不要重复翻译。配对示例:整句译文“我们努力工作,因为我们在乎。”可以分成[{"source":"We work hard","target":"我们努力工作,"},{"source":"because we care.","target":"因为我们在乎。"}],拼接target仍是“我们努力工作,因为我们在乎。”。不能在target_text中写“因为我们在乎,所以我们努力工作。”后却沿用前述分段,否则语序和文字不一致。diff --git a/runtime/krillinai/internal/service/paired_translation_test.go b/runtime/krillinai/internal/service/paired_translation_test.goindex afe341ea..2fbdd83c 100644--- a/runtime/krillinai/internal/service/paired_translation_test.go+++ b/runtime/krillinai/internal/service/paired_translation_test.go@@ -405,6 +405,101 @@ func TestPairedSourceHintKeepsShortTailWithItsClause(t *testing.T) {}}+func TestPairedTranslationKeepsSubjectsWithPredicates(t *testing.T) {+ text := "And the interesting part is that it isn't just a giant database of titles."+ parts, err := splitSubtitleSourceHint(text, 70)+ if err != nil || len(parts) != 2 || parts[0] != "And the interesting part is" || parts[1] != "that it isn't just a giant database of titles." {+ t.Fatalf("参考分段应保留完整从句: %q %v", parts, err)+ }+ previous := config.Conf+ t.Cleanup(func() { config.Conf = previous })+ config.Conf.App.TranslateParallelNum = 1+ calls := 0+ translator := &Translator{chatCompleter: translationCompleterFunc(func(prompt string) (string, error) {+ calls+++ source, target := []string{"And the interesting part is that it", "isn't just a giant database of titles."}, []string{"而有意思的是,它", "不只是一个庞大的书名数据库。"}+ if calls > 1 {+ if !strings.Contains(prompt, "拆开了主语和谓语") {+ t.Error("纠错请求必须说明语义边界问题")+ }+ source, target = parts, []string{"而有意思的是,", "它不只是一个庞大的书名数据库。"}+ }+ response, err := encodePairedTestResponse([]pairedSentence{{ID: "1", FullTarget: "而有意思的是,它不只是一个庞大的书名数据库。", Source: source, Target: target}})+ return string(response), err+ })}+ result, err := translator.translatePairedSentences(context.Background(), []string{text}, "en", "zh_cn", 70, 1, nil)+ if err != nil || calls != 2 || len(result) != 1 || result[0].Target[0] != "而有意思的是," {+ t.Fatalf("不自然的分段应被纠正: calls=%d result=%+v err=%v", calls, result, err)+ }+}++func TestSubtitleSubjectBoundaryGuardIsConservative(t *testing.T) {+ for _, tc := range []struct {+ left, right string+ limit int+ want bool+ }{+ {"And that it", "isn't just a database.", 70, true},+ {"而有意思的是,它", "不只是一个数据库。", 70, true},+ {"但接下来,我们", "会继续探索。", 70, true},+ {"it", "is", 2, false},+ {"I", "can do it.", 70, false},+ {"We discussed it.", "Isn't it great?", 70, false},+ {"I spoke to him", "yesterday.", 70, false},+ {"这是它", "的名字。", 70, false},+ {"他说:他", "不是那个已经离开的人。", 10, false},+ } {+ if got := subtitleBoundarySplitsSubject(tc.left, tc.right, tc.limit); got != tc.want {+ t.Errorf("%q / %q: got %v want %v", tc.left, tc.right, got, tc.want)+ }+ }+}++func TestPairedTranslationMergesShortSentenceBeforeCheckingSubjectBoundary(t *testing.T) {+ input := pairedTranslationInput{MaxTargetChars: 70, Sentences: []pairedTranslationSource{{ID: "1", Text: "We know that it isn't a database."}}}+ response, _ := encodePairedTestResponse([]pairedSentence{{ID: "1", FullTarget: "我们知道,它不是数据库。", Source: []string{"We know that it", "isn't a database."}, Target: []string{"我们知道,它", "不是数据库。"}}})+ result, err := (&Translator{}).parsePairedTranslation(string(response), input, "en", "zh_cn")+ if err != nil || len(result) != 1 || len(result[0].Source) != 1 || result[0].Target[0] != "我们知道,它不是数据库。" {+ t.Fatalf("可直接合并的短句不应触发额外模型请求: %+v %v", result, err)+ }+}++type budgetedTranslationTestCompleter struct {+ translationCompleterFunc+ complete func(context.Context, string, int) (string, error)+}++func (c budgetedTranslationTestCompleter) ChatCompletionContextWithMaxTokens(ctx context.Context, prompt string, limit int) (string, error) {+ return c.complete(ctx, prompt, limit)+}++func TestPairedTranslationOutputBudgetGrowsOnlyAfterTruncation(t *testing.T) {+ previous := config.Conf+ t.Cleanup(func() { config.Conf = previous })+ config.Conf.App.TranslateParallelNum = 1+ for _, truncate := range []bool{false, true} {+ var budgets []int+ translator := &Translator{chatCompleter: budgetedTranslationTestCompleter{complete: func(ctx context.Context, prompt string, limit int) (string, error) {+ budgets = append(budgets, limit)+ if truncate && len(budgets) < 3 {+ return "", fmt.Errorf("llm_translation_truncated: output budget exhausted")+ }+ input, err := decodePairedTestInput(prompt)+ if err != nil {+ return "", err+ }+ return echoPairedTestResponse(input)+ }}}+ _, err := translator.translatePairedSentences(context.Background(), []string{"Hello."}, "en", "zh_cn", 70, 1, nil)+ if err != nil || len(budgets) == 0 || budgets[0] != 2048 {+ t.Fatalf("小批次应使用较小的输出预算: budgets=%v err=%v", budgets, err)+ }+ if truncate && (len(budgets) != 3 || budgets[1] != 4096 || budgets[2] != 8192) || !truncate && len(budgets) != 1 {+ t.Fatalf("截断后应在原重试次数内逐步增加预算: %v", budgets)+ }+ }+}+func TestSubtitleTargetLengthUsesWeightedCharacters(t *testing.T) {for _, tc := range []struct {text stringdiff --git a/runtime/krillinai/internal/service/subtitle_text.go b/runtime/krillinai/internal/service/subtitle_text.goindex 9f6a991e..42b5db3d 100644--- a/runtime/krillinai/internal/service/subtitle_text.go+++ b/runtime/krillinai/internal/service/subtitle_text.go@@ -131,7 +131,21 @@ func splitSubtitleSourceHint(text string, limit int) ([]string, error) {score := max(leftSize, rightSize) - min(leftSize, rightSize)last, _ := utf8.DecodeLastRuneInString(left)if unicode.IsPunct(last) && min(leftSize, rightSize)*4 >= leftSize+rightSize {- score -= limit / 2+ score -= limit+ }+ if subtitleBoundarySplitsSubject(left, right, limit) {+ score += limit * 2+ }+ leftWords, rightWords := strings.Fields(strings.ToLower(left)), strings.Fields(strings.ToLower(right))+ if len(leftWords) > 0 && len(rightWords) > 0 {+ switch leftWords[len(leftWords)-1] {+ case "that", "because", "although", "unless", "whereas":+ score += limit+ }+ switch rightWords[0] {+ case "that", "because", "although", "unless", "whereas":+ score -= limit / 2+ }}if score < bestScore && subtitleSegmentsHaveSafeBoundaries([]string{left, right}) {bestCut, bestScore = cut, score@@ -144,6 +158,37 @@ func splitSubtitleSourceHint(text string, limit int) ([]string, error) {return parts, nil}+// Only flag clear dangling subjects when moving them can still satisfy the limit.+func subtitleBoundarySplitsSubject(left, right string, limit int) bool {+ left, right = strings.TrimSpace(left), strings.TrimSpace(right)+ fields := strings.Fields(left)+ if len(fields) > 1 {+ subject := fields[len(fields)-1]+ switch strings.ToLower(subject) {+ case "i", "you", "he", "she", "it", "we", "they":+ following := strings.Fields(strings.ToLower(right))+ if len(following) > 0 {+ predicate := strings.ReplaceAll(following[0], "’", "'")+ switch predicate {+ case "am", "is", "are", "was", "were", "isn't", "aren't", "wasn't", "weren't", "has", "have", "had", "hasn't", "haven't", "hadn't", "do", "does", "did", "don't", "doesn't", "didn't", "can", "could", "cannot", "can't", "couldn't", "will", "would", "won't", "wouldn't", "should", "shouldn't", "may", "might", "must", "mustn't":+ return subtitleTargetLength(subject+" "+right) <= limit+ }+ }+ }+ }+ for _, subject := range []string{"我", "你", "您", "他", "她", "它", "我们", "你们", "他们", "她们", "它们"} {+ prefix, found := strings.CutSuffix(left, subject)+ if !found || !hasSubtitleContent(prefix) {+ continue+ }+ last, _ := utf8.DecodeLastRuneInString(strings.TrimSpace(prefix))+ if strings.ContainsRune(",,;;::", last) && subtitleTargetLength(subject+right) <= limit {+ return true+ }+ }+ return false+}+func subtitleTextPreview(text string, maxBytes int) string {if len(text) <= maxBytes {return textdiff --git a/runtime/krillinai/pkg/openai/openai.go b/runtime/krillinai/pkg/openai/openai.goindex 17989b54..d5b348d4 100644--- a/runtime/krillinai/pkg/openai/openai.go+++ b/runtime/krillinai/pkg/openai/openai.go@@ -17,6 +17,13 @@ func (c *Client) ChatCompletion(query string) (string, error) {}func (c *Client) ChatCompletionContext(ctx context.Context, query string) (string, error) {+ return c.ChatCompletionContextWithMaxTokens(ctx, query, 8192)+}++func (c *Client) ChatCompletionContextWithMaxTokens(ctx context.Context, query string, maxTokens int) (string, error) {+ if maxTokens < 1 || maxTokens > 8192 {+ return "", fmt.Errorf("llm_translation_invalid_budget: output token budget must be between 1 and 8192")+ }if c.requestTimeout > 0 {var cancel context.CancelFuncctx, cancel = context.WithTimeout(ctx, c.requestTimeout)@@ -36,7 +43,7 @@ func (c *Client) ChatCompletionContext(ctx context.Context, query string) (strinContent: query,},},- MaxTokens: 8192,+ MaxTokens: maxTokens,ResponseFormat: responseFormat,}// DeepSeek V4 的推理可能耗尽字幕 JSON 的输出预算。diff --git a/runtime/krillinai/pkg/openai/openai_test.go b/runtime/krillinai/pkg/openai/openai_test.goindex 3ed88740..6c826ddf 100644--- a/runtime/krillinai/pkg/openai/openai_test.go+++ b/runtime/krillinai/pkg/openai/openai_test.go@@ -34,6 +34,30 @@ func TestChatCompletionReceivesCompleteJSON(t *testing.T) {}}+func TestChatCompletionSendsRequestedOutputBudget(t *testing.T) {+ setTestModel(t)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var request struct {+ MaxTokens int `json:"max_tokens"`+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.MaxTokens != 2048 {+ t.Errorf("输出预算未传给供应商: %d %v", request.MaxTokens, err)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"你好。"}}]}`))+ }))+ defer server.Close()+ client := newClient(server.URL, "test-key", "", time.Second)+ if text, err := client.ChatCompletionContextWithMaxTokens(context.Background(), "translate", 2048); err != nil || text != "你好。" {+ t.Fatalf("text=%q err=%v", text, err)+ }+ for _, budget := range []int{0, -1, 8193} {+ if _, err := client.ChatCompletionContextWithMaxTokens(context.Background(), "translate", budget); err == nil {+ t.Fatalf("无效预算被接受: %d", budget)+ }+ }+}+func TestChatCompletionRejectsEmptyResponse(t *testing.T) {setTestModel(t)server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {