Skip to content

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.

fix(v0.11.5): presence join latency — per-tick diff + announce-on-join (#4)

Ashiq Hussain Mir2c983bdf699b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 882d4d1..8c7a68a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,43 @@
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.5] — 2026-11-01
+
+A newly joined collaborator took **60–90 s to appear** for clients that
+were just *looking* at a design (QA finding F4, the one flagged most
+impactful in `research/V0114-QA-PASS.md`). Two delays stacked: the joining
+client announced nothing until its first 15 s heartbeat, and the stream
+pump only pushed a frame on design events or every 20th tick — ~64 s
+apart on a quiet design at the 3.2 s idle tick cadence.
+
+### Fixed
+- **Presence join latency — per-tick diff + announce-on-join.** The pump
+ now queries presence every tick and compares a stable key of the
+ *visible* snapshot (`id`/`name`/`color`/`cursor` — never `lastSeen`,
+ never row order, see `src/lib/collab/presence-diff.ts`) against the
+ last key it actually sent; any change pushes a frame within one tick
+ (≤ 3.2 s idle, ≤ 800 ms active) and counts as activity for the
+ adaptive backoff. `CollabSession.start()` fires one presence POST
+ immediately, so a fresh participant exists in Postgres from the first
+ moment instead of at `start() + 15 s`. Remote cursors on an idle client
+ drop from ~64 s to ≤ 3.2 s too.
+- Cost: the presence `findMany` doubles (every 2nd → every tick; 0.31 q/s
+ idle / 1.25 q/s active per client — still ~3× below the pre-v0.9.2
+ constant) while idle frame traffic is unchanged: heartbeats and row
+ reorderings don't touch the key, so the diff stays silent when nothing
+ visible changed. The every-20th-tick frame remains as a keepalive.
+
+### Added
+- `src/lib/collab/presence-diff.ts` + 13 unit tests pinning the diff-key
+ contract (changes on join/leave/name/color/cursor; silent on lastSeen,
+ reorder, cursor key order, null-vs-undefined cursor).
+- Playwright `presence-latency.spec.ts`: two contexts, client A held idle
+ past the full tick backoff, client B joins cold — A must see B within
+ 15 s and B must see A immediately. Negative-tested: fails on the
+ v0.11.4 code, passes with the fix.
+- `research/V0115-PRESENCE-JOIN-LATENCY.md` — full analysis, cost math
+ and resulting latency table.
+
## [0.11.4] — 2026-11-01
Share links looked like query strings. Every design URL a user ever
diff --git a/README.md b/README.md
index bfb5306..ef799c8 100644
--- a/README.md
+++ b/README.md
@@ -742,6 +742,9 @@ tool descriptions so agents pick the right format.
*(v0.11.1–v0.11.3)*
- [x] Canonical design URLs — `/design/<id>` share links, address-bar
sync, legacy `/?design=` links self-heal to the canonical path *(v0.11.4)*
+- [x] Presence join latency fix — per-tick presence diff + announce-on-join:
+ a new collaborator shows up for idle clients in ≤ 3.2 s (was 60–90 s),
+ remote cursors included *(v0.11.5)*
- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVP
per `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframe
sandbox with postMessage bridge, an “Apps” panel store, and 2–3
diff --git a/package-lock.json b/package-lock.json
index b2d6ae8..1ffe370 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "canvix",
- "version": "0.11.3",
+ "version": "0.11.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "canvix",
- "version": "0.11.3",
+ "version": "0.11.5",
"hasInstallScript": true,
"dependencies": {
"@imgly/background-removal": "^1.7.0",
diff --git a/package.json b/package.json
index 8d25db7..05fb2c9 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "canvix",
- "version": "0.11.4",
+ "version": "0.11.5",
"private": false,
- "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
+ "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "node scripts/build.mjs",
diff --git a/research/V0114-QA-PASS.md b/research/V0114-QA-PASS.md
index 6cf99e6..bcadbb8 100644
--- a/research/V0114-QA-PASS.md
+++ b/research/V0114-QA-PASS.md
@@ -64,6 +64,9 @@ share → auth → collaboration → comments → versions → mobile.
list per tick and send a presence-only frame when it changes (or cap
the presence cadence at ~5s). Cursor moves already ride heartbeats —
it’s joins/leaves that stall.
+ **→ FIXED in v0.11.5** (per-tick presence diff + announce-on-join;
+ `research/V0115-PRESENCE-JOIN-LATENCY.md` — the same scenario now
+ measures **1.9 s**).
- **F5 — React anti-pattern warning.** Console: “Cannot update a
component (`MagicLayersDialog`) while rendering a different component
(`CanvasStage`)”. A setState-during-render in the MagicLayers flow —
diff --git a/research/V0115-PRESENCE-JOIN-LATENCY.md b/research/V0115-PRESENCE-JOIN-LATENCY.md
new file mode 100644
index 0000000..3379342
--- /dev/null
+++ b/research/V0115-PRESENCE-JOIN-LATENCY.md
@@ -0,0 +1,79 @@
+# v0.11.5 — Presence join latency (F4) analysis & fix
+
+Follow-up to `V0114-QA-PASS.md` finding **F4** (the one flagged "most
+impactful"): *a newly joined participant takes ~60–90 s to appear for
+clients that aren't editing.* Measured in the v0.11.4 QA pass at ~90 s.
+
+## Root cause — two stacked delays
+
+**Delay 1 — the row didn't exist (0–15 s).**
+`CollabSession.start()` connects the SSE stream and schedules the presence
+heartbeat at a **15 s interval — with no immediate beat**. The only other
+thing that writes a presence row is a cursor move. A fresh collaborator
+who joins and just *looks* at the design announces nothing until
+`start() + 15 s`.
+
+**Delay 2 — the frame didn't go out (~64–90 s).**
+The stream pump (`src/app/api/collab/[designId]/stream/route.ts`) sends a
+frame only when `events.length || tick % 20 === 0`. On a quiet design the
+adaptive tick backs off 800 ms → 3.2 s (the v0.9.2 cost fix), so the
+20-tick keepalive is ~64 s apart. Presence rides those frames — so an
+idle client learns about the join only at the next keepalive, whenever
+the row from delay 1 finally landed. Worst case ≈ 15 + 64 ≈ 90 s,
+matching the measurement.
+
+## Fix
+
+1. **Per-tick presence diff** (new `src/lib/collab/presence-diff.ts`).
+ The pump queries presence **every tick** (was every 2nd) and compares a
+ stable key of the *visible* snapshot — `id`, `name`, `color`, `cursor` —
+ against the last key it actually **sent**. Any change pushes a frame
+ within one tick and counts as activity for the backoff (a collaborator
+ joining or moving a cursor keeps the pump at 800 ms, exactly like edits;
+ quiet rooms still back off to 3.2 s).
+ Deliberately **not** in the key:
+ - `lastSeen` — bumps on every 15 s heartbeat; keying on it would push a
+ frame per heartbeat and defeat the idle backoff for zero visible effect
+ - row order — the query orders by `lastSeen desc`, so heartbeats reorder
+ rows constantly; the key sorts rows by identity first
+2. **Announce on join** (`client.ts`). `start()` now fires one presence
+ POST immediately alongside `connect()`, so the row exists from the
+ first moment; the 15 s heartbeat keeps it fresh after that.
+
+## Cost
+
+The presence `findMany` doubles (every 2nd → every tick): idle
+0.16 → 0.31 q/s per client, active 0.625 → 1.25 q/s — a tiny indexed
+`take: 30` query, still ~3× below the pre-v0.9.2 constant 3.75 q/s that
+the cost fix eliminated. Idle **frame** traffic is unchanged (the diff
+only fires on real changes; heartbeats stay silent). The every-20th-tick
+frame remains as a keepalive.
+
+## Resulting latencies
+
+| Scenario | Before | After |
+| --- | --- | --- |
+| Join visible to an idle client | 60–90 s | ≤ one idle tick (~3.2 s worst case) |
+| Join visible to an active client | ≤ 1.6 s | ≤ one active tick (800 ms) |
+| Fresh client sees current room | first frame (unchanged) | first frame, now guaranteed current |
+| Remote cursor updates on an idle client | ~64 s | ≤ 3.2 s |
+
+## Verification
+
+- `presence-diff.test.ts` — 13 unit tests pinning the key contract (join /
+ leave / name / color / cursor changes; silent on lastSeen, reorder,
+ cursor key order, null-vs-undefined cursor; delimiter unambiguity).
+- `tests/e2e/presence-latency.spec.ts` — two browser contexts; client A
+ held idle 12 s (pump fully backed off), client B joins cold, A must see
+ B's avatar within 15 s (CI headroom; observed ~1–4 s locally), and B
+ must see A's avatar immediately. **Negative-tested**: with the fix
+ stashed, the test fails against the v0.11.4 code exactly as the QA pass
+ observed — it guards the regression, not the implementation.
+- Full gates on the branch: vitest 298/298, Playwright 20/20 (incl. the
+ new spec), `tsc --noEmit` clean, eslint clean.
+- Human-like two-browser pass (screenshots 15/16 in the QA archive):
+ A idle in the editor for 35+ s, B joins cold → **B's avatar visible to
+ A in 1.9 s** end-to-end (v0.11.4 QA measured the same scenario at
+ ~90 s); B's cursor arrow + name tag propagated to A's canvas in
+ **2.0 s**; closing B fades the avatar out within the 30 s presence
+ window; both sessions show both avatars, no console errors.
diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.ts
index 5507c98..cf01d5c 100644
--- a/src/app/api/collab/[designId]/stream/route.ts
+++ b/src/app/api/collab/[designId]/stream/route.ts
@@ -1,5 +1,6 @@
import { NextRequest } from 'next/server'
import { db } from '@/lib/db'
+import { presenceKey } from '@/lib/collab/presence-diff'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
@@ -35,6 +36,20 @@ const MAX_STREAM_AGE_MS = Number(process.env.CANVIX_STREAM_TTL_MS ?? 240_000)
* - the MAX(id) aggregate only every 5th tick (gap detection)
* Idle collaboration sessions now cost ~10× less; active editing latency
* is unchanged (first event after activity still arrives in ≤ 800 ms).
+ *
+ * v0.11.5 (F4, research/V0114-QA-PASS.md): frames used to go out only when
+ * design events existed or every 20th tick — so an IDLE client learned that
+ * someone JOINED only via that keepalive: 20 ticks at the 3.2 s idle cadence
+ * ≈ 64–90 s of invisible collaborator. Presence is now queried every tick
+ * and diffed against the last snapshot actually SENT (presenceKey: id /
+ * name / color / cursor — never lastSeen, never row order); any visible
+ * change pushes a frame within one tick (≤ 3.2 s idle, ≤ 800 ms active) and
+ * counts as activity for the backoff. Cost: the presence findMany doubles
+ * (every 2nd → every tick: 0.31 q/s idle, 1.25 q/s active per client — a
+ * tiny indexed take-30 query, still ~3× below the pre-v0.9.2 constant
+ * 3.75 q/s), while idle FRAME traffic is unchanged: the diff only fires on
+ * real changes, and heartbeats (15 s) reorder rows and bump lastSeen
+ * without touching the key.
*/
export async function GET(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
@@ -61,6 +76,10 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
let lastSeq = since
let tick = 0
let delay = 800
+ // v0.11.5: last presence key actually sent to THIS client (null =
+ // nothing sent yet — the first tick always counts as a change, which
+ // also preserves the historical send-a-frame-immediately-on-connect)
+ let lastPresenceKey: string | null = null
const send = (frame: unknown) => {
if (closed) return
@@ -100,15 +119,14 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
orderBy: { id: 'asc' },
take: 200,
}),
- // v0.9.2: presence every 2nd tick — clients heartbeat every 15 s,
- // so a 1.6 s refresh window (when active) is still real-time.
- tick % 2 === 0
- ? db.presence.findMany({
- where: { designId, lastSeen: { gt: new Date(Date.now() - 30_000) } },
- orderBy: { lastSeen: 'desc' },
- take: 30,
- })
- : Promise.resolve([]),
+ // v0.11.5: presence EVERY tick — the diff gate needs a fresh
+ // snapshot to detect a join within one tick (was every 2nd under
+ // the old send-only-every-20th-tick regime; see header note)
+ db.presence.findMany({
+ where: { designId, lastSeen: { gt: new Date(Date.now() - 30_000) } },
+ orderBy: { lastSeen: 'desc' },
+ take: 30,
+ }),
// v0.9.2: the MAX(id) aggregate only matters for gap detection
// after pruning — every 5th tick is plenty.
tick % 5 === 0
@@ -128,7 +146,20 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
// only send a frame when something actually changed (plus periodic keepalive)
const filteredPresence = presence.filter((p) => p.id !== pid)
- if (events.length || tick % 20 === 0) {
+ // v0.11.5 (F4): diff the VISIBLE presence against what this client
+ // was last told — a join/leave/cursor/name/color change pushes a
+ // frame within one tick instead of waiting for the 20-tick
+ // keepalive (~64 s at the idle cadence). Keyed without lastSeen
+ // and row order (see presence-diff.ts) so heartbeats stay silent.
+ const presenceSnapshot = filteredPresence.map((p) => ({
+ id: p.id,
+ name: p.name,
+ color: p.color,
+ cursor: p.cursor,
+ }))
+ const currentKey = presenceKey(presenceSnapshot)
+ const presenceChanged = currentKey !== lastPresenceKey
+ if (events.length || presenceChanged || tick % 20 === 0) {
const frame = {
events: events.map((e) => ({
seq: Number(e.id),
@@ -150,6 +181,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
seq: serverSeq,
}
send(frame)
+ lastPresenceKey = currentKey
} else {
comment('keepalive')
}
@@ -162,7 +194,10 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
/* pruning is best-effort */
}
}
- return events.length > 0
+ // presence changes are activity too: a collaborator joining or
+ // moving a cursor keeps this pump hot (800 ms) exactly like edits
+ // do — idle backoff resumes the moment the room goes quiet
+ return events.length > 0 || presenceChanged
} catch (err) {
console.error('[collab/stream] tick failed', err)
comment('retry')
diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.ts
index 603184b..a84dd43 100644
--- a/src/lib/collab/client.ts
+++ b/src/lib/collab/client.ts
@@ -15,7 +15,11 @@ import {
* - local ops queue and flush every 400 ms (≤ 20 per flush)
* - cursor updates throttled (~300 ms), presence heartbeat every 15 s
* (v0.9.2: was 120 ms / 5 s — each write is a remote-DB upsert, and
- * the old rates let a single moving mouse generate ~8 writes/s)
+ * the old rates let a single moving mouse generate ~8 writes/s);
+ * v0.11.5: one announce fires immediately on join too — a fresh
+ * collaborator's presence row used to appear only at the first 15 s
+ * heartbeat, stacking an invisible-participant delay on top of the
+ * stream's old every-20th-tick frame cadence (QA finding F4)
* - reconnect with exponential backoff (0.5 s → 8 s), gap-free replay via ?since
* - v0.10 offline merge: the op queue and the replay cursor persist
* (IndexedDB / localStorage) — edits made offline survive reloads and
@@ -88,6 +92,10 @@ export class CollabSession {
start() {
if (this.disposed) return
this.connect()
+ // v0.11.5 (F4): announce on join, not at the first 15 s heartbeat —
+ // the server's per-tick presence diff can only show what exists in
+ // Postgres, and other clients' frames were waiting on this row
+ void this.heartbeat()
this.flushTimer = setInterval(() => void this.flush(), 400)
// 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.
diff --git a/src/lib/collab/presence-diff.test.ts b/src/lib/collab/presence-diff.test.ts
new file mode 100644
index 0000000..8328a45
--- /dev/null
+++ b/src/lib/collab/presence-diff.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest'
+import { presenceKey } from './presence-diff'
+
+/**
+ * v0.11.5 (F4): the stream pump diffs presence per tick with presenceKey.
+ * Contract under test — the key changes iff what the client RENDERS changes:
+ * changes: join, leave, name, color, cursor (content)
+ * silent : lastSeen bumps, row reordering, cursor key order, null vs
+ * undefined cursor
+ * A false "change" costs a spurious frame per heartbeat and defeats the
+ * v0.9.2 idle backoff; a false "same" costs an invisible collaborator.
+ */
+
+const alice = { id: 'p_alice', name: 'Alice', color: '#FF5C8A', cursor: null }
+const bob = { id: 'p_bob', name: 'Bob', color: '#00C4CC', cursor: null }
+
+describe('presenceKey', () => {
+ it('is stable for identical snapshots', () => {
+ expect(presenceKey([alice, bob])).toBe(presenceKey([alice, bob]))
+ })
+
+ it('is stable for empty snapshots', () => {
+ expect(presenceKey([])).toBe(presenceKey([]))
+ })
+
+ it('changes when a collaborator joins', () => {
+ expect(presenceKey([alice])).not.toBe(presenceKey([alice, bob]))
+ })
+
+ it('changes when a collaborator leaves', () => {
+ expect(presenceKey([alice, bob])).not.toBe(presenceKey([alice]))
+ })
+
+ it('changes when a display name changes', () => {
+ expect(presenceKey([alice])).not.toBe(presenceKey([{ ...alice, name: 'Alice II' }]))
+ })
+
+ it('changes when a color changes', () => {
+ expect(presenceKey([alice])).not.toBe(presenceKey([{ ...alice, color: '#7630D7' }]))
+ })
+
+ it('changes when a cursor appears or moves', () => {
+ const idle = presenceKey([alice])
+ const page1 = presenceKey([{ ...alice, cursor: { page: 0, x: 10, y: 20 } }])
+ const moved = presenceKey([{ ...alice, cursor: { page: 0, x: 30, y: 20 } }])
+ expect(idle).not.toBe(page1)
+ expect(page1).not.toBe(moved)
+ })
+
+ it('changes when a cursor selection changes', () => {
+ const plain = presenceKey([{ ...bob, cursor: { page: 0, x: 1, y: 2 } }])
+ const selecting = presenceKey([
+ { ...bob, cursor: { page: 0, x: 1, y: 2, selection: ['el_1'] } },
+ ])
+ expect(plain).not.toBe(selecting)
+ })
+
+ it('ignores row order (lastSeen-desc reordering on heartbeats)', () => {
+ expect(presenceKey([alice, bob])).toBe(presenceKey([bob, alice]))
+ })
+
+ it('ignores lastSeen entirely (heartbeats must stay silent)', () => {
+ // lastSeen is not part of the type on purpose — prove extra fields
+ // cannot leak into the key
+ const withStale = [{ ...alice, lastSeen: new Date('2026-01-01') }] as never[]
+ const withFresh = [{ ...alice, lastSeen: new Date('2026-12-31') }] as never[]
+ expect(presenceKey(withStale)).toBe(presenceKey(withFresh))
+ })
+
+ it('treats null and undefined cursors as equal', () => {
+ expect(presenceKey([alice])).toBe(
+ presenceKey([{ id: 'p_alice', name: 'Alice', color: '#FF5C8A', cursor: undefined }]),
+ )
+ })
+
+ it('ignores cursor object key order', () => {
+ const a = presenceKey([{ ...alice, cursor: { page: 0, x: 1, y: 2, selection: ['a', 'b'] } }])
+ const b = presenceKey([{ ...alice, cursor: { selection: ['a', 'b'], y: 2, x: 1, page: 0 } }])
+ expect(a).toBe(b)
+ })
+
+ it('does not let field values blur into each other', () => {
+ // distinct separators must keep (id, name) pairs unambiguous
+ const one = [{ id: 'ab', name: 'c', color: '#111111', cursor: null }]
+ const two = [
+ { id: 'a', name: 'bc', color: '#111111', cursor: null },
+ ]
+ expect(presenceKey(one)).not.toBe(presenceKey(two))
+ })
+})
diff --git a/src/lib/collab/presence-diff.ts b/src/lib/collab/presence-diff.ts
new file mode 100644
index 0000000..44981e9
--- /dev/null
+++ b/src/lib/collab/presence-diff.ts
@@ -0,0 +1,56 @@
+/**
+ * Presence diff key (v0.11.5 — F4 fix).
+ *
+ * The collab stream pump only pushed a frame every 20th tick when a design
+ * was quiet, so an idle client learned about a *joining* collaborator only
+ * via that keepalive — 60–90 s at the 3.2 s idle tick cadence (QA finding
+ * F4, research/V0114-QA-PASS.md). The pump now compares each tick's visible
+ * presence snapshot against the last one it sent and pushes immediately on
+ * any change; this module computes the comparison key.
+ *
+ * What counts as "visible" (and therefore as a change):
+ * id, name, color, cursor — everything the client renders
+ * What deliberately does NOT count:
+ * lastSeen — bumps on every 15 s heartbeat;
+ * keying on it would push a frame per
+ * heartbeat and defeat the v0.9.2
+ * idle backoff for no visible effect
+ * row order — the query orders by lastSeen desc, so
+ * heartbeats reorder rows constantly;
+ * the key sorts rows by identity first
+ *
+ * Pure and dependency-free so it can be unit-tested in isolation.
+ */
+
+export interface PresenceRowLike {
+ id: string
+ name: string
+ color: string
+ cursor: unknown
+}
+
+/** Deterministic JSON: object keys sorted recursively, arrays in order. */
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== 'object') {
+ return JSON.stringify(value) ?? 'null'
+ }
+ if (Array.isArray(value)) {
+ return `[${value.map(stableStringify).join(',')}]`
+ }
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, v]) => v !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`
+}
+
+/**
+ * Stable comparison key for a presence snapshot. Two snapshots produce the
+ * same key iff they render identically (same collaborators, same visible
+ * attributes, cursors equal as JSON modulo key order).
+ */
+export function presenceKey(rows: PresenceRowLike[]): string {
+ return rows
+ .map((r) => [r.id, r.name, r.color, stableStringify(r.cursor ?? null)].join('\u0001'))
+ .sort()
+ .join('\u0002')
+}
diff --git a/tests/e2e/presence-latency.spec.ts b/tests/e2e/presence-latency.spec.ts
new file mode 100644
index 0000000..e339bdc
--- /dev/null
+++ b/tests/e2e/presence-latency.spec.ts
@@ -0,0 +1,71 @@
+import { test, expect } from '@playwright/test'
+
+/**
+ * v0.11.5 (F4, research/V0114-QA-PASS.md): presence join latency.
+ *
+ * The stream pump used to send frames only on design events or every 20th
+ * tick, so a client sitting IDLE in the editor learned about a new
+ * collaborator only via the 20-tick keepalive — measured at 60–90 s in the
+ * v0.11.4 QA pass. The pump now diffs presence per tick and pushes within
+ * one tick (≤ 3.2 s idle).
+ *
+ * This test holds client A idle long enough for its pump to reach the full
+ * 3.2 s backoff, then joins client B cold and requires B's avatar in A's
+ * top bar well inside the old 60 s failure mode. The 15 s bound leaves
+ * generous CI headroom; locally the fix lands in ~1–4 s.
+ *
+ * Needs a database (design + presence APIs) — see playwright.config.ts.
+ */
+test.setTimeout(120_000)
+
+test('a joining collaborator becomes visible to an idle client within seconds', async ({ browser }) => {
+ const ctxA = await browser.newContext()
+ const ctxB = await browser.newContext()
+ const pageA = await ctxA.newPage()
+ const pageB = await ctxB.newPage()
+
+ // deterministic identities, seeded before any app code runs
+ await pageA.addInitScript(() =>
+ localStorage.setItem(
+ 'canvix-identity-v1',
+ JSON.stringify({ id: 'p_e2e_alice', name: 'Alice E2E', color: '#FF5C8A' }),
+ ),
+ )
+ await pageB.addInitScript(() =>
+ localStorage.setItem(
+ 'canvix-identity-v1',
+ JSON.stringify({ id: 'p_e2e_bob', name: 'Bob E2E', color: '#00C4CC' }),
+ ),
+ )
+
+ // A creates a design and goes idle in the editor
+ await pageA.goto('/')
+ await pageA.getByRole('button', { name: /start designing/i }).first().click()
+ await pageA
+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')
+ .first()
+ .click()
+ await expect(pageA.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })
+ const designUrl = pageA.url()
+
+ // let A's pump back off to the idle cadence (worst case for the bug):
+ // 800 → 1200 → 1800 → 2700 → 3200 ms takes ~9.7 s of quiet
+ await pageA.waitForTimeout(12_000)
+
+ // B joins cold — only a presence upsert announces them (no design events)
+ const joinedAt = Date.now()
+ await pageB.goto(designUrl)
+ await expect(pageB.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })
+
+ // A must see B's avatar chip promptly (the old bug: 60–90 s)
+ await expect(pageA.locator('[title="Bob E2E"]')).toBeVisible({ timeout: 15_000 })
+ const latencyMs = Date.now() - joinedAt
+ expect(latencyMs, 'idle-client join latency').toBeLessThan(15_000)
+
+ // and B's fresh stream carries the current room state immediately:
+ // A's avatar shows in B's top bar without waiting for any keepalive
+ await expect(pageB.locator('[title="Alice E2E"]')).toBeVisible({ timeout: 15_000 })
+
+ await ctxA.close()
+ await ctxB.close()
+})