Library app design — lessons from SillyTavern
The crescent library app is the entry-point UI that lists installed daemon apps (which includes chat cards — see "Cards are apps" below) and lets users search, filter, tag, and launch them. It replaces SillyTavern's character browser.
ST at 23k cards is unusable: multi-second freezes on every keystroke, browser hangs on basic operations, 16 MB payloads for a tag click. Investigating the root causes surfaced a clear set of rules the crescent library app must follow. This doc records what ST does wrong and the corresponding prescription. Cross-reference: daemon-transport.md for transport-layer decisions and platform-design.md for the vendoring model.
All file:line pointers below refer to SillyTavern at /mnt/ssd/ai/SillyTavern.
Cards are apps
In crescent, a chat card is not a file owned by one "card app." A card IS a daemon app — its own row in app_index, its own origin, its own caps, its own storage, its own launch token. 23k cards = 23k installed apps. This is load-bearing for everything below: the library is a browser over apps, search is FTS5 over apps, tags are a join on app_tags, and the launch flow already exists.
Templated install
CCv2 import (lib/platform/apps/charactercardv2/import.lua) creates a new app per imported PNG. The new app directory vendors its own copy of the CCv2 chat UI code plus the card's data (parsed JSON, lorebook, PNG thumbnail). This follows the platform's vendoring model: the app directory is the unit of distribution, fully self-contained.
Install cost is ~50 KB of vendored code per card. At 23k cards that's ~1.15 GB — negligible next to the card PNGs themselves (ST collections are commonly tens of GB). Independent per-card install means:
- Each card updates (or doesn't) independently when CCv2 ships a fix.
- Users can customize one card's UI without affecting others.
- PNG export is straightforward: re-tarball the vendored app dir.
Content-addressed shared storage (hardlinks into ~/.crescent/store/<sha>/) is a graceful later upgrade if disk becomes a complaint — install-time behavior changes, on-disk layout still looks like a self-contained app dir, distribution format unchanged. Non-breaking.
Multiple apps, shared code — not one app with pluggable storage
When a foreign data layout needs to be supported (SillyTavern's filesystem, KoboldAI, a Steam library, loose PNG folders), the temptation is "add a storage adapter to the canonical app so it can consume anything." Resist. The correct move is one app per data layout, with shared code factored into a normal vendored library.
Current plan:
lib/platform/apps/charactercardv2/— canonical crescent card app. One storage format (crescent-native, its own app dir per card, its own SQLite). No adapter interface, no configurable storage. Simple.lib/platform/apps/sillytavern/— separate app, purpose-built for~/SillyTavern/public/. Knows ST's directory layout, tag_map JSON, JSONL chats, PNG tEXt chunks. Reads and writes ST's format directly. Also no adapter interface.lib/ccv2-ui/(or similar) — shared library, not an app. UI components, markdown rendering, chat rendering, LLM-cap wiring. Both apps vendor it like any other dep.
Why this beats one-app-with-adapters:
- Neither app grows a storage abstraction. Each is as simple as the current charactercardv2 implementation. No interface to over-engineer.
- The canonical app can evolve its data model freely (proper chat trees, typed tags) without worrying about round-tripping to ST's format.
- The ST app can break when ST changes its on-disk format, or be deleted entirely when the user migrates, without touching anything else. It is explicitly legacy support, not a first-class concern of the canonical design.
- Shared code lives in a normal library. Same pattern the platform already uses everywhere.
- User opinion is expressed by which app they install, not by a settings toggle inside one app.
Generalizes to other foreign layouts: a KoboldAI-formatted card store gets its own app. A loose-PNG-directory browser gets its own app. Steam, itch, RPG Maker, Ren'Py, Godot, Love2D, .desktop files — one app per source, each trivially hackable, all sharing common launcher-helper libs if useful. See "Apps are cheap" in platform-design.md.
Source adapters (the library layer)
The library itself is not a single query over app_index. It's a merged view across sources. A source can be:
- The installed-apps table —
app_indexrows. First-class, launched via the existing mint-token flow. FTS5, tags, thumbnails, ETags, sub-5ms queries. - A filesystem-backed app — e.g. the SillyTavern app enumerates every PNG under its configured ST directory and surfaces each as a library entry. Not an
app_indexrow — a virtual entry the library queries from the ST app via the same interface as installed apps. - A launcher-backed app — Steam, itch, etc. Enumerates external games, surfaces each as a library entry. Launch runs a shell command or opens an external URL. No daemon origin, no caps.
"Source" here means an installed app that exposes a discovery endpoint; the library calls each one with its current query (paginated, filtered) and merges results. The library itself stays dumb — it doesn't know about ST or Steam; it only knows how to ask each installed source for a page of entries.
/discover endpoint contract
Every source adapter app exposes GET /discover with these query params:
| Param | Type | Default | Description |
|---|---|---|---|
q | string | "" | Case-insensitive substring search on name |
limit | integer | 200 | Page size, clamped to [1, 500] |
offset | integer | 0 | Zero-based page start |
Response shape (JSON):
{
"source_name": "SillyTavern",
"total": 23649,
"limit": 200,
"offset": 0,
"entries": [
{
"id": "alice.png",
"name": "Alice",
"description": null,
"tags": [],
"thumb_url": null
}
]
}source_name— human-readable section header in the library UI.total— count of entries matching the current query (used for "N of M").id— source-local identifier, opaque to the library. For the ST adapter this is the filename. For a crescent index adapter this would be the app row id.thumb_url— the library discover proxy rewrites this to a library-origin path (/api/sources/:id/thumb/:entry_id) when the source app has a handler. The library then proxies the request in-process toGET /thumb/:entry_idon the source app handler. This keeps image loads same-origin and CSP-safe (library hasdefault-src 'self'). Source apps that support thumbnails must handleGET /thumb/:entry_id. Null when the source has no handler.descriptionandtags— null/empty is acceptable. Fill in when the source has the data (CCv2 iTXt chunk, STdata.description, etc.).
Discovery of source apps: the library queries the index for installed apps where meta.source_adapter = true. Each such app is called in parallel (future: when the source-adapter dispatch path is wired in the library). The manifest meta.source_adapter flag is the single source of truth for whether an app participates in the merged library view.
Launch of virtual entries: a virtual entry has no daemon app_id. The library launches the source app itself with ?entry=<id> appended so the source app can route to the specific card. The source app is responsible for interpreting its own entry ids.
Launch behavior for virtual entries
A virtual entry isn't an installed app, so there's no app_id to mint a token against. Two dispatch paths:
- Daemon-hosted — virtual entry resolves to "launch the source app itself, scoped to this entry." E.g. clicking an ST card launches the SillyTavern app with a path or query parameter selecting that card. The SillyTavern app is one installed app; every ST card routes into it.
- External — virtual entry carries a shell command or URL. The daemon just exec's or redirects. No crescent origin involved.
No import-on-launch flow is required by default: the SillyTavern app reads ST's files in place. If the user wants to convert an ST card into a crescent-native installed card, that's a deliberate, explicit "promote" action, not an implicit side effect of clicking.
Merged pagination
Pagination across heterogeneous sources is fragile: pulling limit=N from each source and merging breaks when one source dominates (skewed sort), and pulling full results from every source to paginate the merge defeats the point.
Resolution: per-source pagination in the UI, one section per source, each independently paginated. The user sees "Installed (200/23,412)" and "SillyTavern (200/23,649)" side by side, with "load more" per section. This sidesteps the merge problem, makes per-source perf characteristics visible, and lets slow sources not block fast ones.
Payload shape pathologies
/api/characters/all — 45 MB, no pagination
src/endpoints/characters.js:1318 readdirs every PNG and returns the lot in one JSON. 98% of bytes per card are data.creator_notes (median ~19 KB, worst case 337 KB). There is no ?limit, no ?since, no filter parameter. "Shallow mode" exists but still ships creator_notes.
/api/settings/get — 16 MB, refetched on demand
15.5 MB of the blob is one JSON-encoded settings string. Inside:
tag_map8.87 MB —{avatar → [tag_uuids]}, O(cards × avg_tags).tags1.97 MB — 9,291 tag registry entries.- Everything else combined < 300 KB.
Two calls per page load is structural: public/scripts/world-info.js:2062 and public/scripts/extensions/quick-reply/index.js:56 each refetch the whole 16 MB to pluck one field (world_names, quickReplyPresets).
Prescription
- Paginated listing:
GET /cards?limit=200&offset&q&tag&sort=...→ 80–120 B per row{id, name, avatar_url, fav, date_added, date_last_chat, chat_size, tags:[id…]}. Nocreator_notes, nodata.*. 200 rows ≈ 20 KB. - Full card body only on demand:
GET /cards/:id. - Tag membership is a join:
card_tags(card_id, tag_id)in SQLite. Never ship atag_mapblob. Filter by tag isWHERE tag_id=?. - Tag registry:
GET /tagswith ETag. Fetched once, 304 thereafter. - Thumbnails:
GET /cards/:id/thumb?size=128→ raw bytes with longCache-Control. Never base64 into JSON. - Split settings per domain:
/settings/ui,/settings/presets/openai,/world-info/names,/quick-reply/sets. Each ETagged. A UI action that needsworld_namesfetches ~1 KB. - Incremental refresh:
GET /cards?since=<mtime>for delta sync.
UI freeze pathologies
Search: 5–15 s freeze per keystroke
public/scripts/filters.js:317-322 — every keystroke calls fuzzySearchCharacters/Groups/Tags. Each of those (public/scripts/power-user.js:2119) does new Fuse(characters, {keys: 11 fields, threshold 0.2}).search(q).
Fuse's index is rebuilt from scratch every keystroke over 23k cards × 11 string keys (many multi-KB incl. description, mes_example, first_mes). Then printCharacters (public/script.js:989) fully re-renders the DOM. setFilterData (filters.js:351) also does JSON.stringify(oldData) !== JSON.stringify(data) on every call.
Per-keystroke cost: O(N · K · L) ≈ gigabytes of string scanning.
"Insane disk usage" during search is almost certainly swap/compressed-memory pressure — Fuse allocates a tokenized copy of every indexed string per call, GC-pressuring a tab already holding ~1.5 GB of parsed card data. Confirming this needs devtools Memory + iotop; cannot tell from source alone.
Chat close: 5–15 s freeze
public/script.js:10641 closeCurrentChat → select_rm_characters() → printCharacters(doFullRefresh). printCharacters (lines 989–1079) calls getEntitiesList which with bogus_folders=true runs filterByTagState twice plus entitiesFilter.applyFilters per tag entity (lines 1173–1190), plus printTagFilters 3× (lines 1005–1007), each doing Object.values(tag_map).flat() (tags.js:1554,1567) — O(cards × tags_per_card) flattening + .includes() per tag. Closing a chat should be a 2-field state flip; the list view should not re-render at all.
Tag edit: 5–15 s freeze
public/scripts/tags.js:796-797, 831-832 — addTagsToEntity / removeTagFromMap call printCharactersDebounced (same re-render as above) and saveSettingsDebounced. The save (public/script.js:7951, payload 7969–7994) POSTs a single JSON blob containing full tags (9291), full tag_map (23649), all of power_user, extension_settings, world_info, every API setting — the entire 16 MB settings file is rewritten server-side per tag toggle.
"Enable Tags as Folder": indefinite browser hang
public/scripts/power-user.js:3908 toggles #bogus_folders. With it enabled, getEntitiesList (public/script.js:1152-1216) adds every folder-tag as an entity (~9k), then sub-entities loop runs filterByTagState twice + applyFilters per folder-tag. filterByTagState (public/script.js:369) iterates all entities and tests tag membership.
Cost: O(F² · E) ≈ 9k · 9k · 32k ≈ 2.6×10¹² lookups. Not a freeze — a genuine algorithmic wall.
Prescription
- Persistent inverted index, not rebuild-per-keystroke. Build token→rowid bitsets (or trigrams) once at load; search = bitset intersection, O(query + hits). SQLite FTS5 is the natural implementation — available via
lib.sqliteand already in use for the app index. Search happens server-side, returns rowids; client fetches the page. - Mutations touch only affected rows. A tag edit is a 1-row insert or delete in
card_tags. Never rewrite "all settings" to persist a tag change. - Views are derived incrementally. Closing a chat does not refresh the list. Editing a tag updates the affected row in the rendered list, nothing else.
- Folder view is a GROUP BY, precomputed.
SELECT tag_id, COUNT(*) FROM card_tags GROUP BY tag_idfeeds the folder tree. Rendered virtualized (only visible rows in DOM). - Virtualize the DOM. At 23k rows the list must render only what's visible. Non-negotiable.
- Debounce is not a fix. ST debounces these calls — the freeze is the underlying algorithm, not the call frequency. Fix the algorithm.
Cross-cutting principle
ST conflates "state changed" with "rebuild everything." One function (printCharacters) re-enumerates all entities, re-filters, re-sorts, and re-renders on every mutation — even though pagination later slices to one page, the whole 32k set gets processed first.
The crescent rule: mutations touch only affected rows; views are derived incrementally. If an action requires O(N) work where N is the library size, that action is wrong. A library browser that works at 23k cards must work at 230k and 2.3M with the same architecture — only the dataset size changes, not the algorithms.
Pagination and latency
Pagination introduces round-trips, so the instinctive worry is "pagination is laggier on WAN." The opposite is true — pagination is strictly faster on WAN, for every metric that matters.
Initial paint
- Full list: 10 MB compressed over a 25 Mbps link ≈ 3 s transfer + parse + render.
- Paginated: 20 KB first page arrives in ~1 RTT (~200 ms on Tailscale intercontinental).
Pagination wins time-to-interactive by an order of magnitude.
Scroll
Each page boundary costs 1 RTT. Mitigation: prefetch page N+1 when the user enters page N's last 20%. As long as scroll speed × row_height < bandwidth, the RTT is fully hidden. Generous page size (200–500 rows) keeps boundaries rare.
Search (the real latency risk)
Keystroke → query → 200 ms RTT feels sluggish if every character round-trips. Fixes:
- Debounce 150–200 ms. Users don't type faster than that on a phrase, so one RTT per debounce-window naturally masks the latency.
- Server response must be sub-5 ms so
query_time + RTT ≈ RTT. FTS5 over 23k rows is well under 1 ms, so this holds. - Send on
keydown, notkeyup— steals a few ms per keystroke.
Connection reuse
HTTP/1.1 keep-alive is load-bearing here. Without it every page fetch pays a TLS handshake (~1 extra RTT). With it, sequential page fetches are one RTT each. This is the one place transport work has leverage; HTTP/2 multiplexing would also let prefetch and foreground fetches share a connection without head-of-line, but keep-alive captures most of the win for sequential access. See daemon-transport.md for the broader HTTP/2/3 discussion — the conclusion there still stands.
What ST got wrong
ST's failure isn't "chose not to paginate." It's that ST faked pagination by slicing a fully-computed list, paying the compute cost of the full set every render and none of the bandwidth savings on the wire. The architecture has to paginate end-to-end — server query, network payload, client render — or it doesn't help.
How to use this doc
Before adding an endpoint, UI action, or mutation to the library app, check: does the hot path scale with library size? If yes, it's wrong — re-derive against SQLite indexes / FTS5 / bitset intersection before implementing. Add new pathologies here if ST-style anti-patterns reach the PR review.