From 5166c92fc7ca134fa81fb788a7f16431e208ce4d Mon Sep 17 00:00:00 2001 From: Dave Liu <7david12liu@gmail.com> Date: Thu, 13 Aug 2026 17:21:40 -0700 Subject: [PATCH] Restore People-finder focus after search --- IMPLEMENTATION_PLAN.md | 2 + SECURITY.md | 1 + SYSTEM_DESIGN.md | 2 + docs/officers/EVENTS_SHOP_MEMBERS.md | 108 +++++++- .../members/AdminMemberDirectory.test.tsx | 243 ++++++++++++++++++ .../admin/members/AdminMemberDirectory.tsx | 42 +++ 6 files changed, 397 insertions(+), 1 deletion(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 4127210..731a4fd 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -185,6 +185,8 @@ Exit gate: **MEMBERS-DIRECTORY-001K current source boundary:** [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) changes only inbound returned saved-photo admission in the preserved connected Account service. A photo's exact canonical base64 must decode to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, in addition to the existing exact object, MIME, dimensions, and version contract. A malformed response becomes only **Invalid member directory response.** without raw-byte, provider-value, or caught-detail output. The actual Account component-to-actual-service path, with only Firebase Functions mocked, proves mislabeled bytes stop before a saved-thumbnail image or data URL. Structurally admitted but browser-undecodable bytes retain the version-scoped, byte-free **Photo unavailable** fallback and **Remove current saved photo** action. Outbound JPG, PNG, and WebP upload admission and exact bytes remain unchanged. Availability stays `false`, so the default branch and live #623 preview remain inert. #639 changes no Account component, People finder, Function, Rule, index, schema, package, workflow, backend, provider, account, sign-in, production data, deployment, biometric processing, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. +**MEMBERS-DIRECTORY-001L current source boundary:** [#641](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/641) changes only search-settlement keyboard focus in the preserved connected officer People finder. A valid explicit search records an intent only after request-ID creation admits `pending`, only when the persistent name input or Search button owns focus, and only as the exact operation symbol plus that origin. On that current operation's result-card, empty-result, or fixed-failure render, the intent is consumed: the already-focused origin is left alone; body, root, absent, or disconnected focus returns to the same now-enabled origin; and any other connected focus chosen during the request is preserved. Programmatic or outside-focused submit creates no intent. Editing and Clear remove obsolete intent; validation and request-ID failure never enter `pending`; and application change, administrator change, unmount, or stale resolution or rejection cannot move focus. Clear retains its existing zero-ID, zero-call disposal and input focus. The handoff creates no request ID, search, retry, Clear action, result, audit, service call, or data URL. Existing normalization, native pending controls, response and result behavior, privacy bounds, `AdminGuard`, and stale fences remain unchanged. Availability stays `false`, so the default branch and live #623 preview remain inert. #641 changes no data movement, page structure, Account path, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in, production data, deployment, biometric processing, or connected/live behavior. #507 still owns privacy approval, scoped authorization, isolated staging, backend-first deployment/readback, the reviewed availability flip, connected publication, and live proof. + ### Phase 5 — End-to-end qualification **Issue:** TEST-001 plus final closure evidence from all prior phases diff --git a/SECURITY.md b/SECURITY.md index 287627b..e9f4f04 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -107,6 +107,7 @@ These entries are implementation evidence, not a production risk-acceptance deci | Source-only uncertain-change recovery containment for RISK-042 | MEMBERS-DIRECTORY-001I [#635](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/635) gives the preserved connected Account branch a component-lifetime uncertainty marker for an ordinary mutation failure or failed authoritative post-mutation readback. Failed and repeated **Reload settings** reads retain the fixed **We could not confirm that change** warning, keep photo and finder mutation controls hidden, and cannot restore discarded draft bytes or data URLs. A successful guarded authoritative profile read clears uncertainty and displays the returned state. Initial load failures and failed confirming reads after definitive mutation rejection remain generic unavailable; that generic message no longer globally promises **No setting was changed**. Reload creates no request ID or visibility, upload, or removal mutation. Generated-only tests cover repeated failures, eventual authoritative success, generic failures, zero mutation retries, discarded bytes, and stale application/account reload fences. | The marker preserves truthful uncertainty only within one mounted application-and-account component lifetime; it is not provider acknowledgement, durable mutation evidence, reconciliation, deletion proof, or authorization. Generic unavailable state deliberately does not infer whether a prior change occurred. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, service/server contract, Firebase, provider, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | | Source-only recovery-focus containment for RISK-042 | MEMBERS-DIRECTORY-001J [#637](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/637) gives the preserved connected Account branch one explicit recovery-focus intent for a user-initiated uncertain mutation, failed authoritative post-mutation readback, or failed confirming read after definitive rejection. The intent is tied to the current mounted application-and-account lifetime. A Reload-created intent is additionally bound by the next load effect to that exact load identity. Only the matching current unavailable or unknown transition focuses the rendered **Reload settings** action. Repeated failed reloads focus each replacement action. Initial or background load failure has no intent and does not steal focus; successful authoritative reload clears the intent without redirecting focus to an unrelated ready control. Application change, account change, unmount, and stale completion remain focus-inert. Generated-only tests cover all three mutations, both readback-failure classes, repeated uncertain and generic reload failures, successful reload, outside focus, application/account changes, unmount, zero retry or request-ID creation, and the unchanged unavailable default. | Programmatic focus is accessibility state, not provider acknowledgement, authorization, durable reconciliation, deletion proof, or evidence that a stale load became current. It creates no service call, mutation, automatic retry, draft restoration, data URL, or new data flow. The source-controlled availability value stays `false`, and live #623 remains inert. No page structure, service/server contract, Function, Rule, index, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | | Source-only saved-photo response containment for RISK-042 | MEMBERS-DIRECTORY-001K [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) makes the preserved connected Account service admit an inbound returned saved photo only when the existing exact object, `image/webp`, 256×256 dimensions, and UUID version contract contains canonical base64 that decodes to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11. Any failure returns only **Invalid member directory response.** without rendering or logging raw bytes, a provider value, or caught detail. A real Account component-to-real-service test with only `firebase/functions` mocked proves mislabeled bytes stop before a saved-thumbnail image or data URL. Structurally admitted but browser-undecodable bytes retain the version-scoped, byte-free **Photo unavailable** fallback and enabled **Remove current saved photo** action without another callable. Outbound JPG, PNG, and WebP admission and exact bytes remain unchanged. | RIFF/WEBP markers are structural admission, not full decoding, safe image proof, authenticity, server-state proof, authorization, or provider acknowledgement; header-shaped hostile bytes can still reach the browser decoder, so the byte-free render fallback remains required. The source-controlled availability value stays `false`, and live #623 remains inert. No Function, Rule, index, schema, package, workflow, photo query, facial recognition, matching, embedding, similarity, biometric processing, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use only generated non-face test bytes; do not inspect or upload a real photo. | +| Source-only search-focus containment for RISK-042 | MEMBERS-DIRECTORY-001L [#641](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/641) gives the preserved connected People finder one exact-operation focus intent after a valid query and request ID admit `pending`, and only when the persistent name input or Search button owns focus. Current result-card, empty-result, and fixed-failure settlement consumes the intent after render. The already-focused origin is left alone; body, root, absent, or disconnected focus returns to the same now-enabled origin; and another connected element focused during the request retains focus. Programmatic or outside-focused submit creates no intent. Editing, Clear, local validation failure, request-ID failure, application or administrator change, unmount, and stale resolution or rejection clear or fail the guards. Generated-only tests cover both origins and all three outcomes, deliberate outside focus, retained-origin focus, local failures, Clear, context changes, unmount, one exact request, and the unavailable default. | Programmatic focus is accessibility state, not authorization, search correctness, provider acknowledgement, audit proof, membership evidence, or live behavior. It stores no query, name, result, photo, account ID, request ID, or service value and creates no request ID, search, retry, Clear action, result, audit, service call, or data URL. Existing response/privacy bounds and name-only search plus human comparison of voluntary thumbnails remain unchanged; never add a photo query, face recognition, matching, embedding, similarity, biometric processing, totals, export, or roster authority. The source-controlled availability value stays `false`, and live #623 remains inert. No data movement, page structure, service/server contract, Function, Rule, index, Firebase or provider configuration, account, sign-in, production data, deployment, or connected/live behavior changes. #507 still owns notice/retention approval, scoped authorization, protected authority, isolated staging, backend-first deployment/readback, the availability flip, connected publication, and live proof. Use no real name or photo. | | Immediate Product-binding containment part of RISK-031 | PAY-PRODUCT-001A is tracked in live [#353](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/353). One dependency-free projection is used by the paid race and Shop checkout paths. A present stored Product link must be an own primitive non-empty string from 1 through 255 JavaScript code units and is copied without trimming, conversion, character restrictions, or `prod_` inference. Only a genuinely missing own field retains the compatibility Product-create path. Before any mapping write, a resolved Product must provide a bounded custom ID, exact Product kind, expected declared mode, and an installed-SDK 2xx response marker. Malformed stored links stop before token, registration/order identifier, Product-link or business-record write, or Stripe work; earlier access and request-count checks and their safety-counter writes may already have run. Malformed created results stop after at most one Product attempt but before mapping, Checkout Session, or business-record writes. | This structural containment does not prove provider origin, Stripe account ownership, intended catalog identity, metadata binding, Product status, price, dispatch, delivery, or reconciliation. A rejected create result may leave an orphaned Product; do not retry automatically. Anonymous clean-missing creation remains concurrency-prone and reachable from public traffic. Complete #113 inventory/disposition, authenticated idempotent catalog synchronization, Product-specific plan/pre-send/result/lost-acknowledgement/reconciliation controls, isolated staging, protected Firebase deployment, and provider proof before live commerce. | | Immediate current-handler containment part of RISK-003 | PAY-SESSION-001A is tracked in live [#357](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/357). The current paid race and Shop handlers build one immutable expectation before the Session call, catch rejection without opening it, and immediately project only a closed installed-SDK result. A result must match declared test/live mode, payment/open/unpaid state, exact cents, USD, buyer email, exact closed metadata, exact callbacks, a mode-compatible bounded Session ID, one canonical HTTPS capability at the hard-coded default `checkout.stripe.com` origin, and an installed-SDK 200 marker. Only copied ID/URL values continue; records store the ID but never the URL. Invalid results create no registration/order record and return one fixed unknown-result message. The website makes rejection or a missing paid URL terminal for that page visit, retains the form, and blocks a second direct handler call. | This is a narrow legacy compatibility stop, not trusted provider/account origin, deterministic business idempotency, dispatch/delivery proof, durable result evidence, payment proof, or adoption of the unused C4 chain. The Session call occurs first, so a rejected result may leave a payable orphan; earlier rate-counter, token/identifier, and lazy Product-mapping effects may remain. Reload, another tab/device, or a scripted caller bypasses the page lock. A configured Stripe custom checkout domain is blocked until #113 and a protected configuration boundary approve it. Complete PAY-002C/D persistence-first sagas, trusted C4 controller/result persistence, reconciliation, protected staging/deployment, provider readback, and exact website/Firebase/live proof. | | Immediate pre-render browser containment part of RISK-003 | PAY-SESSION-001B is tracked in live [#503](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/503). Each current public race and Shop page now keeps one component-local in-memory marker. After existing local checks admit a request, the handler sets that marker synchronously before analytics or its first Checkout promise can settle. A same-action or later submission on that mounted page is inert, including the gap before React renders the existing pending disabled button. Focused actual-route tests prove one service/analytics attempt across same-action and post-render repeats; preserve free-participant, volunteer-without-price-tier, and both paid-link navigation branches; and prove local waiver/native-disabled paths do not consume an attempt. | This browser marker is not a server boundary, durable idempotency key, provider dispatch/result record, business-state lock, payment proof, or reconciliation. It never releases during the mounted page visit because the admitted result must navigate or enter #357's terminal unknown-result state. Existing form controls other than the submit button remain editable. Reload, a remount, another tab/device, a script, or a direct service caller can bypass it. A same-mounted route change instead stays locked, and this slice does not fence an older pending result from that changed route. Complete PAY-002C/D persistence-first deterministic commands, durable replay/reconciliation, protected deployment, and exact website/Firebase/Stripe/live proof. | diff --git a/SYSTEM_DESIGN.md b/SYSTEM_DESIGN.md index 5b7de43..053f227 100644 --- a/SYSTEM_DESIGN.md +++ b/SYSTEM_DESIGN.md @@ -701,6 +701,8 @@ WEB-002C [#623](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/623) publi **MEMBERS-DIRECTORY-001K saved-photo response admission — SOURCE ONLY:** [#639](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/639) changes only the preserved connected Account service boundary for an inbound returned saved photo. After the existing exact-object and `image/webp` checks, canonical base64 must decode to 12 through 65,536 bytes with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11 before it can become `MemberDirectoryProfile.photo`. Every failure still becomes only **Invalid member directory response.**; the client does not render or log raw bytes, a provider value, or caught detail. Tests import the actual Account profile component and actual service while mocking only `firebase/functions`: mislabeled canonical bytes stop at the service and produce the existing generic unavailable state without a saved-thumbnail image or data URL. This structural admission is not browser decoding. Header-valid bytes may reach the existing fixed `data:image/webp;base64,` image; if the browser cannot display them, the version-scoped, byte-free **Photo unavailable** fallback removes the data URL and keeps **Remove current saved photo** available without another callable. The returned-photo change does not alter outbound JPG, PNG, or WebP admission or bytes. It adds no Function, Rule, index, schema, package, workflow, photo query, facial recognition, matching, embedding, similarity, biometric processing, provider, account, sign-in state, production-data action, deployment, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. +**MEMBERS-DIRECTORY-001L People-finder search focus — SOURCE ONLY:** [#641](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/641) changes only keyboard-focus settlement in the preserved connected officer People finder. After a valid query and request ID admit an explicit search into `pending`, the component records only that exact operation symbol and whether the persistent name input or Search button owned focus; it stores no query, name, result, photo, account ID, request ID, or service value in the focus intent. When that current operation renders result cards, an empty result, or the fixed unavailable state, the intent is consumed. An origin that remains focused is left alone; focus evicted to the document body, root element, no active element, or a disconnected element returns to the same now-enabled origin; any other connected element that the user focused during the request keeps focus. Editing, Clear, local validation failure, request-ID failure, application or administrator change, unmount, and an obsolete resolution or rejection clear or fail the intent guards. Clear retains its existing local disposal and input focus. The handoff creates no request ID, search, retry, Clear action, result, audit, service call, or data URL. Existing normalization, native pending disablement, response bounds, fixed errors, result and photo behavior, `AdminGuard`, and stale-result fences remain unchanged. This adds no data movement, page structure, service contract, Function, Rule, index, package, workflow, backend, provider, account, sign-in state, production-data action, deployment, photo query, face recognition, matching, embedding, similarity, biometric processing, or connected/live behavior. Availability remains byte-for-byte `false`; the default branch and live #623 preview remain inert, and #507 retains every privacy, authorization, staging, backend-first deployment/readback, availability-flip, publication, and live-proof gate. + ### 8.0a Provider-neutral membership authority and entitlement — SOURCE ONLY, UNUSED MEMBERS-IDENTITY-001A [#208](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/208), with its command-order correction in MEMBERS-IDENTITY-001H [#451](https://github.com/Run-MPRC/Run-MPRC.github.io/issues/451), defines one unused pure contract that keeps a stable MPRC membership separate from the Firebase account used to sign in. A membership record can exist and receive monotonic term decisions without a UID. Such a record grants no website entitlement. Google, WhatsApp, Strava, email equality, a profile role, and any browser field remain projections or inputs to future reviewed workflows; none is membership authority. diff --git a/docs/officers/EVENTS_SHOP_MEMBERS.md b/docs/officers/EVENTS_SHOP_MEMBERS.md index 535131d..6767027 100644 --- a/docs/officers/EVENTS_SHOP_MEMBERS.md +++ b/docs/officers/EVENTS_SHOP_MEMBERS.md @@ -2472,7 +2472,7 @@ flowchart TD Connected -. "never photo search or proof" .-> Official["Membership, role, payment, or official records"] ``` -Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; source-only #639 admits a returned saved photo only when its canonical decoded bytes total 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, maps every other returned byte shape to one fixed byte-free failure before the Account image path, preserves the version-scoped **Photo unavailable** fallback and Remove action for structurally admitted bytes the browser cannot display, and leaves outbound uploads unchanged; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. +Text alternative: the published #623 artifact keeps the Account and administrator-guarded People-finder controls disabled; source-only #627 preserves the accessible connected layouts behind the unchanged false availability value; source-only #629 adds local photo review where Cancel sends nothing, Save alone sends the existing upload command, and the current saved photo remains authoritative with a version-reset unavailable fallback; source-only #631 distinguishes a `null` **No photo** result from an unrenderable supplied **Photo unavailable** result, retries a different later photo version, and lets completed local states clear the query, messages, cards, names, and images with an announcement, input focus, and no new request or service call; that Clear action does not cancel work, erase memory or cache, roll back an audit, or recall a seen result; source-only #633 makes **Remove current saved photo** preserve the same local reading or ready replacement through a confirmed authoritative remove, use the refreshed revision only when the person later chooses Save, focus a remaining Remove action before a ready Save action before the persistent file input, keep the draft after a definitive rejection with successful readback, and after an unknown outcome or failed readback discard its bytes, hide photo and finder mutation controls, and retain only the existing Reload settings recovery with no Save retry; source-only #635 keeps that uncertain-change warning through failed Reload settings attempts until one authoritative profile read succeeds, while generic load failures make no global no-change promise and reload sends no mutation; source-only #637 focuses the recovery action after user-initiated mutation or readback failure, binds a Reload focus intent to the exact current load before focusing a replacement after failure, never steals focus on an initial load failure, and keeps stale application, account, and unmounted completions focus-inert; source-only #639 admits a returned saved photo only when its canonical decoded bytes total 12 through 65,536 with `RIFF` at bytes 0–3 and `WEBP` at bytes 8–11, maps every other returned byte shape to one fixed byte-free failure before the Account image path, preserves the version-scoped **Photo unavailable** fallback and Remove action for structurally admitted bytes the browser cannot display, and leaves outbound uploads unchanged; source-only #641 records only the exact current input-or-Search focus origin after a valid search enters pending, restores that same now-enabled origin after cards, empty, or fixed failure only when native disablement left no meaningful focus, and preserves any other connected focus the user chose during the request; and only #507 may later connect name search plus voluntary thumbnails after privacy, authorization, staging, and backend-first readback, without photo search, face recognition, or official-record authority. Officer review steps for the #621 frontend preview: @@ -3141,6 +3141,112 @@ Officer source-review procedure for MEMBERS-DIRECTORY-001K [#639] saved-photo re **Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, raw returned bytes or provider detail reached the page or a log, malformed bytes entered the saved-thumbnail image path, outbound uploads changed, or connected behavior became available. +Officer source-review procedure for MEMBERS-DIRECTORY-001L [#641] People-finder search focus — connected source only, **NOT LIVE**: + +**Purpose:** let a backup officer verify from specialist-prepared evidence that the preserved connected People finder returns keyboard focus to the exact name input or Search button displaced by one current search, without stealing focus deliberately moved elsewhere, connecting the feature, using a real person, or changing production. + +**Approvers:** membership lead, privacy owner, and platform/security owner. + +**Prerequisites:** #639 is reviewed and merged. Ask the platform owner or testing specialist for the exact #641 source candidate, the named synthetic-only test output, the trustworthy old-source failure, and a redacted written behavior report. The specialist runs the tests and records the evidence. The backup officer reviews that written evidence without a terminal or test harness. Keep the source-controlled availability value `false`. Do not sign in to production, enter a real name, inspect a real photo, call production Firebase, or change production data. + +1. Keep the complete profile-photo and People-finder feature marked **NOT AVAILABLE YET**. +2. Ask the platform owner for the exact #641 issue. +3. Ask the platform owner for the reviewed pull request. +4. Ask the platform owner for the candidate or merge commit. +5. Ask the testing specialist for the named MEMBERS-DIRECTORY-001L test output. +6. Ask the testing specialist for the trustworthy old-source failure. +7. Ask the testing specialist for the redacted written synthetic-behavior report. +8. Confirm the report names the specialist who ran the tests. +9. Confirm the evidence uses only a made-up administrator account. +10. Confirm the evidence uses only made-up names. +11. Confirm any image evidence uses generated non-face data. +12. Confirm the source-controlled availability value remains byte-for-byte `false`. +13. Confirm the last verified production deployment remains inert #623 deploy `6a7e072f8f346b0008510d29`. +14. Confirm a valid query must pass before a focus intent can exist. +15. Confirm request-number creation must succeed before a focus intent can exist. +16. Confirm the current search must enter its pending state before a focus intent can exist. +17. Confirm the focus intent records the exact search operation. +18. Confirm the focus intent records whether the name input or Search was the origin. +19. Confirm the focus intent records no query. +20. Confirm the focus intent records no name. +21. Confirm the focus intent records no result or photo. +22. Confirm the focus intent records no account ID. +23. Confirm the focus intent records no request number or service value. +24. Confirm pending still disables the persistent name input. +25. Confirm pending still disables Search. +26. Confirm browser focus eviction from the name input is modeled explicitly. +27. Confirm result cards restore that same now-enabled name input after eviction. +28. Confirm an empty result restores that same now-enabled name input after eviction. +29. Confirm the fixed failure restores that same now-enabled name input after eviction. +30. Confirm browser focus eviction from Search is modeled explicitly. +31. Confirm result cards restore that same now-enabled Search button after eviction. +32. Confirm an empty result restores that same now-enabled Search button after eviction. +33. Confirm the fixed failure restores that same now-enabled Search button after eviction. +34. Confirm the handoff does nothing when the recorded origin already owns focus. +35. Confirm an outside connected control keeps focus when chosen during a pending search. +36. Confirm that outside focus survives a result-card settlement. +37. Confirm that outside focus survives an empty-result settlement. +38. Confirm that outside focus survives a fixed-failure settlement. +39. Confirm a programmatic submit while focus is outside creates no focus intent. +40. Confirm local validation failure keeps the controls enabled. +41. Confirm local validation failure creates no request number. +42. Confirm local validation failure creates no search. +43. Confirm request-number failure keeps the controls enabled. +44. Confirm request-number failure creates no search. +45. Confirm editing the name field clears an obsolete focus intent. +46. Confirm Clear clears an obsolete focus intent. +47. Confirm Clear still removes the query and displayed result state. +48. Confirm Clear still focuses the empty name input. +49. Confirm Clear creates no request number. +50. Confirm Clear creates no directory-service call. +51. Confirm an application change makes a late resolution focus-inert. +52. Confirm an application change makes a late rejection focus-inert. +53. Confirm an administrator change makes a late resolution focus-inert. +54. Confirm an administrator change makes a late rejection focus-inert. +55. Confirm unmount makes a late resolution focus-inert. +56. Confirm unmount makes a late rejection focus-inert. +57. Confirm an obsolete operation cannot move focus. +58. Confirm the focus handoff creates no second request number. +59. Confirm the focus handoff creates no extra search or retry. +60. Confirm the focus handoff creates no Clear action. +61. Confirm the focus handoff creates no result or audit. +62. Confirm the focus handoff creates no service call or data URL. +63. Confirm existing name normalization remains unchanged. +64. Confirm existing response bounds remain unchanged. +65. Confirm existing result and thumbnail behavior remains unchanged. +66. Confirm existing fixed-error and disposal behavior remains unchanged. +67. Confirm the administrator guard remains unchanged. +68. Confirm the source diff changes no Account path. +69. Confirm the source diff changes no client service contract. +70. Confirm the source diff changes no Function, Rule, index, or schema. +71. Confirm the source diff changes no package or workflow. +72. Confirm the source diff adds no photo query or facial recognition. +73. Confirm the source diff adds no image matching or embedding. +74. Confirm the source diff adds no similarity score or biometric processing. +75. Confirm the source diff adds no result total or export. +76. Confirm the source diff adds no roster authority or membership proof. +77. Record the source change as its own state. +78. Record the named test results as their own state. +79. Record whether the change merged as its own state. +80. Record whether any website artifact was published as its own state. +81. Record the exact `runmprc.com` revision as its own state. +82. Record whether Firebase was deployed as its own state. +83. Record whether an outside provider was configured as its own state. +84. Record whether an account or sign-in state changed as its own state. +85. Record whether production data changed as its own state. +86. Record whether connected or live People-finder behavior became available as its own state. +87. Stop before changing availability, Firebase, a provider, an account, production data, or the live website. + +**Expected result:** the reviewed connected source records only an exact-operation name-input or Search-button focus intent after a valid query and request number admit one pending search. Current result cards, empty results, and fixed failure consume that intent after render. The already-focused origin remains focused. Focus evicted to the document body, root, no active element, or a disconnected element returns to the same now-enabled origin. Another connected control deliberately focused during pending keeps focus. Programmatic or outside-focused submit, local validation failure, and request-number failure create no intent. Editing, Clear, application or administrator change, unmount, and obsolete resolution or rejection prevent stale focus movement. Clear keeps its existing local disposal, input focus, and zero-call behavior. Focus creates no request number, extra search, retry, Clear action, result, audit, service call, or data URL. Availability remains `false`; the default branch obtains no directory context, creates no request number, and calls no directory service; and live #623 remains inert. The backend and connected behavior remain **NOT AVAILABLE YET**. + +**Stop conditions:** a real account, name, or photo; production sign-in; direct production Firebase access; a current input- or Search-origin search that leaves focus on the document body after cards, empty, or fixed failure; settlement that moves focus away from another connected control; programmatic submission that steals outside focus; validation or request-number failure that disables controls or starts a search; an application, administrator, unmounted, or obsolete completion that moves focus; a second request number, search, retry, Clear action, result, audit, service call, or data URL caused by focus; changed normalization, response, result, thumbnail, fixed-error, disposal, or guard behavior; a photo query; face recognition, matching, embedding, similarity scoring, biometric processing, total, export, roster authority, or membership proof; a Function, Rule, index, schema, package, workflow, provider, account, sign-in, production-data, or website change; an availability flip; use of a terminal or test harness by the backup officer; or a claim that source, tests, or merge means the feature is live. + +**Success proof:** record the exact #641 issue, reviewed pull request and commit; trustworthy old-source failure; green separately named MEMBERS-DIRECTORY-001L focused tests; green full frontend tests; type-checking; scoped lint; diagnostic production build; unchanged lint baseline; workflow checks; diff-check; independent privacy/security, frontend/accessibility, focus/race, and backup-officer reviews; and exact-main CI if merged. Record source, tests, merge, website publication, exact `runmprc.com` revision, Firebase deployment, provider configuration, account/sign-in change, production-data action, and connected/live behavior separately. Record the unchanged `false` availability value and unchanged #623 deploy separately. Source and tests do not prove merge; merge does not prove publication; publication does not prove Firebase, provider, account, data, or connected-live behavior. Final connection and live proof remain #507 work. + +**Undo:** use one reviewed frontend-and-documentation revert or safe roll-forward. Confirm the default disabled branch still makes zero directory calls. No Firebase, provider, account, or production-data undo is needed because #641 changes source only. Undo must not strand focus after native pending-control eviction or permit a stale completion to move focus. + +**Escalation:** membership lead plus privacy and platform/security owners. Use the private incident path if a real name or photo appeared, focus moved across applications or administrator accounts, settlement stole deliberately moved focus, a focus handoff created a request or service call, or connected behavior became available. + ## Admin screens — NOT AVAILABLE YET Admin event and product editors exist in source, but their live permissions, backup, preview, and rollback behavior have not been approved. Saving can write directly to production Firestore. Officers must not use these screens as a continuity procedure yet. diff --git a/src/pages/admin/members/AdminMemberDirectory.test.tsx b/src/pages/admin/members/AdminMemberDirectory.test.tsx index 41b3f63..5827940 100644 --- a/src/pages/admin/members/AdminMemberDirectory.test.tsx +++ b/src/pages/admin/members/AdminMemberDirectory.test.tsx @@ -677,4 +677,247 @@ describe('Admin People finder', () => { ); }); }); + + describe('MEMBERS-DIRECTORY-001L exact-search focus recovery contract', () => { + type FocusOrigin = 'input' | 'search'; + type SearchOutcome = 'results' | 'empty' | 'failure'; + + function focusOrigin(origin: FocusOrigin) { + const element = origin === 'input' + ? queryInput() + : screen.getByRole('button', { name: 'Search' }); + element.focus(); + expect(element).toHaveFocus(); + return element; + } + + function startFocusedSearch(origin: FocusOrigin, value = 'synthetic') { + const input = queryInput(); + fireEvent.change(input, { target: { value } }); + const element = focusOrigin(origin); + fireEvent.submit(input.closest('form') as HTMLFormElement); + expect(input).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Searching...' })).toBeDisabled(); + return element; + } + + function evictFocusToBody(originElement: HTMLElement) { + originElement.blur(); + if (document.activeElement !== document.body) { + const browserEvictionModel = document.createElement('button'); + browserEvictionModel.type = 'button'; + document.body.appendChild(browserEvictionModel); + browserEvictionModel.focus(); + browserEvictionModel.remove(); + } + expect(document.activeElement).toBe(document.body); + } + + async function settleSearch( + pending: ReturnType>, + outcome: SearchOutcome, + ) { + const observedPromise = pending.promise.catch(() => undefined); + await act(async () => { + if (outcome === 'failure') { + pending.reject(new Error('synthetic-private-search-failure')); + } else if (outcome === 'results') { + pending.resolve({ + schemaVersion: 1, + results: [{ + entryRef: ENTRY_REF, + displayName: 'Synthetic Focus Runner', + photo: null, + }], + }); + } else { + pending.resolve({ schemaVersion: 1, results: [] }); + } + await observedPromise; + }); + } + + test.each([ + ['input', 'results'], + ['input', 'empty'], + ['input', 'failure'], + ['search', 'results'], + ['search', 'empty'], + ['search', 'failure'], + ] as const)( + 'restores the exact %s origin after browser focus eviction and a current %s settlement', + async (origin, outcome) => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + renderDirectory(); + + const originElement = startFocusedSearch(origin); + evictFocusToBody(originElement); + + await settleSearch(pending, outcome); + + await waitFor(() => expect(originElement).toHaveFocus()); + expect(originElement).not.toBeDisabled(); + expect(screen.getByRole('button', { + name: 'Clear search and result cards', + })).not.toHaveFocus(); + expect(createMemberDirectorySearchRequestId).toHaveBeenCalledTimes(1); + expect(searchMemberDirectory).toHaveBeenCalledTimes(1); + }, + ); + + test.each([ + ['input', 'results'], + ['input', 'empty'], + ['input', 'failure'], + ['search', 'results'], + ['search', 'empty'], + ['search', 'failure'], + ] as const)( + 'preserves another connected focus after a %s-origin search reaches %s', + async (origin, outcome) => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + renderDirectory(); + + const originElement = startFocusedSearch(origin); + const outside = screen.getByRole('link', { name: /admin home/i }); + outside.focus(); + expect(outside).toHaveFocus(); + + await settleSearch(pending, outcome); + + expect(outside).toHaveFocus(); + expect(originElement).not.toHaveFocus(); + expect(createMemberDirectorySearchRequestId).toHaveBeenCalledTimes(1); + expect(searchMemberDirectory).toHaveBeenCalledTimes(1); + }, + ); + + test('creates no focus intent for a programmatic submit while focus is outside', async () => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + renderDirectory(); + + const input = queryInput(); + fireEvent.change(input, { target: { value: 'synthetic' } }); + const outside = screen.getByRole('link', { name: /admin home/i }); + outside.focus(); + fireEvent.submit(input.closest('form') as HTMLFormElement); + + await settleSearch(pending, 'results'); + + expect(outside).toHaveFocus(); + expect(input).not.toHaveFocus(); + expect(createMemberDirectorySearchRequestId).toHaveBeenCalledTimes(1); + expect(searchMemberDirectory).toHaveBeenCalledTimes(1); + }); + + test.each([ + ['input'], + ['search'], + ] as const)('does not refocus the %s origin when it already retained focus', async (origin) => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + renderDirectory(); + + const originElement = startFocusedSearch(origin); + expect(originElement).toHaveFocus(); + const focusSpy = jest.spyOn(originElement, 'focus'); + + await settleSearch(pending, 'empty'); + + expect(originElement).toHaveFocus(); + expect(focusSpy).not.toHaveBeenCalled(); + expect(createMemberDirectorySearchRequestId).toHaveBeenCalledTimes(1); + expect(searchMemberDirectory).toHaveBeenCalledTimes(1); + }); + + test('keeps local validation and request-ID failure focus-inert', () => { + renderDirectory(); + + const input = queryInput(); + fireEvent.change(input, { target: { value: 'x' } }); + input.focus(); + fireEvent.submit(input.closest('form') as HTMLFormElement); + expect(input).toHaveFocus(); + expect(input).not.toBeDisabled(); + expect(createMemberDirectorySearchRequestId).not.toHaveBeenCalled(); + expect(searchMemberDirectory).not.toHaveBeenCalled(); + + fireEvent.change(input, { target: { value: 'synthetic' } }); + const search = screen.getByRole('button', { name: 'Search' }); + search.focus(); + (createMemberDirectorySearchRequestId as jest.Mock).mockImplementationOnce(() => { + throw new Error('synthetic-request-id-failure'); + }); + fireEvent.submit(input.closest('form') as HTMLFormElement); + + expect(search).toHaveFocus(); + expect(input).not.toBeDisabled(); + expect(search).not.toBeDisabled(); + expect(searchMemberDirectory).not.toHaveBeenCalled(); + }); + + test.each([ + ['Firebase-app change', 'results', otherApp, 'admin-one'], + ['Firebase-app change', 'failure', otherApp, 'admin-one'], + ['admin-account change', 'results', app, 'admin-two'], + ['admin-account change', 'failure', app, 'admin-two'], + ] as const)('makes old %s %s focus-inert', async ( + _context, + outcome, + nextApp, + nextUid, + ) => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + const view = renderDirectory(); + const oldOrigin = startFocusedSearch('input'); + evictFocusToBody(oldOrigin); + + setContext(nextApp, nextUid); + view.rerender( + + + , + ); + const newInput = queryInput(); + const outside = screen.getByRole('link', { name: /admin home/i }); + outside.focus(); + + await settleSearch(pending, outcome); + + expect(outside).toHaveFocus(); + expect(newInput).not.toHaveFocus(); + expect(screen.queryByText('Synthetic Focus Runner')).not.toBeInTheDocument(); + }); + + test.each([ + ['results'], + ['failure'], + ] as const)('makes %s completion focus-inert after unmount', async (outcome) => { + const pending = deferred(); + (searchMemberDirectory as jest.Mock).mockReturnValueOnce(pending.promise); + const view = renderDirectory(); + const oldOrigin = startFocusedSearch('search'); + evictFocusToBody(oldOrigin); + view.unmount(); + + const outside = document.createElement('button'); + outside.type = 'button'; + outside.textContent = 'Persistent outside control'; + document.body.appendChild(outside); + outside.focus(); + + await settleSearch(pending, outcome); + + expect(outside).toHaveFocus(); + expect(document.body).not.toHaveTextContent('Synthetic Focus Runner'); + outside.remove(); + }); + }); }); diff --git a/src/pages/admin/members/AdminMemberDirectory.tsx b/src/pages/admin/members/AdminMemberDirectory.tsx index 53a9fa2..1e564aa 100644 --- a/src/pages/admin/members/AdminMemberDirectory.tsx +++ b/src/pages/admin/members/AdminMemberDirectory.tsx @@ -38,6 +38,11 @@ type SearchState = | { phase: 'resolved'; results: readonly MemberDirectorySearchResult[] } | { phase: 'unavailable' }; +type SearchFocusIntent = { + operation: symbol; + origin: 'input' | 'search'; +}; + function PhotoFallback({ displayName, unavailable = false, @@ -84,9 +89,11 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { const [state, setState] = useState({ phase: 'idle' }); const [clearAnnouncement, setClearAnnouncement] = useState(null); const queryInputRef = useRef(null); + const searchButtonRef = useRef(null); const mountedRef = useRef(false); const pendingRef = useRef(false); const operationRef = useRef(null); + const focusIntentRef = useRef(null); useEffect(() => { mountedRef.current = true; @@ -94,12 +101,34 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { mountedRef.current = false; pendingRef.current = false; operationRef.current = null; + focusIntentRef.current = null; }; }, []); + useEffect(() => { + if (state.phase === 'idle' || state.phase === 'pending') return; + const intent = focusIntentRef.current; + if (intent === null || operationRef.current !== intent.operation) return; + + focusIntentRef.current = null; + const origin = intent.origin === 'input' + ? queryInputRef.current + : searchButtonRef.current; + if (origin === null || !origin.isConnected) return; + + const { activeElement } = document; + if (activeElement === origin) return; + const meaningfulFocus = activeElement !== null + && activeElement !== document.body + && activeElement !== document.documentElement + && activeElement.isConnected; + if (!meaningfulFocus) origin.focus(); + }, [state]); + function handleQueryChange(event: React.ChangeEvent) { if (pendingRef.current) return; operationRef.current = null; + focusIntentRef.current = null; setQueryInput(event.currentTarget.value); setValidationMessage(null); setState({ phase: 'idle' }); @@ -113,6 +142,7 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { const query = normalizeMemberDirectorySearchQuery(queryInput); if (query === null) { operationRef.current = null; + focusIntentRef.current = null; setValidationMessage(QUERY_REQUIREMENT); setState({ phase: 'idle' }); setClearAnnouncement(null); @@ -123,6 +153,8 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { try { requestId = createMemberDirectorySearchRequestId(); } catch { + operationRef.current = null; + focusIntentRef.current = null; setValidationMessage(null); setState({ phase: 'unavailable' }); setClearAnnouncement(null); @@ -132,6 +164,14 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { const operation = Symbol('member-directory-search'); operationRef.current = operation; pendingRef.current = true; + const { activeElement } = document; + if (activeElement === queryInputRef.current) { + focusIntentRef.current = { operation, origin: 'input' }; + } else if (activeElement === searchButtonRef.current) { + focusIntentRef.current = { operation, origin: 'search' }; + } else { + focusIntentRef.current = null; + } setQueryInput(query); setValidationMessage(null); setState({ phase: 'pending' }); @@ -153,6 +193,7 @@ function SearchAttempt({ app }: { app: FirebaseApp }) { function handleClear() { operationRef.current = null; + focusIntentRef.current = null; setQueryInput(''); setValidationMessage(null); setState({ phase: 'idle' }); @@ -214,6 +255,7 @@ function SearchAttempt({ app }: { app: FirebaseApp }) {