iterate.com / ui

git clone https://git.iterate.com/repos/ui

packages/ui of iterate/private at b57e184844d40fd1df428c55d9da4291f110dc1b

Via: apps/ui/release-round.mjs of /repos/config

ui release builder, 2026-11-26 23:29 UTC · c35a49357c06026b8cf833dd25635a336a615ab6 · parent 2dad9d7

5 files changed

M src/components/context-catalog/catalog-collection.test.ts
@@ -263,6 +263,126 @@
   expect(said).toEqual(["none"]);
 });
 
+test("two key loads that overlap both settle: the first waits for the watch that replaced its own", async () => {
+  const catalog = fakeCatalog();
+  catalog.put("/a", 10);
+  catalog.put("/b", 20);
+  const { contexts } = page(catalog);
+  const one = createLiveQueryCollection((q) =>
+    q.from({ c: contexts }).where(({ c }) => eq(c.path, "/a")),
+  );
+  const first = one.preload();
+  // the first keys watch is sent, and its answer is not here yet
+  await Promise.resolve();
+  await Promise.resolve();
+  const two = createLiveQueryCollection((q) =>
+    q.from({ c: contexts }).where(({ c }) => eq(c.path, "/b")),
+  );
+  await Promise.all([first, two.preload()]);
+  expect(one.toArray.map((row) => row.path)).toEqual(["/a"]);
+  expect(two.toArray.map((row) => row.path)).toEqual(["/b"]);
+  expect(catalog.calls.map((call) => call.query.keys)).toEqual([["/a"], ["/a", "/b"]]);
+});
+
+test("a row that has its old revision after the catalog made its tables again is written again", async () => {
+  const catalog = fakeCatalog();
+  catalog.put("/a", 10, { description: "before" });
+  const { contexts } = page(catalog);
+  const recent = createLiveQueryCollection((q) =>
+    q
+      .from({ c: contexts })
+      .orderBy(({ c }) => c.activeMs, "desc")
+      .limit(5),
+  );
+  await recent.preload();
+  expect(contexts.get("/a")).toMatchObject({ description: "before", rev: 1 });
+  catalog.madeAgain((rows) => {
+    const row = rows.get("/a");
+    if (row) rows.set("/a", { ...row, description: "after" });
+  });
+  catalog.newSession();
+  await tick();
+  expect(contexts.get("/a")).toMatchObject({ description: "after", rev: 1 });
+});
+
+test("a query with no limit says so when more rows match than the catalog holds, and stops saying it", async () => {
+  const catalog = fakeCatalog();
+  for (let n = 0; n < 499; n++) catalog.put(`/t/${String(n)}`, n, { metadata: { kind: "t" } });
+  const { contexts } = page(catalog);
+  const all = createLiveQueryCollection((q) =>
+    q.from({ c: contexts }).where(({ c }) => eq(c.metadata?.kind, "t")),
+  );
+  await all.preload();
+  expect(contexts.utils.demands()).toMatchObject([{ rows: 499, full: false }]);
+  catalog.put("/t/more", 1_000, { metadata: { kind: "t" } });
+  await tick();
+  expect(contexts.utils.demands()).toMatchObject([{ rows: 500, full: true }]);
+  catalog.remove("/t/more");
+  await tick();
+  expect(contexts.utils.demands()).toMatchObject([{ rows: 499, full: false }]);
+});
+
+test("more keys than the catalog watches are refused with the reason, and the keys watch before stays", async () => {
+  const catalog = fakeCatalog();
+  catalog.put("/a", 10, { description: "one" });
+  const { contexts } = page(catalog);
+  const one = createLiveQueryCollection((q) =>
+    q.from({ c: contexts }).where(({ c }) => eq(c.path, "/a")),
+  );
+  await one.preload();
+  const many = createLiveQueryCollection((q) =>
+    q.from({ c: contexts }).where(({ c }) =>
+      inArray(
+        c.path,
+        Array.from({ length: 500 }, (_, n) => `/k/${String(n)}`),
+      ),
+    ),
+  );
+  await expect(many.preload()).rejects.toThrow(/501 contexts by path/);
+  catalog.put("/a", 20, { description: "two" });
+  await tick();
+  expect(one.toArray).toMatchObject([{ description: "two" }]);
+});
+
+test("a refusal that is not the query's makes the catalog no source, a limit of watches does not, and a later probe makes it live", async () => {
+  const catalog = fakeCatalog();
+  const watcher = catalogWatcher(catalog.itx);
+  catalog.refuseNext("UNAVAILABLE");
+  watcher.probe();
+  await tick();
+  expect(watcher.support()).toBe("none");
+  watcher.probe();
+  await tick();
+  expect(watcher.support()).toBe("live");
+  // the session is at its limit: this watch is refused, and the catalog is a source as before
+  catalog.refuseNext("WATCH_LIMIT");
+  const refused = watcher.watch({ awake: true }, CatalogAwakeRow, () => {});
+  await expect(refused.ready).rejects.toThrow();
+  expect(watcher.support()).toBe("live");
+  // the catalog itself failed: an error with no code
+  catalog.refuseNext("");
+  const failed = watcher.watch({ awake: true }, CatalogAwakeRow, () => {});
+  await expect(failed.ready).rejects.toThrow();
+  expect(watcher.support()).toBe("none");
+});
+
+test("a batch whose last frame never comes is ended by the page itself", async () => {
+  const catalog = fakeCatalog();
+  catalog.put("/a", 10);
+  const watcher = catalogWatcher(catalog.itx);
+  const watch = watcher.watch({ order: "active", limit: 10 }, CatalogRow, () => {});
+  await watch.ready;
+  let ends = 0;
+  watcher.onBatch(() => (ends += 1));
+  const [live] = catalog.watching;
+  live?.onFrame({ type: "change", gen: "g1", from: 1, rev: 2, del: ["/a"], rows: [], more: true });
+  expect(watcher.batchOpen()).toBe(true);
+  expect(ends).toBe(0);
+  await new Promise((resolve) => setTimeout(resolve, 80));
+  expect(watcher.batchOpen()).toBe(false);
+  expect(ends).toBe(1);
+});
+
 test("a watch asked before the page's first socket is open is asked once, and a platform without the watch is heard", async () => {
   // a page's session as memberItx says it: no socket yet, then the socket, then the proof
   let connection: ItxConnection = { epoch: 0, state: "opening" };
M src/components/context-catalog/catalog-collection.ts
@@ -31,6 +31,14 @@
 // guessed window gives wrong rows. With no limit, the facts go to the catalog and TanStack DB
 // filters the rest in the page.
 //
+// THE CATALOG'S MATCH OF A FACT IS WIDER THAN THE PAGE'S: it matches a value as its text (`1` and
+// `"1"`) and as an item of a list. TanStack DB filters the rows again with the query's own `eq`
+// or `inArray`, which are strict. So write the form that the stored value has: `eq` for a scalar,
+// `inArray(value, c.metadata.x)` for a list, a number for a number. A window with a limit whose
+// query uses the other form holds rows that the page then drops, and shows fewer rows than exist.
+// `eq(c.activeMs, x)` and `eq(c.createdMs, x)` load no row: they are what TanStack DB asks for
+// the rows that tie with a window's last, which the catalog has sent already.
+//
 // A MIND WHOSE PLATFORM HAS NO `contexts.watch` refuses the first watch: `watcher.support()` then
 // says "none", and the page reads the catalog as before (`useContextCatalog` polls
 // `contexts.list`).
@@ -168,7 +176,15 @@
 /** What a watch tells its holder after each frame is in `rows`: the paths that left and the rows
  *  that came or changed. `answer` marks the answer to a watch that started. `error` is a refusal:
  *  the watch has ended. */
-export type CatalogChange<Row> = { del: string[]; put: Row[]; answer?: true; error?: string };
+export type CatalogChange<Row> = {
+  del: string[];
+  put: Row[];
+  answer?: true;
+  /** The answer is the whole truth (a `reset`): a row's revision may be one that this page has
+   *  seen for other content, since a catalog that made its tables again counts from 0. */
+  whole?: true;
+  error?: string;
+};
 
 /** One query that the catalog keeps answering. `rows` is its answer now. */
 export type CatalogWatch<Row> = {
@@ -187,9 +203,12 @@
 };
 
 /** Whether the mind's catalog answers a watch: "asking" until the first frame or the first
- *  refusal, then "live". "none" for a platform without `contexts.watch`, and from then on for a
- *  catalog that stopped being a source (it refused a watch for a reason that is not the query's,
- *  or a watch lost its place three times in half a minute): the page then reads the list. */
+ *  refusal, then "live". "none" while it is no source: a platform without `contexts.watch`
+ *  (`NOT_A_METHOD`), a catalog that could not be reached (`UNAVAILABLE`) or that failed (an error
+ *  with no code), or a watch that lost its place three times in half a minute. The page then
+ *  reads the list, and `probe()` asks again. `INVALID_INPUT` (this query cannot be answered) and
+ *  `WATCH_LIMIT` (the session has 64 watches, or the mind 512 live queries) refuse one watch
+ *  and say nothing of the catalog. */
 export type CatalogSupport = "asking" | "live" | "none";
 
 export type CatalogWatcher = {
@@ -205,7 +224,13 @@
   /** `end()` runs after the last frame of each batch. One write of the catalog is one batch over
    *  all of this page's queries, so a holder applies it as one transaction. */
   onBatch(end: () => void): () => void;
+  /** True between a frame that says `more` and the end of its batch. */
+  batchOpen(): boolean;
   support(): CatalogSupport;
+  /** Asks, with one watch of the awake list that ends with its answer, whether the catalog is a
+   *  source now: `support()` then says "live", or "none" for any refusal. A page asks at its
+   *  start, and again later while it reads the list. */
+  probe(): void;
   /** For `useSyncExternalStore`: `changed` runs when `support()` answers another word. */
   subscribe(changed: () => void): () => void;
   /** Ends every watch and leaves the session. */
@@ -277,6 +302,16 @@
     return { ...base, bound: last ? sortKeyOf(last, order) : null };
   }
 
+  // ONE WRITE IS ONE BATCH: every frame but the last says `more`. A batch also gets an end of
+  // this page's own, since the catalog cuts a very long message in two and a frame can be lost
+  // with its session: a transaction must not stay open.
+  let batchTimer: ReturnType<typeof setTimeout> | undefined;
+  const endBatch = () => {
+    clearTimeout(batchTimer);
+    batchTimer = undefined;
+    for (const end of batchEnds) end();
+  };
+
   function refuse(held: Held<{ path: string }>, error: string) {
     held.error = error;
     release(held);
@@ -319,9 +354,10 @@
       if (held.start !== started) return;
       // the session went away under the call: its next epoch starts the watch again
       if (sessionNow() !== asked || session.get().state !== "open") return;
-      // INVALID_INPUT is the refusal of this query. Any other refusal is of the watch itself: a
-      // platform that has no `contexts.watch`, or a catalog that does not answer.
-      if (Coded.safeParse(caught).data?.code !== "INVALID_INPUT") say("none");
+      // INVALID_INPUT and WATCH_LIMIT refuse this watch alone. Any other refusal says that the
+      // catalog is no source now (`CatalogSupport`).
+      const code = Coded.safeParse(caught).data?.code;
+      if (code !== "INVALID_INPUT" && code !== "WATCH_LIMIT") say("none");
       refuse(held, caught instanceof Error ? caught.message : String(caught));
     });
     // The catalog ended the watch and this page did not: watch again. A session that went away
@@ -338,6 +374,10 @@
       );
   }
 
+  /** A window is full when it holds its limit: more rows may match than it holds. */
+  const fullOf = (held: Held<{ path: string }>) =>
+    kindOf(held.query) === "window" && held.rows.size >= (held.query.limit || 50);
+
   /** Starts a watch that lost its place, or gives the catalog up with `reason`. */
   function startAgain(held: Held<{ path: string }>, reason: string) {
     const now = Date.now();
@@ -365,7 +405,10 @@
       }
     }
     // The batch ends with its last frame, whoever that frame was for.
-    if (!parsed.success || !parsed.data.more) for (const end of batchEnds) end();
+    if (parsed.success && parsed.data.more) {
+      clearTimeout(batchTimer);
+      batchTimer = setTimeout(endBatch, 50);
+    } else endBatch();
   }
 
   function apply(held: Held<{ path: string }>, frame: z.infer<typeof Frame>) {
@@ -384,11 +427,12 @@
       for (const row of rows) held.rows.set(row.path, row);
       held.rev = frame.rev;
       held.frames += 1;
+      held.full = fullOf(held);
       held.onChange({ del: frame.del, put: rows });
       return;
     }
-    // The answer to a start: every row (`reset`), or every path with only the rows that this
-    // page lacks (`resume`).
+    // An answer: every row (`reset`, which may come at any time and is the whole truth), or every
+    // path with only the rows that this page lacks (`resume`).
     const keep = new Set(frame.type === "reset" ? rows.map((row) => row.path) : frame.ids);
     const del = [...held.rows.keys()].filter((path) => !keep.has(path));
     for (const path of del) held.rows.delete(path);
@@ -399,13 +443,14 @@
     held.full = frame.full;
     held.error = undefined;
     held.answers += 1;
-    held.onChange({ del, put: rows, answer: true });
+    held.onChange({ del, put: rows, answer: true, ...(frame.type === "reset" && { whole: true }) });
     held.resolveReady();
   }
 
   // A new session: every watch of the last one ended with it. The watcher is in the session's
   // list only while it holds a watch, since a page with a subscriber is one that lives on over
   // a new session (#/lib/itx-session.ts).
+  let probing = false;
   let leave: (() => void) | undefined;
   const follow = () => {
     epoch = sessionNow();
@@ -454,6 +499,8 @@
         stop() {
           if (!watches.delete(erased)) return;
           release(erased);
+          // whoever waits for its first answer hears that none comes
+          settle.reject(new Error("the watch was stopped"));
           unfollow();
         },
       };
@@ -477,7 +524,26 @@
       batchEnds.add(end);
       return () => batchEnds.delete(end);
     },
+    batchOpen: () => Boolean(batchTimer),
     support: () => support,
+    probe() {
+      if (probing) return;
+      probing = true;
+      const asked = this.watch({ awake: true }, z.object({ path: z.string() }), () => {});
+      void asked.ready
+        .then(
+          () => {
+            say("live");
+          },
+          () => {
+            say("none");
+          },
+        )
+        .finally(() => {
+          probing = false;
+          asked.stop();
+        });
+    },
     subscribe(changed) {
       supportListeners.add(changed);
       return () => supportListeners.delete(changed);
@@ -698,7 +764,15 @@
     utils: { demands: describe },
     sync: {
       rowUpdateMode: "full",
-      sync: ({ begin, write, commit, markReady, collection }: SyncParams<ContextRow>) => {
+      sync: ({
+        begin,
+        write,
+        commit,
+        markReady,
+        reportError,
+        reportHealthy,
+        collection,
+      }: SyncParams<ContextRow>) => {
         // One batch of the catalog is one write over ALL of this page's queries: it becomes one
         // transaction here, so a join of two of this collection's queries never sees half of it.
         let open = false;
@@ -719,12 +793,13 @@
         const stopBatches = watcher.onBatch(finish);
         const revOf = (path: string) =>
           written.has(path) ? written.get(path) : (collection.get(path)?.rev ?? false);
-        const hold = (demand: object, row: CatalogRow) => {
+        const hold = (demand: object, row: CatalogRow, whole: boolean) => {
           const held = holders.get(row.path) ?? new Set();
           holders.set(row.path, held);
           held.add(demand);
           const now = revOf(row.path);
-          if (now === row.rev) return;
+          // a row of a whole answer is written whatever its revision says (`CatalogChange`)
+          if (now === row.rev && !whole) return;
           transaction();
           const value = contextRow(row);
           if (now === false) write({ type: "insert", value });
@@ -750,8 +825,25 @@
           for (const path of change.del) release(demand, path);
           // an answer is the query's whole set: also the rows that the cursor said are here
           const rows = change.answer ? (watch()?.rows.values() ?? change.put) : change.put;
-          for (const row of rows) hold(demand, row);
+          for (const row of rows) hold(demand, row, Boolean(change.whole));
         };
+        /** A query with no limit shows every row that matches, or says that it cannot: the
+         *  catalog holds 500 of them, and takes the least active out when one more enters. */
+        const tooMany = new Map<object, Error>();
+        const checkAll = (demand: Demand) => {
+          if (!demand.unlimited) return;
+          const said = tooMany.get(demand);
+          if (demand.watch.full && !said) {
+            const error = new Error(
+              `more than ${String(demand.watch.rows.size - 1)} rows match a query with no limit, and the catalog holds ${String(demand.watch.rows.size)}: say an order and a limit`,
+            );
+            tooMany.set(demand, error);
+            reportError(error);
+          } else if (!demand.watch.full && said) {
+            tooMany.delete(demand);
+            reportHealthy(said);
+          }
+        };
         const end = (demand: object, watch: CatalogWatch<CatalogRow> | undefined) => {
           watch?.stop();
           for (const path of watch?.rows.keys() ?? []) release(demand, path);
@@ -765,10 +857,16 @@
           if (keys.length === 0) {
             keysDemand.watch = undefined;
             end(keysDemand, before);
-            finish();
+            // a batch that is open commits at its own end
+            if (!watcher.batchOpen()) finish();
             return;
           }
-          if (JSON.stringify(before?.query.keys) === JSON.stringify(keys)) return before?.ready;
+          if (JSON.stringify(before?.query.keys) === JSON.stringify(keys)) return;
+          // The watch before stays, and its rows stay true, when the catalog cannot take this one.
+          if (keys.length > CATALOG_WINDOW_LIMIT)
+            throw new Error(
+              `the joins of this page ask for ${String(keys.length)} contexts by path, and the catalog watches ${String(CATALOG_WINDOW_LIMIT)} at most: join fewer rows`,
+            );
           const watch = watcher.watch(
             { keys },
             CatalogRow,
@@ -780,8 +878,19 @@
           keysDemand.watch = watch;
           // the new query's answer names every row it holds: what only the old one held goes
           before?.stop();
-          await watch.ready;
         };
+        /** Until the keys watch that is current has answered. A load that waited for a watch
+         *  which another load replaced waits for the newer one. */
+        const keysAnswered = async (): Promise<void> => {
+          const watch = keysDemand.watch;
+          if (!watch) return;
+          try {
+            await watch.ready;
+          } catch (caught) {
+            if (keysDemand.watch === watch) throw caught;
+          }
+          if (keysDemand.watch !== watch) return keysAnswered();
+        };
         const demandKeys = (keys: readonly string[], by: 1 | -1) => {
           for (const key of keys) {
             const count = (keyHolds.get(key) ?? 0) + by;
@@ -790,7 +899,7 @@
           }
           if (keysDemand.scheduled) return keysDemand.settled;
           keysDemand.scheduled = true;
-          keysDemand.settled = Promise.resolve().then(sendKeys);
+          keysDemand.settled = Promise.resolve().then(sendKeys).then(keysAnswered);
           // an unload waits for nothing: its refusal is the load's to hear
           keysDemand.settled.catch(() => {});
           return keysDemand.settled;
@@ -831,6 +940,7 @@
                   CatalogRow,
                   (change) => {
                     apply(made, () => made.watch, change);
+                    checkAll(made);
                   },
                   like,
                 ),
@@ -839,18 +949,9 @@
               demands.set(key, demand);
             }
             demand.holds += 1;
-            const { watch, unlimited } = demand;
-            const check = () => {
-              if (unlimited && watch.full)
-                throw new Error(
-                  `more than ${String(watch.rows.size)} rows match and the query has no limit: say an order and a limit`,
-                );
-            };
-            if (watch.answers > 0 && receipt === true) {
-              check();
-              return true;
-            }
-            return watch.ready.then(check).then(visible);
+            const { watch } = demand;
+            if (watch.answers > 0 && receipt === true) return true;
+            return watch.ready.then(visible);
           },
           unloadSubset: (options) => {
             let asked: ReturnType<typeof catalogQueryOf>;
@@ -870,8 +971,12 @@
             demand.holds -= 1;
             if (demand.holds > 0) return;
             demands.delete(key);
+            const said = tooMany.get(demand);
+            tooMany.delete(demand);
+            if (said) reportHealthy(said);
             end(demand, demand.watch);
-            finish();
+            // a batch that is open commits at its own end
+            if (!watcher.batchOpen()) finish();
           },
           cleanup: () => {
             stopBatches();
@@ -919,9 +1024,12 @@
         const stopBatches = watcher.onBatch(() => {
           if (!open) return;
           open = false;
+          pending.clear();
           commit();
           markReady();
         });
+        const pending = new Map<string, boolean>();
+        const here = (path: string) => pending.get(path) ?? collection.has(path);
         const watch = watcher.watch(query, row, ({ del, put, error }) => {
           if (error) {
             fail(new Error(error));
@@ -929,9 +1037,16 @@
           }
           if (!open) begin();
           open = true;
-          for (const path of del) if (collection.has(path)) write({ type: "delete", key: path });
-          for (const value of put)
-            write({ type: collection.has(value.path) ? "update" : "insert", value });
+          // what the open transaction did is not in the collection yet
+          for (const path of del)
+            if (here(path)) {
+              write({ type: "delete", key: path });
+              pending.set(path, false);
+            }
+          for (const value of put) {
+            write({ type: here(value.path) ? "update" : "insert", value });
+            pending.set(value.path, true);
+          }
         });
         return () => {
           stopBatches();
M src/components/context-catalog/context-catalog-live.test.tsx
@@ -5,7 +5,7 @@
 import { createRoot } from "react-dom/client";
 import { expect, test, vi } from "vitest";
 import type { CatalogItx } from "./catalog-collection.ts";
-import { useWatchedContextCatalog } from "./context-catalog-live.ts";
+import { catalogOf, useWatchedContextCatalog } from "./context-catalog-live.ts";
 import type { ContextListing } from "./context-catalog-rows.ts";
 import { fakeCatalog } from "#/test-support/fake-catalog.ts";
 
@@ -33,8 +33,8 @@
     ["/agents/b", undefined],
   ]);
   expect(page.last()?.error).toBeUndefined();
-  // one watch that asks whether the mind answers one; then two for the page's life, the window
-  // and the awake list; and no poll
+  // one watch that asks whether the catalog is a source; then two for the page's life, the
+  // window and the awake list; and no poll
   expect(catalog.calls.map((call) => call.query)).toEqual([
     { awake: true },
     { order: "active", limit: 500 },
@@ -65,6 +65,35 @@
   expect(list).toHaveBeenCalledTimes(1);
   // the refusal is an answer: nothing failed, so nothing is said on the console
   expect(errors).not.toHaveBeenCalled();
+});
+
+test.for(["UNAVAILABLE", "WATCH_LIMIT", ""])(
+  "a mind that refuses the first watch with %j is asked for the list too",
+  async (code) => {
+    const catalog = fakeCatalog();
+    catalog.put("/agents/a", 10);
+    catalog.refuseNext(code);
+    const list = vi.fn(() => Promise.resolve([]));
+    using page = await drawn(catalog.itx, list);
+    expect(page.last()).toEqual({ rows: [], error: undefined });
+    expect(list).toHaveBeenCalledTimes(1);
+  },
+);
+
+test("when the catalog is a source again, the rows are pushed again, from collections made anew", async () => {
+  const catalog = fakeCatalog();
+  catalog.put("/agents/a", 10);
+  const list = vi.fn(() => Promise.resolve([]));
+  catalog.refuseNext("UNAVAILABLE");
+  using page = await drawn(catalog.itx, list);
+  expect(page.last()?.rows).toEqual([]);
+  const before = catalogOf(catalog.itx).contexts;
+  await act(async () => {
+    catalogOf(catalog.itx).watcher.probe();
+    await settled();
+  });
+  expect(page.last()?.rows?.map((row) => row.path)).toEqual(["/agents/a"]);
+  expect(catalogOf(catalog.itx).contexts === before).toBe(false);
 });
 
 /** Draws the hook, and answers what it last returned. */
M src/components/context-catalog/context-catalog-live.ts
@@ -30,6 +30,7 @@
   contextsCollectionOptions,
   watchedQueryCollectionOptions,
   type CatalogItx,
+  type CatalogWatcher,
 } from "./catalog-collection.ts";
 import { useContextCatalog } from "./context-catalog-list.tsx";
 import type { ContextListing } from "./context-catalog-rows.ts";
@@ -37,8 +38,7 @@
 /** A window's order and a join's key are read through an index of the rows that are here. */
 const INDEXED = { defaultIndexType: BasicIndex, autoIndex: "eager" } as const;
 
-function collectionsOf(itx: CatalogItx) {
-  const watcher = catalogWatcher(itx);
+function collectionsOf(watcher: CatalogWatcher) {
   /** The whole catalog, on demand: a live query of it is a query of the catalog. */
   const contexts = createCollection(contextsCollectionOptions({ watcher, index: INDEXED }));
   /** The contexts that have work now. A join reads it by path, through an index. */
@@ -64,22 +64,53 @@
       .from({ context: recent })
       .join({ awake }, ({ context, awake: row }) => eq(context.path, row.path), "left"),
   );
-  return { watcher, contexts, awake, listings };
+  return { contexts, awake, listings };
 }
 
-const catalogs = new WeakMap<object, ReturnType<typeof collectionsOf>>();
+/** One mind's catalog as a page holds it: the watcher, and the collections that read through it. */
+export type MindCatalog = { watcher: CatalogWatcher } & Readonly<ReturnType<typeof collectionsOf>>;
 
+const catalogs = new WeakMap<object, MindCatalog>();
+
 /** THE CATALOG OF ONE MIND, for the life of the page, whoever asks: one watcher and one set of
- *  collections for an `itx`. A collection that no query reads holds no watch. */
-export function catalogOf(itx: CatalogItx): ReturnType<typeof collectionsOf> {
-  const held = catalogs.get(itx) ?? collectionsOf(itx);
-  catalogs.set(itx, held);
-  return held;
+ *  collections for an `itx`. A collection that no query reads holds no watch. WHEN THE CATALOG
+ *  IS A SOURCE AGAIN after it was none, the collections are made anew: a watch that the catalog
+ *  refused has ended, and its collection would hold rows that nothing keeps true. So read
+ *  `catalogOf(itx).contexts` where the query is written, and keep no collection in a variable. */
+export function catalogOf(itx: CatalogItx): MindCatalog {
+  const held = catalogs.get(itx);
+  if (held) return held;
+  const watcher = catalogWatcher(itx);
+  let collections = collectionsOf(watcher);
+  let wasNone = false;
+  // for the page's life, as the watcher is: nothing ends this subscription
+  watcher.subscribe(() => {
+    const support = watcher.support();
+    if (support === "none") wasNone = true;
+    if (support !== "live" || !wasNone) return;
+    wasNone = false;
+    collections = collectionsOf(watcher);
+  });
+  const made: MindCatalog = {
+    watcher,
+    get contexts() {
+      return collections.contexts;
+    },
+    get awake() {
+      return collections.awake;
+    },
+    get listings() {
+      return collections.listings;
+    },
+  };
+  catalogs.set(itx, made);
+  return made;
 }
 
 /** The catalog's rows, pushed by the mind: the 500 most recently active contexts, the newest
  *  first, each with `awake` and `activities` when it has work now. `rows` is undefined until the
- *  first answer. On a platform without `contexts.watch` the rows are `list`'s, asked again every
+ *  first answer. While the catalog is no source (`CatalogSupport`: a platform without
+ *  `contexts.watch`, a catalog that cannot be reached) the rows are `list`'s, asked again every
  *  `pollMs` (`useContextCatalog`). `of` names whose catalog it is (the mind's address). */
 export function useWatchedContextCatalog(
   itx: CatalogItx,
@@ -92,19 +123,24 @@
     catalog.watcher.support,
     catalog.watcher.support,
   );
-  // WHETHER THE MIND ANSWERS A WATCH is asked with one watch of the awake list, before a
-  // collection reads anything: a refusal is then an answer here, and no failed load of a query.
-  // The watch ends with the answer, and the awake collection then starts its own.
+  // WHETHER THE CATALOG IS A SOURCE is asked before a collection reads anything: a refusal is
+  // then an answer here, and no failed load of a query. While the page reads the list, it asks
+  // again each minute: after a deploy the catalog cannot be reached for up to a minute, and a
+  // session at its limit of watches gets room again.
   useEffect(() => {
-    if (support !== "asking") return;
-    const asked = catalog.watcher.watch({ awake: true }, CatalogAwakeRow, () => {});
+    if (support === "asking") catalog.watcher.probe();
+    if (support !== "none") return;
+    const timer = setInterval(() => {
+      catalog.watcher.probe();
+    }, 60_000);
     return () => {
-      asked.stop();
+      clearInterval(timer);
     };
   }, [catalog, support]);
   const polled = useContextCatalog(support === "none" ? list : null, { of, pollMs });
+  const listings = support === "live" ? catalog.listings : undefined;
   const live = useLiveQuery({
-    query: (q) => (support === "live" ? q.from({ listing: catalog.listings }) : undefined),
+    query: (q) => (listings ? q.from({ listing: listings }) : undefined),
   });
   const data = live.isReady ? live.data : undefined;
   const rows = useMemo(
M src/test-support/fake-catalog.ts
@@ -1,3 +1,8 @@
+// WHERE IT IS NOT THE ENGINE: a fact matches by strict equality (the engine matches a value as its
+// text), there is no limit of watches or of keys, and `putAwake` sends a row and the awake list in
+// one batch, which the engine does not. The proof against the engine itself is a test that runs in
+// a checkout of /repos/kernel (the pull request of this file says where).
+//
 // A MIND'S CATALOG IN MEMORY, for a test of what watches it (components/context-catalog): it
 // answers `contexts.watch` as iterate/api says a watch does. The first frame is a `reset`, or a
 // `resume` for a cursor of this generation and this query; then one `change` for each write that
@@ -31,6 +36,9 @@
   let gen = "g1";
   let connection: ItxConnection = { epoch: 1, state: "open" };
   const sessionListeners = new Set<() => void>();
+  /** The codes that the next calls of `watch` are refused with, one each ("" is an error with no
+   *  code). */
+  const refusals: string[] = [];
 
   const revOf = (row: Row) => ("rev" in row ? row.rev : 0);
   function answerOf(query: CatalogQuery): Row[] {
@@ -45,7 +53,15 @@
           return Array.isArray(held) ? held.includes(value) : held === value;
         }),
       )
-      .filter((row) => !query.under || row.path.startsWith(query.under))
+      .filter(
+        (row) => !query.under || row.path === query.under || row.path.startsWith(`${query.under}/`),
+      )
+      .filter(
+        (row) =>
+          !query.childrenOf ||
+          (row.path.startsWith(`${query.childrenOf === "/" ? "" : query.childrenOf}/`) &&
+            !row.path.slice(query.childrenOf.length + 1).includes("/")),
+      )
       .toSorted((a, b) => compareCatalogRows(a, b, order))
       .slice(0, query.limit ?? 50);
   }
@@ -83,7 +99,16 @@
         await Promise.resolve();
         if (query.where && "refused" in query.where)
           throw Object.assign(new Error("the catalog refuses this"), { code: "INVALID_INPUT" });
-        const q = JSON.stringify(query);
+        if (refusals.length > 0) {
+          const code = refusals.shift();
+          throw Object.assign(
+            new Error(`the catalog says ${code || "nothing"}`),
+            code ? { code } : {},
+          );
+        }
+        // as the engine names a query: by what it selects, not by its keys and not by its limit
+        const { keys: _keys, limit: _limit, ...selects } = query;
+        const q = JSON.stringify(query.keys ? "keys" : selects);
         const answer = answerOf(query);
         const watch: Watching = {
           query,
@@ -122,10 +147,13 @@
             full: answer.length === query.limit,
             rows: answer,
           });
+        const ended = Promise.withResolvers<string>();
         return {
           [Symbol.dispose]: () => {
             watching.delete(watch);
+            ended.resolve("the watcher ended it");
           },
+          ended: () => ended.promise,
         };
       },
     },
@@ -167,6 +195,17 @@
       if (newGeneration) gen = "g2";
       connection = { epoch: connection.epoch + 1, state: "open" };
       for (const changed of sessionListeners) changed();
+    },
+    /** The next calls of `watch` are refused with these codes, one each. */
+    refuseNext(...codes: string[]) {
+      refusals.push(...codes);
+    },
+    /** The catalog made its tables again: another generation, whose revisions count from 0, so
+     *  a row can have the revision that it had before with other content. `edit` changes rows
+     *  and keeps each revision. */
+    madeAgain(edit: (rows: Map<string, CatalogRow>) => void) {
+      edit(rows);
+      gen = `${gen}'`;
     },
     /** A frame that the catalog never sent: the next change then comes with a gap. */
     skipFrame() {