From 466055020fd2e7a924eb2200a74cbf72c04f8472 Mon Sep 17 00:00:00 2001 From: prosolis <5590409+prosolis@users.noreply.github.com> Date: Tue, 28 Jul 2026 23:45:26 -0700 Subject: [PATCH] The garden learns which language a card is in, and read-aloud stops guessing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 28 (c), the last of the phase. A word met inside a Portuguese document is a Portuguese card: migration 0018 mirrors documents.doc_lang onto vocab_words, set server-side from the ownership lookup capture was already making. Every card still reviews — filtering the queue to the half she is learning would drop the words she actually met. Read-aloud was the larger surprise. detectLang routed Han/kana to Chinese and everything else to en-US, so the zh pair was accidentally right and every Latin pair wrong. doc_lang now reaches the client read-only on the document JSON, and docLang(text, verdict) answers for a passage taken out of it — with the script test still winning, because quoted Chinese must never be spelled out one "Chinese letter" at a time. Claude-Session: https://claude.ai/code/session_01GJHNvirh7Hzhc9RL3HAvz7 --- BUILD_PLAN.md | 17 ++++- internal/db/db.go | 25 +++++++ internal/db/models.go | 49 +++++++------ internal/docs/handlers.go | 3 +- internal/suggestions/handlers.go | 9 ++- internal/suggestions/plant_test.go | 57 +++++++++++++++ internal/vocab/handlers.go | 48 ++++++++----- internal/vocab/handlers_test.go | 86 +++++++++++++++++++++++ internal/vocab/plant.go | 9 ++- web/src/App.tsx | 1 + web/src/api/client.ts | 13 ++++ web/src/audio/speech.test.ts | 32 ++++++++- web/src/audio/speech.ts | 18 +++++ web/src/components/Editor/EditorCore.tsx | 18 +++-- web/src/components/Garden/GardenPanel.tsx | 24 +++++-- 15 files changed, 352 insertions(+), 57 deletions(-) diff --git a/BUILD_PLAN.md b/BUILD_PLAN.md index 3117400..69c74ff 100644 --- a/BUILD_PLAN.md +++ b/BUILD_PLAN.md @@ -441,11 +441,11 @@ Today every correction and every explanation comes back in English, whatever she - **`internal/llm/lang.go` already carries the precision the model needs** (`"European Portuguese (pt-PT, never Brazilian Portuguese)"`). Spanish wants the same care pointed the other way: the shipped dictionary deliberately accepts the whole Spanish-speaking world (Phase 25), so the prompt must not quietly impose peninsular usage. - **Spellcheck must not change.** "A word is a misspelling only when *both* dictionaries reject it" (`useSpellChecker.ts:13`) is a deliberate refusal to detect document language, and it is right: it makes English quotations inside Portuguese prose free, in both directions. Teaching it a document verdict buys nothing and costs a false positive on every borrowed word. - Tests worth writing first: doc-level detection per pair (monolingual, 80/20, 50/50, quotation-heavy English), asserting the hysteresis band **from both directions**; the flipped prompt names the target language and drops the ESL framing while the English-document prompt stays **byte-identical** to today's (the path every existing user is on); the two language arguments proven independent by the only pair that can exercise it — a `learning_pair` zh account writing Chinese wants Chinese corrections explained in English, a `learning_en` zh account writing Chinese wants both in Chinese; a handler test in the shape of `pairlang_test.go`; and a language flip invalidating checked chunks. -- **Open, and needs a decision before the last step.** The **vocabulary garden** harvests phrases from documents, so a Portuguese document would seed it with Portuguese — tag entries by language and filter by the half being learned, or gate harvesting to English documents? Tagging looks right and touches stored rows. **Read-aloud** should follow the document too (all five voices now run on the VPS), which is probably small and lands where the verdict lands, but has not been traced. +- [x] **Resolved 2026-07-28 (user's call), and the two questions had different answers.** The **vocabulary garden** tags every card with the language of the document it was met in, and reviews all of them. Filtering the queue to the half she is learning was the alternative and was rejected for the writer this is for: the words she met while writing Portuguese are still words she met, and a garden that quietly drops them stops being a record of her reading. Gating harvesting to English documents was rejected harder — a looked-up word would simply vanish. **Read-aloud** follows the document, which needed the verdict to reach the client at all: it was server-only until now. - **Order:** (a) detection + salt + checkpoint/voice prompts — the whole visible win, independently shippable; (b) translate-card direction, Ask Petal seed, `/translate` direction; (c) garden and read-aloud, once the two questions above are answered. -- **(a) and (b) are built; (c) is still open** and is the only part of Phase 28 left — the garden's language tagging is a stored-rows decision and read-aloud has not been traced. **Not seen in a browser and not deployed**: no migration beyond `doc_lang`, and the flipped translate card and the skipped seed are asserted through the real `/check` and `/translate` paths in Go tests, not watched. A rebuild whenever the user wants it, along with Phases 24–27. +- **(a), (b) and (c) are built — Phase 28 is complete in code.** **Not seen in a browser and not deployed**: the flipped translate card, the skipped seed, and the garden's tagging are asserted through the real `/check`, `/translate` and `/vocab` paths in Go tests, not watched. A rebuild whenever the user wants it, along with Phases 24–27. -**Step (a) as built, 2026-07-28** — items 1–4. Step (b) and (c) are untouched, and the two open questions under (c) are still open. +**Step (a) as built, 2026-07-28** — items 1–4. - `internal/llm/target.go` — `Target{Correct, Explain, Pair}` + `English` (a `Lang` the `langs` map has no business holding: that map answers "which half is hers"). `EnglishTarget(pair)` is the pre-phase behaviour named, and `Flipped()` is the one question the prompts ask. **Three fields, not two**: the collocation coach's parenthetical gloss is addressed to *her* and not to the document, so it reads `Pair` — collapsing it into `Explain` would have silently moved that gloss into English on every English document, which is every document today. - `internal/suggestions/doclang.go` — `documentLang(contentText, pairLang, prev)` → `"en"`/`"pair"`. Per **sentence** (reusing `splitChunks`, salt `""`), three-way: pair / English / **no answer**. The third value is the load-bearing one — a sentence with no evidence ("Bom dia.", a heading) is left out of the ratio rather than counted for the language it isn't, and counting the undecided as English is exactly what would hold a Portuguese journal of short sentences in English forever. So the Latin pairs needed an `englishMarkers` list curated against pt/fr/es with the same care `latinMarkers` was curated against English (no "on"/"son"/"as"/"no"/"para" — each a false English vote inside someone's own language). Band as specified, ≥70% / <40%, plus a **corroboration floor** the plan didn't call for: 3 distinct pair markers (8 Han runes) document-wide, because a ratio computed over "Não. Eu." is 100% of nothing and a flip rewrites every card in the document. - **Migration `0017_document_lang`** — `documents.doc_lang` (`'' | 'en' | 'pair'`). Stored, not recomputed, because hysteresis needs a yesterday; `'pair'` rather than a language code, so changing her pair re-reads her documents instead of stranding a stale language name on all of them. Backfill is the default `''`, which reads as English — true of every document that exists. @@ -456,6 +456,16 @@ Today every correction and every explanation comes back in English, whatever she - **Not deployed, and no live smoke.** The handler tests drive the real router and a real DB, which is what a smoke would have shown; what neither proves is how Qwen behaves on a Portuguese document — in particular whether the "never translate" line holds. That wants the deploy Phases 24–27 are also waiting on, and a pt-PT reader. - **Left standing, deliberately, and visible on a flipped document:** the offline mechanics rule pack is English (it is the one that filed a note about the stray English sentence), `isTranslation` still points one way (item 5), and the Ask Petal seed still round-trips (item 6). + +**Step (c) as built, 2026-07-28** — the garden and read-aloud, once the two questions above were answered. +- **Migration `0018_vocab_lang`** — `vocab_words.lang` (`'' | 'en' | 'pair'`), the same three values as `documents.doc_lang` and set from it. Not a language code, for the same reason 0017 isn't: `'pair'` re-reads through `users.pair_lang`, so changing her pair doesn't strand a stale name on every card she owns. Backfill `''`, which reads as English — true of every card that exists, because before Phase 28 every document was. +- **The card's language is read off its document, never sent by the client.** Capture already ran a row-scoped lookup to prove she owns the `doc_id` it was handed; that query now returns `doc_lang` too, so the tag costs nothing and cannot be forged. A capture with no document is `''`. **The one asymmetry is in the upsert**: `lang` travels with `doc_id` or it doesn't travel — re-looking-up a word from the search box refreshes its gloss but must not relabel a Portuguese card English, which would silently move it to the wrong voice. +- **Planting carries it too, even though the collocation pass didn't flip.** Phase 28 (a) deliberately left collocation on its English prompt (per-language *knowledge*, not framing). The chunk it hands over is still lifted out of her prose, so the card is in the document's language whatever the prompt was — `plant` reads `d.doc_lang` in the join it was already making. +- **`documents.doc_lang` reaches the client, read-only, for the first time.** It rides on the document JSON, which the editor already refetches on every save, so the verdict trails a language flip by one auto-save. That is the whole cost of not blocking the editor on a check, and the cost is one passage read in the old voice. The `/check` response shape is untouched — it is a bare array of suggestions, and widening it into an object to carry one string would have been the expensive way to save a save. +- **`docLang(text, verdict)` in `speech.ts`, beside `nativeLang()`** — and **the script test still wins over the verdict**, which is not redundant. Chinese quoted inside an English document is `'en'` by verdict and must still be read by the Chinese voice: the English voice spells Han characters out one "Chinese letter" at a time, the one failure loud enough to be worse than silence. In the other direction there is nothing to test — an English sentence inside Portuguese prose is the same letters as the Portuguese around it — so the document's verdict is the only answer available. The editor's selection bubble (both paces) and the garden's list and review cards all ask it instead of guessing. +- **The marker is on pair-language cards only.** A badge on every English blossom to explain the rare Portuguese one is a garden with no badges at all; it names the language the way the pair buttons do, in the language's own word for itself (`pack.nativeName`). +- Tests: capture from a flipped / English / no document, a client-supplied `lang` losing to the document, the recapture-outside-a-document case, planting on both kinds of document, and `docLang` from both directions plus the script override. go build/vet/test clean, tsc and 321 frontend tests green. + ### Later / explicitly not now - Learner-facing Chinese writing (the zh pair's second direction) — own phase with its own spec (SUGGESTIONS §4); only after Phases 19–21 prove the pair model - ~~Spanish pair — gated on DreamDict growing an es dataset~~ **ungated 2026-07-26**, **shipped (code) 2026-07-28** — see Phase 25. What it still owes: a deploy, a native reader, and a writer who actually uses it. @@ -473,6 +483,7 @@ Today every correction and every explanation comes back in English, whatever she - [x] **Phase 14 — companion warmth + bedtime nag + night mode**: more encouraging phrases, a gentle "go to bed" nudge after 11pm, and a calm dark theme + falling stars at night. ✅ (see Phase 14 above) ## Session log +- 2026-07-28: **Phase 28 finished — the garden learns which language a card is in, and read-aloud stops guessing** (user: "let's continue the build plan"; step (c), the last of the phase, code only). The two parked questions turned out to have different answers, and the user took the garden one: **tag every card and review all of them**, rather than filter the queue to the half she is learning — the words she met while writing Portuguese are still words she met. Migration `0018_vocab_lang` mirrors `documents.doc_lang` onto `vocab_words`, set server-side from the row-scoped ownership lookup capture was already running, so the tag is free and unforgeable; the one subtlety is that `lang` travels with `doc_id` or not at all, because a lookup from the search box carries no verdict and must not relabel a card. **Read-aloud was the larger surprise: the verdict was server-only.** `detectLang` routed Han/kana to Chinese and *everything else to en-US*, which made the zh pair accidentally right and every Latin pair wrong — a Portuguese selection read by a US English voice. `doc_lang` now rides on the document JSON (read-only, refreshed by the auto-save the editor already makes, so it trails a flip by one save) and `docLang(text, verdict)` answers for a passage lifted out of it. **The script test deliberately still wins over the verdict**: Chinese quoted in an English document is `'en'` and must not be spelled out one "Chinese letter" at a time, while an English sentence inside Portuguese prose is undetectable by construction — which is exactly why the document decides. One thing worth remembering from the build: an extra bind argument passed to `Exec` against a SQL string that never got its matching `?` **did not error** — the planted card came back with an empty `lang` and only the test caught it. Not seen in a browser; not deployed. - 2026-07-28: **Phase 28 finished — the two steps that point the other way** (user: "let's continue the build plan"; the plan's own next items were 28's unbuilt (b), code only). Both steps are about direction, and both turned out to have a wrong answer that looks right. **`isTranslation` could not simply be read backwards**: swapping its two halves would have called every genuine Portuguese correction inside a Portuguese document a translation, because `readsAsEnglish` is a deliberately low bar — Latin letters, not swamped by another script — that Portuguese clears as easily as English does. The flipped direction uses `sentenceLang` from doclang.go instead, where English has its own curated marker list and has to out-evidence the pair language to win; the English-document path is untouched, and the test file now pins both directions with the Portuguese-in-Portuguese case as the one it exists for. **The translate tap-through's whole observable change is a model call that no longer happens**: it now recovers the explanation's language by re-running `targetFor` rather than assuming the pair, which produces exactly today's answer in every case except the one that was broken — the Portuguese writer whose explanation already arrived in Portuguese, previously round-tripped through the model into Portuguese again. It answers `""` there, and the client's existing `res.translation.trim() || explanation` fallback seeds the bubble with the explanation itself, so the fix needed no frontend change at all. It deliberately does *not* render that explanation into English on the grounds that English is technically the other half: an unasked-for rendering into the language she is practising is noise, not a seed, and Ask Petal is where she can ask for it. What is left of the phase is (c) — the garden's language tagging, which touches stored rows, and read-aloud, which has not been traced. Not seen in a browser; not deployed. - 2026-07-28: **Phase 27 — the keystroke that isn't one** (user asked to continue the build plan; the plan's own next item was Phase 26's unbuilt IME guards, named there as the likeliest thing to be wrong the first time anyone types Chinese into Petal for real). **The bug is that a composition is not a keystroke**: the pinyin goes into the document as it is typed, a candidate window sits over it, and all three decoration layers recompute from the live document on every change — rewriting the DOM around the node the browser is composing in, which is what eats half-typed input. **The fix is to hold the redraws, not skip them**: a rebuild that falls due mid-composition marks itself stale and its decorations are *mapped through the transaction*, so they travel with the text growing under them and land correct the moment the composition ends. Skipping would have left every highlight a character behind for as long as she kept typing — the same wrongness, arriving quietly. **The composition flag is read from the state *before* the transaction**, which makes it independent of plugin ordering: the flag was set by compositionstart, not by the transaction being applied, and the end transaction is the one deliberate exception or nothing would ever release. **One piece of timing genuinely matters and is written down where it happens**: a custom `handleDOMEvents` handler runs *before* ProseMirror's own, and ProseMirror's compositionend queues the composition's last DOM changes as a microtask — so the release is a macrotask late, and the held rebuild sees the committed 公园 rather than the *gongyuan* it replaced. If the flush's transaction arrives first it rebuilds anyway; both orders land, which is what makes it not a race. **One thing was checked rather than assumed and turned out already handled**: Tiptap's input-rule plugin returns early while composing — which matters more here than in an English app, because pinyin uses an apostrophe as a syllable separator (xi'an → 西安) and Typography rewrites every `'` into a curly `’`. **The save is deliberately not gated and the analysis is**: a tablet keyboard can hold one composition open for a whole sentence, and Petal never makes writing wait for anything, so `EditorChange` carries the flag, auto-save ignores it, and the checkpoint/rule pack/companion wait — with one more change emitted the instant the composition commits, so nothing is skipped, only deferred by the length of a word. **And four places were quietly stealing keys from the IME**: the Find bar (Enter = next match, Escape = close), the tag picker (Enter = create, in a field whose purpose is a name typed in Chinese), Ask Petal's chat box (the field she types Mandarin into, where Enter sends), and distraction-free mode's global Escape — pressed to fix a wrong candidate, it popped the sidebar back. tsc, vite, go build/vet/test, **vitest 296/296** (12 new, driving real plugin state through a real composition: pinyin in, candidate committed, composition ended). **Then verified in a real browser** (Chrome extension, throwaway DB on :8093): the events are dispatched rather than typed, since this box has no IME, but they drive ProseMirror's own composition machinery, so every layer takes the real path. `gongyuan` typed into the document mid-composition with **the caret moved off it** — so the caret exemption cannot be the explanation — stays un-underlined while `parc` keeps its underline, and underlines on compositionend with no further keystroke. *did a mistake* highlights in 800 ms typed normally and **not at all** after 1.2 s inside a composition, then appears the instant it commits. The save is not held, proven from the other side: with the composition still open and never ended, the server's copy already read `… STILLCOMPOSING`. Escape (`isComposing` and legacy 229) leaves distraction-free mode alone while a real Escape restores the sidebar; the Find bar counter goes 1/4, 1/4, 2/4. **Then with a real IME**, because the user installed one and typed — the only way it could be done: Chrome here runs natively on Wayland, so no key can be injected into its window, and the extension's keys arrive over CDP, which bypasses the OS input method entirely. 很漂亮, composed over **11.6 seconds and 12 candidate changes** (和 → 很 → 狠批 → 很票 → 很漂亮 …), with the preedit genuinely living in the document the whole time — and the underline set never moved, the word committed clean, and English typed afterwards flagged immediately. **The accidental control is the best part**: she typed `henpiaoliang` as plain letters before switching the IME on and it was underlined, so the same syllables appear twice in one sentence, flagged on the path that isn't a composition and untouched on the path that is. ⚠️ **The counterfactual is still unproven** — a clean run with the guard in place can't distinguish "held correctly" from "would have been fine anyway"; settling that means a build with the guard reverted and another minute of her typing. **Not deployed** (no migration — a rebuild, along with Phases 24–26). - 2026-07-28: **Phase 26 — the zh pair's other direction, and a rule pack whose best feature is what it refuses** (user asked to continue the build plan, then chose a new phase over deploying fr/es; scope chosen with the user: **direction column, segmentation + hover pinyin/gloss, 错别字, IME guards**, code only). SUGGESTIONS §4 had called this its own epic, and the reason turned out to be one sentence: **`pair_lang` had always been answering a second question nobody asked.** It says which two languages; every surface built on it assumed English was the one being *learned*, which is why CJK is deliberately never tokenized, never spell-checked and never glossed. All correct for the writer this app was built for, all backwards for the other one. A `direction` column rather than a `zh-learner` pair code, because the two are genuinely separate questions and the column is what lets fr/es/pt inherit the capacity later. **The phase has three decisions in it and they are all about coverage.** The browser gets a word list and the server keeps the dictionary, and their gates come out *opposite*: the client list is frequency-gated at 5 because segmentation by the full union and by the gated list is **identical** on ordinary prose (measured, including 研究生命的起源 and 乒乓球拍卖完了 — the long tail is rare proper nouns and the max-probability walk never picks one), while the dictionary is gated by **nothing**, because its only power is to *explain* and the word a learner stops on is precisely the rare one. That is the es dictionary decision arrived at from both sides in one phase. **Writing the segmenter tests found the boundary bug**: a position names a gap and a word covers characters, so a hover on a boundary was resolving to the word that ended there rather than the one that starts. **The 错别字 pack is the part worth reading.** Chinese has no misspellings — every character an IME offers is real — so the unit of error is a substituted character inside a correct-looking word, and the pack is 24 confusable pairs held by two mechanical gates. Gate one admits a pair only if the wrong form is *not* a dictionary word and the right form is, which is what makes it refuse **自已 for 自己** — one of the commonest slips in written Chinese, whose wrong form is itself a headword — exactly as Phase 22 refused `married with`. Gate two is the one that matters: **自己经常 contains 己经, 睡觉的时候 contains 觉的, 不知到底 contains 知到**, so a substring match would corrupt correct sentences silently, into text still made of real characters. The segmenter settles it — two adjacent single-character tokens is what the walk produces when it has nothing better, which is what a mistyped compound looks like — and where the gate costs a real catch (我不知到他在哪里 *is* 知到 for 知道, but 不知 is a word) it declines rather than risk the identical-looking correct sentence beside it. **`@types/node` went in as a devDependency and quietly fixes something older**: phases 21–25 each verified their shipped dictionary with a throwaway script because vitest could not read files; the suite now asserts against the real assets. go build/vet/test, tsc, vite, **vitest 284/284**, live smoke on a throwaway DB which itself caught a cosmetic build bug ("cat (" left by stripping CC-CEDICT's CL: field). ⚠️ **The IME guards were in scope and are not done** — no composition handling exists anywhere in the app, and a decoration rebuild mid-composition eating half-typed pinyin is the likeliest thing to be wrong the first time anyone types Chinese into Petal for real. Left untouched rather than half-built, and named here rather than buried. ⚠️ **Not deployed** (it carries a migration), **not seen in a browser**, and **no account has ever been in the learner direction**, so everything above about how it feels to use is inference from tests. diff --git a/internal/db/db.go b/internal/db/db.go index 0da7b3e..3207328 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -613,6 +613,31 @@ ALTER TABLE users ADD COLUMN direction TEXT NOT NULL DEFAULT 'learning_en' stmt: ` ALTER TABLE documents ADD COLUMN doc_lang TEXT NOT NULL DEFAULT '' CHECK(doc_lang IN ('', 'en', 'pair')); +`, + }, + { + // Which language a garden card is in — the same '' | 'en' | 'pair' + // vocabulary as documents.doc_lang, and set from it: a word is captured + // (or a phrase planted) out of a document, so the document's verdict is + // the card's language. A card with no document keeps '', which reads as + // English like every other empty here. + // + // The garden needed this the moment a document could be written in her + // own language. Before Phase 28 every card was English by construction; + // now a Portuguese lookup lands beside an English one with nothing to + // tell them apart, and two surfaces get it wrong without the tag — the + // review card's read-aloud (which would say a Portuguese word in a US + // English voice) and the panel, where a mixed garden is illegible. + // + // Every card is reviewed regardless. Filtering the queue to the half she + // is learning was the alternative and is wrong for the writer this is + // for: the words she met while writing Portuguese are still words she + // met, and a garden that quietly drops them is a garden that stops being + // a record of her reading. + name: "0018_vocab_lang", + stmt: ` +ALTER TABLE vocab_words ADD COLUMN lang TEXT NOT NULL DEFAULT '' + CHECK(lang IN ('', 'en', 'pair')); `, }, } diff --git a/internal/db/models.go b/internal/db/models.go index fbd15a5..a24d58a 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -34,15 +34,20 @@ type User struct { // (source of truth for the editor); `ContentText` is the flattened plain text // kept in sync on every save and fed to the LLM. type Document struct { - ID string `json:"id"` - UserID string `json:"user_id"` - Title string `json:"title"` - Content string `json:"content"` // Tiptap JSON - ContentText string `json:"content_text"` // plain text for the LLM - Tone string `json:"tone"` // target writing tone; steers LLM advice - WordCount int `json:"word_count"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + UserID string `json:"user_id"` + Title string `json:"title"` + Content string `json:"content"` // Tiptap JSON + ContentText string `json:"content_text"` // plain text for the LLM + Tone string `json:"tone"` // target writing tone; steers LLM advice + WordCount int `json:"word_count"` + // DocLang is which language this document is written in — '' | 'en' | 'pair' + // (migration 0017), written by the checkpoint pass and never by the client. + // It reaches the client read-only, for the one decision the client has to + // make on its own: which voice reads a selection aloud. '' means English. + DocLang string `json:"doc_lang"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` // PreserveHistory opts this document out of auto-snapshot pruning so its // full writing trail survives as authorship evidence (see the passport). @@ -110,15 +115,15 @@ const ( // coordinates at render time (spec Note #6). `Replacement` is empty for `voice` // flags — those are awareness-only, with no correction to apply. type Suggestion struct { - ID string `json:"id"` - DocID string `json:"doc_id"` - FromPos int `json:"from_pos"` - ToPos int `json:"to_pos"` - Original string `json:"original"` - Replacement string `json:"replacement"` - Explanation string `json:"explanation"` - Type string `json:"type"` // grammar | phrasing | idiom | clarity | translate | voice | collocation - Status string `json:"status"` // pending | accepted | rejected + ID string `json:"id"` + DocID string `json:"doc_id"` + FromPos int `json:"from_pos"` + ToPos int `json:"to_pos"` + Original string `json:"original"` + Replacement string `json:"replacement"` + Explanation string `json:"explanation"` + Type string `json:"type"` // grammar | phrasing | idiom | clarity | translate | voice | collocation + Status string `json:"status"` // pending | accepted | rejected // Source names the engine that proposed the edit, not its family: an offline // rule and the model can both propose a collocation, and the writer is never // told which one spoke. It exists so each pass can replace its own rows. @@ -128,10 +133,10 @@ type Suggestion struct { // Suggestion type and status values, mirrored from the schema CHECK constraints. const ( - SuggestionTypeGrammar = "grammar" - SuggestionTypePhrasing = "phrasing" - SuggestionTypeIdiom = "idiom" - SuggestionTypeClarity = "clarity" + SuggestionTypeGrammar = "grammar" + SuggestionTypePhrasing = "phrasing" + SuggestionTypeIdiom = "idiom" + SuggestionTypeClarity = "clarity" // A span she wrote in her own language, rendered into English. Not a // correction — nothing was wrong with it — which is why it is its own type // rather than a clarity fix: the card is the pair model's flagship moment diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go index 42f5a28..ea00a81 100644 --- a/internal/docs/handlers.go +++ b/internal/docs/handlers.go @@ -225,13 +225,14 @@ func (h *Handler) fetch(userID, id string) (db.Document, error) { var doc db.Document err := h.DB.QueryRow( `SELECT id, user_id, title, content, content_text, tone, word_count, - created_at, updated_at, preserve_history + created_at, updated_at, preserve_history, doc_lang FROM documents WHERE id = ? AND user_id = ?`, id, userID, ).Scan( &doc.ID, &doc.UserID, &doc.Title, &doc.Content, &doc.ContentText, &doc.Tone, &doc.WordCount, &doc.CreatedAt, &doc.UpdatedAt, &doc.PreserveHistory, + &doc.DocLang, ) return doc, err } diff --git a/internal/suggestions/handlers.go b/internal/suggestions/handlers.go index d91ff8c..a57e371 100644 --- a/internal/suggestions/handlers.go +++ b/internal/suggestions/handlers.go @@ -825,13 +825,13 @@ func (h *Handler) setStatus(w http.ResponseWriter, r *http.Request, status strin // hands over a reusable chunk, which is the only thing worth reviewing in a week. func (h *Handler) plant(id, userID string) { var s db.Suggestion - var contentText string + var contentText, docLang string err := h.DB.QueryRow( - `SELECT s.type, s.original, s.replacement, s.explanation, s.doc_id, d.content_text + `SELECT s.type, s.original, s.replacement, s.explanation, s.doc_id, d.content_text, d.doc_lang FROM suggestions s JOIN documents d ON d.id = s.doc_id WHERE s.id = ? AND d.user_id = ?`, id, userID, - ).Scan(&s.Type, &s.Original, &s.Replacement, &s.Explanation, &s.DocID, &contentText) + ).Scan(&s.Type, &s.Original, &s.Replacement, &s.Explanation, &s.DocID, &contentText, &docLang) if err != nil { if !errors.Is(err, sql.ErrNoRows) { log.Printf("suggestions: could not read %s for planting: %v", id, err) @@ -850,6 +850,9 @@ func (h *Handler) plant(id, userID string) { Meaning: s.Explanation, Example: correctedSentence(contentText, s.Original, s.Replacement), DocID: &docID, + // The chunk is her own sentence, corrected — so it is in the document's + // language, whatever the collocation pass was framed in. + Lang: docLang, }); err != nil { log.Printf("suggestions: could not plant %s: %v", id, err) } diff --git a/internal/suggestions/plant_test.go b/internal/suggestions/plant_test.go index 854de5d..f4bf498 100644 --- a/internal/suggestions/plant_test.go +++ b/internal/suggestions/plant_test.go @@ -184,3 +184,60 @@ func TestCorrectedSentence(t *testing.T) { t.Errorf("unterminated doc: got %q", got) } } + +// TestPlantedPhraseCarriesTheDocumentLanguage: a chunk planted out of a document +// written in her own language is a card in that language. The collocation pass +// itself deliberately did not flip in Phase 28 — its prompt is per-language +// knowledge, not framing — but the phrase it hands over is still lifted from her +// prose, so the card has to know what language that prose was in or the garden +// will read it aloud in the wrong voice. +func TestPlantedPhraseCarriesTheDocumentLanguage(t *testing.T) { + srv, docID, h := newTestServer(t, &stubClient{}) + if _, err := h.DB.Exec(`UPDATE documents SET doc_lang = 'pair' WHERE id = ?`, docID); err != nil { + t.Fatalf("set doc_lang: %v", err) + } + id := seedSuggestion(t, h, docID, + "Ontem foi difícil. Tive de tomar uma decisão sobre o trabalho.", + db.SuggestionTypeCollocation, "tomar uma decisão", "tomar uma decisão", + "Em português diz-se “tomar” uma decisão.") + + if rec := do(t, srv, http.MethodPost, "/suggestions/"+id+"/accept", ""); rec.Code != http.StatusNoContent { + t.Fatalf("accept: got %d, want 204", rec.Code) + } + + var lang string + if err := h.DB.QueryRow( + `SELECT lang FROM vocab_words WHERE user_id = ? AND word = ?`, + db.LocalUserID, "tomar uma decisão", + ).Scan(&lang); err != nil { + t.Fatalf("read planted card: %v", err) + } + if lang != "pair" { + t.Fatalf("planted card lang = %q, want pair", lang) + } +} + +// TestPlantedPhraseOnAnEnglishDocumentIsUnchanged is the other half, and the one +// every account is on today: an English document plants an English card, and the +// empty backfill and 'en' both mean that. +func TestPlantedPhraseOnAnEnglishDocumentIsUnchanged(t *testing.T) { + srv, docID, h := newTestServer(t, &stubClient{}) + id := seedSuggestion(t, h, docID, "I had to do a decision about the job.", + db.SuggestionTypeCollocation, "do a decision", "make a decision", + "English pairs “make” with “decision”.") + + if rec := do(t, srv, http.MethodPost, "/suggestions/"+id+"/accept", ""); rec.Code != http.StatusNoContent { + t.Fatalf("accept: got %d, want 204", rec.Code) + } + + var lang string + if err := h.DB.QueryRow( + `SELECT lang FROM vocab_words WHERE user_id = ? AND word = ?`, + db.LocalUserID, "make a decision", + ).Scan(&lang); err != nil { + t.Fatalf("read planted card: %v", err) + } + if lang == "pair" { + t.Fatalf("planted card lang = %q on an English document, want en or empty", lang) + } +} diff --git a/internal/vocab/handlers.go b/internal/vocab/handlers.go index e205f49..5d0d9f1 100644 --- a/internal/vocab/handlers.go +++ b/internal/vocab/handlers.go @@ -19,13 +19,18 @@ import ( // Word is one entry in the vocabulary garden: the looked-up word with its gloss, // phonetic, and the sentence it was met in, plus its spaced-repetition state. type Word struct { - ID string `json:"id"` - Word string `json:"word"` - Gloss string `json:"gloss"` - Definition string `json:"definition"` // English fallback meaning when there's no Chinese gloss - Phonetic string `json:"phonetic"` - Example string `json:"example"` - DocID *string `json:"doc_id"` + ID string `json:"id"` + Word string `json:"word"` + Gloss string `json:"gloss"` + Definition string `json:"definition"` // English fallback meaning when there's no Chinese gloss + Phonetic string `json:"phonetic"` + Example string `json:"example"` + DocID *string `json:"doc_id"` + // Lang is '' | 'en' | 'pair' — the language of the document the word was met + // in (see migration 0018). '' reads as English, like everywhere else this + // vocabulary appears. The client needs it to pick a read-aloud voice: "comum" + // is unguessable from its letters, so the card has to carry the answer. + Lang string `json:"lang"` DueAt time.Time `json:"due_at"` IntervalDays int `json:"interval_days"` Ease float64 `json:"ease"` @@ -54,7 +59,7 @@ func (h *Handler) Routes() chi.Router { return r } -const vocabColumns = `id, word, gloss, definition, phonetic, example, doc_id, +const vocabColumns = `id, word, gloss, definition, phonetic, example, doc_id, lang, due_at, interval_days, ease, reps, lapses, last_reviewed, created_at` func scanWord(s interface { @@ -62,7 +67,7 @@ func scanWord(s interface { }) (Word, error) { var w Word err := s.Scan( - &w.ID, &w.Word, &w.Gloss, &w.Definition, &w.Phonetic, &w.Example, &w.DocID, + &w.ID, &w.Word, &w.Gloss, &w.Definition, &w.Phonetic, &w.Example, &w.DocID, &w.Lang, &w.DueAt, &w.IntervalDays, &w.Ease, &w.Reps, &w.Lapses, &w.LastReviewed, &w.CreatedAt, ) return w, err @@ -165,15 +170,22 @@ func (h *Handler) capture(w http.ResponseWriter, r *http.Request) { // would hit the foreign key and leak a raw "FOREIGN KEY constraint" 500 // instead of a clean 400 (and, once auth lands, would let a word be attached // to another user's document). + // + // The same row-scoped lookup answers what language the card is in: a word is + // met inside a document, so the document's verdict is the word's language. + // Asking the document rather than trusting a `lang` in the request body is + // the same choice `runPass` makes — the client never gets to name a language + // the server can already read. A word with no document is '', which reads as + // English. + lang := "" if req.DocID != nil { if strings.TrimSpace(*req.DocID) == "" { req.DocID = nil } else { - var ok int err := h.DB.QueryRow( - `SELECT 1 FROM documents WHERE id = ? AND user_id = ?`, + `SELECT doc_lang FROM documents WHERE id = ? AND user_id = ?`, *req.DocID, userID, - ).Scan(&ok) + ).Scan(&lang) if errors.Is(err, sql.ErrNoRows) { httputil.ErrorJSON(w, http.StatusBadRequest, "unknown doc_id") return @@ -189,15 +201,19 @@ func (h *Handler) capture(w http.ResponseWriter, r *http.Request) { // schedule (due_at/reps/interval/ease) alone so re-looking-up a word never // resets its progress. _, err := h.DB.Exec( - `INSERT INTO vocab_words (user_id, word, gloss, definition, phonetic, example, doc_id, due_at, interval_days) - VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now', '+1 day'), 1) + `INSERT INTO vocab_words (user_id, word, gloss, definition, phonetic, example, doc_id, lang, due_at, interval_days) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now', '+1 day'), 1) ON CONFLICT(user_id, word) DO UPDATE SET gloss = excluded.gloss, definition = excluded.definition, phonetic = excluded.phonetic, example = CASE WHEN excluded.example != '' THEN excluded.example ELSE vocab_words.example END, - doc_id = COALESCE(excluded.doc_id, vocab_words.doc_id)`, - userID, word, req.Gloss, req.Definition, req.Phonetic, req.Example, req.DocID, + doc_id = COALESCE(excluded.doc_id, vocab_words.doc_id), + -- lang travels with doc_id, and for the same reason: it is the new + -- context or it is nothing. A lookup made outside any document must + -- not relabel a card that was captured inside one. + lang = CASE WHEN excluded.doc_id IS NOT NULL THEN excluded.lang ELSE vocab_words.lang END`, + userID, word, req.Gloss, req.Definition, req.Phonetic, req.Example, req.DocID, lang, ) if err != nil { httputil.ServerError(w, err) diff --git a/internal/vocab/handlers_test.go b/internal/vocab/handlers_test.go index 54d8c2e..6987713 100644 --- a/internal/vocab/handlers_test.go +++ b/internal/vocab/handlers_test.go @@ -253,3 +253,89 @@ func TestDocLinkSurvivesDocDelete(t *testing.T) { t.Fatalf("doc_id should be nulled after doc delete, got %v", *all[0].DocID) } } + +// TestCaptureTakesLanguageFromItsDocument is the garden's half of Phase 28: a +// word met inside a document written in her own language is a card in that +// language, and the server reads that off the document rather than being told. +// +// The three cases are the three the client can actually produce: a lookup inside +// a flipped document, a lookup inside an English one, and a lookup with no +// document at all (the search box) — the last of which is '', which reads as +// English everywhere this value is used. +func TestCaptureTakesLanguageFromItsDocument(t *testing.T) { + srv, database := newTestServer(t) + + seed := func(lang string) string { + t.Helper() + var id string + if err := database.QueryRow( + `INSERT INTO documents (user_id, content_text, doc_lang) VALUES (?, 'hi', ?) RETURNING id`, + db.LocalUserID, lang, + ).Scan(&id); err != nil { + t.Fatalf("seed doc: %v", err) + } + return id + } + pairDoc, enDoc := seed("pair"), seed("en") + + capture := func(word, body string) Word { + t.Helper() + rec := do(t, srv, http.MethodPost, "/vocab", body) + if rec.Code != http.StatusCreated { + t.Fatalf("capture %s: code=%d body=%s", word, rec.Code, rec.Body) + } + var w Word + if err := json.Unmarshal(rec.Body.Bytes(), &w); err != nil { + t.Fatalf("decode %s: %v", word, err) + } + return w + } + + if got := capture("comum", `{"word":"comum","doc_id":"`+pairDoc+`"}`); got.Lang != "pair" { + t.Fatalf("word from a flipped document: lang=%q, want pair", got.Lang) + } + if got := capture("reception", `{"word":"reception","doc_id":"`+enDoc+`"}`); got.Lang != "en" { + t.Fatalf("word from an English document: lang=%q, want en", got.Lang) + } + if got := capture("orphan", `{"word":"orphan"}`); got.Lang != "" { + t.Fatalf("word with no document: lang=%q, want empty", got.Lang) + } + + // A client that names a language is ignored: the document is the authority, + // the same way runPass never lets the request pick its own target. + if got := capture("comum", `{"word":"comum","lang":"en","doc_id":"`+pairDoc+`"}`); got.Lang != "pair" { + t.Fatalf("client-supplied lang should not win: lang=%q, want pair", got.Lang) + } +} + +// TestRecaptureOutsideADocumentKeepsItsLanguage pins the one asymmetry in the +// upsert. Re-looking-up a word refreshes its context, but a lookup made with no +// document carries no verdict — and relabelling a Portuguese card English +// because she checked the word again from the search box would silently move it +// to the wrong voice. lang travels with doc_id, or it doesn't travel. +func TestRecaptureOutsideADocumentKeepsItsLanguage(t *testing.T) { + srv, database := newTestServer(t) + var docID string + if err := database.QueryRow( + `INSERT INTO documents (user_id, content_text, doc_lang) VALUES (?, 'olá', 'pair') RETURNING id`, + db.LocalUserID, + ).Scan(&docID); err != nil { + t.Fatalf("seed doc: %v", err) + } + if rec := do(t, srv, http.MethodPost, "/vocab", + `{"word":"saudade","gloss":"","doc_id":"`+docID+`"}`); rec.Code != http.StatusCreated { + t.Fatalf("capture: code=%d body=%s", rec.Code, rec.Body) + } + rec := do(t, srv, http.MethodPost, "/vocab", `{"word":"saudade","gloss":"longing"}`) + if rec.Code != http.StatusCreated { + t.Fatalf("recapture: code=%d body=%s", rec.Code, rec.Body) + } + var w Word + _ = json.Unmarshal(rec.Body.Bytes(), &w) + if w.Lang != "pair" { + t.Fatalf("recapture outside a document: lang=%q, want pair held", w.Lang) + } + if w.Gloss != "longing" { + t.Fatalf("recapture should still refresh the gloss, got %q", w.Gloss) + } +} diff --git a/internal/vocab/plant.go b/internal/vocab/plant.go index c04041d..dc15cc8 100644 --- a/internal/vocab/plant.go +++ b/internal/vocab/plant.go @@ -28,6 +28,10 @@ type Phrase struct { Meaning string // why it's better — the suggestion's explanation Example string // the sentence she met it in, already corrected DocID *string // where, so "where did I see this?" stays one tap + // Lang is the document's verdict ('' | 'en' | 'pair'), because the chunk is + // lifted out of her own prose and is therefore in whatever language that + // prose is. See migration 0018. + Lang string } // Phrase-card caps. A collocation is a short chunk; anything longer is a @@ -84,13 +88,14 @@ func Plant(ex Execer, userID string, p Phrase) (bool, error) { return false, nil } res, err := ex.Exec( - `INSERT INTO vocab_words (user_id, word, gloss, definition, phonetic, example, doc_id, due_at, interval_days) - VALUES (?, ?, '', ?, '', ?, ?, datetime('now', '+1 day'), 1) + `INSERT INTO vocab_words (user_id, word, gloss, definition, phonetic, example, doc_id, lang, due_at, interval_days) + VALUES (?, ?, '', ?, '', ?, ?, ?, datetime('now', '+1 day'), 1) ON CONFLICT(user_id, word) DO NOTHING`, userID, key, clamp(strings.TrimSpace(p.Meaning), maxDefinitionLen), clamp(strings.TrimSpace(p.Example), maxExampleLen), p.DocID, + p.Lang, ) if err != nil { return false, err diff --git a/web/src/App.tsx b/web/src/App.tsx index cc0a656..65fe344 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -615,6 +615,7 @@ export default function App() { { expect(bodies.at(-1)).toMatchObject({ text: 'chat', lang: 'fr-FR' }) }) }) + +describe('docLang', () => { + // The document's verdict is the answer for a passage lifted out of it, because + // for a Latin pair there is no other answer available: an English sentence and + // a Portuguese one are the same letters. + it('reads a flipped document in her own language', () => { + setPackLang('pt-PT') + expect(docLang('Ontem foi difícil.', 'pair')).toBe('pt-PT') + }) + + it('reads an English document in English, and treats the backfill as English', () => { + setPackLang('pt-PT') + expect(docLang('Yesterday was hard.', 'en')).toBe('en-US') + expect(docLang('Yesterday was hard.', '')).toBe('en-US') + }) + + it('lets the script win over the verdict, so quoted Chinese is never spelled out', () => { + // An English document quoting Chinese is 'en' by verdict, and the English + // voice reads Han characters one "Chinese letter" at a time — the one + // failure worse than silence. + setPackLang('zh') + expect(docLang('你好世界', 'en')).toBe('zh-CN') + }) + + it('is what the editor selection and the garden card ask for', () => { + setPackLang('fr') + speak('Le chat dort.', docLang('Le chat dort.', 'pair')) + expect(bodies.at(-1)).toMatchObject({ text: 'Le chat dort.', lang: 'fr-FR' }) + }) +}) diff --git a/web/src/audio/speech.ts b/web/src/audio/speech.ts index eefc694..7640b01 100644 --- a/web/src/audio/speech.ts +++ b/web/src/audio/speech.ts @@ -90,6 +90,24 @@ export function nativeLang(): string { return pack().locale } +// docLang turns a document-language verdict ('' | 'en' | 'pair', decided +// server-side — see internal/suggestions/doclang.go) into a locale for a passage +// taken out of that document. It is what the editor's read-aloud and the garden's +// review card ask instead of guessing. +// +// The script test still wins, and that is not redundant with the verdict. A +// Chinese sentence quoted inside an English document is 'en' by verdict and +// still has to be read by the Chinese voice: the English voice spells Han +// characters out one "Chinese letter" at a time, which is the one failure loud +// enough to be worse than no audio. In the other direction there is nothing to +// test — an English sentence inside Portuguese prose looks exactly like the +// Portuguese around it — so the document's verdict is the only answer available, +// and it is the answer this phase decided on. +export function docLang(text: string, verdict: string): string { + if (CJK.test(text)) return 'zh-CN' + return verdict === 'pair' ? pack().locale : 'en-US' +} + // speak reads `text` aloud, cancelling anything already in flight so rapid taps // don't queue up. `lang` defaults to a guess from the text (Chinese vs English) // so callers can just pass the selection; pass an explicit locale to override. diff --git a/web/src/components/Editor/EditorCore.tsx b/web/src/components/Editor/EditorCore.tsx index 1c745ad..c3897c8 100644 --- a/web/src/components/Editor/EditorCore.tsx +++ b/web/src/components/Editor/EditorCore.tsx @@ -33,8 +33,8 @@ import { Composition } from './Composition' import { RewritePreview, type RewriteStatus } from './RewritePreview' import { planBatch } from './acceptBatch' import { entryId, idAfterRemoval, stepId, type Direction, type Span } from './triage' -import { api, type Suggestion, type SuggestionType, type WordInfo } from '../../api/client' -import { speak, speechSupported } from '../../audio/speech' +import { api, type DocLang, type Suggestion, type SuggestionType, type WordInfo } from '../../api/client' +import { docLang as docLocale, speak, speechSupported } from '../../audio/speech' import type { SpellChecker } from '../../hooks/useSpellChecker' import { fromIME } from '../../lib/ime' import type { Segmenter } from '../../lib/segment' @@ -65,6 +65,13 @@ export interface EditorChange { interface Props { // Changing docId reloads the editor with that document's content. docId: string + // Which language this document is written in, as the server decided it + // ('' | 'en' | 'pair'). Read-aloud is the only thing here that reads it: a + // Portuguese selection has to be read by the Portuguese voice, and nothing in + // the letters says so. Updated by the server on save, so it trails a language + // flip by one auto-save — a passage read in the old voice once is the whole + // cost of not blocking the editor on a check. + docLang: DocLang initialContent: string onChange: (change: EditorChange) => void // LLM suggestions to highlight; accept/dismiss notify the parent for the API @@ -255,6 +262,7 @@ interface RewriteState { // decoration layer. Hovering a highlight opens its SuggestionCard. export function EditorCore({ docId, + docLang, initialContent, onChange, suggestions, @@ -1532,8 +1540,10 @@ export function EditorCore({ speak(selection.text) : null} - onSpeakSlow={speechSupported() ? () => speak(selection.text, undefined, true) : null} + onSpeak={speechSupported() ? () => speak(selection.text, docLocale(selection.text, docLang)) : null} + onSpeakSlow={ + speechSupported() ? () => speak(selection.text, docLocale(selection.text, docLang), true) : null + } /> )} {rewrite && ( diff --git a/web/src/components/Garden/GardenPanel.tsx b/web/src/components/Garden/GardenPanel.tsx index f2ac745..872924c 100644 --- a/web/src/components/Garden/GardenPanel.tsx +++ b/web/src/components/Garden/GardenPanel.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { api, type VocabGrade, type VocabWord } from '../../api/client' -import { speak, speechSupported, stopSpeech } from '../../audio/speech' +import { docLang as docLocale, speak, speechSupported, stopSpeech } from '../../audio/speech' import { useFocusTrap } from '../../hooks/useFocusTrap' import { usePack, type Line } from '../../i18n' import { JournalView } from './JournalView' @@ -314,7 +314,21 @@ function GardenView({ {blossom(w.reps)} - {w.word} + + {w.word} + {/* Only a card in her own language is marked. An English + garden with a badge on every blossom would be a + garden with no badges at all; the marker exists so + the rare Portuguese word is legible among them. */} + {w.lang === 'pair' && ( + + {t.nativeName} + + )} + {(w.gloss || w.definition) && ( speak(w.word)} + onClick={() => speak(w.word, docLocale(w.word, w.lang))} className="rounded-full px-2.5 py-1 text-xs font-semibold" style={{ background: 'var(--color-surface-alt)' }} > @@ -477,7 +491,7 @@ function ReviewSession({ <>