Flows
Discovery
Search, selection, and canvas navigation.
Entry Points
-
Visual discovery renderer:
discovery-orbit.tsxkeeps covers as accessible DOM buttons;gallery-renderer.tsshares one motion clock with Canvas 2D ink. Position and velocity survive interruption, and persistent connections follow the seed and visible neighbors rather than resetting on focus. New connections deposit a growing brush contour with a tapered moving tip, variable pressure and a fine dry bristle. Painted material deforms with the covers; its progress survives interruption. The gesture spends its time on exposed ink rather than underneath artwork. Mounted edges preserve their reveal through interruption; fully departed edges are discarded and paint again if later recreated. There is no idle shimmer. Drag gathers the covers into a wheel (including the focused cover); release disperses them into a deterministic constellation or looser arrangement. Tapping a satellite recenters it; activating the focus explores through the existing canvas state. Wheel, arrows, Home/End and horizontal swipe remain available. The discarded linear arrangement is recoverable in experiment commitaa73cf0. -
Renderer limits: at most six mobile/seven desktop current covers plus temporary exits. The demand-driven RAF writes transforms/opacity and paints connections without React updates or layout reads per frame. Departing covers/edges fade while retaining their geometry. ResizeObserver measures the viewport; pixel density is capped at 2. Rendering stops at rest, pauses offscreen/in hidden tabs, and resolves immediately for reduced motion. Cover images, labels and hit targets remain DOM elements; WebGL is not used by Search.
-
Cover loading:
discovery-cover-image.tsxowns a source-keyed load/error state over the sharedEntityCoverImage. Deterministic ASCII discs appear after 100 ms; two static text patterns softly crossfade for at most 7.2 seconds using CSS opacity, then remain still. Image completion stops the effect and fades in the artwork without changing cover bounds or restarting canvas motion. Mounted covers retain their loaded state through focus changes; remounted covers rely on the browser cache and delayed placeholder reveal. Errors keep a static disc. Reduced motion disables all placeholder animation and fades. This treatment is limited to canvas covers. -
Route:
app/(main)/search/page.tsx; surface:discovery-map.tsx. -
Interaction:
hooks/use-discovery-canvas.ts,hooks/use-kocteau-search.ts. -
State/navigation:
lib/discovery; search ordering:lib/search/kocteau-first.ts. -
APIs:
app/api/search,app/api/discovery/map. -
Experimental ranking lives in
lib/discovery/mmr.tsand is consumed only by evaluation tests and the curator-only preview lab. It does not change Search or For You; Studio owns its access and snapshot contract. -
Seeded candidates:
lib/discovery/candidates.tsresolves the canonical provider track, then selects related artists and other releases using track/album identity and a bounded variant (0–15). Each lane has a 4.5-second shared deadline and cancellation; partial sources remain usable. Strict provider lookups fail fast, except artist top tracks retain their short enrichment retry. Browser retries are explicit so a total failure does not silently restart the whole provider fan-out. Album seeds use their highest-ranked track from a bounded twelve-track set, retaining the selected artist ID when the album omits it. Complete failure is a retryable, uncached 503, never a starter fallback. Only public pools may be CDN-cached.lib/discovery/canvas.tsranks them with scoped browser opens/revisits, unseen-track preference, lane/artist/cover diversity and a stable per-frame variation. Desktop shows the top six candidate neighbors around the seed; mobile shows the top five within its six-cover limit. This is metadata/context ranking, not audio analysis or a cross-device taste profile. -
Starter cards belong only to the unseeded canvas. A focused frame starts with its selected cover while its own candidates load. Back/Forward restores its frozen pool; legacy seeded snapshots refresh candidates without erasing history or taste memory.
-
Artist familiarity and diversity use provider artist IDs when available, with a normalized-name fallback only for missing identity. Candidate responses retain those IDs through browser ranking. Taste-memory payload version 2 migrates legacy name-only visits without guessing artist IDs, retaining their track revisits and expiry. Frozen canvas frames remain stable.
-
Candidate HTTP and Query keys use the same provider/type/ID, lane and variation inputs. Album artist fallback is part of both keys; client labels and local entity IDs do not fragment the shared public pool. The API still accepts optional legacy display metadata without using it for retrieval.
-
Header ownership: seed URLs share one Search route-transition key.
discovery-navigation.tsxanddiscovery-search.tsxrelinquish all shell portals when their route starts exiting, preventing overlapping identities, inputs and actions on desktop/mobile. -
Server catalog lookups and provider orchestration:
lib/search/catalog.ts./api/searchacceptssource=local|remote|all(defaultallretains the combined response). The hook requests local and remote phases in parallel; available matches stay visible and selectable while the other phase loads. -
Local catalog retrieval uses separate anonymous ranked SQL functions for each title/artist branch. Exact and prefix matches precede substring matches before each existing eighteen-row cap; final grouping/ranking remains TypeScript. Branches retain independent failures and the shared three-second fill budget. Deploy the reviewed
ranked_local_catalog_searchmigration before this code; missing functions fail visibly rather than issuing a legacy-query fallback. Local evidence and rollout gates distinguish coverage from sorting cost. -
Phase responses retain ranking metadata and all candidates; the client applies the same grouping, quotas, identity merging, and Kocteau boost as the combined API. Client query data also retains the per-source readiness headers. Stale/degraded 200 responses keep their usable matches without being marked fresh for 60 seconds; they do not restart on remount/reconnect. Explicit recovery refetches only failed or degraded phases when present. The hook exposes partial degradation separately from an empty-search error; the approved results presentation is unchanged. Changing the input hides matches from the previous debounced query immediately.
-
Anonymous local catalog lookups are cached for 60 seconds, tagged with
entities,artists, andstarter-tracks. Review mutations invalidateentities; artist and starter updates currently refresh through the 60-second TTL. Private data never enters this cache; transient lookup failures return partial data without caching it. Entity links use a separateentities-tagged cache keyed by sorted provider IDs, covering both phases and the combined API. Errors are caught outside the cache. ASCII query casing shares the same local cache key; original text still controls ranking. Concurrent fills for one key share a promise within a process. Fills retain their own three-second deadline for local results and canonical links, independent of one caller cancelling. A failed key has a one-second retry cooldown; pending refresh and failure maps are bounded. Cache tags and the 60-second TTL remain authoritative across instances. Observed failures remain degraded until a successful refresh; the cooldown controls retry timing only.lib/search/entity-links.tsreuses canonical identities already present in a response before looking up only unresolved provider IDs. Failed lookups retain those known identities and available candidates. The live region announces partial results as soon as they become available. -
Provider transport:
lib/deezer/request.ts; external budget:lib/search/deadline.ts. One three-second budget covers requests, retries, backoff, and artist enrichment. Completed providers remain usable when another reaches the deadline. Local catalog and entity-link lookups have separate finite budgets, so the external phase plus canonical links occupies at most about six seconds of dependency work, excluding runtime scheduling and response serialization. The legacy/api/deezer/searchroute uses the same provider deadline and canonical-link resolver. -
Client cancellation reaches external requests and retry waits. Shared public cache fills stay independent of a caller's signal. A cancelled caller receives an empty 499 response without waiting for the shared fill or logging a server failure.
-
Server-Timingreportslocal,catalog,links,rank, andtotalprocessing durations. Local and catalog work overlap, so durations are not additive. Existing sampled performance logs use scope/source fields without search text, identity, or credentials. -
Public Data API reads use a dedicated anonymous PostgREST client. Authenticated and administrative clients retain their existing boundaries. The pinned
supabase-jsconstructor does not forwarddb.retryto PostgREST; the dedicated client explicitly disables automatic retries. Its transport allows eight active reads and 32 waiting reads per process, with a three-second deadline covering queue time, headers, and the complete response body. This is a process-local guard, not a deployment-wide quota.public_data_readdiagnostics split queue, response-header and body time; timeout records identify the unfinished phase. Successful/cancelled reads follow performance sampling; failures are recorded subject to the process cap. Records contain logical table/RPC names, outcome, phase, status, size, timings and the suppression count. The existing performance controls apply, with at most ten diagnostic records per second per process. Header time includes transport/framework waits and is not a measurement of SQL execution. -
Search responses preserve their result-array contract and expose
X-Kocteau-Search-Status(fresh,stale,degraded) plusLocal,Links, andProviderheaders under the same prefix. Stale cached data and detected background refresh failures are observable even with HTTP 200. Missing local data during an outage returns 502; partial sources remain usable. These responses useCache-Control: no-store; server-side local data and provider fetch caches may still be reused. Empty-query responses use the same no-store policy.
Public starter picks use a separate 15-minute tagged cache in
lib/queries/starter.ts. Successful empty catalogs are cacheable. Failed origin
reads escape the cached callback; the optional empty fallback is returned outside
it, so a failed fill remains retryable and a failed refresh cannot replace valid
picks with an empty result. This does not change personalized starter ranking.
Correlated tracing
Existing Sentry request sampling also owns task and public-read child spans.
lib/perf.ts creates child spans for observed reads within an active sampled
request, independently of the diagnostic slow-log filter and ten-log-per-second
cap. Diagnostic logs retain both limits; SDK sampling and span/event limits
still apply to traces. Read spans carry
queue/header/body timings and outcome; HTTP round-trip time is not SQL time.
Foreground/revalidation classification remains unknown until reliably attributed.
No caller context, raw URL, query text or credentials enter these manual spans.
Run pnpm perf:journey:verify from an isolated checkout without application
environment files. It builds the real app with a synthetic loopback Data API and
a local telemetry collector, then verifies native HTTP phase timings and
browser/server trace propagation in mobile/desktop WebKit. It requires the
external Playwright installation described below and preserves homepage ISR.
See delivery evidence and limits.
Preserve
Browsing works signed out; publishing requires auth. Keep the Kocteau ranking boost, provider identity stable, and URL navigation recoverable. The music catalog and source boundaries live in catalog research.
Check
Run discovery/search tests, lint, and the web build. Check selection, browser Back, refresh, empty results, long titles, keyboard use, and touch navigation.
Check stalled providers, total provider failure, client cancellation, cache reuse, and timing headers with isolated upstream fixtures.
Search recovery regression
The shared hook waits 300 ms after typing settles. Query observers follow the current input immediately, so both old HTTP requests are cancelled while the next query waits. Catalog search does not retry failed requests automatically or refetch on window focus. Partial results and the cache for the same query remain usable; a complete failure offers Retry search without replacing the canvas.
The input and scope have separate, validated history/session snapshots, scoped by account or guest, bounded to 80 characters and eight hours. Each history entry keeps its draft so Back restores the previous query; selecting a result clears only the new entry after the canvas accepts it. Storage remains optional. Explicitly closing search, restarting, or clearing memory clears the current input.
For browser regression checks, use an isolated local Supabase stack and its local
environment values, following local setup.
Build and start the app with
NODE_OPTIONS="--import=$PWD/apps/web/tests/load/fixtures/search-recovery-upstreams.mjs"
on both commands. This preload blocks external fetches and provides the disposable
artist used by the browser fixture. The baseline may use the normal isolated
upstream preload. Never point these fixtures at a linked cloud database.
Install Playwright 1.64.1 outside the repository and its Chromium/WebKit browsers.
Set KOCTEAU_PLAYWRIGHT_MODULE to that installation's absolute
node_modules/playwright path, then run from the repository root:
SEARCH_RECOVERY_URL=http://127.0.0.1:3002 \
node apps/web/tests/load/verify-search-recovery.mjs
SEARCH_RECOVERY_BROWSER=webkit SEARCH_RECOVERY_URL=http://127.0.0.1:3002 \
node apps/web/tests/load/verify-search-recovery.mjs
SEARCH_RECOVERY_DESKTOP=1 checks the desktop surface.
SEARCH_RECOVERY_BASELINE=1 reports the old build without asserting the new
behavior. The fixture requires IPv4 loopback and blocks outbound browser requests.
It checks typing request counts, immediate cancellation, no automatic failure
retry, manual recovery, Back/reload, selected-canvas survival, and disabled storage.
For an existing disposable authenticated session,
SEARCH_RECOVERY_COOKIE_FILE accepts a private JSON file containing its cookie
header. Keep it out of Git; the fixture creates no accounts or activity.
This is a browser regression check with simulated API failures, not a load test or
a test on a physical iPhone/TikTok browser.
Gallery motion verification
lib/discovery/gallery-motion.test.ts checks interruptible trajectories, 60/120 Hz
consistency, delayed frames, small-screen bounds and degenerate ink geometry.
The browser check uses an external Playwright installation, as above; it does not
add an application dependency:
KOCTEAU_PLAYWRIGHT_MODULE=/absolute/path/to/node_modules/playwright \
GALLERY_URL=http://localhost:3000/search \
node apps/web/tests/discovery/verify-gallery-motion.mjs
Set GALLERY_BROWSER=webkit for WebKit; GALLERY_WIDTH/GALLERY_HEIGHT select
viewport dimensions. GALLERY_HEADED=1 selects a visible browser.
GALLERY_CONTROLLED_CLOCK=1 uses Playwright's animation clock for functional
geometry checks when a headless compositor throttles RAF; it omits CPU timings.
GALLERY_CHROMIUM_EXECUTABLE can select an installed Chromium.
Use a populated isolated app or an authorized Vercel preview. The local check
stubs recommendation expansion only; it does not validate providers, auth or data
writes. It measures ink-to-artwork attachment during reversals, card identity,
swipe focus, reduced motion, idle/offscreen repaints and the 3x-display resolution
cap. It reports renderer CPU time separately from visual review; workstation
measurements do not establish physical iPhone/Safari/Brave performance.
Canvas 2D was selected for pressure-shaped contours without per-frame SVG path serialization. SVG with Motion Values remains viable for a few simple curves; dash reveals alone cannot deform connections. Canvas artwork/hit testing and WebGL were unnecessary because existing DOM covers preserve the current interactions. The original motion reference video was not available in the checkout.
verify-seeded-canvas.mjs uses the same browser environment variables against a
populated isolated app. It supplies seed-specific response fixtures, asserts no
starter reuse, Back/Forward pool restoration, failure/retry behavior and a maximum
of one canvas/header/input/action owner throughout rapid navigation. It creates
no accounts or library/review writes. Provider-source and route tests separately
cover canonical identity, bounded variation/fanout, cancellation and failures.