Sangeetha-Grantha

Metadata Value
Status Completed
Version 1.0.0
Last Updated 2026-11-02
Author Sangeetha Grantha Team

Track: Mobile Preview (Admin Web)

ID: TRACK-158 Status: Completed (2026-11-02): implemented and verified; changes are uncommitted on branch track-158-mobile-preview Owner: Seshadri Created: 2026-11-02 Updated: 2026-11-02

Goal

Give curators a read-only Mobile Preview in the admin web app. Right after an edit, a curator can see (A) how the krithi, its lists and its browse views will look in the Rasika mobile app, and (B) what a rasika will get when they search, in the same order, with the reason each result matched and a warning when the search index is behind the edit.

Context

Intent

Status: Accepted Accepted by: Seshadri (chat) Accepted at: 2026-11-02

Problem

  1. A curator cannot see the mobile result of an edit without building mobile. The mobile reader orders sections, labels ragamalika ragas, picks the lyric script and shows cycle context in ways the admin editor does not show.
  2. A curator cannot see what a rasika would find. The admin console’s discovery search and the mobile search are different code paths with different visibility, filters and result groups (see the discrepancy list in the Spec). A curator who checks the admin search has not checked what mobile users get.
  3. An edit does not reach hybrid or semantic search by itself. Nothing in the backend writes search_documents; only the Python worker does (embed_catalogue.py). So a saved edit can be correct in the catalogue and absent or out of date in search, and nothing tells the curator.

Proposed outcome

A “Mobile Preview” that is read-only and built on the same data source and the same search code as mobile, with these properties:

  1. Browse and detail (Phase A): the krithi reader, Home, Explore lists, ragas and composers, collections and kshetras, rendered in a phone frame from the mobile V2 DTOs.
  2. Search (Phase B): every search feature the mobile app has, running through RasikaSearchService and the catalogue search, with a “why it matched” panel and an index-freshness banner.
  3. Unpublished and just-saved edits are visible to the preview, through a curator-only preview scope, without changing what mobile users see.
  4. No new mutations and nothing written to mobile analytics.

Constraints

Open questions (decisions for Seshadri; recommendations in the Spec)

  1. Approach: React phone-frame (recommended) or embed the Compose web target?
  2. Backend: curator-only preview endpoints that reuse the V2 services (recommended), or call the V2 routes as they are and give up previewing drafts?
  3. Placement: editor tab plus a standalone route (recommended), or a side panel?
  4. Should search preview show unpublished krithis? Recommended: off by default (mobile parity), one toggle to include them, always labelled.
  5. Is a timestamp-based “index may be out of date” signal acceptable for the first release, with an exact hash check deferred?
  6. Rate limit for preview search (recommended: 20 uncached embeddings per minute per user).

Spec

Status: Accepted Accepted by: Seshadri (chat) Accepted at: 2026-11-02

Evidence read (paths)

Mobile UI and navigation (modules/shared/presentation/src/commonMain/kotlin/com/sangita/grantha/shared/presentation/)

Mobile data path (modules/shared/mobile-data/src/commonMain/kotlin/com/sangita/grantha/shared/mobile/)

Backend

Admin web

Docs: application_documentation/03-api/search.md, 09-ai/embeddings.md, 01-requirements/domain-model.md §6, TRACK-152, TRACK-157.

Findings that drive the approach

F1. Mobile search is the V2 route, which is anonymous and published-only. The V2 handlers never read the admin role (RasikaSearchRoutes.kt comment). A curator’s admin token does not change what V2 returns. So calling V2 as it is cannot preview a draft, and is exactly right for checking what published mobile users get.

F2. Result parity is decided on the server; the client adds little. SearchPresenter only (a) sends the trimmed query with null composerId/ragaId and limit 30 for Hybrid/Semantic, (b) drops KSHETRA cards if the build has no kshetra screen, (c) renders exactTitleMatchId first, then macro cards, then the other kritis in server order, and (d) pages Lexical results 30 at a time up to 3 pages. Ranking, floors, caps and eligibility are all in RasikaSearchService and the repositories. Reusing those gives parity by construction.

F3. Lexical and vector search read different data. Catalogue lexical search (CatalogueRepository.krithiFilter) reads the live krithis, composers and ragas tables, so it reflects an edit at once. Hybrid and Semantic read search_documents and document_embeddings, which only the Python worker writes (no backend file other than the repositories mentions them). An edit is therefore visible in Titles search and can be missing or stale in All matches / Related meanings until embed_catalogue.py runs. embeddings.md says so: “new or corrected content is not automatically re-embedded”.

F4. Query embedding is the only paid step and it is already cached once. HybridSearchService.prepareQuery embeds the query once and RasikaSearchService reuses that vector for the kriti and macro retrievals. The 256-entry LRU is keyed on the trimmed query string. Lexical mode makes no Gemini call.

F5. Mobile analytics is a log line, not a table, and it is keyed on the path. plugins/CatalogueUsage.kt records route, status, elapsed time and the two session headers for paths starting /v1/catalogue or /v2/catalogue, through CatalogueUsageRecorder (a logger sink named catalogue-usage). No stored recent searches, saved searches or search-query table exists in the backend. Preview routes outside those prefixes and without the X-Rasika-* headers are never recorded.

F6. The mobile app has no autocomplete, suggestions, recent searches, saved searches or sort control. A search of presentation and mobile-data for these found none. Favourites and bookmarks exist but are on-device (FavouritesRepository, LocalDocumentStore).

F7. No Compose web target exists. modules/shared/presentation/build.gradle.kts declares android, jvm, iosArm64 and iosSimulatorArm64 only; domain and mobile-data were not found to declare a wasm or js target either (verify in Phase 0).

Discrepancies between mobile and admin (to be surfaced, not hidden)

# Aspect Mobile (V2) Admin today Effect on a curator
D1 Visibility of krithis workflow_state = PUBLISHED only (publishedComposition) GET /v1/admin/krithis/search uses publishedOnly = false Admin list shows krithis mobile users cannot find
D2 Search endpoint POST /v2/catalogue/search/* (macro cards, exactTitleMatchId) POST /v1/search/* (kriti items only) Admin never shows collection and kshetra cards or exact-title-first order
D3 Search visibility Forced published-only publishedOnly = !hasAdminRole() (admin sees unpublished indexed documents) Admin hybrid results can include krithis absent for mobile
D4 Filters on discovery composerId/ragaId always null; filters apply to Lexical only KrithiList can send composer and raga to hybrid Same query, different candidate set
D5 Result limit 30 (DISCOVERY_LIMIT); Lexical 30 per page, at most 3 pages Hybrid/Semantic limit: 30 (KrithiList.tsx); admin lexical page size 50 by default (AdminKrithiRoutes.kt) Same discovery length; lexical pages differ (30 vs 50)
D6 Lexical match fields Title, incipit, composer name/alias, raga name/alias; ordered by normalised title ascending Admin search also has lyric, tala, deity, temple, language filters Different hit sets and order
D7 Mode label vs behaviour Lexical mode is labelled “Titles & lyrics” (RasikaCopy.MODE_LEXICAL) but krithiFilter has no lyric clause n/a Candidate mobile defect: verify in Phase 0 with a lyric-only phrase
D8 Filter pickers loadFilterOptions loads only the first page (30) of ragas and composers Admin pickers load full reference data Candidate mobile limitation: verify in Phase 0
D9 Visibility modes V2 uses ALL_PUBLISHED; V1 catalogue LEGACY_KNOWN_FORMS hides UNESTABLISHED forms n/a The preview must use ALL_PUBLISHED
D10 Index freshness Hybrid/Semantic reflect the last worker run Same, but admin never says so Preview adds a freshness banner

D7 and D8 are suspected from reading code; they are not confirmed.

Requirements

A. Browse and detail

  1. A “Mobile Preview” renders, inside a phone frame, the mobile screens that show catalogue data: Home (discovery), Explore (Krithis, Ragas, Composers), krithi reader (Lyrics and Details panes), raga detail, composer detail, collections (list and detail), kshetras (list and detail), and Browse with lakshana facets.
  2. Content comes from curator-only preview endpoints that call the same CatalogueService methods and mappers as /v2/catalogue/*, with a scope that includes unpublished krithis (Backend design).
  3. The reader applies the presentation rules in SectionLabels, TamilNotation and the section-order rules for the musical form (Domain Model §6.1 to §6.5), including ragamalika raga display and Varnam captions. Where the preview ports a rule to TypeScript, a shared golden fixture test proves the port agrees with the Kotlin rule (Parity guard).
  4. The preview exposes the user preferences that change what is shown: preferred script, text size, light/dark appearance. They are preview-local (browser storage) and are never sent to the server.
  5. A krithi that is not published shows a “Not published: mobile users cannot see this” banner.
  6. After a save in the editor the open preview refreshes without a page reload (Refresh design).

B. Search

  1. Search uses the exact V2 pipeline. Modes: All matches (Hybrid, default), Related meanings (Semantic), Titles & lyrics (Lexical), behind the same “Search options” disclosure; categories Krithis, Ragas, Composers.
  2. Hybrid/Semantic requests send what mobile sends: trimmed query, null composerId/ragaId, limit 30. Lexical uses GET with page size 30 and at most 3 pages; Ragas directory unbounded pages; Composers 3 pages.
  3. Result groups render in mobile order: exact-title kriti first, then collection and kshetra cards (at most 3), then the other kritis in server order. Empty, no-results, loading and error-with-retry states match LoadStateContent and RasikaCopy.
  4. Why it matched (kritis): document kind (COMPOSITION_OVERVIEW or SECTION_PASSAGE), matched passage, similarityScore, lexicalScore, rrfScore, and, where the repository can supply them, the vector rank and lexical rank. Cards: similarity, lexical score, the floor in force and the gap over the 4th anchor. Near-miss cards: candidates that did not clear the floor are listed with the number that kept them out, so a curator can see why a card is absent.
  5. Index freshness: for the krithi being edited, an index-status call reports whether it has search documents, whether they are published, whether embeddings exist for the active profile, and whether the source was changed after the documents were written. The UI shows “Index out of date for this krithi: All matches and Related meanings may show old text. Titles & lyrics is current.” Staleness is never silent.
  6. Scope toggle: “As mobile (published only)” is the default. “Include unpublished” runs the same pipeline with publishedOnly = false, and every result that mobile would not return is badged.
  7. Hybrid/Semantic search runs only on explicit submit (Enter or button), as on mobile; no search-as-you-type.
  8. Search is read-only and writes nothing, including nothing to the usage log.

C. Safety and cost

  1. Preview routes are admin-only (requireRole(Roles.ADMIN)).
  2. Preview search is rate-limited per user (Cost).
  3. Preview routes live outside /v1/catalogue and /v2/catalogue, and the preview client sends no X-Rasika-* headers.
  4. The V2 routes, their DTOs and their results for non-preview callers are byte-for-byte unchanged (integration test).

Approach decision: React phone-frame, not embedded Compose web

  (a) React/Tailwind phone-frame (recommended) (b) Compose Multiplatform web (wasm)
Fits the admin stack Yes: Bun, Vite, TanStack Query, existing auth and API client New Gradle web target, new bundle, a second toolchain inside the admin build
Today’s state No new build target No web target exists (F7); needs one on domain, mobile-data (HTTP client engine, storage expect/actual) and presentation
Pixel fidelity Close, not identical; depends on porting RasikaTheme tokens and layouts Exact, same composables
Presenter-logic fidelity A small ported set (labels, Tamil digits, ordering, card filter) guarded by golden fixtures Exact, the same SearchPresenter
Search parity Same as (b), because results are decided on the server (F2). Only the ~4 rules in F2 are client-side Marginally easier for client rules, no help for ranking
Reflecting drafts and index status Needs preview endpoints either way Needs preview endpoints either way, plus a way to swap the client base URL and scope
Risk Visual drift over time Web target maturity, bundle size and load time unverified here; platform code (storage, files) must be made web-safe

Recommendation: (a). It costs the least, uses the existing admin conventions, and gets search parity from the single server pipeline. The drift risk is handled by a golden-fixture contract (Parity guard). (b) stays a documented alternative if visual drift proves costly; its feasibility (CMP web status for the versions in current-versions.md) was not evaluated here.

Alternative also rejected: (c) compile only mobile-data and the presenters to Kotlin/JS and keep React UI. It would share SearchPresenter logic exactly but needs the same new web target as (b) for no UI benefit.

Backend design (needs ktor-exposed-backend)

Options for reading drafts, with trade-offs:

Option How For Against
1. Call V2 as it is Admin web calls /v2/catalogue/* Zero backend change; mobile-identical Cannot show drafts or just-saved edits; its calls enter mobile analytics logs unless headers are dropped (the route category is still logged)
2. Curator-only preview routes that reuse the services (recommended) New /v1/admin/preview/... routes call CatalogueService and RasikaSearchService with a PreviewScope Same mappers and pipeline; shows drafts; outside the analytics prefix; admin-gated New routes to maintain; scope parameter must be threaded through services and repositories
3. Preview database or snapshot Separate store with draft data Isolation Not the same data source, so it breaks the fidelity goal; heavy

Option 2 detail.

UI placement

Refresh after a save

Mobile search feature map

Parity status: Full = same server code and same client rule; Port = client rule re-implemented in TypeScript behind a golden fixture; Substitute = cannot be replicated faithfully, closest equivalent given; None = the feature does not exist on mobile.

Mobile feature Where in mobile Preview equivalent Parity
Free-text query, submit on commit SearchPresenter.submit Same input, submit only Full
Categories Krithis / Ragas / Composers ExploreCategory Same tabs Full
Mode choice: All matches / Related meanings / Titles & lyrics, “Search options” disclosure KrithiSearchMode, RasikaCopy Same control and copy Port (copy strings shared by fixture)
Hybrid and Semantic kriti ranking (RRF, one doc per krithi, overview preference) RasikaSearchService, KrithiSearchRepository Same service, preview endpoint Full
Collection and kshetra cards, floor per profile, cap 3, one per anchor RasikaSearchService, MacroSearchRepository Same service; plus near-miss and floor explain Full
Exact-title-first ordering exactTitleMatchId, SearchUiState.exactTitleItem Same rule Port
KSHETRA cards dropped when the build has no kshetra screen displayableMacroHits Preview shows all kinds the destination screens support (flag fixed to current mobile value) Port
Lexical krithi search with paging (30 × 3) and title-ascending order CatalogueRepository.searchKrithis Same route Full
Raga and composer filter sheet (Lexical only), applied chips openFilters, applyFilters Same sheet and chips Port; D8 first-30 picker limit reproduced deliberately and flagged
Lakshana facets in Browse with counts BrowsePresenter, /v2/catalogue/facets Same route and chips Full
Raga and composer directory search searchRagas, searchComposers Same routes Full
Home discovery HomePresenter, /v2/catalogue/discovery Same route Full
Search over cycles and kshetras by name TRACK-152 Same service Full
Multi-script lyric search Hybrid lexical branch uses search_documents.indexed_content (trigram + ILIKE) per variant Same service; matched script shown in explain (from search_documents.script_code) Full; whether a transliterated query matches a Devanagari or Tamil passage depends on what was indexed, which the explain panel shows
Stale-request cancellation, loading, empty, error with retry generation, LoadState Same states Port
Autocomplete and suggestions not present not built None
Recent and saved searches not present not built None
Sort control not present (lexical is fixed title order) not built None
Session and interaction ids for usage logging MobileSession Not sent Substitute: omitted on purpose (R17)
Favourites and bookmarks on-device storage Not replicated; shown disabled Substitute: on-device-only
Device text size, system appearance, reduce-motion platform Preview-local toggles (text size, light/dark); reduce-motion not replicated Substitute
Back stack depth cap (8) and tab stacks RasikaNavigator Same cap in the preview navigator Port

Parity guard

API and DTO impact

Risks

Risk Mitigation
A preview that is not identical to mobile gives false confidence Same services and DTOs; parity tests; discrepancy list is shown in the UI help; the scope default is mobile-identical
Scope flag leaks drafts to mobile users Default PUBLISHED_ONLY; V2 routes never read the flag; integration test that a draft is 404 on V2 and visible on preview
Staleness heuristic is wrong (false stale or false fresh) Labelled “may be out of date”; shows both timestamps; exact check deferred to the worker
Gemini cost from repeated preview searches Shared query-vector cache, per-user limit, submit-only, no search-as-you-type
Visual drift between React and Compose Tokens ported from RasikaTheme.kt; golden fixtures; (b) as fallback
D7 or D8 turn out to be real mobile defects Reported to Seshadri as findings with a separate fix track; this track only reproduces behaviour
The scope parameter touches many repository functions Plan step 3 starts with a call-site inventory; the change ships behind tests before any UI depends on it
A new route widens the admin attack surface requireRole(ADMIN), GET and query-only POST, no body persisted

Spec open questions

Same list as in the Intent; recommendations are in the sections above.

Plan

Plan Status: Accepted (all steps done 2026-11-02; accepted 2026-11-02, Seshadri, chat: “Accept Plan”). Decisions taken as recommended in the Spec: React phone frame; preview endpoints reusing V2 services; editor tab plus /mobile-preview; draft search off by default with a labelled toggle; timestamp staleness heuristic first; 20 uncached embeddings per minute per user.

Files expected to change

Live runs (each needs Seshadri’s explicit authorisation)

Order of work

Phase 0 and A are independently shippable; B depends on 0 and on A’s shell.

# Step Check (paste output before reporting done)
Phase 0: Verify what this Spec could only read    
0.1 Confirm which of krithis, krithi_sections, krithi_lyric_variants have an updated_at (or equivalent) and what search_documents.updated_at records; decide the staleness signal. Confirm domain and mobile-data have no web target. Read all call sites of publishedComposition. Written findings in this file’s Progress Log; no code
0.2 Reproduce D6 to D8 in the dev stack with Lexical and catalogue GETs only (no Gemini): a lyric-only phrase through /v2/catalogue/krithis; the first-page limit of the filter pickers; the admin lexical ordering. Curl output and screenshots recorded; D7/D8 marked confirmed or dropped; Seshadri told, separate fix tracks proposed if confirmed
Phase A: Browse and detail    
A1 Backend scope. Add PreviewScope and thread it through the catalogue read paths; add the content routes under /v1/admin/preview/catalogue/. make test; make test-integration: (i) default scope equals V2 for the same ids, (ii) a draft is 404 on V2 and 200 on preview, (iii) non-admin gets 403, (iv) no row is added to AUDIT_LOG
A2 Shell. Route /mobile-preview, phone frame, preview navigator (stack cap 8), tokens ported from RasikaTheme.kt, TypeScript DTO types and API client, TanStack Query keys. make test-frontend; bun run lint; bun run build
A3 Reader. Sections, labels, ragamalika, Varnam caption, preformatted swara, script switch, Tamil digit superscripts, Details pane, cycle context, facet chips, not-published banner. Vitest with golden fixtures; make test-frontend; browser: open three krithis (a Krithi, a Varnam, a Ragamalika) and compare against the mobile simulator screenshot
A4 Lists and browse. Home, Explore (directories), raga and composer detail, collections, kshetras, Browse facets. make test-frontend; browser walk through each screen
A5 Editor tab and refresh. “Mobile Preview” tab for saved krithis; save invalidates preview queries. Vitest for tab visibility; browser flow: edit a section label, save, see the preview change without reload
Phase B: Search    
B1 Search backend. Preview search routes with scope and explain; near-miss macro candidates; rank columns (spike first; if not additive, ship without ranks and say so); per-user rate limit; index-status route and service. make test; make test-integration: default-scope parity with RasikaSearchService; rate limit returns 429 on the 21st request in a minute; usage interceptor records nothing for preview paths; stale/fresh/unindexed status cases. Live Hybrid/Semantic probe only after authorisation
B2 Search UI. Modes and options disclosure, Lexical paging, filter sheet, exact-title-first, macro cards with destinations, loading, empty, error and retry states. make test-frontend; browser: run five queries per mode (title, incipit, raga, a thematic phrase, a no-result phrase) and compare to the mobile simulator
B3 Explain and freshness. Why-matched panel (kind, passage, scores, ranks, floor and near-misses), scope toggle with badges, index-status banner, “edits saved since this search” prompt. make test-frontend; browser: edit a lyric, save, confirm the banner says out of date; after an authorised worker run confirm it says current
Phase C: Guard, docs, close    
C1 Parity guard. Golden fixtures shared by Kotlin and Vitest; DTO drift check; server parity test with the benchmark probes that need no live call. make test; make test-frontend; make test-integration
C2 Docs and register. Update search.md, api-contract.md, OpenAPI, an admin-web feature page, the track file; list D1 to D10 outcomes. make check-docs; python3 conductor/check-registry-sync.py
C3 End-to-end. One Playwright flow: edit → save → preview reader updates → search shows the freshness banner. make test-frontend; Playwright run (authorised)

Completion evidence (fixed)

Out of scope

Progress Log