Skip to content

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.

fix: harden Creator runtime builds and translation recovery

Leggettc99412f19d39
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml
index 1673b633..ca90cb3a 100644
--- a/.github/workflows/desktop-release.yml
+++ b/.github/workflows/desktop-release.yml
@@ -236,7 +236,7 @@ jobs:
with:
path: |
.runtime/build/krillinai/${{ matrix.platform }}-${{ matrix.arch }}
- key: krillinai-build-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('scripts/build-krillinai.mjs', 'scripts/download-go-modules.mjs', 'runtime/krillinai/**') }}
+ key: krillinai-build-${{ runner.os }}-${{ matrix.arch }}-${{ hashFiles('scripts/build-krillinai.mjs', 'scripts/download-go-modules.mjs', 'scripts/krillinai-build-contract.mjs', 'runtime/krillinai/**') }}
- run: pnpm install --frozen-lockfile
- name: 生成 macOS 正式签名安装包
if: matrix.platform == 'darwin'
diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.ts
index db612484..0e039a27 100644
--- a/apps/daemon/src/api/routes.creator.ts
+++ b/apps/daemon/src/api/routes.creator.ts
@@ -782,7 +782,7 @@ export async function registerCreatorRoutes(
stage.status === 'queued' || stage.status === 'running'
));
if (activeStages.length === 0) {
- const latest = job.stages.at(-1);
+ const latest = jobControlStage(job);
if (latest?.status === 'canceled') {
return {
job,
@@ -796,15 +796,15 @@ export async function registerCreatorRoutes(
);
}
const stages = options.stageRunner.cancelJob(id);
- const stage = stages.at(-1);
+ const latestJob = requireCreatorJob(service, id);
+ const stage = jobControlStage(latestJob);
if (stage === undefined) {
throw new CreatorServiceError(
'creator_job_not_running',
'Creator job has no active stage'
);
}
- const latestJob = requireCreatorJob(service, id);
- const canceling = stage.status === 'queued' || stage.status === 'running';
+ const canceling = stages.some(candidate => candidate.status === 'queued' || candidate.status === 'running');
return reply.code(canceling ? 202 : 200).send({
job: latestJob,
stage,
@@ -826,7 +826,7 @@ export async function registerCreatorRoutes(
);
}
let job = requireCreatorJob(service, id);
- const latest = job.stages.at(-1);
+ const latest = jobControlStage(job);
if (job.templateId === 'video-download' && latest) {
const live = options.stageRunner.resumeDownload(latest.id);
if (live) return { job: requireCreatorJob(service, id), stage: live, control: 'resumed' };
@@ -882,19 +882,29 @@ export async function registerCreatorRoutes(
}
job = requireCreatorJob(service, id);
}
- const target = job.stages.at(-1);
+ job = requireCreatorJob(service, id);
+ const target = jobControlStage(job);
+ if (target?.progress.resumedFromStageRunId === latest.id && isAlreadyResumed(job, target)) {
+ return { job, stage: target, control: 'resumed' };
+ }
if (target?.id !== latest.id || (target.status !== 'canceled' && target.status !== 'interrupted')) {
throw new CreatorServiceError(
'creator_job_not_resumable',
'Creator job state changed before it could be resumed'
);
}
+ // Only a stored workflow download may be resumed through system dispatch.
+ const backgroundSourceDownload = job.templateId === 'video-translation'
+ && target.progress.backgroundSourceDownload === true;
const result = options.dispatcher.dispatch(id, {
action: 'run-stage',
expectedRevision: job.revision,
idempotencyKey: `resume:${target.id}`,
input: {
stageId: target.stageId,
+ ...(backgroundSourceDownload
+ ? { backgroundSourceDownload: true }
+ : {}),
...(typeof target.progress.baseResultVersion === 'number'
? { baseResultVersion: target.progress.baseResultVersion }
: {}),
@@ -912,7 +922,7 @@ export async function registerCreatorRoutes(
: {}),
resumedFromStageRunId: target.id
}
- }, 'user', {
+ }, backgroundSourceDownload ? 'system' : 'user', {
scopeKey: target.scopeKey,
inputFingerprint: target.inputFingerprint,
resumedFromStageRunId: target.id,
@@ -1685,6 +1695,16 @@ function latestStageMatching(
return [...job.stages].reverse().find(predicate);
}
+function jobControlStage(job: CreatorJob): CreatorStageRun | undefined {
+ if (job.templateId !== 'video-translation') return job.stages.at(-1);
+ const foreground = latestStageMatching(job, stage => stage.progress.backgroundSourceDownload !== true);
+ if (foreground === undefined || foreground.status !== 'succeeded') return foreground ?? job.stages.at(-1);
+ // A completed subtitle stage may still be waiting for its parallel media download.
+ // Never let that download hide a stopped foreground stage or an ensuing render.
+ return latestStageMatching(job, stage => stage.progress.backgroundSourceDownload === true
+ && stage.progress.workflowParentStageRunId === foreground.id) ?? foreground;
+}
+
function isAlreadyResumed(job: CreatorJob, latest: CreatorStageRun): boolean {
if (
latest.status === 'canceled'
diff --git a/apps/daemon/src/creator/krillin/manifest.ts b/apps/daemon/src/creator/krillin/manifest.ts
index 870c8e82..03bd0914 100644
--- a/apps/daemon/src/creator/krillin/manifest.ts
+++ b/apps/daemon/src/creator/krillin/manifest.ts
@@ -63,6 +63,14 @@ const manifestSchema = z.object({
cliVersion: z.string().min(1).optional(),
sourceCommit: z.string().min(1).optional(),
sourceSha256: z.string().regex(/^[a-f0-9]{64}$/i).optional(),
+ krillinBuild: z.object({
+ buildRecipeSha256: z.string().regex(/^[a-f0-9]{64}$/i),
+ cliSha256: z.string().regex(/^[a-f0-9]{64}$/i)
+ }).strict().optional(),
+ cliSigning: z.object({
+ unsignedSha256: z.string().regex(/^[a-f0-9]{64}$/i),
+ signedSha256: z.string().regex(/^[a-f0-9]{64}$/i)
+ }).strict().optional(),
integrationPatchSha256: z.string().regex(/^[a-f0-9]{64}$/i).optional(),
platform: z.string().min(1),
arch: z.string().min(1),
diff --git a/apps/daemon/test/integration/creator-api.test.ts b/apps/daemon/test/integration/creator-api.test.ts
index 7bfb9600..86db3132 100644
--- a/apps/daemon/test/integration/creator-api.test.ts
+++ b/apps/daemon/test/integration/creator-api.test.ts
@@ -251,8 +251,11 @@ describe('creator api', () => {
expect((await request('GET', `/creator/jobs/${jobWithFiles.id}`)).statusCode).toBe(404);
});
- it('stops an active translation stage and resumes the workflow from that stage', async () => {
+ it.each(['failed', 'succeeded', 'running'] as const)('stops and resumes translation when its parallel download is %s', async downloadStatus => {
let subtitleRuns = 0;
+ let downloadRuns = 0;
+ let releaseResume!: () => void;
+ const resumeGate = new Promise<void>(resolve => { releaseResume = resolve; });
const executor: CreatorExecutor = {
id: 'krillinai',
async run({ stageRun, signal }) {
@@ -265,6 +268,7 @@ describe('creator api', () => {
});
return { outputs: [] };
}
+ await Promise.race([resumeGate, new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }))]);
return {
outputs: [
{ kind: 'source_video', status: 'completed', path: null },
@@ -281,7 +285,18 @@ describe('creator api', () => {
};
}
};
- await setupServer({ creatorExecutors: [executor] });
+ await setupServer({ creatorExecutors: [executor, {
+ id: 'download', async run({ signal }) {
+ if (downloadStatus === 'failed') throw new Error('Source download unavailable');
+ if (downloadStatus === 'running' && ++downloadRuns === 1) {
+ await new Promise<void>(resolve => {
+ if (signal.aborted) resolve();
+ else signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ }
+ return { outputs: [] };
+ }
+ }] });
const created = await request('POST', '/creator/jobs', {
projectId: 'project_job_control',
templateId: 'video-translation',
@@ -290,7 +305,6 @@ describe('creator api', () => {
sourceType: 'url',
sourceUrl: 'https://www.youtube.com/watch?v=job-control',
targetLanguage: 'zh_cn',
- skipVideoDownload: true,
composeVideo: true,
videoFormat: 'horizontal'
}
@@ -305,9 +319,10 @@ describe('creator api', () => {
expect(started.statusCode).toBe(200);
const running = await waitForCreatorJob(job.id, candidate => (
- candidate.stages.at(-1)?.status === 'running'
+ candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'subtitle' && stage.status === 'running')
+ && candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'preview-source-video' && stage.status === downloadStatus)
));
- const canceledStageId = running.stages.at(-1).id;
+ const canceledStageId = running.stages.find((stage: { stageId: string }) => stage.stageId === 'subtitle').id;
const canceled = await request('POST', `/creator/jobs/${job.id}/cancel`);
expect(canceled.statusCode).toBe(202);
expect(canceled.json()).toMatchObject({
@@ -320,7 +335,8 @@ describe('creator api', () => {
const stopped = await waitForCreatorJob(job.id, candidate => (
candidate.status === 'canceled'
- && candidate.stages.at(-1)?.status === 'canceled'
+ && candidate.stages.find((stage: { id: string }) => stage.id === canceledStageId)?.status === 'canceled'
+ && candidate.stages.every((stage: { status: string }) => !['queued', 'running'].includes(stage.status))
));
expect(stopped.artifacts).toEqual([]);
const repeatedCancel = await request('POST', `/creator/jobs/${job.id}/cancel`);
@@ -330,8 +346,13 @@ describe('creator api', () => {
stage: { id: canceledStageId, status: 'canceled' }
});
- const resumed = await request('POST', `/creator/jobs/${job.id}/resume`);
- expect(resumed.statusCode).toBe(202);
+ const resumeResponses = await Promise.all([
+ request('POST', `/creator/jobs/${job.id}/resume`),
+ request('POST', `/creator/jobs/${job.id}/resume`)
+ ]);
+ expect(resumeResponses.map(response => response.statusCode).sort()).toEqual([200, 202]);
+ const resumed = resumeResponses.find(response => response.statusCode === 202)!;
+ expect(resumeResponses[0].json().stage.id).toBe(resumeResponses[1].json().stage.id);
expect(resumed.json()).toMatchObject({
control: 'resumed',
stage: {
@@ -343,24 +364,64 @@ describe('creator api', () => {
}
});
+ releaseResume();
const completed = await waitForCreatorJob(job.id, candidate => (
candidate.status === 'completed'
&& candidate.stages.at(-1)?.stageId === 'render-horizontal'
&& candidate.stages.at(-1)?.status === 'succeeded'
));
- expect(completed.stages.map((stage: { stageId: string; status: string }) => (
+ expect(completed.stages.filter((stage: { stageId: string }) => stage.stageId !== 'preview-source-video').map((stage: { stageId: string; status: string }) => (
`${stage.stageId}:${stage.status}`
))).toEqual([
'subtitle:canceled',
'subtitle:succeeded',
'render-horizontal:succeeded'
]);
- expect(completed.stages[1]).toMatchObject({
+ expect(completed.stages.find((stage: { id: string }) => stage.id === resumed.json().stage.id)).toMatchObject({
progress: {
workflow: true,
resumedFromStageRunId: canceledStageId
}
});
+ expect(subtitleRuns).toBe(2);
+ expect((await request('POST', `/creator/jobs/${job.id}/resume`)).statusCode).toBe(409);
+ });
+
+ it('resumes only the canceled source download after subtitles have completed', async () => {
+ let downloadRuns = 0;
+ const translationStages: string[] = [];
+ await setupServer({ creatorExecutors: [{ id: 'krillinai', async run({ stageRun }) {
+ translationStages.push(stageRun.stageId);
+ return { outputs: [{ kind: stageRun.stageId === 'subtitle' ? 'target_subtitle' : 'horizontal_video', status: 'completed', path: null }] };
+ } }, { id: 'download', async run({ signal }) {
+ if (++downloadRuns === 1) {
+ await new Promise<void>(resolve => {
+ if (signal.aborted) resolve();
+ else signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ return { outputs: [] };
+ }
+ return { outputs: [{ kind: 'source_video', status: 'completed', path: null }] };
+ } }] });
+ const { job } = (await request('POST', '/creator/jobs', { projectId: 'project_download_resume', templateId: 'video-translation', state: {
+ sourceType: 'url', sourceUrl: 'https://youtu.be/download-resume', composeVideo: true, videoFormat: 'horizontal'
+ } })).json();
+ await request('POST', `/creator/jobs/${job.id}/actions`, { action: 'run-stage', expectedRevision: job.revision,
+ idempotencyKey: 'start-download-resume', input: { stageId: 'subtitle', workflow: true } });
+ const waiting = await waitForCreatorJob(job.id, candidate => candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'subtitle' && stage.status === 'succeeded')
+ && candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'preview-source-video' && stage.status === 'running'));
+ const download = waiting.stages.find((stage: { stageId: string }) => stage.stageId === 'preview-source-video');
+ expect((await request('POST', `/creator/jobs/${job.id}/cancel`)).statusCode).toBe(202);
+ await waitForCreatorJob(job.id, candidate => candidate.stages.find((stage: { id: string }) => stage.id === download.id)?.status === 'canceled');
+ const resumed = await request('POST', `/creator/jobs/${job.id}/resume`);
+ expect(resumed.statusCode).toBe(202);
+ expect(resumed.json().stage).toMatchObject({ stageId: 'preview-source-video', progress: {
+ backgroundSourceDownload: true, workflowParentStageRunId: download.progress.workflowParentStageRunId, resumedFromStageRunId: download.id
+ } });
+ await waitForCreatorJob(job.id, candidate => candidate.stages.some((stage: { stageId: string; status: string }) => stage.stageId === 'render-horizontal' && stage.status === 'succeeded'));
+ expect(translationStages).toEqual(['subtitle', 'render-horizontal']);
+ expect(downloadRuns).toBe(2);
+ expect((await request('POST', `/creator/jobs/${job.id}/resume`)).statusCode).toBe(409);
});
it('replays creator job creation after the response is lost', async () => {
diff --git a/apps/daemon/test/unit/creator-krillin-manifest.test.ts b/apps/daemon/test/unit/creator-krillin-manifest.test.ts
index 5a935d6b..0ca139a0 100644
--- a/apps/daemon/test/unit/creator-krillin-manifest.test.ts
+++ b/apps/daemon/test/unit/creator-krillin-manifest.test.ts
@@ -22,6 +22,34 @@ afterEach(() => {
});
describe('Krillin Runtime 清单校验', () => {
+ it.each([false, true])('accepts build provenance from a packaged runtime (signed: %s)', signed => {
+ const fixture = createFixture();
+ const path = join(fixture.root, 'manifest.json');
+ const manifest = JSON.parse(readFileSync(path, 'utf8'));
+ const cliSha256 = manifest.resources[0].sha256;
+ manifest.krillinBuild = { buildRecipeSha256: 'a'.repeat(64), cliSha256 };
+ if (signed) manifest.cliSigning = { unsignedSha256: 'b'.repeat(64), signedSha256: cliSha256 };
+ writeFileSync(path, JSON.stringify(manifest));
+
+ const parsed = readKrillinRuntimeManifest(fixture.root);
+ expect(parsed.krillinBuild).toEqual(manifest.krillinBuild);
+ expect(parsed.cliSigning).toEqual(manifest.cliSigning);
+ expect(verifyKrillinRuntimeManifest(fixture.root, parsed)).toEqual({ cacheHit: false });
+ writeFileSync(fixture.executable, 'tampered-runtime');
+ expect(() => verifyKrillinRuntimeManifest(fixture.root, parsed)).toThrow('dependency_hash_mismatch');
+ });
+
+ it.each([
+ { krillinBuild: { buildRecipeSha256: 'invalid', cliSha256: 'a'.repeat(64) } },
+ { cliSigning: { unsignedSha256: 'a'.repeat(64), signedSha256: 'invalid' } },
+ { unknownMetadata: true }
+ ])('rejects malformed or unknown manifest metadata (%j)', metadata => {
+ const fixture = createFixture();
+ const path = join(fixture.root, 'manifest.json');
+ writeFileSync(path, JSON.stringify({ ...JSON.parse(readFileSync(path, 'utf8')), ...metadata }));
+ expect(() => readKrillinRuntimeManifest(fixture.root)).toThrow();
+ });
+
it('缓存完整校验结果,并在资源变化时拒绝缓存', () => {
const fixture = createFixture();
const manifest = readKrillinRuntimeManifest(fixture.root);
diff --git a/apps/desktop/e2e/creator-packaged-app.spec.ts b/apps/desktop/e2e/creator-packaged-app.spec.ts
index 2b90464f..ec85f38f 100644
--- a/apps/desktop/e2e/creator-packaged-app.spec.ts
+++ b/apps/desktop/e2e/creator-packaged-app.spec.ts
@@ -44,6 +44,43 @@ async function selectChoice(control: Locator, value: string) {
await control.page().getByRole('option').and(control.page().locator(`[data-value="${value}"]`)).click();
}
+test('@package-smoke 内嵌翻译运行时可用,组件页显示 yt-dlp', async ({}, testInfo) => {
+ const fixture = await launchCreatorDesktop();
+ try {
+ await waitForWorkspace(fixture.app.page);
+ const status = await runtimeRequest<{ ytDlp: { source: string; currentVersion: string } }>(
+ fixture.app.page, 'GET', '/creator/yt-dlp/status');
+ expect(status.status, JSON.stringify(status.body)).toBe(200);
+ expect(status.body.ytDlp.source).toBe('bundled');
+
+ const projects = await runtimeRequest<{ projects: Array<{ id: string }> }>(
+ fixture.app.page, 'GET', '/projects?status=all');
+ const created = await runtimeRequest<{ job: { id: string } }>(
+ fixture.app.page, 'POST', '/creator/jobs', {
+ projectId: projects.body.projects[0]!.id, templateId: 'video-translation',
+ creationKey: 'packaged-runtime-preflight',
+ state: { sourceType: 'url', sourceUrl: 'https://www.youtube.com/watch?v=QaBOfzyj0tI',
+ sourceLanguage: 'en', targetLanguage: 'zh_cn', preferPlatformCaptions: true }
+ });
+ expect(created.status).toBe(201);
+ const preflight = await runtimeRequest<{ ready: Array<{ id: string }>; blocked: Array<{ id: string }> }>(
+ fixture.app.page, 'GET', `/creator/jobs/${created.body.job.id}/preflight?stageId=subtitle`);
+ expect(preflight.status, JSON.stringify(preflight.body)).toBe(200);
+ expect(preflight.body.ready.map(check => check.id)).toEqual(
+ expect.arrayContaining(['executor', 'ffmpeg', 'ffprobe', 'yt-dlp', 'krillin-runtime']));
+ expect(preflight.body.blocked.filter(check =>
+ ['executor', 'ffmpeg', 'ffprobe', 'yt-dlp', 'krillin-runtime'].includes(check.id))).toEqual([]);
+
+ await fixture.app.page.evaluate(() => { window.location.hash = '#/settings?tab=local-components'; });
+ await expect(fixture.app.page.getByRole('heading', { name: 'yt-dlp nightly' })).toBeVisible();
+ await expect(fixture.app.page.getByText(status.body.ytDlp.currentVersion, { exact: true }).first()).toBeVisible();
+ await fixture.app.page.screenshot({ path: testInfo.outputPath('runtime-components.png') });
+ } finally {
+ await closePackagedApp(fixture.app);
+ rmSync(fixture.root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ }
+});
+
test('Remotion 组件不随 App 内嵌,首次渲染按需下载后自动继续,更新不重复下载', async () => {
test.setTimeout(180_000);
const release = JSON.parse(readFileSync(join(desktopDir, '.pack', 'components', 'remotion-component.json'), 'utf8'));
diff --git a/apps/desktop/scripts/creator-runtime-build.mjs b/apps/desktop/scripts/creator-runtime-build.mjs
new file mode 100644
index 00000000..b199c7ec
--- /dev/null
+++ b/apps/desktop/scripts/creator-runtime-build.mjs
@@ -0,0 +1,39 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { hashKrillinFile, krillinBuildIdentity, verifyKrillinBuild } from '../../../scripts/krillinai-build-contract.mjs';
+import { verifyCreatorRuntime } from './creator-runtime-contract.mjs';
+
+const defaultRootDir = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
+
+// Package self-consistency alone cannot establish that a cached CLI is current.
+export function verifyCreatorRuntimeBuild(runtimeRoot, platform, arch, options = {}) {
+ const rootDir = options.rootDir ?? defaultRootDir;
+ const buildRoot = options.buildRoot ?? process.env.OPENCREATOR_KRILLINAI_BUILD_OUTPUT
+ ?? join(rootDir, '.runtime/build/krillinai', `${platform}-${arch}`);
+ const build = verifyKrillinBuild(buildRoot, krillinBuildIdentity({ rootDir, platform, arch }));
+ const runtime = JSON.parse(readFileSync(join(runtimeRoot, 'manifest.json'), 'utf8'));
+ const record = JSON.parse(readFileSync(join(runtimeRoot, 'build-record.json'), 'utf8'));
+ for (const metadata of [runtime, record]) {
+ if (metadata.cliVersion !== build.componentVersion
+ || metadata.sourceCommit !== build.sourceCommit
+ || metadata.sourceSha256 !== build.sourceSha256
+ || metadata.platform !== build.platform || metadata.arch !== build.arch
+ || metadata.krillinBuild?.buildRecipeSha256 !== build.buildRecipeSha256
+ || metadata.krillinBuild?.cliSha256 !== build.binaries['krillinai-cli'].sha256) {
+ throw new Error('Packaged KrillinAI CLI does not match the current source build; rebuild required');
+ }
+ }
+ verifyCreatorRuntime(runtimeRoot, platform, arch);
+ const cliSha256 = hashKrillinFile(join(runtimeRoot, 'bin', `krillinai-cli${platform === 'win32' ? '.exe' : ''}`));
+ if (runtime.cliSigning !== undefined) {
+ if (!options.allowSigned || platform !== 'darwin'
+ || runtime.cliSigning.unsignedSha256 !== build.binaries['krillinai-cli'].sha256
+ || runtime.cliSigning.signedSha256 !== cliSha256) {
+ throw new Error('Packaged KrillinAI CLI signing record does not match the current build');
+ }
+ } else if (cliSha256 !== build.binaries['krillinai-cli'].sha256) {
+ throw new Error('Packaged KrillinAI CLI binary hash mismatch with the current source build');
+ }
+ return runtime;
+}
diff --git a/apps/desktop/scripts/package-release.mjs b/apps/desktop/scripts/package-release.mjs
index b77e2954..ede22d32 100644
--- a/apps/desktop/scripts/package-release.mjs
+++ b/apps/desktop/scripts/package-release.mjs
@@ -29,6 +29,7 @@ import { runStapler, submitAndWaitForNotarization } from './apple-notarization.m
import { prepareElectronBuilderCache } from './electron-builder-cache.mjs';
import { runParallelStages, runStage } from './script-utils.mjs';
import { stageReleaseAssets } from './release-assets.mjs';
+import { verifyCreatorRuntimeBuild } from './creator-runtime-build.mjs';
import {
hashDirectory as hashStickmanDirectory,
hashFile as hashStickmanFile,
@@ -57,6 +58,9 @@ const cacheDir = resolve(
);
const env = {
...process.env,
+ OPENCREATOR_VERSION: JSON.parse(readFileSync(join(desktopDir, 'package.json'), 'utf8')).version,
+ OPENCREATOR_KRILLINAI_TARGET_PLATFORM: platform,
+ OPENCREATOR_KRILLINAI_TARGET_ARCH: arch,
OPENCREATOR_DESKTOP_TARGET_PLATFORM: platform,
OPENCREATOR_DESKTOP_TARGET_ARCH: arch,
OPENCREATOR_DESKTOP_CACHE_DIR: cacheDir,
@@ -104,6 +108,7 @@ await runParallelStages([
resolve(scriptDir, 'prepare-codex-runtime.mjs')
], { cwd: rootDir, env, timeoutMs: 10 * 60_000 })
]);
+verifyCreatorRuntimeBuild(resolve(desktopDir, '.pack/creator-runtime/krillinai'), platform, arch);
const candidates = packageRootCandidates(platform, arch);
for (const path of candidates) rmSync(path, { recursive: true, force: true });
@@ -166,10 +171,9 @@ const packageWithSigningEnvironment = async builderEnv => {
resolve(desktopDir, '.pack', 'codex-runtime', 'manifest.json'),
'utf8'
));
- const creatorRuntimeManifest = JSON.parse(readFileSync(
- resolve(desktopDir, '.pack', 'creator-runtime', 'krillinai', 'manifest.json'),
- 'utf8'
- ));
+ const creatorRuntimeManifest = verifyCreatorRuntimeBuild(
+ resolve(desktopDir, '.pack/creator-runtime/krillinai'), platform, arch
+ );
const stickmanRuntimeRoot = resolve(desktopDir, '.pack', 'stickman-runtime');
const stickmanRuntimeManifest = verifyStickmanRuntime(
stickmanRuntimeRoot,
@@ -265,6 +269,7 @@ const packageWithSigningEnvironment = async builderEnv => {
krillinCliVersion: creatorRuntimeManifest.cliVersion,
krillinSourceCommit: creatorRuntimeManifest.sourceCommit,
krillinSourceSha256: creatorRuntimeManifest.sourceSha256,
+ krillinBuild: creatorRuntimeManifest.krillinBuild,
krillinIntegrationPatchSha256: creatorRuntimeManifest.integrationPatchSha256,
ytDlpRuntimeMode: creatorRuntimeManifest.ytDlp?.mode,
ytDlpVersion: creatorRuntimeManifest.ytDlp?.version,
diff --git a/apps/desktop/scripts/prepare-creator-runtime.mjs b/apps/desktop/scripts/prepare-creator-runtime.mjs
index 86a76f11..3524d530 100644
--- a/apps/desktop/scripts/prepare-creator-runtime.mjs
+++ b/apps/desktop/scripts/prepare-creator-runtime.mjs
@@ -21,6 +21,8 @@ import * as fontkit from 'fontkit';
import { verifyRuntimeExecutable } from './runtime-executable-check.mjs';
import { stripMacNodeRuntime } from './prepare-creator-node.mjs';
import { creatorNlpLockPath, prepareCreatorNlpRuntime } from './creator-nlp-runtime.mjs';
+import { krillinBuildIdentity, verifyKrillinBuild } from '../../../scripts/krillinai-build-contract.mjs';
+import { verifyCreatorRuntimeBuild } from './creator-runtime-build.mjs';
const scriptDir = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(scriptDir, '..');
@@ -55,6 +57,10 @@ const vendorVersions = readVendorVersions();
const cliVersion = krillinBuild.componentVersion;
const sourceCommit = krillinBuild.sourceCommit;
const sourceSha256 = krillinBuild.sourceSha256;
+const krillinBuildRecord = {
+ buildRecipeSha256: krillinBuild.buildRecipeSha256,
+ cliSha256: krillinBuild.binaries['krillinai-cli'].sha256
+};
rmSync(outputRoot, { recursive: true, force: true });
mkdirSync(binDir, { recursive: true });
const subtitleFonts = prepareSubtitleFonts();
@@ -110,6 +116,7 @@ const buildRecord = {
cliVersion,
sourceCommit,
sourceSha256,
+ krillinBuild: krillinBuildRecord,
ytDlp: ytDlpRuntime.descriptor,
nlp: nlpRuntime.descriptor,
subtitleFonts: {
@@ -119,6 +126,8 @@ const buildRecord = {
integrationPatchSha256: hashFiles([
join(rootDir, 'scripts', 'build-krillinai.mjs'),
join(rootDir, 'scripts', 'download-go-modules.mjs'),
+ join(rootDir, 'scripts', 'krillinai-build-contract.mjs'),
+ join(scriptDir, 'creator-runtime-build.mjs'),
join(scriptDir, 'install-creator-runtime-dependencies.mjs'),
join(scriptDir, 'creator-runtime-releases.mjs'),
join(scriptDir, 'prepare-creator-runtime.mjs'),
@@ -155,6 +164,7 @@ const manifest = {
cliVersion,
sourceCommit,
sourceSha256,
+ krillinBuild: krillinBuildRecord,
integrationPatchSha256: buildRecord.integrationPatchSha256,
platform: targetPlatform,
arch: targetArch,
@@ -169,6 +179,7 @@ const manifest = {
}))
};
writeFileSync(join(outputRoot, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+verifyCreatorRuntimeBuild(outputRoot, targetPlatform, targetArch, { buildRoot: krillinBuildRoot });
console.log(JSON.stringify({ ok: true, outputRoot, resources: manifest.resources.length }));
function prepareSubtitleFonts() {
@@ -335,6 +346,9 @@ function ensureKrillinBuild() {
cwd: rootDir,
env: {
...process.env,
+ OPENCREATOR_VERSION: JSON.parse(readFileSync(join(desktopDir, 'package.json'), 'utf8')).version,
+ OPENCREATOR_KRILLINAI_TARGET_PLATFORM: targetPlatform,
+ OPENCREATOR_KRILLINAI_TARGET_ARCH: targetArch,
OPENCREATOR_DESKTOP_TARGET_PLATFORM: targetPlatform,
OPENCREATOR_DESKTOP_TARGET_ARCH: targetArch,
OPENCREATOR_KRILLINAI_BUILD_OUTPUT: krillinBuildRoot
@@ -344,29 +358,9 @@ function ensureKrillinBuild() {
}
function readKrillinBuildManifest() {
- const path = join(krillinBuildRoot, 'manifest.json');
- if (!existsSync(path)) {
- throw new Error(`KrillinAI build manifest is missing: ${path}`);
- }
- const manifest = JSON.parse(readFileSync(path, 'utf8'));
- const cli = manifest?.binaries?.['krillinai-cli'];
- const server = manifest?.binaries?.['krillinai-server'];
- if (
- manifest?.version !== 1
- || manifest.component !== 'opencreator-krillinai'
- || typeof manifest.componentVersion !== 'string'
- || typeof manifest.sourceCommit !== 'string'
- || !/^[a-f0-9]{64}$/i.test(manifest.sourceSha256 ?? '')
- || !/^[a-f0-9]{64}$/i.test(manifest.buildRecipeSha256 ?? '')
- || manifest.platform !== targetPlatform
- || manifest.arch !== targetArch
- || manifest.buildVcs !== false
- || typeof cli?.path !== 'string'
- || typeof server?.path !== 'string'
- ) {
- throw new Error('KrillinAI build manifest is invalid or targets another platform');
- }
- return manifest;
+ return verifyKrillinBuild(krillinBuildRoot, krillinBuildIdentity({
+ rootDir, platform: targetPlatform, arch: targetArch
+ }));
}
function ensureExternalDependencies() {
diff --git a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs
index b215131a..cda93f0c 100644
--- a/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs
+++ b/apps/desktop/scripts/sign-creator-runtime-after-pack.mjs
@@ -13,6 +13,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
import { verifyCreatorRuntime } from './creator-runtime-contract.mjs';
+import { verifyCreatorRuntimeBuild } from './creator-runtime-build.mjs';
import { verifyStickmanRuntime } from './stickman-runtime-contract.mjs';
import { findDeveloperIdIdentity, withMacSigningKeychain } from './mac-signing.mjs';
import { prepareMacAppIcon } from './mac-app-icon.mjs';
@@ -34,7 +35,12 @@ const remotionBrowserEntitlements = fileURLToPath(
export async function afterPack(context) {
await prepareMacAppIcon(context);
- if (process.env.OPENCREATOR_SIGN_CREATOR_RUNTIME !== '1') return;
+ if (process.env.OPENCREATOR_SIGN_CREATOR_RUNTIME !== '1') {
+ const arch = process.env.OPENCREATOR_DESKTOP_TARGET_ARCH
+ ?? ({ 1: 'x64', 3: 'arm64' }[context.arch]) ?? process.arch;
+ verifyCreatorRuntimeBuild(creatorRuntimeRoot(context), context.electronPlatformName, arch);
+ return;
+ }
await signDaemonRuntimeBundle(context);
await signCreatorRuntimeBundle(context);
}
@@ -100,12 +106,23 @@ export async function signDaemonRuntimeBundle(context, options = {}) {
}
export async function signCreatorRuntimeBundle(context, options = {}) {
- return signPackagedRuntime(context, options, {
+ const arch = (options.env ?? process.env).OPENCREATOR_DESKTOP_TARGET_ARCH;
+ const root = creatorRuntimeRoot(context);
+ verifyCreatorRuntimeBuild(root, 'darwin', arch, options);
+ await signPackagedRuntime(context, options, {
name: 'Creator Runtime',
relativeRoot: ['creator-runtime', 'krillinai'],
verifyRuntime: options.verifyRuntime ?? verifyCreatorRuntime,
javascriptEntitlements: remotionBrowserEntitlements
});
+ verifyCreatorRuntimeBuild(root, 'darwin', arch, { ...options, allowSigned: true });
+}
+
+function creatorRuntimeRoot(context) {
+ const resources = context.electronPlatformName === 'darwin'
+ ? join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources')
+ : join(context.appOutDir, 'resources');
+ return join(resources, 'creator-runtime', 'krillinai');
}
export async function signStickmanRuntimeBundle(context, options = {}) {
@@ -183,6 +200,16 @@ export function updateManifestHashes(runtimeRoot, signedPaths) {
const resources = new Map(
manifest.resources.map(resource => [resource.path, resource])
);
+ const cliPath = join(runtimeRoot, 'bin', 'krillinai-cli');
+ if (manifest.krillinBuild && signedPaths.some(path => resolve(path) === cliPath)) {
+ if (manifest.cliSigning || resources.get('bin/krillinai-cli')?.sha256 !== manifest.krillinBuild.cliSha256) {
+ throw new Error('KrillinAI CLI must match its unsigned source build before signing');
+ }
+ manifest.cliSigning = {
+ unsignedSha256: manifest.krillinBuild.cliSha256,
+ signedSha256: hashFile(cliPath)
+ };
+ }
for (const path of signedPaths) {
const relativePath = relative(runtimeRoot, path).replaceAll('\\', '/');
const resource = resources.get(relativePath);
diff --git a/apps/desktop/scripts/verify-package.mjs b/apps/desktop/scripts/verify-package.mjs
index 81d1d8e2..34f3ade5 100644
--- a/apps/desktop/scripts/verify-package.mjs
+++ b/apps/desktop/scripts/verify-package.mjs
@@ -28,9 +28,9 @@ import { createHash } from 'node:crypto';
import { homedir, tmpdir } from 'node:os';
import { basename, dirname, join, relative, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { treeSize } from './package-directory-size.mjs';
-import { verifyCreatorRuntime } from './creator-runtime-contract.mjs';
+import { verifyCreatorRuntimeBuild } from './creator-runtime-build.mjs';
import { verifyCreatorNlpRuntime } from './creator-nlp-runtime.mjs';
import { verifyCodexRuntime } from './codex-runtime-contract.mjs';
import {
@@ -116,7 +116,7 @@ await assertBrandingContents();
assertDaemonContents();
assertCreatorPresetContents();
assertWebContents();
-assertCreatorRuntime();
+await assertCreatorRuntime();
assertCreatorSubtitleFontContents();
assertCodexRuntime();
assertStickmanRuntime();
@@ -604,17 +604,26 @@ function normalizedAsarEntries() {
});
}
-function assertCreatorRuntime() {
- const runtime = verifyCreatorRuntime(creatorRuntimeDir, targetPlatform, targetArch);
+async function assertCreatorRuntime() {
+ const runtime = verifyCreatorRuntimeBuild(creatorRuntimeDir, targetPlatform, targetArch, {
+ allowSigned: manifest.macSigningMode === 'developer-id'
+ });
if (runtime.nlp === undefined) throw new Error('Packaged Creator Runtime is missing spaCy');
if (targetPlatform === process.platform && targetArch === process.arch) {
verifyCreatorNlpRuntime(resolve(creatorRuntimeDir, runtime.nlp.executable), runtime.nlp);
+ // Validate with the actual consumer as well as the packaging contract.
+ const { readKrillinRuntimeManifest } = await import(pathToFileURL(
+ join(daemonDir, 'dist', 'creator', 'krillin', 'manifest.js')
+ ).href);
+ readKrillinRuntimeManifest(creatorRuntimeDir);
}
if (typeof manifest.packageRoot !== 'string') return;
if (
manifest.krillinCliVersion !== runtime.cliVersion
|| manifest.krillinSourceCommit !== runtime.sourceCommit
|| manifest.krillinSourceSha256 !== runtime.sourceSha256
+ || manifest.krillinBuild?.buildRecipeSha256 !== runtime.krillinBuild.buildRecipeSha256
+ || manifest.krillinBuild?.cliSha256 !== runtime.krillinBuild.cliSha256
|| manifest.krillinIntegrationPatchSha256 !== runtime.integrationPatchSha256
|| manifest.ytDlpRuntimeMode !== runtime.ytDlp?.mode
|| manifest.ytDlpVersion !== runtime.ytDlp?.version
diff --git a/apps/desktop/test/creator-runtime-signing.test.mjs b/apps/desktop/test/creator-runtime-signing.test.mjs
index dc99c8cb..5d0c6185 100644
--- a/apps/desktop/test/creator-runtime-signing.test.mjs
+++ b/apps/desktop/test/creator-runtime-signing.test.mjs
@@ -10,6 +10,8 @@ import { tmpdir } from 'node:os';
import { dirname, join, relative } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { verifyCreatorRuntime } from '../scripts/creator-runtime-contract.mjs';
+import { verifyCreatorRuntimeBuild } from '../scripts/creator-runtime-build.mjs';
+import { createKrillinBuildFixture, runtimeBuildMetadata } from './helpers/krillinai-build.mjs';
import { verifyStickmanRuntime } from '../scripts/stickman-runtime-contract.mjs';
import {
signDaemonRuntimeBundle,
@@ -116,6 +118,7 @@ describe('Creator Runtime Developer ID signing', () => {
}
}
}, {
+ ...fixture.build,
env: {
OPENCREATOR_APPLE_TEAM_ID: 'NVRH5R5DJ5',
OPENCREATOR_DESKTOP_TARGET_ARCH: 'arm64'
@@ -144,6 +147,14 @@ describe('Creator Runtime Developer ID signing', () => {
join(fixture.runtimeRoot, 'manifest.json'),
'utf8'
));
+ expect(manifest.cliSigning).toEqual({
+ unsignedSha256: fixture.build.manifest.binaries['krillinai-cli'].sha256,
+ signedSha256: hashFile(fixture.binaryPaths[0])
+ });
+ expect(() => verifyCreatorRuntimeBuild(fixture.runtimeRoot, 'darwin', 'arm64', {
+ ...fixture.build, allowSigned: true
+ })).not.toThrow();
+ expect(() => verifyCreatorRuntimeBuild(fixture.runtimeRoot, 'darwin', 'arm64', fixture.build)).toThrow('signing record');
for (const path of fixture.binaryPaths) {
const relativePath = relative(fixture.runtimeRoot, path)
.replaceAll('\\', '/');
@@ -169,6 +180,7 @@ describe('Creator Runtime Developer ID signing', () => {
const fixture = createFixture({ javascriptRuntime: true });
const signBinary = vi.fn();
await signCreatorRuntimeBundle(createContext(fixture.appOutDir), {
+ ...fixture.build,
env: signingEnv(), findIdentity: () => 'Developer ID Application: Junxi YIN (NVRH5R5DJ5)',
findBinaries: () => fixture.binaryPaths, signBinary
});
@@ -265,6 +277,8 @@ function signingEnv() {
function createFixture(options = {}) {
const root = mkdtempSync(join(tmpdir(), 'opencreator-runtime-signing-'));
temporaryDirectories.push(root);
+ const build = createKrillinBuildFixture(root);
+ const metadata = runtimeBuildMetadata(build.manifest);
const appOutDir = join(root, 'mac-arm64');
const runtimeRoot = join(
appOutDir,
@@ -280,7 +294,7 @@ function createFixture(options = {}) {
'bin/ffprobe': 'ffprobe',
'bin/yt-dlp': 'yt-dlp',
...(options.javascriptRuntime ? { 'bin/node': 'node' } : {}),
- 'build-record.json': '{"version":1}',
+ 'build-record.json': JSON.stringify({ version: 1, ...metadata }),
'subtitle-style.json': '{"version":1}'
};
for (const [relativePath, contents] of Object.entries(files)) {
@@ -299,6 +313,7 @@ function createFixture(options = {}) {
cliVersion: 'test',
sourceCommit: 'test',
sourceSha256: 'b'.repeat(64),
+ ...metadata,
integrationPatchSha256: 'a'.repeat(64),
platform: 'darwin',
arch: 'arm64',
@@ -317,6 +332,7 @@ function createFixture(options = {}) {
`${JSON.stringify(manifest, null, 2)}\n`
);
return {
+ build,
appOutDir,
runtimeRoot,
binaryPaths: [
diff --git a/apps/desktop/test/helpers/krillinai-build.mjs b/apps/desktop/test/helpers/krillinai-build.mjs
new file mode 100644
index 00000000..e6ae192a
--- /dev/null
+++ b/apps/desktop/test/helpers/krillinai-build.mjs
@@ -0,0 +1,41 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { hashKrillinFile, krillinBuildIdentity } from '../../../../scripts/krillinai-build-contract.mjs';
+
+export function createKrillinBuildFixture(rootDir, options = {}) {
+ const platform = options.platform ?? 'darwin';
+ const arch = options.arch ?? 'arm64';
+ const buildRoot = join(rootDir, 'build');
+ const files = {
+ 'apps/desktop/package.json': JSON.stringify({ version: options.version ?? 'test' }),
+ 'scripts/build-krillinai.mjs': '// build recipe',
+ 'scripts/download-go-modules.mjs': '// module downloader',
+ 'scripts/krillinai-build-contract.mjs': '// build contract',
+ 'runtime/krillinai/main.go': 'package main\nfunc main() {}',
+ 'build/bin/krillinai-cli': 'krillin',
+ 'build/bin/krillinai-server': 'server',
+ 'build/artifacts/krillinai-cli': 'krillin',
+ 'build/artifacts/krillinai-server': 'server'
+ };
+ for (const [path, content] of Object.entries(files)) {
+ mkdirSync(dirname(join(rootDir, path)), { recursive: true });
+ writeFileSync(join(rootDir, path), content);
+ }
+ const manifest = {
+ version: 1, component: 'opencreator-krillinai', buildVcs: false,
+ ...krillinBuildIdentity({ rootDir, platform, arch }),
+ binaries: Object.fromEntries(['krillinai-cli', 'krillinai-server'].map(name => [name, {
+ path: `bin/${name}`, artifact: `artifacts/${name}`, sha256: hashKrillinFile(join(buildRoot, 'bin', name))
+ }]))
+ };
+ writeFileSync(join(buildRoot, 'manifest.json'), JSON.stringify(manifest));
+ return { rootDir, buildRoot, manifest };
+}
+
+export function runtimeBuildMetadata(build) {
+ return {
+ cliVersion: build.componentVersion, sourceCommit: build.sourceCommit, sourceSha256: build.sourceSha256,
+ platform: build.platform, arch: build.arch,
+ krillinBuild: { buildRecipeSha256: build.buildRecipeSha256, cliSha256: build.binaries['krillinai-cli'].sha256 }
+ };
+}
diff --git a/apps/desktop/test/krillinai-build-provenance.test.mjs b/apps/desktop/test/krillinai-build-provenance.test.mjs
new file mode 100644
index 00000000..c23597d5
--- /dev/null
+++ b/apps/desktop/test/krillinai-build-provenance.test.mjs
@@ -0,0 +1,128 @@
+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { hashKrillinFile, krillinBuildIdentity, verifyKrillinBuild } from '../../../scripts/krillinai-build-contract.mjs';
+import { verifyCreatorRuntime } from '../scripts/creator-runtime-contract.mjs';
+import { verifyCreatorRuntimeBuild } from '../scripts/creator-runtime-build.mjs';
+import { signCreatorRuntimeBundle } from '../scripts/sign-creator-runtime-after-pack.mjs';
+import { createKrillinBuildFixture, runtimeBuildMetadata } from './helpers/krillinai-build.mjs';
+
+const roots = [];
+afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })));
+
+describe('KrillinAI source build provenance', () => {
+ it('accepts the current source and both verified build artifacts', () => {
+ const fixture = createFixture();
+ expect(() => verify(fixture)).not.toThrow();
+ });
+
+ it('rejects an internally consistent old runtime after an uncommitted source change', () => {
+ const fixture = createFixture();
+ writeFileSync(join(fixture.rootDir, 'runtime/krillinai/main.go'), 'package main\n// new progress events');
+ expect(() => verifyCreatorRuntime(fixture.runtimeRoot, 'darwin', 'arm64')).not.toThrow();
+ expect(() => verify(fixture)).toThrow('sourceSha256');
+ });
+
+ it.each(['componentVersion', 'sourceCommit', 'sourceSha256', 'buildRecipeSha256', 'platform', 'arch'])(
+ 'rejects a stale or mismatched build %s', field => {
+ const fixture = createFixture();
+ const build = { ...fixture.manifest, [field]: 'old' };
+ writeFileSync(join(fixture.buildRoot, 'manifest.json'), JSON.stringify(build));
+ expect(() => verify(fixture)).toThrow(field);
+ }
+ );
+
+ it.each(['krillinai-build-contract.mjs', 'download-go-modules.mjs'])('includes %s changes in the build recipe', helper => {
+ const fixture = createFixture();
+ writeFileSync(join(fixture.rootDir, 'scripts', helper), '// updated build helper');
+ expect(() => verify(fixture)).toThrow('buildRecipeSha256');
+ });
+
+ it('checks cached artifacts as well as the binary used for packaging', () => {
+ const fixture = createFixture();
+ writeFileSync(join(fixture.buildRoot, 'artifacts/krillinai-cli'), 'old CLI');
+ expect(() => verifyKrillinBuild(fixture.buildRoot, identity(fixture))).toThrow('hash mismatch');
+ });
+
+ it('rejects an old copied CLI even if its runtime file hashes were regenerated', () => {
+ const fixture = createFixture();
+ writeFileSync(join(fixture.runtimeRoot, 'bin/krillinai-cli'), 'old CLI');
+ refreshRuntime(fixture);
+ expect(() => verifyCreatorRuntime(fixture.runtimeRoot, 'darwin', 'arm64')).not.toThrow();
+ expect(() => verify(fixture)).toThrow('binary hash mismatch');
+ });
+
+ it('rejects stale build records even if the runtime manifest claims the current source', () => {
+ const fixture = createFixture();
+ const record = { ...runtimeBuildMetadata(fixture.manifest), sourceSha256: 'a'.repeat(64) };
+ writeFileSync(join(fixture.runtimeRoot, 'build-record.json'), JSON.stringify(record));
+ refreshRuntime(fixture);
+ expect(() => verify(fixture)).toThrow('does not match the current source build');
+ });
+
+ it('blocks signing an old CLI before the signing tool is called', async () => {
+ const fixture = createFixture();
+ writeFileSync(join(fixture.runtimeRoot, 'bin/krillinai-cli'), 'old CLI');
+ refreshRuntime(fixture);
+ const signBinary = vi.fn();
+ await expect(signCreatorRuntimeBundle({
+ electronPlatformName: 'darwin', appOutDir: join(fixture.rootDir, 'app'),
+ packager: { appInfo: { productFilename: 'OpenCreator' } }
+ }, {
+ ...fixture, env: { OPENCREATOR_DESKTOP_TARGET_ARCH: 'arm64' }, signBinary
+ })).rejects.toThrow('binary hash mismatch');
+ expect(signBinary).not.toHaveBeenCalled();
+ });
+
+ it('rejects a signing record for a different source build', () => {
+ const fixture = createFixture();
+ const manifest = JSON.parse(readFileSync(join(fixture.runtimeRoot, 'manifest.json'), 'utf8'));
+ manifest.cliSigning = { unsignedSha256: 'a'.repeat(64), signedSha256: fixture.manifest.binaries['krillinai-cli'].sha256 };
+ writeFileSync(join(fixture.runtimeRoot, 'manifest.json'), JSON.stringify(manifest));
+ expect(() => verifyCreatorRuntimeBuild(fixture.runtimeRoot, 'darwin', 'arm64', {
+ ...fixture, allowSigned: true
+ })).toThrow('signing record');
+ });
+});
+
+function identity(fixture) {
+ return krillinBuildIdentity({ rootDir: fixture.rootDir, platform: 'darwin', arch: 'arm64' });
+}
+
+function verify(fixture) {
+ return verifyCreatorRuntimeBuild(fixture.runtimeRoot, 'darwin', 'arm64', fixture);
+}
+
+function createFixture() {
+ const rootDir = mkdtempSync(join(tmpdir(), 'krillinai-build-provenance-'));
+ roots.push(rootDir);
+ const build = createKrillinBuildFixture(rootDir);
+ const runtimeRoot = join(rootDir, 'app/OpenCreator.app/Contents/Resources/creator-runtime/krillinai');
+ const metadata = runtimeBuildMetadata(build.manifest);
+ const files = {
+ 'bin/ffmpeg': 'ffmpeg', 'bin/ffprobe': 'ffprobe', 'bin/yt-dlp': 'yt-dlp',
+ 'build-record.json': JSON.stringify(metadata)
+ };
+ for (const [path, content] of Object.entries(files)) {
+ mkdirSync(dirname(join(runtimeRoot, path)), { recursive: true });
+ writeFileSync(join(runtimeRoot, path), content);
+ }
+ copyFileSync(join(build.buildRoot, 'bin/krillinai-cli'), join(runtimeRoot, 'bin/krillinai-cli'));
+ const runtime = {
+ version: 1, runtimeMode: 'cli', ...metadata, integrationPatchSha256: 'a'.repeat(64),
+ ytDlp: { mode: 'standalone', version: 'test', executable: 'bin/yt-dlp' },
+ resources: ['bin/krillinai-cli', ...Object.keys(files)].map(path => ({
+ path, kind: path.startsWith('bin/') ? 'executable' : 'asset', sha256: hashKrillinFile(join(runtimeRoot, path))
+ }))
+ };
+ writeFileSync(join(runtimeRoot, 'manifest.json'), JSON.stringify(runtime));
+ return { ...build, runtimeRoot };
+}
+
+function refreshRuntime(fixture) {
+ const path = join(fixture.runtimeRoot, 'manifest.json');
+ const runtime = JSON.parse(readFileSync(path, 'utf8'));
+ for (const resource of runtime.resources) resource.sha256 = hashKrillinFile(join(fixture.runtimeRoot, resource.path));
+ writeFileSync(path, JSON.stringify(runtime));
+}
diff --git a/apps/desktop/test/krillinai-release-package.test.mjs b/apps/desktop/test/krillinai-release-package.test.mjs
index 90570a6a..19776dae 100644
--- a/apps/desktop/test/krillinai-release-package.test.mjs
+++ b/apps/desktop/test/krillinai-release-package.test.mjs
@@ -11,6 +11,8 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { packageKrillinRelease } from '../../../scripts/package-krillinai-release.mjs';
+import { createKrillinBuildFixture } from './helpers/krillinai-build.mjs';
+import { krillinBuildIdentity } from '../../../scripts/krillinai-build-contract.mjs';
const directories = [];
@@ -76,7 +78,7 @@ describe('KrillinAI release packages', () => {
function createFixture() {
const root = mkdtempSync(join(tmpdir(), 'krillinai-package-fixture-'));
directories.push(root);
- const buildRoot = join(root, 'build');
+ const { buildRoot } = createKrillinBuildFixture(root, { version: '3.0.0' });
const outputDir = join(root, 'release');
const configDir = join(root, 'runtime', 'krillinai', 'config');
const binDir = join(buildRoot, 'bin');
@@ -89,15 +91,17 @@ function createFixture() {
for (const name of ['krillinai-server', 'krillinai-cli']) {
const path = join(binDir, name);
writeFileSync(path, `${name}\n`);
+ writeFileSync(join(buildRoot, 'artifacts', name), `${name}\n`);
binaries[name] = {
path: `bin/${name}`,
- sha256: hashFile(path)
+ sha256: hashFile(path),
+ artifact: `artifacts/${name}`
};
}
writeFileSync(join(buildRoot, 'manifest.json'), JSON.stringify({
version: 1,
component: 'opencreator-krillinai',
- componentVersion: '3.0.0',
+ ...krillinBuildIdentity({ rootDir: root, platform: 'darwin', arch: 'arm64' }),
platform: 'darwin',
arch: 'arm64',
buildVcs: false,
diff --git a/apps/web/e2e/web-desktop-parity.spec.ts b/apps/web/e2e/web-desktop-parity.spec.ts
index f632560c..55f9221a 100644
--- a/apps/web/e2e/web-desktop-parity.spec.ts
+++ b/apps/web/e2e/web-desktop-parity.spec.ts
@@ -4,8 +4,9 @@ import { test, expect, stubVideoDownloadProbe } from './fixtures/runtime.js';
async function selectChoice(control: Locator, value: string) {
await control.click();
- await control.page().getByRole('option')
- .and(control.page().locator(`[data-value="${value}"]`)).click();
+ const listId = await control.getAttribute('aria-controls');
+ expect(listId).toBeTruthy();
+ await control.page().locator(`[id="${listId}"]`).locator(`[role="option"][data-value="${value}"]`).click();
}
test('视频翻译语言检索和选项在 Browser/Desktop 使用相同目录', async ({ browser, runtime }, testInfo) => {
@@ -1418,7 +1419,7 @@ test('视频生成在 Browser/Desktop Bridge 下保持相同界面、请求和
state: {
prompt: '雨夜中的未来城市,镜头平稳向前推进',
provider: 'seedance',
- model: 'doubao-seedance-2-0-260128',
+ model: 'doubao-seedance-2-5-260628',
size: '1280x720',
duration: 5,
currentStep: 1,
@@ -1458,7 +1459,7 @@ test('视频生成在 Browser/Desktop Bridge 下保持相同界面、请求和
const format = workspace.getByRole('combobox', { name: '画幅' });
const duration = workspace.getByRole('combobox', { name: '视频时长' });
await expect(provider).toHaveAttribute('data-value', 'seedance');
- await expect(model).toHaveValue('Seedance 2.0');
+ await expect(model).toHaveValue('Seedance 2.5');
await expect(format).toHaveAttribute('data-value', '1280x720');
await expect(duration).toHaveAttribute('data-value', '5');
await selectChoice(provider, 'veo');
diff --git a/apps/web/src/features/dashboard/DashboardPage.test.tsx b/apps/web/src/features/dashboard/DashboardPage.test.tsx
index 97c345a8..859ebf6c 100644
--- a/apps/web/src/features/dashboard/DashboardPage.test.tsx
+++ b/apps/web/src/features/dashboard/DashboardPage.test.tsx
@@ -695,7 +695,7 @@ function latestTranslationArtifact(job: CreatorJob, kind: string) {
async function startVideoTranslation() {
const workspace = screen.getByRole('region', { name: '视频翻译操作区' });
fireEvent.click(within(workspace).getByRole('button', { name: '开始翻译' }));
- await screen.findByRole('heading', { name: '视频翻译项目' });
+ await screen.findByRole('textbox', { name: '横屏字幕 1' });
}
function completedAgentTurn(jobId: string, content: string) {
@@ -1132,6 +1132,121 @@ describe('DashboardPage', () => {
expect(screen.getByRole('region', { name: '同步视频预览' }).querySelector('.video-result-player-frame')).toHaveAttribute('data-ratio', '9:16');
});
+ it('returns from the translation editor to project outputs without leaving the project', async () => {
+ const onSelectPrompt = vi.fn();
+ const creatorService = createInMemoryCreatorService();
+ render(
+ <DashboardPage
+ onSelectPrompt={onSelectPrompt}
+ creatorService={creatorService}
+ videoMetadataService={{
+ getVideoMetadata: vi.fn(async () => ({
+ platform: 'youtube' as const,
+ title: '测试视频标题',
+ authorName: '测试作者',
+ thumbnailUrl: 'https://i.ytimg.com/vi/test/hqdefault.jpg'
+ }))
+ }}
+ />
+ );
+
+ openBlankWorkspace('视频翻译', '空白视频翻译');
+
+ expect(screen.getByRole('heading', { name: '视频翻译配音' })).toBeInTheDocument();
+ expect(screen.getByRole('complementary', { name: 'OpenCreator' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: '拖放视频到这里' })).toBeInTheDocument();
+ expect(screen.getByRole('list', { name: '支持的平台' }).querySelectorAll('li')).toHaveLength(10);
+ fireEvent.change(screen.getByRole('textbox', { name: '视频链接' }), {
+ target: { value: 'https://www.youtube.com/watch?v=test' }
+ });
+ expect(screen.getByRole('img', { name: 'YouTube 视频缩略图' })).toHaveAttribute(
+ 'src',
+ 'https://i.ytimg.com/vi/test/hqdefault.jpg'
+ );
+ expect(await screen.findByText('测试视频标题')).toBeInTheDocument();
+ expect(screen.getByText('YouTube 视频 · 测试作者')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: '播放 YouTube 视频预览' }));
+ expect(screen.getByTitle('YouTube 视频预览')).toHaveAttribute('src', 'https://www.youtube-nocookie.com/embed/test');
+ expect(screen.queryByRole('heading', { name: '拖放视频到这里' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: '改用本地视频' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: '视频链接' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ expect(screen.getByRole('heading', { name: '设置翻译语言' })).toBeInTheDocument();
+ expect(screen.getByRole('combobox', { name: '源语言' })).toHaveValue('en');
+ expect(screen.getByRole('combobox', { name: '翻译为' })).toHaveValue('zh_cn');
+ expect(screen.queryByRole('switch', { name: '合成字幕视频' })).not.toBeInTheDocument();
+ expect(screen.getByLabelText('任务摘要')).toHaveTextContent('English → 简体中文');
+ expect(screen.getByLabelText('任务摘要')).toHaveClass('video-translation-summary', 'creator-task-summary');
+ expect(screen.getByRole('complementary', { name: 'OpenCreator' })).toContainElement(screen.getByLabelText('任务摘要'));
+ await startVideoTranslation();
+ expect(onSelectPrompt).not.toHaveBeenCalled();
+ expect(screen.getByRole('heading', { name: '视频翻译工作区' })).toBeVisible();
+ expect(screen.getByRole('textbox', { name: '横屏字幕 1' })).toBeVisible();
+ expect(screen.queryByRole('button', { name: '保存字幕' })).not.toBeInTheDocument();
+ fireEvent.click(within(screen.getByRole('region', { name: '视频翻译项目产出' })).getByRole('button', { name: '返回' }));
+ expect(await screen.findByRole('tab', { name: '作品' })).toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByRole('button', { name: '项目 V1' })).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: '返回工作区' }));
+ expect(screen.getByRole('textbox', { name: '横屏字幕 1' })).toBeVisible();
+ });
+
+
+ it('preserves custom subtitle settings across result panels without starting video output', async () => {
+ const service = createInMemoryCreatorService();
+ const applyAction = vi.spyOn(service, 'applyAction');
+ render(<DashboardPage onSelectPrompt={vi.fn()} creatorService={service} />);
+ openBlankWorkspace('视频翻译', '空白视频翻译');
+ fireEvent.change(screen.getByRole('textbox', { name: '视频链接' }), {
+ target: { value: 'https://www.youtube.com/watch?v=test' }
+ });
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ await startVideoTranslation();
+ fireEvent.click(screen.getByRole('button', { name: '字幕样式' }));
+ fireEvent.click(screen.getByRole('button', { name: '在下' }));
+ fireEvent.click(screen.getByRole('button', { name: '自定义样式' }));
+ changeControl(screen.getByRole('combobox', { name: '字幕字体' }), { target: { value: 'rounded' } });
+ changeControl(screen.getByRole('combobox', { name: '字幕大小' }), { target: { value: 'large' } });
+ fireEvent.click(screen.getByRole('button', { name: '选择译文颜色' }));
+ fireEvent.click(screen.getByRole('button', { name: '#FFE45C' }));
+ fireEvent.keyDown(screen.getByRole('button', { name: '#FFE45C' }), { key: 'Escape' });
+ fireEvent.click(screen.getByRole('button', { name: '完成' }));
+ fireEvent.click(screen.getByRole('button', { name: '任务设置' }));
+ fireEvent.click(screen.getByRole('button', { name: '字幕样式' }));
+ expect(screen.getByRole('button', { name: '在下' })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(screen.getByRole('button', { name: '自定义样式' }));
+ expect(screen.getByRole('combobox', { name: '字幕字体' })).toHaveAttribute('data-value', 'rounded');
+ expect(screen.getByRole('combobox', { name: '字幕大小' })).toHaveAttribute('data-value', 'large');
+ expect(screen.getByRole('button', { name: '选择译文颜色' })).toHaveAttribute('aria-label', '选择译文颜色');
+ expect(screen.getByRole('button', { name: '选择译文颜色' }).parentElement).toHaveTextContent('#FFE45C');
+ expect(screen.getByRole('button', { name: '选择原文颜色' })).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: '完成' }));
+ fireEvent.click(screen.getByRole('switch', { name: '双语字幕' }));
+ fireEvent.click(screen.getByRole('button', { name: '自定义样式' }));
+ expect(screen.queryByRole('button', { name: '选择原文颜色' })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: '选择译文颜色' }).parentElement).toHaveTextContent('#FFE45C');
+ expect(applyAction.mock.calls.filter(([, request]) => request.action === 'run-stage')).toHaveLength(1);
+ });
+
+
+ it('keeps style changes as a draft without output or a new result version', async () => {
+ const service = createInMemoryCreatorService();
+ const applyAction = vi.spyOn(service, 'applyAction');
+ render(<DashboardPage onSelectPrompt={vi.fn()} creatorService={service} />);
+ openBlankWorkspace('视频翻译', '空白视频翻译');
+ fireEvent.change(screen.getByRole('textbox', { name: '视频链接' }), {
+ target: { value: 'https://www.youtube.com/watch?v=test' }
+ });
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ await startVideoTranslation();
+ fireEvent.click(screen.getByRole('button', { name: '自定义样式' }));
+ changeControl(screen.getByRole('combobox', { name: '字幕字体' }), { target: { value: 'rounded' } });
+ fireEvent.click(screen.getByRole('button', { name: '完成' }));
+ await waitFor(async () => expect((await service.getJob('creator_test_job_1')).job.state).toMatchObject({ subtitleStyle: { fontPreset: 'rounded' }, composeVideo: false, resultVersion: 1 }));
+ expect(screen.getByRole('button', { name: '项目 V1' })).toBeVisible();
+ expect(applyAction.mock.calls.filter(([, request]) => request.action === 'run-stage').map(([, request]) => request.input.stageId)).toEqual(['subtitle']);
+ expect(applyAction.mock.calls.some(([, request]) => request.action === 'commit-version')).toBe(false);
+ });
+
it('submits public video link analysis from the dashboard', async () => {
const creatorService = createInMemoryCreatorService();
const applyAction = vi.spyOn(creatorService, 'applyAction');
diff --git a/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.test.tsx
index 80cfceaf..60445cfa 100644
--- a/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.test.tsx
+++ b/apps/web/src/features/dashboard/VideoTranslationResultWorkspace.test.tsx
@@ -141,7 +141,7 @@ describe('VideoTranslationResultWorkspace', () => {
render(<EditingHarness />);
fireEvent.click(screen.getByRole('button', { name: '查找与替换' }));
const find = screen.getByRole('search');
- fireEvent.change(within(find).getByRole('combobox', { name: '搜索范围' }), { target: { value: 'sourceText' } });
+ selectOption(within(find).getByRole('combobox', { name: '搜索范围' }), 'sourceText');
fireEvent.change(within(find).getByRole('textbox', { name: '查找' }), { target: { value: '世界' } });
fireEvent.click(within(find).getByRole('button', { name: '替换' }));
expect(screen.getByDisplayValue('你好')).toBeInTheDocument();
diff --git a/apps/web/src/features/settings/RuntimeComponentsSettingsView.test.tsx b/apps/web/src/features/settings/RuntimeComponentsSettingsView.test.tsx
index 0d7cff29..2bf1bbde 100644
--- a/apps/web/src/features/settings/RuntimeComponentsSettingsView.test.tsx
+++ b/apps/web/src/features/settings/RuntimeComponentsSettingsView.test.tsx
@@ -7,6 +7,21 @@ import { LanguageProvider } from '../../i18n/LanguageProvider.js';
import { RuntimeComponentsSettingsView } from './RuntimeComponentsSettingsView.js';
describe('RuntimeComponentsSettingsView', () => {
+ it('keeps yt-dlp visible with a retry action when its status cannot be loaded', async () => {
+ const checkYtDlpUpdate = vi.fn(async () => status());
+ renderView({
+ ytDlpStatus: undefined,
+ checkYtDlpUpdate,
+ issues: [normalizePageIssue('settings-runtime-components', 'runtime.load-yt-dlp',
+ new Error('Runtime unavailable'), '无法读取视频下载组件状态。')]
+ });
+
+ expect(screen.getByRole('heading', { name: 'yt-dlp nightly' })).toBeVisible();
+ expect(screen.getByText('状态读取失败')).toHaveAttribute('data-status', 'failed');
+ fireEvent.click(screen.getByRole('button', { name: '重新检查' }));
+ await waitFor(() => expect(checkYtDlpUpdate).toHaveBeenCalledWith(true));
+ });
+
it('shows current, latest, and updated versions, and installs an available update', async () => {
const updateYtDlp = vi.fn(async () => status({
source: 'managed',
diff --git a/apps/web/src/features/settings/RuntimeComponentsSettingsView.tsx b/apps/web/src/features/settings/RuntimeComponentsSettingsView.tsx
index ec93cfea..d1574110 100644
--- a/apps/web/src/features/settings/RuntimeComponentsSettingsView.tsx
+++ b/apps/web/src/features/settings/RuntimeComponentsSettingsView.tsx
@@ -70,6 +70,25 @@ export function RuntimeComponentsSettingsView(props: {
<section className="settings-section settings-management runtime-components-settings" aria-labelledby="runtime-components-title">
<SettingsHeader />
<RuntimeManagedComponents controller={props.controller} componentId={props.componentId} onReturn={props.onReturn} />
+ <article className="runtime-component-item runtime-component-row">
+ <div className="runtime-component-heading">
+ <div>
+ <div className="runtime-component-title">
+ <h2 className="runtime-component-name"><img className="runtime-component-logo" src="/components/yt-dlp.png" width="26" height="26" alt="" />yt-dlp nightly</h2>
+ <span data-status={hasIssue ? 'failed' : 'checking'}>{hasIssue
+ ? localize('状态读取失败', 'Status unavailable', 'Status är inte tillgänglig')
+ : t('settings.runtimeComponents.loading')}</span>
+ </div>
+ <p>{t('settings.runtimeComponents.ytDlpDescription')}</p>
+ </div>
+ </div>
+ <footer className="runtime-component-footer">
+ <button className="settings-secondary-button" type="button" disabled={busy}
+ onClick={() => void props.controller.checkYtDlpUpdate(true).catch(() => undefined)}>
+ <RefreshCw size={15} aria-hidden="true" />
+ {localize('重新检查', 'Check again', 'Kontrollera igen')}
+ </button>
+ </footer>
{!hasIssue ? (
<div className="settings-state">
<LoaderCircle className="settings-spin" size={17} aria-hidden="true" />
@@ -87,6 +106,7 @@ export function RuntimeComponentsSettingsView(props: {
onDismiss={props.controller.dismissIssue}
/>
)}
+ </article>
</section>
);
}
diff --git a/apps/web/src/runtime/dev-creator-runtime.test.ts b/apps/web/src/runtime/dev-creator-runtime.test.ts
new file mode 100644
index 00000000..624fa7c1
--- /dev/null
+++ b/apps/web/src/runtime/dev-creator-runtime.test.ts
@@ -0,0 +1,108 @@
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { lstatSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { prepareDevCreatorRuntime, resolveDevCreatorRuntimeRoot } from './dev-creator-runtime.js';
+
+vi.mock('node:child_process', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:child_process')>();
+ const build = vi.fn();
+ return { ...actual, default: { ...actual, execFileSync: build }, execFileSync: build };
+});
+
+const roots: string[] = [];
+const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');
+const cliPath = `bin/krillinai-cli${process.platform === 'win32' ? '.exe' : ''}`;
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.clearAllMocks();
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'creator-dev-runtime-'));
+ roots.push(root);
+ const input = { repositoryRoot: root, dependencyRoot: join(root, 'apps/desktop/.pack/creator-runtime/krillinai'),
+ buildRoot: join(root, '.runtime/build/krillinai', `${process.platform}-${process.arch}`), outputRoot: join(root, 'development') };
+ for (const dir of [input.dependencyRoot, input.buildRoot]) mkdirSync(join(dir, 'bin'), { recursive: true });
+ writeFileSync(join(input.dependencyRoot, cliPath), 'old-batch-progress');
+ writeFileSync(join(input.dependencyRoot, 'bin/ffmpeg'), 'media-dependency');
+ writeFileSync(join(input.dependencyRoot, 'subtitle-style.json'), '{}');
+ writeFileSync(join(input.dependencyRoot, 'build-record.json'), '{}');
+ const resources = [cliPath, 'bin/ffmpeg', 'subtitle-style.json', 'build-record.json'].map(path => ({
+ path, sha256: hash(readFileSync(join(input.dependencyRoot, path))), kind: path.startsWith('bin/') ? 'executable' : 'asset'
+ }));
+ writeFileSync(join(input.dependencyRoot, 'manifest.json'), JSON.stringify({
+ version: 1, platform: process.platform, arch: process.arch, sourceCommit: 'old-checkout', resources
+ }));
+ writeFileSync(join(input.buildRoot, cliPath), 'new-detailed-progress');
+ writeFileSync(join(input.buildRoot, 'manifest.json'), JSON.stringify({
+ platform: process.platform, arch: process.arch, sourceCommit: 'current-checkout', sourceSha256: 'a'.repeat(64), componentVersion: '3.2.7',
+ binaries: { 'krillinai-cli': { path: cliPath, sha256: hash('new-detailed-progress') } }
+ }));
+ return input;
+}
+
+describe('development Creator runtime', () => {
+ it('builds from the active checkout before choosing a runtime, overriding inherited cross-build output paths', () => {
+ const input = fixture();
+ vi.stubEnv('OPENCREATOR_CREATOR_RUNTIME_ROOT', '');
+ vi.stubEnv('OPENCREATOR_KRILLINAI_BUILD_OUTPUT', '/another-checkout/build');
+ vi.stubEnv('OPENCREATOR_KRILLINAI_TARGET_PLATFORM', 'another-platform');
+ const root = resolveDevCreatorRuntimeRoot(input.repositoryRoot)!;
+ expect(execFileSync).toHaveBeenCalledWith(process.execPath, [join(input.repositoryRoot, 'scripts/build-krillinai.mjs')], expect.objectContaining({
+ cwd: input.repositoryRoot,
+ env: expect.objectContaining({
+ OPENCREATOR_KRILLINAI_BUILD_OUTPUT: input.buildRoot,
+ OPENCREATOR_KRILLINAI_TARGET_PLATFORM: process.platform,
+ OPENCREATOR_KRILLINAI_TARGET_ARCH: process.arch
+ })
+ }));
+ expect(readFileSync(join(root, cliPath), 'utf8')).toBe('new-detailed-progress');
+ });
+
+ it('runs the current checkout CLI and verifies its manifest without rewriting packaged dependencies', () => {
+ const input = fixture();
+ const root = prepareDevCreatorRuntime(input);
+ expect(readFileSync(join(root, cliPath), 'utf8')).toBe('new-detailed-progress');
+ expect(readFileSync(join(input.dependencyRoot, cliPath), 'utf8')).toBe('old-batch-progress');
+ const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8'));
+ expect(manifest.sourceCommit).toBe('current-checkout');
+ for (const resource of manifest.resources) {
+ expect(lstatSync(join(root, resource.path)).isSymbolicLink()).toBe(false);
+ expect(hash(readFileSync(join(root, resource.path)))).toBe(resource.sha256);
+ }
+ expect(prepareDevCreatorRuntime(input)).toBe(root);
+ });
+
+ it('keeps the selected CLI stable when another worktree overwrites the package or a new build appears', () => {
+ const input = fixture();
+ const root = prepareDevCreatorRuntime(input);
+ writeFileSync(join(input.dependencyRoot, cliPath), 'another-worktree');
+ writeFileSync(join(input.buildRoot, cliPath), 'next-build');
+ expect(readFileSync(join(root, cliPath), 'utf8')).toBe('new-detailed-progress');
+ const build = JSON.parse(readFileSync(join(input.buildRoot, 'manifest.json'), 'utf8'));
+ build.binaries['krillinai-cli'].sha256 = hash('next-build');
+ writeFileSync(join(input.buildRoot, 'manifest.json'), JSON.stringify(build));
+ const next = prepareDevCreatorRuntime(input);
+ expect(next).not.toBe(root);
+ expect(readFileSync(join(next, cliPath), 'utf8')).toBe('next-build');
+ expect(readFileSync(join(root, cliPath), 'utf8')).toBe('new-detailed-progress');
+ });
+
+ it('rejects mismatched binaries instead of silently using the old package', () => {
+ const input = fixture();
+ writeFileSync(join(input.buildRoot, cliPath), 'wrong-build');
+ expect(() => prepareDevCreatorRuntime(input)).toThrow('hash mismatch');
+ });
+
+ it('honors an explicitly configured runtime without requiring a local Go build', () => {
+ const input = fixture();
+ vi.stubEnv('OPENCREATOR_CREATOR_RUNTIME_ROOT', input.dependencyRoot);
+ expect(resolveDevCreatorRuntimeRoot('/missing-checkout')).toBe(input.dependencyRoot);
+ vi.stubEnv('OPENCREATOR_CREATOR_RUNTIME_ROOT', '');
+ expect(resolveDevCreatorRuntimeRoot('/missing-checkout')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/runtime/dev-creator-runtime.ts b/apps/web/src/runtime/dev-creator-runtime.ts
new file mode 100644
index 00000000..92c82935
--- /dev/null
+++ b/apps/web/src/runtime/dev-creator-runtime.ts
@@ -0,0 +1,115 @@
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync,
+ readdirSync, renameSync, rmSync, symlinkSync, writeFileSync
+} from 'node:fs';
+import { join, resolve } from 'node:path';
+
+type Resource = { path: string; sha256: string; kind: string };
+
+// Development uses the current checkout's CLI. Packaged dependencies may have
+// been prepared by another worktree, so never execute their cached CLI directly.
+export function resolveDevCreatorRuntimeRoot(repositoryRoot: string): string | undefined {
+ const configured = process.env.OPENCREATOR_CREATOR_RUNTIME_ROOT?.trim();
+ if (configured) return resolve(configured);
+ const dependencyRoot = join(repositoryRoot, 'apps/desktop/.pack/creator-runtime/krillinai');
+ if (!existsSync(join(dependencyRoot, 'manifest.json'))) return undefined;
+ const buildRoot = join(repositoryRoot, '.runtime/build/krillinai', `${process.platform}-${process.arch}`);
+ execFileSync(process.execPath, [join(repositoryRoot, 'scripts/build-krillinai.mjs')], {
+ cwd: repositoryRoot,
+ env: {
+ ...process.env,
+ OPENCREATOR_KRILLINAI_TARGET_PLATFORM: process.platform,
+ OPENCREATOR_KRILLINAI_TARGET_ARCH: process.arch,
+ OPENCREATOR_KRILLINAI_BUILD_OUTPUT: buildRoot
+ },
+ stdio: ['ignore', 'pipe', 'pipe']
+ });
+ return prepareDevCreatorRuntime({
+ dependencyRoot,
+ buildRoot,
+ outputRoot: join(repositoryRoot, '.runtime/dev/creator-runtime/krillinai')
+ });
+}
+
+export function prepareDevCreatorRuntime(input: {
+ dependencyRoot: string; buildRoot: string; outputRoot: string;
+}): string {
+ const base = JSON.parse(readFileSync(join(input.dependencyRoot, 'manifest.json'), 'utf8'));
+ const build = JSON.parse(readFileSync(join(input.buildRoot, 'manifest.json'), 'utf8'));
+ if ([base, build].some(value => value.platform !== process.platform || value.arch !== process.arch)) {
+ throw new Error('Creator development runtime platform mismatch');
+ }
+ const cli = build.binaries?.['krillinai-cli'];
+ const cliPath = `bin/krillinai-cli${process.platform === 'win32' ? '.exe' : ''}`;
+ if (cli?.path !== cliPath || !/^[a-f0-9]{64}$/.test(cli.sha256)
+ || !base.resources.some((resource: Resource) => resource.path === cliPath)) {
+ throw new Error('Creator development CLI build is incomplete');
+ }
+ const cliBytes = readFileSync(join(input.buildRoot, cliPath));
+ if (sha256(cliBytes) !== cli.sha256) throw new Error('Creator development CLI hash mismatch');
+ const origin = {
+ sourceCommit: build.sourceCommit,
+ sourceSha256: build.sourceSha256,
+ cliVersion: build.componentVersion,
+ cliSource: { kind: 'local-source', revision: build.sourceCommit }
+ };
+ const record = JSON.stringify({
+ ...JSON.parse(readFileSync(join(input.dependencyRoot, 'build-record.json'), 'utf8')),
+ ...origin
+ }, null, 2) + '\n';
+ const manifest = JSON.stringify({
+ ...base, ...origin,
+ resources: base.resources.map((resource: Resource) => ({
+ ...resource,
+ sha256: resource.path === cliPath ? cli.sha256
+ : resource.path === 'build-record.json' ? sha256(record) : resource.sha256
+ }))
+ }, null, 2) + '\n';
+ // Include the dependency location: two checkouts must not share linked assets.
+ const destination = join(input.outputRoot, sha256('dev-runtime-v1:' + resolve(input.dependencyRoot) + manifest));
+ if (existsSync(destination)) {
+ if (readFileSync(join(destination, 'manifest.json'), 'utf8') !== manifest
+ || sha256(readFileSync(join(destination, cliPath))) !== cli.sha256
+ || readFileSync(join(destination, 'build-record.json'), 'utf8') !== record) {
+ throw new Error('Creator development runtime cache is inconsistent');
+ }
+ return destination;
+ }
+ mkdirSync(input.outputRoot, { recursive: true });
+ const staging = mkdtempSync(join(input.outputRoot, '.preparing-'));
+ try {
+ for (const entry of readdirSync(input.dependencyRoot, { withFileTypes: true })) {
+ if (['manifest.json', 'build-record.json', 'bin'].includes(entry.name)) continue;
+ const source = resolve(input.dependencyRoot, entry.name);
+ const target = join(staging, entry.name);
+ if (entry.isDirectory()) symlinkSync(source, target, 'junction');
+ else copyFileSync(source, target, constants.COPYFILE_FICLONE);
+ }
+ mkdirSync(join(staging, 'bin'));
+ for (const entry of readdirSync(join(input.dependencyRoot, 'bin'))) {
+ if (`bin/${entry}` !== cliPath) copyFileSync(resolve(input.dependencyRoot, 'bin', entry), join(staging, 'bin', entry), constants.COPYFILE_FICLONE);
+ }
+ // Copy rather than link the build output: later builds may replace it.
+ copyFileSync(join(input.buildRoot, cliPath), join(staging, cliPath));
+ if (sha256(readFileSync(join(staging, cliPath))) !== cli.sha256) throw new Error('Creator CLI changed while preparing development runtime');
+ writeFileSync(join(staging, 'build-record.json'), record);
+ writeFileSync(join(staging, 'manifest.json'), manifest);
+ try {
+ renameSync(staging, destination);
+ } catch (error) {
+ // Two Vite servers may prepare the same immutable version concurrently.
+ if (!existsSync(join(destination, 'manifest.json'))
+ || readFileSync(join(destination, 'manifest.json'), 'utf8') !== manifest
+ || sha256(readFileSync(join(destination, cliPath))) !== cli.sha256) throw error;
+ }
+ return destination;
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+}
+
+function sha256(value: string | Buffer): string {
+ return createHash('sha256').update(value).digest('hex');
+}
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 0315a196..f4893979 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -24,6 +24,7 @@ import {
parseDevDaemonStartupError,
type DevDaemonConfig
} from './src/runtime/dev-proxy-target.js';
+import { resolveDevCreatorRuntimeRoot } from './src/runtime/dev-creator-runtime.js';
type RuntimeConfig = DevDaemonConfig;
@@ -297,7 +298,7 @@ function getRuntimeConfig(): Promise<RuntimeConfig> {
}
function startRuntimeProcess(): RuntimeProcess {
- const creatorRuntimeRoot = resolveDevCreatorRuntimeRoot();
+ const creatorRuntimeRoot = resolveDevCreatorRuntimeRoot(resolve(webDir, '../..'));
const codexBin = resolveDevCodexBin();
const ytDlpPath = resolveDevYtDlpPath();
const daemonDir = resolve(webDir, '../daemon');
@@ -394,22 +395,6 @@ function resolveDevCodexBin(): string | undefined {
return existsSync(candidate) ? candidate : undefined;
}
-function resolveDevCreatorRuntimeRoot(): string | undefined {
- const configured = process.env.OPENCREATOR_CREATOR_RUNTIME_ROOT?.trim();
- if (configured) return resolve(configured);
-
- const candidate = resolve(
- webDir,
- '../desktop/.pack/creator-runtime/krillinai'
- );
- const executableSuffix = process.platform === 'win32' ? '.exe' : '';
- const requiredAssets = [
- join(candidate, 'manifest.json'),
- join(candidate, 'bin', `krillinai-cli${executableSuffix}`)
- ];
- return requiredAssets.every(path => existsSync(path)) ? candidate : undefined;
-}
-
function resolveDevYtDlpPath(): string | undefined {
const configured = process.env.OPENCREATOR_YT_DLP_PATH?.trim();
return configured ? resolve(configured) : undefined;
diff --git a/docs/development/creator-dev-runtime.md b/docs/development/creator-dev-runtime.md
new file mode 100644
index 00000000..4fe1d4e0
--- /dev/null
+++ b/docs/development/creator-dev-runtime.md
@@ -0,0 +1,9 @@
+# 开发环境的 Creator Runtime
+
+Web 开发服务启动 Daemon 前,先调用 `scripts/build-krillinai.mjs` 检查当前 checkout 的源码与构建缓存;不一致时重新构建 CLI。下载、转录、字体和 NLP 依赖继续复用已准备的 `.pack/creator-runtime/krillinai`。
+
+Daemon 实际使用 `.runtime/dev/creator-runtime/krillinai/<版本摘要>`。该目录独立保存当前 CLI、manifest 和 build-record,并同步两份资源的 SHA-256。后续构建或其他 worktree 替换 `.pack/bin/krillinai-cli` 时,不会替换已经选定的开发 CLI。目录资源仍接受 Daemon 的完整性校验。
+
+合并 Runtime 源码后重新启动开发服务即可选用当前分支;只合并 Go 源码不会热替换已经启动的翻译子进程。显式设置 `OPENCREATOR_CREATOR_RUNTIME_ROOT` 时仍使用指定目录,便于验证固定版本。
+
+这个流程仅用于 Web 开发环境,不修改 Desktop 安装包、生产网关或已有任务价格。已启动的任务沿用原子进程,更新开发版本应等待当前任务结束,避免中断或重复请求。
diff --git a/docs/development/krillinai-release-build.md b/docs/development/krillinai-release-build.md
new file mode 100644
index 00000000..16b03340
--- /dev/null
+++ b/docs/development/krillinai-release-build.md
@@ -0,0 +1,11 @@
+# KrillinAI 发布构建校验
+
+`pnpm desktop:package`、`pnpm desktop:dist`、`pnpm desktop:release` 和 `pnpm krillinai:package` 均使用当前 checkout 中的 `runtime/krillinai` 源码。构建不会自动切换分支或拉取远端;应先将需要发布的代码合并到构建分支。
+
+构建缓存同时绑定源码内容 SHA-256(包括未提交修改)、Git commit、版本、构建脚本及其校验工具、目标系统和架构。只有 CLI、Server 及各自发布产物的文件摘要都一致时才能复用。编译期间源码发生变化会使构建失败,不生成有效构建清单。
+
+准备 Creator Runtime 时,重新验证当前源码和实际 CLI,随后将构建配方摘要及原始 CLI 摘要写入 `manifest.json`、`build-record.json`。打包前、Electron `afterPack` 和最终 `verify-package` 再次检查。只有旧 CLI 和旧清单的自洽缓存也会被拒绝,不能仅通过重写资源文件摘要绕过检查。
+
+macOS Developer ID 签名前必须匹配原始 CLI;签名后记录原始与签后摘要的对应关系,最终包同时校验来源和签后完整性。Windows 及未签名目录包直接对照原始构建摘要。Desktop 构建清单记录 `krillinBuild`,独立 CLI/Server 压缩包同样需要通过当前源码校验。
+
+这些检查发生在构建和打包阶段,不访问模型供应商,也不修改已安装客户端或正在执行的任务。
diff --git a/runtime/krillinai/internal/pipeline/subtitle_recovery_integration_test.go b/runtime/krillinai/internal/pipeline/subtitle_recovery_integration_test.go
index 374c31b4..21445a68 100644
--- a/runtime/krillinai/internal/pipeline/subtitle_recovery_integration_test.go
+++ b/runtime/krillinai/internal/pipeline/subtitle_recovery_integration_test.go
@@ -101,16 +101,10 @@ func TestSubtitleRecoveryIntegration(t *testing.T) {
}
}
blocks, err := readSRTBlocks(filepath.Join(workdir, types.SubtitleTaskTargetLanguageSrtFileName))
- var exported strings.Builder
- for i, block := range blocks {
- exported.WriteString(strings.Join(block.Lines, ""))
- if i > 0 && strings.Split(blocks[i-1].Timestamp, " --> ")[1] != strings.Split(block.Timestamp, " --> ")[0] {
- t.Fatalf("分段时间不连续: %+v", blocks)
- }
- }
- if err != nil || len(blocks) == 0 || exported.String() != target || !strings.HasPrefix(blocks[0].Timestamp, "00:00:01,000 --> ") || !strings.HasSuffix(blocks[len(blocks)-1].Timestamp, " --> 00:00:03,000") {
- t.Fatalf("最终导出内容或时间丢失: %+v err=%v", blocks, err)
+ if err != nil {
+ t.Fatal(err)
}
+ assertPreservedSubtitleExport(t, blocks, target, "00:00:01,000", "00:00:03,000")
}
run()
if calls.Load() != 1 {
@@ -220,16 +214,16 @@ func TestSubtitleFinalLengthRecoveryIntegration(t *testing.T) {
t.Fatalf("修正预算耗尽后应保留原译继续导出: %v", err)
}
fallback, err := readSRTBlocks(filepath.Join(workdir, types.SubtitleTaskTargetLanguageSrtFileName))
- var exported strings.Builder
- for _, block := range fallback {
- exported.WriteString(strings.Join(block.Lines, ""))
+ if err != nil {
+ t.Fatal(err)
}
+ assertPreservedSubtitleExport(t, fallback, target, "00:00:01,000", "00:00:09,000")
expectedBlocks, expectedSplits, resumedSplits := 1, int32(3), int32(4)
if route == "vtt" {
// 冻结排版预算耗尽后,程序分段已经完成;续跑不再支付模型请求。
expectedBlocks, expectedSplits, resumedSplits = 2, 2, 2
}
- if err != nil || len(fallback) != expectedBlocks || exported.String() != target || splits.Load() != expectedSplits {
+ if err != nil || len(fallback) != expectedBlocks || splits.Load() != expectedSplits {
t.Fatalf("未按预算完整导出原译: output=%+v splits=%d err=%v", fallback, splits.Load(), err)
}
ready.Store(true)
@@ -258,3 +252,24 @@ func TestSubtitleFinalLengthRecoveryIntegration(t *testing.T) {
})
}
}
+
+// Segmentation may change, but content, contiguous timing and cue order must survive.
+func assertPreservedSubtitleExport(t *testing.T, blocks []srtBlock, text, start, end string) {
+ t.Helper()
+ if len(blocks) == 0 {
+ t.Fatal("empty subtitle export")
+ }
+ var content strings.Builder
+ previousEnd := start
+ for i, block := range blocks {
+ bounds := strings.Split(block.Timestamp, " --> ")
+ if len(bounds) != 2 || bounds[0] != previousEnd || bounds[1] <= bounds[0] || block.Index != fmt.Sprint(i+1) || len(block.Lines) != 1 || block.Lines[0] == "" {
+ t.Fatalf("lost cue content, order or timing: %+v", block)
+ }
+ previousEnd = bounds[1]
+ content.WriteString(block.Lines[0])
+ }
+ if previousEnd != end || strings.Join(strings.Fields(content.String()), "") != strings.Join(strings.Fields(text), "") {
+ t.Fatalf("subtitle content or outer timing changed: %+v, want %q (%s --> %s)", blocks, text, start, end)
+ }
+}
diff --git a/runtime/krillinai/internal/service/audio2subtitle_test.go b/runtime/krillinai/internal/service/audio2subtitle_test.go
index a9de433c..72e4c54f 100644
--- a/runtime/krillinai/internal/service/audio2subtitle_test.go
+++ b/runtime/krillinai/internal/service/audio2subtitle_test.go
@@ -10,7 +10,6 @@ import (
"krillin-ai/pkg/util"
"os"
"path/filepath"
- "sort"
"strings"
"sync"
"testing"
@@ -355,16 +354,34 @@ func TestSplitTextAndTranslateUsesBatchesAndReportsProgress(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- sort.Ints(completer.batchSizes)
- if fmt.Sprint(completer.batchSizes) != "[3 10]" {
- t.Fatalf("batch sizes = %v, want [3 10]", completer.batchSizes)
+ total := 0
+ for _, size := range completer.batchSizes {
+ if size <= 0 || size > 10 {
+ t.Fatalf("batch exceeds the semantic translation limit: %v", completer.batchSizes)
+ }
+ total += size
+ }
+ if total != len(parts) {
+ t.Fatalf("batch coverage = %d, want %d", total, len(parts))
+ }
+ last := 0
+ for _, completed := range progress {
+ if completed <= last || completed > len(parts) {
+ t.Fatalf("progress is not increasing: %v", progress)
+ }
+ last = completed
}
- if len(progress) != 2 || progress[0] <= 0 || progress[0] >= 13 || progress[1] != 13 {
- t.Fatalf("progress = %v, want two advancing updates ending at 13", progress)
+ if len(progress) != len(completer.batchSizes) || last != len(parts) {
+ t.Fatalf("incomplete progress: %v", progress)
}
- if len(results) != 13 || results[12].TranslatedText == results[12].OriginText {
+ if len(results) != len(parts) {
t.Fatalf("unexpected results: %+v", results)
}
+ for i, result := range results {
+ if result.OriginText != parts[i] || result.TranslatedText == result.OriginText || result.TranslatedText == "" {
+ t.Fatalf("sentence lost, reordered or untranslated: %+v", result)
+ }
+ }
}
type scriptedCompleter struct {
diff --git a/runtime/krillinai/internal/service/paired_translation_test.go b/runtime/krillinai/internal/service/paired_translation_test.go
index 1b97bb00..9f69c37b 100644
--- a/runtime/krillinai/internal/service/paired_translation_test.go
+++ b/runtime/krillinai/internal/service/paired_translation_test.go
@@ -79,8 +79,9 @@ func TestPairedTranslationRateLimitStopsAtConfiguredLimit(t *testing.T) {
calls++
return "", &openaiapi.APIError{HTTPStatusCode: http.StatusTooManyRequests}
})}
- _, err := translator.requestTranslation(context.Background(), "translation request", 1024)
- if translationRequestStatus(err) != http.StatusTooManyRequests || calls != 1 {
+ _, err := translator.translatePairedSentences(context.Background(), []string{"Hello."}, "en", "zh_cn", 50, 1, nil)
+ var exhausted *allTranslationFailedError
+ if !errors.As(err, &exhausted) || exhausted.count != 1 || !strings.Contains(exhausted.reason, "429") || calls != 1 {
t.Fatalf("限流达到配置次数后没有退出: calls=%d error=%v", calls, err)
}
}
@@ -265,7 +266,7 @@ func TestPairedTranslationProgressDoesNotWaitForSlowEarlierBatch(t *testing.T) {
}
}
-func TestPairedTranslationKeepsSuccessfulWindowsWhenOneFails(t *testing.T) {
+func TestPairedTranslationPreservesFailedSentenceAndCommitsOtherWindows(t *testing.T) {
previous := config.Conf
t.Cleanup(func() { config.Conf = previous })
config.Conf.App.TranslateParallelNum = 2
@@ -289,18 +290,22 @@ func TestPairedTranslationKeepsSuccessfulWindowsWhenOneFails(t *testing.T) {
commits := 0
result, err := translator.translatePairedSentences(context.Background(), []string{"One.", "Two.", "Three."}, "en", "zh_cn", 20, 1, func([]pairedSentence, int, int) error { commits++; return nil })
if err != nil || len(result) != 3 || calls["1"] != 1 || calls["2"] != 1 || calls["3"] != 1 || commits != 3 {
- t.Fatalf("calls=%v commits=%d error=%v", calls, commits, err)
+ t.Fatalf("calls=%v commits=%d result=%+v error=%v", calls, commits, result, err)
}
for i, sentence := range result {
- if sentence.ID != fmt.Sprint(i+1) || (sentence.TranslationFallbackReason != "") != (i == 1) {
- t.Fatalf("成功句或失败标记丢失:%+v", result)
+ if sentence.ID != fmt.Sprint(i+1) || sentence.FullSource != []string{"One.", "Two.", "Three."}[i] {
+ t.Fatalf("lost or reordered sentence: %+v", sentence)
+ }
+ if i == 1 {
+ if sentence.FullTarget != "Two." || !strings.Contains(sentence.TranslationFallbackReason, "LLM disconnected") {
+ t.Fatalf("missing original or failure reason: %+v", sentence)
+ }
+ } else if sentence.FullTarget != "这是测试译文," || sentence.TranslationFallbackReason != "" {
+ t.Fatalf("successful translation was discarded: %+v", sentence)
}
- }
- if result[1].FullTarget != "Two." || !strings.Contains(result[1].TranslationFallbackReason, "LLM disconnected") {
- t.Fatalf("失败句未保留原文及原因:%+v", result[1])
}
if failures := task.TranslationFailures(); len(failures) != 1 || failures[0].SentenceID != "2" {
- t.Fatalf("失败报告错误:%+v", failures)
+ t.Fatalf("failure report was lost: %+v", failures)
}
}
@@ -948,7 +953,6 @@ func TestAudioTranslationWorkerStopsOnUpstreamFailure(t *testing.T) {
if failure {
want = 1
}
- // 源文单元通过本地 NLP 整理,不再请求模型预分句。
if calls != want || splitCalls != 0 || (err != nil) != failure {
t.Fatalf("translation calls=%d want=%d split calls=%d error=%v", calls, want, splitCalls, err)
}
@@ -1014,3 +1018,18 @@ func TestAudioModalFilterPreservesPairedSource(t *testing.T) {
t.Fatalf("items=%+v calls=%d error=%v", items, calls, err)
}
}
+
+func TestPairedTranslationRequestRateLimitStopsAtConfiguredLimit(t *testing.T) {
+ previous := config.Conf
+ t.Cleanup(func() { config.Conf = previous })
+ config.Conf.App.TranslateMaxAttempts = 1
+ calls := 0
+ translator := &Translator{chatCompleter: translationCompleterFunc(func(string) (string, error) {
+ calls++
+ return "", &openaiapi.APIError{HTTPStatusCode: http.StatusTooManyRequests}
+ })}
+ _, err := translator.requestTranslation(context.Background(), "translation request", 1024)
+ if translationRequestStatus(err) != http.StatusTooManyRequests || calls != 1 {
+ t.Fatalf("限流达到配置次数后没有退出: calls=%d error=%v", calls, err)
+ }
+}
diff --git a/runtime/krillinai/internal/service/srt_embed_test.go b/runtime/krillinai/internal/service/srt_embed_test.go
index 2599142b..a273fbc1 100644
--- a/runtime/krillinai/internal/service/srt_embed_test.go
+++ b/runtime/krillinai/internal/service/srt_embed_test.go
@@ -169,11 +169,9 @@ func TestHorizontalAssUsesCustomSubtitleStyle(t *testing.T) {
if !strings.Contains(ass, ",4,1.5,2,10,10,44,1") {
t.Fatalf("custom outline/margin missing:\n%s", ass)
}
- if strings.Count(ass, "Dialogue:") != 2 ||
- !strings.Contains(ass, `{\rMajor}{\an2}{\fad(120,180)\blur1}{\1a&HFF&\2a&HFF&\3a&HFF&}主字幕`) ||
- !strings.Contains(ass, `{\rMajor}{\an2}{\fad(120,180)\blur1}{\blur0\shad0}主字幕`) {
- t.Fatalf("custom dialogue tags missing:\n%s", ass)
- }
+ assertASSLayers(t, ass,
+ `{\rMajor}{\an2}{\fad(120,180)\blur1}{\1a&HFF&\2a&HFF&\3a&HFF&}主字幕\N{\rMinor}{\an2}{\1a&HFF&\2a&HFF&\3a&HFF&}副字幕`,
+ `{\rMajor}{\an2}{\fad(120,180)\blur1}{\blur0\shad0}主字幕\N{\rMinor}{\an2}{\blur0\shad0}副字幕`)
}
func TestHorizontalAssWrapsLargeFontChineseSubtitle(t *testing.T) {
@@ -385,11 +383,9 @@ func TestBilingualTranslationOnBottomKeepsSemanticStylesAndShadow(t *testing.T)
if err != nil {
t.Fatal(err)
}
- if strings.Count(string(data), "Dialogue:") != 2 ||
- !strings.Contains(string(data), `{\rMinor}{\an2}{\1a&HFF&\2a&HFF&\3a&HFF&}Source\N{\rMajor}{\an2}{\xshad-4\yshad6\blur2.5}{\1a&HFF&\2a&HFF&\3a&HFF&}Translation`) ||
- !strings.Contains(string(data), `{\rMinor}{\an2}{\blur0\shad0}Source\N{\rMajor}{\an2}{\xshad-4\yshad6\blur2.5}{\blur0\shad0}Translation`) {
- t.Fatalf("subtitle roles or shadow reset order are wrong: %s", data)
- }
+ assertASSLayers(t, string(data),
+ `{\rMinor}{\an2}{\1a&HFF&\2a&HFF&\3a&HFF&}Source\N{\rMajor}{\an2}{\xshad-4\yshad6\blur2.5}{\1a&HFF&\2a&HFF&\3a&HFF&}Translation`,
+ `{\rMinor}{\an2}{\blur0\shad0}Source\N{\rMajor}{\an2}{\xshad-4\yshad6\blur2.5}{\blur0\shad0}Translation`)
})
}
}
@@ -478,3 +474,22 @@ func TestVerticalAssSplitsLongChineseAcrossTime(t *testing.T) {
t.Fatalf("long vertical Chinese subtitle should be split across time, not stacked with line breaks: %s", ass)
}
}
+
+// Check both shadow and foreground passes, including role reset and tag order.
+func assertASSLayers(t *testing.T, ass, shadow, foreground string) {
+ t.Helper()
+ var lines [][]string
+ for _, line := range strings.Split(ass, "\n") {
+ if strings.HasPrefix(line, "Dialogue:") {
+ lines = append(lines, strings.SplitN(line, ",", 10))
+ }
+ }
+ if len(lines) != 2 {
+ t.Fatalf("expected shadow and foreground dialogues: %s", ass)
+ }
+ for i, text := range []string{shadow, foreground} {
+ if len(lines[i]) != 10 || lines[i][0] != fmt.Sprintf("Dialogue: %d", i) || lines[i][9] != text {
+ t.Fatalf("layer %d has incorrect subtitle roles or tags: %v", i, lines[i])
+ }
+ }
+}
diff --git a/runtime/krillinai/internal/service/translation_exhaustion_test.go b/runtime/krillinai/internal/service/translation_exhaustion_test.go
index bc8e51d8..ff9b6cad 100644
--- a/runtime/krillinai/internal/service/translation_exhaustion_test.go
+++ b/runtime/krillinai/internal/service/translation_exhaustion_test.go
@@ -41,7 +41,7 @@ func TestBatchTranslateSrtBlocksKeepsOriginalAfterReviewAndRepairExhaustion(t *t
return "invalid-json", nil
}
return `{"accepted_ids":[],"reason":"一本书改变了原文的大量藏书。"}`, nil
- case strings.HasPrefix(prompt, "任务:translation_length_split\n"):
+ case strings.HasPrefix(prompt, "任务:translation_length_split\n") || strings.HasPrefix(prompt, "Task: translation_length_split\n"):
splits++
return `{"sentences":[]}`, nil
}
diff --git a/runtime/krillinai/internal/service/youtube_caption_text_test.go b/runtime/krillinai/internal/service/youtube_caption_text_test.go
index da20317d..58c6d9fe 100644
--- a/runtime/krillinai/internal/service/youtube_caption_text_test.go
+++ b/runtime/krillinai/internal/service/youtube_caption_text_test.go
@@ -19,25 +19,32 @@ func TestCleanVttTextDecodesSpeakerMarkersBeforeFiltering(t *testing.T) {
}
}
-func TestWordCaptionsPreserveDemonstratedHesitation(t *testing.T) {
+func TestWordCaptionsPreserveAmbiguousHesitationsAndDeduplicateRollingCues(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "hesitation.vtt")
content := "WEBVTT\n\n00:02:04.000 --> 00:02:06.510\nAnd<00:02:04.080><c> the</c><00:02:04.160><c> second</c><00:02:04.440><c> your</c><00:02:04.520><c> explanation</c><00:02:05.120><c> becomes</c>\n\n00:02:06.520 --> 00:02:12.510\nAnd the second your explanation becomes\nuh\n\n00:02:12.520 --> 00:02:14.350\num\n\n00:02:14.360 --> 00:02:15.680\num\nyou<00:02:14.440><c> know</c><00:02:14.560><c> what</c><00:02:14.680><c> you</c><00:02:14.720><c> need</c><00:02:14.880><c> to</c><00:02:14.959><c> work</c><00:02:15.160><c> on.</c>\n"
- if err := os.WriteFile(path, []byte(content), 0600); err != nil {
- t.Fatal(err)
- }
- words, err := (&YouTubeSubtitleService{}).ExtractWordsFromVtt(path)
- if err != nil {
- t.Fatal(err)
- }
- var text []string
- for _, word := range words {
- text = append(text, word.Text)
- }
- // 两个 um 都有完整时长,缺少短暂滚动 cue 的证据,不能仅按词相同删除。
- want := "And the second your explanation becomes uh um um you know what you need to work on."
- if strings.Join(text, " ") != want {
- t.Fatalf("有实际含义的演示停顿丢失或重复: %q", strings.Join(text, " "))
+ for _, tc := range []struct{ name, timestamp, want string }{
+ {"held cue may be a separate utterance", "00:02:12.520 --> 00:02:14.350", "um um"},
+ {"instantaneous rolling cue", "00:02:14.350 --> 00:02:14.359", "um"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ content := strings.Replace(content, "00:02:12.520 --> 00:02:14.350", tc.timestamp, 1)
+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {
+ t.Fatal(err)
+ }
+ words, err := (&YouTubeSubtitleService{}).ExtractWordsFromVtt(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var text []string
+ for _, word := range words {
+ text = append(text, word.Text)
+ }
+ want := "And the second your explanation becomes uh " + tc.want + " you know what you need to work on."
+ if strings.Join(text, " ") != want {
+ t.Fatalf("有实际含义的演示停顿丢失或重复: %q", strings.Join(text, " "))
+ }
+ })
}
}
diff --git a/scripts/build-krillinai.mjs b/scripts/build-krillinai.mjs
index 11aa3292..1e212828 100644
--- a/scripts/build-krillinai.mjs
+++ b/scripts/build-krillinai.mjs
@@ -1,4 +1,3 @@
-import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
chmodSync,
@@ -6,15 +5,19 @@ import {
existsSync,
mkdirSync,
readFileSync,
- readdirSync,
renameSync,
rmSync,
- statSync,
writeFileSync
} from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { downloadGoModules } from './download-go-modules.mjs';
+import {
+ assertKrillinBuildIdentity,
+ hashKrillinFile as hashFile,
+ krillinBuildIdentity,
+ verifyKrillinBuild
+} from './krillinai-build-contract.mjs';
const scriptPath = fileURLToPath(import.meta.url);
const rootDir = resolve(dirname(scriptPath), '..');
@@ -41,13 +44,8 @@ const artifactDir = join(outputRoot, 'artifacts');
const executableSuffix = targetPlatform === 'win32' ? '.exe' : '';
const version = process.env.OPENCREATOR_VERSION?.trim()
|| JSON.parse(readFileSync(join(rootDir, 'apps', 'desktop', 'package.json'), 'utf8')).version;
-const sourceCommit = gitOutput(['rev-parse', 'HEAD']) || 'unknown';
-const sourceSha256 = hashSourceTree(sourceRoot);
-const buildRecipeSha256 = createHash('sha256')
- .update(readFileSync(scriptPath))
- .update('\0')
- .update(readFileSync(join(rootDir, 'scripts', 'download-go-modules.mjs')))
- .digest('hex');
+const identityOptions = { rootDir, platform: targetPlatform, arch: targetArch, version };
+const identity = krillinBuildIdentity(identityOptions);
const testOnly = process.argv.includes('--test-only');
const runTests = testOnly || process.argv.includes('--test');
const targets = [
@@ -77,6 +75,7 @@ if (
process.exit(0);
}
+rmSync(manifestPath, { force: true });
mkdirSync(binDir, { recursive: true });
mkdirSync(artifactDir, { recursive: true });
if (!runTests) prepareGoModules(targetGoEnvironment());
@@ -127,44 +126,22 @@ for (const targetBinary of targets) {
const manifest = {
version: 1,
component: 'opencreator-krillinai',
- componentVersion: version,
- sourceCommit,
- sourceSha256,
- buildRecipeSha256,
- platform: targetPlatform,
- arch: targetArch,
+ ...identity,
goVersion: commandOutput('go', ['version']),
buildVcs: false,
binaries
};
+// Never label a binary with a source snapshot that changed during compilation.
+assertKrillinBuildIdentity(identity, krillinBuildIdentity(identityOptions));
writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
console.log(JSON.stringify({ ok: true, reused: false, outputRoot, binaries }));
function canReuseBuild(path) {
if (!existsSync(path)) return false;
try {
- const manifest = JSON.parse(readFileSync(path, 'utf8'));
- if (
- manifest.version !== 1
- || manifest.component !== 'opencreator-krillinai'
- || manifest.componentVersion !== version
- || manifest.sourceCommit !== sourceCommit
- || manifest.sourceSha256 !== sourceSha256
- || manifest.buildRecipeSha256 !== buildRecipeSha256
- || manifest.platform !== targetPlatform
- || manifest.arch !== targetArch
- || manifest.buildVcs !== false
- ) {
- return false;
- }
- return Object.values(manifest.binaries ?? {}).every(binary => {
- const path = resolve(outputRoot, binary.path);
- const artifact = resolve(outputRoot, binary.artifact);
- return existsSync(path)
- && existsSync(artifact)
- && hashFile(path) === binary.sha256
- && hashFile(artifact) === binary.sha256;
- }) && Object.keys(manifest.binaries ?? {}).length === targets.length;
+ verifyKrillinBuild(outputRoot, identity);
+ assertKrillinBuildIdentity(identity, krillinBuildIdentity(identityOptions));
+ return true;
} catch {
return false;
}
@@ -223,56 +200,6 @@ function isNativeTarget() {
&& targetArch === normalizeArch(process.arch);
}
-function hashSourceTree(root) {
- const digest = createHash('sha256');
- for (const path of listSourceFiles(root)) {
- const relativePath = relative(root, path).replaceAll('\\', '/');
- digest.update(relativePath).update('\0');
- digest.update(readFileSync(path)).update('\0');
- }
- return digest.digest('hex');
-}
-
-function listSourceFiles(root) {
- const files = [];
- visit(root);
- return files.sort();
-
- function visit(current) {
- for (const entry of readdirSync(current, { withFileTypes: true })) {
- if (
- entry.name === '.git'
- || entry.name === 'build'
- || entry.name === 'dist'
- || entry.name === '.tmp'
- || entry.name === 'bin'
- || entry.name === 'models'
- || entry.name === 'uploads'
- || entry.name === '.DS_Store'
- || entry.name.endsWith('.log')
- || (current === join(root, 'config') && entry.name === 'config.toml')
- ) {
- continue;
- }
- const path = join(current, entry.name);
- if (entry.isDirectory()) visit(path);
- else if (entry.isFile()) files.push(path);
- }
- }
-}
-
-function hashFile(path) {
- return createHash('sha256').update(readFileSync(path)).digest('hex');
-}
-
-function gitOutput(args) {
- try {
- return commandOutput('git', args, rootDir);
- } catch {
- return '';
- }
-}
-
function commandOutput(command, args, cwd = rootDir) {
return execFileSync(command, args, {
cwd,
diff --git a/scripts/krillinai-build-contract.mjs b/scripts/krillinai-build-contract.mjs
new file mode 100644
index 00000000..82da7f2b
--- /dev/null
+++ b/scripts/krillinai-build-contract.mjs
@@ -0,0 +1,96 @@
+import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { isAbsolute, join, relative, resolve, sep } from 'node:path';
+
+const binaryNames = ['krillinai-cli', 'krillinai-server'];
+const identityFields = [
+ 'componentVersion', 'sourceCommit', 'sourceSha256', 'buildRecipeSha256', 'platform', 'arch'
+];
+
+export function krillinBuildIdentity({ rootDir, platform, arch, version }) {
+ let sourceCommit = 'unknown';
+ try {
+ sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: rootDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']
+ }).trim();
+ } catch { /* Source archives may not include Git metadata. */ }
+ const recipe = createHash('sha256');
+ for (const path of ['scripts/build-krillinai.mjs', 'scripts/download-go-modules.mjs', 'scripts/krillinai-build-contract.mjs']) {
+ recipe.update(path).update('\0').update(readFileSync(join(rootDir, path))).update('\0');
+ }
+ return {
+ componentVersion: version ?? JSON.parse(readFileSync(join(rootDir, 'apps/desktop/package.json'), 'utf8')).version,
+ sourceCommit,
+ sourceSha256: hashKrillinSource(join(rootDir, 'runtime/krillinai')),
+ buildRecipeSha256: recipe.digest('hex'),
+ platform,
+ arch
+ };
+}
+
+export function assertKrillinBuildIdentity(actual, expected) {
+ for (const field of identityFields) {
+ if (actual?.[field] !== expected[field]) {
+ throw new Error(`KrillinAI build does not match current source/target: ${field}; rebuild required`);
+ }
+ }
+}
+
+export function verifyKrillinBuild(buildRoot, expected) {
+ const manifest = JSON.parse(readFileSync(join(buildRoot, 'manifest.json'), 'utf8'));
+ assertKrillinBuildIdentity(manifest, expected);
+ if (manifest.version !== 1 || manifest.component !== 'opencreator-krillinai' || manifest.buildVcs !== false
+ || Object.keys(manifest.binaries ?? {}).sort().join(',') !== binaryNames.join(',')) {
+ throw new Error('KrillinAI build manifest is invalid');
+ }
+ for (const name of binaryNames) {
+ const binary = manifest.binaries[name];
+ if (!/^[a-f0-9]{64}$/.test(binary?.sha256 ?? '')) {
+ throw new Error(`KrillinAI build manifest is missing ${name}`);
+ }
+ for (const path of [binary.path, binary.artifact]) {
+ const absolute = resolveBuildPath(buildRoot, path);
+ if (!statSync(absolute).isFile() || hashKrillinFile(absolute) !== binary.sha256) {
+ throw new Error(`KrillinAI build binary hash mismatch: ${name}`);
+ }
+ }
+ }
+ return manifest;
+}
+
+export function resolveBuildPath(root, path) {
+ if (typeof path !== 'string' || !path || isAbsolute(path)) throw new Error('Invalid KrillinAI build path');
+ const absolute = resolve(root, path);
+ const inside = relative(resolve(root), absolute);
+ if (!inside || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
+ throw new Error('KrillinAI build path escapes its root');
+ }
+ return absolute;
+}
+
+export function hashKrillinFile(path) {
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
+}
+
+export function hashKrillinSource(root) {
+ const files = [];
+ visit(root);
+ const digest = createHash('sha256');
+ for (const path of files.sort()) {
+ digest.update(relative(root, path).replaceAll('\\', '/')).update('\0');
+ digest.update(readFileSync(path)).update('\0');
+ }
+ return digest.digest('hex');
+
+ function visit(current) {
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
+ if (['.git', 'build', 'dist', '.tmp', 'bin', 'models', 'uploads', '.DS_Store'].includes(entry.name)
+ || entry.name.endsWith('.log')
+ || (current === join(root, 'config') && entry.name === 'config.toml')) continue;
+ const path = join(current, entry.name);
+ if (entry.isDirectory()) visit(path);
+ else if (entry.isFile()) files.push(path);
+ }
+ }
+}
diff --git a/scripts/package-krillinai-release.mjs b/scripts/package-krillinai-release.mjs
index 8e95ec6d..7fdbd561 100644
--- a/scripts/package-krillinai-release.mjs
+++ b/scripts/package-krillinai-release.mjs
@@ -15,6 +15,7 @@ import { tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { krillinReleaseAssetNames } from '../apps/desktop/scripts/release-assets.mjs';
+import { krillinBuildIdentity, verifyKrillinBuild } from './krillinai-build-contract.mjs';
const scriptPath = fileURLToPath(import.meta.url);
const defaultRootDir = resolve(dirname(scriptPath), '..');
@@ -62,7 +63,7 @@ export function packageKrillinRelease(options = {}) {
});
}
- const manifest = readBuildManifest(buildRoot, version, platform, arch);
+ const manifest = verifyKrillinBuild(buildRoot, krillinBuildIdentity({ rootDir, version, platform, arch }));
const assetNames = krillinReleaseAssetNames(version, platform, arch);
const specifications = [
{ assetName: assetNames[0], binaryName: 'krillinai-server' },
@@ -88,6 +89,9 @@ export function packageKrillinRelease(options = {}) {
const executableName = `${specification.binaryName}${executableSuffix}`;
mkdirSync(join(packageRoot, 'config'), { recursive: true });
copyFileSync(source, join(packageRoot, executableName));
+ if (hashFile(join(packageRoot, executableName)) !== binary.sha256) {
+ throw new Error('KrillinAI release binary changed while copying');
+ }
if (platform !== 'win32') {
chmodSync(join(packageRoot, executableName), 0o755);
}
@@ -118,6 +122,7 @@ export function packageKrillinRelease(options = {}) {
return archivePath;
});
+ verifyKrillinBuild(buildRoot, krillinBuildIdentity({ rootDir, version, platform, arch }));
if (process.env.GITHUB_ENV) {
appendFileSync(
process.env.GITHUB_ENV,
@@ -141,34 +146,6 @@ export function packageKrillinRelease(options = {}) {
}
}
-function readBuildManifest(buildRoot, version, platform, arch) {
- const path = join(buildRoot, 'manifest.json');
- if (!existsSync(path)) {
- throw new Error(`KrillinAI build manifest is missing: ${path}`);
- }
- const manifest = JSON.parse(readFileSync(path, 'utf8'));
- if (
- manifest.version !== 1
- || manifest.component !== 'opencreator-krillinai'
- || manifest.componentVersion !== version
- || manifest.platform !== platform
- || manifest.arch !== arch
- || manifest.buildVcs !== false
- ) {
- throw new Error('KrillinAI build manifest does not match the release target');
- }
- for (const name of ['krillinai-server', 'krillinai-cli']) {
- const binary = manifest.binaries?.[name];
- if (
- typeof binary?.path !== 'string'
- || !/^[a-f0-9]{64}$/i.test(binary.sha256 ?? '')
- ) {
- throw new Error(`KrillinAI build manifest is missing ${name}`);
- }
- }
- return manifest;
-}
-
function createArchive({ archivePath, packageName, stagingRoot, windowsZip }) {
if (!windowsZip) {
execFileSync('tar', ['-czf', archivePath, '-C', stagingRoot, packageName], {