Skip to content

UX, tenancy hardening, invite/reset accounts & admin backoffice (UX-1…UX-7) - #157

Merged
spuentesp merged 42 commits into
masterfrom
ux/integration
Nov 25, 2026
Merged

spuentesp merged 42 commits into
masterfrom
ux/integration

Conversation

@spuentesp

Copy link
Copy Markdown
Owner

Implements docs/architecture/UX_TENANCY_BACKOFFICE_PLAN.md (UX-1 … UX-7).

What changed

  • Tenancy (UX-1): acting-owner assertions on lorebook, knowledge-pack, play-session, combat and game-system write tools; typed quota/tenancy errors re-raised through blanket 5xx wrappers (429/404, not 502); strict creator match for ingest jobs; share-link detail limited to player-safe fields; WS 4401/4404 handshake tests.
  • Provider keys (UX-4): admin-only shared pool; saving a key outside local mode requires MONITOR_PROVIDER_KEY_ENCRYPTION_KEY; no key echoes.
  • Accounts (UX-2): invite-only signup (MONITOR_SIGNUP_MODE=invite|open|closed), password reset by email (MONITOR_SMTP_*) or admin-issued link, single-session revoke; login return-to, forgot/reset pages, /settings/account, AuthGate skeleton + session-expired handling.
  • Admin (UX-3): Users / Invites / Usage / Providers tabs, confirmation dialogs, reset link, revoke sessions; admin_action structlog events.
  • GM Assistant (UX-5): page split into components, Prep → Run → Wrap-up stepper, first-run guide, shortcuts, cancel on AI panels, daily-limit message.
  • Auto GM (UX-6): PlayConsole split, reconnect/wait/cancel, POST /api/chat/{id}/rewind powering Undo / Edit-last-turn / Regenerate (refuses when canon already committed), canon pending badge, quick start, mobile pass.
  • Cross-cutting (UX-7): sidebar user menu, operator links hidden for non-admins, a11y labels / aria-live.

Verification

  • Backend: uv run pytest packages tests -n 4 — 10,553 passed, 236 skipped.
  • Frontend: vitest 783 passed; tsc --noEmit clean.
  • Strict mypy, ruff check, layer-dependency check clean. Sealed suites untouched.

Not verified

  • No live two-user pass against a real stack; SMTP delivery untested; ESLint not run (symlinked node_modules); no Playwright e2e for the new flows.
  • Rewind does not roll back an active NPC ConversationLoop's memory or the Mongo SceneLoop checkpoint.

🤖 Generated with Claude Code

Sebastian and others added 30 commits November 20, 2026 03:07
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Split the 1,936-line app/gm/page.tsx into focused panels under
components/gm/ (DiceRoller, RulesPanel, SessionNotebook, PlotHooksPanel,
ContradictionsPanel, SessionPrepPanel, ThreadsPanel, HandoutsPanel,
GMSelector) plus a shared ActiveToolPanel renderer used by both the
desktop tools column and the narrow single-panel view. page.tsx keeps
only layout and state. Behavior-preserving; gm/page.test.tsx still
passes unchanged (12/12).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- GmStepper component in the header: Prep narrows the tools column to
  session-prep/hooks/threads/handouts (desktop strip and narrow tab bar
  both filter); Run is the default view with the full tool set; Wrap-up
  opens the existing WrapUpModal flow.
- Wrap-up is transient: closing returns to the step it was opened from
  and never overwrites storage. Prep/run persist per universe in
  localStorage (try/catch, corrupt values ignored) under
  monitor.gm.step.<universeId>.
- SessionRecorder reports its active recording id so the page can mount
  WrapUpModal once (both layout instances used to be able to mount it);
  with no recording yet, a dialog explains what to do first.
- Tests: GmStepper.test.tsx (5) and page.stepper.test.tsx (4).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…, lib/auth-errors)

- AuthConfig gains signup_open / signup_invite_only / email_reset per the
  shared accounts contract; typed invite, session, token, reset-link and
  usage shapes.
- authApi: signup invite_token, change/forgot/reset password, session
  list/revoke-one/revoke-all, API token CRUD.
- adminApi: invites CRUD, admin password-reset link, revoke user sessions,
  usage summary + limit updates.
- lib/auth-errors: sanitizeNextPath (same-origin ?next=), context-aware
  auth messages (distinct banned/429/invite/expired-reset), per-field
  sign-up error extraction, absoluteUrl helper — with unit tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…expired toast

- PageSkeleton replaces the blank null while the session query loads and
  during a 401 redirect.
- On 401, AuthGate now redirects to /login?next=<pathname+search> (path
  sanitized through sanitizeNextPath) and toasts "session expired" only
  when the user actually had a session this SPA session.
- /forgot-password and /reset-password join /login as public paths that
  are never bounced to /login.
- QueryCache no longer toasts raw 401 bodies (AuthGate owns that story)
  and uses real ApiError status codes for client-error classification.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ages

Login:
- ?next= return-to, validated as a same-origin relative path (falls back
  to /), preserved across sign-in and sign-up.
- Show/hide password toggle, per-field sign-up validation plus server 422
  detail mapping, distinct banned (403) / rate-limited (429) banners.
- "Create account" hidden unless config.signup_open; invite-only mode shows
  "Have an invite?" and an invite-code field; ?invite=<token> opens
  sign-up prefilled and submits invite_token.

New public pages (excluded from AuthGate redirect):
- /forgot-password: always enumeration-safe 202 confirmation; when
  config.email_reset is false it tells the user to ask their admin for a
  reset link instead of sending anything.
- /reset-password?token=: client-side password confirmation, single-use
  <=1h token flow, expired/invalid token messaging, success notes that all
  sessions were signed out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- Profile card (read-only identity + role) from the existing /auth/me.
- Change password via POST /auth/password with per-state errors (wrong
  current password, length, mismatch) and a success toast noting that
  other sessions were signed out.
- Active sessions via GET /auth/sessions: revoke one (confirmation
  dialog; revoking the current session signs you out) and "sign out
  everywhere" via DELETE /auth/sessions.
- API tokens: create (optional expiry) with the raw value shown exactly
  once in a copy dialog, list with revoked state, revoke.
- Shared ConfirmDialog and CopyValueDialog built on DialogShell, which now
  exposes role="dialog"/aria-modal/aria-label for accessibility and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…-admins

- Footer gains a user menu (display name + email) with an Account link to
  /settings/account and Sign out (hidden in auth-disabled local mode);
  dismisses on outside click/Escape via useDismissRef.
- The Configuration section (label + /config link) is now operator-only
  alongside Admin — non-admins see only Lobby and Workbench.
- Sidebar tests updated for the new visibility rules plus user-menu
  coverage (account link, sign-out, local mode, outside-click dismiss).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…eusable panel

Move LLMTab and its helpers (AddProviderForm, ProviderCard,
TierAssignment, provider/role metadata) verbatim into
components/settings/LLMProvidersPanel.tsx so the admin Providers tab and
the Configuration page render the same component. config/page.tsx keeps
all other tabs; PROVIDER_META stays exported for the Agents tab's
provider badges. No behavior change — covered by the existing
config/page.test.tsx (7 passing).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- Page becomes a tab shell gated on me.user.is_admin (non-admins get the
  operator-access notice; loading shows a skeleton instead of a blank).
- Users: keeps search/ban/unban/role; ban and role changes now go through
  a confirmation dialog with the ban reason inside the ban dialog; adds
  "Reset password" (one-time link shown once in a copy dialog, absolute
  URL from window.location.origin + url_path) and "Revoke sessions".
- Invites: create (optional email, expiry hours, default 168), absolute
  link copy dialog, list with active/used/expired/revoked badges, revoke
  with confirmation.
- Usage: daily tokens/calls vs caps from GET /admin/usage, inline editing
  of token/call caps and the exempt flag via PUT /admin/usage/{id}/limits,
  over-cap badges per row and in the header.
- Providers: renders the extracted shared LLMProvidersPanel.
- Tests: 10 vitest cases across access control and all four tabs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- When no universe is selected the center column shows a guided
  first-run state (pick a world → choose a system → record) with a
  link to Forge, instead of the empty recorder placeholder.
- Small dismissible tour card atop the page covering the dice roller,
  rules lookup and session recorder (plus the r/n/j/k shortcuts);
  dismissal remembered in localStorage (monitor.gm.tour.v1) with
  try/catch, so a storage failure only means the card shows again.
- Tests: FirstRunGuide.test.tsx (4), page.firstrun.test.tsx (1);
  page.test.tsx still 12/12.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- useGmShortcuts: r focuses the dice roller (switches the narrow panel
  when needed), n opens and focuses the scratchpad, j/k walk the page's
  [data-gm-entry] entries (dice history, recorder transcript, threads).
  Ignored inside inputs/textareas/selects and with ctrl/meta/alt.
- GmOfflineBanner: ConnectionStatus-pattern health poll; when the
  backend/LLM is unreachable (or degraded) it says AI panels won't
  respond but dice and notes still work — no raw errors.
- Larger touch targets under xl on tab strips, stepper, selector
  selects and primary panel actions (max-xl:min-h-11).
- Tests: useGmShortcuts.test.tsx (7), GmOfflineBanner.test.tsx (3),
  page.shortcuts.test.tsx (3); regressions green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- api.ts: optional signal accepted by gmApi.detectContradictions,
  gmApi.captureInsights and searchApi.universeSearch (forwarded to the
  existing req() abort plumbing; universeSearch strips it out of the
  query string).
- ContradictionsPanel: Detect is now cancellable — Cancel appears while
  running, aborts the request and never shows an error for a user cancel.
- AskTheWorldPanel: Cancel question while consulting canon; the question
  is handed back to the composer instead of being lost.
- SessionRecorder: per-entry insight analysis shows an Analyzing state
  with a Cancel control; in-flight analyses are aborted on supersede and
  unmount. Logging stays non-blocking.
- Tests: ContradictionsPanel.test.tsx (4), SessionRecorder insights
  cancel (1 added, 20 total), AskTheWorld cancel + signal assertion
  (3 total). AskTheWorld's existing call assertion extended with the
  new signal arg (contract adaptation, not a weakening).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Add components/gm/gmErrors.ts: RATE_LIMIT_MESSAGE ("Daily limit reached
- resets 00:00 UTC. Ask your admin to raise it."), isRateLimit (status
duck-typed so it also works when tests mock @/lib/api), gmErrorMessage
(fallback per panel) and gmErrorText.

Applied to every GM panel error display: hooks, contradictions, session
prep, handouts, ask-the-world, combat, lookups, prep-to-table, session
log, audio transcript, knowledge and the wrap-up modal. Non-429 errors
keep their existing panel copy (behavior unchanged).

Tests: gmErrors.test.ts (3), ContradictionsPanel 429 case (5 total),
AskTheWorld 429 case (4 total); all touched panel suites green
(Combat 8, TableLookups 5, PrepToTable 8, SessionLog 5, Audio 6,
Knowledge 8, WrapUp 9) plus page suites.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… play sessions, combat, game systems

Close the write-tool breadth gaps named in MULTI_TENANCY_PLAN §4:

- tenancy.py: resolvers/assertions for play sessions, combat encounters
  (via scene), character scope (universe:/card/entity chain mirroring
  require_playable_character), game systems, and rule overrides.
- lorebook: create/bulk/update/delete and scan-config writes assert the
  character scope.
- knowledge packs: owner-stamped creates, update/delete/apply/publish
  assert the pack owner; apply also asserts the target universe; the
  owner stamp tool refuses stamping a foreign owner.
- play sessions: create asserts the universe; update/add-scene resolve
  the session universe and assert.
- combat: encounter tools assert scene→universe; session tracker tools
  assert the universe carried in the request.
- game systems: create stamps the acting owner (dedup preserves an
  existing owner); update/delete assert an owner-stamped doc; builtin
  and ownerless (ingestion/legacy) systems stay shared — documented
  behavior. Rule overrides assert their story/scene scope.

Tests: test_tenancy_write_guards_families.py — one foreign-owner
refusal + one no-owner-unchanged test per family, plus matching-owner
happy paths. Shared fakes gain create_index/find_one_and_update/
insert_many/replace_one and the new tool modules.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…rash

- New suites for the extracted panels: DiceRoller (4), RulesPanel (2),
  SessionNotebook (3), PlotHooksPanel (3), SessionPrepPanel (2),
  ThreadsPanel (3), HandoutsPanel (3), GMSelector (3) — empty states,
  server-authoritative rolls, generate flows, 429 copy, thread actions.
- RulesPanel: rules were rendered with useState inside system.rules.map,
  so the hook count changed between the loading and loaded renders and
  any system with >=1 rule crashed the panel. Extracted RuleRow with its
  own state; behavior (expand/collapse) unchanged.
- Full touched-file sweep: 27 vitest files, 143 tests, all green;
  tsc --noEmit clean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- quota.ts: recognise HTTP 429 (ApiError + raw body text) and rewrite
  turn-failure details to "Daily limit reached - resets 00:00 UTC. Ask
  your admin to raise it." (UX-4/UX-6 copy)
- quickStart.ts: one-click session payload with SetupPanel defaults
  (first universe, first system, dramatic/narrative/autonomous-GM)

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- ConnectionBanner: visible reconnecting/connecting/disconnected state
  (auto backoff lives in useChatWebSocket; this makes it legible)
- TurnWaitBar: "GM is thinking / writing" elapsed time with a local
  cancel — the chat WS protocol has no server-side cancel frame
- TurnControls: Regenerate re-sends the last player action via the
  existing POST /chat/{id}/send; edit-last-turn and undo are hidden
  because no backend endpoint exists

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Inline badge when the session's story has GM-proposed canon changes
awaiting review, linking to /forge/review. Reuses GET
/stories/{id}/canon-queue (same query as CanonReviewPanel).

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Behavior-preserving split of the 1075-line PlayConsole (P-18):

- playConsoleHelpers.ts: pure helpers (OOC wrap, Begin-Story gate,
  image-suggestion extraction), re-exported from PlayConsole so
  existing imports keep working
- hooks/usePlaySession: sessions query, active-session selection,
  session-state/benchmark queries, all session mutations
- hooks/usePlaySocket: wraps useChatSession with reconnect status,
  GM-thinking elapsed timer, and a local turn cancel
- hooks/usePlaySuggestions: quick-action chips + image-suggestion
  dismissal state
- PlayHeader: header bar (tone/roll menus, phase chips, skip/begin,
  drawer toggles, canon badge)
- PlaySidePanel: right column; collapsible overlay drawer below xl
- SessionList: hidden below md unless opened as a drawer
- SetupPanel: optional one-click Quick start entry
- Console wires ConnectionBanner, TurnWaitBar, TurnControls,
  quota-aware failures, aria-live streamed region, quick start

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The GM payload carries roll_breakdown alongside roll_detail; the bubble
previously hid the breakdown whenever a dice card rendered. Surface it
as a "Reasoning" block under the card (legacy-only branch unchanged).

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
One-click Quick start creates a session with shared defaults (same
helper as the play console) and navigates to /play?session=; the
NewCampaignWizard stays as the advanced path. Phone padding on the
lobby shell; NotificationProvider mock added to the page test.

P-18, UX-6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Composer root padding responsive (px-3 below sm) — minimal edit in
features/chat; recap modal body padding responsive with more scroll
height. Side panels and session list become drawers below md/xl in
the preceding split commit.

P-18, UX-6, UX-7

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Handlers that normalized every exception into a 500/502/503 swallowed
QuotaExceededError and OwnerViolationError before the app-level handlers
in monitor_ui.main could map them to 429 / the generic 404.

Insert `except (QuotaExceededError, OwnerViolationError): raise` before
the blanket `except Exception` clauses (only where the block raises an
HTTP 5xx) in:

- image_gen.py (provider + storage 502s)
- gm_tools.py (LLM routes, combat routes, prep/clock/lookup/share)
- entities.py (502 sites not already covered)
- light_rp.py (chat start/reply/graduate 502s)
- openai_compat.py (upstream LM + session open/send 502s)

Log-only and release-and-re-raise blocks were left alone (the latter
already propagate the original error).

Tests: test_typed_error_http_mapping.py (gm_tools, entities, light_rp,
openai_compat — quota -> 429 readable message, owner violation -> 404)
and two portrait tests in test_image_gen.py for the same contract.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… (UX-2)

Migration 4 adds single-use signup invites and <=1h password-reset tokens,
both stored as SHA-256 hashes only. user_create_with_invite consumes the
invite and creates the account in one transaction (conditional UPDATE, so
a race or a duplicate-account rollback never burns a token);
password_reset_consume marks the token used, sets the new password and
revokes ALL sessions in one transaction, without touching is_banned.

Schemas gain UserCreate.invite_token, PasswordForgotRequest and
PasswordResetRequest. FakePostgres mirrors the new client methods for the
hermetic UI-backend suite.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…-2, UX-3)

MONITOR_SIGNUP_MODE (invite default | open | closed) gates password signup
and Google first-login; invite mode consumes a single-use token atomically
with account creation, and the invite rides the OAuth round-trip via a
one-shot cookie. /api/auth/config reports signup_open, signup_invite_only
and email_reset.

POST /api/auth/password/forgot always answers the same 202 {ok:true} for
known and unknown logins (rate-limited per IP and per account through the
login limiter; email scheduled on a daemon thread so SMTP latency and
failures never reach the caller — structlog warning only).
POST /api/auth/password/reset redeems a hashed <=1h single-use token and
revokes every session without un-banning.

Admin surface: create/list/revoke invites, issue one-time reset links,
revoke a user's sessions — all require_admin, all emitting structlog
admin_action events (actor_id, target_id, action) alongside ban/unban/
role/usage-limits. Hermetic suite defaults to open signup via the root
conftest; PUBLIC_ROUTES gains only forgot/reset, and the cross-tenant
suite gains the explicit non-admin case for the invite/reset operator
routes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
env.example documents MONITOR_SIGNUP_MODE, the one-shot OAuth invite
cookie, MONITOR_PUBLIC_URL and the MONITOR_SMTP_* block (blank host =
email disabled). MULTI_TENANCY_PLAN section 5 gains the same rows plus a
note on how invite/reset tokens are stored and consumed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sebastian and others added 12 commits November 20, 2026 04:20
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Findings: no production path ever stamped ingestion_jobs.owner_id (the
create callers all omit it, mongodb_set_ingestion_job_owner had no
callers) and _convert_ingestion_job_doc dropped owner_id from responses,
so the ingest router's "strict creator match" actually failed closed for
EVERY job in enforced mode, while the shared resolver silently fell back
to universe ownership.

Make the strict creator match the real rule everywhere:

- ingestion_jobs tool: create stamps owner from the acting-owner context
  (explicit param wins); the response converter round-trips owner_id.
- ingest router: _run_ingest_in_thread carries the authenticated
  creator and _capture_job stamps it (upload, rescan, resume flows);
  new _stamp_job_owner helper is best-effort and never fails a run.
- book_stage: decomposition jobs inherit the source job's owner.
- ownership.require_ingestion_job_owner: strict creator match,
  mirroring ingest._check_job_owner — universe ownership no longer
  grants access; ownerless/missing jobs get the generic 404 (they were
  already invisible to owner-scoped list filters).

Tests: owner stamping + round-trip (test_ingestion_job_tools.py),
resolver divergence/ownerless/missing + stamp helper + creator route
(test_ingest_ownership.py), decomposition owner inheritance
(test_book_service.py).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Audit results (fixes + what was already sound):

Already covered, unchanged: token entropy (secrets.token_urlsafe(32) =
256 bits, pinned by test_token_is_unguessable_and_url_safe), expiry and
revocation rejection in ShareAgent.resolve_share (agent tests), owner+
universe predicated revoke/publish toggles (tool tests), published-only
listing with defense-in-depth filtering, spoiler/witnessed-facts
visibility, per-(IP, token) rate limiting, and generic 404s for
unknown/revoked/expired/draft/foreign.

Gap fixed: GET /share/{token}/recap|handout/{id} returned the full
SharedArtifact, exposing the GM's owner_id plus universe_id,
source_fact_ids, session_id and published to unauthenticated token
holders. New PlayerArtifact response model carries only the player-safe
fields (id, story_id, type, title, content, spoiler_level,
scope_character_id, updated_at); the router maps through
_to_player_artifact. Markdown export unchanged (title + body only).

Test: test_recap_detail_exposes_only_player_safe_fields pins the
allow-list and the absence of every internal field.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ng session

test_unauthenticated_ws_rejected_before_accept now asserts the close code
(4401 from get_current_ws_principal's WebSocketException), and a new
test proves a nonexistent session id closes with the same 4404 as a
foreign one (plan D4: missing and foreign are indistinguishable).
Foreign-session 4404 was already covered.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… key echoes

- llm_mgmt: _require_encryption_for_key_save refuses POST/PUT/duplicate
  of any provider api_key with a clear 503 naming
  MONITOR_PROVIDER_KEY_ENCRYPTION_KEY when MONITOR_AUTH_DISABLED=false
  and the env key is unset (keyless saves stay allowed). Local mode
  keeps the plaintext path and the one-time startup warning.
- Env auto-seed withholds API keys (profiles still created) under the
  same condition instead of silently writing plaintext.
- _mask_key decrypts first so the shown last-4 is the real key's last-4
  even for Fernet rows; responses still never contain the key.
- Google test/list calls move the key from the URL query into the
  x-goog-api-key header (httpx exception messages echo URLs), and
  test_provider redacts the key from any error string it returns.

429 messaging: the app handler already returns QuotaExceededError.
user_message (readable, 00:00 UTC, "Ask an admin"); tests now pin the
"admin" pointer (test_quota HTTP path + new unit test).

Tests: test_llm_provider_key_hardening.py (8: non-admin 403, 503 gates
on create/update/duplicate, keyless allowed, encrypted save with no
plaintext echo, local-mode plaintext allowed, 429 wording) and
test_test_provider_error_response_never_contains_the_key.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…_PLAN §4

Section 4 now reflects: the five write-tool families guarded (with the
deliberate game-system/pack-create exceptions spelled out), blanket 5xx
wrappers closed, strict ingest-job creator match + stamping paths,
share-link audit outcome, and the UX-4 provider-key encryption gate;
remaining breadth (visual identities, conversation turns, session
recorder entries, resolutions, GM notes, parties, tone libraries) stays
listed. Status header notes the 2026-11-20 pass; §1's covered-tool list
matches §4.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…flight gates

POST /api/chat/{session_id}/rewind removes the final player message and every
GM/system message after it from the in-process _MESSAGES cache, the MongoDB
store and the shared Redis message cache. Before any mutation it gates:

- 409 while a turn is in flight — REST sends mark the session for the whole
  turn, WS frames mark it via an async-generator wrapper whose finally runs
  on every exit path (idempotent per-socket pop);
- 409 with "The GM's last turn already changed canon; it can't be rewound."
  when the exchange's proposals are already accepted/committed — the check
  and the pending -> rejected updates (reason "rewound") go through the
  data-layer proposal tools only, never Neo4j (CanonKeeper rule);
- 404 when the transcript has no player message.

The exchange's still-pending proposals are rejected, session fields keyed to
it (pending consequence/dice, latest_* state) are cleared or re-derived, and
the cached scene/preplay loops are dropped so the next turn rebuilds clean.
ConversationLoop has no history-trim API and is deliberately left alone.

Tests: test_chat_rewind.py — 17 hermetic cases; chat in-flight globals added
to the shared cache-reset fixture.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- test_cross_tenant: B calling POST /api/chat/{id}/rewind on A's session gets
  the generic 404 ({"detail": "Not found"}) and A's transcript is byte-for-byte
  unchanged; the route added to the by-kind chat-session case, and the
  generated sweep picks it up automatically as a session_id route.
- test_route_auth_coverage: anonymous POST /api/chat/{id}/rewind answers 401.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- chatApi.rewind (POST /chat/{id}/rewind) + RewindResult type.
- TurnControls now renders all three controls: Undo once any player message
  exists, Edit/Regenerate only when the final player message is a plain
  action (dice/roll messages keep their own flow); all disabled while a
  turn is in flight.
- PlayConsole shares one rewind flow: it removes the excised exchange from
  the local messages view (then refetches state/sessions), Edit pre-fills
  the composer with the server-returned last_player_text, Regenerate
  rewinds first and re-sends that text — the player message is never
  duplicated in the transcript. Refusals (409 canon / 409 in flight / 404)
  surface through notify with the backend's readable detail.

Tests: TurnControls.test.tsx (12 cases), rewind.test.ts (10 cases);
npx tsc --noEmit clean.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@spuentesp
spuentesp merged commit 5ecabe9 into master Nov 25, 2026
5 checks passed
@spuentesp
spuentesp deleted the ux/integration branch November 25, 2026 04:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant