0070. Coach chat: the web's hand-off to the worker, and the allowance it shows
Source:
docs/decisions/0070-chat-web-hand-off.md. Generated at build time; edit the source file.
Date: 2026-11-22. Status: accepted (M5b Task 5). Builds on ADR 0064 (Ask your coach), ADR 0062
(the Agent SDK sidecar), ADR-WEB-8 (SSE delivery) and R3 Task 25 (backend/crates/ai/src/chat).
Rulings R5 and R6 of the M5b plan, and the coordinator’s ruling G1 (beta entitlements).
Context
Section titled “Context”R3 built the chat in Rust: chat::threads creates, posts, lists, reads and deletes threads,
and the coach-chat job answers one pending assistant message, streaming chat.chunk events
and ending with chat.message.ready or chat.message.failed. Those three events are
user-owned (user_events.user_id, Audience::User). The web (TypeScript) has to offer the
same operations without a Rust HTTP API, and without ever talking to the sidecar.
Decision
Section titled “Decision”- Streaming over the existing event stream (R5). The web writes
coach_conversations,coach_messagesand thecoach-chatjob, and nothing else. The worker’schat.*events reach the browser through/api/events, whose hub and replay already deliver a user-owned event only to its owner (eventVisibleTo). There is no web-to-sidecar route; the sidecar’s URL and token are not in the web’s environment (pinned bytest/coach/hand-off.test.ts). - One-transaction post.
postUserMessageportspost_user_message: blank (only UnicodeWhite_Space, as Ruststr::trim; a BOM is not blank) isempty, more than 2000 Unicode scalar values istoo_long, the conversation row is lockedFOR UPDATE(scoped byuser_id), an assistant answerpendingorstreamingmakes itbusy, the user turn (done) goes atmax(seq) + 1and thependinganswer after it,last_message_at = now(). The job ({"messageId": …}, keychat:<id>,user_keythe account, priority 10, 2 attempts) is enqueued in the same transaction (R1’sENQUEUE_SQLon the caller’s transaction, Task 2). That is stronger than Rust, which enqueues after its commit; the reconciler still fails an answer whose job was lost. - One-transaction start, deduplicated.
POST /api/coach/threadswith a question runsstartConversation: the create, both turns and the job commit together, so a refused (429) or failed first post leaves no thread behind. Under the user’s create lock, a repeat of the same start (account, time class, anchor and question, or an empty start with no messages) within 60 seconds answers the first thread, so a retry or a double submit never makes a second thread, job or quota charge. No client key is needed and no migration. - Ownership. Every read, post and delete is filtered by
coach_conversations.user_id; another user of the same linked account gets not-found (404), never 403. Creating and posting also need the user’s ownaccount_linksrow; posting after unlinking is403 not_linked, while reading and deleting still work (as Rust). Creating on an account the user is not linked to is answered as not-found, so no account’s existence leaks; so is listing threads of such an account (GET /api/coach/threads?account=is 200,[]when empty, only for a linked account). A single thread stays readable by id after unlinking. - Chunk replay. On a reload mid-answer,
getThreadreturns, for eachpendingorstreaminganswer, thechat.chunkpayloads already inuser_eventswithuser_id= the user, the conversation’s account, andpayload->>'messageId'= the message, deduplicated and inseqorder. Live chunks then append throughapplyCoachEvent(deduplicated byseq), so nothing streamed is lost or doubled. Events older than the 7-day retention are gone, but by then the answer has long ended. - Copy parity. The chat’s fixed server copy (fallback, refusal, off-topic, no-data,
unavailable, engine-pending, the dropped-statement and engine-limit notes, the cap texts and the
fallback titles) is mirrored byte for byte from
limits.rsandsummary.rs, pinned bytest/coach/copy-parity.test.ts. Web-onlyfailureCopycovers the reasons Rust has no player text for (budget,not_linked,lost, anything new). - The allowance (R6).
chatAllowancecounts exactly as the job’sused_per_window: assistant answers in the account’s conversations that arestreaming, ordonewith a non-nullai_disclosure(fixed no-data copy is free), created inside each UTC window (day from 00:00, week from Monday 00:00, month from the 1st). The composer is disabled with the reset copy when a quota is exhausted, but the web never refuses a post for quota: the job is the authority, and its denial arrives aschat.message.failedwith the cap reason. - The plan. Quotas are
free3 a week andpro30 a day and 300 a month (Rustentitlements.rs), plusbetafor the private beta (ruling G1): 100 a week, set byAI_BETA_CHAT_WEEKLY. The web reads the deployment’s plan fromAI_DEFAULT_PLAN(defaultbeta), the variable the plan names for the worker’s entitlements (Task B wires the Rust side to the same names and defaults), so the composer shows what the job will enforce. - Abuse bounds, not quotas. A user may post 10 questions per 10 minutes over all their
threads (429
rate_limitedwithretry-after) and start 30 conversations an hour. Each is counted under a per-user transaction advisory lock (classes 30031 for posts, 30032 for creates; R4 uses 30030, R3 30001–30004 and 30020), so the count is exact. Bodies are capped at 16 KiB; strings with U+0000 or lone surrogates are refused (400invalid_body); a malformed anchor is dropped, never stored.
Consequences
Section titled “Consequences”- A chat answer needs no new service, port or secret on the web side.
- The post holds a row lock for a few statements only; two concurrent posts give one
postedand onebusy. - Follow-up:
AI_DEFAULT_PLANandAI_BETA_CHAT_WEEKLYmay give way to per-user limits, read through one function on each side (aiPlan()on the web,Entitlements::planin Rust). - Follow-up: the quota’s budget scope is the account (Rust
DefaultEntitlements:: budget_scope), so a user with several linked accounts (verified or not) gets one allowance per account. Per-user limits should scope it per user, or count verified links only. - If the worker’s plan variable and the web’s ever disagree, the composer’s count is wrong but the quota still holds (the job decides).
Addendum: the chat pages (M5b Task 9)
Section titled “Addendum: the chat pages (M5b Task 9)”- The stored answer is authoritative. The thread page shows an unfinished answer’s chunks as
chat.chunkevents reach the query cache (merged with the chunksgetThreadreplayed, one perseq). When the stream ends (chat.message.readyorchat.message.failed) the page reads the thread again and renders the stored segments, so a retracted or repaired stream (replace) never stays on screen. A failure readsfailureCopy(reason)at once, even before the re-read. - No open stream, no “live”. While
useRealtime().modeis notsse(connecting, polling, or no provider mounted), the page reads the thread everyPOLL_INTERVAL_MSwhile an answer runs and says “Updates every few seconds”. An answer therefore finishes on screen even without the event stream. - Platform game ids. Chat segments and anchors name a game by its platform id, as the worker
resolves them; the review page takes
games.id.server/profile/game-ids.ts(reviewGameIds, shared with the weaknesses pages) maps them on the conversation’s own account, behind the user’s link. An id it cannot map links nowhere and an anchor it cannot map is dropped, so no answer links to a not-found page. - Composer states. A used-up allowance disables the composer with the cap copy and the allowance line gives the reset day. An answer in progress disables it with a status line (“Your coach is answering”), not the “paused until they reset” placeholder. A post shows the question as sending until the server accepts it; a refused post keeps the text in the box and says why. A failed answer offers “Ask again” only when asking again could succeed (an outage or an unknown error, never a cap, the spending limit or an unlinked account).
- Attempts (review I3, coordinator ruling). A released and retried turn streams again from
seq0. Everychat.chunk,chat.message.readyandchat.message.failedpayload now carries the turn’sattempt(Rustcoach_messages.turn_attempts; 0 when no attempt was reserved). The web keys chunks by (attempt, seq): a higher attempt discards every chunk of a lower one, live (applyCoachEvent) and on replay (getThreadkeeps only the latest attempt and reports it asstreamedAttempt), and an older attempt’s events change nothing. - The stream’s cache entry (review I1). The thread keeps an observer on
chatStream(messageId)while it is open, so the entry is never collected mid-turn; it is removed when the answer settles or the thread closes. - Settling (review I2).
readywithreplacehides the streamed text at once. Re-reads after the end back off from 1 s to 30 s and keep going until the stored row is final; after 20 s the turn reads “finished, but it didn’t load” with a Reload action and the composer unlocks. - Focus (review I4). A send from the box moves focus to the polite “Your coach is writing” status while the box is disabled, and back to the box when it opens again.