Code-review follow-ups: httputil, validation caps, a11y

Backend:
- Extract shared internal/httputil (WriteJSON/ErrorJSON/BadRequest/
  ServerError); drop the triple-duplicated helpers in docs, suggestions,
  vocab. ServerError now logs the real error and returns a generic 500 so
  raw DB/internal errors never reach the client.
- vocab capture: validate doc_id ownership (blank -> none, unknown -> 400
  instead of a leaked FK 500); rune-safe clamp word/gloss/definition/
  phonetic/example.
- vocab review(): wrap the read-modify-write in a transaction (TOCTOU).
- /api request-size cap via MaxBytesReader middleware (2 MiB), exempting
  /api/images (own 10 MiB limit).

Frontend:
- StatusBar: drive the checking/voicing/collocating indicators from one
  array; llmDown uses !anyBusy.
- Slide-overs: new useFocusTrap hook (focus-in, Tab trap, focus-restore)
  on GardenPanel + HistoryPanel, both role=dialog/aria-modal/aria-label.
- speech.ts: export stopSpeech(); GardenPanel cancels audio on unmount.

Tests: add doc_id-validation and field-clamp coverage; full suite green.

Claude-Session: https://claude.ai/code/session_016Yr6jELuRc7hyzYLccQKZd
This commit is contained in:
prosolis
2026-06-26 16:59:23 -07:00
parent 4161830da6
commit 8c6bc1604b
18 changed files with 436 additions and 204 deletions

View File

@@ -10,6 +10,7 @@ import (
"github.com/go-chi/chi/v5"
"gitea.parodia.dev/drwily/petal/internal/db"
"gitea.parodia.dev/drwily/petal/internal/httputil"
"gitea.parodia.dev/drwily/petal/internal/llm"
)
@@ -29,7 +30,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
var body chatRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
errorJSON(w, http.StatusBadRequest, "invalid request body")
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid request body")
return
}
@@ -37,8 +38,8 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
// scoped to the local user so a stray id can't read another user's doc.
var (
original, replacement, explanation, typ string
fromPos int
contentText string
fromPos int
contentText string
)
err := h.DB.QueryRow(
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text
@@ -48,11 +49,11 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
sugID, db.LocalUserID,
).Scan(&original, &replacement, &explanation, &typ, &fromPos, &contentText)
if errors.Is(err, sql.ErrNoRows) {
errorJSON(w, http.StatusNotFound, "suggestion not found")
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
return
}
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
@@ -63,7 +64,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
// Flush through; bail with a plain error if somehow they don't.
flusher, ok := w.(http.Flusher)
if !ok {
serverError(w, errors.New("streaming unsupported"))
httputil.ServerError(w, errors.New("streaming unsupported"))
return
}
@@ -71,7 +72,7 @@ func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
if err != nil {
// The stream never opened (e.g. LLM unreachable) — a normal JSON error is
// still appropriate since we haven't written SSE headers yet.
errorJSON(w, http.StatusBadGateway, "chat failed: "+err.Error())
httputil.ErrorJSON(w, http.StatusBadGateway, "chat failed: "+err.Error())
return
}

View File

@@ -8,7 +8,6 @@ package suggestions
import (
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"strings"
@@ -16,6 +15,7 @@ import (
"github.com/go-chi/chi/v5"
"gitea.parodia.dev/drwily/petal/internal/db"
"gitea.parodia.dev/drwily/petal/internal/httputil"
"gitea.parodia.dev/drwily/petal/internal/llm"
)
@@ -99,17 +99,17 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
docID, db.LocalUserID,
).Scan(&contentText, &tone)
if errors.Is(err, sql.ErrNoRows) {
errorJSON(w, http.StatusNotFound, "document not found")
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
// Nothing to analyze on an empty document — skip the LLM round-trip.
if strings.TrimSpace(contentText) == "" {
writeJSON(w, http.StatusOK, []db.Suggestion{})
httputil.WriteJSON(w, http.StatusOK, []db.Suggestion{})
return
}
@@ -119,10 +119,10 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
// error, so the frontend keeps showing current suggestions.
existing, err := h.fetchPending(docID)
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
writeJSON(w, http.StatusOK, existing)
httputil.WriteJSON(w, http.StatusOK, existing)
return
}
@@ -132,12 +132,12 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
// the per-document slot for the full interval — stranding the frontend's
// auto-retry on the throttle path. Release it so a retry can re-run.
limiter.Release(docID, slotAt)
errorJSON(w, http.StatusBadGateway, "llm pass failed: "+err.Error())
httputil.ErrorJSON(w, http.StatusBadGateway, "llm pass failed: "+err.Error())
return
}
if err := h.replacePending(docID, contentText, raw, scope); err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
@@ -146,10 +146,10 @@ func (h *Handler) runPass(w http.ResponseWriter, r *http.Request, limiter *llm.R
// throttle path above stays consistent with the success path.
out, err := h.fetchPending(docID)
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
writeJSON(w, http.StatusOK, out)
httputil.WriteJSON(w, http.StatusOK, out)
}
// pendingScope describes how one LLM pass touches the shared suggestions table:
@@ -261,10 +261,10 @@ func suggestionKey(original, replacement string) string {
func (h *Handler) listForDoc(w http.ResponseWriter, r *http.Request) {
out, err := h.fetchPending(chi.URLParam(r, "id"))
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
writeJSON(w, http.StatusOK, out)
httputil.WriteJSON(w, http.StatusOK, out)
}
func (h *Handler) fetchPending(docID string) ([]db.Suggestion, error) {
@@ -310,11 +310,11 @@ func (h *Handler) setStatus(w http.ResponseWriter, r *http.Request, status strin
status, chi.URLParam(r, "id"), db.SuggestionStatusPending,
)
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
if n, _ := res.RowsAffected(); n == 0 {
errorJSON(w, http.StatusNotFound, "pending suggestion not found")
httputil.ErrorJSON(w, http.StatusNotFound, "pending suggestion not found")
return
}
w.WriteHeader(http.StatusNoContent)
@@ -341,19 +341,3 @@ func normalizeType(t string) string {
return db.SuggestionTypeGrammar
}
}
// --- response helpers -------------------------------------------------------
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func errorJSON(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
func serverError(w http.ResponseWriter, err error) {
errorJSON(w, http.StatusInternalServerError, err.Error())
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/go-chi/chi/v5"
"gitea.parodia.dev/drwily/petal/internal/db"
"gitea.parodia.dev/drwily/petal/internal/httputil"
"gitea.parodia.dev/drwily/petal/internal/llm"
)
@@ -36,17 +37,17 @@ func (h *Handler) rewrite(w http.ResponseWriter, r *http.Request) {
var body rewriteRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
errorJSON(w, http.StatusBadRequest, "invalid request body")
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid request body")
return
}
text := strings.TrimSpace(body.Text)
if text == "" {
errorJSON(w, http.StatusBadRequest, "no text to rewrite")
httputil.ErrorJSON(w, http.StatusBadRequest, "no text to rewrite")
return
}
if len([]rune(text)) > llm.RewriteMaxRunes {
errorJSON(w, http.StatusBadRequest, "selection too long to rewrite")
httputil.ErrorJSON(w, http.StatusBadRequest, "selection too long to rewrite")
return
}
@@ -58,19 +59,19 @@ func (h *Handler) rewrite(w http.ResponseWriter, r *http.Request) {
docID, db.LocalUserID,
).Scan(&exists)
if errors.Is(err, sql.ErrNoRows) {
errorJSON(w, http.StatusNotFound, "document not found")
httputil.ErrorJSON(w, http.StatusNotFound, "document not found")
return
}
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
out, err := llm.RunRewrite(r.Context(), h.Client, text, body.Style)
if err != nil {
errorJSON(w, http.StatusBadGateway, "rewrite failed: "+err.Error())
httputil.ErrorJSON(w, http.StatusBadGateway, "rewrite failed: "+err.Error())
return
}
writeJSON(w, http.StatusOK, rewriteResponse{Rewrite: out})
httputil.WriteJSON(w, http.StatusOK, rewriteResponse{Rewrite: out})
}

View File

@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"gitea.parodia.dev/drwily/petal/internal/db"
"gitea.parodia.dev/drwily/petal/internal/httputil"
"gitea.parodia.dev/drwily/petal/internal/llm"
)
@@ -33,25 +34,25 @@ func (h *Handler) translate(w http.ResponseWriter, r *http.Request) {
sugID, db.LocalUserID,
).Scan(&explanation)
if errors.Is(err, sql.ErrNoRows) {
errorJSON(w, http.StatusNotFound, "suggestion not found")
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
return
}
if err != nil {
serverError(w, err)
httputil.ServerError(w, err)
return
}
explanation = strings.TrimSpace(explanation)
if explanation == "" {
writeJSON(w, http.StatusOK, translateResponse{Translation: ""})
httputil.WriteJSON(w, http.StatusOK, translateResponse{Translation: ""})
return
}
out, err := llm.RunTranslate(r.Context(), h.Client, explanation)
if err != nil {
errorJSON(w, http.StatusBadGateway, "translate failed: "+err.Error())
httputil.ErrorJSON(w, http.StatusBadGateway, "translate failed: "+err.Error())
return
}
writeJSON(w, http.StatusOK, translateResponse{Translation: out})
httputil.WriteJSON(w, http.StatusOK, translateResponse{Translation: out})
}