From d2dfc094952567e43c420187b48f6ae87b875f28 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 16 Nov 2026 15:42:43 +0100 Subject: [PATCH] :bug: Carry the team id in every team scoped navigation (#12963) * :bug: Carry the team id in every team scoped navigation The eleven `go-to-*` helpers of `app.main.data.common` resolved the team with a plain `or` against `:current-team-id`, or read that key alone, so an event emitted while no team was initialized built a dashboard or workspace route without a `team-id`. `team-container*` raises `:not-found :invalid-team-id` for such a route and `exception-section*` does not report `:not-found`, so the user landed on the not-found page and PostHog never saw it. Add `resolve-team-id`, which falls back to the team of the route already on screen and then to the profile `:default-team-id`. The route goes first on purpose: an emitter that runs from a team screen knows which team the user is looking at, and the personal team would open their file under another team. The `:default` sentinel keeps its meaning. With none of the four the helper still navigates with a nil id, which is the documented last resort. Harden the team-container test at the same time: it now renders the same component with the store team the caller wants, captures markup and errors per render, unmounts the root from a `finally`, and covers the guard that compares the route id with the store team. React reports a hook-order violation through `console.error` and recovers, and only when a render adds hooks, so the harness captures that too and the "id leaves" direction stays a guard test. Closes #12962 AI-assisted-by: deepseek-v4.1-flash * :recycle: Measure the navigation tests by termination The `emitted` helper of `common_test` waited for the first event, with a budget of 50 macrotasks, so a helper that emitted anything before its navigation could be disposed early, and a helper that stopped closing its stream passed on the first event. Wait for termination instead: `async/observe` over a subject, and make `go-to-dashboard-search` complete by pushing the `::rt/navigated` it listens for, which is the event it waits for in the app to focus the search box. Every helper of the family is measured the same way now, `-search` included. `nav-params` returns nil when no navigation matched instead of calling `deref` on nil, as its docstring promised. Add the mirror test for the `:default` sentinel of `go-to-dashboard-deleted`, the second copy of the branch that `-recent` already had covered. Correct two memories: the resolver decides for every team scoped helper, not for every `go-to-*` and not alone, since two direct `rt/nav` emitters are the residual; and `(rx/empty)` is for a stream that must not emit, not for one that must stay open. Relates to #12962 AI-assisted-by: deepseek-v4.1-flash --- .../frontend/routing-app-shell-subtleties.md | 3 + .serena/memories/frontend/testing.md | 2 + frontend/src/app/main/data/common.cljs | 59 +++--- .../test/frontend_tests/data/common_test.cljs | 174 ++++++++++++++++++ frontend/test/frontend_tests/runner.cljs | 2 + .../ui/team_container_test.cljs | 146 +++++++++++---- 6 files changed, 321 insertions(+), 65 deletions(-) create mode 100644 frontend/test/frontend_tests/data/common_test.cljs diff --git a/.serena/memories/frontend/routing-app-shell-subtleties.md b/.serena/memories/frontend/routing-app-shell-subtleties.md index 8c43a30161..2735fa292e 100644 --- a/.serena/memories/frontend/routing-app-shell-subtleties.md +++ b/.serena/memories/frontend/routing-app-shell-subtleties.md @@ -22,6 +22,9 @@ - `flash-persistence` only delegates to another handler for `:authentication`, `:not-found` and `:code :vern-conflict`. Everything else it reports itself, and the report type is derived from the cause: `#{:validation :server-error :internal}` are application defects and report as `unhandled-exception` so they reach the internal reports and the alerts; the rest stay `handled-exception`. `:cause-type` wins over `:type` when classifying, because `persistence-failed` wraps the original cause under `:type :persistence`. Environment failures are deliberately kept handled: they land here after the retry budget is spent and the user's connection is not our bug. `:assertion` is also kept handled, matching its own handler. - The report governor is global and stateful across tests: two reports with the same fingerprint inside `report-window-ms` collapse. Call `errors/reset-report-governor!` between assertions that expect an emission. - Error messages are bounded at the source: `app.common.exceptions/get-hint` clamps to `max-message-length` (1000 chars) and the CLJS `format-throwable` clamps the message line of the stack trace and honors `:trace-length`. A message can embed a whole payload (a serialized file, for example) and reach megabytes; the bound keeps the audit `:hint` prop and the `:report` string small. The `Context: Hint:` header in `generate-report` prints `get-hint` (not the raw `:hint` from `ex-data`) for the same reason. +- A team scoped navigation carries a team whenever any of the four tiers exists, and `app.main.data.common/resolve-team-id` decides it for every team scoped `go-to-*` helper of that namespace: the UUID the caller passes, `:current-team-id`, the team of the route already on screen (`?team-id`), then the profile `:default-team-id`. `go-to-feedback` and `go-to-viewer` are not team scoped and do not go through it, and `:team-id :default` keeps meaning the profile default, resolved before the rest. The route goes before the profile default because an emitter that runs from a team screen knows which team the user is looking at, and the personal team would open their file under another team. Two `rt/nav` emitters outside that namespace still decide their own id and can still emit nil, and they are the residual: `app.main.ui.nitrate.entry/nitrate-entry*` (the profile default) and the root branch of `app.main.ui.routes/on-query-navigate` (`dtm/resolve-login-team-id`, which answers nil when the profile has no default team). When none of the tiers exists the helper still fires the navigation with a nil id, so the not-found page appears instead of the click doing nothing. +- `app.main.ui/team-container*` raises `:not-found :invalid-team-id` for a dashboard or workspace route without a valid `team-id`; the raise is what keeps a broken URL from painting a blank shell, so it stays after the hook fix of #12728. `exception-section*` skips `errors/submit-report` for `:not-found`, so this failure never reaches PostHog and cannot be measured from the error dashboard. The exit from that page is the `error-container*` header (logo plus `not-found.no-permission.go-dashboard`), which emits `go-to-dashboard-recent` with the profile default and falls back to `rt/nav-root`; every not-found and authentication page already carries it, so there is no button to add there. +- A click cannot reach a team screen before its team is resolved: `team-container*` paints its children only when the route id matches the store team, and `refs/team` derives from `:current-team-id`, so with that key empty the dashboard and the workspace paint nothing clickable. The nil-id emissions come from events that run on their own (login, invitation acceptance, membership change, the sidebar logo, the workspace shortcuts) and from typed or bookmarked URLs. ## Store and websocket diff --git a/.serena/memories/frontend/testing.md b/.serena/memories/frontend/testing.md index 7678594169..45e6bff9e4 100644 --- a/.serena/memories/frontend/testing.md +++ b/.serena/memories/frontend/testing.md @@ -44,6 +44,8 @@ To assert over emitted event sequences, observe termination: subscribe through ` - A body that awaits must be `(^:async fn …)` even if the rest is sync; sync sequences are atomic vs the event loop. - `app.main.errors` prints every handled cause with `ex/print-throwable` before notifying, and the app logger does not gate it. A test that runs a real handler end to end stubs that var (`main-errors-test/quiet-throwable`): without it, the 10 000-error governor test alone wrote 190 k of the 192 k lines of a run log (13,8 MB), and GitHub truncates a step log past ~4 MB, cutting the summary and any failing assertion. Same for a production `console.error` a test provokes on purpose: `code-gen-markup-svg-wasm-test` silences `(.-error js/console)` in a `try/finally` while two WASM panics go through `get-svg-markup` (2 blocks, 70 lines, and the exception dumps its own `data`/`arr`). - The `:esm` test build cannot load the CommonJS `sax` module behind `tubax`, so SVG parsing fails in tests (`dwm/valid-svg-string?` answers false, `dwm/svg->clj` errors): mock both with the parsed data. +- A hook-order violation in a mounted component reaches neither the root's `onUncaughtError`/`onCaughtError`/`onRecoverableError` nor the markup: React logs an internal error to `console.error` and recovers, so the callbacks stay empty and the tree repaints. Assert on a captured `console.error` too. It only fires when a render *adds* hooks (nil → uuid); a render that calls none at all slips through React's bookkeeping, so the regression test needs the "hooks arrive" direction. `frontend-tests.ui.team-container-test` does both, with a jsdom document. +- `beicon.v2.core` has no `never`. A stream that must **not emit** is `(rx/empty)`: it completes at once, which is enough for `merge`, `filter` and `take` where only the emission matters. A stream that must **stay open** is a `(rx/subject)` nobody pushes to; `rx/empty` would complete the flow behind it. An undeclared `rx/never` compiles to an undefined var and the test dies as a rejected body, which `cljs.test` reports as a test with zero assertions instead of a failure. From `frontend/`: - Full unit test run (always builds, suppressed output): `pnpm run test:quiet`. diff --git a/frontend/src/app/main/data/common.cljs b/frontend/src/app/main/data/common.cljs index c2a7de99af..f6653e7695 100644 --- a/frontend/src/app/main/data/common.cljs +++ b/frontend/src/app/main/data/common.cljs @@ -13,6 +13,7 @@ [app.common.time :as ct] [app.common.types.organization :as cto] [app.common.types.team :as ctt] + [app.common.uuid :as uuid] [app.config :as cf] [app.main.data.helpers :as dsh] [app.main.data.modal :as modal] @@ -405,6 +406,26 @@ ;; NAVEGATION EVENTS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +(defn- resolve-team-id + "The team a team scoped navigation must carry: the UUID the caller + passes, the team initialized in the store, the team of the route + already on screen, or the profile default. A navigation carries a nil + id only when none of the four exists. + + The route goes before the profile default on purpose: the emitters that + run from a team screen know the team the user is looking at, and the + personal team would open their file under another team. + + `team-container*` raises `:not-found :invalid-team-id` for a dashboard + or workspace route without a valid id, and `:not-found` is not reported + to the error pipeline, so a navigation that loses the id ends on the + not-found page without leaving a trace." + [state team-id] + (or (when (uuid? team-id) team-id) + (:current-team-id state) + (some-> (rt/get-query-param (rt/get-params state) :team-id) uuid/parse*) + (dm/get-in state [:profile :default-team-id]))) + (defn go-to-feedback [] (ptk/reify ::go-to-feedback @@ -420,7 +441,7 @@ ptk/WatchEvent (watch [_ state _] (let [profile (get state :profile) - team-id (or team-id (:current-team-id state)) + team-id (resolve-team-id state team-id) project-id (if (= project-id :default) (:default-project-id profile) project-id) @@ -434,7 +455,7 @@ (ptk/reify ::go-to-dashboard-search ptk/WatchEvent (watch [_ state stream] - (let [team-id (:current-team-id state)] + (let [team-id (resolve-team-id state nil)] (rx/merge (->> (rx/of (rt/nav :dashboard-search {:team-id team-id @@ -454,7 +475,7 @@ (ptk/reify ::go-to-dashboard-libraries ptk/WatchEvent (watch [_ state _] - (let [team-id (or team-id (:current-team-id state))] + (let [team-id (resolve-team-id state team-id)] (rx/of (rt/nav :dashboard-libraries {:team-id team-id})))))) @@ -463,7 +484,7 @@ (ptk/reify ::go-to-dashboard-fonts ptk/WatchEvent (watch [_ state _] - (let [team-id (or team-id (:current-team-id state))] + (let [team-id (resolve-team-id state team-id)] (rx/of (rt/nav :dashboard-fonts {:team-id team-id})))))) (defn go-to-dashboard-recent @@ -472,15 +493,9 @@ ptk/WatchEvent (watch [_ state _] (let [profile (get state :profile) - team-id (cond - (= :default team-id) + team-id (if (= :default team-id) (:default-team-id profile) - - (uuid? team-id) - team-id - - :else - (:current-team-id state)) + (resolve-team-id state team-id)) params {:team-id team-id}] (rx/of (modal/hide) (rt/nav :dashboard-recent params options)))))) @@ -490,7 +505,7 @@ (ptk/reify ::go-to-dashboard-members ptk/WatchEvent (watch [_ state _] - (let [team-id (:current-team-id state)] + (let [team-id (resolve-team-id state nil)] (rx/of (rt/nav :dashboard-members {:team-id team-id})))))) (defn go-to-dashboard-invitations @@ -498,7 +513,7 @@ (ptk/reify ::go-to-dashboard-invitations ptk/WatchEvent (watch [_ state _] - (let [team-id (:current-team-id state)] + (let [team-id (resolve-team-id state nil)] (rx/of (rt/nav :dashboard-invitations {:team-id team-id})))))) (defn go-to-dashboard-webhooks @@ -506,7 +521,7 @@ (ptk/reify ::go-to-dashboard-webhooks ptk/WatchEvent (watch [_ state _] - (let [team-id (:current-team-id state)] + (let [team-id (resolve-team-id state nil)] (rx/of (rt/nav :dashboard-webhooks {:team-id team-id})))))) (defn go-to-dashboard-settings @@ -514,7 +529,7 @@ (ptk/reify ::go-to-dashboard-settings ptk/WatchEvent (watch [_ state _] - (let [team-id (:current-team-id state)] + (let [team-id (resolve-team-id state nil)] (rx/of (rt/nav :dashboard-settings {:team-id team-id})))))) (defn go-to-workspace @@ -522,7 +537,7 @@ (ptk/reify ::go-to-workspace ptk/WatchEvent (watch [_ state _] - (let [team-id (or team-id (:current-team-id state)) + (let [team-id (resolve-team-id state team-id) file-id (or file-id (:current-file-id state)) page-id (or page-id (:current-page-id state) (-> (dsh/lookup-file-data state file-id) @@ -575,15 +590,9 @@ ptk/WatchEvent (watch [_ state _] (let [profile (get state :profile) - team-id (cond - (= :default team-id) + team-id (if (= :default team-id) (:default-team-id profile) - - (uuid? team-id) - team-id - - :else - (:current-team-id state)) + (resolve-team-id state team-id)) params {:team-id team-id}] (rx/of (modal/hide) (rt/nav :dashboard-deleted params options)))))) diff --git a/frontend/test/frontend_tests/data/common_test.cljs b/frontend/test/frontend_tests/data/common_test.cljs new file mode 100644 index 0000000000..b0c43bd4c8 --- /dev/null +++ b/frontend/test/frontend_tests/data/common_test.cljs @@ -0,0 +1,174 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns frontend-tests.data.common-test + "Every team-scoped navigation carries a team. + + `team-container*` raises `:not-found :invalid-team-id` for a dashboard + or workspace route without a valid `team-id`, and `:not-found` is not + reported to the error pipeline, so a navigation that loses the id ends + on the not-found page without leaving a trace. The helpers resolve the + id from the argument, the initialized team, the team of the route + already on screen, and the profile default, in that order." + (:require + [app.common.uuid :as uuid] + [app.main.data.common :as dcm] + [app.main.router :as rt] + [beicon.v2.core :as rx] + [cljs.test :as t :include-macros true] + [frontend-tests.helpers.async :as async] + [potok.v2.core :as ptk])) + +(def ^:private file-id (uuid/next)) + +(defn- state + "A slice of the store with the teams a navigation can resolve. The + route is the one a team screen leaves behind: its query names the team + the user is looking at." + [{:keys [current-team-id route-team-id default-team-id]}] + (cond-> {:profile {:id (uuid/next)}} + (some? current-team-id) + (assoc :current-team-id current-team-id) + + (some? default-team-id) + (assoc-in [:profile :default-team-id] default-team-id) + + (some? route-team-id) + (assoc :route {:data {:name :dashboard-recent} + :params {:path {} :query {:team-id (str route-team-id)}} + :query-params {:team-id (str route-team-id)}}))) + +(defn- ^:async emitted + "Runs `event` against `state` and returns every event it emitted, once + the event's stream terminates. + + The stream is a subject the caller of `ptk/watch` never sees: `go-to- + dashboard-search` keeps listening to the router after navigating and + completes only when it receives one `::rt/navigated`, which is the event + it waits for in the app to focus the search box. Pushing it here makes + that helper terminate like the rest, so every event of the family is + measured the same way, subscribe and await termination. + + `observe` forces asynchronous delivery even for a synchronous source and + rejects when the stream does not terminate in time, so a helper that + stops closing its stream fails here instead of passing on the first + event." + [event state] + (let [stream (rx/subject) + events (atom []) + done (async/observe (ptk/watch event state stream) + :on-next #(swap! events conj %))] + ;; `observe` subscribes inside its promise executor, so the subject + ;; already has a listener; a subject drops values nobody hears. + (rx/push! stream (rt/navigated {:data {:name :dashboard-search}} false)) + (await done) + @events)) + +(defn- nav-params + "The params of the last navigation to `route-id`, or nil when the event + emitted none." + [events route-id] + (some->> events + (filter #(and (= ::rt/navigate (ptk/type %)) + (= route-id (:id @%)))) + (last) + (deref) + (:params))) + +(t/deftest ^:async go-to-workspace-takes-the-team-of-the-route-on-screen + ;; The opened file belongs to the team of the route. The personal + ;; default would open it under another team. + (let [route-team-id (uuid/next) + default-team-id (uuid/next) + events (await (emitted (dcm/go-to-workspace :file-id file-id) + (state {:route-team-id route-team-id + :default-team-id default-team-id})))] + (t/is (= route-team-id (:team-id (nav-params events :workspace)))))) + +(t/deftest ^:async go-to-workspace-takes-the-team-initialized-in-the-store + (let [current-team-id (uuid/next) + events (await (emitted (dcm/go-to-workspace :file-id file-id) + (state {:current-team-id current-team-id + :route-team-id (uuid/next) + :default-team-id (uuid/next)})))] + (t/is (= current-team-id (:team-id (nav-params events :workspace)))))) + +(t/deftest ^:async go-to-workspace-takes-the-profile-default-when-no-team-is-known + (let [default-team-id (uuid/next) + events (await (emitted (dcm/go-to-workspace :file-id file-id) + (state {:default-team-id default-team-id})))] + (t/is (= default-team-id (:team-id (nav-params events :workspace)))))) + +(t/deftest ^:async go-to-workspace-keeps-the-team-the-caller-passes + (let [team-id (uuid/next) + events (await (emitted (dcm/go-to-workspace :team-id team-id :file-id file-id) + (state {:current-team-id (uuid/next) + :route-team-id (uuid/next) + :default-team-id (uuid/next)})))] + (t/is (= team-id (:team-id (nav-params events :workspace)))))) + +(t/deftest ^:async go-to-dashboard-recent-keeps-the-default-sentinel + (let [default-team-id (uuid/next) + events (await (emitted (dcm/go-to-dashboard-recent :team-id :default) + (state {:current-team-id (uuid/next) + :route-team-id (uuid/next) + :default-team-id default-team-id})))] + (t/is (= default-team-id (:team-id (nav-params events :dashboard-recent)))))) + +(t/deftest ^:async go-to-dashboard-deleted-keeps-the-default-sentinel + ;; The sentinel is a second copy of the branch in `-recent`; without its + ;; own test, a divergence here would navigate to the current team. + (let [default-team-id (uuid/next) + events (await (emitted (dcm/go-to-dashboard-deleted :team-id :default) + (state {:current-team-id (uuid/next) + :route-team-id (uuid/next) + :default-team-id default-team-id})))] + (t/is (= default-team-id (:team-id (nav-params events :dashboard-deleted)))))) + +(t/deftest ^:async go-to-dashboard-recent-resolves-a-nil-team-through-the-route + (let [route-team-id (uuid/next) + events (await (emitted (dcm/go-to-dashboard-recent) + (state {:route-team-id route-team-id + :default-team-id (uuid/next)})))] + (t/is (= route-team-id (:team-id (nav-params events :dashboard-recent)))))) + +(def ^:private dashboard-helpers + "The rest of the family, with the route each one navigates to." + [[dcm/go-to-dashboard-files :dashboard-files] + [dcm/go-to-dashboard-search :dashboard-search] + [dcm/go-to-dashboard-libraries :dashboard-libraries] + [dcm/go-to-dashboard-fonts :dashboard-fonts] + [dcm/go-to-dashboard-members :dashboard-members] + [dcm/go-to-dashboard-invitations :dashboard-invitations] + [dcm/go-to-dashboard-webhooks :dashboard-webhooks] + [dcm/go-to-dashboard-settings :dashboard-settings] + [dcm/go-to-dashboard-deleted :dashboard-deleted]]) + +(t/deftest ^:async dashboard-helpers-take-the-team-of-the-route-on-screen + (doseq [[helper route-id] dashboard-helpers] + (let [route-team-id (uuid/next) + events (await (emitted (helper) + (state {:route-team-id route-team-id + :default-team-id (uuid/next)})))] + (t/is (= route-team-id (:team-id (nav-params events route-id))) + (str "route: " route-id))))) + +(t/deftest ^:async dashboard-helpers-take-the-profile-default-when-no-team-is-known + (doseq [[helper route-id] dashboard-helpers] + (let [default-team-id (uuid/next) + events (await (emitted (helper) + (state {:default-team-id default-team-id})))] + (t/is (= default-team-id (:team-id (nav-params events route-id))) + (str "route: " route-id))))) + +(t/deftest ^:async navigations-still-fire-when-no-team-can-be-resolved + ;; Documented last resort: a profile without a default team is a broken + ;; or transient state, and there is nothing to resolve. The navigation + ;; still fires, so the not-found page appears with its exit in the + ;; header instead of the click doing nothing. + (let [events (await (emitted (dcm/go-to-dashboard-members) (state {})))] + (t/is (some? (nav-params events :dashboard-members))) + (t/is (nil? (:team-id (nav-params events :dashboard-members)))))) diff --git a/frontend/test/frontend_tests/runner.cljs b/frontend/test/frontend_tests/runner.cljs index 7dc29e4857..8bc2051371 100644 --- a/frontend/test/frontend_tests/runner.cljs +++ b/frontend/test/frontend_tests/runner.cljs @@ -13,6 +13,7 @@ [frontend-tests.data.auth-test] [frontend-tests.data.comments-batches-test] [frontend-tests.data.comments-filters-test] + [frontend-tests.data.common-test] [frontend-tests.data.dashboard-test] [frontend-tests.data.event-test] [frontend-tests.data.exports-assets-test] @@ -225,6 +226,7 @@ 'frontend-tests.data.auth-test 'frontend-tests.data.comments-batches-test 'frontend-tests.data.comments-filters-test + 'frontend-tests.data.common-test 'frontend-tests.data.dashboard-test 'frontend-tests.data.event-test 'frontend-tests.data.fix-deleted-fonts-test diff --git a/frontend/test/frontend_tests/ui/team_container_test.cljs b/frontend/test/frontend_tests/ui/team_container_test.cljs index b16d0b089d..99649f0485 100644 --- a/frontend/test/frontend_tests/ui/team_container_test.cljs +++ b/frontend/test/frontend_tests/ui/team_container_test.cljs @@ -7,8 +7,10 @@ (ns frontend-tests.ui.team-container-test "`team-container*` renders the same hooks with and without a team id. React throws when the hook count changes between two renders of the - same component, so these tests mount it and render it again; the - documents come from jsdom since the runner has no DOM." + same component, so these tests mount it and render it again with each + id of the sequence; the documents come from jsdom since the runner has + no DOM. The guard that compares the route id with the store team is + covered too: it decides whether the children are painted at all." (:require ["jsdom" :refer [JSDOM]] ["react-dom" :as rd] @@ -30,51 +32,115 @@ (js/Promise. (fn [resolve] (js/setImmediate resolve)))) (defn- ^:async render-with - "Mounts `team-container*` once and renders it again with each of - `team-ids`, in order. Resolves to the errors React reported and the - markup left in the document. + "Mounts `team-container*` once, with `team` as the store's team, and + renders it again with each of `team-ids`, in order. Resolves to + `{:renders [...] :console-errors [...]}`: one entry per render, holding + the markup the document had right after that render and the errors + React reported up to that point, plus everything React logged to + `console.error` while the sequence ran. + + Per render matters: a render error makes React drop the subtree, so + reading the document once at the end tells `renders nothing on purpose` + and `rendered and then crashed` apart from the errors alone. + + The console is part of the evidence because a hook-order violation is + reported there and as an internal React error, not through the root's + error callbacks: React logs it and recovers, so the callbacks stay + empty and the markup looks right. react-dom reads the global `window` while it renders, and its scheduler does so again on a later turn, so the jsdom one stays installed until - the root is unmounted and the scheduler has run. - - The effect is replaced by a hook that does nothing: the real one raises - for an invalid id, and what is under test is the render. It must still - take a hook slot, because React only compares the hooks of two renders - when the first one had any." - [team-ids] - (let [errors (volatile! []) - on-error (fn [error _info] (vswap! errors conj error)) - window (.-window (JSDOM. "
")) - container (.getElementById (.-document window) "root") - root (rdc/createRoot container #js {:onUncaughtError on-error - :onCaughtError on-error - :onRecoverableError on-error}) - child (mf/html [:span "inside"]) - previous (.-window js/globalThis)] + the root is unmounted and the scheduler has run." + [team team-ids] + (let [errors (volatile! []) + rendered (volatile! []) + console-errors (volatile! []) + on-error (fn [error _info] (vswap! errors conj error)) + window (.-window (JSDOM. "
")) + container (.getElementById (.-document window) "root") + root (rdc/createRoot container #js {:onUncaughtError on-error + :onCaughtError on-error + :onRecoverableError on-error}) + child (mf/html [:span "inside"]) + previous (.-window js/globalThis) + console (.-console js/globalThis) + console-error (.-error console) + torn-down (volatile! false) + teardown (fn [] + (when-not @torn-down + (vreset! torn-down true) + (rd/flushSync #(.unmount root)) + (.close window)))] (set! (.-window js/globalThis) window) + (set! (.-error console) + (fn [& args] (vswap! console-errors conj (str/join " " (mapv str args))))) (try - (with-redefs [refs/team (l/atom {:id team-id :permissions {:can-edit true}}) - mf/useEffect (fn [_f _deps] (mf/use-ref nil))] - (doseq [id team-ids] - (rd/flushSync - (fn [] - (.render root (mf/element (deref #'ui/team-container*) - #js {:teamId id :children child})))))) - (let [markup (.-innerHTML container)] - (rd/flushSync #(.unmount root)) - (await (next-immediate)) - {:errors @errors - :markup markup}) + ;; The root goes down from `finally` even when a render throws, and + ;; before the scheduler turn that closes the window behind it. + (try + ;; `with-redefs` restores the vars when the block ends, so every + ;; render under it must be synchronous. `flushSync` is; a promise + ;; is not, and defers past the restore. + (with-redefs [refs/team (l/atom team) + mf/useEffect (fn [_f _deps] (mf/use-ref nil))] + (doseq [id team-ids] + (rd/flushSync + (fn [] + (.render root (mf/element (deref #'ui/team-container*) + #js {:teamId id :children child})))) + (vswap! rendered conj {:markup (.-innerHTML container) + :errors @errors}))) + (finally + (teardown))) + (await (next-immediate)) (finally - (set! (.-window js/globalThis) previous))))) + (set! (.-error console) console-error) + (set! (.-window js/globalThis) previous))) + {:renders @rendered + :console-errors @console-errors})) + +(defn- messages + [result] + (mapv #(.-message %) (:errors result))) (t/deftest ^:async team-id-arriving-after-the-first-render-keeps-the-hooks - (let [{:keys [errors markup]} (await (render-with [nil team-id]))] - (t/is (empty? (map #(.-message %) errors))) - (t/is (str/includes? markup "inside")))) + (let [{:keys [renders console-errors]} + (await (render-with {:id team-id :permissions {:can-edit true}} + [nil team-id]))] + (t/is (empty? console-errors)) + (t/is (every? #(empty? (messages %)) renders)) + (t/is (str/includes? (:markup (last renders)) "inside")))) (t/deftest ^:async team-id-leaving-after-the-first-render-keeps-the-hooks - (let [{:keys [errors markup]} (await (render-with [team-id nil]))] - (t/is (empty? (map #(.-message %) errors))) - (t/is (= "" markup)))) + ;; This direction is not what React flags: a render that calls no hooks + ;; at all slips through its bookkeeping, so the guard is covered here + ;; and the hook regression is the `nil` -> uuid case above. + (let [{:keys [renders console-errors]} + (await (render-with {:id team-id :permissions {:can-edit true}} + [team-id nil]))] + (t/is (empty? console-errors)) + (t/is (every? #(empty? (messages %)) renders)) + (t/is (str/includes? (:markup (first renders)) "inside")) + ;; The guard drops the children on purpose, so the second render is + ;; empty for its own reason and not because React removed the subtree. + (t/is (= "" (:markup (last renders)))))) + +(t/deftest ^:async team-container-renders-nothing-when-the-route-team-is-not-the-store-team + ;; A valid uuid that does not match the team held in the store must not + ;; paint: the providers would otherwise wrap another team's children. + (let [{:keys [renders console-errors]} + (await (render-with {:id (uuid/next) :permissions {:can-edit true}} + [team-id])) + result (last renders)] + (t/is (empty? console-errors)) + (t/is (empty? (messages result))) + (t/is (= "" (:markup result))))) + +(t/deftest ^:async team-container-renders-the-team-when-the-profile-has-no-permissions + (let [{:keys [renders console-errors]} + (await (render-with {:id team-id :permissions nil} + [team-id])) + result (last renders)] + (t/is (empty? console-errors)) + (t/is (empty? (messages result))) + (t/is (str/includes? (:markup result) "inside"))))