Files
SnapOtter/tests/e2e-docker/feature-lifecycle.spec.ts
T
SnapOtterandGitHub b37faed95f fix: QA sweep - tool routes, security, i18n, a11y, + AI bundle install hardening (#393)
* 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
2026-07-03 09:54:02 +08:00

578 lines
20 KiB
TypeScript

import type { APIRequestContext } from "@playwright/test";
import { expect, test } from "@playwright/test";
import { apiToolPath } from "@snapotter/shared";
// ---- Helpers ---------------------------------------------------------------
const API = process.env.API_URL || "http://localhost:1349";
/** Minimal 1x1 transparent PNG used for tool endpoint checks. */
const pngBuffer = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
"base64",
);
const VALID_STATUSES = ["not_installed", "queued", "installed", "installing", "error"];
let _token: string | undefined;
async function getToken(request: APIRequestContext): Promise<string> {
if (_token) return _token;
const res = await request.post(`${API}/api/auth/login`, {
data: { username: "admin", password: "admin" },
});
const body = await res.json();
_token = body.token as string;
return _token;
}
async function authHeaders(request: APIRequestContext) {
return { Authorization: `Bearer ${await getToken(request)}` };
}
async function getBundleStatus(request: APIRequestContext, bundleId: string): Promise<string> {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
const data = await res.json();
const bundle = data.bundles.find((b: any) => b.id === bundleId);
return bundle?.status ?? "unknown";
}
async function getBundle(request: APIRequestContext, bundleId: string): Promise<any> {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
const data = await res.json();
return data.bundles.find((b: any) => b.id === bundleId) ?? null;
}
async function waitForInstallComplete(
request: APIRequestContext,
bundleId: string,
timeoutMs = 600_000,
): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const status = await getBundleStatus(request, bundleId);
if (status === "installed") return;
if (status === "error") throw new Error(`Install failed for ${bundleId}`);
await new Promise((r) => setTimeout(r, 3000));
}
throw new Error(`Install timeout for ${bundleId} after ${timeoutMs}ms`);
}
async function ensureUninstalled(request: APIRequestContext, bundleId: string): Promise<void> {
const status = await getBundleStatus(request, bundleId);
if (status === "installed") {
const headers = await authHeaders(request);
await request.post(`${API}/api/v1/admin/features/${bundleId}/uninstall`, {
headers,
});
}
}
async function ensureInstalled(request: APIRequestContext, bundleId: string): Promise<void> {
const status = await getBundleStatus(request, bundleId);
if (status !== "installed") {
const headers = await authHeaders(request);
await request.post(`${API}/api/v1/admin/features/${bundleId}/install`, {
headers,
});
await waitForInstallComplete(request, bundleId);
}
}
/** POST a tool endpoint with a minimal PNG and return the response. */
async function callTool(
request: APIRequestContext,
toolId: string,
settings: Record<string, unknown> = {},
) {
const headers = await authHeaders(request);
return request.post(`${API}${apiToolPath(toolId)}`, {
headers,
multipart: {
file: {
name: "test.png",
mimeType: "image/png",
buffer: pngBuffer,
},
settings: JSON.stringify(settings),
},
});
}
// ---- 1. Feature listing baseline -------------------------------------------
test.describe("Feature listing baseline", () => {
test.describe.configure({ mode: "serial" });
test("GET /api/v1/features returns all 6 bundles", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
expect(res.ok()).toBeTruthy();
const data = await res.json();
expect(data.bundles).toHaveLength(6);
const expectedIds = [
"background-removal",
"face-detection",
"object-eraser-colorize",
"upscale-enhance",
"photo-restoration",
"ocr",
];
const ids = data.bundles.map((b: any) => b.id);
for (const id of expectedIds) {
expect(ids).toContain(id);
}
});
test("each bundle has complete shape", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
const data = await res.json();
for (const bundle of data.bundles) {
expect(typeof bundle.id).toBe("string");
expect(typeof bundle.name).toBe("string");
expect(bundle.name.length).toBeGreaterThan(0);
expect(typeof bundle.description).toBe("string");
expect(bundle.description.length).toBeGreaterThan(0);
expect(typeof bundle.estimatedSize).toBe("string");
expect(bundle.estimatedSize.length).toBeGreaterThan(0);
expect(Array.isArray(bundle.enablesTools)).toBeTruthy();
expect(bundle.enablesTools.length).toBeGreaterThan(0);
expect(typeof bundle.status).toBe("string");
// progress and error may be null
expect("progress" in bundle).toBeTruthy();
expect("error" in bundle).toBeTruthy();
}
});
test("all statuses are valid enum values", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
const data = await res.json();
for (const bundle of data.bundles) {
expect(VALID_STATUSES).toContain(bundle.status);
}
});
test("GET /api/v1/admin/features/disk-usage returns totalBytes", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/admin/features/disk-usage`, {
headers,
});
expect(res.ok()).toBeTruthy();
const data = await res.json();
expect(typeof data.totalBytes).toBe("number");
expect(data.totalBytes).toBeGreaterThanOrEqual(0);
});
});
// ---- 2. Auth and permission guards -----------------------------------------
test.describe("Auth and permission guards", () => {
test.describe.configure({ mode: "serial" });
test("install without auth returns 401", async ({ request }) => {
const res = await request.post(`${API}/api/v1/admin/features/face-detection/install`);
expect(res.status()).toBe(401);
});
test("uninstall without auth returns 401", async ({ request }) => {
const res = await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`);
expect(res.status()).toBe(401);
});
test("install as non-admin returns 403", async ({ request }) => {
const headers = await authHeaders(request);
// Create a test user with role "user"
const createRes = await request.post(`${API}/api/auth/register`, {
headers,
data: {
username: "lifecycle_test_user",
password: "TestPass123",
role: "user",
},
});
expect(createRes.status()).toBe(201);
const created = await createRes.json();
try {
// Login as the test user
const loginRes = await request.post(`${API}/api/auth/login`, {
data: { username: "lifecycle_test_user", password: "TestPass123" },
});
expect(loginRes.ok()).toBeTruthy();
const loginBody = await loginRes.json();
const userHeaders = { Authorization: `Bearer ${loginBody.token}` };
// Attempt install -- should be denied
const installRes = await request.post(`${API}/api/v1/admin/features/face-detection/install`, {
headers: userHeaders,
});
expect(installRes.status()).toBe(403);
} finally {
// Cleanup: delete the test user
await request.delete(`${API}/api/auth/users/${created.id}`, { headers });
}
});
});
// ---- 3. Validation guards --------------------------------------------------
test.describe("Validation guards", () => {
test.describe.configure({ mode: "serial" });
test("install unknown bundle returns 404", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/nonexistent-bundle/install`, {
headers,
});
expect(res.status()).toBe(404);
});
test("uninstall unknown bundle returns 404", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/nonexistent-bundle/uninstall`, {
headers,
});
expect(res.status()).toBe(404);
});
test("uninstall not-installed bundle returns 409", async ({ request }) => {
// Ensure face-detection is not installed for this check
await ensureUninstalled(request, "face-detection");
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`, {
headers,
});
expect(res.status()).toBe(409);
});
});
// ---- 4. Install lifecycle - face-detection ---------------------------------
test.describe("Install lifecycle - face-detection", () => {
test.describe.configure({ mode: "serial" });
let diskUsageBefore: number;
test.beforeAll(async ({ request }) => {
await ensureUninstalled(request, "face-detection");
});
test("POST install returns 202 with jobId", async ({ request }) => {
test.setTimeout(600_000);
// Record disk usage before install
const headers = await authHeaders(request);
const diskRes = await request.get(`${API}/api/v1/admin/features/disk-usage`, { headers });
const diskData = await diskRes.json();
diskUsageBefore = diskData.totalBytes;
const res = await request.post(`${API}/api/v1/admin/features/face-detection/install`, {
headers,
});
expect(res.status()).toBe(202);
const body = await res.json();
expect(typeof body.jobId).toBe("string");
// Validate UUID format (8-4-4-4-12)
expect(body.jobId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
});
test("install progress is available via features endpoint", async ({ request }) => {
// Give the installer a moment to start
await new Promise((r) => setTimeout(r, 2000));
const bundle = await getBundle(request, "face-detection");
expect(bundle).toBeTruthy();
// Status should be "installing" while the install is in progress
// (or "installed" if the install was very fast)
expect(["installing", "installed"]).toContain(bundle.status);
});
// New contract: the server owns the install queue, so a concurrent install is
// no longer rejected with 409. A repeat POST of the *same* installing bundle
// is deduped (202, not newly queued, same job); a *different* bundle is
// queued (202 { queued: true }) and reported as "queued" via GET /features.
test("second install of same bundle is deduped (202, not a new job)", async ({ request }) => {
const status = await getBundleStatus(request, "face-detection");
if (status === "installing") {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/install`, {
headers,
});
expect(res.status()).toBe(202);
const body = await res.json();
expect(body.queued).toBe(false);
expect(typeof body.jobId).toBe("string");
}
// If already installed (fast download), this test is a no-op
});
test("install of different bundle while one is active is queued (202)", async ({ request }) => {
test.setTimeout(900_000);
const status = await getBundleStatus(request, "face-detection");
if (status !== "installing") return; // fast install already finished; nothing to assert
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/ocr/install`, { headers });
expect(res.status()).toBe(202);
expect((await res.json()).queued).toBe(true);
const ocr = await getBundle(request, "ocr");
expect(["queued", "installing"]).toContain(ocr.status);
// ocr auto-starts once face-detection finishes. Drain and uninstall it so
// the rest of the serial suite runs against a clean lock/state.
await waitForInstallComplete(request, "face-detection");
await waitForInstallComplete(request, "ocr", 900_000);
await request.post(`${API}/api/v1/admin/features/ocr/uninstall`, { headers });
expect(await getBundleStatus(request, "ocr")).toBe("not_installed");
});
test("after install completes, status is installed with version", async ({ request }) => {
test.setTimeout(600_000);
await waitForInstallComplete(request, "face-detection");
const bundle = await getBundle(request, "face-detection");
expect(bundle.status).toBe("installed");
});
test("after install, disk usage increased", async ({ request }) => {
const headers = await authHeaders(request);
const diskRes = await request.get(`${API}/api/v1/admin/features/disk-usage`, { headers });
const diskData = await diskRes.json();
expect(diskData.totalBytes).toBeGreaterThan(diskUsageBefore);
});
test("POST install already-installed returns 409", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/install`, {
headers,
});
expect(res.status()).toBe(409);
});
test("installed bundle has installedVersion string", async ({ request }) => {
const bundle = await getBundle(request, "face-detection");
expect(bundle.status).toBe("installed");
// installedVersion should be a string (or null for bundles without versioning)
expect(
typeof bundle.installedVersion === "string" || bundle.installedVersion === null,
).toBeTruthy();
});
});
// ---- 5. Tool availability after install ------------------------------------
test.describe("Tool availability after install", () => {
test.describe.configure({ mode: "serial" });
test.beforeAll(async ({ request }) => {
await ensureInstalled(request, "face-detection");
});
test("blur-faces returns 200 after face-detection installed", async ({ request }) => {
test.setTimeout(60_000);
const res = await callTool(request, "blur-faces");
expect(res.status()).toBe(200);
});
test("red-eye-removal returns 200 after face-detection installed", async ({ request }) => {
test.setTimeout(60_000);
const res = await callTool(request, "red-eye-removal");
expect(res.status()).toBe(200);
});
test("smart-crop face mode returns 200 after face-detection installed", async ({ request }) => {
test.setTimeout(60_000);
const res = await callTool(request, "smart-crop", {
mode: "face",
width: 100,
height: 100,
});
expect(res.status()).toBe(200);
});
test("resize still works (non-AI tool unaffected)", async ({ request }) => {
const res = await callTool(request, "resize", {
width: 100,
height: 100,
method: "fit",
});
// Should succeed or fail with a processing error, NOT 501
expect(res.status()).not.toBe(501);
});
});
// ---- 6. Uninstall lifecycle ------------------------------------------------
test.describe("Uninstall lifecycle", () => {
test.describe.configure({ mode: "serial" });
test.beforeAll(async ({ request }) => {
await ensureInstalled(request, "face-detection");
});
test("POST uninstall face-detection returns 200", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`, {
headers,
});
expect(res.ok()).toBeTruthy();
const body = await res.json();
expect(body.ok).toBe(true);
});
test("status is not_installed after uninstall", async ({ request }) => {
const status = await getBundleStatus(request, "face-detection");
expect(status).toBe("not_installed");
});
test("blur-faces returns 501 after uninstall", async ({ request }) => {
const res = await callTool(request, "blur-faces");
expect(res.status()).toBe(501);
});
test("501 response has FEATURE_NOT_INSTALLED code and bundle info", async ({ request }) => {
const res = await callTool(request, "blur-faces");
expect(res.status()).toBe(501);
const body = await res.json();
expect(body.code).toBe("FEATURE_NOT_INSTALLED");
expect(body.feature).toBe("face-detection");
expect(body.featureName).toBeTruthy();
expect(body.estimatedSize).toBeTruthy();
});
test("POST uninstall again returns 409", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`, {
headers,
});
expect(res.status()).toBe(409);
});
});
// ---- 7. Reinstall round-trip -----------------------------------------------
test.describe("Reinstall round-trip", () => {
test.describe.configure({ mode: "serial" });
test("reinstall after uninstall returns 202", async ({ request }) => {
test.setTimeout(600_000);
await ensureUninstalled(request, "face-detection");
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/install`, {
headers,
});
expect(res.status()).toBe(202);
await waitForInstallComplete(request, "face-detection");
});
test("tools work again after reinstall", async ({ request }) => {
test.setTimeout(60_000);
const res = await callTool(request, "blur-faces");
expect(res.status()).toBe(200);
});
test("uninstall after reinstall succeeds", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`, {
headers,
});
expect(res.ok()).toBeTruthy();
const status = await getBundleStatus(request, "face-detection");
expect(status).toBe("not_installed");
});
});
// ---- 8. Shared model protection --------------------------------------------
test.describe("Shared model protection", () => {
test.describe.configure({ mode: "serial" });
test("install both face-detection and photo-restoration", async ({ request }) => {
test.setTimeout(600_000);
await ensureInstalled(request, "face-detection");
await ensureInstalled(request, "photo-restoration");
const fdStatus = await getBundleStatus(request, "face-detection");
const prStatus = await getBundleStatus(request, "photo-restoration");
expect(fdStatus).toBe("installed");
expect(prStatus).toBe("installed");
});
test("uninstall face-detection, photo-restoration tools still work", async ({ request }) => {
test.setTimeout(120_000);
const headers = await authHeaders(request);
// Uninstall face-detection
const uninstallRes = await request.post(
`${API}/api/v1/admin/features/face-detection/uninstall`,
{ headers },
);
expect(uninstallRes.ok()).toBeTruthy();
// Verify face-detection is gone
const fdStatus = await getBundleStatus(request, "face-detection");
expect(fdStatus).toBe("not_installed");
// photo-restoration tools should still work (shared models preserved)
const res = await callTool(request, "restore-photo");
expect(res.status()).toBe(200);
});
test("cleanup: uninstall photo-restoration", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.post(`${API}/api/v1/admin/features/photo-restoration/uninstall`, {
headers,
});
expect(res.ok()).toBeTruthy();
const status = await getBundleStatus(request, "photo-restoration");
expect(status).toBe("not_installed");
});
});
// ---- 9. Container restart recovery -----------------------------------------
test.describe("Container restart recovery", () => {
test.describe.configure({ mode: "serial" });
test("no stale installing state after container restart", async ({ request }) => {
const headers = await authHeaders(request);
const res = await request.get(`${API}/api/v1/features`, { headers });
expect(res.ok()).toBeTruthy();
const data = await res.json();
// After all previous uninstalls, no bundle should be stuck in "installing"
for (const bundle of data.bundles) {
expect(bundle.status).not.toBe("installing");
}
});
test("install works after restart", async ({ request }) => {
test.setTimeout(600_000);
// Install face-detection from clean state
await ensureInstalled(request, "face-detection");
// Verify it works
const res = await callTool(request, "blur-faces");
expect(res.status()).toBe(200);
// Cleanup: uninstall
const headers = await authHeaders(request);
await request.post(`${API}/api/v1/admin/features/face-detection/uninstall`, { headers });
const status = await getBundleStatus(request, "face-detection");
expect(status).toBe("not_installed");
});
});