Chat Feature Flags
Status: Phases 1–3 shipped (2026-04-30) · Phase 3.5 (Feature Settings modal + user defaults) shipped (2026-09-04) · Phase 4 blocked on Echo charging infrastructure Related: Mode-Specific Lorebook Injection, Model Profile Base Prompts & Flavors, Design Principles
Shipped state (2026-04-30): smart-skip on the embedding step, pre-send composer indicator, HowDrawer feature surface (Behavior / Active Features / Coming Soon) with real toggleable rows,
Features.*keys with provider-level pipeline gating + Memories→Summaries cascade, embedding readiness pill on the WhoDrawer "World Knowledge" lorebook cards with owner-conditional reindex action,ChatInfoModalrebranded to "How Chat Works" with expanded help content. Phase 4 (Echo cost number on the indicator) is blocked on the allocate / commit / release ledger functions for feature spend — see the Phase 4 punch list at the bottom.
Overview
Modes are built from content providers — modular pieces that supply different sections of the LLM prompt. Not every mode needs every provider. A simple assistant mode has no use for lorebooks. A quick-chat mode doesn't need recalled memories. A creative writing mode might skip scenario injection entirely.
The pipeline already only runs providers a mode's sub-prompts reference — but it doesn't take this further. There is no single place in the UI where the user can see, per conversation, what the mode supports, what they have turned on, and what that will cost in Echoes before they hit send. Embeddings in particular cost real money once Echo accounting lands, so the user needs to see — before sending — whether this message will generate one.
This feature delivers:
- Feature toggles folded into the existing HowDrawer, the canonical "how this chat operates" surface — no parallel modal entry point. Every per-conversation lever (model, mode, streaming, the new feature toggles) lives in one place.
- A two-value resolution model — mode declares supported, user declares wanted — with explicit dependency rules.
- Embedding usage as derived, visible state — shown next to the message composer so the user knows whether sending this message will spend embedding Echoes.
- A "Coming Soon" surface for features that are designed but not yet shipped (greyed-out toggle rows in HowDrawer).
Problem
No single place to see / set chat features
Today, settings are scattered: streaming lives in HowDrawer ungrouped, semantic-search granularity lives in deep settings, lorebook config in another surface, and there are no provider-level on/off toggles at all. There is no consolidated view in HowDrawer that says "here is everything that affects how this chat behaves, and here is what you've chosen."
Mode capabilities aren't surfaced to users
A mode's sub-prompts already define which providers it uses. But the UI doesn't surface this. Users tweak settings that have zero effect on the current mode and have no upfront signal of what their mode actually does.
Embeddings cost Echoes — and it's invisible
Once Echo accounting is wired into the pipeline, embedding generation will cost the user every message. Today the user has no way to know whether the next message will trigger an embedding call. They find out by watching their balance tick down. The user must see the embedding state before sending.
Users can't opt out of expensive features cleanly
The only way to disable vector search today is via granular settings (Knowledge.EnableVectorSearch, Memory.EnableVectorSearch). There is no clean per-feature toggle, and no enforced dependency rules between related features (e.g., memories require summaries).
Proposed Design
Home: the existing HowDrawer
The feature toggles live inside the existing chat-v2 HowDrawer (clientConsole/src/pages/chat-v2/components/HowDrawer.tsx), not in a separate modal. HowDrawer is already the canonical "how this chat works" surface: model, preset, mode, context budget, streaming. Adding feature toggles fits naturally — it keeps every per-conversation operational lever in one place, reuses the streaming toggle exactly where it already is, and avoids a parallel entry point next to WHO/HOW that would force users to learn a new affordance.
New sections added to HowDrawer (collapsible):
- Behavior — streaming (already there) and other UX-level toggles that don't touch the prompt pipeline.
- Active Features — the prompt-pipeline toggles described below.
- Coming Soon — designed-but-not-shipped features, greyed out, with a one-line description.
Each toggle row shows three things:
- Label + short description
- Mode support state — supported / not in this mode
- User toggle — on / off (disabled when mode doesn't support it, with an explanation)
The existing HowDrawer content (model picker, preset, mode, context budget) stays in its current section above these. Streaming moves out of its own ungrouped row and into the new Behavior section.
Section visual pattern (Active Features)
Each Active Features section in HowDrawer (Summaries / Memories / Lorebook, plus the Coming Soon rows) follows a consistent shape:
- Header row: label, short description, mode-support badge, toggle on the right.
- Expanded content below — always visible, swapped based on state:
- Feature ON → the feature's actual details: sub-toggles (e.g., Semantic recall / Semantic search), per-row warnings when applicable, lorebook readiness pills, links to relevant settings, etc.
- Feature OFF (user disabled) → a short explanation of what the feature is and what being off means in practice. Not just "turn on to configure" — informational copy that teaches.
- Plan-locked ("not in this prompt plan") → toggle disabled + explanation of why the current Base + enabled Flavors do not include the provider, with a one-line pointer at how to enable it (use a different Base or, when offered, toggle the relevant Profile Flavor).
- Dependency-locked (Memories with Summaries off) → toggle disabled + "Requires Summaries — turn Summaries on to enable Memories."
- Coming Soon → toggle disabled + a paragraph describing what the feature will do when it ships. These are the most informational of all the states because the user can't yet experience the feature any other way.
Example off-state copy (Memories):
Memory recall is off. When on, the assistant searches past summaries for content relevant to your current message and adds it to the prompt — this is what lets the character "remember" things you discussed many turns ago, even after older messages roll out of the context window. Turning it off means the assistant only sees the recent context window and your current summaries.
Example off-state copy (Lorebook):
Lorebook search is off. When on, the assistant scans your bound lorebooks for entries relevant to the current message and adds matching entries to the prompt. Without it, characters / settings / facts defined only in lorebooks won't be available to the model unless they happen to appear in recent messages.
Why always-expanded: an empty/collapsed off-state is a missed opportunity. Off is the state where the user is most likely to be unsure what they're missing — that's exactly when the explanation needs to be visible. Coming Soon is the same logic taken further.
Behavior section is shape-different. Streaming and other UX-level toggles have no meaningful "configure when on" content. The Behavior section renders flat — toggle + description, no expanded panel per row. This is intentional: Behavior is a list of independent UX preferences, not a list of feature configurators.
Renaming ChatInfoModal
The existing ChatInfoModal.tsx (clientConsole/src/pages/chat-v2/components/ChatInfoModal.tsx) currently uses the title "Chat Features" for what is actually a help/explanation modal (WHO/HOW drawer descriptions, keyboard shortcuts). Two changes:
- Rename the header to "How Chat Works" so the "Chat Features" name doesn't carry semantic conflict with the new toggle home in HowDrawer.
- Expand the content with substantive help: explain the WHO drawer (character / persona / lorebooks / custom instructions), the HOW drawer including the new feature toggles and what each one does, the composer's pre-send embedding indicator, lorebook embedding-readiness pills, the mid-conversation-change caveat, and keyboard shortcuts. The renamed modal becomes the canonical "I'm new — what does any of this mean?" surface for chat — much higher information value than today's four bullet points per drawer.
Two-Value Resolution
For every prompt-pipeline feature there are two independent values:
| Value | Source | Meaning |
|---|---|---|
effectivePromptPlan.supports(feature) |
Derived by canonical introspection from the resolved Base + enabled Flavors (Base only on unsupported doors) | Does the exact next-message plan include the provider? |
user.wants(feature) |
Conversation setting (with user-default fallback) | Does the user want this feature on for this chat? |
Effective state: active = effectivePromptPlan.supports(feature) && user.wants(feature)
A user can disable what the prompt plan supports. A user cannot enable what the current plan does not support. Older examples/code sketches below that say mode.supports are shorthand for this canonical plan-aware result; they must not be implemented as a Base-only SQL shortcut. When the plan does not support a feature, the toggle is shown locked with a "not in this prompt plan" label.
The Active Features list
Shipped, real toggles:
| Feature | Depends on | Notes |
|---|---|---|
| Summaries | — | Conversation summary generation/injection. |
| Memories | Summaries (must be on) | Recalled memories. Toggle is disabled while Summaries is off. Turning Summaries off auto-disables Memories. |
| Lorebook | — | Lorebook search and injection. |
Per-feature semantic search (embeddings)
Memory and Lorebook each have their own semantic search toggle, mirroring today's Memory.EnableVectorSearch / Knowledge.EnableVectorSearch settings. They are independent:
- Memories → Semantic recall (maps to
Memory.EnableVectorSearch). Off → memory recall falls back to FTS / keyword. - Lorebook → Semantic search (maps to
Knowledge.EnableVectorSearch). Off → lorebook search falls back to FTS / keyword.
When a user manually turns one of these off while the parent feature is on, a per-feature warning appears in that row:
Semantic recall: OFF — Memory recall will degrade to keyword/FTS only. Turn it back on for full semantic matching.
Semantic search: OFF — Lorebook search will degrade to keyword/FTS only. Turn it back on for full semantic matching.
The wording is deliberate — "degrades" rather than "disables" — because providers handle embedding = null by falling back to FTS and keyword. The chat keeps working, just with shallower recall.
One embedding per message, shared between features
Critical cost point: the user's message embedding is generated at most once per message and shared between memory recall and lorebook search. The pipeline already lazy-loads it via PipelineContextBase.GetCurrentMessageEmbeddingAsync() and caches the result for the rest of the pipeline run.
Implications for the user's mental model — and for the pre-send indicator:
- Turning either Memories-semantic or Lorebook-semantic on → one embedding will be generated, charged once.
- Turning both off → no embedding at all, no Echo spend.
- Turning both on does not double the cost — it's still one embedding, used by both providers.
So even though the toggles are independent at the feature level, the cost is a single OR across the two. The composer indicator reflects this: it says "this message will use embeddings" (single line, single cost) when at least one semantic toggle is on AND the conversation has something to search.
Lorebook embedding readiness
Bound lorebooks may not be fully embedded — embeddings are generated as a background job, and a freshly-imported or recently-edited lorebook can have entries that aren't searchable yet. Semantic search silently misses those entries.
Rather than reinventing this in the HowDrawer feature sections, the embedding-readiness pill lives on the lorebook card itself as a shared piece of UI. Anywhere a lorebook is rendered — browse, vault, chat sidebar, the modal's expanded Lorebook row — the card shows the same pill:
47/47 embedded✓ — all entries searchable.23/47 embedded — 24 entries will be missed by semantic search— partial coverage.
Actions on the card depend on ownership:
- User owns the lorebook → inline "Generate missing embeddings" button on the card that triggers the existing embedding job.
- User doesn't own it → muted hint on the card: "Ask the creator to regenerate embeddings." A copy-link / open-creator-profile affordance is enough; no built-in nag flow.
Putting the pill on the card means the HowDrawer feature sections gets readiness for free when the user expands the Lorebook row — it just renders the lorebook cards.
Memories get an aggregate readiness pill on the Memories row of the modal (12/12 memories embedded). Memories are normally embedded on archival, so this is usually complete — but exposing it gives a way to spot stuck jobs and reinforces parity with Lorebook.
Pre-send embedding indicator
The composer area shows a small indicator: "Next message will use embeddings (≈X Echoes)" or "No embedding will be generated for this message." This reflects the actual runtime check that the pipeline already performs (mode-uses-vector-providers? AND has-lorebook-entries? AND has-memories?). It is not a setting — it is a live preview of what the pipeline will do.
This means the user sees the same logic the backend will execute, before paying for it.
Coming Soon (shown, greyed out)
These features will appear in HowDrawer's Coming Soon section as greyed-out rows, with their description and a "Coming soon" label. They are not toggleable yet and have no backing setting.
- Trackers — structured state extracted and tracked across the conversation.
- Journal — long-form chronological log of conversation events.
- Living Lorebook — lorebook entries that update themselves from chat content. Live since M10 (2026-10) as a real row,
Features.EnableLivingLorebook(default on, requires Journal): the story keeps its own Cast & places and flags a fact that contradicts a lorebook entry. Saving Cast & places as lorebook entries is M11. - Picture entries — image-bearing lorebook entries.
Coming-soon rows are non-interactive — clicks do nothing. They exist to set expectations and give a single coherent picture of where chat is going. When each ships, the row flips from greyed to live without changing the modal's structure.
Phase 3.5 — Feature Settings modal + account-wide defaults (shipped 2026-09-04)
The toggles moved out of the drawer body and into a modal, and gained a user-level default, in response to a request for the feature switches to be settable once for the whole account.
Chat (conversation scope). The How drawer's Active Features section is now a compact summary — one line per feature with an On / Off / Not in this mode / Requires X badge, a "Conversation" pill on any row set for this chat, and a Feature settings link — the same shape as Context Budget → Context settings. The link opens the Feature Settings modal carrying the full rows (toggle, always-on explanation, mode/dependency locks) plus, per row:
- a source badge — Conversation (set for this chat), User (the account default from
Settings → Features) or Server Default — using the same vocabulary as the generic
settings controls (
SettingSourceBadge); - Reset to inherited on a conversation-level override, which drops the row back to the user default (or the server default if none).
Toggles still write immediately (optimistic) to PUT /api/settings/conversation/{id}/{key};
reset is DELETE on the same route and is not optimistic (the client doesn't know the inherited
value until the envelope refetch lands). The envelope carries featureSources next to
featureToggles — both read off the SAME settings snapshot in WebChatFeatureStateService
(DictionarySettingsProvider now carries the source column of fn_get_web_settings via
ISettingSourceProvider), so value and provenance can't disagree.
Settings → Features (user scope). A new Settings tab renders the same six rows through the
same FeatureSettingsList against /api/settings/user?view=features (value + source per key).
There is no mode at user scope, so nothing is mode-locked there — modeSupports absent means
"no mode context", never "supports nothing" — while the dependency locks still apply (a
Memories default is locked by a Summaries=off default, Picture entries by Lorebook=off). Every
conversation without its own value follows these; a conversation that set its own keeps it.
The tab is a staged form, not a row of live switches: it is a Settings page, so it follows
the repo's Save/Cancel pattern rather than the chat modal's write-on-click. Toggling stages into a
draft, one always-visible Save/Cancel pair commits or discards the lot, and Save is surgical — only
the keys that actually changed are sent. The blast radius is what decides it: a click here moves
every future conversation, so it gets a confirmation step; a click in the chat modal moves one
conversation and lands immediately. A staged row keeps reporting the source of its committed
value and adds a Modified marker — badging it "User" before Save would claim an account setting
that Cancel is still free to discard. Reset to inherited stays immediate in both surfaces (it
is a delete, not a value edit) — the same split DynamicSettingsSection already uses.
Resolution is unchanged — conversation → user → default via fn_get_web_settings — the
user leg simply has a UI now. Nothing changes in the pipeline.
Files: shared/src/components/features/{FeatureRow,FeatureSettingsList,featureRows,featureRowContent,featureKeys},
shared/src/chat/settings/FeatureTogglesSection.tsx (summary + modal; the writing client's How drawer and
the chat console's Story settings both render it), clientConsole/src/pages/settings/FeatureDefaultsTab.tsx +
hooks/useFeatureDefaults.ts, shared/src/components/settings/SettingSourceBadge.tsx; server Core/Pipeline/Interfaces/ISettingSourceProvider.cs,
WebChat/Services/IWebChatFeatureStateService.cs (FeatureToggleSources), FeatureSourcesDto on the
conversation detail, SettingsViewConfig["features"].
Acceptance Criteria (Phase 3.5)
The feature is not done until every box below is verified ✅ against the running product.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a user in a chat, I can open the How drawer → Active Features → Feature settings and toggle any supported feature for this chat only.
- As a user, I can see on each row whether its value is set for this chat, is my account default, or is the server default.
- As a user, I can reset a conversation-level override so the chat follows my default again.
- As a user, I can set account-wide feature defaults from Settings → Features without insider knowledge (tab is listed next to Context).
- As a user, I can stage several default changes and commit them with one Save, or abandon them with Cancel, without any of them reaching the server in between.
Behavior:
-
GET /api/conversations/{id}returnsfeatureSourceswith one ofconversation | user | defaultper feature, matching wherefn_get_web_settingsresolved the value. -
PUT /api/settings/user/Features.EnableXmakes a conversation with no override resolve that value with sourceuser; a conversation with its own override keeps sourceconversation. -
DELETEat conversation scope falls back to the user value (sourceuser) when one exists, else server default. -
GET /api/settings/user?view=featuresreturns exactly the sixFeatures.*rows. - Settings → Features writes nothing until Save, and Save sends only the changed keys.
Invariants that must stay true:
- Mode locks apply only in chat: a user-scope row is never "Not in this mode".
- Dependency locks (Memories ← Summaries, Picture entries ← Lorebook) apply in both scopes.
- Journal and Trackers are never mode-locked (soft note only), unchanged from Phase 1 of those features.
- Fresh account / fresh conversation: every row On, source Server Default, no reset offered.
- The drawer summary and the modal agree (same derivation, same optimistic overlay).
- A staged (unsaved) row never reports its value as already living at the scope being edited.
- The chat modal keeps writing immediately — the staged form is the Settings page's rule, not the component's.
Edges:
- Reset on a row with no override at this scope is not offered (no 404 path reachable from the UI); a user-scope DELETE that 404s is treated as already-default.
- A settings provider without provenance (test doubles) reports
default, never null. - Load failure on Settings → Features shows an error section, not an empty list.
- A row with a staged edit hides its reset link (reset would drop a different value than the one pending).
Resolution Order
For each feature in (Summaries, Memories, Lorebook):
if not mode.supports(feature):
active = false
ui_state = "locked: not in this mode"
continue
if feature == Memories and not active(Summaries):
active = false
ui_state = "locked: requires Summaries"
continue
active = user.wants(feature) // conversation setting → user default → true
ui_state = active ? "on" : "off (user disabled)"
// Per-feature semantic toggles (independent, map to existing settings):
Memories.semantic.active = active(Memories) and user.wants(Memory.EnableVectorSearch)
Lorebook.semantic.active = active(Lorebook) and user.wants(Knowledge.EnableVectorSearch)
// Single shared embedding decision (one generation per message, used by both):
embedding_will_generate =
(Memories.semantic.active and HasArchivedMemories) or
(Lorebook.semantic.active and HasLorebookEntries)
Pipeline Changes
PromptContextManager (user preference + dependency check)
PromptContextManager already only calls providers whose key matches a mode section. The new behavior adds two layered checks before running a provider:
- Dependency check. If the provider is
recalled_memoryand Summaries is off, skip — regardless of the user's Memories toggle. - User preference check. If the user has the corresponding
Features.*toggle off, skip.
Smart skip for the shared message embedding
The shared per-message embedding (lazy-loaded in PipelineContextBase.GetCurrentMessageEmbeddingAsync()) should not be generated when there's nothing for it to match. Two precomputed flags on the pipeline context drive this:
HasArchivedMemories— already wired (WebChatEntryPoint.cs:96, 125, viaIMemorySearchRepository.HasMemoriesAsync).HasLorebookEntries— new. Mirror the memories pattern: a cheap aggregate "any entries across any bound lorebook?" check, computed in parallel with the existingGetLorebookIdsAsynccall. Note: this is an entry-count check, not a binding-count check — a conversation may have lorebooks bound that contain zero entries.
Combined with the per-feature semantic toggles, the embedding generates iff:
(Memory.EnableVectorSearch && HasArchivedMemories) || (Knowledge.EnableVectorSearch && HasLorebookEntries)
When both clauses are false, return null — providers already handle null by falling back to FTS / keyword.
Exposing the embedding decision to the client
embeddingPreview is added to the existing per-conversation metadata payload that chat-v2 already loads when the conversation header initializes — no new endpoint, no extra round-trip. The implementer extends that response with a small object computed from the same code path the pipeline uses. Refresh triggers (lorebook bind/unbind, memory archived, Base/Entry/Flavor plan change, feature toggle change) bust the same cache that backs the conversation-header load.
Data Model
No schema changes.
- Prompt-plan supports is derived by the shared introspection service from the exact resolved Base rows plus enabled Web Classic Flavor inline dependencies; Direct/Discord/Hybrid use the Base-only projection. Do not derive it only from
prompt_mode_sub_prompt_linksonce Flavors land. - User wants uses settings keys, resolved through the standard hierarchy (conversation → user → default):
- New keys (Phase 3):
Features.EnableSummaries,Features.EnableMemories,Features.EnableLorebook. - Existing keys, surfaced in HowDrawer:
Memory.EnableVectorSearch,Knowledge.EnableVectorSearch(per-feature semantic sub-toggles),UI.EnableStreaming(Behavior section).
- New keys (Phase 3):
- Whether the message embedding gets generated is derived at runtime from the toggles above plus
HasArchivedMemories/HasLorebookEntries. There is no separate "embeddings" key.
Reads use ISettingsProvider (read-only — GetBool / GetSetting). Writes use the existing conversation-settings update API.
UI Considerations
HowDrawer additions (the toggle home)
- New collapsible sections appended inside the existing
HowDrawer(clientConsole/src/pages/chat-v2/components/HowDrawer.tsx): Behavior, Active Features, Coming Soon. - Existing HowDrawer content (model picker, preset, mode, context budget) stays above the new sections.
- Streaming moves out of its current ungrouped row into Behavior.
- Each toggle row: label, short description, mode-support badge, user toggle.
- Locked toggles show why (not in this mode / requires Summaries).
- Memories and Lorebook rows expose a nested Semantic recall / Semantic search sub-toggle. When the sub-toggle is off (and the parent is on), a per-row warning explains the degradation.
Message-box indicator
Small line above or below the composer:
- "Next message will use embeddings" — neutral icon
- "No embedding will be generated for this message." — muted
When Echo costs land, the indicator includes the cost: "≈3 Echoes (embedding)".
Mode Editor (Creator's Forge)
Read-only "Features used" summary derived from the mode's sub-prompt provider keys, so creators see at a glance what their mode supports.
Settings panel filtering
When a mode doesn't support a feature, the settings panel hides that feature's deeper configuration (thresholds, max entries, etc.). HowDrawer still shows the locked row for transparency, but advanced sub-settings are hidden.
Examples
Example 1: Casual chat, no semantic features
Mode: "Casual Chat"
Sub-prompts: character, persona, summary
→ Mode supports: Summaries
→ Mode does NOT support: Memories, Lorebook
HowDrawer / Active Features:
Summaries: [ON]
└─ (feature details — summary count, window size, etc.)
Memories: [LOCKED] not in this mode
└─ "Memory recall isn't included in this mode. Switch to a
mode that includes recalled_memory to use it."
Lorebook: [LOCKED] not in this mode
└─ "Lorebook search isn't included in this mode. Switch to a
mode that includes lorebook to use it."
Message box: "No embedding will be generated for this message."
Example 2: Full RP mode, user opts out of memories
Mode: "Epic Roleplay"
Sub-prompts: character, persona, lorebook, recalled_memory, summary, scenario
→ Mode supports: Summaries, Memories, Lorebook
User toggles:
Summaries: ON
Memories: OFF ← user choice
Lorebook: ON
Semantic search: ON
HowDrawer / Active Features:
Summaries: [ON]
└─ (summary details)
Memories: [OFF]
└─ "Memory recall is off. When on, the assistant searches
past summaries for content relevant to your current
message... [full explanation]"
Lorebook: [ON]
└─ Semantic search [ON]
└─ Bound lorebooks (with readiness pills)
Message box: "Next message will use embeddings (≈3 Echoes)."
(Lorebook semantic on + entries exist → one embedding.)
Example 3: User turns off Summaries — Memories cascades
User flips Summaries: ON → OFF
Effect:
Summaries: [OFF]
└─ "Conversation summaries are off. When on, older messages
get rolled into condensed summaries..."
Memories: [LOCKED] requires Summaries
└─ "Memory recall depends on summaries — turn Summaries on
to enable Memories."
Lorebook: [ON] unchanged
└─ Semantic search [ON]
Message box: "Next message will use embeddings (≈3 Echoes)."
(Lorebook semantic still drives the embedding.)
Example 4: Both Lorebook and Memories off → no embedding
User toggles:
Summaries: ON
Memories: OFF
Lorebook: OFF
Modal:
Summaries: [ON]
Memories: [OFF] user disabled
Lorebook: [OFF] user disabled
Message box: "No embedding will be generated for this message."
Example 4b: User disables semantic recall on Memories only → warning on that row
User toggles:
Summaries: ON
Memories: ON
Semantic recall: OFF ← manual
Lorebook: ON
Semantic search: ON
Modal:
Summaries: [ON]
Memories: [ON]
└─ Semantic recall [OFF] Memory recall will degrade to
keyword/FTS only.
Lorebook: [ON]
└─ Semantic search [ON]
└─ MyLore 47/47 embedded ✓
└─ Setting 23/47 embedded — 24 entries will be missed
[Generate missing embeddings] (user owns it)
Message box: "Next message will use embeddings (≈3 Echoes)."
(Lorebook semantic is still on → one embedding,
shared and used by lorebook search only.)
Example 4c: User disables semantic on both → no embedding, two warnings
User toggles:
Memories: ON
Semantic recall: OFF
Lorebook: ON
Semantic search: OFF
Modal:
Memories: [ON]
└─ Semantic recall [OFF] Memory recall will degrade to
keyword/FTS only.
Lorebook: [ON]
└─ Semantic search [OFF] Lorebook search will degrade to
keyword/FTS only.
Message box: "No embedding will be generated for this message."
Example 5: Smart skip even with features on
Mode: "Detailed RP" — supports everything, all user toggles ON
Conversation state:
→ 0 lorebooks bound, 0 memories archived
Pipeline:
→ No data to search → embedding skipped at runtime
Message box: "No embedding will be generated for this message."
After first summarization archives a memory:
Message box: "Next message will use embeddings (≈3 Echoes)."
Changing Features Mid-Conversation
These toggles are designed to be set before a chat starts or between chats. Flipping them mid-flow is allowed but can produce visible discontinuities, and the user should be warned in HowDrawer:
- Turning Summaries off mid-chat stops generating new summaries and removes the summary section from the prompt going forward. Earlier turns implicitly assumed that summary as compression — the model now sees a longer raw history and may behave differently. Recovery is automatic on re-enable, but the gap doesn't backfill.
- Turning Memories off mid-chat stops recalling past memories. The current message will not include any recalled context — the model may forget things it referenced two turns ago.
- Turning Lorebook off mid-chat drops in-prompt lorebook entries. Characters / settings / facts that were "known" via lorebook will silently disappear from the prompt.
- Turning a Semantic sub-toggle off mid-chat flips that feature's matching to FTS/keyword only for subsequent messages. The model may lose access to entries that previously matched semantically.
- Re-enabling any of these does not retroactively repair earlier turns — the prompt for older messages was built without them.
HowDrawer should show a small Changes apply to the next message note near the toggles. We do not need a confirm dialog — the cost of a "wrong toggle" is recoverable (flip it back) — but the note manages expectation.
Interaction with Other Features
Echoes / cost transparency
Embedding generation is the first chat operation that will charge Echoes. The composer indicator is the user's only pre-send signal of cost. It must reflect the exact runtime decision.
Mode-Specific Lorebook Injection
Mode-specific lorebook injection controls which lorebooks are searched and where content lands. Feature flags control whether lorebook search runs at all. Complementary, not overlapping.
Model Profile Base Prompts & Flavors
Model Profile Base Prompts & Flavors keeps the Base as an ordinary Mode selected by the winning Profile Entry and layers optional Profile-owned Flavors in Web Classic. Feature support is derived from the exact effective Base + enabled-Flavor plan: for example, a genuinely optional “Lore-Enhanced” Flavor can add a conditional {{knowledge}} dependency to a Base that otherwise omits it. The How drawer reflects that expanded support automatically. Base-only Direct/Discord/Hybrid projections never claim Flavor-added support.
Subscription Tiers
A free tier could force Features.EnableLorebook and Features.EnableMemories off at the platform level, eliminating embedding spend for free users. Pro users get the full feature set. Enforced via the settings hierarchy at the platform layer.
Migration Path
Phase 0: Extract a chat-specific LorebookCard (prep) — ✅ shipped, then ↩️ reversed
Originally planned as a chat-local component to render bound lorebooks inside the Lorebook feature row. Built in a4d7d778, then deleted in 75063504 in favor of putting the embedding pill on the existing WhoDrawer "World Knowledge" cards. The reasoning: lorebooks already had a canonical surface in chat (Who drawer); a parallel chat-specific card surface in HowDrawer was duplicate work and ran against the design doc's own decision that "the pill lives on the lorebook card itself, anywhere a lorebook is rendered." HowDrawer's Lorebook row body now references "Who → World Knowledge" instead of rendering its own list.
What survived from this phase: the LorebookEmbeddingPill component (slim "X/Y embedded" badge with state color). It renders on WhoDrawer cards today and is reusable for any future lorebook card surface that wants it.
Phase 1: Smart embedding skip + composer indicator — ✅ shipped (9385fc95)
- New
ILorebookSearchRepository.HasEntriesForConversationAsync— cheap EXISTS query againstlorebook_entriesjoined tofn_get_conversation_lorebook_ids, filtersis_enabled = TRUEso the count matches what the runtime would actually search. - New
IPipelineContext.HasLorebookEntriesflag (defaulttrue), precomputed inWebChatEntryPointalongside the existingHasArchivedMemories.LorebookContentProviderupgraded its smart-skip from binding-count to entry-count semantics — strict superset of the old skip, covers the previously leaky "bindings exist but contain zero entries" case. - New
IWebChatFeatureStateServicereturning aConversationFeatureStaterecord (will-generate-embedding + mode-support flags + user-toggle flags after Phase 3). Added to the existingGET /api/conversations/{id}payload asEmbeddingPreviewDto— no new endpoint, no extra round-trip. - Message-box-area
EmbeddingIndicatorcomponent reads the preview off the loaded conversation. Cost field reserved for Phase 4. - Discord scope: web-only. DiscordChat passes
embeddingClient: nulltoday, so there's nothing to skip on that side. The web path isn't accidentally gated for Discord —PromptContextManageris shared but Discord doesn't writeFeatures.*settings, and the defaults are all-on.
Phase 2: HowDrawer extension + ChatInfoModal rename — ✅ shipped (8bd9a0f8)
- New collapsible sections inside HowDrawer: Behavior (existing
StreamingTogglemoved in), Active Features (Summaries / Memories / Lorebook rows with state-conditional copy), Coming Soon (Trackers / Journal / Living Lorebook / Picture entries — non-interactive greyed rows). All four have since become live rows; Living Lorebook was the last, at M10, and the Coming Soon group is gone. - New
FeatureRowcomponent implementing the always-expanded section visual pattern. In Pass 1 it rendered state badges only; in Phase 3 it gained interactive toggles for active/inactive states. - Mode-support state derived from sub-prompts via
WebChatFeatureStateService(canonical + alias keys:lorebook∪knowledge,recalled_memory,summary∪memory). ChatInfoModalrenamed"Chat Features"→"How Chat Works", content expanded to cover the new HowDrawer sections, the composer indicator, lorebook readiness pills, mid-conversation change semantics, and keyboard shortcuts.
Phase 2 Pass 2: lorebook readiness — ✅ shipped on the Who drawer (75063504)
Originally drafted to render chat-specific lorebook cards inside HowDrawer; reversed mid-build (see Phase 0 above) to consolidate on the existing Who drawer surface.
BrowseLorebooksForConversationenriches eachChatLorebookwithEmbeddingTotal/EmbeddingIndexedfrom a singleGetEmbeddingStatsForConversationAsynclateral-join query, merged by UUID.- Each WhoDrawer "World Knowledge" card now renders the
LorebookEmbeddingPillin its header and an owner-conditional action below:"Generate missing embeddings"button (wired to the existing creator reindex endpoint) for owners;"Ask the creator to regenerate"muted hint for non-owners.
Phase 3: User feature toggles + cascade — ✅ shipped (75063504)
- New
SettingsKeys.Featuresnamespace:EnableSummaries/EnableMemories/EnableLorebook(defaulttrue). Mirrored inclientConsole/src/constants/settingKeys.ts. PromptContextManagergates each provider on its matchingFeatures.*key inside the existing provider-key loop.IsFeatureGatedOffenforces the Memories→Summaries cascade:recalled_memoryis skipped when EITHERFeatures.EnableMemoriesORFeatures.EnableSummariesis false. Aliases honored —knowledgesub-prompts get the lorebook gate,memory(alias forsummary) gets the summaries gate.WebChatFeatureStateServicefactors the user toggles + cascade intoWillGenerateEmbeddingand surfaces the raw user prefs asSummariesEnabled/MemoriesEnabled/LorebookEnabledso the UI can render the toggle state and the dependency-locked badge correctly.FeatureRowgains interactive toggles for active/inactive states (locked / coming-soon variants still render badges). Toggle write goes through the existing settings PUT endpoint, refreshes the conversation envelope, and mode-support / cascade / embedding preview update in sync.
Phase 4: Echo cost in the composer indicator — ⏸️ blocked
The indicator's EchoCost? slot is reserved but inert. Echo charging on the embedding step requires the allocate / commit / release ledger functions for feature spend, which are explicitly WIP per the Echo subsystem in root CLAUDE.md. See the Phase 4 punch list below.
Open Questions
(none currently blocking — see Decisions below.)
Decisions
embeddingPreviewcache invalidation triggers in shipped scope. Feature-toggle writes refetch the conversation envelope (viaonConversationUpdate). Lorebook bind/unbind, memory archival, and mode change rely on the existing per-event refetch paths in chat-v2. Cross-tab edits would need a websocket-style signal — out of scope.- Lorebook readiness pills live on the WhoDrawer "World Knowledge" card — single canonical surface in chat. HowDrawer's Lorebook feature row references that surface rather than rendering a parallel list. (Original plan was a chat-specific LorebookCard inside HowDrawer; reversed during Pass 2 in favor of the consolidation.)
- Coming-soon rows are non-interactive. Clicks do nothing. Re-evaluate per feature when each ships.
- Per-feature semantic-search sub-toggles described in earlier sections of this doc are not surfaced in the shipped UI. The underlying
Memory.EnableVectorSearch/Knowledge.EnableVectorSearchsettings still exist and are honored at the algorithm level, but the HowDrawer feature rows expose only the provider-levelFeatures.*toggle. Earlier sections that reference nested "Semantic recall / Semantic search" sub-toggles describe a richer design that wasn't pursued for the v1 shipped scope. Re-evaluate if a user ever asks for finer-grained control than "feature on/off". - Discord parity: web-only. DiscordChat passes
embeddingClient: null, so there's nothing to smart-skip there. TheFeatures.*settings apply uniformly viaPromptContextManager(shared across platforms), but Discord won't write them today and the defaults are all-on, so behavior is unchanged on the Discord side.
Codebase Validation (2026-04-29)
This plan was validated against the current codebase. Several pieces already exist and the migration path can be tightened accordingly.
Already wired — the doc was overclaiming work
IPipelineContext.HasArchivedMemoriesalready exists (IPipelineContext.cs:199, PipelineContextBase.cs:233). It's precomputed in WebChatEntryPoint.cs:125 and consumed in WebMemoryContentProvider.cs:101 to skip recall when there are no memories. Phase 1's "smart embedding skip" is half done already — only the lorebook-entries equivalent is missing. Need:HasLorebookEntriesForConversationAsync(or a precomputedHasLorebookEntriesflag on the context, mirroring memories).UI.EnableStreamingalready exists in SettingsKeys.cs:463 and is wired throughclientConsole/src/constants/settingKeys.ts. The Behavior section of the modal just hosts the existing toggle — no new key.Provider keys & aliases match the doc. ContextKeys.cs confirms all keys used in the table; PromptContextManager.cs:35-39 confirms the
knowledge ↔ lorebookandmemory ↔ summaryaliases.DynamicProviderKeys(:25) is also a useful reference for any "uses embeddings" derivation —summaryis dynamic but does NOT use embeddings, so derive embedding-usage from{lorebook, knowledge, recalled_memory, memory}∩ mode sub-prompts.Embedding stats infrastructure already exists for the readiness pills:
- EmbeddingStatsResponse.cs — server model.
GET .../embedding-statsendpoints on lorebooks (CreatorLorebookEndpoints.cs), conversations (ConversationsEndpoints.cs), and admin variants.EmbeddingStatsPanel(shared/src/components/common/EmbeddingStatsPanel.tsx) is a shared component with the exact shape we need:{ total, indexed, pending, model, lastGeneratedAt, currentModel, isStale }, plus a Reindex button and stale indicator. The "owner sees Generate missing embeddings" UX is already implemented in this panel.
Implication: the lorebook readiness pill is mostly a presentation choice, not new server work. Reuse the panel (or a slimmer pill variant of it) on whichever lorebook card surface we end up on.
Tensions / clarifications needed
Existing granular settings stay separate — no umbrella key. SettingsKeys.cs:228-272 defines
Memory.EnableVectorSearch,Memory.EnableFtsSearch,Memory.EnableSimpleKeywordSearchand the same triplet underKnowledge.*. These remain the source of truth — the modal does not introduce a unified "Embeddings" master key. Two axes coexist cleanly:Features.EnableMemories= "should memory recall run at all?" (provider-level, new key).Memory.EnableVectorSearch= "within memory recall, use semantic similarity?" (algorithm-level, existing key).
The modal renders the algorithm-level vector toggles as per-feature sub-toggles inside the Memories and Lorebook rows. Warnings are per-feature too ("Memory recall will degrade to keyword/FTS only" / "Lorebook search will degrade to keyword/FTS only") — turning Memory-semantic off does not warn about Lorebook, and vice versa.
Cost note (the part engineers need to understand): the embedding itself is a single resource shared between the two providers.
PipelineContextBase.GetCurrentMessageEmbeddingAsync()lazy-loads + caches per pipeline run, so even though the toggles are independent, the embedding generation (and Echo charge) is one OR across both features:(Memory.EnableVectorSearch && HasArchivedMemories) || (Knowledge.EnableVectorSearch && HasLorebookEntries). The composer indicator computes that single OR — one line, one cost — not a pair of per-feature pills.No shared
LorebookCardcomponent. shared/src/components/common/index.ts does not export one — lorebook cards are page-local inclientConsole. The "pill on the card" decision implies either (a) extracting a sharedLorebookCardfirst, or (b) wiring the pill into each existing per-page card. Option (a) is the right move long-term per the project's reuse rule, but it's scope-additional. Flag for the user.Features.*namespace is new. TodaySettingsKeys.cshas noFeaturesstatic class. We'll add one withEnableSummaries,EnableMemories,EnableLorebook(and mirror inclientConsole/src/constants/settingKeys.ts).
Reusable shared components for the modal
The HowDrawer feature sections can be assembled almost entirely from existing shared components — no new primitives needed.
| Need | Existing component |
|---|---|
| Modal shell | Modal |
| Section grouping (Behavior / Active / Coming Soon) | Section (variant info) — or a flat layout with headings |
| Per-feature on/off toggle | Toggle |
| Per-feature semantic-search sub-toggle | Toggle (nested) |
| Mode-support state ("not in this mode", "requires Summaries") | Badge (variant subdued / locked) |
| Per-feature semantic-off warning | WarningSection (from Section) — one per affected row |
| Coming-soon rows | Card (variant subdued) + Badge "Coming soon" |
| Message-box pre-send indicator | Badge + LoadingSpinner for the live recompute state |
| "Save as user default" affordance | Checkbox + Button |
| Mid-conversation change note | InfoSection |
New small component needed: LorebookEmbeddingPill. EmbeddingStatsPanel is too heavy for a card-corner pill — it's a full panel with the reindex button and stale indicator. We want a slim variant that shows just indexed/total + a state color (✓ complete / ⚠ partial), with the panel-style affordances (Reindex / "Ask the creator") hidden behind a click-through. Either: (a) extract the badge-only render path out of EmbeddingStatsPanel into a sibling LorebookEmbeddingPill, sharing the same EmbeddingStats type, or (b) add a compact prop to the existing panel that hides the reindex button and shrinks the layout. Prefer (a) — keeps the panel honest as a panel, and the pill picks up an obvious shared component slot.
Form components (Toggle, Checkbox) already accept label / description / mandatory props — do not wrap them in custom label divs (per project convention).
Updated migration path
Phase 0 (chat-specific LorebookCard extraction) is added as a small prep step — see the Migration Path section above. It's marked chat-specific deliberately to avoid sprawling into a full lorebook-card-surface unification.
Phase 1 narrows to a pure-backend slice that's smaller than originally written:
- Add
HasLorebookEntries(precomputed) to the pipeline context, mirroringHasArchivedMemories. Wire fromWebChatEntryPointonly — DiscordChat passesembeddingClient: nulltoday and doesn't generate embeddings, so there's nothing to skip. Revisit when Discord adopts embeddings. - Add the symmetric skip in
LorebookContentProvider(early-return when!HasLorebookEntries, mirroringWebMemoryContentProvider's!HasArchivedMemoriesskip). - Add
embeddingPreviewto the existing per-conversation metadata payload (no new endpoint). Derived from(Memory.EnableVectorSearch && HasArchivedMemories) || (Knowledge.EnableVectorSearch && HasLorebookEntries). - Message-box indicator reads
embeddingPreview. No HowDrawer changes yet.
Phase 2 (modal shell + streaming toggle move) and Phase 3 (Features.* keys + pipeline gating) stay as written, with the correction above: the modal renders per-feature semantic sub-toggles wired to the existing Memory.EnableVectorSearch and Knowledge.EnableVectorSearch settings — independent rows, independent warnings, no umbrella key.
Implementation Readiness — Second Validation Pass
Verdict: ready to implement. All four blocking decisions resolved.
1. ChatInfoModal collision — RESOLVED
ChatInfoModal collisionChatInfoModal.tsx keeps its file and component name. Header renames from "Chat Features" → "How Chat Works". Content gets expanded into a substantive help surface covering the new HowDrawer sections, composer indicator, lorebook readiness pills, and mid-conversation caveat. Folded into Phase 2.
2. HOW drawer overlap — RESOLVED
HOW drawer overlapFeature toggles fold into HowDrawer as three new collapsible sections (Behavior / Active Features / Coming Soon). No parallel modal entry point. Streaming moves out of its current ungrouped row into the new Behavior section. Existing HowDrawer content (model, preset, mode, context budget) stays in place above the new sections.
3. embeddingPreview attachment point — RESOLVED
embeddingPreview attachment pointNo new endpoint. embeddingPreview is added to whatever payload chat-v2 already loads when the conversation header initializes — the existing per-conversation metadata fetch. Implementer locates that endpoint (likely in clientConsole/src/api/conversations.ts and the corresponding ServerAPI ConversationsEndpoints handler) and extends its response with the new field. Cache invalidation triggers (lorebook bind/unbind, memory archived, mode change, feature toggle change) bust the same cache that backs the conversation-header load.
4. Discord parity — RESOLVED (web-only for now)
Finding from second-pass code read: server/EchoOfDreams.DiscordChat/Chat/DiscordChatEntryPoint.cs:76, 197 constructs DiscordChatContext with embeddingClient: null in every path. DiscordChat does not generate embeddings today, so there is nothing to smart-skip on the Discord side. The earlier "mirror in DiscordChat" decision was based on an assumption that's not true in code.
Phase 1 is web-only. When/if DiscordChat adopts an embedding client, the same precompute one-liner applies — pattern is documented here. No action on the Discord entry point in this scope.
Smaller validation notes (not blocking, but worth noting)
- Lorebook embedding-stats endpoint is creator-scoped (CreatorLorebookEndpoints.cs:634 —
/api/creator/lorebooks/{id}/entries/embedding-stats). A chat user who bound a lorebook but doesn't own / can't view it via the creator surface may not be authorized to read its stats. Phase 0's chat-specificLorebookCardeither needs a chat-scoped endpoint that returns just the publictotal/indexed/pendingtriple regardless of ownership, or the pill needs to gracefully degrade to "Embedding status unavailable" when the stats fetch returns 403. Lean toward the chat-scoped endpoint. ISettingsProvideris read-only (ISettingsProvider.cs). The pipeline reads viaGetBool/GetSetting; modal toggle writes go through the existing conversation-settings update API, not throughISettingsProvider. This is implicit in the doc — flagged for absolute clarity.HasLorebookEntriesis an entry-count check, not a binding-count check. Now called out explicitly in the Pipeline Changes section, sinceWebChatEntryPointalready loadslorebookIds(binding count) — the new repo method must aggregate across bindings and check non-zero entries.StreamingToggle.tsxis reusable as-is — 19-line component takingenabled/onChangeprops. Phase 2 just imports it into the Behavior section.
Stale claims cleaned up in this pass
- Examples 1–3, the Data Model section, the UI Considerations "Embeddings row is informational" line, and the mid-flow "Turning Embeddings off" bullet all referenced an "Embeddings master toggle" that was removed two revisions ago. All replaced with the per-feature semantic-toggle model.
- Pipeline Changes section now states the embedding-skip condition correctly using both flags and both per-feature semantic settings, instead of describing it as "extending an already-partly-wired check."
Ready to implement
All four blocking decisions are resolved. Remaining work is mechanical:
- Phase 0: chat-specific
LorebookCard+ slimLorebookEmbeddingPill. Add a chat-scoped lorebook embedding-stats endpoint (or have the pill degrade gracefully when the creator-scoped endpoint returns 403 — implementer's call, but a chat-scoped endpoint is cleaner). - Phase 1: new repo method
HasLorebookEntriesAsync(conversationId)(entry-count aggregated across bound lorebooks); mirror the existingHasArchivedMemoriesprecompute pattern in bothWebChatEntryPoint.csand the DiscordChat entry point; addembeddingPreviewto the existing per-conversation metadata payload (no new endpoint); composer indicator reads it. - Phase 2: extend HowDrawer with the three new collapsible sections; move
StreamingToggleinto Behavior; rename and expandChatInfoModal. - Phase 3: new
Features.*keys inSettingsKeys.cs+ frontend mirror; HowDrawer toggles wired; pipeline gating inPromptContextManager. - Phase 4: Echo cost number in the composer indicator when Echo charging lands on the embedding step.
Tests per phase
Use the dotnet-blackbox-tests skill before writing any new test. Avoid EchoOfDreams.Database.Tests (40+ min, dev runs manually) — keep new tests in the fast unit projects.
Phase 0 — LorebookCard + LorebookEmbeddingPill + chat-scoped stats endpoint.
- ServerAPI.Tests: chat-scoped lorebook embedding-stats endpoint — owner / non-owner-with-binding / non-owner-without-binding (403) / unknown lorebook (404). Stats payload shape matches
EmbeddingStatsResponse. - Frontend (Vitest):
LorebookEmbeddingPillrenders complete (47/47), partial (23/47with warning copy), zero-state, and stats-unavailable (graceful degrade). Snapshot of the chat-specificLorebookCardwith each pill state.
Phase 1 — Smart-skip + composer indicator.
- Database.Tests (skip in CI, dev runs locally):
HasLorebookEntriesAsyncreturns false for conversation with zero bindings, false for conversation whose bindings have zero entries, true once any bound lorebook has at least one entry. Aggregates correctly across multiple bindings. - WebChat.Tests:
WebChatEntryPointprecomputesHasLorebookEntriesand sets it on the context (mirror the existingHasArchivedMemoriestest pattern inWebMemoryContentProviderTests/WebChatEcosystemTests). - DiscordChat.Tests:
Discord precompute test— N/A in Phase 1 (Discord doesn't use embeddings yet). - Core.Tests:
LorebookContentProviderearly-returns empty when!HasLorebookEntries(mirrorWebMemoryContentProvider's!HasArchivedMemoriestest). Add toLorebookContentProviderTests. - Core.Tests: extend
PipelineContextBasetests soGetCurrentMessageEmbeddingAsyncreturnsnullwhen(Memory.EnableVectorSearch && HasArchivedMemories) || (Knowledge.EnableVectorSearch && HasLorebookEntries)is false — covering all four flag combinations × both feature toggles. - ServerAPI.Tests: per-conversation metadata endpoint includes
embeddingPreviewwith the correct derived value across the same matrix (mode supports vector providers? × HasArchivedMemories × HasLorebookEntries × the two*.EnableVectorSearchsettings). - Frontend (Vitest): composer indicator renders "No embedding will be generated" / "Next message will use embeddings" off
embeddingPreviewcorrectly.
Phase 2 — HowDrawer extension + ChatInfoModal rename.
- Frontend (Vitest):
- HowDrawer renders the three new sections (Behavior / Active Features / Coming Soon).
- Streaming toggle moved out of its old row into Behavior — old position empty, new position renders the existing
StreamingToggle. - Active Features rows reflect mode-support state correctly (locked when mode doesn't support; "requires Summaries" lock on Memories when Summaries is off).
- Per-row warnings render when a Semantic sub-toggle is off while the parent is on; do NOT render when the parent is off.
- Each Active Features section is always expanded, with content swapping by state: ON shows feature details, OFF shows the explanatory off-state copy, mode-locked / dependency-locked / Coming Soon each render their respective informational copy with a disabled toggle.
- Coming Soon rows render greyed-out and are non-interactive (click does nothing); the descriptive paragraph is present.
ChatInfoModalheader renders "How Chat Works"; expanded content sections present.
Phase 3 — Features.* keys + pipeline gating.
- SettingsKeys parity check:
clientConsole/src/constants/settingKeys.tsincludes the newFeatures.*keys and matchesSettingsKeys.cs(the existing parity test pattern, if there's one — otherwise add one). - Core.Tests / WebChat.Tests:
PromptContextManagerskipsrecalled_memorywhenFeatures.EnableMemories=false, skipslorebookwhenFeatures.EnableLorebook=false, skips bothsummaryandrecalled_memorywhenFeatures.EnableSummaries=false(Memories cascade). Add toPromptContextManagerTests. - ServerAPI.Tests: writing
Features.*toggles via the existing conversation-settings update endpoint round-trips correctly and is reflected in the nextembeddingPreviewread. - Frontend (Vitest): toggling a HowDrawer feature row sends a surgical update (only the changed key), and the row reflects the persisted state on reload.
Phase 4 — Echo cost in the indicator.
- Frontend (Vitest): composer indicator renders the Echo cost number when
embeddingPreview.willGenerate=trueand the cost is provided; falls back to the no-cost copy when the cost field is null. - ServerAPI.Tests / Core.Tests: when Echo charging lands on the embedding step, the charged amount matches what the indicator displayed (close the loop between preview and actual spend so the user is never surprised).
Cross-phase regression checks.
- Existing
HasArchivedMemoriesskip behavior unchanged after Phase 1 lands. - Mid-conversation toggle changes apply on the next message and do not retroactively alter persisted history (covered by an end-to-end pipeline test in
WebChatEcosystemTests).
Phase 4 punch list (blocked)
The composer indicator's EchoCost? slot is reserved but inert. Wiring real cost requires Echo charging at the embedding step, which depends on allocate / commit / release ledger functions that aren't built yet. Per root CLAUDE.md: "Allocate/commit/release for feature spend is WIP."
What's already in place:
BudgetAwareEmbeddingClientis the single choke point — every embedding call goes through it.EmbeddingCallContext.CurrentUserId(AsyncLocal) carries user identity into the embedding stack.- AuthService Echo endpoints exist for read (balance, transactions) and claim (daily tasks, gift codes).
What's missing, in dependency order:
1. Product decisions (no code)
- Cost model. Flat (e.g. 1 Echo per embedding call), or model-tiered? Reindex jobs charge per entry × N or one bundled price?
- Free tier behavior. Free users get no embeddings (FTS only) or a small daily allowance funded by the existing budget system?
- Insufficient balance UX. Hard-fail the message ("not enough Echoes — top up"), or silently degrade to FTS/keyword and tell the user via the indicator? The cost-transparency thesis leans toward hard-fail because partial-quality surprises are worse than refusal, but graceful degrade is the AO3-style "always works" choice.
2. Echo ledger write functions (SQL + AuthService)
The two-phase pattern the Echoes subsystem doc gestures at:
fn_allocate_echoes(user_id, source, amount, metadata) → hold_id— pre-flight reservation, fails fast if balance < amount.fn_commit_echo_hold(hold_id, actual_amount)— finalize deduction (actual ≤ allocated).fn_release_echo_hold(hold_id)— refund on failure / cancellation.
UTC boundary, partitioning, and advisory-lock rules from 41a_echo_ledger_functions.sql carry over (any new function that joins echo_transactions, daily_*, or ai_task_runs must SET LOCAL timezone = 'UTC').
Plus internal AuthService endpoints (POST /api/internal/echoes/allocate / /commit / /release, gated by INTERNAL_API_SECRET like the existing chat-progress one), so ServerAPI/WebChat can call without touching the ledger directly.
3. Cost config
New SettingsKeys.Echoes.EmbeddingCost (admin-controlled, not per-user) holding the per-call price. Single source of truth — preview reads it, runtime charges it. Hardcoded constant for v1 is fine; promote to a setting once you have product certainty.
4. Chat-side decorator
New EchoChargingEmbeddingClient (or extend BudgetAwareEmbeddingClient) — wraps _inner.GetEmbeddingAsync with allocate → generate → commit/release:
hold = await _ledger.AllocateAsync(userId, "embedding", cost)
try {
var vec = await _inner.GetEmbeddingAsync(text)
await _ledger.CommitAsync(hold, cost)
return vec
} catch (anything) {
await _ledger.ReleaseAsync(hold)
throw
}
Pricing for batch (GetEmbeddingsAsync(texts)): allocate cost × N upfront, commit cost × actualSucceeded on completion, release the difference.
Insufficient-balance path: AllocateAsync throws → bubbles as a typed exception (EchoBalanceExceededException analog of the existing EmbeddingBudgetExceededException) → handled by the pipeline's existing exception-to-HTTP mapping.
5. Surface the cost on the preview
EmbeddingPreviewDto(WillGenerate, EchoCost?)— add the cost field.WebChatFeatureStateService.GetFeatureStateAsyncreadsSettingsKeys.Echoes.EmbeddingCostonce and includes it on the result.- One-line types update on the frontend (
EmbeddingPreview { willGenerate: boolean; echoCost?: number }). EmbeddingIndicatoralready has a placeholder spot for the cost — renderNext message will use embeddings (≈3 Echoes)when both fields are present, fall back to current copy when not.
6. Loop-closing test
The single test that earns the most: assert that the cost the indicator showed equals the actual_amount committed to the ledger. Closes the trust loop between preview and spend.
7. Free tier policy enforcement (if "free = FTS only")
Features.EnableLorebook / EnableMemories forced to false for the free tier at the platform setting layer (existing settings hierarchy supports this via the user-default fallback). Alternative: keep the toggles but EmbeddingCost setting includes a "free" override of 0, and the budget gate is what stops abuse.
Suggested attack order
- Pricing decisions + free-tier policy (no code, just settle).
- SQL functions for allocate / commit / release — testable in isolation against
Database.Tests. - AuthService internal endpoints wrapping the SQL functions, with
INTERNAL_API_SECRETgating, mirroring the existing chat-progress endpoint shape. IEchoLedgerClientinterface in Core + HTTP impl in Database, registered in DI.EchoChargingEmbeddingClientdecorator, wrapsBudgetAwareEmbeddingClient, registered as the outermost layer.EmbeddingCostsetting +EmbeddingPreviewDto.EchoCost+EmbeddingIndicatorcost rendering — one commit, the user-visible payoff lands.- Loop-closing test + insufficient-balance UX.
The single biggest decision is #1 — graceful degrade vs. hard fail on insufficient balance. The plumbing is roughly the same either way; the failure path is what changes.