mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
* fix(api): correct format/filename/container handling across tool routes Found during a comprehensive QA sweep exercising every tool against its full accepted-format matrix: - watermark-image, compose: preserve the requested output format and a matching download filename/extension instead of always emitting the source format - compose: crop oversized overlays to the visible base area instead of crashing Sharp's composite, and reject only overlays fully outside the base image instead of any oversized one - compare, vectorize: switch to the shared image input handler so filenames and formats like .svgz/.tga/RAW survive validation instead of being rejected pre-processing - tool-factory, images-to-video: normalize frames through Sharp before handing them to FFmpeg, fixing GIF/AVIF/RAW image-to-video jobs that previously failed or hung - media-tool, replace-audio, embed-subtitles: fix legacy container MIME/codec handling for MPEG sources and subtitle remux cases - files: expand download MIME mapping for text/data/document/video/audio outputs that were falling back to a generic content type - convert-document/presentation/spreadsheet: same-format conversions now return the original validated file instead of erroring or producing corrupt tiny output Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(web): dropzone a11y, stale localStorage getter, dead code - dropzone: stop making the whole drop-zone section clickable/focusable. A section acting as an interactive element around a real upload button is a nested-interactive-element anti-pattern that confuses screen readers; drag-and-drop doesn't need focus semantics, only the button fallback does. Keeps that button semantic and keyboard-reachable. Updates the two e2e call sites that clicked the section directly. - api, use-auth: read through window.localStorage via the existing API storage helper instead of the bare global, which resolves to Node's experimental localStorage getter under Vitest and threw - find-duplicates-settings, info-settings, login-page: remove dead code (unused zip-download handler, a stale mount-only effect dependency that left cached info stuck at reused indices, an unused response variable) Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(i18n): pt-BR, zh-CN, zh-TW were silently falling back to English The locale loader looked up dynamic-import exports by the raw locale code (mod["pt-BR"], mod["zh-CN"], mod["zh-TW"]), but those three modules export camelCased bindings (ptBR, zhCN, zhTW) since identifiers can't contain hyphens. The lookup returned undefined and every consumer silently fell back to English for these three locales. Replaces the generic lookup with explicit per-locale loaders so the mapping can't drift out of sync again. Also updates the dropzone helper copy across all 21 locales to match the drag-only dropzone wording from the previous commit. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(docs): clear build warnings in the VitePress site - config.mts: add an onwarn handler for the @vueuse INVALID_ANNOTATION warnings emitted during the docs build - deployment.md: the caddyfile code fence language isn't a shiki grammar VitePress ships with, so it warned on every build; use txt instead Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * test(qa): update QA harness for the drag-only dropzone and regen metadata - api-sweep, qa-helpers, verify-ai: add JSON-body tools, multi-input secondary fixtures, async polling for slow valid jobs, 501 FEATURE_NOT_INSTALLED skip handling, and safer per-tool settings - input-preview, pipeline-ui specs: update upload flow for the drag-only dropzone surface - add tests/fixtures/data/valid/chart.json, a valid chart fixture the updated helpers route to - regenerate tools-meta.json against current TOOLS[] Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(security): close a login timing side-channel, harden zip-slip tests Found during a black-box security sweep of the real auth-enabled production container: a nonexistent username returned 401 in ~3-10ms, while a wrong password for a real user took ~35-42ms, because scrypt verification only ran when a user row existed. That timing gap lets an attacker enumerate valid usernames without ever guessing a password. Now runs verification against a cached dummy hash on the unknown-user path too, so both cases cost the same regardless of outcome. extract-zip already had a relative-traversal regression test (../evil.txt), but its absolute-path rejection branches (name.startsWith("/") / startsWith("\\")) had none. Added the three missing cases: deep relative traversal, absolute Unix path, and Windows-style absolute path. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * test(qa): add UI-driven AI bundle install scripts QA_PROMPT.md's Phase 2 requires installing AI models the way a user does -- through the UI, on demand from HuggingFace -- and treats the curl-based admin install endpoint as fallback-only. Nothing in the harness actually drove that flow; tests/qa/seed-ai-models.sh installs via docker exec + pip, which is further from a real user than even the API fallback. install-ai-bundles-ui.mts logs in, opens Settings > AI Features, screenshots the pre-install state, clicks Install All, and screenshots progress -- then exits, since installs continue server-side once triggered. verify-ai-install-complete.mts polls bundle status, screenshots the completed state, and runs one real tool per installed bundle to prove the freshly-downloaded model actually executes. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(qa): correct the apiToolPath import in the AI verify script Dynamic import of the package name failed under tsx's module resolution from apps/api's node_modules context; use the same relative-path import api-sweep.mts already uses successfully. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(web): correct AI bundle size estimates shown before install Measured real downloads during GPU-node QA verification: photo-restoration pulls ~4.4GB (was advertised as 800MB-1GB, off by 4-5x) and ocr pulls ~5.5GB (was advertised as 3-4GB). Both estimates only accounted for model weights, not the pip dependencies (torch/paddle) that come down with them. Updated to reflect actual total download size, since that's what a user deciding whether they have the disk/bandwidth actually needs to know. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(web): make desktop Settings reachable when auth is disabled AvatarDropdown (the only desktop entry point to Settings) was gated behind `!isMobile && authEnabled`. With AUTH_ENABLED=false the synthetic anonymous admin user should have full Settings access per how auth.ts documents this mode -- and the mobile bottom nav already worked this way, showing Settings unconditionally. Desktop just had a stray extra gate the component doesn't need: AvatarDropdown already resolves its own username internally (falling back to "admin") and reads authEnabled itself where it actually matters (hiding the Logout button). Removed the outer gate; verified end-to-end against a fresh AUTH_ENABLED=false instance -- avatar now renders, Settings opens, shows the anonymous/Admin identity correctly. Also documents (not changes) a related finding in install_feature.py: detect_arch() always resolves amd64 hosts to the GPU-bundled archive variant regardless of actual GPU presence, since no CPU-only amd64 archive is published to the bundle repo yet. Left as a code comment rather than a behavior change, since requesting an unpublished archive key would hard-fail installs entirely -- worse than the current oversized-but-working download. Full detail in the QA report. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(ai): stop logging expected dispatcher reloads as crashes After each AI bundle install the Python dispatcher reloads because the venv changed, and after every app shutdown it's SIGTERMed. Both took the close handler's `code !== 0` branch (SIGTERM makes the exit code null), so they were counted as crashes -- producing an alarming "crash" line in the logs and a pointless ~1s recovery backoff after each of 7 installs. A `stopping` flag set in shutdown() lets the close handler tell an intentional stop apart from a real crash. The request-timeout kill path deliberately does not set it, so a genuinely hung script still records a crash and the 5-in-60s permanent-disable threshold is untouched. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(api): return a clean message when content-aware resize times out Carving a very high-resolution image down to a tiny target could exceed the caire subprocess timeout, and the raw error forwarded to the user was caire's terminal output -- ANSI color codes and progress-spinner control characters -- instead of anything actionable. Now: the timeout path throws a clear "timed out; try a smaller image or larger target" message (keeping the raw stderr as `cause` for server logs); friendlyError() strips ANSI/control chars centrally so any subprocess dump surfaced through the shared sanitizer is plain text; and the content-aware-resize route (a custom route that bypassed the sanitizer) now routes its error paths through friendlyError like every other tool. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(ai): stop bundle installs from exhausting host disk Installing an AI bundle on a tight-disk host could push the root filesystem to zero bytes free after the preflight check had already passed. Two root causes: - move_tree used copytree+rmtree, so during the move the extracted payload existed in both staging and the venv at once -- a full transient doubling on disk. Rewrote it to rename entries (a cheap metadata op on the same filesystem, no copy), falling back to a copy only across filesystems. - the preflight budget used the manifest's extractedSize verbatim, which is 0 for several archives, collapsing the estimate to just the compressed size. Added a conservative fallback (3x compressed) so a missing value can't under-reserve. Also added a real-on-disk re-check immediately before the first destructive venv write (measuring the actual extracted payload and whether the move needs extra space for a cross-filesystem copy), which also now covers the offline-import path that previously skipped the disk check entirely; wrapped the moves so an out-of-space failure returns a clean actionable error instead of a traceback; and made the disk check resolve the nearest existing ancestor so it never throws on a not-yet-created venv path. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * feat(web): show the real per-arch AI bundle download size The bundle cards and install prompt showed a hardcoded, architecture-blind estimatedSize string. That's misleading: amd64 hosts always pull the CUDA-inclusive archive (there's no CPU-only amd64 variant published), so a bundle labelled "1-2 GB" can actually download several times that, while arm64 pulls a much smaller archive for the same label. The manifest already carries the real per-arch compressedSize (and extractedSize where measured), so surface those: a new optional downloadBytes/installedBytes on FeatureBundleState, populated in getFeatureStates() for this host's arch (resolver mirrors install_feature.py detect_arch), shown by the UI when present with estimatedSize kept as the fallback label. Also nudged upscale-enhance's fallback string (4-5 -> 5-6 GB) to match its real compressed size, consistent with the earlier photo-restoration/ocr fixes. Fields are optional so demo/mock and existing tests stay compiling; the manifest's extractedSize is 0 for a few archives, which now surfaces as null rather than a bogus 0. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(web): move the AI install queue to the server so it survives tab close Installing multiple bundles could silently lose all but the first. The server rejected a concurrent install with 409, so the client worked around it by queueing the rest in browser-local state and only POSTing each once it saw the previous finish. A single POSTed install is durable (the installer child is detached from the request), but a queued one had zero server footprint -- close the tab mid-queue and those installs vanished with no error, while the UI still showed them "Queued". The client "mutex" didn't even serialize: the queued bundles' local waits all resolved at once and raced into concurrent POSTs that 409'd each other. Now the queue lives on the server (a small in-memory FIFO leaf module). The install endpoint enqueues instead of 409-ing and returns 202 {jobId, queued}; a pump starts the next bundle when the current one's child exits (and after an offline import releases the lock), all behind the existing venv + file locks, which are unchanged. The client just POSTs every bundle immediately and reflects the server-reported queued/installing status; Install All fires all POSTs and lets the server serialize them, keeping the one-shot retry-on-failure. Adds "queued" to FeatureStatus (the bundle card already rendered that state) and surfaces it from getFeatureStates. In-memory is deliberate: it matches the existing contract (survives a tab close, not a server restart, which already clears the lock on boot). Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG * fix(qa): don't log env-derived credentials in the AI-install script CodeQL flagged clear-text logging of sensitive information: the login status line interpolated the QA base URL and username (both read from the process environment) into a console.log. Replaced with a static message. QA helper only, but it's a real hygiene issue and cleared the high-severity code-scanning alert on the PR. Claude-Session: https://claude.ai/code/session_019fpSXhLGLXWwfyZY2tWhLG
499 lines
18 KiB
TypeScript
499 lines
18 KiB
TypeScript
// Shared helpers for the exhaustive tool QA sweep. Discovery shards import these
|
|
// to upload files, run tools, assert previews render (the user's #1 concern),
|
|
// verify downloads, and capture console/network issues. Designed for the
|
|
// isolated QA container (auth off) on http://localhost:13499.
|
|
|
|
import { execFileSync } from "node:child_process";
|
|
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { expect, type Page } from "@playwright/test";
|
|
|
|
export const REPO_ROOT = path.join(__dirname, "..", "..");
|
|
export const FIXTURES = path.join(REPO_ROOT, "tests", "fixtures");
|
|
|
|
/** Absolute path to a fixture. Accepts current paths and legacy QA aliases. */
|
|
export function fixture(...parts: string[]): string {
|
|
const direct = path.join(FIXTURES, ...parts);
|
|
if (fs.existsSync(direct)) return direct;
|
|
|
|
const [scope, ...rest] = parts;
|
|
const legacyScopes: Record<string, string[]> = {
|
|
content: [path.join("image", "valid"), path.join("document", "valid")],
|
|
formats: [path.join("image", "formats"), path.join("image", "valid")],
|
|
media: [
|
|
path.join("video", "formats"),
|
|
path.join("video", "valid"),
|
|
path.join("audio", "formats"),
|
|
path.join("audio", "valid"),
|
|
],
|
|
documents: [
|
|
path.join("document", "formats"),
|
|
path.join("document", "valid"),
|
|
path.join("document", "edge"),
|
|
path.join("document", "hostile"),
|
|
],
|
|
data: [path.join("data", "valid")],
|
|
};
|
|
|
|
for (const candidateScope of legacyScopes[scope] ?? []) {
|
|
const candidate = path.join(FIXTURES, candidateScope, ...rest);
|
|
if (fs.existsSync(candidate)) return candidate;
|
|
}
|
|
|
|
if (parts.length === 1) {
|
|
const legacyBareScopes = [
|
|
path.join("image", "valid"),
|
|
path.join("image", "edge"),
|
|
path.join("image", "formats"),
|
|
path.join("document", "valid"),
|
|
path.join("document", "formats"),
|
|
path.join("document", "edge"),
|
|
path.join("video", "valid"),
|
|
path.join("video", "formats"),
|
|
path.join("audio", "valid"),
|
|
path.join("audio", "formats"),
|
|
path.join("data", "valid"),
|
|
];
|
|
for (const candidateScope of legacyBareScopes) {
|
|
const candidate = path.join(FIXTURES, candidateScope, parts[0]);
|
|
if (fs.existsSync(candidate)) return candidate;
|
|
}
|
|
}
|
|
|
|
return direct;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tool metadata (generated by extract-tools-meta.mts). Tools route as
|
|
// /:modality/:toolId, so navigation needs each tool's modality.
|
|
// ---------------------------------------------------------------------------
|
|
export interface ToolMeta {
|
|
id: string;
|
|
name: string;
|
|
modality: "image" | "video" | "audio" | "document" | "file";
|
|
acceptedInputs: string[];
|
|
executionHint: "fast" | "long";
|
|
isAI: boolean;
|
|
}
|
|
|
|
export const TOOLS_META: ToolMeta[] = JSON.parse(
|
|
fs.readFileSync(path.join(__dirname, "tools-meta.json"), "utf8"),
|
|
);
|
|
|
|
const TOOL_BY_ID = new Map<string, ToolMeta>(TOOLS_META.map((t) => [t.id, t]));
|
|
|
|
export function toolMeta(toolId: string): ToolMeta {
|
|
const m = TOOL_BY_ID.get(toolId);
|
|
if (!m) throw new Error(`Unknown toolId "${toolId}" (not in tools-meta.json)`);
|
|
return m;
|
|
}
|
|
|
|
/** The /:modality/:toolId URL path for a tool. */
|
|
export function toolPath(toolId: string): string {
|
|
const m = toolMeta(toolId);
|
|
return `/${m.modality}/${m.id}`;
|
|
}
|
|
|
|
export type Hint = "fast" | "long" | "ai";
|
|
const HINT_TIMEOUT: Record<Hint, number> = {
|
|
fast: 30_000,
|
|
long: 180_000,
|
|
ai: 600_000,
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Console / network instrument: attach to every page; assert clean at the end.
|
|
// ---------------------------------------------------------------------------
|
|
export interface PageIssues {
|
|
consoleErrors: string[];
|
|
pageErrors: string[];
|
|
failedRequests: string[];
|
|
serverErrors: string[];
|
|
}
|
|
|
|
/** Returns true if no console error / page error / network failure / 5xx seen. */
|
|
export function isClean(i: PageIssues): boolean {
|
|
return (
|
|
i.consoleErrors.length === 0 &&
|
|
i.pageErrors.length === 0 &&
|
|
i.failedRequests.length === 0 &&
|
|
i.serverErrors.length === 0
|
|
);
|
|
}
|
|
|
|
export function issuesSummary(i: PageIssues): string {
|
|
const parts: string[] = [];
|
|
if (i.consoleErrors.length) parts.push(`console: ${i.consoleErrors.join(" | ")}`);
|
|
if (i.pageErrors.length) parts.push(`pageerror: ${i.pageErrors.join(" | ")}`);
|
|
if (i.failedRequests.length) parts.push(`netfail: ${i.failedRequests.join(" | ")}`);
|
|
if (i.serverErrors.length) parts.push(`5xx: ${i.serverErrors.join(" | ")}`);
|
|
return parts.join("\n");
|
|
}
|
|
|
|
// Benign console noise that is not a product bug.
|
|
const CONSOLE_IGNORE = [
|
|
/Download the React DevTools/i,
|
|
/\[vite\]/i,
|
|
/favicon/i,
|
|
/ResizeObserver loop/i,
|
|
];
|
|
|
|
/** Attach listeners that collect issues for the lifetime of the page. */
|
|
export function instrument(page: Page): PageIssues {
|
|
const issues: PageIssues = {
|
|
consoleErrors: [],
|
|
pageErrors: [],
|
|
failedRequests: [],
|
|
serverErrors: [],
|
|
};
|
|
page.on("console", (msg) => {
|
|
if (msg.type() !== "error") return;
|
|
const text = msg.text();
|
|
if (CONSOLE_IGNORE.some((re) => re.test(text))) return;
|
|
issues.consoleErrors.push(text);
|
|
});
|
|
page.on("pageerror", (err) => {
|
|
issues.pageErrors.push(String(err?.message ?? err));
|
|
});
|
|
page.on("requestfailed", (req) => {
|
|
const f = req.failure();
|
|
if (!f) return;
|
|
// ERR_ABORTED is normal for cancelled navigations / superseded requests.
|
|
if (/ERR_ABORTED|net::ERR_ABORTED/.test(f.errorText)) return;
|
|
issues.failedRequests.push(`${req.method()} ${req.url()} ${f.errorText}`);
|
|
});
|
|
page.on("response", (resp) => {
|
|
if (resp.status() >= 500) issues.serverErrors.push(`${resp.status()} ${resp.url()}`);
|
|
});
|
|
return issues;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Navigation / upload / run
|
|
// ---------------------------------------------------------------------------
|
|
export async function gotoTool(page: Page, toolId: string): Promise<void> {
|
|
await page.goto(toolPath(toolId), { waitUntil: "domcontentloaded" });
|
|
}
|
|
|
|
/** Upload one or more files via the dropzone file chooser. */
|
|
export async function uploadFiles(page: Page, files: string | string[]): Promise<void> {
|
|
const arr = Array.isArray(files) ? files : [files];
|
|
const chooserPromise = page.waitForEvent("filechooser");
|
|
const uploadBtn = page.getByRole("button", { name: /upload from computer/i }).first();
|
|
if (await uploadBtn.isVisible({ timeout: 3_000 }).catch(() => false)) {
|
|
await uploadBtn.click();
|
|
} else {
|
|
await page.locator("[class*='border-dashed']").first().click();
|
|
}
|
|
const chooser = await chooserPromise;
|
|
await chooser.setFiles(arr);
|
|
}
|
|
|
|
/** Set a secondary file input by selector (multi-input tools, e.g. "#compose-overlay-image"). */
|
|
export async function setSecondaryInput(page: Page, selector: string, file: string): Promise<void> {
|
|
await page.locator(selector).setInputFiles(file);
|
|
}
|
|
|
|
/** Click the tool's submit/process button. */
|
|
export async function runTool(page: Page, toolId: string): Promise<void> {
|
|
const submit = page.getByTestId(`${toolId}-submit`);
|
|
await submit.first().waitFor({ state: "visible", timeout: 15_000 });
|
|
await submit.first().click();
|
|
}
|
|
|
|
export interface ResultState {
|
|
ok: boolean;
|
|
error?: string;
|
|
}
|
|
|
|
/**
|
|
* Wait for processing to resolve to either success (a download/result control
|
|
* appears) or a surfaced error. Distinguishes a real error from a slow tool via
|
|
* per-hint timeouts. Never hangs forever.
|
|
*/
|
|
export async function waitForResult(
|
|
page: Page,
|
|
toolId: string,
|
|
hint: Hint = "fast",
|
|
): Promise<ResultState> {
|
|
const timeout = HINT_TIMEOUT[hint];
|
|
const download = page.getByTestId(`${toolId}-download`).first();
|
|
const genericDownload = page.locator("[data-download-button]").first();
|
|
const errorRegion = page
|
|
.locator("[role='alert'], [aria-live='assertive']")
|
|
.filter({ hasText: /error|failed|invalid|unsupported|not supported|too large/i })
|
|
.first();
|
|
|
|
const deadline = Date.now() + timeout;
|
|
while (Date.now() < deadline) {
|
|
if (await download.isVisible().catch(() => false)) return { ok: true };
|
|
if (await genericDownload.isVisible().catch(() => false)) return { ok: true };
|
|
if (await errorRegion.isVisible().catch(() => false)) {
|
|
const error = await errorRegion.innerText().catch(() => "error surfaced");
|
|
return { ok: false, error: error.trim() };
|
|
}
|
|
await page.waitForTimeout(500);
|
|
}
|
|
return { ok: false, error: `timeout after ${timeout}ms (hint=${hint})` };
|
|
}
|
|
|
|
/** Convenience: run + wait. */
|
|
export async function processTool(
|
|
page: Page,
|
|
toolId: string,
|
|
hint: Hint = "fast",
|
|
): Promise<ResultState> {
|
|
await runTool(page, toolId);
|
|
return waitForResult(page, toolId, hint);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Preview oracles (per modality). "Rendered" means actually decoded, not a
|
|
// broken-image placeholder / dead player / "Load failed".
|
|
// ---------------------------------------------------------------------------
|
|
export interface ImgDims {
|
|
w: number;
|
|
h: number;
|
|
}
|
|
|
|
/** Assert an <img> matching alt actually decoded (naturalWidth/Height > 0). */
|
|
export async function assertImageRendered(page: Page, alt: string, label = alt): Promise<ImgDims> {
|
|
const img = page.locator(`img[alt="${alt}"]`).first();
|
|
await expect(img, `${label} image visible`).toBeVisible({ timeout: 15_000 });
|
|
const dims = await img.evaluate((el: HTMLImageElement) => ({
|
|
w: el.naturalWidth,
|
|
h: el.naturalHeight,
|
|
}));
|
|
expect(dims.w, `${label} naturalWidth > 0 (0 means broken image)`).toBeGreaterThan(0);
|
|
expect(dims.h, `${label} naturalHeight > 0`).toBeGreaterThan(0);
|
|
return dims;
|
|
}
|
|
|
|
/** Assert no <img> on the page is a broken placeholder. Catches silent preview failures. */
|
|
export async function assertNoBrokenImages(page: Page): Promise<void> {
|
|
const broken = await page.evaluate(() =>
|
|
Array.from(document.images)
|
|
.filter((im) => im.complete && im.naturalWidth === 0 && !!im.currentSrc)
|
|
.map((im) => im.currentSrc),
|
|
);
|
|
expect(broken, `broken images present: ${broken.join(", ")}`).toHaveLength(0);
|
|
}
|
|
|
|
/** Assert the video player loaded a decodable frame. */
|
|
export async function assertVideoPreview(page: Page): Promise<void> {
|
|
const v = page.getByTestId("media-player-video").first();
|
|
await expect(v, "video player visible").toBeVisible({ timeout: 15_000 });
|
|
await expect
|
|
.poll(async () => v.evaluate((el: HTMLVideoElement) => el.readyState), { timeout: 25_000 })
|
|
.toBeGreaterThanOrEqual(1);
|
|
const vw = await v.evaluate((el: HTMLVideoElement) => el.videoWidth);
|
|
expect(vw, "video has decoded dimensions").toBeGreaterThan(0);
|
|
}
|
|
|
|
/** Assert the audio waveform reached ready state (play control enabled). */
|
|
export async function assertAudioPreview(page: Page): Promise<void> {
|
|
const wf = page.getByTestId("waveform-container").first();
|
|
await expect(wf, "waveform container visible").toBeVisible({ timeout: 15_000 });
|
|
const play = page.getByTestId("waveform-play-pause").first();
|
|
await expect(play, "waveform play control enabled (decoded)").toBeEnabled({ timeout: 25_000 });
|
|
}
|
|
|
|
/** Assert the pdf.js document canvas rendered a non-blank page and did not fail to load. */
|
|
export async function assertDocumentPreview(page: Page): Promise<void> {
|
|
const canvas = page.getByTestId("document-canvas").first();
|
|
await expect(canvas, "document canvas visible").toBeVisible({ timeout: 25_000 });
|
|
await expect(page.locator(".text-destructive"), "no document load error").toHaveCount(0);
|
|
const nonBlank = await canvas.evaluate((c: HTMLCanvasElement) => {
|
|
const ctx = c.getContext("2d");
|
|
if (!ctx || c.width === 0 || c.height === 0) return false;
|
|
const data = ctx.getImageData(0, 0, c.width, c.height).data;
|
|
for (let i = 0; i < data.length; i += 4) {
|
|
if (data[i] !== 255 || data[i + 1] !== 255 || data[i + 2] !== 255) return true;
|
|
}
|
|
return false;
|
|
});
|
|
expect(nonBlank, "document canvas is non-blank").toBe(true);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Download + decode verification (ground truth = the downloaded artifact).
|
|
// ---------------------------------------------------------------------------
|
|
export interface DownloadedFile {
|
|
path: string;
|
|
name: string;
|
|
size: number;
|
|
buf: Buffer;
|
|
}
|
|
|
|
export async function downloadResult(page: Page, toolId: string): Promise<DownloadedFile> {
|
|
const dlPromise = page.waitForEvent("download", { timeout: 30_000 });
|
|
const btn = page.getByTestId(`${toolId}-download`).first();
|
|
if (await btn.isVisible().catch(() => false)) {
|
|
await btn.click();
|
|
} else {
|
|
await page.locator("[data-download-button]").first().click();
|
|
}
|
|
const dl = await dlPromise;
|
|
const name = dl.suggestedFilename();
|
|
const out = path.join(os.tmpdir(), `qa-${toolId}-${process.hrtime.bigint()}-${name}`);
|
|
await dl.saveAs(out);
|
|
const buf = fs.readFileSync(out);
|
|
return { path: out, name, size: buf.length, buf };
|
|
}
|
|
|
|
const MAGIC: Record<string, (b: Buffer) => boolean> = {
|
|
png: (b) => b.length > 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47,
|
|
jpg: (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
|
|
jpeg: (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
|
|
gif: (b) => b.subarray(0, 3).toString("latin1") === "GIF",
|
|
webp: (b) =>
|
|
b.subarray(0, 4).toString("latin1") === "RIFF" &&
|
|
b.subarray(8, 12).toString("latin1") === "WEBP",
|
|
bmp: (b) => b[0] === 0x42 && b[1] === 0x4d,
|
|
tiff: (b) => (b[0] === 0x49 && b[1] === 0x49) || (b[0] === 0x4d && b[1] === 0x4d),
|
|
pdf: (b) => b.subarray(0, 5).toString("latin1") === "%PDF-",
|
|
zip: (b) => b[0] === 0x50 && b[1] === 0x4b,
|
|
avif: (b) => b.subarray(4, 12).toString("latin1").includes("ftyp"),
|
|
heic: (b) => b.subarray(4, 12).toString("latin1").includes("ftyp"),
|
|
ico: (b) => b[0] === 0x00 && b[1] === 0x00 && b[2] === 0x01 && b[3] === 0x00,
|
|
mp4: (b) => b.subarray(4, 8).toString("latin1") === "ftyp",
|
|
mp3: (b) =>
|
|
(b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) || (b[0] === 0xff && (b[1] & 0xe0) === 0xe0),
|
|
wav: (b) =>
|
|
b.subarray(0, 4).toString("latin1") === "RIFF" &&
|
|
b.subarray(8, 12).toString("latin1") === "WAVE",
|
|
flac: (b) => b.subarray(0, 4).toString("latin1") === "fLaC",
|
|
ogg: (b) => b.subarray(0, 4).toString("latin1") === "OggS",
|
|
};
|
|
|
|
/** Best-effort magic-byte check for a downloaded artifact's format. Unknown ext => true. */
|
|
export function magicMatches(buf: Buffer, ext: string): boolean {
|
|
const key = ext.replace(/^\./, "").toLowerCase();
|
|
const fn = MAGIC[key];
|
|
return fn ? fn(buf) : true;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Decode oracles on downloaded bytes (semantic correctness, not DOM).
|
|
// ---------------------------------------------------------------------------
|
|
export interface ImageInfo {
|
|
width: number;
|
|
height: number;
|
|
codec: string;
|
|
pixFmt: string;
|
|
hasAlpha: boolean;
|
|
}
|
|
|
|
function sharpHasAlpha(file: string): boolean {
|
|
try {
|
|
const script = `
|
|
import sharp from "sharp";
|
|
const meta = await sharp(process.argv[1]).metadata();
|
|
console.log(JSON.stringify({ hasAlpha: meta.hasAlpha === true }));
|
|
`;
|
|
const out = execFileSync(process.execPath, ["--input-type=module", "-e", script, file], {
|
|
cwd: path.join(REPO_ROOT, "apps", "api"),
|
|
encoding: "utf8",
|
|
timeout: 20_000,
|
|
});
|
|
return JSON.parse(out).hasAlpha === true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Image dimensions/format/alpha via ffprobe (png/jpg/webp/gif/tiff/bmp/avif/heic/...). */
|
|
export function imageInfo(file: string): ImageInfo {
|
|
const out = execFileSync(
|
|
"ffprobe",
|
|
[
|
|
"-v",
|
|
"quiet",
|
|
"-select_streams",
|
|
"v:0",
|
|
"-show_entries",
|
|
"stream=width,height,codec_name,pix_fmt",
|
|
"-print_format",
|
|
"json",
|
|
file,
|
|
],
|
|
{ encoding: "utf8", timeout: 20_000 },
|
|
);
|
|
const s = (JSON.parse(out).streams ?? [])[0] ?? {};
|
|
const pixFmt: string = s.pix_fmt ?? "";
|
|
const hasAlpha =
|
|
/(rgba|bgra|argb|abgr|ya\d|yuva|gbrap)/i.test(pixFmt) ||
|
|
(s.codec_name === "png" && sharpHasAlpha(file));
|
|
return {
|
|
width: s.width ?? 0,
|
|
height: s.height ?? 0,
|
|
codec: s.codec_name ?? "",
|
|
pixFmt,
|
|
hasAlpha,
|
|
};
|
|
}
|
|
|
|
/** First-frame luma (YAVG 0-255) and saturation (SATAVG 0-255) via ffmpeg signalstats. */
|
|
export function signalStats(file: string): { luma: number; saturation: number } {
|
|
const esc = file.replace(/\\/g, "\\\\").replace(/:/g, "\\:").replace(/'/g, "\\'");
|
|
const out = execFileSync(
|
|
"ffprobe",
|
|
[
|
|
"-v",
|
|
"quiet",
|
|
"-f",
|
|
"lavfi",
|
|
"-i",
|
|
`movie=${esc},signalstats`,
|
|
"-show_entries",
|
|
"frame_tags=lavfi.signalstats.YAVG,lavfi.signalstats.SATAVG",
|
|
"-read_intervals",
|
|
"%+#1",
|
|
"-print_format",
|
|
"json",
|
|
],
|
|
{ encoding: "utf8", timeout: 20_000 },
|
|
);
|
|
const tags = (JSON.parse(out).frames ?? [])[0]?.tags ?? {};
|
|
return {
|
|
luma: Number(tags["lavfi.signalstats.YAVG"] ?? 0),
|
|
saturation: Number(tags["lavfi.signalstats.SATAVG"] ?? 0),
|
|
};
|
|
}
|
|
|
|
/** Mean luminance (0-255); for brightness/contrast oracles. */
|
|
export function imageLuma(file: string): number {
|
|
return signalStats(file).luma;
|
|
}
|
|
|
|
/** Mean saturation (0-255); ~0 for grayscale, for desaturate/colorize oracles. */
|
|
export function imageSaturation(file: string): number {
|
|
return signalStats(file).saturation;
|
|
}
|
|
|
|
/** ffprobe a media file on disk: returns parsed JSON (format + streams). */
|
|
export function probeMedia(file: string): {
|
|
format?: { duration?: string; tags?: Record<string, string> };
|
|
streams?: Array<{
|
|
codec_type?: string;
|
|
width?: number;
|
|
height?: number;
|
|
channels?: number;
|
|
tags?: Record<string, string>;
|
|
}>;
|
|
} {
|
|
const out = execFileSync(
|
|
"ffprobe",
|
|
["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", file],
|
|
{ encoding: "utf8", timeout: 20_000 },
|
|
);
|
|
return JSON.parse(out);
|
|
}
|
|
|
|
/** Media duration in seconds (for trim/speed/fade oracles). */
|
|
export function mediaDuration(file: string): number {
|
|
const info = probeMedia(file);
|
|
return Number(info.format?.duration ?? 0);
|
|
}
|