fsanyoto commited on
Commit
b47a3dc
·
verified ·
1 Parent(s): c6d0f9c

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "e0555c8",
3
  "releases": [
4
  {
5
  "version": "v75",
 
1
  {
2
+ "current": "7cfc5df",
3
  "releases": [
4
  {
5
  "version": "v75",
VERSION CHANGED
@@ -1 +1 @@
1
- e0555c8
 
1
+ 7cfc5df
api/routes_admin.py CHANGED
@@ -2091,8 +2091,13 @@ def _confines_to_one_bu(tree):
2091
  return any(kids) if node.get("conj") == "or" else all(kids)
2092
  if node.get("colId") != "dba":
2093
  return True # every other condition: assume satisfied
2094
- want = str(node.get("value") or "").strip().lower()
2095
  op = node.get("op")
 
 
 
 
 
 
2096
  if op == "eq":
2097
  return brand.lower() == want
2098
  if op == "neq":
@@ -2107,6 +2112,8 @@ def _confines_to_one_bu(tree):
2107
  return True
2108
  return True # an op that cannot judge a brand does not confine
2109
 
 
 
2110
  nodes, conj = (tree.get("nodes") or []), tree.get("conj", "and")
2111
  root = {"conj": conj, "children": nodes}
2112
  admitted = {b for b in ("Fisch", "Royal", "Both") if admits(root, b)}
 
2091
  return any(kids) if node.get("conj") == "or" else all(kids)
2092
  if node.get("colId") != "dba":
2093
  return True # every other condition: assume satisfied
 
2094
  op = node.get("op")
2095
+ if op in fe.MULTI_VALUE_OPS:
2096
+ # HOTFIX 2026-09-23: `dba is any of [Royal]` is the shape the condition builder writes
2097
+ # now, and `perm_scope` already reads it. Falling to "cannot judge" here made a save
2098
+ # that KEPT the BU condition read as one that removed it, and refused it as bu_widening.
2099
+ return fe._match_multi_value(op, brand, fe.parse_filter_values(node.get("values")))
2100
+ want = str(node.get("value") or "").strip().lower()
2101
  if op == "eq":
2102
  return brand.lower() == want
2103
  if op == "neq":
 
2112
  return True
2113
  return True # an op that cannot judge a brand does not confine
2114
 
2115
+ from harness import filter_eval as fe
2116
+
2117
  nodes, conj = (tree.get("nodes") or []), tree.get("conj", "and")
2118
  root = {"conj": conj, "children": nodes}
2119
  admitted = {b for b in ("Fisch", "Royal", "Both") if admits(root, b)}
api/routes_connected_tables.py CHANGED
@@ -62,6 +62,8 @@ def connected_table_rows(table_key: str,
62
  sorts: str = Query(default=None),
63
  search: str = Query(default=None),
64
  related: str = Query(default=None),
 
 
65
  session: Session = Depends(require_session)):
66
  """ONE WINDOW over a connected grid — `{fields, rows, total, totalUnfiltered, offset, limit,
67
  limits, identity, recordsMutable}`, whichever connector the rows come from.
@@ -89,4 +91,5 @@ def connected_table_rows(table_key: str,
89
  import routes_odoo_tables
90
  return routes_odoo_tables.odoo_table_rows(
91
  table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,
92
- sorts=sorts, search=search, related=related, session=session)
 
 
62
  sorts: str = Query(default=None),
63
  search: str = Query(default=None),
64
  related: str = Query(default=None),
65
+ groupBy: str = Query(default=None),
66
+ groupKey: str = Query(default=None),
67
  session: Session = Depends(require_session)):
68
  """ONE WINDOW over a connected grid — `{fields, rows, total, totalUnfiltered, offset, limit,
69
  limits, identity, recordsMutable}`, whichever connector the rows come from.
 
91
  import routes_odoo_tables
92
  return routes_odoo_tables.odoo_table_rows(
93
  table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,
94
+ sorts=sorts, search=search, related=related, groupBy=groupBy, groupKey=groupKey,
95
+ session=session)
api/routes_external.py CHANGED
@@ -747,8 +747,13 @@ def _markdown_inline(value) -> str:
747
  return " ".join(text.replace("`", "'").split())
748
 
749
 
750
- def _portable_skill_document(session: Session, base_url: str) -> str:
751
- scoped = [
 
 
 
 
 
752
  row for row in _resolve_external_scope(session, include_schema=True)
753
  if row["permitted"]
754
  ]
@@ -757,6 +762,35 @@ def _portable_skill_document(session: Session, base_url: str) -> str:
757
  example = scoped[0]
758
 
759
  surface_url = f"{base_url.rstrip('/')}/api/v1/external"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
  lines = [
761
  "---",
762
  "name: loopable-external-data",
@@ -780,6 +814,7 @@ def _portable_skill_document(session: Session, base_url: str) -> str:
780
  "",
781
  f"Base URL: `{surface_url}`",
782
  "",
 
783
  "## First call: list databases",
784
  "",
785
  "Endpoint: `GET /api/v1/external/databases`",
@@ -836,6 +871,27 @@ def _portable_skill_document(session: Session, base_url: str) -> str:
836
  "answerable right now. The reason appears in the scope below."),
837
  "",
838
  ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
839
  else:
840
  lines.extend([
841
  "No schema call is available because this user's current scope has no databases.",
@@ -848,8 +904,18 @@ def _portable_skill_document(session: Session, base_url: str) -> str:
848
  "",
849
  ])
850
 
851
- lines.extend(["## This user's current read scope", ""])
852
- if not scoped:
 
 
 
 
 
 
 
 
 
 
853
  lines.extend(["No databases are currently permitted.", ""])
854
  for row in scoped:
855
  database = _markdown_inline(row["database"])
@@ -2739,4 +2805,17 @@ def oauth_resource_metadata_rfc(request: Request):
2739
  return oauth_resource_metadata(request)
2740
 
2741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2742
  router.routes.extend(_discovery_router.routes)
 
747
  return " ".join(text.replace("`", "'").split())
748
 
749
 
750
+ def _portable_skill_document(session: Session | None, base_url: str) -> str:
751
+ """The skill.md an agent reads. With a session it carries that user's own read scope; with
752
+ None it is the PUBLIC document served at `/skill.md` (owner hotfix 2026-09-23, Monid's
753
+ `set up <url>/SKILL.md`), which names no tenant, database or field and sends the agent to
754
+ discover its scope after it authenticates."""
755
+ public = session is None
756
+ scoped = [] if public else [
757
  row for row in _resolve_external_scope(session, include_schema=True)
758
  if row["permitted"]
759
  ]
 
762
  example = scoped[0]
763
 
764
  surface_url = f"{base_url.rstrip('/')}/api/v1/external"
765
+ connect = [
766
+ "## Set up",
767
+ "",
768
+ "Connect once, with the Loopable sign-in (remote MCP over OAuth) or with an API key.",
769
+ "",
770
+ f"MCP server URL: `{surface_url}/mcp`",
771
+ "",
772
+ "Claude Code:",
773
+ "",
774
+ "```sh",
775
+ f"claude mcp add --transport http loopable {surface_url}/mcp",
776
+ "```",
777
+ "",
778
+ "Then run `/mcp` in Claude Code and finish the Loopable sign-in in the browser.",
779
+ "",
780
+ "Codex:",
781
+ "",
782
+ "```sh",
783
+ f"codex mcp add loopable --url {surface_url}/mcp",
784
+ "codex mcp login loopable",
785
+ "```",
786
+ "",
787
+ ("Cursor: add `{\"mcpServers\": {\"loopable\": {\"url\": \"" + surface_url + "/mcp\"}}}` "
788
+ "to `~/.cursor/mcp.json`, keeping any existing servers, then finish the Loopable sign-in."),
789
+ "",
790
+ ("For code or an SDK, ask the user to create an API key in Loopable under AI API and to "
791
+ "store it in an environment variable. Never ask for the key in chat and never print it."),
792
+ "",
793
+ ] if public else []
794
  lines = [
795
  "---",
796
  "name: loopable-external-data",
 
814
  "",
815
  f"Base URL: `{surface_url}`",
816
  "",
817
+ *connect,
818
  "## First call: list databases",
819
  "",
820
  "Endpoint: `GET /api/v1/external/databases`",
 
871
  "answerable right now. The reason appears in the scope below."),
872
  "",
873
  ])
874
+ elif public:
875
+ lines.extend([
876
+ "```sh",
877
+ "curl --request GET \\",
878
+ " --header 'Authorization: Bearer <your Loopable credential>' \\",
879
+ f" '{surface_url}/databases/{{database}}/schema'",
880
+ "```",
881
+ "",
882
+ "## Query a database",
883
+ "",
884
+ "Endpoint: `POST /api/v1/external/databases/{database}/query`",
885
+ "",
886
+ "```sh",
887
+ "curl --request POST \\",
888
+ " --header 'Authorization: Bearer <your Loopable credential>' \\",
889
+ " --header 'Content-Type: application/json' \\",
890
+ " --data '{\"fields\":[\"<field key from the schema>\"],\"filters\":null}' \\",
891
+ f" '{surface_url}/databases/{{database}}/query'",
892
+ "```",
893
+ "",
894
+ ])
895
  else:
896
  lines.extend([
897
  "No schema call is available because this user's current scope has no databases.",
 
904
  "",
905
  ])
906
 
907
+ if public:
908
+ lines.extend([
909
+ "## Your read scope",
910
+ "",
911
+ ("Loopable answers only with what the signed-in user may already read in the app. "
912
+ "After connecting, call `GET /databases` for the databases, then "
913
+ "`GET /databases/{database}/schema` for the fields each one exposes, before any query."),
914
+ "",
915
+ ])
916
+ else:
917
+ lines.extend(["## This user's current read scope", ""])
918
+ if not scoped and not public:
919
  lines.extend(["No databases are currently permitted.", ""])
920
  for row in scoped:
921
  database = _markdown_inline(row["database"])
 
2805
  return oauth_resource_metadata(request)
2806
 
2807
 
2808
+ # The PUBLIC skill.md at the site root, like Monid's `monid.ai/SKILL.md`: an agent told
2809
+ # "set up <origin>/skill.md" reads it with no session. It is the session-free document, so it
2810
+ # carries no tenant, database or field name; `/api/v1/external/skill.md` keeps the per-user one.
2811
+ @_discovery_router.get("/skill.md")
2812
+ @_discovery_router.get("/SKILL.md")
2813
+ def public_skill(request: Request):
2814
+ return Response(
2815
+ content=_portable_skill_document(None, str(request.base_url)),
2816
+ media_type="text/markdown; charset=utf-8",
2817
+ headers={"Cache-Control": "public, max-age=300"},
2818
+ )
2819
+
2820
+
2821
  router.routes.extend(_discovery_router.routes)
api/routes_odoo_tables.py CHANGED
@@ -22,6 +22,7 @@ import base64
22
  import hashlib
23
  import hmac
24
  import json
 
25
  import time
26
  from contextlib import contextmanager
27
 
@@ -2301,6 +2302,155 @@ def _views_as_cohorts(tree, table_key, session, spec, cols, base_where, wall_par
2301
  return tree, sets
2302
 
2303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2304
  def _may_see_view(session, vid, store):
2305
  """May this caller open that saved view? The same predicate the view rail asks.
2306
 
@@ -2541,8 +2691,12 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
2541
  # the reader is held to, exactly as `viewSets` resolves inside the rows the client holds) and
2542
  # before `_leaf_cols` below, so the leaf never reaches the sentence that explains a column with
2543
  # no mirror expression. One place learns it; `/rows` and `/aggregates` share this compiler.
 
2544
  tree, cohort_sets = _views_as_cohorts(tree, table_key, session, spec, cols,
2545
  base_where, wall_params, cur, limits)
 
 
 
2546
 
2547
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
2548
  # ⛔ `_PSEUDO_COLS` is subtracted BEFORE the missing-column test. `__cohort__` and `__view__`
@@ -2667,8 +2821,12 @@ def _materialised_read(table_key, session, query, related):
2667
  "cols": bindings, "where": None}
2668
  cols = _filter_columns(spec, fields)
2669
  limits = list(payload.get("limits") or [])
 
2670
  tree, cohorts = _views_as_cohorts(query["filters"], table_key, session, spec, cols,
2671
  None, [], cur, limits)
 
 
 
2672
  missing = _leaf_cols(tree) - _PSEUDO_COLS - set(cols)
2673
  if missing:
2674
  raise err(400, "filter_unsupported", "A filter names a column unavailable to this account.")
@@ -2689,7 +2847,42 @@ def _materialised_read(table_key, session, query, related):
2689
  "frm": {"table": "pinned_rows"}, "limits": limits, "payload": payload}
2690
 
2691
 
2692
- def _materialised_window(table_key, session, offset, limit, filters, filterConj, sorts, search, related):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2693
  from harness import datastore
2694
 
2695
  query = _selection_query({"filters": _json_arg(filters, "filters"), "filterConj": filterConj,
@@ -2697,8 +2890,13 @@ def _materialised_window(table_key, session, offset, limit, filters, filterConj,
2697
  with _materialised_read(table_key, session, query, related) as read:
2698
  spec = read["spec"]
2699
  order = _fs().compile_order_by(query["sorts"], read["cols"], tiebreak_sql=spec["id"])
2700
- win = datastore.window(select=f'{spec["id"]} AS pid', where=read["where"],
2701
- params=tuple(read["params"]), order_by=order or spec["id"],
 
 
 
 
 
2702
  offset=offset, limit=limit or None, cur=read["cur"], **read["frm"])
2703
  payload = read["payload"]
2704
  by_id = {int(row["pid"]): row for row in payload["rows"]}
@@ -2721,6 +2919,8 @@ def odoo_table_rows(table_key: str,
2721
  sorts: str = Query(default=None),
2722
  search: str = Query(default=None),
2723
  related: str = Query(default=None),
 
 
2724
  session: Session = Depends(require_session)):
2725
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
2726
 
@@ -2751,7 +2951,7 @@ def odoo_table_rows(table_key: str,
2751
 
2752
  if _materialised_table(table_key):
2753
  return _materialised_window(table_key, session, offset, limit, filters, filterConj,
2754
- sorts, search, related)
2755
 
2756
  # ⛔⛔ ONE COMPILER, AND THE AGGREGATES DOOR CALLS THE SAME ONE. The permission wall, the
2757
  # hidden-field closure, the user predicate and the search all live in `_compiled_read` above,
@@ -2765,6 +2965,10 @@ def odoo_table_rows(table_key: str,
2765
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
2766
  base_where, wall_params = read["base_where"], read["wall_params"]
2767
  where, params, sort_spec = read["where"], read["params"], read["sort_spec"]
 
 
 
 
2768
 
2769
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
2770
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
 
22
  import hashlib
23
  import hmac
24
  import json
25
+ import math
26
  import time
27
  from contextlib import contextmanager
28
 
 
2302
  return tree, sets
2303
 
2304
 
2305
+ def _ranks_as_cohorts(tree, conj, spec, cols, base_where, wall_params, cur, cohort_sets,
2306
+ had_cohort, today, limits=None):
2307
+ """Resolve every ACTIVE rank leaf (Top N, quartile, above average ...) into a synthetic
2308
+ `__cohort__` leaf over the ids it selects. `(tree, cohort_sets)`.
2309
+
2310
+ A rank is a property of the SET, so `filter_sql` refuses it at row grain. The set is answered
2311
+ here the way the client answers it: the residue (every non-rank condition) under the wall is
2312
+ the domain, and `filter_eval.resolve_rank_sets` (the Python port of the client's set pass,
2313
+ ties by ascending pid) picks the members. Only the id and the ranked columns are read, uncapped.
2314
+ """
2315
+ fe = _fe()
2316
+ leaves = fe._rank_leaves(tree or [], cols)
2317
+ if not leaves:
2318
+ return tree, cohort_sets
2319
+ if had_cohort:
2320
+ raise err(400, "filter_unsupported",
2321
+ "a condition on cohort membership cannot be evaluated on this database's live "
2322
+ "connection, because a cohort is resolved from this tenant's own records rather "
2323
+ "than from the connection. Filter on a saved view instead, or open this "
2324
+ "database's stored copy")
2325
+ residue = fe._strip_rank_leaves(tree)
2326
+ try:
2327
+ pred = _fs().compile_filter_tree(residue, conj=conj, columns=cols, id_sql=spec["id"],
2328
+ today=today, cohort_sets=cohort_sets)
2329
+ except ValueError as exc:
2330
+ raise err(400, "filter_unsupported", str(exc))
2331
+ if pred is not None and pred.uses_aggregate:
2332
+ raise err(400, "filter_unsupported",
2333
+ "This condition cannot be evaluated for individual rows.")
2334
+ where = base_where
2335
+ params = list(wall_params)
2336
+ if pred is not None:
2337
+ where = f"({where}) AND {pred.sql}" if where else pred.sql
2338
+ params.extend(pred.params)
2339
+ frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
2340
+ answers = {}
2341
+ python_leaves = []
2342
+ for n in leaves:
2343
+ got = _rank_ids_sql(n, cols, spec["id"], frm_body, where, params, cur)
2344
+ if got is None:
2345
+ python_leaves.append(n)
2346
+ else:
2347
+ answers[id(n)] = got
2348
+ if python_leaves:
2349
+ # A GROUP-scoped rank (rare on this door) keeps the reference resolver: read the id and
2350
+ # the ranked columns once, uncapped, and let `resolve_rank_sets` answer it.
2351
+ ranked = sorted({str(n.get("colId")) for n in python_leaves if n.get("colId") in cols})
2352
+ select = ", ".join([spec["id"]] + [cols[c]["sql"] for c in ranked])
2353
+ sql = f"SELECT {select} FROM {frm_body}" + (f" WHERE {where}" if where else "")
2354
+ rows = []
2355
+ for r in cur.execute(sql, params).fetchall():
2356
+ if not r or r[0] is None:
2357
+ continue
2358
+ row = {"pid": int(r[0])}
2359
+ for i, c in enumerate(ranked, start=1):
2360
+ row[c] = r[i]
2361
+ rows.append(row)
2362
+ resolved = fe.resolve_rank_sets({"nodes": python_leaves, "conj": "and"}, rows, cols)
2363
+ for n in python_leaves:
2364
+ answers[id(n)] = sorted(resolved.sets.get(fe._rank_key(n)) or ())
2365
+ sets = dict(cohort_sets or {})
2366
+ counter = [0]
2367
+ wanted = {id(n) for n in leaves}
2368
+
2369
+ def rewrite(nodes):
2370
+ out = []
2371
+ for n in (nodes or []):
2372
+ if isinstance(n, dict) and isinstance(n.get("children"), list):
2373
+ out.append(dict(n, children=rewrite(n["children"])))
2374
+ elif isinstance(n, dict) and id(n) in wanted:
2375
+ counter[0] += 1
2376
+ key = "__rank_%d__" % counter[0]
2377
+ got = answers.get(id(n))
2378
+ sets[key] = got if got is not None else []
2379
+ if (limits is not None and isinstance(got, list)
2380
+ and len(got) >= _PIN_REPORT_AT):
2381
+ limits.append({
2382
+ "subject": str(n.get("colId") or ""), "effect": "slow",
2383
+ "cause": f"this ranking condition selects {len(got):,} rows, and "
2384
+ f"each page of this database names every one of them in the "
2385
+ f"query that narrows it",
2386
+ "recommendation": "rank a smaller slice (a lower Top N or percentage), "
2387
+ "or add a condition beside it"})
2388
+ out.append({"colId": "__cohort__", "op": "anyOf", "value": key})
2389
+ else:
2390
+ out.append(n)
2391
+ return out
2392
+
2393
+ return rewrite(tree), sets
2394
+
2395
+
2396
+ def _rank_ids_sql(leaf, cols, id_sql, frm_body, where, params, cur):
2397
+ """One GLOBAL rank leaf as SQL: a `SqlMembership` selecting its ids, or None for the resolver.
2398
+
2399
+ Measured 2026-09-23: `resolve_rank_sets` over 256,542 order lines took 3.6 s in Python, and a
2400
+ paged grid pays it on every page; as a SQL window the same answer is tens of milliseconds,
2401
+ and as a subquery it never becomes a six-figure IN list. Semantics are the resolver's, line
2402
+ for line (parity-tested over all eight ops with ties and blanks): blank or non-finite values
2403
+ are ABSENT, ties break by ascending id in both directions, a bound outside the builder's
2404
+ whole-number range is unanswerable (empty), and a quartile or decile of fewer rows than
2405
+ buckets is empty. The domain's count and mean are read once here and inlined as literals.
2406
+ """
2407
+ fe = _fe()
2408
+ Sql = _fs().SqlMembership
2409
+ empty = Sql("SELECT NULL WHERE FALSE", [])
2410
+ scope, _field = fe._rank_scope(leaf, None)
2411
+ if scope != "global":
2412
+ return None
2413
+ col = cols.get(leaf.get("colId")) or {}
2414
+ if col.get("type") not in fe.NUMERIC_TYPES:
2415
+ return empty
2416
+ v = f"TRY_CAST({col['sql']} AS DOUBLE)"
2417
+ dom = (f"SELECT {id_sql} AS pid, {v} AS v FROM {frm_body} WHERE "
2418
+ + (f"({where}) AND " if where else "") + f"{v} IS NOT NULL AND isfinite({v})")
2419
+ params = list(params)
2420
+ op = leaf.get("op")
2421
+ if op in ("topN", "bottomN"):
2422
+ bound = fe._rank_bound(leaf.get("value"), 1, 10000)
2423
+ if bound is None:
2424
+ return empty
2425
+ direction = "DESC" if op == "topN" else "ASC"
2426
+ return Sql(f"SELECT pid FROM ({dom}) d ORDER BY v {direction}, pid ASC LIMIT {bound}",
2427
+ params)
2428
+ count, total = cur.execute(f"SELECT count(*), sum(v) FROM ({dom}) d", params).fetchone()
2429
+ count = int(count or 0)
2430
+ if not count:
2431
+ return empty
2432
+ if op in ("inTopPct", "inBottomPct"):
2433
+ pct = fe._rank_bound(leaf.get("value"), 1, 100)
2434
+ if pct is None:
2435
+ return empty
2436
+ take = min(count, max(1, math.ceil(count * pct / 100)))
2437
+ direction = "DESC" if op == "inTopPct" else "ASC"
2438
+ return Sql(f"SELECT pid FROM ({dom}) d ORDER BY v {direction}, pid ASC LIMIT {take}",
2439
+ params)
2440
+ if op in ("aboveAvg", "belowAvg"):
2441
+ mean = float(total) / count
2442
+ cmp = ">" if op == "aboveAvg" else "<"
2443
+ return Sql(f"SELECT pid FROM ({dom}) d WHERE v {cmp} {mean!r}", params)
2444
+ if op in ("inQuartile", "inDecile"):
2445
+ buckets = 4 if op == "inQuartile" else 10
2446
+ wanted = fe._rank_bound(leaf.get("value"), 1, buckets)
2447
+ if wanted is None or count < buckets:
2448
+ return empty
2449
+ return Sql(f"SELECT pid FROM (SELECT pid, row_number() OVER (ORDER BY v ASC, pid ASC) - 1"
2450
+ f" AS idx FROM ({dom}) d) r WHERE least({buckets}, (idx * {buckets}) // {count}"
2451
+ f" + 1) = {int(wanted)}", params)
2452
+ return None
2453
+
2454
  def _may_see_view(session, vid, store):
2455
  """May this caller open that saved view? The same predicate the view rail asks.
2456
 
 
2691
  # the reader is held to, exactly as `viewSets` resolves inside the rows the client holds) and
2692
  # before `_leaf_cols` below, so the leaf never reaches the sentence that explains a column with
2693
  # no mirror expression. One place learns it; `/rows` and `/aggregates` share this compiler.
2694
+ _had_cohort = bool(_active_cohort_leaves(tree))
2695
  tree, cohort_sets = _views_as_cohorts(tree, table_key, session, spec, cols,
2696
  base_where, wall_params, cur, limits)
2697
+ tree, cohort_sets = _ranks_as_cohorts(
2698
+ tree, (filterConj if filterConj in ("and", "or") else "and"), spec, cols, base_where,
2699
+ wall_params, cur, cohort_sets, _had_cohort, _today(), limits)
2700
 
2701
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
2702
  # ⛔ `_PSEUDO_COLS` is subtracted BEFORE the missing-column test. `__cohort__` and `__view__`
 
2821
  "cols": bindings, "where": None}
2822
  cols = _filter_columns(spec, fields)
2823
  limits = list(payload.get("limits") or [])
2824
+ _had_cohort = bool(_active_cohort_leaves(query["filters"]))
2825
  tree, cohorts = _views_as_cohorts(query["filters"], table_key, session, spec, cols,
2826
  None, [], cur, limits)
2827
+ tree, cohorts = _ranks_as_cohorts(tree, query["filterConj"], spec, cols, None, [], cur,
2828
+ cohorts, _had_cohort,
2829
+ payload.get("today") or _today(), limits)
2830
  missing = _leaf_cols(tree) - _PSEUDO_COLS - set(cols)
2831
  if missing:
2832
  raise err(400, "filter_unsupported", "A filter names a column unavailable to this account.")
 
2847
  "frm": {"table": "pinned_rows"}, "limits": limits, "payload": payload}
2848
 
2849
 
2850
+ def _group_pin(cols, group_by, group_key):
2851
+ """`(sql, params)` narrowing a window to ONE group of `/aggregates`' grouping, or `(None, [])`.
2852
+
2853
+ HOTFIX 2026-09-23 (owner: "whatever is GROUPED we can add pagination per group"). A group's
2854
+ records page through this door, so the narrowing is the SAME expression `_aggregate_over`
2855
+ groups by (`filter_sql.group_sql`), never a client-built `eq` leaf: `_value_sql` lowercases
2856
+ text and rounds numbers, which would make a group's pages disagree with its count.
2857
+ `group_key` is the JSON of the key `/aggregates` put on the wire (`null` = the blank bucket).
2858
+ """
2859
+ # A plain-Python caller that omits the argument hands us FastAPI's `Query` sentinel, not
2860
+ # None (the `related` scar in `routes_connected_tables`), so anything but a string is "none".
2861
+ gcol = group_by.strip() if isinstance(group_by, str) else ""
2862
+ if not gcol:
2863
+ return None, []
2864
+ group_key = group_key if isinstance(group_key, str) else None
2865
+ gspec = cols.get(gcol)
2866
+ if gspec is None:
2867
+ raise err(400, "bad_group", "this column cannot be grouped on this database's live "
2868
+ "connection, or it is not visible to your account")
2869
+ try:
2870
+ key = json.loads(group_key) if group_key not in (None, "") else None
2871
+ except ValueError:
2872
+ raise err(400, "bad_group", "groupKey must be the JSON of a group key")
2873
+ gexpr = _fs().group_sql(gspec)
2874
+ if key is None:
2875
+ return f"({gexpr}) IS NULL", []
2876
+ if gspec["type"] in _fs().NUMERIC_TYPES:
2877
+ try:
2878
+ return f"({gexpr}) = ?", [float(key)]
2879
+ except (TypeError, ValueError):
2880
+ raise err(400, "bad_group", "groupKey must be a number for a number column")
2881
+ return f"({gexpr}) = ?", [str(key)]
2882
+
2883
+
2884
+ def _materialised_window(table_key, session, offset, limit, filters, filterConj, sorts, search, related,
2885
+ groupBy=None, groupKey=None):
2886
  from harness import datastore
2887
 
2888
  query = _selection_query({"filters": _json_arg(filters, "filters"), "filterConj": filterConj,
 
2890
  with _materialised_read(table_key, session, query, related) as read:
2891
  spec = read["spec"]
2892
  order = _fs().compile_order_by(query["sorts"], read["cols"], tiebreak_sql=spec["id"])
2893
+ where, params = read["where"], list(read["params"])
2894
+ gsql, gparams = _group_pin(read["cols"], groupBy, groupKey)
2895
+ if gsql:
2896
+ where = f"({where}) AND {gsql}" if where else gsql
2897
+ params.extend(gparams)
2898
+ win = datastore.window(select=f'{spec["id"]} AS pid', where=where,
2899
+ params=tuple(params), order_by=order or spec["id"],
2900
  offset=offset, limit=limit or None, cur=read["cur"], **read["frm"])
2901
  payload = read["payload"]
2902
  by_id = {int(row["pid"]): row for row in payload["rows"]}
 
2919
  sorts: str = Query(default=None),
2920
  search: str = Query(default=None),
2921
  related: str = Query(default=None),
2922
+ groupBy: str = Query(default=None),
2923
+ groupKey: str = Query(default=None),
2924
  session: Session = Depends(require_session)):
2925
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
2926
 
 
2951
 
2952
  if _materialised_table(table_key):
2953
  return _materialised_window(table_key, session, offset, limit, filters, filterConj,
2954
+ sorts, search, related, groupBy, groupKey)
2955
 
2956
  # ⛔⛔ ONE COMPILER, AND THE AGGREGATES DOOR CALLS THE SAME ONE. The permission wall, the
2957
  # hidden-field closure, the user predicate and the search all live in `_compiled_read` above,
 
2965
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
2966
  base_where, wall_params = read["base_where"], read["wall_params"]
2967
  where, params, sort_spec = read["where"], read["params"], read["sort_spec"]
2968
+ _gsql, _gparams = _group_pin(cols, groupBy, groupKey)
2969
+ if _gsql:
2970
+ where = f"({where}) AND {_gsql}" if where else _gsql
2971
+ params = list(params) + list(_gparams)
2972
 
2973
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
2974
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
platform/harness/filter_sql.py CHANGED
@@ -157,6 +157,9 @@ _DATE_CMP = dict(_NUM_CMP)
157
  #: rather than WHERE; columns_used = colIds actually referenced in the emitted SQL (an
158
  #: always-true `1=1` branch references nothing, and must not force HAVING routing).
159
  Compiled = namedtuple('Compiled', 'sql params uses_aggregate columns_used')
 
 
 
160
 
161
 
162
  # --------------------------------------------------------------------------- value coercion
@@ -612,6 +615,10 @@ def _compile_cohort(rule, state):
612
 
613
  parts, params = [], []
614
  for ids in members:
 
 
 
 
615
  ids = [int(x) for x in ids]
616
  if not ids:
617
  parts.append('1=0')
 
157
  #: rather than WHERE; columns_used = colIds actually referenced in the emitted SQL (an
158
  #: always-true `1=1` branch references nothing, and must not force HAVING routing).
159
  Compiled = namedtuple('Compiled', 'sql params uses_aggregate columns_used')
160
+ #: HOTFIX 2026-09-23: a cohort set given as a SELECT of ids rather than a list. A server-side
161
+ #: rank answer (Top N, above average ...) over 256k rows is a subquery, never a 128k-id IN list.
162
+ SqlMembership = namedtuple('SqlMembership', 'sql params')
163
 
164
 
165
  # --------------------------------------------------------------------------- value coercion
 
615
 
616
  parts, params = [], []
617
  for ids in members:
618
+ if isinstance(ids, SqlMembership):
619
+ parts.append(f"COALESCE({id_sql} IN ({ids.sql}), FALSE)")
620
+ params.extend(ids.params)
621
+ continue
622
  ids = [int(x) for x in ids]
623
  if not ids:
624
  parts.append('1=0')
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- a20f6498ebd3bc79f3dc2734694ef244248f1110b97812632115c78506702a5a
 
1
+ d5353b4213c73bb8c44701a60613e479f7ab9426db03e6ae55b281a15557b25b
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -34,13 +34,14 @@ import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview";
34
  // ⭐ WAVE 30 · W30-T42 (contract C2) — the WINDOWED grid's arithmetic, pure and node-run in
35
  // `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where
36
  // only its own source text could otherwise be checked.
37
- import { WINDOW_ROWS, fetchAggregates, personalGridLayout } from "./apiBridge";
 
38
  // ⭐⭐ W50-T03 / CONTRACT C1 — the windowed aggregate's envelope. Lane F serves the route
39
  // (W50-T31); this side is written to C1's shape and degrades to the loaded window until it
40
  // lands, which is the done-when's own observable rather than a workaround.
41
  import type { AggregateResult } from "./apiBridge";
42
  import {
43
- EMPTY_WINDOW_PREDICATE, limitSummary, lockedRecordsNote, nextWindowOffset,
44
  windowedCapabilityNote, windowedFoldNote, windowPredicateKey,
45
  } from "./counts";
46
  // ⭐ W35-T29/T30 (C5) — the record star's client, and its own stylesheet imported HERE, by the
@@ -3631,6 +3632,18 @@ function CustomerGridSurface({
3631
  }),
3632
  [config.filters, config.filterConj, config.sorts, search]
3633
  );
 
 
 
 
 
 
 
 
 
 
 
 
3634
  const sentPredicate = useRef<string | null>(null);
3635
  useEffect(() => {
3636
  if (!serverWindowed) {
@@ -3649,6 +3662,7 @@ function CustomerGridSurface({
3649
  return;
3650
  }
3651
  sentPredicate.current = windowPredicate;
 
3652
  requestWindow(windowRequest(0));
3653
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
3654
 
@@ -3673,18 +3687,12 @@ function CustomerGridSurface({
3673
  const [canvasX, setCanvasX] = useState(0);
3674
  const onVisibleRegionChanged = useCallback(
3675
  (range: Rectangle, tx: number) => {
 
 
 
3676
  setCanvasX(Number.isFinite(tx) ? tx : 0);
3677
- if (!serverWindowed) return;
3678
- const offset = nextWindowOffset({
3679
- lastVisibleRow: range.y + range.height,
3680
- loaded: payload?.counts?.shown ?? 0,
3681
- matched: payload?.counts?.matched ?? 0,
3682
- limit: WINDOW_ROWS,
3683
- });
3684
- if (offset !== null) requestWindow(windowRequest(offset));
3685
  },
3686
- [serverWindowed, payload?.counts?.shown, payload?.counts?.matched, requestWindow,
3687
- windowRequest]
3688
  );
3689
 
3690
  // CG-8 — measure conditions, answered by the host as `{ruleId: pid[]}`. Converted to Sets
@@ -4077,7 +4085,9 @@ function CustomerGridSurface({
4077
  );
4078
  const summaryRequestKey = JSON.stringify(summaryRequest);
4079
  useEffect(() => {
4080
- if (!serverWindowed || !summaryRequestKey || summaryRequestKey === "[]") {
 
 
4081
  setServerAggs(null);
4082
  return;
4083
  }
@@ -4098,7 +4108,7 @@ function CustomerGridSurface({
4098
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
4099
  answer W50-T03 already asks for, byte for byte. */
4100
  ...(config.groupBy ? { groupBy: config.groupBy } : {}),
4101
- aggs: JSON.parse(summaryRequestKey) as { colId: string; agg: string; p?: number }[],
4102
  }).then((result) => {
4103
  if (live) setServerAggs(result);
4104
  });
@@ -4223,14 +4233,89 @@ function CustomerGridSurface({
4223
  * is not available on this table. Summary mode is the ONE state whose intended shape is
4224
  * header-only, so it is the one state that may take this source.
4225
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4226
  const serverGroupRows = useMemo(() => {
4227
- if (!serverWindowed || !config.groupBy || !groupSummaryOn) return null;
4228
  const groups = serverAggs?.groups;
4229
  if (!groups || !groups.length) return null;
4230
- return serverGroupHeaders(
4231
  groups, fields, summaryMap, serverAggs.aggregates, serverAggs.totalRows
4232
  );
4233
- }, [serverWindowed, config.groupBy, serverAggs, fields, summaryMap]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4234
  /** R6's SECOND SENTENCE, on the client side of the wire: the limits D's route DECLARED on this
4235
  * response. Received and painted nothing = the limit is silent again, one layer further out. */
4236
  // ⭐ W32-T03: `counts` rides along so the clamped-window clause can say "Showing 5,000 of
@@ -5177,7 +5262,7 @@ function CustomerGridSurface({
5177
  // Do not paint loaded rows as though they were the whole update. Invalidate every cached
5178
  // window and request a fresh one, then state exactly what the server says it wrote.
5179
  dropTableRowsCache(scope);
5180
- requestWindow(windowRequest(0));
5181
  signal(ROWS_STALE_EVENT);
5182
  setServerFilteredSelection(null);
5183
  clearSelection();
@@ -6117,6 +6202,17 @@ function CustomerGridSurface({
6117
  toggleFold(row.groupKey);
6118
  return;
6119
  }
 
 
 
 
 
 
 
 
 
 
 
6120
  // W40-T30 — the virtual "Go" cell's tap door stood here, matched by POSITION on the index
6121
  // one past the persisted columns. Owner instruction 27 removed it; the transit link is a
6122
  // pre-set URL field now, so it opens through the ordinary url-cell branch below, which is
@@ -9420,8 +9516,10 @@ function CustomerGridSurface({
9420
  const onExpandAllGroups = useCallback(() => {
9421
  const keys = new Set<string>();
9422
  for (const vr of visibleRows) if (vr.kind === "group-header") keys.add(vr.groupKey);
 
 
9423
  setFold(keys);
9424
- }, [visibleRows, setFold]);
9425
  /**
9426
  * Item 7 (C-TS) — the pid set the time series asks about: exactly the rows the current
9427
  * filter kept, so the panel and the toolbar count can never disagree about "who".
@@ -10554,7 +10652,7 @@ function CustomerGridSurface({
10554
  sortsLocked={activeSortsLocked}
10555
  onCopyToChange={() => duplicateView(activeViewId)}
10556
  // the toolbar must not advertise a grouping the pipeline is not applying
10557
- groupBy={serverWindowed ? null : config.groupBy}
10558
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
10559
  onCollapseAllGroups={onCollapseAllGroups}
10560
  onExpandAllGroups={onExpandAllGroups}
@@ -10854,15 +10952,14 @@ function CustomerGridSurface({
10854
  `cg-app-launch-state`: route-app.css:28-31 hides the Data toolbar's controls on
10855
  `.cg-main:has(.cg-app-launch-state)`, so borrowing that class would flash the whole toolbar
10856
  away on every rail click. Only the bar classes are reused; they carry size and the pulse. */}
 
 
 
 
10857
  {!applicationLaunching && viewSwitchPending && (
10858
- <div className="cg-view-pending" role="status" aria-label="Loading view"
10859
- style={{ display: "grid", alignContent: "start", gap: 12, padding: 24 }}>
10860
- <span className="cg-app-launch-line is-wide" />
10861
- <span className="cg-app-launch-line" />
10862
- <span className="cg-app-launch-grid" />
10863
- </div>
10864
  )}
10865
- {displayMode === "grid" && !applicationLaunching && !viewSwitchPending && (
10866
  <>
10867
  <DataEditor
10868
  ref={gridRef}
@@ -11671,6 +11768,19 @@ function CustomerGridSurface({
11671
  />
11672
  )}
11673
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
11674
  {/* ⭐ W30-T42 — the WINDOWED grid's honest footnotes, in the strip that already exists
11675
  for exactly this job. Reuses `.cg-more` / `.cg-more-note` rather than adding a
11676
  class: `index.css` is another lane's fence this wave, and this needs no new pixel.
 
34
  // ⭐ WAVE 30 · W30-T42 (contract C2) — the WINDOWED grid's arithmetic, pure and node-run in
35
  // `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where
36
  // only its own source text could otherwise be checked.
37
+ import { WINDOW_ROWS, fetchAggregates, fetchTableWindow, personalGridLayout } from "./apiBridge";
38
+ import { GridPager } from "./GridPager";
39
  // ⭐⭐ W50-T03 / CONTRACT C1 — the windowed aggregate's envelope. Lane F serves the route
40
  // (W50-T31); this side is written to C1's shape and degrades to the loaded window until it
41
  // lands, which is the done-when's own observable rather than a workaround.
42
  import type { AggregateResult } from "./apiBridge";
43
  import {
44
+ EMPTY_WINDOW_PREDICATE, limitSummary, lockedRecordsNote,
45
  windowedCapabilityNote, windowedFoldNote, windowPredicateKey,
46
  } from "./counts";
47
  // ⭐ W35-T29/T30 (C5) — the record star's client, and its own stylesheet imported HERE, by the
 
3632
  }),
3633
  [config.filters, config.filterConj, config.sorts, search]
3634
  );
3635
+ /* ⭐⭐ HOTFIX 2026-09-23 — THE PAGE. The owner revoked the virtualise-only ruling: *"I want
3636
+ fucking either pagination or next page and only load 50 at a time"*. A read-through grid now
3637
+ holds ONE page of `WINDOW_ROWS` rows at `pageOffset`, moved by the pager under the canvas.
3638
+ A predicate change returns to the first page. */
3639
+ const [pageOffset, setPageOffset] = useState(0);
3640
+ const pageOffsetRef = useRef(0);
3641
+ pageOffsetRef.current = pageOffset;
3642
+ const goToPage = useCallback((offset: number) => {
3643
+ const next = Math.max(0, Math.floor(offset));
3644
+ setPageOffset(next);
3645
+ requestWindow(windowRequest(next));
3646
+ }, [requestWindow, windowRequest]);
3647
  const sentPredicate = useRef<string | null>(null);
3648
  useEffect(() => {
3649
  if (!serverWindowed) {
 
3662
  return;
3663
  }
3664
  sentPredicate.current = windowPredicate;
3665
+ setPageOffset(0);
3666
  requestWindow(windowRequest(0));
3667
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
3668
 
 
3687
  const [canvasX, setCanvasX] = useState(0);
3688
  const onVisibleRegionChanged = useCallback(
3689
  (range: Rectangle, tx: number) => {
3690
+ // HOTFIX 2026-09-23: a read-through grid PAGES (the pager under the canvas) instead of
3691
+ // appending on scroll, so the visible region only drives the summary bar's track now.
3692
+ void range;
3693
  setCanvasX(Number.isFinite(tx) ? tx : 0);
 
 
 
 
 
 
 
 
3694
  },
3695
+ []
 
3696
  );
3697
 
3698
  // CG-8 — measure conditions, answered by the host as `{ruleId: pid[]}`. Converted to Sets
 
4085
  );
4086
  const summaryRequestKey = JSON.stringify(summaryRequest);
4087
  useEffect(() => {
4088
+ // HOTFIX 2026-09-23: a grouped windowed table needs its groups even when no column carries
4089
+ // a summary, because the groups ARE the canvas now (per-group paging).
4090
+ if (!serverWindowed || ((!summaryRequestKey || summaryRequestKey === "[]") && !config.groupBy)) {
4091
  setServerAggs(null);
4092
  return;
4093
  }
 
4108
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
4109
  answer W50-T03 already asks for, byte for byte. */
4110
  ...(config.groupBy ? { groupBy: config.groupBy } : {}),
4111
+ aggs: JSON.parse(summaryRequestKey || "[]") as { colId: string; agg: string; p?: number }[],
4112
  }).then((result) => {
4113
  if (live) setServerAggs(result);
4114
  });
 
4233
  * is not available on this table. Summary mode is the ONE state whose intended shape is
4234
  * header-only, so it is the one state that may take this source.
4235
  */
4236
+ /* ⭐⭐ HOTFIX 2026-09-23: GROUPED PAGING ON A READ-THROUGH TABLE. Owner: *"whatever is GROUPED
4237
+ we can add pagination per group as well. So we only show the total for each group when its
4238
+ metric or formula or numeric but to show the record we need to add pagination."* The groups,
4239
+ their counts and their totals come from `/aggregates` over the WHOLE predicate; an OPEN group
4240
+ pages its own records 50 at a time through `/rows?groupBy&groupKey`, whose narrowing is the
4241
+ server's grouping expression, so a group's pages always add up to its count. */
4242
+ const groupKeyRaw = useMemo(() => {
4243
+ const m = new Map<string, string | number | null>();
4244
+ for (const g of serverAggs?.groups ?? []) {
4245
+ const raw = g.key as unknown as string | number | null;
4246
+ m.set(raw == null ? "" : String(raw), raw);
4247
+ }
4248
+ return m;
4249
+ }, [serverAggs]);
4250
+ const [groupPages, setGroupPages] = useState<
4251
+ ReadonlyMap<string, { offset: number; rows: Row[]; pending: boolean }>
4252
+ >(() => new Map());
4253
+ const groupPageSeq = useRef(0);
4254
+ useEffect(() => {
4255
+ groupPageSeq.current += 1;
4256
+ setGroupPages(new Map());
4257
+ }, [serverWindowed, windowPredicate, config.groupBy, relatedPin]);
4258
+ const loadGroupPage = useCallback((key: string, offset: number) => {
4259
+ const by = config.groupBy;
4260
+ if (!by || !groupKeyRaw.has(key)) return;
4261
+ const seq = groupPageSeq.current;
4262
+ setGroupPages((prev) => {
4263
+ const next = new Map(prev);
4264
+ next.set(key, { offset, rows: prev.get(key)?.rows ?? [], pending: true });
4265
+ return next;
4266
+ });
4267
+ void fetchTableWindow(scope, {
4268
+ ...windowRequest(offset),
4269
+ related: relatedPin,
4270
+ group: { by, key: groupKeyRaw.get(key) ?? null },
4271
+ }).then((page) => {
4272
+ if (seq !== groupPageSeq.current) return;
4273
+ setGroupPages((prev) => {
4274
+ const cur = prev.get(key);
4275
+ if (cur && cur.offset !== offset) return prev;
4276
+ const next = new Map(prev);
4277
+ next.set(key, { offset, rows: page?.rows ?? cur?.rows ?? [], pending: false });
4278
+ return next;
4279
+ });
4280
+ });
4281
+ }, [config.groupBy, groupKeyRaw, scope, windowRequest, relatedPin]);
4282
+ useEffect(() => {
4283
+ if (!serverWindowed || !config.groupBy || groupSummaryOn) return;
4284
+ for (const key of expanded) {
4285
+ if (groupKeyRaw.has(key) && !groupPages.has(key)) loadGroupPage(key, 0);
4286
+ }
4287
+ }, [serverWindowed, config.groupBy, groupSummaryOn, expanded, groupKeyRaw, groupPages,
4288
+ loadGroupPage]);
4289
  const serverGroupRows = useMemo(() => {
4290
+ if (!serverWindowed || !config.groupBy) return null;
4291
  const groups = serverAggs?.groups;
4292
  if (!groups || !groups.length) return null;
4293
+ const heads = serverGroupHeaders(
4294
  groups, fields, summaryMap, serverAggs.aggregates, serverAggs.totalRows
4295
  );
4296
+ if (groupSummaryOn) return heads;
4297
+ const out: VisibleRow[] = [];
4298
+ for (const h of heads) {
4299
+ if (h.kind !== "group-header") continue;
4300
+ const raw = h.groupKey as unknown as string | number | null;
4301
+ const key = raw == null ? "" : String(raw);
4302
+ const open = expanded.has(key);
4303
+ out.push({ ...h, groupKey: key, collapsed: !open });
4304
+ if (!open) continue;
4305
+ const page = groupPages.get(key);
4306
+ for (const record of page?.rows ?? []) out.push({ kind: "data", record });
4307
+ out.push({
4308
+ kind: "group-footer",
4309
+ groupKey: key,
4310
+ aggs: h.aggs,
4311
+ ...(h.count > WINDOW_ROWS
4312
+ ? { page: { offset: page?.offset ?? 0, total: h.count, size: WINDOW_ROWS } }
4313
+ : {}),
4314
+ });
4315
+ }
4316
+ return out;
4317
+ }, [serverWindowed, config.groupBy, serverAggs, fields, summaryMap, groupSummaryOn, expanded,
4318
+ groupPages]);
4319
  /** R6's SECOND SENTENCE, on the client side of the wire: the limits D's route DECLARED on this
4320
  * response. Received and painted nothing = the limit is silent again, one layer further out. */
4321
  // ⭐ W32-T03: `counts` rides along so the clamped-window clause can say "Showing 5,000 of
 
5262
  // Do not paint loaded rows as though they were the whole update. Invalidate every cached
5263
  // window and request a fresh one, then state exactly what the server says it wrote.
5264
  dropTableRowsCache(scope);
5265
+ requestWindow(windowRequest(pageOffsetRef.current));
5266
  signal(ROWS_STALE_EVENT);
5267
  setServerFilteredSelection(null);
5268
  clearSelection();
 
6202
  toggleFold(row.groupKey);
6203
  return;
6204
  }
6205
+ // HOTFIX 2026-09-23: a paged group's footer. The left half of its first cell is
6206
+ // Previous, the right half Next (`groupFooterCell` paints both marks there).
6207
+ if (row.kind === "group-footer" && row.page) {
6208
+ event.preventDefault();
6209
+ if (cell[0] !== 0) return;
6210
+ const { offset, total, size } = row.page;
6211
+ const back = event.localEventX < event.bounds.width / 2;
6212
+ const next = back ? offset - size : offset + size;
6213
+ if (next >= 0 && next < total) loadGroupPage(row.groupKey, next);
6214
+ return;
6215
+ }
6216
  // W40-T30 — the virtual "Go" cell's tap door stood here, matched by POSITION on the index
6217
  // one past the persisted columns. Owner instruction 27 removed it; the transit link is a
6218
  // pre-set URL field now, so it opens through the ordinary url-cell branch below, which is
 
9516
  const onExpandAllGroups = useCallback(() => {
9517
  const keys = new Set<string>();
9518
  for (const vr of visibleRows) if (vr.kind === "group-header") keys.add(vr.groupKey);
9519
+ // HOTFIX 2026-09-23: a read-through table's groups come from the server, not the page.
9520
+ if (serverWindowed) for (const k of groupKeyRaw.keys()) keys.add(k);
9521
  setFold(keys);
9522
+ }, [visibleRows, setFold, serverWindowed, groupKeyRaw]);
9523
  /**
9524
  * Item 7 (C-TS) — the pid set the time series asks about: exactly the rows the current
9525
  * filter kept, so the panel and the toolbar count can never disagree about "who".
 
10652
  sortsLocked={activeSortsLocked}
10653
  onCopyToChange={() => duplicateView(activeViewId)}
10654
  // the toolbar must not advertise a grouping the pipeline is not applying
10655
+ groupBy={config.groupBy}
10656
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
10657
  onCollapseAllGroups={onCollapseAllGroups}
10658
  onExpandAllGroups={onExpandAllGroups}
 
10952
  `cg-app-launch-state`: route-app.css:28-31 hides the Data toolbar's controls on
10953
  `.cg-main:has(.cg-app-launch-state)`, so borrowing that class would flash the whole toolbar
10954
  away on every rail click. Only the bar classes are reused; they carry size and the pulse. */}
10955
+ {/* ⭐⭐ HOTFIX 2026-09-23 — PENDING NO LONGER UNMOUNTS THE GRID. S64-T01 swapped the canvas
10956
+ for a skeleton on every view switch, even when the page came back from cache, and
10957
+ the owner felt that as "we used to click from one view to another without ANY load".
10958
+ The rows in hand stay painted; a thin bar says a newer page is on its way. */}
10959
  {!applicationLaunching && viewSwitchPending && (
10960
+ <div className="cg-view-pending" role="status" aria-label="Loading view" />
 
 
 
 
 
10961
  )}
10962
+ {displayMode === "grid" && !applicationLaunching && (
10963
  <>
10964
  <DataEditor
10965
  ref={gridRef}
 
11768
  />
11769
  )}
11770
  </div>
11771
+ {/* ⭐⭐ HOTFIX 2026-09-23 — THE PAGER. One page of a read-through table at a time, and
11772
+ every page reachable: `matched` is the server's own count, so this is a view onto the
11773
+ whole population rather than a cap on it (standing rule 1). Grouped, each open group
11774
+ pages on its own footer instead. */}
11775
+ {serverWindowed && !config.groupBy && displayMode === "grid" && (
11776
+ <GridPager
11777
+ offset={pageOffset}
11778
+ size={WINDOW_ROWS}
11779
+ total={payload?.counts?.matched ?? 0}
11780
+ pending={windowPending}
11781
+ onPage={goToPage}
11782
+ />
11783
+ )}
11784
  {/* ⭐ W30-T42 — the WINDOWED grid's honest footnotes, in the strip that already exists
11785
  for exactly this job. Reuses `.cg-more` / `.cg-more-note` rather than adding a
11786
  class: `index.css` is another lane's fence this wave, and this needs no new pixel.
web/src/customer-grid/GridPager.tsx ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ⭐⭐ HOTFIX 2026-09-23 — the read-through grid's pager.
3
+ *
4
+ * Owner, verbatim: *"I want fucking either pagination or next page and only load 50 at a time to
5
+ * be fucking back."* This revokes SDLC 62 R3 (virtualise only). A read-through table holds ONE
6
+ * page of `size` rows; Previous and Next move it. `total` is the server's count of everything the
7
+ * predicate matches, so every row stays reachable and the count is never `rows.length`.
8
+ */
9
+ export function pageLabel(offset: number, size: number, total: number): string {
10
+ if (total <= 0) return "No records";
11
+ const from = Math.min(total, offset + 1);
12
+ const to = Math.min(total, offset + size);
13
+ return `${from.toLocaleString()} to ${to.toLocaleString()} of ${total.toLocaleString()}`;
14
+ }
15
+
16
+ export function GridPager({
17
+ offset,
18
+ size,
19
+ total,
20
+ pending,
21
+ onPage,
22
+ }: {
23
+ offset: number;
24
+ size: number;
25
+ total: number;
26
+ pending: boolean;
27
+ onPage: (offset: number) => void;
28
+ }) {
29
+ const pages = Math.max(1, Math.ceil(total / size));
30
+ const page = Math.min(pages, Math.floor(offset / size) + 1);
31
+ const hasPrev = offset > 0;
32
+ const hasNext = offset + size < total;
33
+ return (
34
+ <nav className="cg-pager" aria-label="Pages" aria-busy={pending || undefined}>
35
+ <button
36
+ type="button"
37
+ className="cg-btn"
38
+ disabled={!hasPrev}
39
+ onClick={() => onPage(Math.max(0, offset - size))}
40
+ >
41
+ Previous
42
+ </button>
43
+ <span className="cg-pager-label">
44
+ {pageLabel(offset, size, total)}
45
+ <span className="cg-pager-page">Page {page.toLocaleString()} of {pages.toLocaleString()}</span>
46
+ </span>
47
+ <button
48
+ type="button"
49
+ className="cg-btn"
50
+ disabled={!hasNext}
51
+ onClick={() => onPage(offset + size)}
52
+ >
53
+ Next
54
+ </button>
55
+ </nav>
56
+ );
57
+ }
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -864,7 +864,7 @@ export default function Toolbar({
864
  recordCount,
865
  scopeCounts,
866
  pool,
867
- serverWindowed = false,
868
  cohortAction,
869
  filterSeed = null,
870
  modeControl,
@@ -1193,16 +1193,10 @@ export default function Toolbar({
1193
  {() => (
1194
  <div className="cg-pop-body">
1195
  <div className="cg-pop-title">Group by</div>
1196
- {serverWindowed ? (
1197
- // CG-3. Grouping runs over the rows in hand; on a windowed table those are ONE
1198
- // PAGE, so every group header would report a count and subtotals for the page
1199
- // while presenting them as the group's. Say why, rather than silently omitting
1200
- // the control — a missing button reads as a bug.
1201
- <div className="cg-pop-note">
1202
- Not available on this table. It loads one page at a time, so a group would
1203
- count only the rows currently fetched.
1204
- </div>
1205
- ) : (
1206
  <>
1207
  {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1208
  all and the opposite (Expand all)". Inside the NON-windowed branch on
 
864
  recordCount,
865
  scopeCounts,
866
  pool,
867
+ serverWindowed: _serverWindowed = false,
868
  cohortAction,
869
  filterSeed = null,
870
  modeControl,
 
1193
  {() => (
1194
  <div className="cg-pop-body">
1195
  <div className="cg-pop-title">Group by</div>
1196
+ {/* HOTFIX 2026-09-23: grouping is back on a read-through table. The groups, counts
1197
+ and totals come from the server over the whole match set, and each open group
1198
+ pages its own records (owner revoked the virtualise-only ruling). */}
1199
+ {(
 
 
 
 
 
 
1200
  <>
1201
  {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1202
  all and the opposite (Expand all)". Inside the NON-windowed branch on
web/src/customer-grid/apiBridge.ts CHANGED
@@ -565,7 +565,9 @@ export async function fetchAssignedCustomerRows(viewId: string): Promise<Custome
565
  /** One window's worth of rows. 200 is what D measured the route at (79 ms warm on 32,700
566
  * orders, against 474 ms for the whole read); the server clamps anything over
567
  * `datastore.WINDOW_MAX` (5,000) and REPORTS the clamp rather than trimming quietly. */
568
- export const WINDOW_ROWS = 200;
 
 
569
 
570
  export interface RowWindowRequest {
571
  offset: number;
@@ -586,6 +588,10 @@ export interface RowWindowRequest {
586
  * to see in the network panel.
587
  */
588
  related?: RelatedPin | null;
 
 
 
 
589
  }
590
 
591
  /**
@@ -629,6 +635,10 @@ export function windowRowsPath(tableKey: string, req: RowWindowRequest): string
629
  payload; assuming both were bodies is the half-wired contract that paints the right rows
630
  under a summary computed over the whole table. */
631
  if (req.related) q.set("related", JSON.stringify(req.related));
 
 
 
 
632
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
633
  }
634
 
 
565
  /** One window's worth of rows. 200 is what D measured the route at (79 ms warm on 32,700
566
  * orders, against 474 ms for the whole read); the server clamps anything over
567
  * `datastore.WINDOW_MAX` (5,000) and REPORTS the clamp rather than trimming quietly. */
568
+ // HOTFIX 2026-09-23 (owner): "pagination or next page and only load 50 at a time". The grid
569
+ // pages a read-through table 50 rows at a time with Prev / Next; `total` stays the server's.
570
+ export const WINDOW_ROWS = 50;
571
 
572
  export interface RowWindowRequest {
573
  offset: number;
 
588
  * to see in the network panel.
589
  */
590
  related?: RelatedPin | null;
591
+ /** HOTFIX 2026-09-23 — page ONE group of `/aggregates`' grouping. `key` is the group key
592
+ * exactly as `/aggregates` put it on the wire (`null` = the blank bucket). Part of the path,
593
+ * therefore part of the cache key. */
594
+ group?: { by: string; key: string | number | null } | null;
595
  }
596
 
597
  /**
 
635
  payload; assuming both were bodies is the half-wired contract that paints the right rows
636
  under a summary computed over the whole table. */
637
  if (req.related) q.set("related", JSON.stringify(req.related));
638
+ if (req.group && req.group.by) {
639
+ q.set("groupBy", req.group.by);
640
+ q.set("groupKey", JSON.stringify(req.group.key ?? null));
641
+ }
642
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
643
  }
644
 
web/src/customer-grid/counts.ts CHANGED
@@ -294,7 +294,6 @@ function firstSentence(cause: string | undefined): string {
294
  * there without a line here.
295
  */
296
  export const WINDOWED_TOOLS_OFF = [
297
- "grouping and its subtotals",
298
  "the kanban, calendar, list, map and catalog views",
299
  "export",
300
  "add to cohort, and remove from cohort",
 
294
  * there without a line here.
295
  */
296
  export const WINDOWED_TOOLS_OFF = [
 
297
  "the kanban, calendar, list, map and catalog views",
298
  "export",
299
  "add to cohort, and remove from cohort",
web/src/customer-grid/types.ts CHANGED
@@ -2855,7 +2855,14 @@ export type VisibleRow =
2855
  collapsed: boolean;
2856
  aggs: Record<string, string>;
2857
  }
2858
- | { kind: "group-footer"; groupKey: string; aggs: Record<string, string> };
 
 
 
 
 
 
 
2859
 
2860
  /** Multi-level sort: ordered = precedence (each key breaks ties within the prior). */
2861
  export interface SortRule {
 
2855
  collapsed: boolean;
2856
  aggs: Record<string, string>;
2857
  }
2858
+ | {
2859
+ kind: "group-footer";
2860
+ groupKey: string;
2861
+ aggs: Record<string, string>;
2862
+ /** HOTFIX 2026-09-23: per-group paging, the page this footer's group is showing. Absent
2863
+ * when the group fits on one page. */
2864
+ page?: { offset: number; total: number; size: number };
2865
+ };
2866
 
2867
  /** Multi-level sort: ordered = precedence (each key breaks ties within the prior). */
2868
  export interface SortRule {
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -746,38 +746,24 @@ export function useCustomerData(
746
  const requestWindow = useCallback((req: RowWindowRequest) => {
747
  if (suppliedPayload || !readThroughRef.current || STREAMLIT_COMPONENT || EMBEDDED_HTML) return;
748
  const offset = Math.max(0, Math.floor(req.offset || 0));
749
- // ⛔ ONE REQUEST PER PAGE IN FLIGHT. glide fires its visible-region callback on every frame
750
- // of a scroll; without this the same offset is asked for on each one. Offset 0 is exempt on
751
- // purpose — that is a PREDICATE change, and the newest predicate must always be able to
752
- // overtake an older one rather than be suppressed by it.
753
- if (offset > 0 && inflightOffset.current === offset) return;
754
- /* ⛔⛔ S64-T01 / C4 — PENDING IS FOR THE PREDICATE CHANGE ONLY, AND THE `offset === 0` GUARD
755
- IS THE WHOLE REASON THIS DOES NOT BREAK THE SCROLL. The two callers mean opposite things
756
- about the rows already on screen. Offset 0 REPLACES them: it is a view switch (the rows
757
- belong to the view the reader just left) or `CustomerGrid.tsx`'s bulk-write refresh, whose
758
- own comment says *"Do not paint loaded rows as though they were the whole update"*. Offset
759
- > 0 APPENDS to a window that is still the right view.
760
- ⛔ Without the guard every scroll page entered pending, and `viewSwitchPending` unmounts the
761
- `DataEditor` — so paging a read-through grid would blank it and return the reader to the top
762
- of the table, on every page. `counts.ts::nextWindowOffset` returns `loaded`, always >= 1, so
763
- that fires on EVERY append rather than in some corner. Pinned by `verify_api.py`'s C4
764
- section and its negative control. */
765
- if (offset === 0) setWindowPending(true);
766
  const seq = ++windowSeq.current;
767
- if (offset > 0) inflightOffset.current = offset;
768
- /* ⭐⭐ W51-T06 / C6 — AND THE SCROLL CARRIES THE PIN, WHICH IS THE HALF A CLOSURE LOSES.
769
- ⛔ `related` IS IN THE DEPENDENCY LIST BELOW FOR THIS ONE LINE. Left out, this callback
770
- would keep the pin it was built with: the first page correct and every appended page the
771
- WHOLE table, under a `total` that still described the pinned set. Nothing errors, the
772
- count agrees with itself, and the rows are two different populations stacked. */
773
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
774
- if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
775
  if (seq !== windowSeq.current) return;
776
  setWindowPending(false);
777
  if (!next) return;
778
- setData((prev) => mergeWindow(prev, next, offset));
779
  }).catch(() => {
780
- if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
781
  if (seq === windowSeq.current) setWindowPending(false);
782
  });
783
  }, [scope, related, suppliedPayload]);
 
746
  const requestWindow = useCallback((req: RowWindowRequest) => {
747
  if (suppliedPayload || !readThroughRef.current || STREAMLIT_COMPONENT || EMBEDDED_HTML) return;
748
  const offset = Math.max(0, Math.floor(req.offset || 0));
749
+ /* ⭐⭐ HOTFIX 2026-09-23 (owner: "pagination or next page and only load 50 at a time") — EVERY
750
+ request is a PAGE that REPLACES the rows in hand, so every one enters pending and the
751
+ newest one always wins (`windowSeq`). There is no scroll append any more, so the
752
+ one-request-per-offset dedupe that existed for scroll spam is gone: it could suppress a
753
+ page the reader asked for again while an older request for it was still in flight.
754
+ ⛔ Pending no longer unmounts the grid (`CustomerGrid.tsx::viewSwitchPending`): the rows
755
+ on screen stay until the next page lands, which is what made view switches feel instant. */
756
+ setWindowPending(true);
 
 
 
 
 
 
 
 
 
757
  const seq = ++windowSeq.current;
758
+ /* ⭐⭐ W51-T06 / C6 — THE PAGE CARRIES THE PIN. `related` IS IN THE DEPENDENCY LIST BELOW FOR
759
+ THIS ONE LINE: left out, every page after the first would be the WHOLE table under a
760
+ `total` that still described the pinned set. */
 
 
 
761
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
 
762
  if (seq !== windowSeq.current) return;
763
  setWindowPending(false);
764
  if (!next) return;
765
+ setData((prev) => mergeWindow(prev, next, 0));
766
  }).catch(() => {
 
767
  if (seq === windowSeq.current) setWindowPending(false);
768
  });
769
  }, [scope, related, suppliedPayload]);
web/src/customer-grid/useGetCellContent.ts CHANGED
@@ -199,6 +199,20 @@ function loadingCell(width: number | undefined, row: number, pulse: number): Gri
199
  */
200
  function groupFooterCell(vr: GroupFooterRow, col: number, field: Field | undefined): GridCell {
201
  const agg = field ? vr.aggs[field.key] : undefined;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  if (agg === undefined && col === 0 && vr.groupKey === TOTAL_GROUP_KEY)
203
  return {
204
  ...summaryCell(TOTAL_ROW_LABEL, SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
 
199
  */
200
  function groupFooterCell(vr: GroupFooterRow, col: number, field: Field | undefined): GridCell {
201
  const agg = field ? vr.aggs[field.key] : undefined;
202
+ // HOTFIX 2026-09-23: a paged group's first footer cell is its pager. The click handler in
203
+ // `CustomerGrid.onCellClicked` reads the left half as Previous and the right half as Next.
204
+ if (col === 0 && vr.page) {
205
+ const { offset, total, size } = vr.page;
206
+ const from = Math.min(total, offset + 1).toLocaleString();
207
+ const to = Math.min(total, offset + size).toLocaleString();
208
+ const prev = offset > 0 ? "‹ Prev" : "";
209
+ const next = offset + size < total ? "Next ›" : "";
210
+ return {
211
+ ...summaryCell(`${prev} ${from} to ${to} of ${total.toLocaleString()} ${next}`.trim(),
212
+ SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
213
+ contentAlign: "center",
214
+ };
215
+ }
216
  if (agg === undefined && col === 0 && vr.groupKey === TOTAL_GROUP_KEY)
217
  return {
218
  ...summaryCell(TOTAL_ROW_LABEL, SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
web/src/index.css CHANGED
@@ -422,6 +422,43 @@ body {
422
  overflow: hidden;
423
  }
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  .cg-loading {
426
  width: 100%;
427
  height: 100%;
 
422
  overflow: hidden;
423
  }
424
 
425
+ /* HOTFIX 2026-09-23: the read-through grid pages 50 rows at a time (owner). */
426
+ .cg-pager {
427
+ display: flex;
428
+ align-items: center;
429
+ justify-content: flex-end;
430
+ gap: 12px;
431
+ padding: 6px 12px;
432
+ border-top: 1px solid var(--cg-line, #E3E8EF);
433
+ font-size: 12px;
434
+ color: var(--cg-muted, #5B6B7F);
435
+ flex: 0 0 auto;
436
+ }
437
+ .cg-pager-label { display: inline-flex; gap: 10px; font-variant-numeric: tabular-nums; }
438
+ .cg-pager-page { color: var(--cg-faint, #8A97A8); }
439
+ .cg-pager[aria-busy="true"] .cg-pager-label { opacity: 0.6; }
440
+ /* The view-switch pending bar: the rows stay painted underneath it. */
441
+ .cg-view-pending {
442
+ position: absolute;
443
+ top: 0;
444
+ left: 0;
445
+ right: 0;
446
+ height: 2px;
447
+ z-index: 3;
448
+ background: linear-gradient(90deg, transparent, #1F4E78, transparent);
449
+ background-size: 50% 100%;
450
+ background-repeat: no-repeat;
451
+ animation: cg-view-pending-slide 0.9s linear infinite;
452
+ pointer-events: none;
453
+ }
454
+ @keyframes cg-view-pending-slide {
455
+ from { background-position: -50% 0; }
456
+ to { background-position: 150% 0; }
457
+ }
458
+ @media (prefers-reduced-motion: reduce) {
459
+ .cg-view-pending { animation: none; background: #1F4E78; opacity: 0.4; }
460
+ }
461
+
462
  .cg-loading {
463
  width: 100%;
464
  height: 100%;
web/src/settings/ExternalAccessPane.tsx CHANGED
@@ -157,8 +157,6 @@ type ApiResult<T> =
157
  // the MCP step verifies, and two copies of a route are two things to keep in step.
158
  const CONNECTIONS_PATH = "/external/oauth/connections";
159
 
160
- // What the user sends a coding agent once skill.md sits in the project folder.
161
- const SKILL_MESSAGE = "set up ./skill.md";
162
 
163
  function messageFrom(body: unknown, fallback: string): string {
164
  if (!body || typeof body !== "object") return fallback;
@@ -194,33 +192,6 @@ async function call<T>(path: string, init?: RequestInit): Promise<ApiResult<T>>
194
  }
195
  }
196
 
197
- async function callText(path: string): Promise<ApiResult<string>> {
198
- try {
199
- const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS });
200
- if (checkTenant(response)) {
201
- return { ok: false, message: "This workspace changed. Reloading.", status: 409 };
202
- }
203
- const body = await response.text();
204
- if (!response.ok) {
205
- if (response.status === 401 && typeof window !== "undefined") {
206
- window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
207
- }
208
- let parsed: unknown = null;
209
- try { parsed = JSON.parse(body); } catch { /* Markdown is the success shape. */ }
210
- return {
211
- ok: false,
212
- status: response.status,
213
- message: response.status >= 500
214
- ? "The AI API is unavailable right now."
215
- : messageFrom(parsed, "That request could not be completed."),
216
- };
217
- }
218
- return { ok: true, data: body };
219
- } catch {
220
- return { ok: false, message: "The server could not be reached.", status: 0 };
221
- }
222
- }
223
-
224
  function parseKey(value: unknown): ExternalKeyMetadata | null {
225
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
226
  const row = value as Record<string, unknown>;
@@ -339,6 +310,11 @@ export default function ExternalAccessPane() {
339
  const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
340
  return `${origin}${API_V1}/external/mcp`;
341
  }, []);
 
 
 
 
 
342
 
343
  const client = CLIENTS.find((entry) => entry.id === clientId);
344
  const connectionKinds: readonly ConnectionKind[] = client?.connections ?? [];
@@ -665,33 +641,6 @@ export default function ExternalAccessPane() {
665
  }
666
  }
667
 
668
- async function skillDocument(action: "copy" | "download"): Promise<string | null> {
669
- setBusy(`skill-${action}`); setError(""); setNotice("");
670
- const result = await callText("/external/skill.md");
671
- setBusy("");
672
- if (!result.ok) { setError(result.message); return null; }
673
- return result.data;
674
- }
675
-
676
- async function copySkill() {
677
- const document = await skillDocument("copy");
678
- if (document === null) return;
679
- await copy(document, "skill");
680
- setNotice("skill.md copied. It contains no API key or other secret.");
681
- }
682
-
683
- async function downloadSkill() {
684
- const document = await skillDocument("download");
685
- if (document === null) return;
686
- try {
687
- const url = URL.createObjectURL(new Blob([document], { type: "text/markdown;charset=utf-8" }));
688
- const anchor = window.document.createElement("a");
689
- anchor.href = url; anchor.download = "skill.md"; window.document.body.appendChild(anchor);
690
- anchor.click(); anchor.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 0);
691
- setNotice("skill.md downloaded. It contains no API key or other secret.");
692
- } catch { setError("skill.md could not be downloaded. Copy it instead."); }
693
- }
694
-
695
  function databaseChecks(selected: string[], change: (next: string[]) => void) {
696
  return (
697
  <div className="set-field" style={{ maxHeight: 216, overflowY: "auto" }}>
@@ -899,6 +848,7 @@ export default function ExternalAccessPane() {
899
  border-radius: var(--lp-r-sm);
900
  }
901
  .external-guide .set-help { margin-top: 16px; }
 
902
  .external-instructions {
903
  margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit;
904
  font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh);
@@ -1063,25 +1013,8 @@ export default function ExternalAccessPane() {
1063
  {step === "skill" && client ? (
1064
  <>
1065
  {settingUpFor()}
1066
- <ol className="external-steps">
1067
- <li>
1068
- <span>Save <kbd>skill.md</kbd> in your project folder</span>
1069
- <div className="set-actions" style={{ marginTop: 8 }}>
1070
- <button type="button" className="set-secondary" disabled={canMint !== true || busy !== ""}
1071
- onClick={() => void downloadSkill()}>{busy === "skill-download" ? "Preparing…" : "Download skill.md"}</button>
1072
- <button type="button" className="set-secondary" disabled={canMint !== true || busy !== ""}
1073
- onClick={() => void copySkill()}>{busy === "skill-copy" ? "Copying…" : copied === "skill" ? "Copied" : "Copy skill.md"}</button>
1074
- </div>
1075
- {canMint === false ? (
1076
- <p className="set-help">skill.md requires the Analyst module. Ask an administrator to grant it.</p>
1077
- ) : null}
1078
- </li>
1079
- <li>
1080
- <span>In your agent&apos;s chat, send</span>
1081
- {codeBlock(SKILL_MESSAGE, "skill-message")}
1082
- </li>
1083
- </ol>
1084
- <p className="set-help" style={{ marginTop: 16 }}>skill.md teaches {client.label} the Loopable API. It contains no API key or other secret.</p>
1085
  </>
1086
  ) : null}
1087
 
 
157
  // the MCP step verifies, and two copies of a route are two things to keep in step.
158
  const CONNECTIONS_PATH = "/external/oauth/connections";
159
 
 
 
160
 
161
  function messageFrom(body: unknown, fallback: string): string {
162
  if (!body || typeof body !== "object") return fallback;
 
192
  }
193
  }
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  function parseKey(value: unknown): ExternalKeyMetadata | null {
196
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
197
  const row = value as Record<string, unknown>;
 
310
  const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
311
  return `${origin}${API_V1}/external/mcp`;
312
  }, []);
313
+ // Monid's "set up <url>/SKILL.md": the public skill.md at the site root, readable with no session.
314
+ const skillMessage = useMemo(() => {
315
+ const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin;
316
+ return `set up ${origin}/skill.md`;
317
+ }, []);
318
 
319
  const client = CLIENTS.find((entry) => entry.id === clientId);
320
  const connectionKinds: readonly ConnectionKind[] = client?.connections ?? [];
 
641
  }
642
  }
643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644
  function databaseChecks(selected: string[], change: (next: string[]) => void) {
645
  return (
646
  <div className="set-field" style={{ maxHeight: 216, overflowY: "auto" }}>
 
848
  border-radius: var(--lp-r-sm);
849
  }
850
  .external-guide .set-help { margin-top: 16px; }
851
+ .external-send { margin: 0; font-size: var(--lp-fs-sm); color: var(--lp-ink); }
852
  .external-instructions {
853
  margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit;
854
  font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh);
 
1013
  {step === "skill" && client ? (
1014
  <>
1015
  {settingUpFor()}
1016
+ <p className="external-send">In your agent&apos;s chat, send:</p>
1017
+ {codeBlock(skillMessage, "skill-message")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1018
  </>
1019
  ) : null}
1020