Skip to content

feat(settings): add user-facing device settings - #527

Merged
Quick104 merged 11 commits into
mainfrom
t3code/redesign-user-device-settings
Aug 1, 2026
Merged

Quick104 merged 11 commits into
mainfrom
t3code/redesign-user-device-settings

Conversation

@Quick104

@Quick104 Quick104 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Part of #NNN

Users can only manage settings for the device and profile attached to their current session. They cannot review which devices belong to their profile, see which settings differ per device, or manage another household device without using it directly. Household parents also lack a single place to manage device settings across profiles.

Approach

Add authenticated device and household-profile APIs, and extend the existing settings-value routes with optional device_id and profile_id targeting while preserving their current session-derived defaults.

Enforce device ownership and household-management authorization server-side, return audit metadata for changed settings, and keep account-wide store results filtered to the caller's authorized profile scope.

Add a responsive Settings > Devices experience with profile filtering, search, pagination, per-device changed-setting counts, and a detail editor driven by the settings contract. Reuse the canonical setting controls and invalidate affected queries after mutations so remote edits remain consistent.

Testing

Actual command output was not included in the supplied change context.

The change adds focused Go and web coverage for:

  • Named-device and named-profile authorization, including cross-account rejection
  • Device listing, profile filtering, changed-setting counts, and current-device detection
  • Household profile visibility and primary-profile access rules
  • Setting-value reads, writes, deletes, and audit timestamps
  • Device-list filtering, pagination, responsive behavior, and mutation-driven refreshes
  • Device setting grouping, controls, and contract-defined value ranges

UI screenshots or recordings still need to be attached.

AI Disclosure

  • Tool(s): Codex
  • Model(s): GPT-5
  • Involvement: Generated the change request title and body from the supplied commits and diff.
  • Adversarial review: No adversarial review results were provided.

Checklist

  • I ran an adversarial AI review of the diff and summarized findings above.
  • I ran the repo verify commands: make lint, cd web && pnpm run lint, cd web && pnpm run format:check, and relevant go test ./....

Summary by CodeRabbit

  • New Features

    • Added a “Your Devices” settings page for viewing and managing registered devices.
    • View device activity, platform details, profiles, and changed-setting counts with search and filtering.
    • Edit, reset, clear, or forget device-specific settings where permitted.
    • Added authorized household device and profile management with confirmation and activity feedback.
    • Added reusable language selectors with custom language entry and validation.
  • Security

    • Added profile ownership checks, PIN verification, scoped access controls, and audit records for household changes.
  • Documentation

    • Added an implementation plan covering device settings, authorization, testing, and known limitations.

Quick104 and others added 7 commits July 31, 2026 13:47
Adds the server half of the user-facing device settings screen: a viewer can
see the devices they watch on and change settings for any of them from
whichever device they are holding, and the household parent can do the same for
everyone on the account.

No schema change. user_devices and user_setting_values are already keyed
(user_id, profile_id, device_id), and both list queries are already
account-wide, so this is authorization plus routes.

Two identity widenings on the canonical settings API, each behind a guard:

- A caller may name a device_id other than the request's own. Authorized
  against user_devices for that profile, which is why DeviceExists lands
  first: completeIdentity validated an identity's shape but never that the
  device belonged to the caller, safe only while the id came from the header.
- A household parent may name a profile_id other than their own. Guarded by
  canManageHousehold, extracted from ProfileHandler so profile management and
  settings management cannot drift apart. Existence resolves through the
  caller's own store, so a foreign profile is 404 and the cross-account
  boundary holds for free.

Both default to today's behavior when the parameter is absent, so existing
clients need no change.

New self-service routes: GET /devices, DELETE /devices/{id}, and
DELETE /devices/{id}/settings. The list filters to the calling profile in the
handler — ListDevices is account-wide by construction in both backends (no
WHERE at all in the per-user SQLite), so a passthrough would have shown every
household member's devices to everyone. ?scope=household is opt-in and guarded.

Also fixes a bug the widening exposed: registerWritingDevice fired on every
device write, so writing to another device — or on another profile's behalf —
would have registered the actor's browser under the target, inventing a device
nobody holds.

Cross-profile and admin mutations are audited. The record carries identity
only, never the value, for the same reason user_settings.changed does: admins
receive other accounts' events. Ordinary self-service writes are not audited —
a trail that records everything answers nothing.

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds "Your devices" under Settings: a searchable device list and an editable
detail pane, so someone can fix how Silo behaves on any device they watch on
without borrowing that device. The household parent gets an "Everyone" switch
covering every profile on the account.

Layout is master-detail, and holds at eleven devices: fixed-height rows
carrying a name, when it was last used, and the one number that matters — how
many settings differ there. A device with nothing changed shows a dash rather
than a zero, so "which one did I change?" is answerable by scanning. Rows group
by recency, or by person in the household view.

Settings are grouped by what they affect — Picture, Sound, Subtitles,
Episodes — rather than in manifest order, and no raw key is ever shown: labels,
descriptions, controls, bounds and options all come from the contract. A test
asserts every device-scoped key lands in exactly one group or is deliberately
hidden, so a key added to the manifest cannot silently vanish from the screen.

Values round-trip as typed JSON rather than through strings, unlike the admin
console: a slider re-parsed from text is a hazard on a screen a viewer drives.

Policy caps are explained rather than hidden. A capped setting renders only the
permitted options and says which value the household limit displaced; a locked
one says so instead of presenting a disabled control with no reason.

Acting for someone else is stated, never implied — a persistent banner, and
reset actions that name the person ("Use Robin's setting"). The household view
also states what it does not show: this is how Silo is set up per device, not
what anyone watched.

Two fixes the work turned up:

- effectiveSettingsQueryKey was namespaced by active profile only, so reading
  another device's values would have collided with the current device's cache
  entry and served one device's settings as another's.
- The settings shell caps content at max-w-3xl, which is right for a single
  column of rows and squeezes a two-pane page. Pages that manage their own
  layout now opt out.

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds profile chips above the device list in the household view: Everyone, then
one per person, each with a device count. Picking a person narrows the list to
their devices; picking the active chip again clears it.

The chips only appear in the household view, where more than one profile is on
screen. A viewer looking at their own devices has exactly one profile, so a
filter with a single option would be chrome that explains nothing.

Three details the interaction needs to be honest:

- Counts come from the unfiltered list, so a chip keeps saying how many devices
  it would reveal instead of collapsing to zero once another chip is active.
- Grouping falls back to recency once a person is chosen, because a person
  heading would only repeat the chip above it.
- The detail pane follows the filter. Leaving someone else's device open while
  the list shows another person would make the list and the pane disagree about
  whose settings are being edited — the one thing this screen cannot be vague
  about. Leaving the household view clears the filter for the same reason.

The chip's count sits in its own element, so its accessible name is set
explicitly: without it a screen reader announces "Everyone3".

Part of #215

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Seeding a realistic eight-profile household made the ordering problem obvious:
chips were in device-arrival order, which put the person actually using the
screen last. Their own profile now comes first and the rest sort by name, so a
chip stays where it was last seen rather than moving as devices are used.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The screen was built two-pane and stacked those panes vertically on narrow
viewports, which is the wrong shape for a phone: the device list ran past a
thousand pixels before the first setting, so reaching "turn HDR off" meant
scrolling through every other device to get there. The whole page measured 4726
CSS pixels — 5.6 screens — for four devices.

Below xl the list and the settings are now two screens rather than two panes.
Picking a device swaps to it and a back control returns; the page header and
scope switch belong to the list screen, and the detail screen's own header says
which device it is about. The list page is 1050px, and scroll position resets on
each swap so a tap does not land mid-settings.

Touch targets were 32-36px throughout. Rows, chips, the scope switch, the reset
link and the header actions now clear 44px on a phone and keep their compact
desktop sizing from xl. Device rows carry a chevron below xl, because there they
navigate rather than select in place. The device search input goes to 16px on
mobile — iOS Safari zooms the viewport for anything smaller and does not zoom
back out.

Profile chips wrapped to three lines at eight profiles and pushed the list off
screen; they scroll horizontally on one line instead, the same trade the
settings shell's own mobile tab bar makes. Switches now sit beside their labels
rather than below, saving a row on each of ~18 toggles, while selects and
sliders still take the full width they need.

Two fixes the pass turned up, neither mobile-specific:

- playback.max_bitrate_kbps is declared as an integer range with a select
  control and no members, so it rendered as a dropdown with one blank entry —
  unusable, and silent about the value it was storing. It now offers real
  bandwidth choices bounded by the definition's own range, and keeps a
  non-preset stored value selectable.
- Select triggers had no accessible name, announcing as bare comboboxes.

Forget is destructive and rare, so it no longer sits as a full-width sibling of
the common action.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A real account carries 260 devices; the test fixtures had 14. Every browser
profile, private window, reinstall and test build registers a device identity
and nothing prunes them, so the list grew without limit — 13,681 CSS pixels,
sixteen screens, and the settings themselves never came into view. That is the
same failure the mobile pass just fixed, at a scale the fixtures never showed.

Three changes:

- The list is a bounded scroll area rather than an unbounded column. The page
  is now ~1,300px whatever the device count, and section headings stick while
  scrolling so the recency or person grouping stays legible.
- Devices nobody has used for 90 days that carry no settings of their own
  collapse behind "Show N unused devices". Over half of the real fleet is that:
  one-off sessions that never changed anything. The current device and anything
  with settings always stay visible, however old.
- Search spans everything including the hidden tail, because searching means
  looking for something specific and hiding a device from its own name would
  read as the device having vanished.

The 90-day threshold matches the settings contract's own rule for removing
empty device records, which is specified but not yet implemented server-side —
until it is, this keeps the screen usable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The bandwidth cap stopped at 40 Mbps because the ladder behind it was a
hardcoded list I wrote, not anything the contract said. The definition allows
up to 200,000 kbps, and remuxed 4K HDR or an untouched Blu-ray rip needs well
past 40 — so the picker was silently capping people below what their own server
could already send them.

The ladder now runs to the definition's own ceiling. Its low end mirrors the
in-player quality switcher, so a cap chosen here lines up with what the player
offers mid-playback, and entries outside a definition's declared range are
filtered out as before.

Also stops duplicating the label format a third time: the player's
formatQualityBitrate is now exported and reused, since both surfaces pick from
the same ladder and should not disagree about how to spell a number.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds user-facing device settings. It adds device APIs, profile and device authorization, audit logging, targeted settings operations, query isolation, and a web interface for listing and editing devices.

Changes

Device Settings Feature

Layer / File(s) Summary
Implementation plan document
docs/superpowers/plans/2026-07-31-user-facing-device-settings.md
Documents the planned server, authorization, web, verification, and scope boundaries.
Device storage and household authorization
internal/userstore/*, internal/userdb/*, internal/api/handlers/household.go, internal/api/handlers/profiles.go
Adds profile-scoped device existence and deletion operations. Centralizes household and PIN-token authorization.
Device registry API and routing
internal/api/handlers/devices.go, internal/api/handlers/devices_test.go, internal/api/router.go
Adds device listing, settings clearing, forgetting, ownership checks, audit calls, events, tests, and authenticated routes.
Targeted settings and audit logging
internal/api/handlers/settings_values.go, internal/api/handlers/settings_audit.go, internal/api/handlers/settings_values_test.go
Adds profile and device targeting for settings reads and mutations. Adds ownership checks, conditional registration, language suggestion restrictions, and cross-profile audit records.
Web contracts and query state
web/src/api/types.ts, web/src/hooks/queries/*
Adds device response types, query keys, device hooks, recency grouping, targeted effective-settings requests, cache isolation, and mutation invalidation.
Device list experience
web/src/components/settings/DeviceList.tsx, web/src/components/settings/DeviceList.test.tsx
Adds search, profile filtering, recency grouping, dormant-device handling, selectable rows, accessibility states, and relative activity labels.
Device setting grouping and editor
web/src/lib/deviceSettingGroups.ts, web/src/components/settings/DeviceSettingGroups.tsx, web/src/components/settings/LanguageSelect.tsx, web/src/pages/settings/LibrarySettings.tsx, web/src/pages/settings/PlaybackSettings.tsx, web/src/pages/settings/SubtitleAppearanceSettings.tsx, related tests
Adds grouped device settings, hidden-key handling, reset behavior, typed controls, bitrate options, household constraints, shared language selection, and reusable bitrate formatting.
Device settings page and application wiring
web/src/pages/settings/DeviceSettings.tsx, web/src/App.tsx, web/src/pages/SettingsLayout.tsx, web/src/lib/documentTitle.ts
Adds device selection and detail editing, household switching, destructive-action confirmations, routing, navigation, wide layout support, and the page title.
Subtitle facet query update
internal/catalog/browse.go
Deduplicates subtitle-language query branches before combining them and applies the configured facet limit.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding user-facing device settings.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/redesign-user-device-settings

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 31, 2026
…device-settings

# Conflicts:
#	internal/api/handlers/settings_values_test.go

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5530770d11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +75 to +78
const selected = useMemo(() => {
if (selectable.length === 0) return null;
return selectable.find((device) => device.device_id === selectedId) ?? selectable[0];
}, [selectable, selectedId]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Key selected devices by both profile and device

In household view, the same installation can have registry rows for multiple profiles, but selection retains only device_id. Clicking the later profile's row therefore resolves to the first matching row and opens the wrong profile's detail editor; DeviceList also highlights every row with that ID. Store and compare the (profile_id, device_id) pair so mutations cannot target the wrong household member.

AGENTS.md reference: AGENTS.md:L42-L44

Useful? React with 👍 / 👎.

Comment on lines +588 to +593
if named := strings.TrimSpace(r.URL.Query().Get("profile_id")); named != "" && named != rc.ProfileID {
if !h.mayActForProfile(w, r, named) {
return
}
rc.ProfileID = named
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve constraints for the target profile

When a household parent supplies another profile_id, this changes only the resolver context; h.constraintsFor(r) still reads the access scope that middleware resolved from the parent's X-Profile-Id. If the child has a different max_playback_quality, the device screen consequently reports the parent's effective quality and permitted choices rather than the child's. Re-resolve the policy inputs for the named target before resolving its settings.

AGENTS.md reference: AGENTS.md:L42-L44

Useful? React with 👍 / 👎.

Comment on lines +380 to +384
<DeviceSettingGroups
settings={settings}
ownerLabel={ownerLabel}
disabled={setValue.isPending || clearValue.isPending}
onChange={(key: SettingKey, value: unknown) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wire the subtitle appearance control

playback.subtitle_appearance is an object setting, so DeviceSettingGroups renders its enabled "Change how they look" button and invokes the optional onOpenPanel callback. This integration never supplies that callback, making the button silently do nothing whenever a user tries to edit subtitle appearance for a device.

Useful? React with 👍 / 👎.

Comment on lines +230 to +233
if _, err := store.DeleteSettingValuesForDevice(r.Context(), profileID, deviceID); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to clear device settings")
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make device cleanup atomic

Both store backends already make DeleteAllDeviceSettings transactionally delete canonical and legacy rows, but this preceding call commits the canonical deletion separately. If the later cleanup or registry deletion fails, the endpoint returns 500 after partially clearing the device and before publishing invalidations, leaving clients and registry state inconsistent; consolidate the cleanup into one atomic store operation.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +225 to +228
if !owned && len(keys) == 0 {
writeError(w, http.StatusNotFound, "not_found", "Device not found")
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep repeated device forgets idempotent

After the first successful forget, both owned and keys are empty, so a retry takes this branch and returns 404. The implementation plan included in this change explicitly requires the second call to return 204 (docs/superpowers/plans/2026-07-31-user-facing-device-settings.md:177), which is important when a successful response is lost and the client retries; return success for an already-absent device while preserving the same non-disclosing response for unknown IDs.

AGENTS.md reference: AGENTS.md:L53-L53

Useful? React with 👍 / 👎.

}
}

devices, err := registry.ListDevices(r.Context())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Register devices during ordinary authenticated use

This endpoint can only return rows already present in user_devices, but a repo-wide search shows production registration occurs only when legacy device-setting routes are accessed or after a successful canonical device-setting write. A newly signed-in device that only browses or plays media—and never changes a device setting—therefore never appears in this registry, despite the page promising all devices a viewer watches on. Record observed device metadata during normal authenticated use, not only setting mutations.

Useful? React with 👍 / 👎.

Comment on lines +106 to +107
// One pass over the stored values rather than a count query per device.
counts, err := deviceOverrideCounts(r, store)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Query only device-scoped counts

deviceOverrideCounts calls ListAllSettingValues, whose PostgreSQL and SQLite implementations select and sort every explicit value at every scope, including potentially large per-series and per-library collections, then discard everything except profile_device. Opening this page can therefore perform an account-wide materialization just to calculate badges; add a scoped aggregate/count query so device listing cost tracks the number of devices rather than all stored preferences.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +8 to +12
import {
classifyPlatform,
PlatformIcon,
platformKindLabel,
} from "@/components/admin/deviceOverrides";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Move shared device display helpers out of admin

The user-facing settings page imports platform classification and icons from the 714-line admin device-overrides module, which also owns admin settings controls, anomaly logic, and admin query dependencies. This inverts package ownership and couples an ordinary viewer screen to an admin implementation; the implementation plan explicitly calls for moving these helpers into a shared device-display module and having both screens consume it.

AGENTS.md reference: AGENTS.md:L16-L18

Useful? React with 👍 / 👎.

Comment on lines +60 to +62
const { data: devices = [], isLoading } = useMyDevices({
household: household && canSeeHousehold,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Render failures instead of plausible empty settings

Both device queries discard their error state: a failed list request becomes devices = [] and renders "No devices yet," while a failed effective-settings request becomes {} and renders every control with its contract default. On a transient store failure, expired household permission, or concurrently forgotten device, the page therefore presents plausible but false state and still leaves mutation controls available; render an error/retry state and disable editing until the read succeeds.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +75 to +78
const selected = useMemo(() => {
if (selectable.length === 0) return null;
return selectable.find((device) => device.device_id === selectedId) ?? selectable[0];
}, [selectable, selectedId]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Select the current device before the first list entry

Despite the comment and the API's is_current_device field, the initial selectedId is null, so this expression always falls back to selectable[0] rather than the current device. Because listing the registry does not refresh last_seen_at, another device can easily be first, causing the page to open a remote device by default and making the first setting change target somewhere other than the device the viewer is holding.

Useful? React with 👍 / 👎.

The bounded device list kept the browser's default scrollbar, which reads as a
heavy grey slab against a rounded dark panel. The app already has
.overlay-scroll for exactly this — a thin, low-contrast thumb over a
transparent track — and it now sits in the panel's gutter rather than flush
against the rounded edge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 10

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (14)
docs/superpowers/plans/2026-07-31-user-facing-device-settings.md-429-431 (1)

429-431: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make current-device detection profile-aware.

The household design permits the same physical device to be registered by multiple profiles. The provided internal/api/handlers/devices.go compares only device_id. In household mode, both profile rows can be marked as current. Compare (profile_id, device_id) and add a same-device/different-profile test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 429 - 431, Update current-device detection in the devices handler to
compare the authenticated profile ID together with device_id, rather than
device_id alone, so only the matching profile/device pair is marked current. Add
coverage for the same physical device registered under different profiles,
ensuring only the correct profile row is detected as current.
docs/superpowers/plans/2026-07-31-user-facing-device-settings.md-210-213 (1)

210-213: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Align the canManageHousehold interface with its callers.

The plan declares three parameters. The provided internal/api/handlers/devices.go calls canManageHousehold(r, store, h.UserRepo, h.ProfileTokens). Add the UserRepo dependency to the documented interface, or explain how store supplies it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 210 - 213, Update the documented canManageHousehold interface to include
the UserRepo dependency used by internal/api/handlers/devices.go, matching the
call canManageHousehold(r, store, h.UserRepo, h.ProfileTokens). Keep the wrapper
and existing call-site behavior unchanged, or explicitly document how store
provides UserRepo if that is the intended design.
docs/superpowers/plans/2026-07-31-user-facing-device-settings.md-245-262 (1)

245-262: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Specify the actor in the cross-account profile test.

The required authorization order checks canManageHousehold before loading the target profile. A non-primary or PIN-unverified caller receives 403. An authorized primary or admin can reach the caller-store lookup and receive 404 for an external profile. Set the test actor explicitly and cover these cases separately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 245 - 262, Update the cross-account profile tests around
identityForSessionKey to set the caller actor explicitly and separate
authorization outcomes: non-primary and PIN-unverified callers must receive 403
before profile lookup, while an authorized primary or admin must reach the
caller-owned store lookup and receive 404 for an external profile. Ensure each
test uses the appropriate actor and validates the required status and error
details.
web/src/pages/settings/DeviceSettings.tsx-60-62 (1)

60-62: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Report a failed device load instead of showing "No devices yet."

useMyDevices returns data = [] on error because of the default value at line 60. The page then renders "No devices yet. They appear here as you sign in on them." A network failure, or a 403 from the household scope, therefore reads as an empty registry. Read isError and render a distinct message with a retry action.

Also applies to: 158-162

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/settings/DeviceSettings.tsx` around lines 60 - 62, Update the
useMyDevices result destructuring in DeviceSettings to capture isError and the
query retry handler, then render a distinct device-load failure state with a
retry action instead of the “No devices yet” empty state when isError is true.
Preserve the existing empty-state message for successful requests that return no
devices.
web/src/components/settings/DeviceList.tsx-122-143 (1)

122-143: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Key profile sections by profile id, not by title.

sections uses title as the React key at line 206. Two profiles can produce the same title. title falls back to "Other profile" whenever profile_name is empty, and the server returns an empty profile_name for every device when its profile lookup fails (internal/api/handlers/devices.go sets profileNames = map[string]string{} on error). Every section then shares one key, which produces a React duplicate-key warning and can mis-reconcile rows between sections.

Carry a stable id on each section.

🛠️ Proposed fix
   const sections = useMemo(() => {
     if (groupByProfile && !profileFilter) {
-      const byProfile = new Map<string, { title: string; devices: UserDevice[] }>();
+      const byProfile = new Map<string, { id: string; title: string; devices: UserDevice[] }>();
       for (const device of filtered) {
         const existing = byProfile.get(device.profile_id);
         if (existing) {
           existing.devices.push(device);
         } else {
           byProfile.set(device.profile_id, {
+            id: device.profile_id,
             title: device.profile_name || "Other profile",
             devices: [device],
           });
         }
       }
       return [...byProfile.values()];
     }
 
     return GROUP_ORDER.map((group) => ({
+      id: group,
       title: GROUP_TITLES[group],
       devices: filtered.filter((device) => deviceRecencyGroup(device, now) === group),
     })).filter((section) => section.devices.length > 0);
   }, [filtered, groupByProfile, profileFilter, now]);

Then update the render:

-          <section key={section.title}>
+          <section key={section.id}>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceList.tsx` around lines 122 - 143, Update
the sections built in the useMemo block to carry a stable profile id alongside
each profile section, using the profile id as the section identity even when
profile_name is empty or duplicated. Then update the section rendering near the
existing title-based React key to use that stable id, while preserving the
displayed title and existing recency-group behavior.
web/src/components/settings/DeviceSettingGroups.tsx-177-179 (1)

177-179: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The constraint message prints raw contract values.

String(permitted) and String(effective.stored_value) render the stored JSON. For playback.max_bitrate_kbps the sentence reads "limit this to 4000, so your choice of 20000 isn't available right now." The same screen already formats that key as "4 Mbps" through formatBitrate. Booleans render as "true" and "false".

Format the values with the same helpers the controls use, or fall back to a value-free sentence for keys with no display formatter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.tsx` around lines 177 - 179,
Update the constraint message generation around effective.stored_value and
permitted to format values using the same display helpers used by the controls,
including formatBitrate for playback.max_bitrate_kbps and human-readable boolean
formatting. For keys without a display formatter, use a value-free constraint
message instead of interpolating raw contract values.
web/src/components/settings/DeviceSettingGroups.test.tsx-21-24 (1)

21-24: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Guard the two jsdom stubs independently.

scrollIntoView is stubbed inside the hasPointerCapture guard. The two capabilities are unrelated. If a later jsdom release adds hasPointerCapture, this block is skipped entirely, scrollIntoView stays undefined, and the Radix Select tests fail with an unrelated error.

♻️ Proposed fix
 if (typeof window !== "undefined" && !window.HTMLElement.prototype.hasPointerCapture) {
   window.HTMLElement.prototype.hasPointerCapture = () => false;
-  window.HTMLElement.prototype.scrollIntoView = () => {};
 }
+if (typeof window !== "undefined" && !window.HTMLElement.prototype.scrollIntoView) {
+  window.HTMLElement.prototype.scrollIntoView = () => {};
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.test.tsx` around lines 21 -
24, Update the jsdom setup in DeviceSettingGroups.test.tsx so the
hasPointerCapture and scrollIntoView stubs use separate capability checks. Keep
the window guard for each, but assign each HTMLElement prototype method
independently when that method is unavailable.
web/src/lib/documentTitle.ts-48-48 (1)

48-48: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Move "settings/devices" to SETTINGS_TITLES as "devices": "Your Devices". resolveSettingsDocumentTitle("/settings/devices") currently returns "Settings" because SETTINGS_TITLES has no "devices" key.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/lib/documentTitle.ts` at line 48, Move the devices title entry from
the current settings title mapping into SETTINGS_TITLES, changing its key to
"devices" while retaining the "Your Devices" value. Ensure
resolveSettingsDocumentTitle("/settings/devices") resolves to that title and
remove the obsolete "settings/devices" entry.
web/src/pages/SettingsLayout.tsx-312-323 (1)

312-323: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the contract labels for the device search index.

Replace "Video quality", "Data use limit", "Play Dolby Vision films as HDR10", and "How video fills the screen" with "Preferred quality", "Maximum bitrate", "Dolby Vision Profile 7 fallback", and "Video sizing".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/SettingsLayout.tsx` around lines 312 - 323, Update the settings
search index created by settingIndex in SettingsLayout so its labels use the
device-search contract: replace “Video quality” with “Preferred quality”, “Data
use limit” with “Maximum bitrate”, “Play Dolby Vision films as HDR10” with
“Dolby Vision Profile 7 fallback”, and “How video fills the screen” with “Video
sizing”; leave the other labels unchanged.
web/src/components/settings/DeviceSettingGroups.tsx-211-222 (1)

211-222: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Disable the panel button without a handler.

When onOpenPanel is absent, set disabled={disabled || !onOpenPanel}. Use definition.label for the button text instead of the fixed "Change how they look" label. The DeviceSettings page currently omits onOpenPanel, so the button is enabled but does nothing.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.tsx` around lines 211 - 222,
Update the panel Button in the control/definition.type branch to disable it when
either disabled is true or onOpenPanel is absent, and replace the hardcoded text
with definition.label. Keep the existing onClick behavior and styling unchanged.
web/src/components/settings/DeviceSettingGroups.tsx-368-397 (1)

368-397: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Expose and apply the numeric ceiling to the bitrate ladder.

numericSelectChoices renders through definition.maximum because numeric ceilings omit permitted_values. A viewer can select up to 200 Mbps even when the server caps playback at 8 Mbps. Expose the numeric ceiling in the effective-settings response, then bound the ladder by that limit. Do not use effective.value directly because it is the stored value when it is already below the ceiling.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.tsx` around lines 368 - 397,
Expose each numeric setting’s maximum in the effective-settings response and its
client-facing type, then ensure numericSelectChoices uses that ceiling when
filtering BITRATE_CHOICES_KBPS. Preserve the stored effective value
independently; do not derive the ceiling from effective.value.
internal/api/handlers/devices_test.go-164-173 (1)

164-173: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the index before the error message reads it.

If body.Devices is empty, the condition on line 170 is true through the length check, and then body.Devices[0].ProfileName on line 171 panics with an index-out-of-range. The test then reports a panic instead of the assertion it intended.

💚 Proposed fix
-	if len(body.Devices) != 1 || body.Devices[0].ProfileName != "Sam" {
-		t.Errorf("profile_name = %q, want Sam", body.Devices[0].ProfileName)
-	}
+	if len(body.Devices) != 1 {
+		t.Fatalf("returned %d devices, want 1: %+v", len(body.Devices), body.Devices)
+	}
+	if body.Devices[0].ProfileName != "Sam" {
+		t.Errorf("profile_name = %q, want Sam", body.Devices[0].ProfileName)
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/devices_test.go` around lines 164 - 173, Update
TestListDevices_IncludesProfileName so the failure message does not index
body.Devices unless the slice is non-empty; guard the diagnostic access while
preserving the existing length and ProfileName assertions.
internal/api/handlers/devices.go-234-252 (1)

234-252: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Publish invalidations for legacy device settings.

HandleGetDeviceSetting still serves player.next_up_prompt_seconds from user_device_settings. deviceSettingKeys reads only canonical values, so clearing a registered device with only a legacy row deletes the setting without publishing user_settings.changed for the legacy key. Collect legacy keys before deletion and publish their invalidations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/devices.go` around lines 234 - 252, Update the
device-settings clearing flow around DeleteAllDeviceSettings to collect legacy
keys from user_device_settings before deletion, including
player.next_up_prompt_seconds and any other keys served by
HandleGetDeviceSetting. Merge these keys with the canonical keys before
publishing user_settings.changed events, while preserving the existing deletion
and forget-device behavior.
internal/api/handlers/devices.go-126-145 (1)

126-145: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Sort devices by normalized timestamps, not raw strings.

SQLite RFC3339Nano values sort incorrectly when one timestamp has fractional seconds and another does not. Parse or normalize LastSeenAt before sorting. PostgreSQL includes a timezone offset, so its format does not cause the browser timezone shift described here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/devices.go` around lines 126 - 145, Update the sorting
logic in the devices handler’s sort.SliceStable comparator to compare parsed or
normalized LastSeenAt timestamps rather than raw strings. Preserve descending
last-seen ordering and the existing DeviceID ascending tie-breaker, handling the
timestamp formats returned by SQLite and PostgreSQL consistently.
🧹 Nitpick comments (7)
web/src/hooks/queries/devices.test.ts (1)

58-68: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make the profile-separation test independent of the ambient active profile.

mine omits profileId, so effectiveSettingsQueryKey falls back to activeProfileId() (web/src/hooks/queries/settingValues.ts, line 104). The assertion then depends on whatever the ambient active profile is in the test environment. Pass both profile ids explicitly so the test states its own premise.

♻️ Suggested change
-    const mine = effectiveSettingsQueryKey({ keys, deviceId: "shared-tv" });
+    const mine = effectiveSettingsQueryKey({
+      keys,
+      deviceId: "shared-tv",
+      profileId: "profile-1",
+    });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/hooks/queries/devices.test.ts` around lines 58 - 68, Update the
“gives each profile its own cache entry” test to pass an explicit profileId for
both effectiveSettingsQueryKey calls, using different profile ids while keeping
the shared deviceId and keys unchanged. This removes reliance on
activeProfileId().
web/src/lib/deviceSettingGroups.ts (1)

37-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Key the override tables by SettingKey to catch stale keys at build time.

EXPLICIT_GROUPS and HIDDEN_KEYS both use string keys. If a manifest key is renamed or misspelled here, TypeScript stays silent and the entry becomes dead: groupForDeviceSetting then falls back to the manifest category, or the key stops being hidden. The file's own goal is that a key cannot silently move. A typed record gives that guarantee at compile time.

♻️ Proposed typing change
-const EXPLICIT_GROUPS: Partial<Record<string, DeviceSettingGroupId>> = {
+const EXPLICIT_GROUPS: Partial<Record<SettingKey, DeviceSettingGroupId>> = {
-const HIDDEN_KEYS = new Set<string>([
+const HIDDEN_KEYS = new Set<SettingKey>([

HIDDEN_KEYS.has(key) still type-checks because key is a SettingKey.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/lib/deviceSettingGroups.ts` around lines 37 - 79, Update
EXPLICIT_GROUPS to use SettingKey as its record key type and HIDDEN_KEYS to be a
Set of SettingKey rather than string-based collections. Import or reuse the
existing SettingKey type, preserving current values and membership behavior so
invalid or renamed manifest keys fail at compile time.
web/src/components/settings/DeviceSettingGroups.tsx (1)

337-337: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add permitted_values to EffectiveSetting and read it directly.

The API returns this field for constrained settings, but EffectiveSetting omits it. Declare permitted_values?: unknown[], then use effective?.permitted_values instead of a structural cast.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.tsx` at line 337, Update the
EffectiveSetting type to declare permitted_values?: unknown[], then change the
permitted assignment in DeviceSettingGroups to read effective?.permitted_values
directly and remove the structural cast.
internal/userstore/storetest/settingvalues.go (1)

52-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a ForgetDevice conformance case.

The suite now pins DeviceExists across backends. ForgetDevice has no case here. Its most important property — forgetting one profile's row leaves another profile's row for the same device intact — is asserted only in internal/api/handlers/devices_test.go, which runs against the SQLite store. The Postgres implementation of ForgetDevice stays unexercised by this shared suite.

Add a ForgetDevice subtest that registers one device under p1 and p2, forgets p1, then asserts DeviceExists(p2, deviceApple) is still true.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/userstore/storetest/settingvalues.go` around lines 52 - 54, Add a
ForgetDevice subtest alongside the existing DeviceExists case in the shared
store conformance suite. Register deviceApple for profiles p1 and p2, invoke
ForgetDevice for p1, then assert DeviceExists for p2 and deviceApple remains
true, exercising this behavior across all backends.
internal/api/handlers/settings_values_test.go (1)

1187-1210: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

captureAuditLogs replaces the process-global slog default.

The helper swaps slog.Default() and reads buf from the returned closure. No test in this file calls t.Parallel(), so the tests run sequentially and this is safe today. It is fragile: if any test in package handlers later calls t.Parallel(), the handler swap and the buf reads race with concurrent tests, and captured records leak between tests.

Consider adding a comment that states these tests must not run in parallel, or guard buf with a mutex through a small io.Writer wrapper.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/settings_values_test.go` around lines 1187 - 1210, Make
captureAuditLogs safe against concurrent use by protecting writes to the
captured buffer and reads performed by the returned closure with a mutex-backed
io.Writer wrapper. Keep the existing slog default restoration in
captureAuditLogs, and ensure record parsing reads a synchronized snapshot so
captured audit records cannot race or leak across tests.
internal/api/handlers/devices_test.go (1)

365-384: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the unknown target profile.

removeDevice answers 404 when ?profile_id= names a profile that does not exist on the account (internal/api/handlers/devices.go lines 195-198). No test reaches that branch. A household-scoped request with an unknown profile_id would pin it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/devices_test.go` around lines 365 - 384, Add a test
alongside TestForgetDevice_PrimaryMayForgetHouseholdDevice that calls
HandleForgetDevice with a household-scoped request whose profile_id does not
exist on the account, then assert the response is HTTP 404 and verify the
targeted device remains unchanged.
internal/api/handlers/household_test.go (1)

140-153: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a subtest for a stale policy revision.

verifyProfileToken rejects a token whose PolicyRevision differs from the user's AccessPolicyRevision. The current tests mint the token with PolicyRevision: 0 against a user whose revision is also 0, so the comparison never fails in a test. A subtest with a mismatched revision pins that part of the boundary.

💚 Suggested subtest
t.Run("pin with stale policy revision may not", func(t *testing.T) {
	store, tokens := setup(t, "1234")
	repo := stubUserRepo{user: &models.User{ID: 1, AccessPolicyRevision: 2}}
	token, _, err := tokens.Mint(access.ProfileTokenClaims{
		UserID: 1, SessionID: "session-1", ProfileID: "primary", PolicyRevision: 1,
	})
	if err != nil {
		t.Fatalf("issuing token: %v", err)
	}
	if _, err := canManageHousehold(householdRequest("primary", false, token), store, repo, tokens); !errors.Is(err, access.ErrProfileUnverified) {
		t.Fatalf("stale revision err = %v, want ErrProfileUnverified", err)
	}
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/household_test.go` around lines 140 - 153, Add a
subtest alongside the existing valid-token case to cover a stale policy
revision: configure stubUserRepo with AccessPolicyRevision 2, mint the primary
profile token with PolicyRevision 1, and assert canManageHousehold returns
access.ErrProfileUnverified. Preserve the existing valid-token test unchanged
and handle token-minting errors consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md`:
- Line 9: Reconcile the plan’s “no new storage and no schema change” statement
with Task 7’s settings audit requirement. Update the audit design to define
durable storage, schema, retention, and failure behavior, or make it explicitly
log-only by removing stored-audit-row requirements and documenting delivery
guarantees.
- Around line 185-187: The device-clearing flow must delete both settings
storage generations atomically instead of separately committing
DeleteSettingValuesForDevice before DeleteAllDeviceSettings. Add or reuse a
single store operation that performs the complete cleanup in one transaction,
then remove the registry row only after that operation succeeds; preserve the
required user_settings.changed event publication.
- Around line 172-177: Revise the forget-device plan and related tests to define
a state/status contract that distinguishes an already-forgotten device from an
unknown device owned by another profile, while preserving 404 for the latter and
204 for repeated requests. Update the ForgetDevice flow and
TestForgetDevice_IsIdempotent, TestForgetDevice_RejectsOtherProfilesDevice, and
TestForgetDevice_RemovesSettingsAndRegistryRow to validate the chosen contract.
- Around line 262-272: Revise the plan’s capability statement to classify
cross-profile, cross-device device-settings reads and writes as a new
capability, rather than claiming the change only replaces an existing path. Make
the Apple and Android client follow-up explicit and required, including
coordinated updates in both client repositories for the client-visible API
changes, and update the related repeated section as well.

In `@internal/api/handlers/settings_values.go`:
- Around line 923-941: Update internal/api/handlers/settings_values.go:923-941
so the resolved identity.DeviceID is checked with deviceBelongsToProfile
whenever identity.ProfileID differs from the acting profile, including when the
device came from the header; preserve the own-profile lazy-registration
exception. Update internal/api/handlers/settings_values.go:584-600 to apply the
same validation before resolution after rc.ProfileID is widened, requiring an
explicit device_id or validating the header device against rc.ProfileID. Add
coverage in internal/api/handlers/settings_values_test.go for widened-profile
requests without device_id on both write and effective-read paths.
- Around line 52-57: Update canManageHousehold to return false when UserRepo or
ProfileTokens is nil before evaluating the primary-profile-without-PIN path,
while keeping the existing server-admin bypass ahead of this dependency check.

In `@internal/api/router.go`:
- Around line 2183-2190: Add a GET /devices/capability endpoint within the
deviceHandler route registration, alongside HandleListDevices and the device
settings routes. Return HTTP 200 with an explicit enabled flag, and ensure the
endpoint is available only when deviceHandler is registered.

In `@web/src/components/settings/DeviceSettingGroups.tsx`:
- Around line 224-254: Add accessible names in the control rendering logic:
update the Switch component in the switch branch with
aria-label={definition.label}, and pass thumbLabels={[definition.label]} to the
Slider component in the slider/stepper branch so its thumb receives the label.

In `@web/src/hooks/queries/devices.ts`:
- Around line 15-28: Update useMyDevices and the own-scope deviceKeys.list query
key to include the active profile ID, while leaving the household key unchanged.
Reuse the existing active-profile source used by the hook so profile switches
produce distinct own-device cache entries and do not reuse the previous
profile’s data.

In `@web/src/pages/settings/DeviceSettings.tsx`:
- Around line 145-157: Gate the selected-device detail rendering in
DeviceSettings so it only renders once profile?.id has resolved; do not pass an
empty fallback as actingProfileId. Preserve the existing selected-device
behavior after resolution, including the DeviceDetail props and mobile back
handling, and apply the same guard to the corresponding alternate detail branch.

---

Minor comments:
In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md`:
- Around line 429-431: Update current-device detection in the devices handler to
compare the authenticated profile ID together with device_id, rather than
device_id alone, so only the matching profile/device pair is marked current. Add
coverage for the same physical device registered under different profiles,
ensuring only the correct profile row is detected as current.
- Around line 210-213: Update the documented canManageHousehold interface to
include the UserRepo dependency used by internal/api/handlers/devices.go,
matching the call canManageHousehold(r, store, h.UserRepo, h.ProfileTokens).
Keep the wrapper and existing call-site behavior unchanged, or explicitly
document how store provides UserRepo if that is the intended design.
- Around line 245-262: Update the cross-account profile tests around
identityForSessionKey to set the caller actor explicitly and separate
authorization outcomes: non-primary and PIN-unverified callers must receive 403
before profile lookup, while an authorized primary or admin must reach the
caller-owned store lookup and receive 404 for an external profile. Ensure each
test uses the appropriate actor and validates the required status and error
details.

In `@internal/api/handlers/devices_test.go`:
- Around line 164-173: Update TestListDevices_IncludesProfileName so the failure
message does not index body.Devices unless the slice is non-empty; guard the
diagnostic access while preserving the existing length and ProfileName
assertions.

In `@internal/api/handlers/devices.go`:
- Around line 234-252: Update the device-settings clearing flow around
DeleteAllDeviceSettings to collect legacy keys from user_device_settings before
deletion, including player.next_up_prompt_seconds and any other keys served by
HandleGetDeviceSetting. Merge these keys with the canonical keys before
publishing user_settings.changed events, while preserving the existing deletion
and forget-device behavior.
- Around line 126-145: Update the sorting logic in the devices handler’s
sort.SliceStable comparator to compare parsed or normalized LastSeenAt
timestamps rather than raw strings. Preserve descending last-seen ordering and
the existing DeviceID ascending tie-breaker, handling the timestamp formats
returned by SQLite and PostgreSQL consistently.

In `@web/src/components/settings/DeviceList.tsx`:
- Around line 122-143: Update the sections built in the useMemo block to carry a
stable profile id alongside each profile section, using the profile id as the
section identity even when profile_name is empty or duplicated. Then update the
section rendering near the existing title-based React key to use that stable id,
while preserving the displayed title and existing recency-group behavior.

In `@web/src/components/settings/DeviceSettingGroups.test.tsx`:
- Around line 21-24: Update the jsdom setup in DeviceSettingGroups.test.tsx so
the hasPointerCapture and scrollIntoView stubs use separate capability checks.
Keep the window guard for each, but assign each HTMLElement prototype method
independently when that method is unavailable.

In `@web/src/components/settings/DeviceSettingGroups.tsx`:
- Around line 177-179: Update the constraint message generation around
effective.stored_value and permitted to format values using the same display
helpers used by the controls, including formatBitrate for
playback.max_bitrate_kbps and human-readable boolean formatting. For keys
without a display formatter, use a value-free constraint message instead of
interpolating raw contract values.
- Around line 211-222: Update the panel Button in the control/definition.type
branch to disable it when either disabled is true or onOpenPanel is absent, and
replace the hardcoded text with definition.label. Keep the existing onClick
behavior and styling unchanged.
- Around line 368-397: Expose each numeric setting’s maximum in the
effective-settings response and its client-facing type, then ensure
numericSelectChoices uses that ceiling when filtering BITRATE_CHOICES_KBPS.
Preserve the stored effective value independently; do not derive the ceiling
from effective.value.

In `@web/src/lib/documentTitle.ts`:
- Line 48: Move the devices title entry from the current settings title mapping
into SETTINGS_TITLES, changing its key to "devices" while retaining the "Your
Devices" value. Ensure resolveSettingsDocumentTitle("/settings/devices")
resolves to that title and remove the obsolete "settings/devices" entry.

In `@web/src/pages/settings/DeviceSettings.tsx`:
- Around line 60-62: Update the useMyDevices result destructuring in
DeviceSettings to capture isError and the query retry handler, then render a
distinct device-load failure state with a retry action instead of the “No
devices yet” empty state when isError is true. Preserve the existing empty-state
message for successful requests that return no devices.

In `@web/src/pages/SettingsLayout.tsx`:
- Around line 312-323: Update the settings search index created by settingIndex
in SettingsLayout so its labels use the device-search contract: replace “Video
quality” with “Preferred quality”, “Data use limit” with “Maximum bitrate”,
“Play Dolby Vision films as HDR10” with “Dolby Vision Profile 7 fallback”, and
“How video fills the screen” with “Video sizing”; leave the other labels
unchanged.

---

Nitpick comments:
In `@internal/api/handlers/devices_test.go`:
- Around line 365-384: Add a test alongside
TestForgetDevice_PrimaryMayForgetHouseholdDevice that calls HandleForgetDevice
with a household-scoped request whose profile_id does not exist on the account,
then assert the response is HTTP 404 and verify the targeted device remains
unchanged.

In `@internal/api/handlers/household_test.go`:
- Around line 140-153: Add a subtest alongside the existing valid-token case to
cover a stale policy revision: configure stubUserRepo with AccessPolicyRevision
2, mint the primary profile token with PolicyRevision 1, and assert
canManageHousehold returns access.ErrProfileUnverified. Preserve the existing
valid-token test unchanged and handle token-minting errors consistently.

In `@internal/api/handlers/settings_values_test.go`:
- Around line 1187-1210: Make captureAuditLogs safe against concurrent use by
protecting writes to the captured buffer and reads performed by the returned
closure with a mutex-backed io.Writer wrapper. Keep the existing slog default
restoration in captureAuditLogs, and ensure record parsing reads a synchronized
snapshot so captured audit records cannot race or leak across tests.

In `@internal/userstore/storetest/settingvalues.go`:
- Around line 52-54: Add a ForgetDevice subtest alongside the existing
DeviceExists case in the shared store conformance suite. Register deviceApple
for profiles p1 and p2, invoke ForgetDevice for p1, then assert DeviceExists for
p2 and deviceApple remains true, exercising this behavior across all backends.

In `@web/src/components/settings/DeviceSettingGroups.tsx`:
- Line 337: Update the EffectiveSetting type to declare permitted_values?:
unknown[], then change the permitted assignment in DeviceSettingGroups to read
effective?.permitted_values directly and remove the structural cast.

In `@web/src/hooks/queries/devices.test.ts`:
- Around line 58-68: Update the “gives each profile its own cache entry” test to
pass an explicit profileId for both effectiveSettingsQueryKey calls, using
different profile ids while keeping the shared deviceId and keys unchanged. This
removes reliance on activeProfileId().

In `@web/src/lib/deviceSettingGroups.ts`:
- Around line 37-79: Update EXPLICIT_GROUPS to use SettingKey as its record key
type and HIDDEN_KEYS to be a Set of SettingKey rather than string-based
collections. Import or reuse the existing SettingKey type, preserving current
values and membership behavior so invalid or renamed manifest keys fail at
compile time.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2e1bce7b-1bf4-42b7-b702-36fe5c51983b

📥 Commits

Reviewing files that changed from the base of the PR and between 73488d1 and 5530770.

📒 Files selected for processing (31)
  • docs/superpowers/plans/2026-07-31-user-facing-device-settings.md
  • internal/api/handlers/devices.go
  • internal/api/handlers/devices_test.go
  • internal/api/handlers/household.go
  • internal/api/handlers/household_test.go
  • internal/api/handlers/profiles.go
  • internal/api/handlers/settings_audit.go
  • internal/api/handlers/settings_values.go
  • internal/api/handlers/settings_values_test.go
  • internal/api/router.go
  • internal/userdb/settings.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/settings.go
  • internal/userstore/store.go
  • internal/userstore/storetest/settingvalues.go
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/settings/DeviceList.test.tsx
  • web/src/components/settings/DeviceList.tsx
  • web/src/components/settings/DeviceSettingGroups.test.tsx
  • web/src/components/settings/DeviceSettingGroups.tsx
  • web/src/hooks/queries/devices.test.ts
  • web/src/hooks/queries/devices.ts
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/settingValues.ts
  • web/src/lib/deviceSettingGroups.test.ts
  • web/src/lib/deviceSettingGroups.ts
  • web/src/lib/documentTitle.ts
  • web/src/pages/SettingsLayout.tsx
  • web/src/pages/settings/DeviceSettings.tsx
  • web/src/player/hooks/useTranscodeQuality.ts


**Goal:** Let a person see and change the device settings for every device they watch on, from whichever device they are holding — and let the household parent do the same for everyone on the account.

**Architecture:** No new storage and no schema change. `user_devices` and `user_setting_values` are already keyed `(user_id, profile_id, device_id, …)` and both list queries are already account-wide, so the work is authorization plus routes plus UI. Two identity widenings on the existing canonical settings API, each behind a guard: a caller may name a `device_id` other than the request's own (checked against `user_devices`), and a household parent may name a `profile_id` other than their own (checked by the existing `canManageHouseholdProfiles`). One new self-service device registry endpoint, deliberately profile-filtered by default. One new settings page reusing `SettingsGroup`/`SettingRow`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Reconcile the audit design with the no-storage constraint.

Line 9 says there is no new storage or schema change. Task 7 requires a settings audit sink and refers to a stored audit row. Define the durable storage, schema, retention, and failure behavior. If the audit is log-only, remove the stored-row requirement and specify its delivery guarantees.

Also applies to: 276-293

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` at line 9,
Reconcile the plan’s “no new storage and no schema change” statement with Task
7’s settings audit requirement. Update the audit design to define durable
storage, schema, retention, and failure behavior, or make it explicitly log-only
by removing stored-audit-row requirements and documenting delivery guarantees.

Comment on lines +172 to +177
- [ ] **Step 1: Write failing tests**

- `TestForgetDevice_RemovesSettingsAndRegistryRow`
- `TestForgetDevice_RejectsOtherProfilesDevice` → 404
- `TestClearDeviceSettings_KeepsRegistryRow`
- `TestForgetDevice_IsIdempotent` — a second call returns 204, not 500

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Resolve the forget-device idempotency contract.

The plan requires both a 404 for another profile's device and a 204 for a repeated forget. After the first forget removes the registry row and settings, a repeated request is indistinguishable from an unknown device. The provided internal/api/handlers/devices.go implementation therefore returns 404 when !owned && len(keys) == 0. Choose a state or status contract that can implement both requirements.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 172 - 177, Revise the forget-device plan and related tests to define a
state/status contract that distinguishes an already-forgotten device from an
unknown device owned by another profile, while preserving 404 for the latter and
204 for repeated requests. Update the ForgetDevice flow and
TestForgetDevice_IsIdempotent, TestForgetDevice_RejectsOtherProfilesDevice, and
TestForgetDevice_RemovesSettingsAndRegistryRow to validate the chosen contract.

Comment on lines +185 to +187
- [ ] **Step 3: Implement both routes**

Reuse `DeleteSettingValuesForDevice` (`internal/userstore/store.go:216`) and `DeleteAllDeviceSettings`. Publish `user_settings.changed` once per cleared key so other devices invalidate — or once for the device if a batch event shape is added; do not skip the event.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Keep device clearing atomic across storage generations.

internal/userdb/settings.go:206-226 already deletes both settings formats in one transaction. The provided handler first calls DeleteSettingValuesForDevice and then calls DeleteAllDeviceSettings. If the second call fails, the first delete has already committed. Use one atomic store operation for the complete cleanup, then forget the registry row only after cleanup succeeds.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 185 - 187, The device-clearing flow must delete both settings storage
generations atomically instead of separately committing
DeleteSettingValuesForDevice before DeleteAllDeviceSettings. Add or reuse a
single store operation that performs the complete cleanup in one transaction,
then remove the registry row only after that operation succeeds; preserve the
required user_settings.changed event publication.

Comment on lines +262 to +272
In `identityForSessionKey`: when `profile_id` is present and differs from the session profile, require `canManageHousehold`; on failure return 403 without disclosing whether the profile exists. Then resolve the profile through the caller's **own** store, exactly as `internal/access/resolver.go:73-86` does — a profile from another account is simply absent, which yields the 404 and preserves the cross-account boundary for free.

For `GET /api/v1/devices`, add `?scope=household` (default: own profile only). Do not make household the default; the plain screen must stay private by construction.

- [ ] **Step 4: Run and verify GREEN, then the full package**

```bash
go test ./internal/api/handlers/ -v
```

**Record in the PR:** this widening does not create a new capability. The primary profile can already rewrite a sibling's canonical settings rows through `PUT /profiles/{id}` (`internal/api/handlers/profiles_settings_sync.go:218-231`), and `GET /profiles` (`profiles.go:263`) already returns every sibling's resolved preferences to any profile with no gate. All profiles share one login session, so `X-Profile-Id` is self-asserted for PIN-less profiles — stated in-repo at `internal/api/middleware/auth.go:180-184`. This task replaces an unlabelled path with a guarded, audited one.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Treat remote device editing as a new capability.

Existing profile-level settings access does not establish access to another profile's device-scoped settings. This PR adds cross-profile, cross-device reads and writes. Document this as a new capability and make the Apple and Android follow-up explicit rather than optional.

As per coding guidelines, client-visible API changes generally require coordinated follow-up in both client repositories.

Also applies to: 490-492

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-31-user-facing-device-settings.md` around
lines 262 - 272, Revise the plan’s capability statement to classify
cross-profile, cross-device device-settings reads and writes as a new
capability, rather than claiming the change only replaces an existing path. Make
the Apple and Android client follow-up explicit and required, including
coordinated updates in both client repositories for the client-visible API
changes, and update the related repeated section as well.

Source: Coding guidelines

Comment on lines +52 to +57

// UserRepo and ProfileTokens enable household management: a primary profile
// naming another profile on its own account. Both nil means the widening is
// simply unavailable — never that it is unguarded.
UserRepo userLookup
ProfileTokens *access.ProfileTokenService

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect canManageHousehold and verifyProfileToken for nil-dependency handling.
set -euo pipefail

fd -t f 'household.go' internal/api/handlers --exec ast-grep outline {} --items all

fd -t f 'household.go' internal/api/handlers --exec rg -n -C 6 'func canManageHousehold|func verifyProfileToken|UserRepo|ProfileTokens|== nil' {}

Repository: Silo-Server/silo-server

Length of output: 2574


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- household policy ---'
sed -n '1,125p' internal/api/handlers/household.go

printf '%s\n' '--- settings handler call path ---'
rg -n -C 12 'mayActForProfile|canManageHousehold|newValuesTestHandler|ProfileTokens|UserRepo' \
  internal/api/handlers/settings_values.go internal/api/handlers/settings_values_test.go

Repository: Silo-Server/silo-server

Length of output: 50379


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- test handler construction ---'
sed -n '27,82p' internal/api/handlers/settings_values_test.go

printf '%s\n' '--- direct policy verifier ---'
python3 - <<'PY'
from pathlib import Path

source = Path("internal/api/handlers/household.go").read_text()
start = source.index("func canManageHousehold(")
end = source.index("\n}\n\n// verifyProfileToken", start)
body = source[start:end]

checks = {
    "admin bypass precedes dependency checks": "if apimw.IsAdmin(ctx) {\n\t\treturn true, nil\n\t}" in body,
    "non-PIN primary bypasses token verification": 'if active.PINHash == "" {\n\t\treturn true, nil\n\t}' in body,
    "nil dependencies are checked only by verifyProfileToken": "users == nil || tokens == nil" not in body,
}
for name, passed in checks.items():
    print(f"{name}: {'PASS' if passed else 'FAIL'}")
if not all(checks.values()):
    raise SystemExit(1)
PY

Repository: Silo-Server/silo-server

Length of output: 2365


Guard household-management widening when dependencies are nil.

canManageHousehold returns true for a primary profile without a PIN before it calls verifyProfileToken, so nil UserRepo and ProfileTokens do not disable profile_id widening. Add a fail-closed dependency check before the primary-profile decision, while preserving the server-admin bypass.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/settings_values.go` around lines 52 - 57, Update
canManageHousehold to return false when UserRepo or ProfileTokens is nil before
evaluating the primary-profile-without-PIN path, while keeping the existing
server-admin bypass ahead of this dependency check.

Comment on lines 923 to 941
if scope == settingscontract.ScopeProfileDevice {
identity.DeviceID = deviceMetadataFromRequest(r).DeviceID
// A device may be named explicitly so one device can manage another's
// settings — the screen that lists your devices edits them in place.
// Unlike the profile above, that is safe to accept from the query only
// because the device is then checked against this profile's registry.
named := strings.TrimSpace(r.URL.Query().Get("device_id"))
identity.DeviceID = named
if identity.DeviceID == "" {
identity.DeviceID = deviceMetadataFromRequest(r).DeviceID
}
if identity.DeviceID == "" {
writeError(w, http.StatusBadRequest, "bad_request",
"X-Silo-Device-Id header is required for a device override")
return userstore.SettingIdentity{}, false
}
if named != "" && !h.deviceBelongsToProfile(w, r, identity.ProfileID, named) {
return userstore.SettingIdentity{}, false
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

The device ownership check keys off the device_id parameter instead of the target profile. Both paths call deviceBelongsToProfile only when the query supplies device_id. When a primary profile widens profile_id and omits device_id, both paths fall back to the caller's own header device and pair it with the sibling profile. The header device is exempt from the check for a good reason — lazy registration means a new device has no registry row yet — but that reason applies only to the caller's own profile.

  • internal/api/handlers/settings_values.go#L923-L941: verify the resolved identity.DeviceID whenever identity.ProfileID differs from the acting profile, not only when device_id was named. Otherwise the write stores a profile_device row for a device the target profile does not own, and Line 440 suppresses registration, so that row never appears in the target profile's device list and cannot be cleared by forgetting a device.
  • internal/api/handlers/settings_values.go#L584-L600: apply the same rule before resolution. Once rc.ProfileID is widened at Line 592, either require an explicit device_id or validate the header device from Line 579 against rc.ProfileID, so the resolver does not read overrides for a device outside that profile.

Add a test for the widened-profile, omitted-device_id request on both the write and effective-read paths. internal/api/handlers/settings_values_test.go currently covers only the case where device_id is present.

📍 Affects 1 file
  • internal/api/handlers/settings_values.go#L923-L941 (this comment)
  • internal/api/handlers/settings_values.go#L584-L600
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/settings_values.go` around lines 923 - 941, Update
internal/api/handlers/settings_values.go:923-941 so the resolved
identity.DeviceID is checked with deviceBelongsToProfile whenever
identity.ProfileID differs from the acting profile, including when the device
came from the header; preserve the own-profile lazy-registration exception.
Update internal/api/handlers/settings_values.go:584-600 to apply the same
validation before resolution after rc.ProfileID is widened, requiring an
explicit device_id or validating the header device against rc.ProfileID. Add
coverage in internal/api/handlers/settings_values_test.go for widened-profile
requests without device_id on both write and effective-read paths.

Comment thread internal/api/router.go
Comment on lines +2183 to +2190
if deviceHandler != nil {
r.Route("/devices", func(r chi.Router) {
r.Use(apimw.RequireProfile)
r.Get("/", deviceHandler.HandleListDevices)
r.Delete("/{device_id}", deviceHandler.HandleForgetDevice)
r.Delete("/{device_id}/settings", deviceHandler.HandleClearDeviceSettings)
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Add a capability endpoint for the device routes.

The /devices routes are a new API feature. They are registered only when deviceHandler != nil, and deviceHandler requires deps.UserStoreProvider. A client therefore cannot tell "this server does not serve device settings" from "this path does not exist on this version" except by reading a 404. The settings feature already follows the required pattern with /settings/capability and /settings/contract/capabilities.

Expose an equivalent probe, for example GET /devices/capability, that returns a 200 with an explicit enabled flag.

Based on coding guidelines: "Expose capability endpoints for new API features instead of relying on client version sniffing."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/router.go` around lines 2183 - 2190, Add a GET
/devices/capability endpoint within the deviceHandler route registration,
alongside HandleListDevices and the device settings routes. Return HTTP 200 with
an explicit enabled flag, and ensure the endpoint is available only when
deviceHandler is registered.

Source: Coding guidelines

Comment on lines +224 to +254
if (control === "switch") {
return (
<span className="order-1 flex min-h-11 items-center sm:order-none sm:min-h-0">
<Switch
checked={value === true}
disabled={disabled}
onCheckedChange={(checked) => onChange(settingKey, checked)}
/>
</span>
);
}

if (control === "slider" || control === "stepper") {
const numeric = typeof value === "number" ? value : Number(definition.defaultValue ?? 0);
return (
<div className="order-1 flex w-full items-center gap-3 sm:order-none sm:max-w-[260px]">
<Slider
value={[numeric]}
min={definition.minimum}
max={definition.maximum}
step={definition.step}
disabled={disabled}
onValueCommit={(values) => onChange(settingKey, values[0] ?? numeric)}
/>
<span className="text-muted-foreground min-w-16 text-right text-xs font-medium">
{numeric}
{definition.unit ? ` ${definition.unit}` : ""}
</span>
</div>
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'slider' web/src/components/ui --exec cat -n {}
fd -t f 'switch' web/src/components/ui --exec cat -n {}

Repository: Silo-Server/silo-server

Length of output: 4242


🏁 Script executed:

#!/bin/bash
set -e

printf '%s\n' '--- DeviceSettingGroups.tsx: control and label context ---'
cat -n web/src/components/settings/DeviceSettingGroups.tsx | sed -n '90,125p;195,330p'

printf '%s\n' '--- Slider wrapper usages and thumbLabels support ---'
rg -n -C 3 'thumbLabels|<Slider|aria-label=' web/src --glob '*.{js,jsx,ts,tsx}' | head -n 300

printf '%s\n' '--- DeviceSettingControl callers and panel handlers ---'
rg -n -C 5 'DeviceSettingControl|onOpenPanel|control === "panel"|type === "object"' web/src/components/settings --glob '*.{js,jsx,ts,tsx}'

Repository: Silo-Server/silo-server

Length of output: 41209


🏁 Script executed:

#!/bin/bash
set -e

python3 - <<'PY'
from pathlib import Path
import re

control = Path("web/src/components/settings/DeviceSettingGroups.tsx").read_text()
slider = next(Path("web/src/components/ui").glob("*slider*")).read_text()
switch = next(Path("web/src/components/ui").glob("*switch*")).read_text()

checks = {
    "switch control has no accessible-name prop": (
        "<Switch" in control and 'aria-label={definition.label}' not in
        control[control.index('if (control === "switch")'):control.index('if (control === "slider"')]
    ),
    "slider control has no thumbLabels prop": (
        "<Slider" in control and "thumbLabels=" not in
        control[control.index('if (control === "slider"'):control.index("const options")]
    ),
    "Switch forwards props to its primitive root": (
        "<SwitchPrimitive.Root" in switch and "{...props}" in switch
    ),
    "Slider forwards props to its primitive root": (
        "<SliderPrimitive.Root" in slider and "{...props}" in slider
    ),
    "Slider maps thumbLabels to each primitive thumb": (
        "aria-label={thumbLabels?.[index]}" in slider
    ),
}

for name, result in checks.items():
    print(f"{'PASS' if result else 'FAIL'}: {name}")
PY

Repository: Silo-Server/silo-server

Length of output: 409


Give switch and slider controls accessible names.

Add aria-label={definition.label} to Switch. Pass thumbLabels={[definition.label]} to Slider; the wrapper applies labels to slider thumbs, not the root element.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/DeviceSettingGroups.tsx` around lines 224 - 254,
Add accessible names in the control rendering logic: update the Switch component
in the switch branch with aria-label={definition.label}, and pass
thumbLabels={[definition.label]} to the Slider component in the slider/stepper
branch so its thumb receives the label.

Comment on lines +15 to +28
export function useMyDevices(options?: { household?: boolean; enabled?: boolean }) {
const household = options?.household ?? false;

return useQuery({
queryKey: deviceKeys.list(household ? "household" : "own"),
queryFn: async () => {
const result = await api<UserDeviceListResponse>(
`/devices${household ? "?scope=household" : ""}`,
);
return result.devices ?? [];
},
enabled: options?.enabled ?? true,
staleTime: 30 * 1000,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for cache resets / profile-switch handling and how other keys scope by profile.
fd -e ts -e tsx . web/src --exec rg -n 'clear\(\)|resetQueries|removeQueries|activeProfileId|X-Profile-Id' {} +

Repository: Silo-Server/silo-server

Length of output: 48711


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- device query definitions and usages ---'
rg -n -A12 -B4 'deviceKeys|useMyDevices' web/src/hooks web/src | head -240
printf '%s\n' '--- profile and query-cache lifecycle ---'
cat -n web/src/App.tsx | sed -n '230,305p'
cat -n web/src/hooks/useAuth.tsx | sed -n '220,315p'
printf '%s\n' '--- current-profile state and selectors ---'
cat -n web/src/hooks/useCurrentProfile.ts | sed -n '1,100p'
rg -n -A8 -B8 'selectedProfileId|setSelectedProfile|switch.*profile|profile.*switch' web/src --glob '*.ts' --glob '*.tsx' | head -260
printf '%s\n' '--- server profile resolution ---'
rg -n -A18 -B8 'HandleListDevices|X-Profile-Id|scope=household' internal web --glob '*.go' --glob '*.ts' --glob '*.tsx' | head -260

Repository: Silo-Server/silo-server

Length of output: 50379


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact query key implementation ---'
fd -i 'devices.ts' web/src --exec cat -n {} \;
printf '%s\n' '--- exact profile-switch handlers ---'
rg -n -A35 -B15 'selectedProfileId|setSelectedProfileId|selectProfile|onProfileChange|switchProfile' web/src --glob '*.ts' --glob '*.tsx' | head -320
printf '%s\n' '--- all query-cache clearing calls with surrounding code ---'
rg -l 'queryClient\.clear\(\)|qc\.clear\(\)|removeQueries|resetQueries' web/src --glob '*.ts' --glob '*.tsx' | while read -r f; do
  echo "### $f"
  rg -n -A12 -B12 'queryClient\.clear\(\)|qc\.clear\(\)|removeQueries|resetQueries' "$f"
done

Repository: Silo-Server/silo-server

Length of output: 50380


🏁 Script executed:

#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
for name in [
    "web/src/hooks/queries/devices.ts",
    "web/src/hooks/useCurrentProfile.ts",
    "web/src/App.tsx",
    "web/src/hooks/useAuth.tsx",
]:
    p = Path(name)
    print(f"### {name}")
    lines = p.read_text().splitlines()
    for i, line in enumerate(lines, 1):
        if name.endswith("devices.ts") or name.endswith("useCurrentProfile.ts"):
            if i <= 130:
                print(f"{i:4}: {line}")
        elif name.endswith("App.tsx"):
            if 230 <= i <= 300:
                print(f"{i:4}: {line}")
        else:
            if 220 <= i <= 315:
                print(f"{i:4}: {line}")
PY
printf '%s\n' '--- profile selection call sites ---'
rg -n -A20 -B12 'selectedProfileId|setSelectedProfileId|currentProfileId' web/src --glob '*.ts' --glob '*.tsx' | head -400

Repository: Silo-Server/silo-server

Length of output: 39130


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- relevant source excerpts ---'
sed -n '1,120p' web/src/hooks/queries/devices.ts
sed -n '250,295p' web/src/App.tsx
sed -n '235,310p' web/src/hooks/useAuth.tsx
printf '%s\n' '--- profile-selection references ---'
rg -n -A15 -B10 'selectedProfileId|setSelectedProfileId|currentProfileId' web/src --glob '*.ts' --glob '*.tsx' | head -240

Repository: Silo-Server/silo-server

Length of output: 24967


Scope the own-device query key by profile.

QueryCacheManager removes several profile-scoped queries on profile switch, but it does not remove deviceKeys entries. Since HandleListDevices uses X-Profile-Id, deviceKeys.list("own") can retain the previous profile's devices until a refetch. Include the active profile ID in the own-scope key.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/hooks/queries/devices.ts` around lines 15 - 28, Update useMyDevices
and the own-scope deviceKeys.list query key to include the active profile ID,
while leaving the household key unchanged. Reuse the existing active-profile
source used by the hook so profile switches produce distinct own-device cache
entries and do not reuse the previous profile’s data.

Comment on lines +145 to +157
) : selected ? (
<div className={cn(!showDetailOnMobile && "hidden xl:block")}>
<DeviceDetail
key={`${selected.profile_id}:${selected.device_id}`}
device={selected}
actingProfileId={profile?.id ?? ""}
now={now}
onBack={() => {
setShowDetailOnMobile(false);
window.scrollTo({ top: 0, behavior: "instant" });
}}
/>
</div>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not treat an unresolved profile as a different profile.

actingProfileId is profile?.id ?? "" at line 150. If useCurrentProfile has not resolved yet, actingProfileId is "", so forSomeoneElse becomes true for every device. Two consequences follow. The page shows the warning "You're changing X's settings, not your own." for the viewer's own device. And targetProfileId is set, so reads and writes send profile_id, which the server rejects with 403 for a non-primary profile.

Render the detail pane only after the profile id resolves.

🛠️ Proposed fix
-        ) : selected ? (
+        ) : selected && profile?.id ? (
           <div className={cn(!showDetailOnMobile && "hidden xl:block")}>
             <DeviceDetail
               key={`${selected.profile_id}:${selected.device_id}`}
               device={selected}
-              actingProfileId={profile?.id ?? ""}
+              actingProfileId={profile.id}

Also applies to: 234-236

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/settings/DeviceSettings.tsx` around lines 145 - 157, Gate the
selected-device detail rendering in DeviceSettings so it only renders once
profile?.id has resolved; do not pass an empty fallback as actingProfileId.
Preserve the existing selected-device behavior after resolution, including the
DeviceDetail props and mobile back handling, and apply the same guard to the
corresponding alternate detail branch.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c969025d6c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +241 to +245
if forget && isRegistry {
if err := registry.ForgetDevice(r.Context(), profileID, deviceID); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to forget device")
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Unregister push tokens when forgetting a device

When the forgotten installation has an enabled push_devices row, this removes only its user_devices registry entry. The push table has no foreign key to that registry, and its registration is removed only through PushDeviceService.Unregister, so the device can continue receiving private notifications after disappearing from the device list and being reported as forgotten. Include push-registration cleanup in the forget operation.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +334 to +337
function permittedOptions(settingKey: SettingKey, effective: EffectiveSetting | undefined) {
const definition = SETTING_DEFINITIONS[settingKey];
const all = optionsFor(definition);
const permitted = (effective as { permitted_values?: unknown[] } | undefined)?.permitted_values;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include runtime language suggestions in device selectors

When the effective audio or subtitle language is an open tag outside the vendored contract floor, or the server discovers additional languages in this deployment's catalog, the effective response supplies them in suggested_values; this code discards that field and builds the select exclusively from optionsFor(definition). The current value then has no matching item and catalog-specific languages cannot be selected, so build language options from both effective.value and effective.suggested_values as the other settings screens do.

Useful? React with 👍 / 👎.

<DeviceSettingGroups
settings={settings}
ownerLabel={ownerLabel}
disabled={setValue.isPending || clearValue.isPending}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Disable controls during destructive device mutations

After a user confirms Clear all or Forget, the setting controls remain enabled because this flag ignores clearDevice.isPending and forgetDevice.isPending. A quick toggle can therefore race the destructive request: it may recreate a setting after clear, or pass the device-existence check before forget deletes the registry row and then leave an orphan user_setting_values row afterward. Disable all editing and competing device actions while either destructive mutation is pending.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment thread internal/api/router.go
Comment on lines +2187 to +2191
r.Route("/devices", func(r chi.Router) {
r.Use(apimw.RequireProfile)
r.Get("/", deviceHandler.HandleListDevices)
r.Delete("/{device_id}", deviceHandler.HandleForgetDevice)
r.Delete("/{device_id}/settings", deviceHandler.HandleClearDeviceSettings)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Publish a capability for the new device-management API

These new /api/v1/devices routes and the named-device/profile settings behavior are exposed without adding any corresponding capability flag or endpoint; HandleGetCapabilities still reports only the pre-existing generic settings features. Apple, Android, and other clients therefore cannot distinguish a server that supports this API from an older one without probing routes or version-sniffing. Publish a dedicated capability before clients adopt the new behavior.

AGENTS.md reference: AGENTS.md:L112-L119

Useful? React with 👍 / 👎.

Comment on lines +73 to +76
"ui.theme",
"ui.text_scale",
"ui.text_weight",
"ui.high_contrast",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep device-scoped appearance overrides editable

ui.theme, ui.text_scale, ui.text_weight, and ui.high_contrast are valid remote profile_device settings, but hiding them here leaves no user-facing device-scope editor because the Appearance and Accessibility screens only write profile defaults. When an existing client or admin has created one of these overrides, it continues to win during resolution while the user cannot inspect or reset it, making profile appearance changes seem ineffective on that device. Render these preference keys here or add device-scope controls to their owning screens; only remembered browse state should be excluded.

Useful? React with 👍 / 👎.

Quick104 and others added 2 commits August 1, 2026 01:24
…anguage scans

GET /settings/values/effective computed suggested language values with
three sequential full-catalog scans on every request. On a 439k-item
deployment that took ~25s, dominated by the subtitle listing whose UNION
deduplicated ~5M unnested track rows.

- Deduplicate each subtitle arm before merging (UNION ALL of two
  DISTINCT arms instead of UNION across all rows) and bound the result
  with the facet LIMIT: 22.8s -> ~8.5s of per-arm work on that catalog.
- Cache the observed lists per (list kind, access scope) for 15 minutes
  and collapse concurrent misses with singleflight.
- Run the three lookups concurrently, and cap a cold-cache wait at 2s:
  the response ships with the contract floor while the detached scan
  finishes and fills the cache for the next request.

Part of the device settings screen work; the regression itself shipped
in #526.

Co-Authored-By: Claude Fable 5 <[email protected]>
…free entry

Deployment-observed suggestions now decorate catalog.metadata_language
only — original_language is one indexed DISTINCT scan (~0.2s on a 439k
item catalog) and feeds the metadata-exceptions panel, where observed
data is load-bearing. The audio and subtitle track listings (up to tens
of seconds of media-file walking) are no longer queried for settings at
all, which also removes the TTL cache and singleflight added to manage
them.

Those pickers keep the contract's authored floor and gain an explicit
escape hatch instead: a shared LanguageSelect with an "Other…" entry
that accepts a BCP 47 tag, previews the resolved language name, and
refuses invalid tags. The settings are open language_tag values, so a
typed tag needs no server change, and a stored off-floor value already
renders through the current-value merge. The device screen hides the
free entry when policy pins permitted_values.

The browse facet queries keep the subtitle UNION ALL rewrite from the
previous commit; catalog browse still lists observed track languages.

suggested_values on playback.audio_language and
playback.subtitle_language now returns only the contract floor plus the
stored value — Android and Apple pickers need the same free-entry
affordance as follow-up.

Co-Authored-By: Claude Fable 5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8f54e798d4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}: DeviceSettingGroupsProps) {
return (
<div className="space-y-4">
{groupDeviceSettings().map((group) => (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Filter controls to the selected device platform

When the selected device is on a platform excluded by a definition's platforms metadata, this unconditionally renders every device-scoped key. For example, web browsers and iPhones are offered player.match_frame_rate even though it is limited to Android/Android TV/tvOS, while TVs are offered the mobile-only player.orientation_mode; these controls successfully save overrides that the target client does not consume. The contract design explicitly requires platform-inapplicable settings to be hidden (docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md:1057), so pass the selected device platform into this component and filter the grouped definitions before rendering.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/catalog/browse.go`:
- Around line 894-895: Update the SQL filter in queryDistinctStrings to use
BTRIM(value) <> '' instead of value <> ''. Apply this before the LIMIT so
whitespace-only language values are excluded prior to limiting results.

In `@web/src/components/settings/LanguageSelect.tsx`:
- Around line 75-78: Update commitDraft in
web/src/components/settings/LanguageSelect.tsx at lines 75-78 to pass the
computed canonical draftTag to onValueChange instead of raw trimmed input.
Update web/src/components/settings/LanguageSelect.test.tsx at lines 46-62 to use
valid input that normalizes differently and assert the callback receives the
canonical tag.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2db1dbca-d640-4844-9e23-bd807fce5214

📥 Commits

Reviewing files that changed from the base of the PR and between c969025 and 8f54e79.

📒 Files selected for processing (10)
  • internal/api/handlers/settings_values.go
  • internal/api/handlers/settings_values_test.go
  • internal/catalog/browse.go
  • web/src/components/settings/DeviceSettingGroups.tsx
  • web/src/components/settings/LanguageSelect.test.tsx
  • web/src/components/settings/LanguageSelect.tsx
  • web/src/lib/languageOptions.ts
  • web/src/pages/settings/LibrarySettings.tsx
  • web/src/pages/settings/PlaybackSettings.tsx
  • web/src/pages/settings/SubtitleAppearanceSettings.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/settings/DeviceSettingGroups.tsx

Comment on lines +894 to +895
LIMIT %d
`, fromClause, mediaFileJoin, browseFilterPrefix(whereClause), fromClause, mediaFileJoin, browseFilterPrefix(whereClause), catalogFacetMaxValues)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- browse.go outline ---'
ast-grep outline internal/catalog/browse.go --match 'queryDistinctStrings' --view expanded 2>/dev/null || true

printf '%s\n' '--- SQL and helper context ---'
sed -n '840,920p' internal/catalog/browse.go
sed -n '1225,1280p' internal/catalog/browse.go

printf '%s\n' '--- related query definitions and tests ---'
rg -n -C 3 'catalogFacetMaxValues|queryDistinctStrings|BTRIM|TRIM|subtitle|language' internal/catalog --glob '*.go' --glob '*.sql'

Repository: Silo-Server/silo-server

Length of output: 50380


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- limit definition and helper call sites ---'
rg -n -C 4 'catalogFacetMaxValues|queryDistinctStrings\(' internal/catalog/browse.go internal/catalog --glob '*.go' \
  | head -n 240

printf '%s\n' '--- language column definitions and migrations ---'
rg -n -C 6 'subtitle_language_codes|audio_language_codes|external_subtitles|subtitle_tracks' . \
  --glob '*.sql' --glob '*.go' --glob '*.md' \
  | head -n 500

printf '%s\n' '--- schema constraints and write paths for subtitle metadata ---'
rg -n -C 5 'subtitle_language_codes|external_subtitles|subtitle_tracks' . \
  --glob '*.sql' --glob '*.go' \
  | rg -v 'search_indexer_test|detail_batch_equivalence_test|query_builder.go|browse.go' \
  | head -n 500

Repository: Silo-Server/silo-server

Length of output: 50381


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- migration 121 language canonicalization ---'
sed -n '1,155p' migrations/sql/121_canonicalize_language_codes.sql

printf '%s\n' '--- all language normalization helpers and write-time transformations ---'
rg -n -C 8 'canonical_language_code|jsonb_track_language_codes|LanguageCode|language.*Trim|Trim.*language|strings\.(TrimSpace|ToLower).*language|language.*strings\.' . \
  --glob '*.go' --glob '*.sql' \
  | head -n 700

printf '%s\n' '--- compact behavioral model of LIMIT-before-filter ---'
python3 - <<'PY'
limit = 1000
raw = [' ' * 1] + [f'lang-{i:04d}' for i in range(1000)]
sql_rows = [v for v in sorted(set(raw)) if v is not None and v != ''][:limit]
returned = [v for v in sql_rows if v.strip()]
print(f'sql_rows={len(sql_rows)} returned={len(returned)}')
print(f'last_sql_row={sql_rows[-1]!r} last_returned={returned[-1]!r}')
PY

Repository: Silo-Server/silo-server

Length of output: 50379


Filter whitespace-only languages before LIMIT.

WHERE value <> '' admits whitespace-only values. queryDistinctStrings removes them after LIMIT, so they can reduce the returned languages below catalogFacetMaxValues. Use BTRIM(value) <> ''.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/catalog/browse.go` around lines 894 - 895, Update the SQL filter in
queryDistinctStrings to use BTRIM(value) <> '' instead of value <> ''. Apply
this before the LIMIT so whitespace-only language values are excluded prior to
limiting results.

Comment on lines +75 to +78
const commitDraft = () => {
if (!draftTag) return;
onValueChange(trimmed);
setDraft(null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Persist and test canonical language tags.

The free-entry flow computes draftTag but persists raw trimmed input. This permits non-canonical language values and the current test does not detect it.

  • web/src/components/settings/LanguageSelect.tsx#L75-L78: pass draftTag to onValueChange.
  • web/src/components/settings/LanguageSelect.test.tsx#L46-L62: use a valid input that normalizes differently and assert the callback receives the canonical value.
📍 Affects 2 files
  • web/src/components/settings/LanguageSelect.tsx#L75-L78 (this comment)
  • web/src/components/settings/LanguageSelect.test.tsx#L46-L62
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/settings/LanguageSelect.tsx` around lines 75 - 78, Update
commitDraft in web/src/components/settings/LanguageSelect.tsx at lines 75-78 to
pass the computed canonical draftTag to onValueChange instead of raw trimmed
input. Update web/src/components/settings/LanguageSelect.test.tsx at lines 46-62
to use valid input that normalizes differently and assert the callback receives
the canonical tag.

@Rhainland Rhainland mentioned this pull request Oct 22, 2026
11 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant