Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
fix(v0.11.1): production smoke of v0.11.0 — preview playback, export audio, offline detection
Ashiq Hussain Mire315889176f3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aaa522e..bf38416 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,63 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.11.1] — 2026-10-30++Production smoke-test release: the focused v0.11.0 verification+(`research/V0110-SMOKE-TEST.md`) confirmed the v0.10.1 fixes hold — zero+P2002s, zero 30-second hangs across the whole probe session — and found+four real bugs in the browser-only paths that API probes and unit tests+cannot reach. All four shipped in v0.11.0's headline features and none+had ever worked end-to-end.++### Fixed+- **Preview never played audio/video (and could skip entry animations)** —+ `PreviewStage` mounts its Konva stage only after the ResizeObserver+ measures the container, but the playback effects bailed on the first+ run (layer ref still null) and their deps never changed afterwards.+ Whether media played was a commit-vs-observer race — manual testing+ usually won it, headless browsers deterministically lose it. A+ `stageReady` dep re-runs both effects when the stage actually mounts.+- **Live video frames never swapped in** — the swap looked up+ `findOne('#id')` as a Konva `Image`, but `VideoNode` renders a Group;+ every video silently kept its poster. The swap now targets the Image+ inside the group.+- **Video froze at trimStart in a `canplay` seek-loop** — the handler+ sought to `trimStart` on every `canplay` event; each completed seek+ re-fired `canplay` (~130 `play()` calls/s, playback never advancing).+ The trim seek now happens once, and looping videos wrap back to+ `trimStart` instead of the source start.+- **Video export could record digital silence** — two stacked races: the+ recorder could start before `audioCtx.resume()` landed, and the export+ render loop's tight MessageChannel yielding starves the audio element's+ resource-selection task (the fetch never started; `readyState` stayed 0+ and the pending `play()` aborted in cleanup). The export now bounded-+ awaits both the context resume and `canplay` on every audio element+ before recording begins; on timeout it still exports (silent, honestly)+ rather than hanging.+- **Collab status stayed "Live" through a hard network cut** — a+ silently-dead SSE socket never fires `onerror`, so the editor claimed+ Live while every flush failed and queued. The session now listens to+ the browser's `online`/`offline` events: an honest "Offline — edits+ save locally" badge appears immediately, and reconnect happens the+ moment the network returns instead of waiting out the backoff.+- **Flaky white-noise BPM unit test** — `Math.random()` input meant ~1 in+ 3 runs drew noise spurious enough to clear the detector's periodicity+ gate; the test now uses a seeded PRNG (5/5 stable re-runs).++### Verification+- `scripts/smoke-v0110.ts` — focused API-level production smoke: auth,+ ownership/read-only, the two-designs-one-browser P2002 scenario,+ SSE drop/reconnect/gap-free replay, idempotent retried flushes, the+ chunked media lifecycle, latency ceiling tracking, composite-PK DB+ state. **46/46 green**; probe rows cleaned up afterwards.+- `tests/e2e/v0110-smoke.spec.ts` — the browser-only surface: preview+ plays uploaded audio AND video (playback observed, not assumed), video+ export muxes a **non-silent** audio track (ffprobe + volumedetect), an+ edit made offline syncs on reconnect and survives reload. 3/3 green,+ stable across re-runs.+- Offline-merge probe 18/18 · deploy-readiness ALL GREEN · 285 unit tests.+## [0.11.0] — 2026-10-29The "sound & motion" release: native audio/video elements, a chunkeddiff --git a/package.json b/package.jsonindex 7acd305..17e929d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.11.0",+ "version": "0.11.1","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/research/V0110-SMOKE-TEST.md b/research/V0110-SMOKE-TEST.mdnew file mode 100644index 0000000..a4c73a2--- /dev/null+++ b/research/V0110-SMOKE-TEST.md@@ -0,0 +1,147 @@+# Canvix — v0.11.0 Focused Production Smoke Test++Date: 2026-10-30 · Build under test: `163a071` (v0.11.0) → findings fixed+as **v0.11.1** during the run · Verdict: **PASS after fixes** — and the+smoke caught **four real product bugs** that unit tests and API probes+could not see.++## Environment++The self-host / Vercel-equivalent reference path (per+`research/DEPLOYMENT-VERIFICATION.md`):++- `npm run build` → `NODE_ENV=production node .next/standalone/server.js`+- Live Supabase transaction pooler (PostgreSQL 17.11, ap-southeast-2)+- API-level probe: `scripts/smoke-v0110.ts` (plain HTTP, latency-ledgered)+- Browser-level probe: `tests/e2e/v0110-smoke.spec.ts` (Playwright Chromium,+ `--autoplay-policy=no-user-gesture-required`; ffprobe/ffmpeg verify media)+- Unit suite 285 · offline-merge probe 18 · deploy-readiness probe++Re-run:++```bash+npm run build+PORT=3100 NODE_ENV=production DATABASE_URL=<supabase-pooler-url> \+ node .next/standalone/server.js &+npx tsx scripts/smoke-v0110.ts http://127.0.0.1:3100+BASE_URL=http://127.0.0.1:3100 npx playwright test tests/e2e/v0110-smoke.spec.ts+npx tsx scripts/cleanup-v0110-probes.ts # removes the browser probes' rows+```++## Results matrix++| Area | Probe | Result |+|---|---|---|+| Account registration/login | API §1 | ✓ 7/7 (register, me, logout, wrong-pw 401, login, 2nd account, dup 409) |+| Ownership & read-only | API §2 | ✓ 8/8 (owner save fast-path, anon/other-account `readOnly:true` + PUT 403, CSRF 403) |+| Realtime across two designs | API §3 | ✓ 10/10 — the v0.10.1 P2002 scenario: one pid live in designs A **and** B, 8/8 interleaved heartbeats + cursors 200, 3-way concurrent-create race 200, events isolated per design, presence visible in both, DB rows = 2 under the composite PK |+| Reconnect behaviour | API §4 | ✓ 5/5 (drop → events keep landing → `?since` replay gap-free, duplicate flush accepted 0, `retry: 1500`, keepalives) |+| A/V upload & playback | API §5 | ✓ 15/15 (2-chunk WAV byte-exact, offset-guard 409, finalize guards, Range 206/416, immutable headers, real MP4 round-trip + seek slice, A/V document round-trip, 415/413/403 guards) |+| Latency ceiling | API §6 | ✓ max 8.05 s (4.4 MB bytea finalize to Sydney) — **nothing near 30 s** |+| DB state | API §7 | ✓ same pid present in both designs (impossible under the old PK) |+| Browser: preview playback | e2e #1 | ✓ after fixes — audio AND video issue `play()` and `currentTime` genuinely advances |+| Browser: export with audio | e2e #2 | ✓ after fixes — ffprobe: video+audio streams; volumedetect: non-silent track |+| Browser: offline edit | e2e #3 | ✓ after fixes — honest Offline badge, queued op syncs on reconnect (server-side watcher), survives reload |+| Offline-merge regression | verify-offline-merge | ✓ 18/18 |+| Deploy readiness | verify-deploy-readiness | ✓ ALL GREEN |+| Unit suite | vitest | ✓ 285/285 (5/5 re-runs after de-flaking) |++## The P2002 / 30-second-timeout question++**No new P2002 errors and no 30-second timeouts appeared.**++- The production server log across the entire fixed-build session (two+ browser suites + the full API smoke + regression suites) contains **zero**+ `P2002`, zero `[collab/presence]` / `[collab/events]` errors, zero+ `tick failed`, zero `db-timeout`/`recycle` comments — boot banner and+ pooler-detection notes only.+- The API probe times every request: **56 requests, median ~1.3 s, max+ 8.05 s** (the slowest five are all multi-MB media bytea round-trips to+ the Sydney pooler — expected, and an order of magnitude under the 30 s+ ceiling).+- The exact v0.10.1 incident scenario (one browser heartbeating into two+ designs simultaneously, plus a concurrent-create race on the same+ `(designId, pid)`) returns 200 every time, and the composite-PK rows+ coexist in the database.++## Findings — four real bugs (all fixed in v0.11.1)++The browser-level probes are what found these: three of the four live in+code paths that only execute in a real browser (Konva refs, media element+lifecycle, MediaRecorder), and the fourth was masked by the first.++### 1. Preview audio/video/animation effects never ran (race)++`PreviewStage` renders its Konva `<Stage>` only after the ResizeObserver+measures the container (`scale > 0`), but both playback effects bail when+`layerRef.current` is null on first run — and their deps+(`[page, animated, reduceMotion, playKey]`) never change afterwards.+Whether media played was a commit-vs-observer **race** — manual testing+usually won it, headless Chromium deterministically lost it.+**Fix:** a `stageReady = scale > 0` dep re-runs both effects when the+stage actually mounts (`preview-stage.tsx`).++### 2. Live video frames never swapped in (dead code)++The swap did `layer.findOne<Konva.Image>('#id')` — but `VideoNode`+renders a Konva **Group** (poster + play chip + badges) carrying the id.+`typeof group.image !== 'function'` → every video silently kept its+poster. This dead path also masked finding #3.+**Fix:** find the `Image` **inside** the group.++### 3. `canplay` seek-loop froze video at `trimStart` (~130 play()/s)++The `canplay` handler sought to `trimStart` unconditionally; the completed+seek re-triggered `canplay`, which sought again — playback never advanced+past `trimStart` while `play()` was re-invoked ~130 times/second.+**Fix:** seek once per element; the rAF tick now also wraps looping+videos back to `trimStart` (the native loop wraps to 0).++### 4. Video export recorded digital silence (two stacked races)++(a) `audioCtx.resume()` was fire-and-forget — a recorder started while the+context was still suspended records silence. (b) Worse: the export render+loop yields via a tight MessageChannel cycle that **starves the media+element's resource-selection task** — the audio element sat at+`readyState 0` (fetch never started) for the entire export, then+`finally` aborted the pending `play()` (AbortError) and the track was+-91 dB silence. Deterministic in headless, racy on real machines.+**Fix:** bounded `await` for context resume **and** for `canplay` on every+audio element *before* `recorder.start()` (main thread still idle); on+timeout the export still completes (silent, honestly) instead of hanging.++### 5. Collab status stayed "Live" through a hard network cut++A silently-dead SSE socket never fires `onerror` (no read timeout in+EventSource), so through a network cut the editor kept claiming "Live"+while every flush failed and queued. The browser's `online`/`offline`+events are the reliable signal.+**Fix:** `CollabSession` now listens: offline → honest "Offline — edits+save locally" badge immediately; online → reconnect instantly (clears the+backoff timer) instead of waiting it out. This is also what the e2e+offline-edit test now asserts end-to-end: badge → edit while offline →+reconnect → op observed landing on the server event log → survives reload.++### 6. Flaky unit test (pre-existing)++`beat-detect.test.ts` "white noise → undefined" used `Math.random()`, so+roughly one run in three drew a noise sample with enough spurious+autocorrelation to clear the detector's gate. **Fix:** seeded PRNG —+5/5 stable re-runs.++## Honest limitations++- Single server instance, single region (Sydney pooler), synthetic+ payloads; no multi-region or failover behaviour was exercised.+- The browser video probe uploads WebM (VP8+Vorbis) because Playwright's+ Chromium lacks proprietary codecs; the H.264/AAC MP4 path is verified at+ the HTTP level (byte-exact + Range) but not decoded in the browser here.+- Video export still renders poster frames, not moving video frames —+ documented v0.11 scope (`research/MEDIA-AND-BEAT-SYNC.md`).+- The e2e spec leaves probe rows (designs/media) in the DB by design —+ media has no delete API. Run `scripts/cleanup-v0110-probes.ts` after+ browser-suite runs; it matches only the spec's distinct design name and+ harvests media ids from those designs' own elements.+- The register route's in-memory rate limit (5 sign-ups/h/IP per instance)+ makes back-to-back API-smoke runs 429 on the duplicate-username check —+ the probe treats that as environmental and reports it as a note.diff --git a/scripts/cleanup-v0110-probes.ts b/scripts/cleanup-v0110-probes.tsnew file mode 100644index 0000000..3ce8734--- /dev/null+++ b/scripts/cleanup-v0110-probes.ts@@ -0,0 +1,53 @@+// scripts/cleanup-v0110-probes.ts — one-off hygiene: remove ALL probe rows+// created by tests/e2e/v0110-smoke.spec.ts runs. The spec overwrites its+// probe ledger each run, so match by the distinct design name the spec+// uses ('v0110 browser smoke', always ownerless) and harvest the media ids+// from the designs' own element srcs — never touch other rows.+export {}++import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { createScriptClient } from '../src/lib/db-script'++const PROBE_NAME = 'v0110 browser smoke'++async function main() {+ const env = readFileSync(join(process.cwd(), '.env'), 'utf8')+ const line = env.split('\n').find((l) => l.startsWith('DATABASE_URL='))+ if (!line) throw new Error('no DATABASE_URL in .env')+ const db = createScriptClient(line.slice('DATABASE_URL='.length).trim())++ const designs = await db.design.findMany({+ where: { name: PROBE_NAME, ownerId: null },+ select: { id: true, pages: true },+ })+ console.log(`probe designs found: ${designs.length}`)++ // harvest media ids from the designs' audio/video element srcs+ const mediaIds = new Set<string>()+ for (const d of designs) {+ const pages = (d.pages as Array<{ elements?: Array<{ type?: string; src?: string }> }> | null) ?? []+ for (const p of pages) {+ for (const el of p.elements ?? []) {+ if ((el.type === 'audio' || el.type === 'video') && typeof el.src === 'string') {+ const m = /\/api\/media\/([a-z0-9]+)/i.exec(el.src)+ if (m) mediaIds.add(m[1])+ }+ }+ }+ }+ console.log(`media referenced: ${mediaIds.size}`)++ const ids = designs.map((d) => d.id)+ const dl = await db.design.deleteMany({ where: { id: { in: ids } } })+ const ml = await db.media.deleteMany({ where: { id: { in: [...mediaIds] } } })+ const pl = await db.presence.deleteMany({ where: { designId: { in: ids } } })+ const cl = await db.comment.deleteMany({ where: { designId: { in: ids } } })+ await db.$disconnect()+ console.log(`deleted: ${dl.count} designs (events cascade), ${ml.count} media, ${pl.count} presence, ${cl.count} comments`)+}++main().catch((err) => {+ console.error(err)+ process.exit(1)+})diff --git a/scripts/smoke-v0110.ts b/scripts/smoke-v0110.tsnew file mode 100644index 0000000..e34b897--- /dev/null+++ b/scripts/smoke-v0110.ts@@ -0,0 +1,923 @@+// scripts/smoke-v0110.ts — focused v0.11.0 production smoke test.+//+// Point at a RUNNING production server (standalone build against the live+// database — the self-host / Vercel-equivalent reference path):+// npx tsx scripts/smoke-v0110.ts [BASE_URL] (default http://127.0.0.1:3100)+//+// Focused scope (everything the plugin system depends on staying healthy):+// 1. auth — register → me → logout → wrong password 401 → login+// 2. ownership — owner saves; anonymous + other account are read-only+// (GET readOnly:true, PUT 403, cross-origin PUT 403)+// 3. realtime — ONE browser identity live in TWO designs at once (the+// v0.10.1 P2002 scenario): interleaved heartbeats + cursors+// + concurrent-create races all 200; events isolated per+// design; the participant visible in BOTH designs' streams+// 4. reconnect — SSE drop → events keep landing → ?since replay gap-free;+// retried flush (same eventIds) inserts nothing (idempotent);+// `retry: 1500` hint present; keepalives flow+// 5. media — two-chunk WAV round-trip (offset-guard 409, finalize+// guards, byte-exact GET, Range 206/416, immutable headers),+// real MP4 upload + range playback semantics, audio+video+// element document round-trip+// 6. latency — every request timed; the 30 s function-hang regression+// must not reappear (nothing may approach the ceiling)+// 7. db state — presence rows for the probe pid exist in BOTH designs+// simultaneously (impossible under the old single-column PK)+//+// Probe rows (users, designs, events, presence, media) are removed at the end.++export {}++import { execFileSync } from 'node:child_process'+import { existsSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { createScriptClient } from '../src/lib/db-script'++const BASE = (process.argv[2] ?? process.env.BASE_URL ?? 'http://127.0.0.1:3100').replace(/\/$/, '')+const EVIL = 'https://evil-smoke.example'++let failures = 0+let checks = 0+function pass(label: string, detail: string) {+ checks+++ console.log(` ✓ ${label} — ${detail}`)+}+function fail(label: string, detail: string) {+ failures+++ checks+++ console.error(` ✗ ${label} — ${detail}`)+}+function note(label: string, detail: string) {+ console.log(` · ${label} — ${detail}`)+}++// ── latency ledger (the 30 s-hang guard) ─────────────────────+interface ReqStat {+ label: string+ ms: number+ status: number+}+const reqStats: ReqStat[] = []+async function hfetch(label: string, url: string, init?: RequestInit): Promise<Response> {+ const full = url.startsWith('http') ? url : `${BASE}${url}`+ const t0 = Date.now()+ try {+ const res = await fetch(full, init)+ reqStats.push({ label, ms: Date.now() - t0, status: res.status })+ return res+ } catch (err) {+ reqStats.push({ label, ms: Date.now() - t0, status: 0 })+ throw err+ }+}++// ── minimal cookie jar ───────────────────────────────────────+class Jar {+ private jar = new Map<string, string>()+ update(res: Response) {+ const h = res.headers as Headers & { getSetCookie?: () => string[] }+ const raw = typeof h.getSetCookie === 'function' ? h.getSetCookie() : []+ for (const c of raw) {+ const [pair] = c.split(';')+ const eq = pair.indexOf('=')+ if (eq > 0) this.jar.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim())+ }+ }+ get header(): string | undefined {+ return this.jar.size ? [...this.jar].map(([k, v]) => `${k}=${v}`).join('; ') : undefined+ }+}++// ── SSE reader (what the browser's EventSource sees) ─────────+interface StreamFrame {+ events: { seq: number; eventId?: string; kind: string; actorId: string }[]+ presence: { id: string; name: string; cursor: unknown }[]+ seq: number+}+class SSEReader {+ frames: StreamFrame[] = []+ comments: string[] = []+ retryHint: string | null = null+ closed = false+ private ctrl = new AbortController()+ private opened = false++ constructor(readonly designId: string, readonly pid: string) {}++ async open(since = 0): Promise<void> {+ const res = await fetch(`${BASE}/api/collab/${this.designId}/stream?since=${since}&pid=${this.pid}`, {+ signal: this.ctrl.signal,+ headers: { accept: 'text/event-stream' },+ })+ if (res.status !== 200) throw new Error(`stream opened with ${res.status}`)+ const reader = res.body!.getReader()+ const dec = new TextDecoder()+ let buf = ''+ void (async () => {+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ buf += dec.decode(value, { stream: true })+ let idx: number+ while ((idx = buf.indexOf('\n\n')) >= 0) {+ const chunk = buf.slice(0, idx)+ buf = buf.slice(idx + 2)+ this.handle(chunk)+ }+ }+ } catch {+ /* aborted mid-read — expected on drop */+ }+ this.closed = true+ })()+ // the server emits `: open design=… since=…` on start — await it+ const t0 = Date.now()+ while (!this.opened && Date.now() - t0 < 10_000) await sleep(100)+ if (!this.opened) throw new Error('stream never sent its open comment')+ }++ private handle(chunk: string) {+ for (const line of chunk.split('\n')) {+ if (line.startsWith('data: ')) {+ try {+ this.frames.push(JSON.parse(line.slice(6)) as StreamFrame)+ } catch {+ /* partial frame — ignored */+ }+ } else if (line.startsWith('retry: ')) {+ this.retryHint = line.slice(7).trim()+ } else if (line.startsWith(': ')) {+ const c = line.slice(2)+ this.comments.push(c)+ if (c.startsWith('open ')) this.opened = true+ }+ }+ }++ abort() {+ this.ctrl.abort()+ }++ countEvent(eventId: string): number {+ return this.frames.reduce((n, f) => n + f.events.filter((e) => e.eventId === eventId).length, 0)+ }+ hasPresence(pid: string): boolean {+ return this.frames.some((f) => f.presence.some((p) => p.id === pid))+ }+ lastSeq(): number {+ let s = 0+ for (const f of this.frames) {+ if (f.seq > s) s = f.seq+ for (const e of f.events) if (e.seq > s) s = e.seq+ }+ return s+ }+}++function sleep(ms: number) {+ return new Promise<void>((r) => setTimeout(r, ms))+}++async function waitFor<T>(desc: string, fn: () => T | undefined, timeoutMs = 15_000): Promise<T> {+ const t0 = Date.now()+ for (;;) {+ const v = fn()+ if (v !== undefined) return v+ if (Date.now() - t0 > timeoutMs) throw new Error(`timeout waiting for ${desc}`)+ await sleep(150)+ }+}++// ── collab helpers ───────────────────────────────────────────+interface Envelope {+ eventId: string+ hlc: string+ op: Record<string, unknown>+}+let envSeq = 0+function envelope(op: Record<string, unknown>): Envelope {+ envSeq+++ return { eventId: `smoke-${Date.now()}-${envSeq}`, hlc: `${Date.now()}:0:smoke`, op }+}+const addRect = (id: string) => ({+ kind: 'element:add',+ pageId: 'p1',+ element: {+ id,+ type: 'rect',+ x: 12,+ y: 12,+ width: 140,+ height: 90,+ fill: '#02C0CC',+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ },+})+const rename = (name: string) => ({ kind: 'design:rename', name })++async function flushEvents(designId: string, pid: string, events: Envelope[]) {+ const res = await hfetch(`POST collab/events (${designId.slice(0, 8)})`, `/api/collab/${designId}/events`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ pid, name: 'Smoke Probe', color: '#7630D7', events }),+ })+ const body = (await res.json().catch(() => null)) as { accepted?: number; rejected?: string[] } | null+ return { status: res.status, body }+}++async function heartbeat(designId: string, pid: string, cursor = false) {+ const res = await hfetch(`POST collab/presence (${designId.slice(0, 8)})`, `/api/collab/${designId}/presence`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ pid,+ name: 'Smoke Probe',+ color: '#FF5C8A',+ ...(cursor ? { cursor: { page: 0, x: 111.5, y: 42.25, selection: [] } } : {}),+ }),+ })+ return res.status+}++// ── probe payloads ───────────────────────────────────────────+/** minimal mono 16-bit PCM WAV (~4.2 MB → forces two upload chunks), 120 BPM clicks */+function makeWav(): Uint8Array<ArrayBuffer> {+ const sampleRate = 44_100+ const samples = Math.floor((4.2 * 1024 * 1024) / 2)+ const buf = new Uint8Array(44 + samples * 2)+ const dv = new DataView(buf.buffer)+ const w = (off: number, s: string) => {+ for (let i = 0; i < s.length; i++) dv.setUint8(off + i, s.charCodeAt(i))+ }+ w(0, 'RIFF')+ dv.setUint32(4, 36 + samples * 2, true)+ w(8, 'WAVE')+ w(12, 'fmt ')+ dv.setUint32(16, 16, true)+ dv.setUint16(20, 1, true)+ dv.setUint16(22, 1, true)+ dv.setUint32(24, sampleRate, true)+ dv.setUint32(28, sampleRate * 2, true)+ dv.setUint16(32, 2, true)+ dv.setUint16(34, 16, true)+ w(36, 'data')+ dv.setUint32(40, samples * 2, true)+ const period = Math.floor(sampleRate * 0.5)+ for (let i = 0; i < samples; i++) {+ const t = i % period+ const v = t < 400 ? Math.round(Math.exp(-t / 80) * 22000 * (t % 4 < 2 ? 1 : -1)) : 0+ dv.setInt16(44 + i * 2, v, true)+ }+ return buf+}++/** real H.264+AAC mp4 via ffmpeg (2 s testsrc + 440 Hz sine) */+function makeMp4(): Uint8Array<ArrayBuffer> | null {+ const p = join(tmpdir(), 'canvix-smoke-probe.mp4')+ try {+ if (!existsSync(p)) {+ execFileSync(+ 'ffmpeg',+ [+ '-y', '-loglevel', 'error',+ '-f', 'lavfi', '-i', 'testsrc=duration=2:size=320x240:rate=15',+ '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2',+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', p,+ ],+ { timeout: 30_000 },+ )+ }+ const buf = readFileSync(p)+ return new Uint8Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))+ } catch {+ return null+ }+}++// ── probe registry (for the DB cleanup at the end) ───────────+const probe = {+ users: [] as string[],+ designs: [] as string[],+ media: [] as string[],+ pids: [] as string[],+}++// ── media upload helper (the client's chunked-upload lifecycle) ──+async function uploadMedia(mime: string, bytes: Uint8Array<ArrayBuffer>): Promise<string | null> {+ const init = await hfetch('POST /api/media (init)', '/api/media', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ mime, size: bytes.length }),+ })+ const j = (await init.json().catch(() => null)) as { id?: string; chunkSize?: number } | null+ if (init.status !== 201 || !j?.id) {+ fail('media init', `status ${init.status}`)+ return null+ }+ const id = j.id+ probe.media.push(id)+ const chunkSize = j.chunkSize ?? 3 * 1024 * 1024+ for (let off = 0; off < bytes.length; off += chunkSize) {+ const part = bytes.subarray(off, Math.min(off + chunkSize, bytes.length))+ const r = await hfetch(`PATCH /api/media chunk@${off}`, `/api/media/${id}?offset=${off}`, {+ method: 'PATCH',+ headers: { 'content-type': 'application/octet-stream' },+ body: part,+ })+ if (r.status !== 200) fail('media chunk', `offset ${off} → ${r.status}`)+ }+ const fin = await hfetch('PUT /api/media (finalize)', `/api/media/${id}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ expectedSize: bytes.length }),+ })+ if (fin.status !== 200) fail('media finalize', `status ${fin.status}`)+ return id+}++async function main() {+ console.log(`smoke-v0110 → ${BASE}\n`)+ const TS = Date.now()+ const owner = new Jar()+ const other = new Jar()+ const anon = new Jar()+ const USER_OWNER = `smoke_owner_${TS}`+ const USER_OTHER = `smoke_other_${TS}`+ const PASS = 'smoke-Tr0ub4dor-pass'+ const PID_MAIN = `smoke-main-${TS}`+ const PID_OBS = `smoke-obs-${TS}`+ probe.users.push(USER_OWNER, USER_OTHER)+ probe.pids.push(PID_MAIN, PID_OBS)++ // ═══ 1. auth — registration / login ═════════════════════════+ console.log('── 1. account registration & login')+ {+ let res = await hfetch('POST /api/auth/register', '/api/auth/register', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ username: USER_OWNER, password: PASS }),+ })+ owner.update(res)+ if (res.status === 201) pass('register', `201, ${USER_OWNER}`)+ else fail('register', `status ${res.status}: ${await res.text()}`)++ res = await hfetch('GET /api/auth/me (signed in)', '/api/auth/me', { headers: { cookie: owner.header! } })+ const me = (await res.json().catch(() => null)) as { user?: { username?: string } } | null+ if (me?.user?.username === USER_OWNER) pass('me after register', 'session cookie valid')+ else fail('me after register', `user=${JSON.stringify(me)}`)++ res = await hfetch('POST /api/auth/logout', '/api/auth/logout', {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: owner.header! },+ })+ owner.update(res)+ res = await hfetch('GET /api/auth/me (logged out)', '/api/auth/me', { headers: { cookie: owner.header! } })+ const me2 = (await res.json().catch(() => null)) as { user?: unknown } | null+ if (me2?.user == null) pass('logout', 'session revoked')+ else fail('logout', 'still signed in')++ const bad = await hfetch('POST /api/auth/login (wrong pw)', '/api/auth/login', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ username: USER_OWNER, password: 'wrong-password' }),+ })+ if (bad.status === 401) pass('wrong password', '401')+ else fail('wrong password', `status ${bad.status}`)++ res = await hfetch('POST /api/auth/login', '/api/auth/login', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ username: USER_OWNER, password: PASS }),+ })+ owner.update(res)+ if (res.status === 200) pass('login', '200, fresh session')+ else fail('login', `status ${res.status}`)++ res = await hfetch('POST /api/auth/register (other)', '/api/auth/register', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ username: USER_OTHER, password: PASS }),+ })+ other.update(res)+ if (res.status === 201) pass('second account', `201, ${USER_OTHER}`)+ else fail('second account', `status ${res.status}`)++ // duplicate username — LAST (each register POST consumes one hit from+ // the 5/hour/IP bucket; the priority accounts are already created)+ const dup = await hfetch('POST /api/auth/register (dup)', '/api/auth/register', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ username: USER_OWNER, password: PASS }),+ })+ if (dup.status === 409) pass('duplicate username', '409')+ else if (dup.status === 429) note('duplicate username', 'rate-limited (5/h/IP) — expected on back-to-back runs')+ else fail('duplicate username', `status ${dup.status}`)+ }++ // ═══ 2. ownership & read-only access ════════════════════════+ console.log('\n── 2. design ownership & read-only access')+ let designX = ''+ {+ let res = await hfetch('POST /api/designs (owner)', '/api/designs', {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: owner.header! },+ body: JSON.stringify({ name: 'smoke ownership probe', width: 800, height: 600 }),+ })+ const created = (await res.json().catch(() => null)) as { id?: string } | null+ if (res.status === 201 && created?.id) {+ designX = created.id+ probe.designs.push(designX)+ pass('owner create', `201, ${designX.slice(0, 10)}…`)+ } else fail('owner create', `status ${res.status}`)++ // owner save — fast path (fresh baseUpdatedAt, no merge)+ res = await hfetch('GET /api/designs/[id] (owner)', `/api/designs/${designX}`, { headers: { cookie: owner.header! } })+ const mine = (await res.json().catch(() => null)) as { updatedAt?: string; readOnly?: boolean } | null+ if (mine?.readOnly === false) pass('owner GET', 'readOnly=false')+ else fail('owner GET', `readOnly=${mine?.readOnly}`)++ res = await hfetch('PUT /api/designs/[id] (owner save)', `/api/designs/${designX}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json', cookie: owner.header! },+ body: JSON.stringify({+ name: 'smoke ownership probe (saved)',+ baseUpdatedAt: mine?.updatedAt,+ pages: [{ id: 'p1', background: { kind: 'solid', color: '#ffffff' }, elements: [] }],+ }),+ })+ const saved = (await res.json().catch(() => null)) as { merged?: boolean } | null+ if (res.status === 200 && !saved?.merged) pass('owner save', '200, fast path (no merge)')+ else fail('owner save', `status ${res.status} merged=${saved?.merged}`)++ // anonymous browser: link-open is read-only+ res = await hfetch('GET /api/designs/[id] (anon)', `/api/designs/${designX}`)+ const anonView = (await res.json().catch(() => null)) as { readOnly?: boolean; name?: string } | null+ if (res.status === 200 && anonView?.readOnly === true) pass('anon GET', '200, readOnly=true (link view)')+ else fail('anon GET', `status ${res.status} readOnly=${anonView?.readOnly}`)++ const anonPut = await hfetch('PUT /api/designs/[id] (anon)', `/api/designs/${designX}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json', cookie: anon.header ?? '' },+ body: JSON.stringify({ name: 'hijacked' }),+ })+ if (anonPut.status === 403) pass('anon PUT', '403 — cannot edit')+ else fail('anon PUT', `status ${anonPut.status}`)++ // a DIFFERENT signed-in account is equally read-only+ res = await hfetch('GET /api/designs/[id] (other account)', `/api/designs/${designX}`, { headers: { cookie: other.header! } })+ const otherView = (await res.json().catch(() => null)) as { readOnly?: boolean } | null+ if (res.status === 200 && otherView?.readOnly === true) pass('other-account GET', '200, readOnly=true')+ else fail('other-account GET', `status ${res.status} readOnly=${otherView?.readOnly}`)++ const otherPut = await hfetch('PUT /api/designs/[id] (other account)', `/api/designs/${designX}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json', cookie: other.header! },+ body: JSON.stringify({ name: 'hijacked by other' }),+ })+ if (otherPut.status === 403) pass('other-account PUT', '403 — ownership enforced')+ else fail('other-account PUT', `status ${otherPut.status}`)++ const csrf = await hfetch('PUT /api/designs/[id] (cross-origin)', `/api/designs/${designX}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json', origin: EVIL, cookie: owner.header! },+ body: JSON.stringify({ name: 'csrf probe' }),+ })+ if (csrf.status === 403) pass('cross-origin PUT', '403 — CSRF guard')+ else fail('cross-origin PUT', `status ${csrf.status}`)+ }++ // ═══ 3. real-time collaboration across two designs ══════════+ console.log('\n── 3. one browser, two designs (the v0.10.1 P2002 scenario)')+ let designA = ''+ let designB = ''+ {+ for (const [label, name] of [+ ['A', 'smoke realtime A'],+ ['B', 'smoke realtime B'],+ ] as const) {+ const res = await hfetch(`POST /api/designs (${label})`, '/api/designs', {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: owner.header! },+ body: JSON.stringify({ name, width: 800, height: 600 }),+ })+ const j = (await res.json().catch(() => null)) as { id?: string } | null+ if (res.status === 201 && j?.id) {+ if (label === 'A') designA = j.id+ else designB = j.id+ probe.designs.push(j.id)+ } else fail(`create design ${label}`, `status ${res.status}`)+ }+ pass('two designs created', 'A + B (one owner)')++ // one OBSERVER browser reads both streams; MAIN is "one browser in two designs"+ const obsA = new SSEReader(designA, PID_OBS)+ const obsB = new SSEReader(designB, PID_OBS)+ await obsA.open(0)+ await obsB.open(0)+ pass('SSE open', 'observer streams live on A and B')++ // interleaved heartbeats + cursors into BOTH designs — every single one+ // of these used to 502 with P2002 before migration 0004+ let hbOk = true+ for (let r = 1; r <= 4; r++) {+ const sA = await heartbeat(designA, PID_MAIN, true)+ const sB = await heartbeat(designB, PID_MAIN, true)+ if (sA !== 200 || sB !== 200) hbOk = false+ await sleep(1_200)+ }+ if (hbOk) pass('heartbeats in both designs', '8/8 interleaved (4×A + 4×B) all 200')+ else fail('heartbeats in both designs', 'some heartbeat did not return 200')++ // concurrent-create race on the same (design, pid) — belt-and-braces path+ const race = await Promise.all([+ heartbeat(designA, PID_MAIN),+ heartbeat(designA, PID_MAIN),+ heartbeat(designA, PID_MAIN),+ ])+ if (race.every((s) => s === 200)) pass('concurrent presence race', '3 simultaneous POSTs all 200 (P2002 fallback)')+ else fail('concurrent presence race', `statuses ${race.join(',')}`)++ // events into A, then into B — must stay isolated+ const eA1 = envelope(addRect('smoke-rect-A1'))+ const eA2 = envelope(rename('smoke realtime A (renamed)'))+ const eB1 = envelope(addRect('smoke-rect-B1'))+ const eB2 = envelope(rename('smoke realtime B (renamed)'))+ const fA = await flushEvents(designA, PID_MAIN, [eA1, eA2])+ const fB = await flushEvents(designB, PID_MAIN, [eB1, eB2])+ if (fA.status === 200 && fA.body?.accepted === 2) pass('flush A', '2 ops accepted')+ else fail('flush A', `status ${fA.status} accepted=${fA.body?.accepted}`)+ if (fB.status === 200 && fB.body?.accepted === 2) pass('flush B', '2 ops accepted')+ else fail('flush B', `status ${fB.status} accepted=${fB.body?.accepted}`)++ try {+ await waitFor('A events on A stream', () =>+ obsA.countEvent(eA1.eventId) === 1 && obsA.countEvent(eA2.eventId) === 1 ? true : undefined,+ )+ await waitFor('B events on B stream', () =>+ obsB.countEvent(eB1.eventId) === 1 && obsB.countEvent(eB2.eventId) === 1 ? true : undefined,+ )+ pass('event delivery', 'A ops → A stream, B ops → B stream (≤15 s)')+ } catch (err) {+ fail('event delivery', (err as Error).message)+ }++ await sleep(2_500) // let a couple more frames (with presence) land+ if (obsA.countEvent(eB1.eventId) === 0 && obsB.countEvent(eA1.eventId) === 0)+ pass('design isolation', 'no cross-design event leakage')+ else fail('design isolation', 'events leaked across designs')++ // the participant must be visible in BOTH designs simultaneously —+ // the exact state the old single-column Presence PK forbade.+ // Frames only emit on event ticks (presence is queried every 2nd tick),+ // so keep the sessions realistically active until a presence-carrying+ // frame lands on each stream — mirroring a live editing session.+ let seenA = obsA.hasPresence(PID_MAIN)+ let seenB = obsB.hasPresence(PID_MAIN)+ for (let r = 1; r <= 6 && !(seenA && seenB); r++) {+ await flushEvents(designA, PID_MAIN, [envelope(rename(`smoke realtime A (tick ${r})`))])+ await flushEvents(designB, PID_MAIN, [envelope(rename(`smoke realtime B (tick ${r})`))])+ await sleep(1_400)+ seenA = seenA || obsA.hasPresence(PID_MAIN)+ seenB = seenB || obsB.hasPresence(PID_MAIN)+ }+ if (seenA && seenB) pass('presence in both designs', 'same pid live on A and B at once')+ else fail('presence in both designs', `A=${seenA} B=${seenB}`)++ // retried flush with identical eventIds — must insert NOTHING+ const dup = await flushEvents(designA, PID_MAIN, [eA1, eA2])+ await sleep(2_000)+ if (dup.status === 200 && (dup.body?.accepted ?? 1) === 0 && obsA.countEvent(eA1.eventId) === 1)+ pass('idempotent retry', 'replayed flush accepted 0, stream unchanged')+ else fail('idempotent retry', `accepted=${dup.body?.accepted} count=${obsA.countEvent(eA1.eventId)}`)++ // ═══ 4. reconnect: drop → gap-free replay ═══════════════+ console.log('\n── 4. reconnect behaviour (SSE drop + gap-free replay)')+ const since = obsA.lastSeq()+ obsA.abort()+ await sleep(700)+ note('connection dropped', `observer A disconnected at seq=${since}`)++ const eA3 = envelope(addRect('smoke-rect-A3'))+ const eA4 = envelope(rename('smoke realtime A (renamed again)'))+ const f3 = await flushEvents(designA, PID_MAIN, [eA3, eA4])+ const dup3 = await flushEvents(designA, PID_MAIN, [eA3]) // duplicate while disconnected+ if (f3.body?.accepted === 2 && dup3.body?.accepted === 0)+ pass('events while disconnected', '2 accepted, duplicate replay accepted 0')+ else fail('events while disconnected', `${f3.body?.accepted}/${dup3.body?.accepted}`)++ const obsA2 = new SSEReader(designA, PID_OBS)+ await obsA2.open(since)+ try {+ await waitFor('replayed events', () =>+ obsA2.countEvent(eA3.eventId) === 1 && obsA2.countEvent(eA4.eventId) === 1 ? true : undefined,+ )+ const gapFree = obsA2.frames.some((f) => f.events.some((e) => e.seq > since))+ if (gapFree) pass('gap-free replay', `reconnect ?since=${since} delivered exactly the missed ops`)+ else fail('gap-free replay', 'no events beyond `since` seen')+ } catch (err) {+ fail('gap-free replay', (err as Error).message)+ }+ if (obsA2.retryHint === '1500') pass('retry hint', 'stream advertises retry: 1500 (invisible reconnect)')+ else fail('retry hint', `retry=${obsA2.retryHint}`)++ // keepalives must flow while the design is quiet+ await sleep(4_000)+ const ka = [...obsB.comments, ...obsA2.comments].filter((c) => c === 'keepalive').length+ if (ka > 0) pass('keepalives', `${ka} keepalive comments received while idle`)+ else fail('keepalives', 'none received in 4 s of idle')++ obsA2.abort()+ obsB.abort()+ }++ // ═══ 5. audio/video upload & playback semantics ═════════════+ console.log('\n── 5. audio/video upload & playback (media store)')+ let wavId: string | null = null+ let mp4Id: string | null = null+ {+ const wav = makeWav()+ // offset-guard replay probe needs a manual first chunk+ const init = await hfetch('POST /api/media (wav init)', '/api/media', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ mime: 'audio/wav', size: wav.length }),+ })+ const initJ = (await init.json().catch(() => null)) as { id?: string; chunkSize?: number } | null+ if (init.status === 201 && initJ?.id) {+ const id = initJ.id+ probe.media.push(id)+ const CHUNK = initJ.chunkSize ?? 3 * 1024 * 1024+ const c1 = wav.subarray(0, CHUNK)+ const r1 = await hfetch('PATCH /api/media chunk 1', `/api/media/${id}?offset=0`, {+ method: 'PATCH',+ headers: { 'content-type': 'application/octet-stream' },+ body: c1,+ })+ const r1j = (await r1.json().catch(() => null)) as { size?: number } | null+ if (r1.status === 200 && r1j?.size === c1.length) pass('wav chunk 1', `${c1.length} bytes`)+ else fail('wav chunk 1', `status ${r1.status}`)++ const replay = await hfetch('PATCH /api/media replay', `/api/media/${id}?offset=0`, {+ method: 'PATCH',+ headers: { 'content-type': 'application/octet-stream' },+ body: c1,+ })+ if (replay.status === 409) pass('offset guard', 'replayed chunk rejected 409')+ else fail('offset guard', `status ${replay.status}`)++ const c2 = wav.subarray(CHUNK)+ const r2 = await hfetch('PATCH /api/media chunk 2', `/api/media/${id}?offset=${CHUNK}`, {+ method: 'PATCH',+ headers: { 'content-type': 'application/octet-stream' },+ body: c2,+ })+ const r2j = (await r2.json().catch(() => null)) as { size?: number } | null+ if (r2.status === 200 && r2j?.size === wav.length) pass('wav chunk 2', `total ${r2j?.size} bytes (two chunks)`)+ else fail('wav chunk 2', `status ${r2.status} size=${r2j?.size}`)++ const badFin = await hfetch('PUT /api/media (wrong size)', `/api/media/${id}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ expectedSize: wav.length + 7 }),+ })+ if (badFin.status === 409) pass('finalize guard', 'wrong expectedSize → 409')+ else fail('finalize guard', `status ${badFin.status}`)++ wavId = (await uploadFinalize(id, wav.length)) ? id : null+ } else {+ fail('wav init', `status ${init.status}`)+ }++ // full GET — byte-exact round-trip + playback headers+ if (wavId) {+ const got = await hfetch('GET /api/media (wav)', `/api/media/${wavId}`)+ const buf = new Uint8Array(await got.arrayBuffer())+ let equal = buf.length === wav.length+ for (let i = 0; equal && i < wav.length; i++) if (buf[i] !== wav[i]) equal = false+ const ct = got.headers.get('content-type') ?? ''+ const cc = got.headers.get('cache-control') ?? ''+ const ar = got.headers.get('accept-ranges')+ if (equal) pass('wav round-trip', `${buf.length} bytes exact`)+ else fail('wav round-trip', `${buf.length} bytes (want ${wav.length})`)+ if (ct === 'audio/wav' && ar === 'bytes' && cc.includes('immutable'))+ pass('wav playback headers', 'content-type + accept-ranges + immutable cache')+ else fail('wav playback headers', `ct=${ct} ar=${ar} cc=${cc}`)++ const range = await hfetch('GET /api/media (wav range)', `/api/media/${wavId}`, {+ headers: { range: 'bytes=100-199' },+ })+ const rb = new Uint8Array(await range.arrayBuffer())+ const sliceOk = rb.length === 100 && rb.every((b, i) => b === wav[100 + i])+ if (range.status === 206 && sliceOk && (range.headers.get('content-range') ?? '').endsWith(`/${wav.length}`))+ pass('wav Range 206', 'seek slice exact + content-range')+ else fail('wav Range 206', `status ${range.status} len=${rb.length}`)+ const tail = await hfetch('GET /api/media (wav 416)', `/api/media/${wavId}`, {+ headers: { range: `bytes=${wav.length + 5}-` },+ })+ if (tail.status === 416) pass('wav Range 416', 'out-of-range rejected')+ else fail('wav Range 416', `status ${tail.status}`)+ }++ // real MP4 (H.264+AAC) — what a video element uploads+ const mp4 = makeMp4()+ if (!mp4) {+ note('mp4 probe', 'ffmpeg unavailable — video upload checks skipped')+ } else {+ mp4Id = await uploadMedia('video/mp4', mp4)+ if (mp4Id) {+ pass('mp4 upload', `${mp4.length} bytes, single chunk, finalized`)+ const got = await hfetch('GET /api/media (mp4)', `/api/media/${mp4Id}`)+ const buf = new Uint8Array(await got.arrayBuffer())+ let equal = buf.length === mp4.length+ for (let i = 0; equal && i < mp4.length; i++) if (buf[i] !== mp4[i]) equal = false+ const ct = got.headers.get('content-type') ?? ''+ if (equal && ct === 'video/mp4') pass('mp4 round-trip', 'byte-exact + content-type')+ else fail('mp4 round-trip', `equal=${equal} ct=${ct}`)+ // mid-file range — exactly what a seeking <video> issues+ const range = await hfetch('GET /api/media (mp4 range)', `/api/media/${mp4Id}`, {+ headers: { range: `bytes=200-${Math.min(1199, mp4.length - 1)}` },+ })+ const rb = new Uint8Array(await range.arrayBuffer())+ if (range.status === 206 && rb.every((b, i) => b === mp4[200 + i]))+ pass('mp4 Range 206', 'seek slice exact')+ else fail('mp4 Range 206', `status ${range.status}`)+ } else {+ fail('mp4 upload', 'upload failed')+ }+ }++ // document round-trip: audio + video elements survive save/load intact+ if (wavId && mp4Id) {+ let res = await hfetch('POST /api/designs (media doc)', '/api/designs', {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: owner.header! },+ body: JSON.stringify({+ name: 'smoke media doc',+ width: 800,+ height: 600,+ pages: [+ {+ id: 'p1',+ background: { kind: 'solid', color: '#ffffff' },+ elements: [+ {+ id: 'AUD1',+ type: 'audio',+ x: 40, y: 40, width: 420, height: 96,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${wavId}`,+ name: 'probe-clicks.wav',+ duration: 49.9,+ volume: 0.9,+ loop: false,+ autoplay: true,+ peaks: [0.1, 0.9, 0.2, 0.7],+ bpm: 120,+ beats: [0.1, 0.6, 1.1, 1.6],+ },+ {+ id: 'VID1',+ type: 'video',+ x: 40, y: 160, width: 320, height: 240,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${mp4Id}`,+ poster: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+ duration: 2,+ volume: 0.8,+ muted: false,+ loop: true,+ autoplay: true,+ trimStart: 0.2,+ trimEnd: 1.8,+ },+ ],+ },+ ],+ }),+ })+ const created = (await res.json().catch(() => null)) as { id?: string } | null+ if (res.status === 201 && created?.id) {+ probe.designs.push(created.id)+ const got = await hfetch('GET /api/designs/[id] (media doc)', `/api/designs/${created.id}`)+ const doc = (await got.json().catch(() => null)) as {+ pages?: { elements?: Record<string, unknown>[] }[]+ } | null+ const aud = doc?.pages?.[0]?.elements?.find((e) => e.id === 'AUD1')+ const vid = doc?.pages?.[0]?.elements?.find((e) => e.id === 'VID1')+ const audOk =+ aud && aud.src === `/api/media/${wavId}` && aud.bpm === 120 && Array.isArray(aud.peaks) && Array.isArray(aud.beats)+ const vidOk = vid && vid.src === `/api/media/${mp4Id}` && vid.trimStart === 0.2 && vid.trimEnd === 1.8 && typeof vid.poster === 'string'+ if (audOk && vidOk) pass('A/V document round-trip', 'audio (peaks/bpm/beats) + video (poster/trim) intact')+ else fail('A/V document round-trip', `aud=${JSON.stringify(aud).slice(0, 80)} vid=${JSON.stringify(vid).slice(0, 80)}`)+ } else {+ fail('A/V document round-trip', `create status ${res.status}`)+ }+ }++ // rejection guards still hold+ const badMime = await hfetch('POST /api/media (bad mime)', '/api/media', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ mime: 'image/png', size: 1000 }),+ })+ if (badMime.status === 415) pass('mime rejection', 'image/png → 415')+ else fail('mime rejection', `status ${badMime.status}`)+ const csrf = await hfetch('POST /api/media (cross-origin)', '/api/media', {+ method: 'POST',+ headers: { 'content-type': 'application/json', origin: EVIL },+ body: JSON.stringify({ mime: 'audio/wav', size: 10 }),+ })+ if (csrf.status === 403) pass('media CSRF', 'cross-site init rejected')+ else fail('media CSRF', `status ${csrf.status}`)+ }++ // ═══ 6. latency summary (the 30 s-hang guard) ═══════════════+ console.log('\n── 6. request latency (30 s-hang regression guard)')+ {+ const sorted = [...reqStats].sort((a, b) => b.ms - a.ms)+ const max = sorted[0]+ const slow = sorted.slice(0, 5)+ note('requests', `${reqStats.length} tracked, median ${sorted[Math.floor(sorted.length / 2)].ms} ms`)+ for (const s of slow) note('slowest', `${s.ms} ms — ${s.label} (${s.status})`)+ if (max && max.ms < 10_000) pass('latency ceiling', `max ${max.ms} ms — nowhere near the 30 s function limit`)+ else if (max) fail('latency ceiling', `max ${max.ms} ms on ${s_clean(max.label)} — investigate`)+ }++ // ═══ 7. database state ══════════════════════════════════════+ console.log('\n── 7. database state (composite Presence PK)')+ {+ const db = createScriptClient(readEnvDatabaseUrl())+ try {+ const n = await db.presence.count({ where: { id: PID_MAIN } })+ if (n === 2) pass('presence rows', 'same pid present in BOTH designs (old schema: impossible)')+ else fail('presence rows', `count=${n} (expected 2)`)+ } finally {+ await db.$disconnect()+ }+ }+}++function s_clean(label: string) {+ return label.replace(/\s+/g, ' ').trim()+}++async function uploadFinalize(id: string, expectedSize: number): Promise<boolean> {+ const fin = await hfetch('PUT /api/media (finalize)', `/api/media/${id}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ expectedSize }),+ })+ if (fin.status === 200) {+ pass('wav finalize', 'upload marked complete')+ return true+ }+ fail('wav finalize', `status ${fin.status}`)+ return false+}++/** the standalone server does not read .env — mirror the URL from it for the cleanup client */+function readEnvDatabaseUrl(): string {+ try {+ const env = readFileSync(join(process.cwd(), '.env'), 'utf8')+ const line = env.split('\n').find((l) => l.startsWith('DATABASE_URL='))+ if (line) return line.slice('DATABASE_URL='.length).trim().replace(/^["']|["']$/g, '')+ } catch {+ /* fallthrough */+ }+ const url = process.env.DATABASE_URL+ if (!url || url.startsWith('file:')) throw new Error('no postgres DATABASE_URL found (.env or env)')+ return url+}++async function cleanup() {+ console.log('\n── cleanup')+ try {+ const db = createScriptClient(readEnvDatabaseUrl())+ const p = await db.presence.deleteMany({ where: { id: { in: probe.pids } } })+ const m = await db.media.deleteMany({ where: { id: { in: probe.media } } })+ const d = await db.design.deleteMany({ where: { id: { in: probe.designs } } })+ const u = await db.user.deleteMany({ where: { username: { in: probe.users } } })+ await db.$disconnect()+ note('probe rows removed', `${d.count} designs (events cascade), ${p.count} presence, ${m.count} media, ${u.count} users (+sessions)`)+ } catch (err) {+ fail('cleanup', (err as Error).message)+ }+}++main()+ .catch((err) => {+ fail('probe crashed', err instanceof Error ? err.message : String(err))+ })+ .then(() => cleanup())+ .then(() => {+ console.log(`\n${failures === 0 ? 'ALL GREEN' : 'FAILURES PRESENT'} — ${checks - failures}/${checks} checks passed`)+ process.exit(failures === 0 ? 0 : 1)+ })+diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsxindex 15ce7ea..2457fb6 100644--- a/src/components/editor/canvas/preview-stage.tsx+++ b/src/components/editor/canvas/preview-stage.tsx@@ -46,6 +46,13 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedconst scale = size.w > 0 && size.h > 0 ? Math.min(size.w / designWidth, size.h / designHeight) : 0const offsetX = size.w > 0 ? (size.w - designWidth * scale) / 2 : 0const offsetY = size.h > 0 ? (size.h - designHeight * scale) / 2 : 0+ // v0.11.1 fix: the Konva Stage only renders once the ResizeObserver has+ // measured the container (scale > 0), but both playback effects used to+ // bail on the first run (layerRef still null) and their deps never changed+ // afterwards — so preview audio/video and entry animations silently+ // no-op'd depending on a commit-vs-observer race. `stageReady` flips once+ // the stage mounts and re-runs the effects with the layer present.+ const stageReady = scale > 0const bg = page.backgroundconst bgProps =@@ -129,7 +136,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedcancelAnimationFrame(raf)resetNodes(layer, page, bases)}- }, [page, hasAnimations, reduceMotion, playKey, designWidth, designHeight])+ }, [page, hasAnimations, reduceMotion, playKey, designWidth, designHeight, stageReady])// ── v0.11: media playback — audio elements, video frames, Beat Sync ──// Presentation/preview is where media plays (the editor canvas always@@ -160,12 +167,17 @@ export default function PreviewStage({ page, designWidth, designHeight, animated}// 2. video: swap the poster Konva image for a live <video> + redraw- const videos: Array<{ v: HTMLVideoElement; node: Konva.Image; prev: CanvasImageSource | undefined; trimEnd: number; loop: boolean }> = []+ const videos: Array<{ v: HTMLVideoElement; node: Konva.Image; prev: CanvasImageSource | undefined; trimStart: number; trimEnd: number; loop: boolean }> = []if (!reduceMotion) {for (const el of page.elements as PageData['elements']) {if (el.type !== 'video' || el.visible === false || !el.autoplay) continueconst vd = el as VideoElement- const node = layer.findOne<Konva.Image>(`#${vd.id}`)+ // v0.11.1 fix: VideoNode renders a GROUP (poster + play chip + trim+ // badge) that carries the element id — findOne('#id') returns that+ // Group, which has no .image(), so the live-frame swap silently+ // skipped EVERY video. Target the KonvaImage inside the group.+ const group = layer.findOne<Konva.Group>(`#${vd.id}`)+ const node = (group?.findOne('Image') as Konva.Image | undefined) ?? undefinedif (!node || typeof node.image !== 'function') continueconst v = document.createElement('video')v.src = vd.src@@ -174,9 +186,17 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedv.volume = clamp01(vd.volume)v.playsInline = trueconst prev = node.image() as CanvasImageSource | undefined+ // v0.11.1 fix: the trim seek must happen ONCE. Seeking inside every+ // `canplay` event self-sustains a loop (seek completes → readyState+ // transitions → canplay refires → seek back to trimStart…) that+ // freezes the video at trimStart with play() re-invoked ~130×/s.+ let didTrimSeek = falseconst onCanPlay = () => {try {- v.currentTime = vd.trimStart+ if (!didTrimSeek && vd.trimStart > 0) {+ didTrimSeek = true+ v.currentTime = vd.trimStart+ }} catch {/* seek not ready */}@@ -184,7 +204,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animated}v.addEventListener('canplay', onCanPlay)node.image(v)- videos.push({ v, node, prev, trimEnd: vd.trimEnd, loop: vd.loop })+ videos.push({ v, node, prev, trimStart: vd.trimStart, trimEnd: vd.trimEnd, loop: vd.loop })cleanups.push(() => {v.removeEventListener('canplay', onCanPlay)v.pause()@@ -226,8 +246,18 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedif (videos.length > 0 || (beatTargets.length > 0 && beatAudio && beats && !reduceMotion)) {let raf = 0const tick = () => {- for (const { v, node, trimEnd, loop } of videos) {- if (!loop && trimEnd < v.duration && v.currentTime >= trimEnd) v.pause()+ for (const { v, node, trimStart, trimEnd, loop } of videos) {+ // v0.11.1: honour the trim window — non-looping pauses at trimEnd,+ // looping wraps back to trimStart (the native loop attr wraps to 0)+ if (trimEnd < v.duration && v.currentTime >= trimEnd) {+ if (loop) {+ try {+ v.currentTime = trimStart+ } catch {+ /* seek not ready */+ }+ } else v.pause()+ }node.getLayer()?.batchDraw()}if (beatAudio && beats) {@@ -254,7 +284,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedfor (const fn of cleanups) fn()restoreBeatTargets()}- }, [page, animated, reduceMotion, playKey])+ }, [page, animated, reduceMotion, playKey, stageReady])return (<div ref={containerRef} className="w-full h-full overflow-hidden" data-testid="preview-stage">diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.tsindex 93c93c2..603184b 100644--- a/src/lib/collab/client.ts+++ b/src/lib/collab/client.ts@@ -69,6 +69,22 @@ export class CollabSession {// ── lifecycle ─────────────────────────────────────────────+ // v0.11.1 fix: the browser's online/offline events are the only reliable+ // signal for a hard network cut — a silent SSE socket (server drop, NAT+ // timeout, emulated offline) never errors, so the status used to stay+ // "live" while every flush failed and queued. Listen and reflect it:+ // offline → honest 'offline' badge ("edits save locally"); online →+ // reconnect immediately instead of waiting out the backoff.+ private onOffline = () => this.setStatus('offline')+ private onOnline = () => {+ if (this.disposed) return+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer)+ this.reconnectTimer = null+ }+ this.connect()+ }+start() {if (this.disposed) returnthis.connect()@@ -76,6 +92,10 @@ export class CollabSession {// v0.9.2: 15 s heartbeat — the server treats presence as live for 30 s,// so this still tolerates one lost beat before a collaborator fades out.this.heartbeatTimer = setInterval(() => void this.heartbeat(), 15_000)+ if (typeof window !== 'undefined') {+ window.addEventListener('offline', this.onOffline)+ window.addEventListener('online', this.onOnline)+ }// v0.10: restore ops persisted while offline and flush them as soon as// we have a connection (they carry HLC stamps, so they merge safely no// matter what happened on the server meanwhile)@@ -102,6 +122,10 @@ export class CollabSession {if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)if (this.reconnectTimer) clearTimeout(this.reconnectTimer)if (this.persistTimer) clearTimeout(this.persistTimer)+ if (typeof window !== 'undefined') {+ window.removeEventListener('offline', this.onOffline)+ window.removeEventListener('online', this.onOnline)+ }// v0.10: flush what we can one last time, then durably persist the restvoid this.flush().finally(() => this.scheduleQueuePersist(0))this.es?.close()diff --git a/src/lib/media/beat-detect.test.ts b/src/lib/media/beat-detect.test.tsindex cc883eb..eedda37 100644--- a/src/lib/media/beat-detect.test.ts+++ b/src/lib/media/beat-detect.test.ts@@ -95,8 +95,19 @@ describe('detectBpm', () => {})it('returns undefined for white noise (no periodicity)', () => {+ // v0.11.1: deterministic noise (seeded PRNG). Math.random() made this+ // test flaky — roughly one run in three drew a sample with enough+ // spurious autocorrelation to clear the detector's periodicity gate.+ let seed = 0x9e3779b9+ const rand = () => {+ seed |= 0+ seed = (seed + 0x6d2b79f5) | 0+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296+ }const noise = new Float32Array(ANALYSIS_RATE * 8)- for (let i = 0; i < noise.length; i++) noise[i] = Math.random() * 2 - 1+ for (let i = 0; i < noise.length; i++) noise[i] = rand() * 2 - 1expect(detectBpm(onsetOf(noise), ANALYSIS_RATE / Math.max(1, Math.round(ANALYSIS_RATE / 86)))).toBeUndefined()})})diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex c8fef04..32d97b4 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -432,7 +432,15 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportconst Ctx: typeof AudioContext =window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContextaudioCtx = new Ctx()- void audioCtx.resume().catch(() => { /* suspended → silent track */ })+ // v0.11.1 fix: resume() is async — a context that is still suspended+ // when the recorder starts records DIGITAL SILENCE for the whole+ // export (racy in headless browsers, possible on real ones after a+ // background-tab suspension). Wait (bounded) for it to run before+ // any audio flows; on timeout we still proceed honestly — the+ // guards below keep the export correct, just silent.+ await Promise.race([audioCtx.resume(), new Promise<void>((r) => setTimeout(r, 750))]).catch(() => {+ /* suspended → silent track */+ })audioDest = audioCtx.createMediaStreamDestination()for (const els of segmentAudio) {for (const a of els) audioCtx.createMediaElementSource(a).connect(audioDest)@@ -442,6 +450,41 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportaudioDest = null}}+ // v0.11.1 fix: WAIT for the audio to be buffered before recording starts.+ // The render loop below yields via MessageChannel in a tight cycle, which+ // starves the media element's resource-selection task — a not-yet-loaded+ // element at recorder.start() never loads during the export (readyState+ // stays 0, play() aborts in the finally) and the track records digital+ // silence. Here the main thread is still idle: the fetch completes in+ // milliseconds. Bounded at 1.5 s — a slow network still exports (silent,+ // honestly) instead of hanging.+ if (audioDest) {+ const all = segmentAudio.flat()+ await Promise.race([+ Promise.all(+ all.map(+ (a) =>+ new Promise<void>((resolve) => {+ if (a.readyState >= 3) return resolve()+ const done = () => {+ a.removeEventListener('canplay', done)+ a.removeEventListener('error', done)+ resolve()+ }+ a.addEventListener('canplay', done)+ a.addEventListener('error', done)+ try {+ a.load() // explicit resource selection — don't rely on the queued task+ } catch {+ resolve()+ }+ }),+ ),+ ),+ new Promise<void>((resolve) => setTimeout(resolve, 1_500)),+ ])+ }+const recordStream = audioDest ? new MediaStream([track, ...audioDest.stream.getAudioTracks()]) : streamconst recorder = new MediaRecorder(recordStream, {diff --git a/tests/e2e/v0110-smoke.spec.ts b/tests/e2e/v0110-smoke.spec.tsnew file mode 100644index 0000000..bc05cef--- /dev/null+++ b/tests/e2e/v0110-smoke.spec.ts@@ -0,0 +1,331 @@+import { test, expect, type APIRequestContext } from '@playwright/test'+import { execFileSync } from 'node:child_process'+import { existsSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++/**+ * v0.11.0 focused production smoke — the browser-only surface that the+ * API-level probe (scripts/smoke-v0110.ts) cannot see:+ *+ * 1. preview plays the uploaded audio + video (real preview pipeline:+ * new Audio(src) / live <video> — playback observed, not assumed)+ * 2. video export muxes the page audio (MediaRecorder + AudioContext →+ * ffprobe confirms an audio stream; volumedetect confirms non-silent)+ * 3. an edit made while offline survives the drop and syncs on reconnect+ * (server-side event watcher + reload persistence)+ *+ * Run against the production standalone server:+ * BASE_URL=http://127.0.0.1:3100 npx playwright test tests/e2e/v0110-smoke.spec.ts+ */++test.use({+ viewport: { width: 1600, height: 900 }, // the status chip is xl:and-up+ launchOptions: { args: ['--autoplay-policy=no-user-gesture-required'] },+})++const BASE = process.env.BASE_URL ?? 'http://localhost:3000'++// ── probe payloads ───────────────────────────────────────────+/** mono 16-bit PCM WAV, 120 BPM click track (decodable everywhere) */+function makeWav(seconds = 2.5): Buffer {+ const sampleRate = 44_100+ const samples = Math.floor(sampleRate * seconds)+ const buf = Buffer.alloc(44 + samples * 2)+ buf.write('RIFF', 0)+ buf.writeUInt32LE(36 + samples * 2, 4)+ buf.write('WAVE', 8)+ buf.write('fmt ', 12)+ buf.writeUInt32LE(16, 16)+ buf.writeUInt16LE(1, 20)+ buf.writeUInt16LE(1, 22)+ buf.writeUInt32LE(sampleRate, 24)+ buf.writeUInt32LE(sampleRate * 2, 28)+ buf.writeUInt16LE(2, 32)+ buf.writeUInt16LE(16, 34)+ buf.write('data', 36)+ buf.writeUInt32LE(samples * 2, 40)+ const period = sampleRate / 2 // 120 BPM+ for (let i = 0; i < samples; i++) {+ const t = i % period+ const v = t < 400 ? Math.round(Math.exp(-t / 80) * 22000 * (t % 4 < 2 ? 1 : -1)) : 0+ buf.writeInt16LE(v, 44 + i * 2)+ }+ return buf+}++/** VP8+Vorbis WebM (open codecs — decodable in stock Chromium) via ffmpeg */+function makeWebm(): Buffer | null {+ const p = join(tmpdir(), 'canvix-smoke-e2e.webm')+ try {+ if (!existsSync(p)) {+ execFileSync(+ 'ffmpeg',+ [+ '-y', '-loglevel', 'error',+ '-f', 'lavfi', '-i', 'testsrc=duration=2:size=320x240:rate=15',+ '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2',+ '-c:v', 'libvpx', '-b:v', '200k', '-c:a', 'libvorbis', '-shortest', p,+ ],+ { timeout: 30_000 },+ )+ }+ return readFileSync(p)+ } catch {+ return null+ }+}++// ── setup: upload media + create the design (anonymous, link-editable) ──+interface Setup {+ designId: string+ wavId: string+ webmId: string | null+}++const created = { designs: [] as string[], media: [] as string[] }++async function uploadMedia(request: APIRequestContext, mime: string, bytes: Buffer): Promise<string | null> {+ const init = await request.post(`${BASE}/api/media`, { data: { mime, size: bytes.length } })+ if (!init.ok()) return null+ const { id, chunkSize } = (await init.json()) as { id: string; chunkSize: number }+ created.media.push(id)+ for (let off = 0; off < bytes.length; off += chunkSize) {+ const part = bytes.subarray(off, Math.min(off + chunkSize, bytes.length))+ const r = await request.patch(`${BASE}/api/media/${id}?offset=${off}`, {+ headers: { 'content-type': 'application/octet-stream' },+ data: part,+ })+ if (!r.ok()) return null+ }+ const fin = await request.put(`${BASE}/api/media/${id}`, { data: { expectedSize: bytes.length } })+ return fin.ok() ? id : null+}++async function setup(request: APIRequestContext): Promise<Setup> {+ const wavId = (await uploadMedia(request, 'audio/wav', makeWav()))!+ const webmBuf = makeWebm()+ const webmId = webmBuf ? await uploadMedia(request, 'video/webm', webmBuf) : null+ const beats = Array.from({ length: 5 }, (_, i) => 0.1 + i * 0.5) // 120 BPM grid+ const res = await request.post(`${BASE}/api/designs`, {+ data: {+ name: 'v0110 browser smoke',+ width: 800,+ height: 600,+ pages: [+ {+ id: 'p1',+ background: { kind: 'solid', color: '#ffffff' },+ elements: [+ {+ id: 'AUD1', type: 'audio',+ x: 40, y: 40, width: 420, height: 96,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${wavId}`,+ name: 'probe-clicks.wav',+ duration: 2.5, volume: 0.9, loop: true, autoplay: true,+ peaks: [0.1, 0.9, 0.2, 0.7, 0.3], bpm: 120, beats,+ },+ ...(webmId+ ? [+ {+ id: 'VID1', type: 'video',+ x: 40, y: 160, width: 320, height: 240,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${webmId}`,+ poster: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+ duration: 2, volume: 0.7, muted: false, loop: true, autoplay: true,+ trimStart: 0.1, trimEnd: 1.8,+ },+ ]+ : []),+ {+ id: 'REC1', type: 'rect',+ x: 420, y: 160, width: 200, height: 140,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ fill: '#02C0CC', stroke: '', strokeWidth: 0, cornerRadius: 0,+ beatPulse: 0.8,+ },+ ],+ },+ ],+ },+ })+ if (!res.ok()) throw new Error(`design create failed: ${res.status()}`)+ const { id } = (await res.json()) as { id: string }+ created.designs.push(id)+ writeFileSync(join(tmpdir(), 'canvix-v0110-e2e-probes.json'), JSON.stringify(created))+ return { designId: id, wavId, webmId }+}++/** watch the design's event log server-side until an op of `kind` lands */+function watchForEvent(designId: string, kind: string, timeoutMs: number): Promise<void> {+ return new Promise((resolve, reject) => {+ const ctrl = new AbortController()+ const timer = setTimeout(() => {+ ctrl.abort()+ reject(new Error(`no "${kind}" event within ${timeoutMs} ms`))+ }, timeoutMs)+ void fetch(`${BASE}/api/collab/${designId}/stream?since=0&pid=node-watcher`, {+ signal: ctrl.signal,+ })+ .then(async (res) => {+ if (!res.ok) throw new Error(`watcher stream ${res.status}`)+ const reader = res.body!.getReader()+ const dec = new TextDecoder()+ let buf = ''+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ buf += dec.decode(value, { stream: true })+ if (buf.includes(`"kind":"${kind}"`)) {+ clearTimeout(timer)+ ctrl.abort()+ resolve()+ return+ }+ if (buf.length > 1_000_000) buf = buf.slice(-100_000)+ }+ } catch {+ /* aborted — expected on resolve */+ }+ clearTimeout(timer)+ reject(new Error('watcher stream ended before the event'))+ })+ .catch((err) => {+ clearTimeout(timer)+ reject(err)+ })+ })+}++async function openEditor(page: import('@playwright/test').Page, designId: string) {+ await page.goto(`/?design=${designId}`)+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })+ await expect(page.locator('.konvajs-content').first()).toBeVisible({ timeout: 30_000 })+}++// ═══ 1. preview plays the uploaded audio + video ═════════════+test('preview plays the uploaded audio and video', async ({ page, request }) => {+ test.setTimeout(120_000)+ const { designId, webmId } = await setup(request)+ test.skip(!webmId, 'ffmpeg unavailable — video playback not probeable here')+ await openEditor(page, designId)++ // instrument HTMLMediaElement.play — the exact call preview makes for+ // both audio (new Audio(src)) and video (live <video> frames)+ await page.evaluate(() => {+ const w = window as unknown as { __media: HTMLMediaElement[] }+ w.__media = []+ const orig = HTMLMediaElement.prototype.play+ HTMLMediaElement.prototype.play = function (this: HTMLMediaElement, ...args: unknown[]) {+ w.__media.push(this)+ return (orig as (...a: unknown[]) => Promise<void>).apply(this, args)+ }+ })++ await page.getByLabel('Preview design').click()++ await expect+ .poll(+ async () =>+ page.evaluate(() => {+ const m = (window as unknown as { __media?: HTMLMediaElement[] }).__media ?? []+ return m.filter((el) => el.tagName === 'AUDIO' && el.src.includes('/api/media/')).length+ }),+ { timeout: 20_000 },+ )+ .toBeGreaterThanOrEqual(1)+ await expect+ .poll(+ async () =>+ page.evaluate(() => {+ const m = (window as unknown as { __media?: HTMLMediaElement[] }).__media ?? []+ return m.filter((el) => el.tagName === 'VIDEO' && el.src.includes('/api/media/')).length+ }),+ { timeout: 20_000 },+ )+ .toBeGreaterThanOrEqual(1)++ // genuinely playing: currentTime advances on BOTH the audio and the video+ await expect+ .poll(+ async () =>+ page.evaluate(() => {+ const m = (window as unknown as { __media?: HTMLMediaElement[] }).__media ?? []+ return m.filter((el) => el.currentTime > 0.3 && !el.paused).length+ }),+ { timeout: 20_000 },+ )+ .toBeGreaterThanOrEqual(2)+})++// ═══ 2. video export muxes the page audio ════════════════════+test('video export contains a non-silent audio track', async ({ page, request }) => {+ test.setTimeout(180_000)+ const { designId } = await setup(request)+ await openEditor(page, designId)++ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()++ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 120_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ const path = (await download.path())!++ // ffprobe — the export must carry BOTH streams+ const probe = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name', '-of', 'json', path]).toString(),+ ) as { streams: { codec_type: string; codec_name: string }[] }+ const types = probe.streams.map((s) => s.codec_type)+ expect(types, `streams: ${JSON.stringify(probe.streams)}`).toContain('video')+ expect(types, `streams: ${JSON.stringify(probe.streams)}`).toContain('audio')++ // volumedetect — the audio track must be non-silent (the WAV really played+ // through the AudioContext into the recorder)+ const vol = execFileSync('sh', ['-c', `ffmpeg -i "${path}" -af volumedetect -f null - 2>&1`]).toString()+ const m = /mean_volume:\s*(-?[\d.]+) dB/.exec(vol)+ expect(m, `volumedetect output: ${vol.slice(-400)}`).not.toBeNull()+ expect(Number(m![1]), `mean_volume ${m![1]} dB — audio track is silent`).toBeGreaterThan(-55)+})++// ═══ 3. offline edit survives the drop and syncs on reconnect ═+test('an edit made offline syncs after the connection returns', async ({ page, request, context }) => {+ test.setTimeout(180_000)+ const { designId } = await setup(request)+ const sawAdd = watchForEvent(designId, 'element:add', 60_000)++ await openEditor(page, designId)+ await expect(page.locator('[title^="Live —"]')).toBeVisible({ timeout: 30_000 })++ // drop the network — the editor flags it honestly (browser offline event;+ // a silently-dead SSE socket alone never errors, v0.11.1 fix)+ await context.setOffline(true)+ await expect(page.locator('[title^="Offline —"]')).toBeVisible({ timeout: 20_000 })++ // edit while offline (the op queues durably instead of being lost)+ await page.getByRole('button', { name: 'Elements', exact: true }).first().click()+ await page.getByLabel('Add Square').click()+ await page.waitForTimeout(1_500)++ // connection returns — status returns to Live…+ await context.setOffline(false)+ await expect(page.locator('[title^="Live —"]')).toBeVisible({ timeout: 30_000 })+ // …and the queued element:add reached the server event log+ await sawAdd++ // reload — no lost work: the rectangle is in the document+ await page.reload()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })+ await page.getByRole('button', { name: 'Tools', exact: true }).first().click()+ await page.getByRole('button', { name: 'Layers', exact: true }).click()+ await expect(page.getByText('Rect', { exact: true }).first()).toBeVisible({ timeout: 20_000 })+})