21 KiB
21 KiB
spec, created, status
| spec | created | status |
|---|---|---|
| docs/specs/ui/requirements/relative-last-seen.md | 2026-08-16 | done |
Implementation Plan: Relative Last Seen in Account Security
Overview
Add a persisted per-user enum setting last_seen_display ("absolute" default | "relative") and
a select on the Active sessions card of /settings/account/security. In relative mode the Last seen
column renders a live-updating, locale-aware relative label with the absolute timestamp in a
fine-pointer tooltip or a coarse-pointer touch drawer. The setting follows the established
changes_panel_layout pattern end to end: JSON-blob user settings on the backend, boot-payload +
WS-push hydration on the frontend, and the shared manual-save settings flow in the UI.
Design decisions
- Shared manual save. The select edits a local draft. The shared
Save changesaction callsuseSettingsSaveContributorand persists the draft. The sharedResetaction restores the confirmed value. A failed save keeps the draft dirty so the user can retry. - Queued write with revision-aware confirmation. The contributor save uses
createQueuedUserSettingsSyncWithResponse. The draft lives in local component state and is never written into the store directly. The store'suserSettings.lastSeenDisplayis the confirmed baseline, updated by exactly two ingestion paths: a successful PATCH response mapped withmapUserSettingsResponse(response, current)and applied throughsetUserSettings(which discards older revisions), and a neweruser.settings.updatedWS snapshot through the existing handler path (mapUserSettingsData+ handler revision gate, unchanged per task 02). A save response reconciles the draft with the revision-gated store result, so a newer foreign snapshot wins. A failed save leaves the submitted draft in place. - Revision-gated draft reconciliation; no writer-id correlation or store metadata. The backend publishes the settings event before the PATCH response and broadcasts a full snapshot to every subscriber. A newer local draft stays visible while Save is in flight. The unchanged WebSocket handler applies own echoes and foreign snapshots to the confirmed store. After a successful response, the component reconciles the draft with the revision-gated store result. A failed save keeps the draft dirty for retry. A writer-id scheme is not needed because the shared settings provider owns Save and Reset, and the store remains the confirmed baseline.
- Default
"absolute"preserves current behavior for users who never opt in. formatRelativeTimefrom@/lib/i18n/formats(locale-aware, acceptsnow) renders the relative label; the shareduseNowhook drives the live update only while the cell is in relative mode (mounted in a dedicated child component so the interval is never created in absolute mode), with an age-aware cadence: tick every second while the timestamp is under a minute old (second-scale labels need live updates) and every minute once the age crosses a minute.- Exact time disclosure uses
@kandev/ui/tooltipwithformatDateTime(last_seen_at)on fine-pointer devices. Coarse-pointer devices use the shippeduseTouchDrawerand Drawer pattern to show the same timestamp after a tap.
Backend
apps/backend/internal/user/models/models.go: addLastSeenDisplay stringtoUserSettingswithjson:"last_seen_display"; addLastSeenDisplayAbsolute = "absolute"/LastSeenDisplayRelative = "relative"constants and aNormalizeLastSeenDisplayhelper (anything other thanrelativecoerces toabsolute).apps/backend/internal/user/store/sqlite.go: default"absolute"indefaultUserSettings; add the field to BOTH hand-built JSON codec paths (the model struct alone does not persist it):marshalUserSettingsPayloadmap entry, thescanUserSettingspayload struct field, and the scan assignment withNormalizeLastSeenDisplaycoercion. Guard the PATCH write against the read-modify-write lost-update race:UpsertUserSettingsPreservingTaskCreateLastUsedgains anexpectedRevisionparameter and its UPDATE gainsAND settings_revision = ?(SQLite and Postgres paths), returning a revision-conflict sentinel when zero rows match. The conflict is distinguished from a missing user explicitly: after a zero-row conditional UPDATE the repo existence-checks the user row; missing → the existing user-not-found error, present →ErrUserSettingsRevisionConflict(both drivers tested). The service routes ALL full-blob writers through one bounded read-apply-CAS-retry helper (read → apply patch → upsert with the read revision → on conflict re-read and re-apply the ORIGINAL patch, ~3 attempts): bothUpdateUserSettingsandClearDefaultEditorID(service.go:883-900 currently upserts once and would otherwise either fail to clear on conflict or bypass CAS and overwrite the setting), with exactly one event publication after the successful final write. The helper carries the IMMUTABLEtaskCreatePatchextracted from the original request (service.go:198-202) as a separate input passed to EVERY CAS attempt, and treats a non-empty task patch asappliedeven when the blob is otherwise unchanged (a task-create-only PATCH must not be classified no-op and dropped); a task-create-only PATCH under a forced conflict survives the retry, merges with the winner, increments the revision once on its own successful retry (the winner already bumped R to R+1, so the final revision is R+2), and emits the snapshot event (existing public behavior, service.go:197-206 / service_test.go:1257-1283). Every upsert callsite is updated: the store interface, both driver implementations, the controller/service test fakes, and the direct sqlite_test.go calls (~31/96/151/1274/1323/1379, passing the revision from the preceding read; the existing concurrent test at ~150 asserts conflict-and-retry semantics). Without this, a concurrent omitted-field PATCH (app-status-bar/review save) that read the pre-PATCH row can serialize a stale snapshot overlast_seen_displayat a newer revision, which the frontend then accepts as truth.apps/backend/internal/user/service/service.go: addLastSeenDisplay *stringtoUpdateUserSettingsRequest; addapplyLastSeenDisplay(trim, validate against the two values, reject otherwise) and call it fromapplyBasicSettings; add"last_seen_display": models.NormalizeLastSeenDisplay(settings.LastSeenDisplay)to the hand-builtpublishUserSettingsEventsnapshot map so the WSuser.settings.updatedpayload carries the field to every other tab. NO writer-id plumbing: the publisher signature stayspublishUserSettingsEvent(ctx, settings)(no direct test callsite changes needed:app_status_bar_visibility_test.go:44,service_test.go:1312, 1333, 1354, 1377, 1399, 1417), and pending-selection protection is entirely client-side (pending-write gating).apps/backend/internal/user/dto/dto.go: addLastSeenDisplaytoUserSettingsDTO(json:"last_seen_display"), map it inFromUserSettingsviamodels.NormalizeLastSeenDisplay(settings.LastSeenDisplay)(matching how every other enum-like setting is normalized at the API boundary, so a model assembled outside the store can never emit a non-canonical value); addLastSeenDisplay *stringto the DTOUpdateUserSettingsRequest.apps/backend/internal/user/controller/controller.go: passreq.LastSeenDisplayinto the service request. The controller test assertsreq.LastSeenDisplayreaches the service request (the REST handler and the WSwsUpdateUserSettingshandler share this one controller path, handlers.go:113, so one test covers both transports).apps/backend/internal/backendapp/boot_state_routes.go: maplastSeenDisplayinmapUserSettingsStatevia a small normalize helper (mirroringchangesPanelLayout(...)).
Frontend contracts
apps/web/lib/types/http-user-settings.ts:LastSeenDisplaytype ("absolute" | "relative");last_seen_display?: LastSeenDisplayonUserSettingsandUserSettingsUpdatePayload.apps/web/lib/types/http.ts: addLastSeenDisplayto the explicithttp-user-settingsre-export list (the established import surface; omitting it breaks type resolution for barrel consumers).apps/web/lib/state/slices/settings/types.ts:lastSeenDisplay: LastSeenDisplayonUserSettingsState(default"absolute"). NO client-only metadata field: pending-selection protection lives in the component (pending-write gating), so no writer-id/lastWriterId state exists to be wiped bymapUserSettingsResponsecallers that build from a fresh default state (use-layout-settings, layout-preset-selector, use-ensure-user-settings, hydration).apps/web/lib/ssr/user-settings.ts: default"absolute"forlastSeenDisplayincreateDefaultUserSettings;parseLastSeenDisplay(only"relative"accepted, else"absolute"); maplastSeenDisplayinbuildAppearanceFieldsviamapDefined.- The WS
user.settings.updatedhandler inapps/web/lib/ws/handlers/users.tspicks the field up throughmapUserSettingsDatawith its existing revision gate, UNCHANGED otherwise (own echoes are applied normally, so the store converges even if the component unmounts mid-write); addusers.test.tsassertions (valid value applies, unknown value normalizes to"absolute", omitted field leaves the current value, stale revision ignored), so the cross-tab producer→handler path is tested on both sides. apps/web/hooks/use-ensure-user-settings.test.ts(makeUnloadedSettings, lines ~47-110) builds a complete typedUserSettingsStateand gainslastSeenDisplay: "absolute"; audit remaining typed fixtures for the new required field.
Security page UI
apps/web/components/settings/account/security-settings.tsx:- Read
userSettings.lastSeenDisplayfrom the store inSessionsCard. - Add a labeled select (Absolute time / Relative time) in the card, above the table, with a
discovery target id
ACCOUNT_SETTINGS_TARGETS.lastSeenDisplayand self-documenting copy. - On change: keep the draft in local component state and mark the
SessionsCarddirty. Register the field withuseSettingsSaveContributor. The contributor'ssavesends a queuedcreateQueuedUserSettingsSyncWithResponse({ last_seen_display })write. The contributor'sdiscardrestores the confirmed store value. A failed save keeps the draft dirty and shows error copy so the shared Save action can retry. - Apply successful responses through
mapUserSettingsResponseintosetUserSettingsonly (never a raw store write).setUserSettingsdiscards older revisions, so a deferred PATCH response arriving after a newer cross-tab WS event cannot regress the value or revision. After the response, reconcile the draft with the revision-gated store result. A newer foreign value therefore wins when it supersedes the submitted response. - Extract a small
LastSeenCellcomponent: absolute mode rendersformatDateTime; relative mode mounts a tickinguseNowwrapper and renders aformatRelativeTime(last_seen_at, now)label. Fine-pointer devices use a focusable semantic trigger and aTooltipwith the absolute time. Coarse-pointer devices use an explicit tap trigger and the shippeduseTouchDrawerDrawer pattern to show the same absolute time. The cell validates the timestamp once; when unparseable it renders an empty cell with no disclosure surface (guarding theformatDateTimecontent, which throwsRangeErroron invalid dates).
- Read
apps/web/lib/settings-discovery/catalog/account.ts: addlastSeenDisplay: "setting-account-last-seen-display"target and akind: "control"discovery definition. The SessionsCard'sSettingsCardalready registers thesessionstarget and accepts exactly onediscoveryTargetId(settings-card.tsx:7-30), so the select's wrapper registers the new target separately withuseSettingsTargetRegistration(ACCOUNT_SETTINGS_TARGETS.lastSeenDisplay)(fromsettings-target-provider.tsx) rather than replacing the card's target; add a discovery-target test asserting both targets register and reveal.- i18n: new keys in
apps/web/src/locales/en/account.json(+ pseudo/pt-pt/zh-cn/zh-hk/zh-tw mirrors). Use plain punctuation (no em dash).
Tests
- Backend:
servicetest forapplyLastSeenDisplay(accept both values, reject invalid, nil no-op); apublishUserSettingsEventtest asserting the published event map carries the normalizedlast_seen_display(inservice/user_settings_cas_test.go; the existing publisher tests atservice_test.go:1312-1417stay untouched); store tests assertingdefaultUserSettings, a JSON round-trip of the new field throughmarshalUserSettingsPayload/scanUserSettings(stored"relative"reads back as"relative", stored unknown/empty coerces to"absolute", a later PATCH updates the stored JSON); adtotest assertingFromUserSettingsemits the canonical value for an unknown model value; acontrollermapping test assertingreq.LastSeenDisplayreaches the service request (the controller is a manual field-by-field adapter; an omission compiles and silently no-ops);boot_state_routes_test.gomapping test (relative passes through, unknown coerces to absolute); a barrier-based concurrent PATCH test proving an unrelated omitted-field write (started from the same initial revision) cannot revertlast_seen_display— both fields are present in the final row and the retry loop merges the loser's patch; a concurrentClearDefaultEditorID+ settings PATCH test (the editor is cleared ANDlast_seen_displaysurvives; TWO events are published, one per successful write with distinct revisions — the helper contract is exactly one event per successful final write, so two successful writes emit two events; a one-event outcome is only valid in the no-op scenario); a CAS-conflict no-op barrier test that FORCES callback re-evaluation (Clear's initial read completes seeingold-editor, its upsert is blocked; the PATCH commitsnew-editorat R+1 and publishes; Clear's stale upsert then conflicts, the retry fresh-reads the row, the callback re-evaluates with the immutableold-editorand returnsapplied=false→ no Clear write/event; assert read count >= 2,clearUpsertAttempts == 1(the forced stale CAS invocation that conflicts) withclearSuccessfulUpserts == 0,clearEvents == 0, exactly one PATCH event — counters named to distinguish attempts from successful commits) PLUS a separate fresh-read no-op test (Clear starts after the PATCH committed; immediate no-op, no conflict); repo zero-row tests for both drivers (missing user → user-not-found, revision mismatch →ErrUserSettingsRevisionConflict); direct repo tests migrated to CAS and MOVED to new focused files (the unique-revision concurrent test becomes one success + one conflict; the stale-blob merge tests re-read the current revision or assert the conflict) becausesqlite_test.go/service_test.goare over Revive's 800-line test-file limit and new code there fails the changed-file lint — new files:store/sqlite_last_seen_cas_test.go,service/user_settings_cas_test.go. The concurrent SERVICE tests use a dedicated synchronized fake (clones settings per read, models revision-conditional writes, records reads/upserts and events through synchronized state/channels, channel barriers for phase observation) — NOT the existingrecordingUserRepository/recordingEventBusfakes, which share one mutablegetSettingspointer, mutate unprotected fields, and append events unsynchronized (service_test.go:1741-1801), racing undergo test -race. - Frontend:
ssr/user-settings.test.tscoversparseLastSeenDisplayandmapUserSettingsData;users.test.tscovers valid, unknown, omitted, and stale WebSocket snapshots. TheSessionsCardtests cover the absolute default, relative labels, fine-pointer tooltip and keyboard focus, coarse-pointer drawer disclosure, live ticking, invalid timestamps, local draft state, shared Save and Reset actions, failed-save retry state, revision-gated PATCH responses, foreign WebSocket updates, and unmount/remount convergence. - E2E (desktop + mobile + cross-tab): add
apps/web/e2e/tests/auth/relative-last-seen.spec.ts(Desktop Chrome,authproject) grouped intest.describe.serial(single-shotsetupAdmin+ shared worker backend/DB require serial ordering), restarting the worker backend with auth on and its OWNKANDEV_DATABASE_PATH(auth setup is single-shot and worker DB is preserved across restart; without a dedicated DB the focused command collides with sibling auth specs), callingsetupAdmininbeforeAllso focused test runs are independent, logging in, opening/settings/account/security, switching to Relative time, saving through the shared Save action, and asserting a relative label renders with an absolute tooltip on hover. Restore the original setting infinally, and restart the baseline backend inafterAll. The same file adds a two-context cross-tab scenario that armswatchWs(pageA)BEFOREpageA.goto(it only sees sockets opened after it is called) AND arms the subscription wait (const subscriptionAck = watcher.waitForResponse("user.subscribe")) before the samegoto, then awaitssubscriptionAckafter navigation before tab B mutates (frames are not buffered andwaitForResponseonly records request ids once armed, so arming the wait before navigation is required to catch the ACK); the assertion is causal: tab B changes the setting, tab A observes the update via WS without a reload. Addapps/web/e2e/tests/auth/mobile-relative-last-seen.spec.ts(mobile-chromeproject, namedmobile-*so the project routes it) that spreads...devices["Pixel 5"]into a manualbrowser.newContext(manual contexts do not inherit project device options), asserts the resulting viewport width, uses its own DB +setupAdmin, operates the select with touch-nativetap()on the trigger and option, saves through the shared Save action, proves relative labels render without hover and without horizontal overflow, taps a relative label, and asserts the absolute stamp in the touch drawer. Restore the setting. The Last seen trigger and options get a mobile-appropriate touch target (min-h-11 / 44px at phone widths via responsive classes on this instance, per /mobile-parity — the shared Select defaults to 28px trigger/items), and the mobile E2E asserts the trigger's and option's bounding boxes meet 44px in the active dimension.
Implementation waves
Wave 1:
Wave 2:
Wave 3:
Wave 4:
Verification
make -C apps/backend test
cd apps/web && pnpm run typecheck && pnpm run lint:i18n components/settings/account/security-settings.tsx
cd apps/web && pnpm vitest run components/settings/account lib/ssr/user-settings.test.ts
cd apps/web && pnpm e2e:run --project auth tests/auth/relative-last-seen.spec.ts
cd apps/web && pnpm e2e:run --project mobile-chrome tests/auth/mobile-relative-last-seen.spec.ts
Risks
- The select shares the floating Save and Reset actions with the other
/settingsconfiguration controls. Its table preview updates from the local draft, while the durable setting changes only after Save. - Live ticking is wasted work if the user never switches to relative mode; the ticking interval is created only inside the relative-mode cell component, so absolute mode stays inert.
- Tooltip timing/positioning inside a table cell: use the standard Radix tooltip for fine-pointer devices. Coarse-pointer devices use the shipped Drawer pattern, and mobile E2E taps the label and asserts the visible absolute stamp.
- The hand-built backend JSON codec paths and the WS event snapshot are easy to miss because the model struct change alone looks sufficient; task 01 lists each path explicitly and tests the stored-JSON round trip and the published event map.
- The auth E2E project shares one worker backend whose SQLite DB survives restarts, and auth setup
is single-shot; both new specs must use dedicated
KANDEV_DATABASE_PATHvalues or the focused commands become order-dependent (theusers-self-actionspattern). - The PATCH write path is read-modify-write over a full settings blob; without expected-revision
CAS, a concurrent omitted-field PATCH can revert
last_seen_displayat a newer revision that the frontend accepts. CAS + bounded retry is in task 01; the barrier test pins it.