From 29eb2fe1fc1dbffc6229c6abb2d8deae537c4412 Mon Sep 17 00:00:00 2001 From: prosolis <5590409+prosolis@users.noreply.github.com> Date: Tue, 28 Jul 2026 23:29:50 -0700 Subject: [PATCH] The translate card, pointed the other way, and a call that no longer happens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 28's step (b): both remaining items are about direction, and both had a wrong answer that looked right. isTranslation could not simply be read backwards. readsAsEnglish is a deliberately low bar — Latin letters, not swamped by another script — which every Portuguese sentence clears as easily as English does, so swapping its two halves would have called every genuine Portuguese correction inside a Portuguese document a translation. 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; reconcilePending carries the verdict to ask the question the right way round. The tap-through's whole observable change is a model call that stops happening. /suggestions/{id}/translate now recovers the explanation's language by re-running targetFor rather than assuming the pair, which gives today's answer everywhere except the case 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 — 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. Tests pin both directions of the detector, with Portuguese-in-Portuguese as the case the file exists for, plus four handler tests through the real /check and /translate paths — including the skipped seed asserting the model was never called, and the learning_pair zh learner whose English explanation still renders into Chinese. Left of the phase: (c) the garden's language tagging and read-aloud. Claude-Session: https://claude.ai/code/session_01GJHNvirh7Hzhc9RL3HAvz7 --- BUILD_PLAN.md | 10 +- internal/suggestions/doclang_test.go | 134 ++++++++++++++++++++++++++ internal/suggestions/handlers.go | 24 +++-- internal/suggestions/language.go | 33 +++++-- internal/suggestions/language_test.go | 97 ++++++++++++++++++- internal/suggestions/reconcile.go | 10 +- internal/suggestions/translate.go | 46 +++++++-- 7 files changed, 318 insertions(+), 36 deletions(-) diff --git a/BUILD_PLAN.md b/BUILD_PLAN.md index d48af4b..3117400 100644 --- a/BUILD_PLAN.md +++ b/BUILD_PLAN.md @@ -423,7 +423,7 @@ Phase 26's own outstanding item, and the thing it named as most likely to be wro - ⚠️ **What this still does not prove is the counterfactual** — that the bug would have bitten *here* without the guard. Chrome's own composition handling is robust, and a clean run with the guard in place cannot distinguish "held correctly" from "would have been fine anyway". Settling it means building with the guard reverted and asking her to type once more; offered, not assumed. - **Not deployed.** No migration; a rebuild whenever the user wants it, along with Phases 24–26. -### Phase 28 — following the writing into her own language (planned 2026-07-28; step (a) built 2026-07-28) +### Phase 28 ✅ (2026-07-28, code half) — following the writing into her own language Today every correction and every explanation comes back in English, whatever she wrote. `CheckpointMessages` (`internal/llm/prompts.go:49`) takes the text and the tone and **nothing else** — there is no language parameter to pass, so there has never been a language decision to get wrong. The pair language reaches her only on demand: tapping Ask Petal fetches a translation of the English explanation (`AskPetal.tsx:93`), and that panel answers in her language because `AskPetalSystemPrompt` is given one. Right default for a writer practising English; wrong default for a document written in Portuguese, where Petal reads the Portuguese prose, says nothing about it, and files a mechanics note about the one English sentence at the end. **Observed on the live build 2026-07-28**: two pt-PT sentences drew no cards at all. 1. [x] **The rule is two decisions, not one, and they read different state.** What gets *corrected* follows the **document** — Portuguese prose gets Portuguese corrections, which is the whole point. What language the explanation is *written in* follows the **writer**: the half of her pair she is not learning, from the `direction` column (`internal/auth/users.go:96`), because an explanation is teaching and teaching lands in the language she reads most easily. So a native Portuguese speaker practising English, writing Portuguese, gets Portuguese corrections explained in Portuguese; a native English speaker learning French, writing French, gets French corrections explained in English. Neither is trapped — the other language stays one tap away, in both directions. @@ -434,13 +434,16 @@ Today every correction and every explanation comes back in English, whatever she - **Plain code, no model call** — the house rule that the LLM is garnish, never a gatekeeper. zh is a rune-script count (already written); pt-PT, fr and es reuse `latinMarkers`, aggregated per sentence rather than per span. 3. [x] **`checkpointSystemPrompt` cannot simply take a language.** It opens with *"helping someone who speaks English as a second language"* and asks for ESL patterns — appending "explain in Portuguese" hands the model two contradictory instructions. Split it: shared JSON contract and tone clause, framing sentence filled per direction. `CheckpointMessages` and `VoiceMessages` (which has no language at all today) take **two** language arguments — corrected and explained-in — and **resist collapsing them into one `Lang` while every current account has them equal**: that equality is a fact about today's `learnerPairs`, not about the design. 4. [x] **The verdict rides with `pairLang` in the row-scoped lookup and folds into the chunk salt** next to `tone` (`handlers.go`). That is the cheap correct answer to stale cards: when a document's language flips, every sentence's identity changes, so old-language cards are re-checked rather than left sitting there in the wrong language. -5. [ ] **`isTranslation` learns which way it points.** It currently means "her language rendered into English"; in a flipped document the useful translate card is the mirror image, so the test takes the document verdict and checks the direction that matches. -6. [ ] **The tap-through has to stop assuming its direction, and this is not optional dressing** — it is what makes rule 1 safe for a learner reading explanations in English. `/suggestions/{id}/translate` always renders into the pair language today; it should render into whichever half the explanation is *not* already in, and skip the seed entirely when those coincide rather than round-tripping Portuguese into Portuguese. +5. [x] **`isTranslation` learns which way it points — and the flipped test could not be the old one read backwards.** In an English document it still means "her language rendered into English", byte-for-byte the old path. In a flipped document it means the mirror image: an English sentence she dropped into her Portuguese, rendered into Portuguese. The naive symmetry — swap the two halves — is a bug, because `readsAsEnglish` is deliberately a low bar (Latin letters, not swamped by another script) that *every Portuguese sentence also clears*, so it would have labelled every genuine Portuguese correction a translation. The flipped direction therefore uses `sentenceLang` from doclang.go instead, where English has its own marker list and has to out-evidence the pair language to win. `reconcilePending` takes the verdict alongside `pairLang` to ask the question the right way round. +6. [x] **The tap-through stops assuming its direction, and the whole observable change is a call that no longer happens.** `/suggestions/{id}/translate` now recovers the explanation's own language by re-running `targetFor` over the same three pieces of state the card was written under, and renders into whichever half the explanation is not already in. For every non-skipped case that is still the pair language, which is why nothing visible moved for existing accounts. The case that moved is the Portuguese writer on a Portuguese document: her explanation already arrived in Portuguese, so the endpoint answers `""` with no model call at all, and the client's existing `res.translation.trim() || explanation` fallback seeds the bubble with the explanation itself. The old code would have sent Portuguese to the model to be turned into Portuguese. + - **What it deliberately does not do** is render that explanation into English instead, on the grounds that English is technically "the other half". An unasked-for English rendering of an explanation she can already read is not a seed, it is noise; the language she is practising stays available through Ask Petal, which is where she can ask for it. + - **A card carries no language of its own**, so a row written before this phase — or on a document whose verdict has since flipped — is read as whatever the rule says today. The alternative is a language column on every suggestion row, and the cost of being wrong is one bubble seeded in the language it was already in. - **`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. - **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. **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. - `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. @@ -470,6 +473,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 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. - 2026-07-28: **Phase 25 — the es pair, and a plan that had quietly chosen the wrong Spanish** (user asked where Spanish support had gone, then "yes" to starting the phase; scope chosen with the user: **Latin American neutral**, quorum review, code only). The starting point was a misreading worth recording: the plan *reads* as though Spanish shipped, because the DreamDict rebuild, the LLM language entry, the L1 rule gating and the TTS env-discovery are all `[x]` — every piece of groundwork was done and the pair itself had never been built. `shippedPairs` was the honest answer all along: the server had been refusing `es` on purpose. **The regional question was the phase.** pt-PT's was forced by packaging and fr's turned out not to exist; es had a real choice with no default, and once the user chose Latin American, the plan's own two concrete decisions were both wrong. It warned that `hunspell-es` is "packaged per country — check what `es_ES` actually is": it ships twenty country codes and **every one is a symlink to one pan-Hispanic file**, so the trap was not there. And it named **`es_ES-davefx-medium`** for the voice, which *is* the trap — six of Piper's nine Spanish voices are peninsular, so the obvious pick would have read Latin American copy in a Castilian accent, the pt-PT mistake arriving through a different door. `es_MX-ald-medium` instead. **Then the user asked "should we pick a different Spanish dictionary?" and the answer was yes** — the phase had shipped the wrong one and written a confident justification for it. Debian's `hunspell-es` symlinks twenty country codes to one file, which reads as pan-Hispanic; RLA actually publishes twenty-four builds per release, one per country **plus a generic `es` that is the union**, and Debian ships **peninsular `es_ES`**. The 58,622-form difference is essentially **voseo**: under the first build, *vení* and *tenés* — the ordinary present tense of Argentina, Uruguay, Paraguay and much of Central America — were underlined as misspellings, and this document called that a known gap handled on principle. **What makes it worth writing down is that the MUST_ACCEPT list was designed to catch exactly this and could not**: it asserted the pan-Hispanic *vocabulary*, and every RLA variant carries the full pan-Hispanic vocabulary — only the paradigms are localised — so it was satisfiable by all twenty-four. The `REP` table cited as the corroborating witness (yeísmo, seseo) is likewise shared by every build. Two independent-looking proofs, neither of which could distinguish anything, agreeing with each other. The profile now demands **voseo** (rejects es_ES and Debian), **vosotros** (rejects es_MX) and **another region's everyday words** — *arepa*, *chévere*, *bacán* (rejects es_AR, which has both paradigms and would otherwise pass); all four neighbours were run through it and confirmed refused. Shipping the union is the same call fr made between *coût* and *cout*: the dictionary's only power is to underline, so it holds every variety, while the *copy* picks a register because speaking requires one. 717,640 forms, 1.74 MB gzipped, **762 ms / 97 MB** in a real nspell, and **fr and pt-PT rebuild byte-identical** from their own upstream debs. **The quorum review earned its place twice**: four models, ≥2-of-4, 5 of 27 findings applied — one of which caught the pack's bedtime proverb being *Qui dort dîne* calqued into Spanish, English gloss and all, which is exactly the "a pack is not a translation of another pack" rule the fr header states and I had broken while writing it. And one below-threshold finding (a missing `¡` on an exclamative, seen by 1 of 4 because an absent *opening* mark has no closing `!` to look wrong against) was applied anyway and **turned into an assertion**: the suite now rejects any native line that closes `?`/`!` without opening one. That is Phase 24's lesson one level up — what a review finds once, a test should find every time. go build/vet/test, tsc, vite, **vitest 251/251**. ⚠️ **Not deployed, not seen in a browser, not read by a native speaker, and no es account exists** — all four accounts' worth of Spanish experience is still hypothetical, and the pack says so in its own header. diff --git a/internal/suggestions/doclang_test.go b/internal/suggestions/doclang_test.go index ab32c9a..d40075d 100644 --- a/internal/suggestions/doclang_test.go +++ b/internal/suggestions/doclang_test.go @@ -1,6 +1,7 @@ package suggestions import ( + "encoding/json" "net/http" "path/filepath" "strings" @@ -259,3 +260,136 @@ func TestLanguageFlipReopensCheckedSentences(t *testing.T) { t.Fatalf("the already-checked sentence was not re-opened by the flip:\n%s", client.lastPrompt) } } + +// The translate card, pointed the other way. She is writing her journal in +// Portuguese and drops in the one English sentence she knows; Petal renders it +// into Portuguese, and that card is a translation — not a correction to prose +// that was never wrong. +func TestEnglishSpanBecomesATranslateCardInAPortugueseDocument(t *testing.T) { + const english = "I want to say this but I don't know how to say it." + // The model volunteers "clarity", as it did for the zh case. Not consulted. + client := &stubClient{response: `{"suggestions":[ + {"original":"` + english + `","replacement":"Eu quero dizer isto mas não sei como o dizer.","explanation":"Aqui está em português.","type":"clarity"} + ]}`} + srv, docID, _ := newDirectedServer(t, client, "pt-PT", auth.DirectionLearningEn, ptDocument+" "+english) + + var out []db.Suggestion + rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "") + if rec.Code != http.StatusOK { + t.Fatalf("check: code=%d body=%s", rec.Code, rec.Body) + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + if len(out) != 1 { + t.Fatalf("want 1 card, got %d: %+v", len(out), out) + } + if out[0].Type != db.SuggestionTypeTranslate { + t.Fatalf("card type = %q, want %q", out[0].Type, db.SuggestionTypeTranslate) + } +} + +// And the half that keeps it honest: a genuine Portuguese correction in the same +// document stays a correction. Reading the English-document test backwards would +// have called this a translation, because every Portuguese sentence also "reads +// as English" by that test's deliberately low bar. +func TestPortugueseCorrectionKeepsItsTypeInAPortugueseDocument(t *testing.T) { + client := &stubClient{response: `{"suggestions":[ + {"original":"Não sei porque isso é tão difícil para mim.","replacement":"Não sei porque isto é tão difícil para mim.","explanation":"Aqui usa-se isto.","type":"grammar"} + ]}`} + srv, docID, _ := newDirectedServer(t, client, "pt-PT", auth.DirectionLearningEn, ptDocument) + + var out []db.Suggestion + rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/check", "") + if rec.Code != http.StatusOK { + t.Fatalf("check: code=%d body=%s", rec.Code, rec.Body) + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + if len(out) != 1 { + t.Fatalf("want 1 card, got %d: %+v", len(out), out) + } + if out[0].Type == db.SuggestionTypeTranslate { + t.Fatal("a Portuguese correction inside a Portuguese document was labelled a translation") + } +} + +// setDocLang writes a document's language verdict directly, so a test of the +// tap-through doesn't have to run a checkpoint through the same stub client to +// get one. +func setDocLang(t *testing.T, h *Handler, docID, lang string) { + t.Helper() + if _, err := h.DB.Exec(`UPDATE documents SET doc_lang = ? WHERE id = ?`, lang, docID); err != nil { + t.Fatalf("set doc_lang: %v", err) + } +} + +// seedExplanation files one card carrying a given explanation and returns its +// id — the shape the translate tap-through needs, where only the explanation and +// the document it hangs off matter. +func seedExplanation(t *testing.T, h *Handler, docID, explanation string) string { + t.Helper() + var sugID string + if err := h.DB.QueryRow( + `INSERT INTO suggestions (doc_id, original, replacement, explanation, type, from_pos, to_pos) + VALUES (?, ?, ?, ?, ?, 0, 5) RETURNING id`, + docID, "isso", "isto", explanation, "grammar", + ).Scan(&sugID); err != nil { + t.Fatalf("seed suggestion: %v", err) + } + return sugID +} + +// The tap-through has to read the same decision the card was written under. On a +// Portuguese document by a Portuguese writer the explanation already arrived in +// Portuguese, and the old endpoint would have sent it to the model to be +// rendered into Portuguese again. +func TestTranslateSkipsWhenTheExplanationIsAlreadyHers(t *testing.T) { + client := &stubClient{response: "Não devia ser chamado."} + srv, docID, h := newDirectedServer(t, client, "pt-PT", auth.DirectionLearningEn, ptDocument) + setDocLang(t, h, docID, docLangPair) + sugID := seedExplanation(t, h, docID, "Aqui usa-se isto.") + + rec := do(t, srv, http.MethodPost, "/suggestions/"+sugID+"/translate", "") + if rec.Code != http.StatusOK { + t.Fatalf("translate: code=%d body=%s", rec.Code, rec.Body) + } + var out translateResponse + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + if out.Translation != "" { + t.Fatalf("translation = %q, want empty: the bubble seeds from the explanation itself", out.Translation) + } + if client.calls != 0 { + t.Fatal("the model was asked to render Portuguese into Portuguese") + } +} + +// The learner travelling the other way is the case that proves the endpoint +// derives its destination rather than skipping whenever a document is flipped: a +// native English speaker learning Chinese, writing Chinese, gets her +// explanations in English — and the tap still has somewhere to go. +func TestTranslateStillRendersForALearnersEnglishExplanation(t *testing.T) { + const zhDocument = "今天天气很好。我早上去公园散步。下午我在家里写作业。晚上我和朋友一起吃饭。" + client := &stubClient{response: "这里应该用这个。"} + srv, docID, h := newDirectedServer(t, client, "zh", auth.DirectionLearningPair, zhDocument) + setDocLang(t, h, docID, docLangPair) + sugID := seedExplanation(t, h, docID, "This measure word doesn't fit here.") + + rec := do(t, srv, http.MethodPost, "/suggestions/"+sugID+"/translate", "") + if rec.Code != http.StatusOK { + t.Fatalf("translate: code=%d body=%s", rec.Code, rec.Body) + } + var out translateResponse + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v", err) + } + if out.Translation == "" { + t.Fatal("a learner's English explanation was left untranslated") + } + if !strings.Contains(client.lastPrompt, "Simplified Chinese") { + t.Fatalf("translate didn't render into the pair language:\n%s", client.lastPrompt) + } +} diff --git a/internal/suggestions/handlers.go b/internal/suggestions/handlers.go index 673922e..d91ff8c 100644 --- a/internal/suggestions/handlers.go +++ b/internal/suggestions/handlers.go @@ -317,10 +317,22 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R return } + // What language is this document in, and so what language should its cards be + // written in? Computed from the whole content_text — never from `askText`, + // which on a chunked pass is only the sentences that changed, and would put an + // English card in a Portuguese journal the moment she edits its one English + // line. + // + // Decided before the empty-document exit so every reconcile below is told the + // same verdict. An emptied document has nothing to go on and holds whatever it + // said last (see documentLang), which is what keeps a Portuguese journal + // Portuguese while she clears it to start the entry again. + docLang := documentLang(contentText, pairLang, prevLang) + // Nothing to analyze on an empty document — skip the LLM round-trip. The // family's rows go with the text they were about. if strings.TrimSpace(contentText) == "" { - if err := h.reconcilePending(docID, contentText, pairLang, nil, scope, nil, nil, false); err != nil { + if err := h.reconcilePending(docID, contentText, pairLang, docLang, nil, scope, nil, nil, false); err != nil { httputil.ServerError(w, err) return } @@ -333,12 +345,6 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R return } - // What language is this document in, and so what language should its cards be - // written in? Computed from the whole content_text — never from `askText`, - // which on a chunked pass is only the sentences that changed, and would put an - // English card in a Portuguese journal the moment she edits its one English - // line. - docLang := documentLang(contentText, pairLang, prevLang) if docLang != normalizeDocLang(prevLang) { if _, err := h.DB.Exec( `UPDATE documents SET doc_lang = ? WHERE id = ? AND user_id = ?`, @@ -376,7 +382,7 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R if len(changed) == 0 { // Every sentence has already been read. Drop the rows whose sentence is // gone, keep the rest exactly as they are, and answer immediately. - if err := h.reconcilePending(docID, contentText, pairLang, nil, scope, chunks, nil, false); err != nil { + if err := h.reconcilePending(docID, contentText, pairLang, docLang, nil, scope, chunks, nil, false); err != nil { httputil.ServerError(w, err) return } @@ -421,7 +427,7 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R // A whole-document pass re-read everything, so every one of its rows is up for // re-proposal; a chunked pass only puts the sentences it asked about in play. - if err := h.reconcilePending(docID, contentText, pairLang, raw, scope, chunks, fresh, !scope.chunked); err != nil { + if err := h.reconcilePending(docID, contentText, pairLang, docLang, raw, scope, chunks, fresh, !scope.chunked); err != nil { httputil.ServerError(w, err) return } diff --git a/internal/suggestions/language.go b/internal/suggestions/language.go index 6ae0e60..0f3d8bd 100644 --- a/internal/suggestions/language.go +++ b/internal/suggestions/language.go @@ -28,16 +28,35 @@ import ( // common words a sentence in that language can hardly avoid and an English // sentence has no reason to contain. -// isTranslation reports whether this edit is her own language rendered into -// English, rather than a correction to her English. Both halves must hold: the -// quoted span reads as the pair language, and what Petal offers back reads as -// English. The second half matters — a Chinese span rewritten into different -// Chinese is something else entirely, and Petal has no business calling it a -// translation. -func isTranslation(original, replacement, pairLang string) bool { +// isTranslation reports whether this edit is a rendering of one language into +// the other, rather than a correction. Both halves must hold: the quoted span +// reads as one language, and what Petal offers back reads as the other. The +// second half matters — a Chinese span rewritten into different Chinese is +// something else entirely, and Petal has no business calling it a translation. +// +// Which way it points follows the document (Phase 28). In an English document +// the translate card is her language rendered into English — she reached for a +// sentence she couldn't say yet, and Petal said it for her. In a document she +// wrote in her own language the useful card is the mirror image: an English +// sentence she dropped into her Portuguese, rendered into Portuguese. Asking the +// English-document question there would label nothing, and the card would file +// as a correction to prose that was never wrong. +// +// The flipped direction cannot be the same test read backwards. `readsAsEnglish` +// is a low bar on purpose — Latin letters, not swamped by another script — which +// every Portuguese sentence also clears, so using it on the *original* would +// call every genuine Portuguese correction a translation. The flipped test +// instead uses the sentence-level vote from doclang.go, where English has its +// own marker list and has to out-evidence the pair language to win. +func isTranslation(original, replacement, pairLang, docLang string) bool { if strings.TrimSpace(original) == "" || strings.TrimSpace(replacement) == "" { return false } + if normalizeDocLang(docLang) == docLangPair { + p := normalizePairLang(pairLang) + return sentenceLang(original, p) == docLangEnglish && + sentenceLang(replacement, p) == docLangPair + } return readsAsPairLang(original, pairLang) && readsAsEnglish(replacement) } diff --git a/internal/suggestions/language_test.go b/internal/suggestions/language_test.go index efe0b61..8a08a88 100644 --- a/internal/suggestions/language_test.go +++ b/internal/suggestions/language_test.go @@ -3,6 +3,10 @@ package suggestions import "testing" // The flagship case, and the ones next to it that must NOT become translations. +// +// Every case here is an ENGLISH document — the path every account was on before +// Phase 28 — so `docLang` is left at "". The mirror image lives in +// TestIsTranslationInAPairLanguageDocument below. func TestIsTranslation(t *testing.T) { cases := []struct { name string @@ -134,8 +138,93 @@ func TestIsTranslation(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - if got := isTranslation(c.original, c.replacement, c.pairLang); got != c.want { - t.Errorf("isTranslation(%q, %q, %q) = %v, want %v", + if got := isTranslation(c.original, c.replacement, c.pairLang, ""); got != c.want { + t.Errorf("isTranslation(%q, %q, %q, en) = %v, want %v", + c.original, c.replacement, c.pairLang, got, c.want) + } + }) + } +} + +// The mirror image (Phase 28): in a document she wrote in her own language, the +// translate card is the English sentence rendered into her language — and the +// English-document question, asked here, would label nothing. +// +// The case this file exists to pin is the third one: a genuine Portuguese +// correction inside a Portuguese document. Reading the English-document test +// backwards would call it a translation, because `readsAsEnglish` is a low bar +// that Portuguese clears too. It has to stay a correction. +func TestIsTranslationInAPairLanguageDocument(t *testing.T) { + cases := []struct { + name string + original string + replacement string + pairLang string + want bool + }{ + { + name: "English sentence rendered into Portuguese", + original: "I want to say this but I don't know how to say it.", + replacement: "Eu quero dizer isso mas não sei como o dizer.", + pairLang: "pt-PT", + want: true, + }, + { + name: "English sentence rendered into Chinese", + original: "I don't know how to say this in Chinese.", + replacement: "我不知道这句话用中文怎么说。", + pairLang: "zh", + want: true, + }, + { + // The one that matters. Portuguese in, Portuguese out, inside a + // Portuguese document: a correction, and nothing else. + name: "Portuguese corrected as Portuguese", + original: "Eu quero dizer isso mas não sei como.", + replacement: "Eu quero dizer isto mas não sei como.", + pairLang: "pt-PT", + want: false, + }, + { + // And its Chinese twin, which the script test already caught. + name: "Chinese corrected as Chinese", + original: "我想说这句话", + replacement: "我要说这句话", + pairLang: "zh", + want: false, + }, + { + // The old direction, asked in the new document. She quoted English in + // her Portuguese and Petal rendered it into Portuguese — which IS a + // translation, and is the case above. This is its reverse: Portuguese + // out of an English document that isn't one. No label. + name: "Portuguese rendered into English is not this document's translation", + original: "Eu quero dizer isso mas não sei como.", + replacement: "I want to say this but I don't know how.", + pairLang: "pt-PT", + want: false, + }, + { + // English prose without enough evidence to vote. Silence, not a guess. + name: "too short to read as English", + original: "OK", + replacement: "Está bem, muito obrigado.", + pairLang: "pt-PT", + want: false, + }, + { + name: "unknown pair language declines in both directions", + original: "I don't know how to say that.", + replacement: "Ich weiß nicht wie man das sagt.", + pairLang: "de", + want: false, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := isTranslation(c.original, c.replacement, c.pairLang, docLangPair); got != c.want { + t.Errorf("isTranslation(%q, %q, %q, pair) = %v, want %v", c.original, c.replacement, c.pairLang, got, c.want) } }) @@ -151,8 +240,8 @@ func TestNormalizePairLang(t *testing.T) { "fr": "fr", "fr-FR": "fr", "es": "es", "es-ES": "es", " zh ": "zh", - "": "", - "de": "de", + "": "", + "de": "de", } { if got := normalizePairLang(in); got != want { t.Errorf("normalizePairLang(%q) = %q, want %q", in, got, want) diff --git a/internal/suggestions/reconcile.go b/internal/suggestions/reconcile.go index b2c499b..94499bf 100644 --- a/internal/suggestions/reconcile.go +++ b/internal/suggestions/reconcile.go @@ -131,10 +131,12 @@ func reposition(tx *sql.Tx, row pendingRow, from, to int, chunkHash string) erro // collocation coach — where every row is up for re-proposal because the model // just re-read everything. // -// `pairLang` is the writer's own language, needed only to type a finding that -// turns out to be her language rendered into English (see language.go). +// `pairLang` is the writer's own language and `docLang` this document's language +// verdict; between them they type a finding that turns out to be one language +// rendered into the other, in whichever direction this document makes useful +// (see language.go). func (h *Handler) reconcilePending( - docID, contentText, pairLang string, + docID, contentText, pairLang, docLang string, raw []llm.RawSuggestion, scope pendingScope, chunks, fresh []chunk, @@ -235,7 +237,7 @@ func (h *Handler) reconcilePending( typ := scope.forceType if typ == "" { typ = normalizeType(s.Type) - if isTranslation(s.Original, s.Replacement, pairLang) { + if isTranslation(s.Original, s.Replacement, pairLang, docLang) { typ = db.SuggestionTypeTranslate } } diff --git a/internal/suggestions/translate.go b/internal/suggestions/translate.go index 6b35779..a3efca3 100644 --- a/internal/suggestions/translate.go +++ b/internal/suggestions/translate.go @@ -17,23 +17,37 @@ type translateResponse struct { Translation string `json:"translation"` } -// translate renders a suggestion's English explanation into Simplified Chinese -// for the Ask Petal bubble, so the ESL reader sees the "why" in her first -// language instead of a second copy of the same English text. The explanation is -// loaded server-side from the suggestion id (scoped to the local user) and never -// trusted from the client, mirroring chat (spec Note #10). +// translate renders a suggestion's explanation into the other half of the +// writer's pair for the Ask Petal bubble, so she sees the "why" in the language +// she reads most easily instead of a second copy of the same text. The +// explanation is loaded server-side from the suggestion id (scoped to the +// caller) and never trusted from the client, mirroring chat (spec Note #10). +// +// Which language it renders into cannot be assumed (Phase 28). Before that phase +// every explanation was English and every rendering went into her language, so +// "the pair language" was a safe constant. Now the explanation's language is a +// decision — `targetFor`, from the document's verdict and her direction — and +// this endpoint has to read the same decision back, or it round-trips Portuguese +// into Portuguese and calls it a translation. +// +// So: render into whichever half the explanation is NOT already in, and when the +// explanation already arrived in the language this bubble exists to reach her +// in, skip the model call and answer "". The client seeds the bubble with the +// explanation itself when the translation comes back empty, which is exactly +// right — there is nothing to add. func (h *Handler) translate(w http.ResponseWriter, r *http.Request) { sugID := chi.URLParam(r, "id") - var explanation, pairLang string + var explanation, pairLang, direction, docLang string err := h.DB.QueryRow( - `SELECT s.explanation, COALESCE(u.pair_lang, '') + `SELECT s.explanation, COALESCE(u.pair_lang, ''), + COALESCE(u.direction, ''), d.doc_lang FROM suggestions s JOIN documents d ON d.id = s.doc_id JOIN users u ON u.id = d.user_id WHERE s.id = ? AND d.user_id = ?`, sugID, auth.UserID(r.Context()), - ).Scan(&explanation, &pairLang) + ).Scan(&explanation, &pairLang, &direction, &docLang) if errors.Is(err, sql.ErrNoRows) { httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found") return @@ -49,7 +63,21 @@ func (h *Handler) translate(w http.ResponseWriter, r *http.Request) { return } - out, err := llm.RunTranslate(r.Context(), h.Client, explanation, llm.LangFor(pairLang)) + // The explanation's own language, recovered from the same rule that chose it + // when the card was written. A card written before this phase — or on a + // document whose verdict has since flipped — is read as whatever the rule says + // today; the alternative is a language column on every suggestion row, and the + // cost of being wrong is one bubble seeded in the language it was already in. + target := targetFor(pairLang, direction, docLang) + if target.Explain.Code == target.Pair.Code { + // Already in her language. The other half is English — the language she is + // practising — and an unasked-for English rendering of an explanation she + // can already read is not a seed, it's noise. + httputil.WriteJSON(w, http.StatusOK, translateResponse{Translation: ""}) + return + } + + out, err := llm.RunTranslate(r.Context(), h.Client, explanation, target.Pair) if err != nil { httputil.UpstreamError(w, "translate", err) return