Phase 19: the copy stops being hardcoded Mandarin

Every `中文 · English` string moves out of ~29 components into
web/src/i18n: one Pack type, a verbatim zh pack, and two ways to read
it — usePack() for components, pack() for the modules that build a line
when something happens rather than when something renders.

Anything with a value in it is a function on the pack rather than a
template at the call site, English pluralisation included: word order
isn't universal, and a pack author has to be able to move the number.
The roster constants (tones, rewrite styles, export formats, companions)
keep only value + emoji, so a label can't drift from its key.

On the server, internal/llm/lang.go replaces "Simplified Chinese" in the
three prompts that actually name her language. pt-PT is spelled
"European Portuguese (pt-PT, never Brazilian Portuguese)" in the prompt
itself, and each Lang carries her word for "why" so the tutor prompt
still recognises the question when she asks it her way.

pair_lang reaches the model through the row-scoped query each handler
already ran — the one that proves she owns the document — rather than a
second lookup that could disagree with it.

Also records Phase 18's deploy: migration 0011 rehearsed against a copy
of the live VPS database, then applied for real.
This commit is contained in:
prosolis
2026-07-27 08:37:05 -07:00
parent 30d5e691c9
commit 336cae93e0
45 changed files with 1331 additions and 371 deletions
+6 -3
View File
@@ -40,14 +40,17 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
original, replacement, explanation, typ string
fromPos int
contentText string
pairLang string
)
err := h.DB.QueryRow(
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text,
COALESCE(u.pair_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(&original, &replacement, &explanation, &typ, &fromPos, &contentText)
).Scan(&original, &replacement, &explanation, &typ, &fromPos, &contentText, &pairLang)
if errors.Is(err, sql.ErrNoRows) {
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
return
@@ -58,7 +61,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
}
paragraph := surroundingParagraph(contentText, fromPos)
systemPrompt := llm.AskPetalSystemPrompt(original, replacement, typ, explanation, paragraph)
systemPrompt := llm.AskPetalSystemPrompt(original, replacement, typ, explanation, paragraph, llm.LangFor(pairLang))
// SSE requires an unbuffered, flushable writer. chi's middleware writers pass
// Flush through; bail with a plain error if somehow they don't.
+16 -7
View File
@@ -194,9 +194,12 @@ func (h *Handler) collocation(w http.ResponseWriter, r *http.Request) {
}
// pass is the signature shared by the grammar checkpoint and the voice pass:
// given the document text and the document's tone it returns the model's raw
// suggestions. The voice pass ignores tone (see llm.RunVoice).
type pass func(ctx context.Context, client llm.LLMClient, contentText, tone string) ([]llm.RawSuggestion, error)
// given the document text, the document's tone and the writer's pair language it
// returns the model's raw suggestions. The voice pass ignores both extras (see
// llm.RunVoice) and the checkpoint ignores the language — only the collocation
// coach writes a word of it — but one signature keeps runPass free of special
// cases.
type pass func(ctx context.Context, client llm.LLMClient, contentText, tone string, lang llm.Lang) ([]llm.RawSuggestion, error)
// runPass is the shared body for both LLM passes. It loads the document text,
// enforces the pass's per-document rate limit, runs the model, swaps in the
@@ -206,11 +209,17 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
docID := chi.URLParam(r, "id")
userID := auth.UserID(r.Context())
var contentText, tone string
// The writer's pair language rides along with the document rather than in a
// second query: it is read from the same row-scoped lookup that already
// proves she owns this document.
var contentText, tone, pairLang string
err := h.DB.QueryRow(
`SELECT content_text, tone FROM documents WHERE id = ? AND user_id = ?`,
`SELECT d.content_text, d.tone, COALESCE(u.pair_lang, '')
FROM documents d
JOIN users u ON u.id = d.user_id
WHERE d.id = ? AND d.user_id = ?`,
docID, userID,
).Scan(&contentText, &tone)
).Scan(&contentText, &tone, &pairLang)
if errors.Is(err, sql.ErrNoRows) {
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
return
@@ -239,7 +248,7 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
return
}
raw, err := run(r.Context(), h.Client, contentText, tone)
raw, err := run(r.Context(), h.Client, contentText, tone, llm.LangFor(pairLang))
if err != nil {
// Allow ran before the model call, so a failed pass would otherwise hold
// the per-document slot for the full interval — stranding the frontend's
+109
View File
@@ -0,0 +1,109 @@
package suggestions
import (
"net/http"
"path/filepath"
"strings"
"testing"
"github.com/go-chi/chi/v5"
"gitea.parodia.dev/drwily/petal/internal/auth"
"gitea.parodia.dev/drwily/petal/internal/db"
"gitea.parodia.dev/drwily/petal/internal/llm"
)
// The langpack decides what Petal says in the browser; users.pair_lang has to
// decide what the *model* says too, or a pt-PT writer gets a Mandarin gloss on
// an otherwise Portuguese screen. These tests follow the value from the column
// to the system prompt for each pass that names a language.
//
// This is the same failure mode the standing isolation rule guards against: the
// column is read in a query the handler already ran, so nothing fails loudly if
// the join is dropped — the prompt just quietly reverts to Mandarin.
// newPairServer seeds one writer on the given pair with a document of her own.
func newPairServer(t *testing.T, client llm.LLMClient, pairLang string) (http.Handler, string, *db.DB) {
t.Helper()
database, err := db.Open(filepath.Join(t.TempDir(), "pair.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { database.Close() })
const userID = "writer-pt"
if _, err := database.Exec(
`INSERT INTO users (id, email, display_name, pair_lang) VALUES (?, ?, ?, ?)`,
userID, "w@example.com", "Writer", pairLang,
); err != nil {
t.Fatalf("seed user: %v", err)
}
var docID string
if err := database.QueryRow(
`INSERT INTO documents (user_id, content_text) VALUES (?, ?) RETURNING id`,
userID, "The rain was strong yesterday.",
).Scan(&docID); err != nil {
t.Fatalf("seed doc: %v", err)
}
h := New(database, client)
r := chi.NewRouter()
r.Route("/docs", func(dr chi.Router) { h.RegisterDocRoutes(dr) })
r.Mount("/suggestions", h.Routes())
return auth.Middleware(auth.StaticResolver(userID))(r), docID, database
}
func TestCollocationPromptUsesTheWritersPair(t *testing.T) {
client := &recordingClient{response: `{"suggestions":[]}`}
srv, docID, _ := newPairServer(t, client, "pt-PT")
rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/collocation", "")
if rec.Code != http.StatusOK {
t.Fatalf("collocation: code=%d body=%s", rec.Code, rec.Body)
}
system := client.last.Messages[0].Content
if !strings.Contains(system, "European Portuguese") {
t.Fatalf("collocation prompt ignored pair_lang:\n%s", system)
}
if strings.Contains(system, "Simplified Chinese") {
t.Fatalf("collocation prompt fell back to Mandarin:\n%s", system)
}
}
func TestTranslatePromptUsesTheWritersPair(t *testing.T) {
client := &recordingClient{response: "Chove muito."}
srv, docID, database := newPairServer(t, client, "pt-PT")
var sugID string
if err := database.QueryRow(
`INSERT INTO suggestions (doc_id, original, replacement, explanation, type, from_pos, to_pos)
VALUES (?, ?, ?, ?, ?, 0, 5) RETURNING id`,
docID, "strong rain", "heavy rain", "Natives usually say heavy rain.", "collocation",
).Scan(&sugID); err != nil {
t.Fatalf("seed suggestion: %v", err)
}
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)
}
system := client.last.Messages[0].Content
if !strings.Contains(system, "European Portuguese") || strings.Contains(system, "Chinese") {
t.Fatalf("translate prompt ignored pair_lang:\n%s", system)
}
}
// A writer whose column still holds the default — every account today — must be
// answered exactly as before.
func TestDefaultPairIsUnchanged(t *testing.T) {
client := &recordingClient{response: `{"suggestions":[]}`}
srv, docID, _ := newPairServer(t, client, "zh")
if rec := do(t, srv, http.MethodPost, "/docs/"+docID+"/collocation", ""); rec.Code != http.StatusOK {
t.Fatalf("collocation: code=%d body=%s", rec.Code, rec.Body)
}
if system := client.last.Messages[0].Content; !strings.Contains(system, "Simplified Chinese (Mandarin) gloss") {
t.Fatalf("zh writer no longer gets a Mandarin gloss:\n%s", system)
}
}
+5 -4
View File
@@ -25,14 +25,15 @@ type translateResponse struct {
func (h *Handler) translate(w http.ResponseWriter, r *http.Request) {
sugID := chi.URLParam(r, "id")
var explanation string
var explanation, pairLang string
err := h.DB.QueryRow(
`SELECT s.explanation
`SELECT s.explanation, COALESCE(u.pair_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)
).Scan(&explanation, &pairLang)
if errors.Is(err, sql.ErrNoRows) {
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
return
@@ -48,7 +49,7 @@ func (h *Handler) translate(w http.ResponseWriter, r *http.Request) {
return
}
out, err := llm.RunTranslate(r.Context(), h.Client, explanation)
out, err := llm.RunTranslate(r.Context(), h.Client, explanation, llm.LangFor(pairLang))
if err != nil {
httputil.ErrorJSON(w, http.StatusBadGateway, "translate failed: "+err.Error())
return