Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Check generation downloads before release

Bitticcca7784a2a1
diff --git a/docs/updater.md b/docs/updater.md
index 9088ffb..2924b54 100644
--- a/docs/updater.md
+++ b/docs/updater.md
@@ -11,6 +11,31 @@ marker do not check for updates. Both packaging scripts add this marker only to
the uncompressed folder for local testing, after creating the ZIP. The distributed
ZIP omits the marker, so extracted release builds can check for updates.
+## Pre-release tests
+
+`release.cmd` runs `npm run test:release` after installing dependencies and before
+building any release artifacts. A failed check stops the script, including when
+using `--publish`. Run the same command separately to check without building or
+publishing anything.
+
+The generation URL tests use the app's fresh-install generator and LoRA catalogs.
+They check every model URL, GPU/VRAM download variant, additional conditioning
+file and bundled LoRA, combining duplicate URLs into a single request. Hugging
+Face `blob` links are converted to the same `resolve` links used by the app.
+
+Checks follow redirects and require a successful, nonempty file response rather
+than an HTML page. They use `HEAD` first; when the server does not support it or
+omits the size, they request `bytes=0-0` and cancel after the first streamed chunk.
+Even if the server ignores the range, the response is never read in full or saved.
+Checks run three at a time, with a 20-second timeout per attempt and one retry
+for network failures, timeouts, rate limits or server errors. Internet access is
+required; unavailable files or persistent connection failures block the release.
+
+Add future release checks as `tests/release/**/*.test.ts`. The dedicated
+`vitest.release.config.ts` discovers them automatically. Regular `npm test` runs
+exclude these live checks; the URL probe's local HTTP regression tests run in the
+regular suite as `scripts/release-downloads.test.ts`.
+
## Signing key
The public key is committed in `src-tauri/tauri.conf.json`. The matching private
diff --git a/package.json b/package.json
index 585eaae..0e15631 100644
--- a/package.json
+++ b/package.json
@@ -9,6 +9,7 @@
"build": "tsc -b && vite build",
"preview": "vite preview",
"test": "vitest run",
+ "test:release": "vitest run --config vitest.release.config.ts",
"icons": "node scripts/make-icons.mjs",
"reference-icons": "node scripts/generate-reference-icons.mjs",
"tauri": "tauri"
diff --git a/release.cmd b/release.cmd
index e1972a1..e3df820 100644
--- a/release.cmd
+++ b/release.cmd
@@ -79,9 +79,13 @@ rem after, and kept there afterwards so the build is runnable without unpacking.
set "OUTPUT_DIR=%ARTIFACTS_DIR%\%OUTPUT_STEM%-portable"
echo.
-echo [1/5] Installing locked frontend dependencies...
+echo [1/6] Installing locked frontend dependencies...
call npm ci || goto :fail
+echo.
+echo [2/6] Running pre-release tests...
+call npm run test:release || goto :fail
+
rem `npm run tauri build` - NOT `cargo build --release`. Plain cargo compiles the
rem binary but never runs the Tauri CLI, so the app keeps its dev configuration:
rem it points the webview at the dev server on localhost:1420 instead of the
@@ -89,7 +93,7 @@ rem built frontend. The result launches to ERR_CONNECTION_REFUSED on any machine
rem without a dev server running. The CLI runs the frontend build, embeds dist/
rem into the binary, and produces the installers.
echo.
-echo [2/5] Building the release application and installers...
+echo [3/6] Building the release application and installers...
rem Use the supplied password or an empty one without an interactive prompt.
call npm run tauri build -- --ci || goto :fail
@@ -102,12 +106,12 @@ if not exist "%RELEASE_EXE%" (
rem Guard against silently shipping the dev-mode binary again: a production
rem build embeds the hashed frontend assets, a dev-mode one does not.
echo.
-echo [3/5] Verifying the frontend is embedded...
+echo [4/6] Verifying the frontend is embedded...
powershell.exe -NoProfile -NonInteractive -Command "$ErrorActionPreference='Stop'; $asset=(Get-ChildItem -LiteralPath (Join-Path $env:ROOT_DIR 'dist\assets') -Filter '*.js' | Select-Object -First 1).BaseName; if (-not $asset) { Write-Host 'ERROR: no built frontend found in dist/assets.'; exit 1 }; $bytes=[IO.File]::ReadAllBytes($env:RELEASE_EXE); $text=[Text.Encoding]::ASCII.GetString($bytes); if ($text.Contains($asset)) { Write-Host (' OK - ' + $asset + ' is embedded in the executable.'); exit 0 }; Write-Host ''; Write-Host 'ERROR: the executable does not contain the built frontend. It would launch'; Write-Host ' to ERR_CONNECTION_REFUSED. This happens when the binary is built with'; Write-Host ' cargo directly instead of through the Tauri CLI.'; exit 1"
if errorlevel 1 goto :fail
echo.
-echo [4/5] Collecting artifacts...
+echo [5/6] Collecting artifacts...
if not exist "%ARTIFACTS_DIR%" mkdir "%ARTIFACTS_DIR%"
rem Pick the newest bundle of each kind rather than hard-coding Tauri's file
@@ -154,7 +158,7 @@ call :write_readme "%OUTPUT_DIR%\README.txt"
echo Folder: %OUTPUT_STEM%-portable\
echo.
-echo [5/5] Creating the portable archive...
+echo [6/6] Creating the portable archive...
rem Archive without the marker so distributed copies can check for updates.
powershell.exe -NoProfile -NonInteractive -Command "$ErrorActionPreference='Stop'; Compress-Archive -Path (Join-Path $env:OUTPUT_DIR '*') -DestinationPath $env:OUTPUT_ZIP -CompressionLevel Optimal -Force" || goto :fail
rem Disable updates only in the unpacked folder used for local testing.
@@ -185,6 +189,7 @@ exit /b 0
:help
echo Usage: release.cmd [--publish]
+echo Run pre-release tests before building; a failed test stops the release.
echo Build signed installers, updater manifest and portable ZIP.
echo --publish uploads a draft to GitHub, then publishes it as latest.
echo Requires gh auth login and a pushed version tag matching this commit.
diff --git a/scripts/release-downloads.test.ts b/scripts/release-downloads.test.ts
new file mode 100644
index 0000000..6863997
--- /dev/null
+++ b/scripts/release-downloads.test.ts
@@ -0,0 +1,140 @@
+import { createServer, type IncomingMessage, type ServerResponse, type Server } from 'node:http';
+import { once } from 'node:events';
+import { afterEach, expect, it } from 'vitest';
+import { createGeneratorTemplate } from '../src/lib/settings';
+import { checkDownloadUrl, generationDownloads } from './release-downloads';
+
+const servers: Server[] = [];
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map(async (server) => {
+ const closed = new Promise<void>((resolve) => server.close(() => resolve()));
+ server.closeAllConnections();
+ await closed;
+ }));
+});
+
+async function serve(handler: (request: IncomingMessage, response: ServerResponse) => void) {
+ const server = createServer(handler);
+ servers.push(server);
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test server address');
+ return `http://127.0.0.1:${address.port}/file`;
+}
+
+it('follows redirects and checks large files using HEAD without a GET', async () => {
+ const methods: string[] = [];
+ const url = await serve((request, response) => {
+ methods.push(request.method!);
+ if (request.url === '/redirect') response.writeHead(302, { Location: '/file' });
+ else response.writeHead(200, { 'Content-Length': '15000000000', 'Content-Type': 'application/octet-stream' });
+ response.end();
+ });
+ await checkDownloadUrl(url.replace('/file', '/redirect'));
+ expect(methods).toEqual(['HEAD', 'HEAD']);
+});
+
+it.each([
+ [404, {}, 'HTTP 404'],
+ [403, {}, 'HTTP 403'],
+ [200, { 'Content-Length': '100', 'Content-Type': 'text/html' }, 'HTML page'],
+ [200, { 'Content-Length': '0' }, 'empty file'],
+] as const)('rejects inaccessible, HTML and empty files (%s)', async (status, headers, message) => {
+ let requests = 0;
+ const url = await serve((_request, response) => {
+ requests++;
+ response.writeHead(status, headers);
+ response.end();
+ });
+ await expect(checkDownloadUrl(url)).rejects.toThrow(message);
+ expect(requests).toBe(1);
+});
+
+it.each([405, 501, 200])('requests one byte when HEAD is unsupported or has no size (%s)', async (headStatus) => {
+ const requests: Array<[string, string | undefined]> = [];
+ const url = await serve((request, response) => {
+ requests.push([request.method!, request.headers.range]);
+ if (request.method === 'HEAD') { response.writeHead(headStatus); response.end(); }
+ else {
+ response.writeHead(206, { 'Content-Range': 'bytes 0-0/15000000000', 'Content-Length': '1' });
+ response.end('x');
+ }
+ });
+ await checkDownloadUrl(url);
+ expect(requests).toEqual([['HEAD', undefined], ['GET', 'bytes=0-0']]);
+});
+
+it('cancels a streaming response when the server ignores Range', async () => {
+ let sent = 0;
+ let markClosed!: () => void;
+ const closed = new Promise<void>((resolve) => { markClosed = resolve; });
+ const url = await serve((request, response) => {
+ if (request.method === 'HEAD') { response.writeHead(405); response.end(); return; }
+ response.writeHead(200, { 'Content-Length': '15000000000' });
+ const send = () => { sent += 1024; response.write(Buffer.alloc(1024)); };
+ send();
+ const timer = setInterval(send, 10);
+ response.on('close', () => { clearInterval(timer); markClosed(); });
+ });
+ await checkDownloadUrl(url);
+ await closed;
+ expect(sent).toBeGreaterThan(0);
+ expect(sent).toBeLessThan(15_000_000_000);
+});
+
+it('rejects an empty streamed response even when the size is unknown', async () => {
+ const url = await serve((_request, response) => { response.writeHead(200); response.end(); });
+ await expect(checkDownloadUrl(url)).rejects.toThrow('empty file');
+});
+
+it.each([429, 503])('retries a transient HTTP error once (%s)', async (status) => {
+ let requests = 0;
+ const url = await serve((_request, response) => {
+ requests++;
+ response.writeHead(requests === 1 ? status : 200, { 'Content-Length': '1024' });
+ response.end();
+ });
+ await checkDownloadUrl(url, { retryDelayMs: 0 });
+ expect(requests).toBe(2);
+});
+
+it('blocks a release when a server error persists after the retry', async () => {
+ let requests = 0;
+ const url = await serve((_request, response) => {
+ requests++;
+ response.writeHead(503);
+ response.end();
+ });
+ await expect(checkDownloadUrl(url, { retryDelayMs: 0 })).rejects.toThrow(`${url}: HTTP 503`);
+ expect(requests).toBe(2);
+});
+
+it('fails with the URL after bounded timeouts instead of hanging a release', async () => {
+ const url = await serve(() => {});
+ await expect(checkDownloadUrl(url, { timeoutMs: 30, retryDelayMs: 0 })).rejects.toThrow(`${url}: Timed out`);
+});
+
+it('collects all variants, conditioning files and LoRAs, deduplicating normalized URLs', () => {
+ const template = createGeneratorTemplate('Fixture');
+ template.paths.transformer = 'https://huggingface.co/owner/model/blob/main/model.safetensors';
+ template.sources = { transformer: [
+ { url: template.paths.transformer.replace('/blob/', '/resolve/'), gpuModel: '', minVramGb: 24 },
+ { url: 'https://example.com/small.safetensors', gpuModel: '', minVramGb: 0 },
+ ] };
+ template.additionalSafetensors = [{ id: 'conditioning', name: 'Conditioning', url: 'https://example.com/conditioning.safetensors' }];
+ template.loras = [{ loraId: 'adapter', enabled: false, strength: 0 }];
+ const loras = [
+ { id: 'adapter', name: 'Adapter', path: '', url: 'https://example.com/adapter.safetensors' },
+ { id: 'optional', name: 'Optional', path: '', url: 'https://example.com/optional.safetensors' },
+ ];
+ const downloads = generationDownloads([template], loras);
+ expect(downloads.map(({ url }) => url)).toEqual([
+ template.paths.transformer.replace('/blob/', '/resolve/'),
+ 'https://example.com/small.safetensors',
+ 'https://example.com/conditioning.safetensors',
+ loras[0].url, loras[1].url,
+ ]);
+ expect(downloads[0].labels).toContain('transformer variant');
+ expect(() => generationDownloads([template], [])).toThrow('missing bundled LoRA URL');
+});
diff --git a/scripts/release-downloads.ts b/scripts/release-downloads.ts
new file mode 100644
index 0000000..3965805
--- /dev/null
+++ b/scripts/release-downloads.ts
@@ -0,0 +1,105 @@
+import type { GeneratorTemplate } from "../src/lib/settings";
+import type { Lora } from "../src/lib/loras";
+
+export function downloadUrl(value: string): string {
+ const url = new URL(value.trim());
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
+ throw new Error(`Expected a public HTTP(S) file URL: ${value}`);
+ }
+ // Match the application's download URL normalization.
+ if (url.hostname === 'huggingface.co') url.pathname = url.pathname.replace('/blob/', '/resolve/');
+ url.hash = '';
+ return url.href;
+}
+
+export function generationDownloads(templates: GeneratorTemplate[], loras: Lora[]) {
+ const downloads = new Map<string, Set<string>>();
+ const add = (value: string, label: string) => {
+ const url = downloadUrl(value);
+ const labels = downloads.get(url) ?? new Set<string>();
+ labels.add(label);
+ downloads.set(url, labels);
+ };
+ for (const template of templates) {
+ for (const [field, path] of Object.entries(template.paths)) {
+ if (/^https?:\/\//i.test(path.trim())) add(path, `${template.name}: ${field}`);
+ }
+ for (const [field, variants] of Object.entries(template.sources ?? {})) {
+ for (const variant of variants ?? []) add(variant.url, `${template.name}: ${field} variant`);
+ }
+ for (const file of template.additionalSafetensors ?? []) add(file.url, `${template.name}: ${file.name}`);
+ for (const selection of template.loras ?? []) {
+ const lora = loras.find(({ id }) => id === selection.loraId);
+ if (!lora?.url) throw new Error(`${template.name}: missing bundled LoRA URL for ${selection.loraId}`);
+ add(lora.url, `${template.name}: ${lora.name}`);
+ }
+ }
+ // Also cover adapters offered in the library, even when no template enables them yet.
+ for (const lora of loras) if (lora.url) add(lora.url, `LoRA: ${lora.name}`);
+ return [...downloads].map(([url, labels]) => ({ url, labels: [...labels].join('; ') }));
+}
+
+class ProbeError extends Error {
+ constructor(message: string, readonly retryable = false) { super(message); }
+}
+
+function checkHeaders(response: Response) {
+ if (!response.ok) {
+ throw new ProbeError(`HTTP ${response.status}`, response.status === 429 || response.status >= 500);
+ }
+ const type = response.headers.get('content-type') ?? '';
+ if (/text\/html|application\/xhtml\+xml/i.test(type)) throw new ProbeError('URL returned an HTML page instead of a file');
+ const size = response.headers.get('content-length');
+ if (size !== null && Number(size) === 0) throw new ProbeError('URL returned an empty file');
+}
+
+async function probeOnce(url: string, timeoutMs: number) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const head = await fetch(url, { method: 'HEAD', redirect: 'follow', signal: controller.signal });
+ try {
+ if (head.status !== 405 && head.status !== 501) {
+ checkHeaders(head);
+ if (Number(head.headers.get('content-length')) > 0) return;
+ }
+ } finally {
+ await head.body?.cancel();
+ }
+ // HEAD can be unsupported or omit the length. Never buffer a full response,
+ // including when a server ignores Range and returns HTTP 200.
+ const response = await fetch(url, {
+ headers: { Range: 'bytes=0-0', 'Accept-Encoding': 'identity' },
+ redirect: 'follow', signal: controller.signal,
+ });
+ const reader = response.body?.getReader();
+ try {
+ checkHeaders(response);
+ const first = await reader?.read();
+ if (!first?.value?.byteLength) throw new ProbeError('URL returned an empty file');
+ } finally {
+ await reader?.cancel();
+ }
+ } catch (error) {
+ if (controller.signal.aborted) throw new ProbeError(`Timed out after ${timeoutMs} ms`, true);
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ controller.abort();
+ }
+}
+
+export async function checkDownloadUrl(value: string, { timeoutMs = 20_000, retryDelayMs = 500 } = {}) {
+ const url = downloadUrl(value);
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ await probeOnce(url, timeoutMs);
+ return;
+ } catch (error) {
+ if (attempt === 1 || (error instanceof ProbeError && !error.retryable)) {
+ throw new Error(`${url}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
+ }
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
+ }
+ }
+}
diff --git a/tests/release/generation-urls.test.ts b/tests/release/generation-urls.test.ts
new file mode 100644
index 0000000..f42ec29
--- /dev/null
+++ b/tests/release/generation-urls.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it, vi } from "vitest";
+import { loadGeneratorTemplateSettings } from "../../src/lib/settings";
+import { loadLoras } from "../../src/lib/loras";
+import { checkDownloadUrl, generationDownloads } from "../../scripts/release-downloads";
+
+// Read the same fresh-install catalog as the app, independent of machine settings.
+vi.stubGlobal('localStorage', { getItem: () => null });
+const downloads = generationDownloads(loadGeneratorTemplateSettings().templates, loadLoras());
+vi.unstubAllGlobals();
+
+it('has bundled generation downloads to check', () => {
+ expect(downloads.length).toBeGreaterThan(0);
+});
+
+describe('public generation files', () => {
+ it.concurrent.each(downloads)('$labels — $url', async ({ url }) => {
+ await checkDownloadUrl(url);
+ });
+});
diff --git a/tsconfig.node.json b/tsconfig.node.json
index 0150624..115ae92 100644
--- a/tsconfig.node.json
+++ b/tsconfig.node.json
@@ -8,5 +8,5 @@
"allowImportingTsExtensions": true,
"noEmit": true
},
- "include": ["vite.config.ts"]
+ "include": ["vite.config.ts", "vitest.release.config.ts"]
}
diff --git a/vite.config.ts b/vite.config.ts
index aa84bc7..c092ccf 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -14,6 +14,5 @@ export default defineConfig({
},
envPrefix: ["VITE_", "TAURI_ENV_*"],
build: { target: ["es2021", "chrome100", "safari13"] },
- test: { exclude: ["**/node_modules/**", "**/dist/**", "**/.claude/worktrees/**"] },
+ test: { exclude: ["**/node_modules/**", "**/dist/**", "**/.claude/worktrees/**", "tests/release/**"] },
});
-
diff --git a/vitest.release.config.ts b/vitest.release.config.ts
new file mode 100644
index 0000000..17007cd
--- /dev/null
+++ b/vitest.release.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["tests/release/**/*.test.ts"],
+ environment: "node",
+ testTimeout: 50_000,
+ maxConcurrency: 3,
+ fileParallelism: false,
+ reporters: ["verbose"],
+ },
+});