Skip to content

Add owner preferences endpoint (locale/language) - #260

Merged
max-tet merged 10 commits into
mainfrom
feature/clayde/owner-preferences-endpoint
Nov 26, 2026
Merged

max-tet merged 10 commits into
mainfrom
feature/clayde/owner-preferences-endpoint

Conversation

@ClaydeCode

Copy link
Copy Markdown
Contributor

Closes #168.

What

Adds the owner preferences endpoint the web-terminal rewrite (Sundial) needs for i18n:

  • GET /protected/preferences → {"language": "de"} — an extensible object.
  • PUT /protected/preferences with {"language": "de"} → persists it.

The preference lives on the users row (users.language, nullable TEXT, migration 0007), not as one global blob, so it grows into a fuller per-user profile once multi-user lands. The response is an object so fields can be added without breaking clients.

Design decisions (where the issue left room)

  • Unset reads as 200 {"language": null}, not 404. The issue's 404 fallback was scoped to "until this endpoint exists" (older shards). Once the endpoint exists it is a profile object that always exists for a logged-in user. Sundial should treat null exactly like the legacy 404 — fall back to navigator.language/English. Cross-repo coordination: deploy order matters — the shard must not go out ahead of a Sundial that only branches on 404. See the adversarial reviewer note below.
  • language is plain TEXT, shape-validated, not a PG enum. Which UI languages exist is Sundial's concern, not the shard's. Validation accepts a BCP-47-ish lowercased tag (^[a-z]{2,3}(-[a-z0-9]{2,8})*$, capped at 35 chars) so junk/injection stays out of the column, without gatekeeping the set (adding a language needs no shard migration).
  • language is required on PUT (no clear-to-autodetect): the only writer today, the switcher, always picks a concrete language.
  • Extracted the cookie→user resolution shared with the users route into web/protected/session.py (session_user), so the 401/403 failure modes live in one place rather than drifting across two copies.

Verification

  • uv run ruff check . clean.
  • tests/test_preferences.py (14 tests) green; re-ran test_users.py, test_owner_email.py, test_db_snapshot.py, test_settings_endpoint.py (48 tests) green to confirm the session_user refactor and the new column are regression-free.
  • Docs: agents.md updated with the endpoint, the null/404 contract, and the TEXT-not-enum rationale.

Review panel

All reviewers were dispatched sequentially and reported. No blocking findings from any lens.

  • Adversarial (always): No blocking. Confirmed the session_user refactor is behavior-preserving and app-container reachability is handled (401 without a valid cookie). Advisories: (1) cross-repo 200+null vs 404 coordination — addressed by documenting the deploy-order dependency here and in agents.md; (2) unused module log — dismissed, defining an unused log is the established convention in sibling routes (settings.py, users.py, stats.py, help.py); (3) theoretical mid-request-delete → 500 — dismissed, pre-existing pattern identical to users.patch_me, not introduced here.
  • Test adversary: No blocking. Found the overlong-language test exercised the regex, not the length cap (a raised-cap mutant survived). Fixed in aa61c9b: valid-shape tags on both sides of the 35-char boundary, plus whitespace-trim and present-but-null coverage.
  • DevEx / readability: No blocking. Fixed in ffd34fa: suffixed the compiled pattern _RE per repo convention, expressed the length cap with Field(max_length=...) like the sibling InputUser, and commented the cap value and the owner-row test read.
  • Security: No blocking, nothing exploitable. Checked ReDoS (linear — anchored delimiter + 35-char cap), SQL injection (parameterized value + hardcoded column + allowlist), stored XSS (shape regex forbids <>"'), token/secret leakage (none; InvalidJwt → bare 401), IDOR and mass-assignment (clean — language not on InputUser). Advisories were pre-existing architecture (app reachability, no-exp terminal JWTs), not regressions.
  • DB / migration: No blocking. Confirmed depends: points at 0006, nullable-no-default ADD COLUMN is catalog-only (no rewrite), forward-only is the repo convention, and db_snapshot backup/restore is safe both directions (old→new omits the column → NULL; new→old drops it with a warning). Advisory A1 (use IF NOT EXISTS) — dismissed, matches 0005's style and yoyo bookkeeping makes it moot.

🤖 Generated with Claude Code

ClaydeCode and others added 6 commits October 17, 2026 17:01
Add a nullable users.language column (migration 0007) and surface it on the
User model and the updatable-columns allowlist, so the preference lives on the
user row and grows with multi-user support. The column is plain TEXT, not a PG
enum, because which UI languages exist is the web-terminal's concern, not the
shard's.

Add the preferences request/response models. OutputPreferences is an object so
it can grow into a fuller per-user profile; InputPreferences validates the
shape of a BCP-47-ish language tag (so junk stays out of the column) without
gatekeeping the specific set.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The web-terminal reads the owner's preferred UI language on load and writes it
from its settings language switcher. GET always answers 200 for a valid
session with an extensible object; an unset language is null, which the client
treats like the 404 an older shard returns — fall back to its own detection.
PUT persists a validated language onto the session user's row.

Extract the cookie-to-user resolution shared with the users route into
web/protected/session.py, so the mapping from session cookie to acting user
(and its 401/403 failure modes) lives in one place instead of drifting across
two copies.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Cover the web-terminal's reliance on it: 401 without a session, an unset
language reading back as null, a written language surviving to the users row
(not just the reply), case normalization, a region subtag the shard does not
itself enumerate, and rejection of free text, empty, overlong, and missing
language.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Record the per-user design, the null/404 fallback contract the web-terminal
relies on, the deliberate TEXT-not-enum choice, and the shared session_user
helper.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The overlong-language test sent a dash-free string that the shape regex already
rejects, so the length cap itself was never exercised (a mutant raising the cap
survived). Replace it with valid-shape tags on both sides of the 35-char
boundary so the cap is what rejects, add a whitespace-trim test, and cover the
present-but-null language distinctly from the absent-field case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Suffix the compiled pattern _RE as every other regex in the repo does, express
the length cap with Field(max_length=...) like the sibling InputUser instead of
a hand-rolled check (the validator now only settles shape and casing), and note
why the cap exists and why the owner-row read works in the tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…mail

The preferences endpoint has somewhere to store a language now; this is the
one existing consumer that already needs it. shard_core includes the owner's
stored preference as a `language` field whenever it asks the controller to
send a verification email, so the controller can pick a template once it
reads that field (freeshard-controller#543).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@ClaydeCode

Copy link
Copy Markdown
Contributor Author

Added one more thing while this was still open: `send_verification_email` (the only existing consumer with an immediate, named need — Max wants the verification mail sent in German when that's the owner's preference) now forwards `user.language` to the controller as a third field on the `POST /api/email_verification` body. Covered by 3 new tests in `test_owner_email.py` (38 passed total).

The controller-side consumption (branch the template on that field) is tracked separately as freeshard-controller#543, since it needs this PR merged first to have a real value to read.

-- preference stored yet" — the client falls back to its own detection. The
-- column is plain TEXT, not a PG enum, so the set of offered languages is the
-- web-terminal's to grow, not a shard migration.
ALTER TABLE users ADD COLUMN language TEXT;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to be able to clearly distinguish preferences from other columns. Perhaps by prefix or as a separate table with a FK to the user.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went with the separate table: user_preferences(user_id PK/FK → users.id ON DELETE CASCADE, language). Matches the "grows into a fuller per-user profile" framing better than a prefix would once more fields land, and keeps users itself purely identity. Rewrote migration 0007 directly since nothing has shipped it yet.

Comment thread shard_core/data_model/preferences.py Outdated

# A BCP-47-ish language tag: a 2-3 letter primary subtag, optionally followed by
# region/script subtags ("en", "de", "en-us", "pt-br", "zh-hans"). The shard
# only stores this preference on behalf of the web-terminal; it is the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are mentioning the web-terminal but sundial is the web-UI. web-terminal is EOL. Use a generic term like UI or client or something. And fix the reason you used the wrong term. Probably a readme or agents.md somewhere.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Root cause was README.md's dev-setup instructions linking to the retired FreeshardBase/web-terminal repo — fixed that link (now points at sundial) and rewrote every place this PR's own new text copied the term forward (data_model/preferences.py, the route docstring, agents.md, test docstrings) to say "UI client" generically instead.

Comment thread shard_core/data_model/preferences.py Outdated
simply demands a language.
"""

language: str = Field(max_length=_MAX_LANGUAGE_LENGTH)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With more fields in the future it makes sense to make all of them optional so that clients can send a sparse object to modify only a few fields.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — InputPreferences.language is now Optional, and the route reads model_dump(exclude_unset=True) so an omitted field is left alone (same idiom patch_me already uses for display_name). An explicit null is still rejected, since there's still no "clear it" use case — just no longer a required field.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea to put this in one place. However there are no api endpoints here unlike with sibling files. Perhaps move it into a utils file or something that makes clear that this does not correspond to a route.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it to web/protected/_auth.py — the leading underscore marks it as having no routes of its own, same signal a sibling route module not having one would lack otherwise. Open to a different name/location if you had one in mind.

- user_preferences gets its own table (FK to users), not a column on
  users, so identity and preferences stay visibly apart as the latter
  grows into a fuller per-user profile.
- InputPreferences fields are all optional (omitted ones are left
  alone via exclude_unset, same idiom as patch_me); an explicit null
  is still rejected, there is just no "required field" case anymore.
- Drop the stale "web-terminal" naming this PR's own new docs picked
  up from README.md's dead link to that retired repo; fixed the link
  too, and reworded to a generic "UI client" throughout.
- session_user moves to web/protected/_auth.py (leading underscore):
  it resolves a cookie to a user for every /protected route that
  needs one, and isn't itself a route like its former siblings.

Full suite: 493 passed, 1 pre-existing environment flake (disk-space
assertion, unrelated to this change) on a fresh test container.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@ClaydeCode

Copy link
Copy Markdown
Contributor Author

Pushed a commit addressing all four review comments (replies on each thread): separate `user_preferences` table instead of a `users` column, `InputPreferences` fields now optional (sparse writes via `exclude_unset`), "web-terminal" terminology fixed at its root (a dead README link) plus everywhere this PR's own new text had copied it, and `session_user` moved to `web/protected/_auth.py`.

Also: the CI failure was mine, not flaky — `test_setting_an_address_passes_the_owners_stored_language` (added on top of #260 to forward the preference to the verification mail) failed locally too against a stale local test-Postgres container left over from an earlier interrupted run; a fresh container passes clean. Full suite: 493 passed, 1 pre-existing environment-only flake (a disk-space assertion unrelated to this change, this sandbox is genuinely low on disk).

@ClaydeCode

Copy link
Copy Markdown
Contributor Author

CI is green now. The second failure (test_docker_prune, after the push fixing the four review comments) was an unrelated timing flake — it polls for a cron-scheduled prune task to log within ~10s and doesn't touch anything in this diff; a rerun of just that job passed.

max-tet and others added 2 commits November 26, 2026 21:24
test_setting_an_address_passes_the_owners_stored_language indexed
calls_to(..., VERIFY_PATH)[0], assuming set_address's own send was the
first. Main's merge brought in a pairing change that now also sends a
real verification (for the controller's profile address) synchronously
during pairing itself, so [0] is that one instead. Switched to [-1],
matching the sibling test right above it that already carries this
exact fix and comment.

Full suite: 553 passed, 1 pre-existing environment flake (disk-space
assertion, unrelated) on a fresh test container.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@max-tet
max-tet merged commit d46c09c into main Nov 26, 2026
7 checks passed
@max-tet
max-tet deleted the feature/clayde/owner-preferences-endpoint branch November 26, 2026 22:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add owner preferences endpoint (locale/language now; user profile later)

2 participants