fsanyoto commited on
Commit
d349fee
Β·
verified Β·
1 Parent(s): 3b266d8

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (41) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/automation_engine.py +0 -0
  4. api/connectors_ig.py +0 -0
  5. api/main.py +35 -0
  6. api/odoo_relational.py +339 -0
  7. api/routes_automation.py +18 -0
  8. api/routes_keychain.py +24 -6
  9. api/routes_nav.py +94 -13
  10. api/routes_odoo_tables.py +80 -0
  11. api/routes_tables.py +91 -31
  12. platform/aios_grid.py +183 -4
  13. platform/core/grid_events.py +0 -0
  14. platform/core/table_store.py +31 -0
  15. platform/core/user_tables.py +56 -1
  16. web/src/alerts/AlertsPane.tsx +35 -2
  17. web/src/alerts/alertsModel.ts +25 -0
  18. web/src/automation/AutomationBuilder.tsx +0 -0
  19. web/src/automation/AutomationDetail.tsx +140 -43
  20. web/src/automation/AutomationFind.tsx +893 -763
  21. web/src/automation/automationApi.ts +24 -8
  22. web/src/automation/steps.ts +422 -359
  23. web/src/customer-grid/ColumnMenu.tsx +0 -0
  24. web/src/customer-grid/CustomerGrid.tsx +0 -0
  25. web/src/customer-grid/JsonViewer.tsx +1015 -481
  26. web/src/customer-grid/RecordDetail.tsx +216 -21
  27. web/src/customer-grid/SwipeView.tsx +476 -0
  28. web/src/customer-grid/ViewSidebar.tsx +0 -0
  29. web/src/customer-grid/cells.ts +744 -724
  30. web/src/customer-grid/display.ts +28 -0
  31. web/src/customer-grid/filterSeed.ts +152 -0
  32. web/src/customer-grid/folders.ts +50 -0
  33. web/src/customer-grid/iconShapes.ts +53 -0
  34. web/src/customer-grid/timeSeriesData.ts +44 -1
  35. web/src/customer-grid/types.ts +180 -46
  36. web/src/index.css +543 -39
  37. web/src/settings/permsModel.ts +5 -0
  38. web/src/shell/Shell.tsx +215 -95
  39. web/src/shell/nav.ts +26 -0
  40. web/src/viz/seriesData.ts +7 -0
  41. web/src/viz/types.ts +9 -1
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "6e6c42b",
3
  "releases": [
4
  {
5
  "version": "v14",
 
1
  {
2
+ "current": "v14 (bee5eaf)",
3
  "releases": [
4
  {
5
  "version": "v14",
VERSION CHANGED
@@ -1 +1 @@
1
- 6e6c42b
 
1
+ v14 (bee5eaf)
api/automation_engine.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/connectors_ig.py ADDED
The diff for this file is too large to render. See raw diff
 
api/main.py CHANGED
@@ -74,6 +74,7 @@ import routes_tables # noqa: E402 (wave 18 C3-UT β€” user-created databases ov
74
  import routes_connectors # noqa: E402 (wave 23 C11 β€” the connectors directory; SESSION A's router)
75
  import routes_forms # noqa: E402 (wave 23 C9 β€” the PUBLIC form door; SESSION D's router)
76
  import routes_templates # noqa: E402 (wave 23 C12 β€” template apply doors; SESSION E's router)
 
77
  from core import grid_events # noqa: E402
78
  from deps import Session, module_gate # noqa: E402
79
 
@@ -223,6 +224,11 @@ app.include_router(routes_connectors.router) # item 10 / C11 β€” the connectors
223
  # by scanning tenants with a constant-time compare and answers a uniform 403, so a bad token cannot
224
  # distinguish "no such form" from "not yours", and it never echoes a tenant, table or slug.
225
  app.include_router(routes_forms.router) # item 8 / C9 β€” the PUBLIC form door
 
 
 
 
 
226
 
227
 
228
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
@@ -396,6 +402,35 @@ def _store_resync_loop():
396
  _ds.reconcile_deletes(log=lambda *a, **k: None)
397
  except Exception as e: # noqa: BLE001
398
  print(f"[aios-api] store resync failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
 
401
  def _prewarm():
 
74
  import routes_connectors # noqa: E402 (wave 23 C11 β€” the connectors directory; SESSION A's router)
75
  import routes_forms # noqa: E402 (wave 23 C9 β€” the PUBLIC form door; SESSION D's router)
76
  import routes_templates # noqa: E402 (wave 23 C12 β€” template apply doors; SESSION E's router)
77
+ import routes_odoo_tables # noqa: E402 (wave 27 item 17 β€” Odoo relational; SESSION E's router)
78
  from core import grid_events # noqa: E402
79
  from deps import Session, module_gate # noqa: E402
80
 
 
224
  # by scanning tenants with a constant-time compare and answers a uniform 403, so a bad token cannot
225
  # distinguish "no such form" from "not yours", and it never echoes a tenant, table or slug.
226
  app.include_router(routes_forms.router) # item 8 / C9 β€” the PUBLIC form door
227
+ # WAVE 27 item 17 β€” E's Odoo relational doors. Mounted in the SAME change that E's module landed,
228
+ # because the wave-23 scar is exactly this: three finished routers shipped with no include_router
229
+ # line β€” complete, gated, type-clean and 404 for every caller. `verify_api.section_mounts` walks
230
+ # `main.app.routes` and pins these two paths by NAME, so an unmounted router now goes RED.
231
+ app.include_router(routes_odoo_tables.router)
232
 
233
 
234
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
 
402
  _ds.reconcile_deletes(log=lambda *a, **k: None)
403
  except Exception as e: # noqa: BLE001
404
  print(f"[aios-api] store resync failed: {e}")
405
+ # ⭐ WAVE 27 item 17 (E's ASK ->A, resolved): the Odoo RELATIONAL tables are rebuilt
406
+ # AFTER the mirror they are derived from, in the same pass and in that order β€” deriving
407
+ # from a mirror this loop is about to advance would publish a worklist one cycle stale
408
+ # every single time.
409
+ #
410
+ # β›” ITS OWN try/except, NOT the one above. Folding it in would mean a failing relational
411
+ # rebuild swallowed the sync's error message, and worse: a sync failure would skip a
412
+ # rebuild that had nothing wrong with it. Two independent failures, two independent logs.
413
+ #
414
+ # ⚠ THE REBUILD IS NOT THE FRESHNESS GUARANTEE β€” the rows carry a visible `_refreshed`
415
+ # stamp for that. This loop is a daemon thread whose failure path is a `print` (D-29), so
416
+ # "the wiring exists" and "the data is current" are different claims and only the stamp
417
+ # can tell a user which one they are looking at.
418
+ # ⚠ SCOPED TO ROYAL-IMPORTS, and that is CORRECT here rather than the D-29 shortcut it
419
+ # resembles. `sync_all()` above advances whichever DuckDB file this process currently has
420
+ # open β€” tenant #0's β€” so royal's is the only mirror that just moved, and it is the only
421
+ # one these tables derive from (R1: the sole tenant with Odoo). Iterating tenants here
422
+ # would walk straight into D-29's documented hazard: `harness/datastore` is a
423
+ # ONE-FILE-AT-A-TIME process-global, and rebinding it in a daemon thread under live
424
+ # readers can serve one tenant's rows to another with nothing raised.
425
+ # `is_royal` stays the authority on which slugs qualify β€” this passes the slug and lets
426
+ # E's own guard refuse, rather than re-deciding the rule here.
427
+ try:
428
+ import odoo_relational as _rel
429
+ from harness import runtime as _runtime
430
+ if _rel.is_royal("royal-imports"):
431
+ _rel.refresh(_runtime.get_runtime("royal-imports"), "royal-imports")
432
+ except Exception as e: # noqa: BLE001
433
+ print(f"[aios-api] odoo relational rebuild failed: {e}")
434
 
435
 
436
  def _prewarm():
api/odoo_relational.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """odoo_relational.py β€” Odoo entities as LOCKED relational databases (wave 27 item 17, PHASE 1).
2
+
3
+ Owner ruling R1 / contract C8: spawn preset Odoo databases for Royal Imports, give them preset
4
+ Link + Rollup fields, and prove each rollup against the `measure_` column it will eventually
5
+ replace. `measure_` columns are NOT touched this wave.
6
+
7
+ β›” WHAT C8 ASKED FOR AND WHY TWO THIRDS OF IT IS NOT HERE (AMENDMENT E1, measured 2026-08-08).
8
+ C8 named three tables β€” orders, order lines, invoices. `core.user_tables.MAX_ROWS` is **5000**, and
9
+ the Royal mirror holds **32,700** confirmed orders, **254,189** order lines and **31,418** posted
10
+ customer invoices. Order lines are **50.8x** the cap and still **3.3x** over it at a 90-day window,
11
+ so no window rescues that table. Every `ut_*` table also lives in ONE JSON blob under one store key
12
+ that is read whole per render, so this is not a limit to raise β€” 318k rows there is a different
13
+ store, not a bigger number. C8's other half (Link/Rollup fields hosted on the Customer/Product
14
+ grids) is dead twice over: `aios_grid.fields_from_workspace` emits no `link`/`rollup` bag for a
15
+ `custom_` field, and `compute_relation_cells` reads `ut_all(rt)` exclusively while those grids have
16
+ no stored rows at all. Phase 2 therefore needs a READ-THROUGH binding over the DuckDB store the
17
+ rows already live in β€” not a copy. That is booked as debt, not attempted here.
18
+
19
+ ⭐ SO WHAT SHIPS IS THE POPULATION THAT FITS *AND* IS COMPLETE FOR ITS QUESTION: every OPEN customer
20
+ receivable (**1,228 rows / 438 partners / $591,828.54**, measured), two locked databases joined by a
21
+ derived link,
22
+ carrying the rollups that answer "what does this customer owe". A slice that is complete for a
23
+ question is a feature; a truncated copy of a bigger table is a number that is quietly wrong, which
24
+ is the one thing this repo refuses everywhere else. **This module REFUSES rather than truncates.**
25
+
26
+ THE POPULATION IS THE AR ORACLE'S, NOT ONE OF ITS OWN. `modules/ar._open_docs` selects
27
+ `state='posted'` AND `move_type in (out_invoice,out_refund)` AND
28
+ `payment_state in (not_paid,partial)`, minus `core.odoo.excluded_partner_ids()` (the GIFTWARE /
29
+ Amazon channel, out of wholesale scope). This module uses THAT predicate β€” not an equivalent one.
30
+ ⚠ Measured 2026-08-08: `payment_state in (not_paid,partial)` and `residual <> 0` return the
31
+ identical 1,238 rows / $2,347,608.49 today. They still are not the same QUESTION, and copying the
32
+ oracle's definition is what keeps them from drifting apart later.
33
+
34
+ ⚠⚠ AND THE EXCLUSION IS NOT A ROUNDING DETAIL: **GIFTWARE DEALS alone carries $1,755,779.95 of the
35
+ $2,347,608.49 raw open balance β€” 75% of it β€” across just 10 invoices.** So wholesale open AR is
36
+ $591,828.54, and anyone comparing this table against a raw `account_move` sum will see a 4x gap and
37
+ reasonably conclude something is broken. It is the Amazon channel being out of wholesale scope,
38
+ exactly as `modules/ar` and the Customer grid already have it.
39
+ """
40
+ import datetime as _dt
41
+
42
+ #: Royal Imports only (R1). A tenant slug that is not this one gets a refusal, never a spawn:
43
+ #: nurilab has no Odoo mirror behind these tables and would get two empty locked databases.
44
+ RI_SLUGS = ("", "royal-imports")
45
+
46
+ INVOICES_KEY = "ut_odoo_invoices"
47
+ CUSTOMERS_KEY = "ut_odoo_customers"
48
+
49
+ #: The join column both tables carry. The derived link resolves through it (`on`/`from`).
50
+ JOIN_KEY = "partner_id"
51
+
52
+ #: The oracle's own predicate β€” see the module docstring.
53
+ _AR_WHERE = ("state = 'posted' AND move_type IN ('out_invoice','out_refund') "
54
+ "AND payment_state IN ('not_paid','partial')")
55
+
56
+
57
+ def _ut():
58
+ import core.user_tables as user_tables
59
+ return user_tables
60
+
61
+
62
+ def _iso_today():
63
+ return _dt.date.today().strftime("%Y-%m-%d")
64
+
65
+
66
+ def _preset(field, flow="odoo_relational"):
67
+ """Stamp a field as machine-owned + preset β€” the `ut_ensure` lock_fields convention, so the
68
+ grid renders it grey and the preset walls refuse a rename or a delete."""
69
+ field = dict(field)
70
+ field["automation"] = {"flowId": flow, "preset": True}
71
+ return field
72
+
73
+
74
+ # ---------------------------------------------------------------------------------------------
75
+ # FIELD CONTRACTS
76
+ # ---------------------------------------------------------------------------------------------
77
+ # ⚠ Every type here must be in `core.user_tables.UT_FIELD_TYPES`, and `_clean_field` returns None
78
+ # for an unknown one β€” which DELETES the column silently on the next read rather than erroring.
79
+ def invoice_fields():
80
+ return [_preset(f) for f in (
81
+ {"key": "invoice_no", "label": "Invoice", "type": "text", "source": "overlay",
82
+ "default": True, "pinned": True},
83
+ {"key": "customer", "label": "Customer", "type": "text", "source": "overlay",
84
+ "default": True},
85
+ {"key": JOIN_KEY, "label": "Odoo partner id", "type": "int", "source": "overlay",
86
+ "default": False},
87
+ {"key": "invoice_date", "label": "Invoice date", "type": "date", "source": "overlay",
88
+ "default": True},
89
+ {"key": "due_date", "label": "Due date", "type": "date", "source": "overlay",
90
+ "default": True},
91
+ {"key": "residual", "label": "Outstanding $", "type": "currency", "source": "overlay",
92
+ "default": True, "agg": "sum"},
93
+ {"key": "amount_untaxed", "label": "Invoiced $", "type": "currency", "source": "overlay",
94
+ "default": False, "agg": "sum"},
95
+ {"key": "payment_state", "label": "Payment state", "type": "select", "source": "overlay",
96
+ "default": True, "options": ["not_paid", "partial"]},
97
+ {"key": "move_type", "label": "Document", "type": "select", "source": "overlay",
98
+ "default": False, "options": ["out_invoice", "out_refund"]},
99
+ {"key": "refreshed", "label": "Refreshed", "type": "date", "source": "overlay",
100
+ "default": False},
101
+ )]
102
+
103
+
104
+ def customer_fields():
105
+ """⭐ The LINK is DERIVED (`on` declared), so the engine owns the cell and a human cannot edit
106
+ a relation that Odoo already decided. The three rollups are C8's parity targets that this
107
+ substrate can actually host; the other two (order count, fully-invoiced sales) have no table to
108
+ roll up β€” they are proven in `verify_odoo_relational.py` instead, against the same fold."""
109
+ return [_preset(f) for f in (
110
+ {"key": "customer", "label": "Customer", "type": "text", "source": "overlay",
111
+ "default": True, "pinned": True},
112
+ {"key": JOIN_KEY, "label": "Odoo partner id", "type": "int", "source": "overlay",
113
+ "default": False},
114
+ {"key": "invoices", "label": "Open invoices", "type": "link", "source": "overlay",
115
+ "default": True,
116
+ "link": {"table": INVOICES_KEY, "on": JOIN_KEY, "from": JOIN_KEY}},
117
+ {"key": "ar_outstanding", "label": "AR outstanding $", "type": "rollup",
118
+ "source": "overlay", "default": True, "agg": "sum",
119
+ "rollup": {"link": "invoices", "field": "residual", "fn": "sum"}},
120
+ {"key": "open_invoices", "label": "Open invoices #", "type": "rollup",
121
+ "source": "overlay", "default": True,
122
+ "rollup": {"link": "invoices", "fn": "countall"}},
123
+ # β›” NOT `min`. `_rollup_fold`'s min/max are NUMERIC folds (`_lane_num`), so `min` over a
124
+ # date column finds no numbers and returns BLANK β€” a column that renders empty forever
125
+ # while looking configured. Ranking a DATE is what `latest` + `sortBy` is for: sort the
126
+ # linked rows ascending by due date and take the first. Caught by this module's own gate.
127
+ {"key": "oldest_due", "label": "Oldest due date", "type": "rollup", "source": "overlay",
128
+ "default": True,
129
+ "rollup": {"link": "invoices", "field": "due_date", "fn": "latest",
130
+ "sortBy": "due_date", "sortDir": "asc"}},
131
+ {"key": "refreshed", "label": "Refreshed", "type": "date", "source": "overlay",
132
+ "default": False},
133
+ )]
134
+
135
+
136
+ # ---------------------------------------------------------------------------------------------
137
+ # READING THE MIRROR
138
+ # ---------------------------------------------------------------------------------------------
139
+ def excluded_names():
140
+ """The partner names out of wholesale scope, from the ONE place that defines them.
141
+
142
+ Read through `core.odoo` rather than re-listed here: a second literal is a second scope, and
143
+ the day somebody adds a channel this module would keep answering the old question.
144
+ """
145
+ try:
146
+ import core.odoo as odoo
147
+ names = getattr(odoo, "EXCLUDE_PARTNER_NAMES", None) or set()
148
+ return {str(n).strip().lower() for n in names if str(n).strip()}
149
+ except Exception: # noqa: BLE001
150
+ return set()
151
+
152
+
153
+ def read_open_ar(cur, excluded=None):
154
+ """[(row dict)] β€” every open customer receivable in the mirror, oracle-scoped.
155
+
156
+ Takes a CURSOR so the gate can hand it a fixture connection; no global store binding here.
157
+ """
158
+ excluded = excluded if excluded is not None else excluded_names()
159
+ sql = ("SELECT id, name, partner_id, partner_name, invoice_date, invoice_date_due, "
160
+ " amount_untaxed_signed, amount_residual_signed, payment_state, move_type "
161
+ f"FROM account_move WHERE {_AR_WHERE} AND partner_id IS NOT NULL")
162
+ out = []
163
+ for r in cur.execute(sql).fetchall():
164
+ (mid, name, pid, pname, inv_date, due, untaxed, residual, pay_state, mtype) = r
165
+ if str(pname or "").strip().lower() in excluded:
166
+ continue
167
+ out.append({
168
+ "_id": str(mid),
169
+ "invoice_no": str(name or ""),
170
+ "customer": str(pname or ""),
171
+ JOIN_KEY: int(pid),
172
+ "invoice_date": _as_date(inv_date),
173
+ "due_date": _as_date(due),
174
+ "residual": float(residual or 0.0),
175
+ "amount_untaxed": float(untaxed or 0.0),
176
+ "payment_state": str(pay_state or ""),
177
+ "move_type": str(mtype or ""),
178
+ })
179
+ return out
180
+
181
+
182
+ def _as_date(value):
183
+ """ISO date string, or ''. The grid renders `date` cells itself (W26: `Aug 5, 2026`), so the
184
+ STORED value stays ISO β€” a formatted string in the cell is a value the filters cannot sort."""
185
+ if not value:
186
+ return ""
187
+ text = str(value)
188
+ return text[:10]
189
+
190
+
191
+ def customers_from(invoice_rows):
192
+ """The partners carrying open AR β€” derived from the SAME rows the invoice table holds, never
193
+ from a second query. Two populations built by two queries drift the moment one is edited."""
194
+ out = {}
195
+ for row in invoice_rows:
196
+ pid = row[JOIN_KEY]
197
+ entry = out.setdefault(str(pid), {"_id": str(pid), "customer": row["customer"],
198
+ JOIN_KEY: pid})
199
+ # A partner's name can differ across documents (renames land on new invoices only);
200
+ # the newest non-empty one wins so the locked table shows what Odoo shows today.
201
+ if row["customer"]:
202
+ entry["customer"] = row["customer"]
203
+ return list(out.values())
204
+
205
+
206
+ # ---------------------------------------------------------------------------------------------
207
+ # THE SPAWN
208
+ # ---------------------------------------------------------------------------------------------
209
+ class Refused(Exception):
210
+ """A refusal a caller should SHOW, not swallow. Every raise names what would otherwise have
211
+ been written wrong."""
212
+
213
+
214
+ def plan(cur, rt=None):
215
+ """The rows that WOULD be written, plus the refusals that apply β€” no store WRITE at all.
216
+
217
+ Separated from `apply_plan` so a route, a gate and a dry run all measure the same thing, and
218
+ so **every cap is checked before anything is committed**.
219
+
220
+ β›” `rt` IS WHAT MAKES THE TABLE-COUNT CHECK HONEST, and leaving it out was a real half-spawn
221
+ bug. This spawn writes TWO tables in two updater passes; a tenant one slot short of
222
+ `MAX_TABLES` would create `ut_odoo_invoices`, then refuse `ut_odoo_customers` β€” leaving a
223
+ locked invoices database with no rollup host, while the route answered 409 as though nothing
224
+ had happened. A partial spawn is worse than a refused one, so the count is checked against the
225
+ tables that ALREADY exist, before the first write.
226
+ """
227
+ ut = _ut()
228
+ invoices = read_open_ar(cur)
229
+ customers = customers_from(invoices)
230
+ problems = []
231
+ if rt is not None:
232
+ try:
233
+ existing = dict(rt.get(ut.STORE_KEY) or {})
234
+ except Exception: # noqa: BLE001
235
+ existing = {}
236
+ needed = [k for k in (INVOICES_KEY, CUSTOMERS_KEY) if k not in existing]
237
+ if needed and len(existing) + len(needed) > ut.MAX_TABLES:
238
+ problems.append(
239
+ f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} user tables and "
240
+ f"needs {len(needed)} more ({', '.join(needed)}); refusing rather than creating "
241
+ f"one half of a linked pair")
242
+ # β›” REFUSE, NEVER TRUNCATE. A capped AR table understates what customers owe while looking
243
+ # exactly like a complete one -- the failure mode this whole module is arranged against.
244
+ for key, rows in ((INVOICES_KEY, invoices), (CUSTOMERS_KEY, customers)):
245
+ if len(rows) > ut.MAX_ROWS:
246
+ problems.append(f"{key}: {len(rows)} rows exceeds MAX_ROWS={ut.MAX_ROWS}; refusing "
247
+ f"(a truncated receivables table understates the balance)")
248
+ return {"invoices": invoices, "customers": customers, "problems": problems}
249
+
250
+
251
+ def apply_plan(rt, built, username="automation", today=None):
252
+ """Create-or-merge both tables and their rows. Idempotent by construction.
253
+
254
+ Row ids ARE the Odoo ids, so a re-run updates in place and never appends a second copy of the
255
+ same invoice. Rows that left the population (paid since the last run) are REMOVED β€” an AR
256
+ worklist that keeps settled invoices is worse than a stale one, because every total it feeds
257
+ is then too high.
258
+ """
259
+ if built.get("problems"):
260
+ raise Refused("; ".join(built["problems"]))
261
+ stamp = today or _iso_today()
262
+ written = {}
263
+ for key, label, fields, rows in (
264
+ (INVOICES_KEY, "Odoo open invoices", invoice_fields(), built["invoices"]),
265
+ (CUSTOMERS_KEY, "Odoo AR customers", customer_fields(), built["customers"])):
266
+ written[key] = _ensure_table(rt, key, label, fields, rows, username, stamp)
267
+ return written
268
+
269
+
270
+ def _ensure_table(rt, key, label, fields, rows, username, stamp):
271
+ """One table: definition merged, rows reconciled, written only when something changed."""
272
+ ut = _ut()
273
+ wanted = {r["_id"]: {k: v for k, v in r.items() if k != "_id"} for r in rows}
274
+ for row in wanted.values():
275
+ row["refreshed"] = stamp
276
+ counts = {"added": 0, "updated": 0, "removed": 0, "rows": len(wanted)}
277
+
278
+ def _up(cur):
279
+ cur = cur if isinstance(cur, dict) else {}
280
+ table = cur.get(key)
281
+ if table is None:
282
+ if len(cur) >= ut.MAX_TABLES:
283
+ # ⚠ `ut_ensure` returns silently at this cap; a silent no-op here would report a
284
+ # successful refresh over a table that does not exist.
285
+ raise Refused(f"{key}: tenant is at MAX_TABLES={ut.MAX_TABLES}; nothing created")
286
+ table = cur[key] = {
287
+ "key": key, "label": label, "source": ut.AUTOMATION_SOURCE,
288
+ "createdBy": username, "created": stamp, "fields": [], "rows": {},
289
+ # recordMode = a LOCKED database (item-3 nomenclature): no human may add or
290
+ # delete records, while fields stay addable. Odoo owns this population.
291
+ "recordMode": ut.AUTOMATION_RECORD_MODE,
292
+ }
293
+ table.setdefault("recordMode", ut.AUTOMATION_RECORD_MODE)
294
+ have = {str(f.get("key")) for f in (table.get("fields") or [])}
295
+ for field in fields:
296
+ if str(field.get("key")) not in have:
297
+ table.setdefault("fields", []).append(dict(field))
298
+ stored = table.setdefault("rows", {})
299
+ for rid, values in wanted.items():
300
+ current = stored.get(rid)
301
+ if current is None:
302
+ stored[rid] = dict(values)
303
+ counts["added"] += 1
304
+ elif any(str(current.get(k, "")) != str(v) for k, v in values.items()
305
+ if k != "refreshed"):
306
+ current.update(values)
307
+ counts["updated"] += 1
308
+ else:
309
+ current["refreshed"] = values["refreshed"]
310
+ for rid in [r for r in stored if r not in wanted]:
311
+ stored.pop(rid, None)
312
+ counts["removed"] += 1
313
+ return cur
314
+
315
+ rt.update(ut.STORE_KEY, _up, flush="sync")
316
+ return counts
317
+
318
+
319
+ def is_royal(tenant):
320
+ return str(tenant or "").strip().lower() in RI_SLUGS
321
+
322
+
323
+ def refresh(rt, tenant, username="automation", cur=None, today=None):
324
+ """THE entry point β€” the store-resync path and the route both call this.
325
+
326
+ ⚠ It must be CALLED on resync by something outside this file (see the ASK to session A). If it
327
+ is not wired, every row still carries a `refreshed` stamp, so a stale worklist is at least
328
+ LEGIBLE rather than silently authoritative.
329
+ """
330
+ if not is_royal(tenant):
331
+ raise Refused(f"tenant {tenant!r} has no Odoo mirror behind these tables (R1: Royal "
332
+ f"Imports only); refusing to spawn two empty locked databases")
333
+ if cur is None:
334
+ from harness import datastore
335
+ cur = datastore.ro_con()
336
+ built = plan(cur, rt=rt)
337
+ written = apply_plan(rt, built, username=username, today=today)
338
+ return {"tables": written,
339
+ "invoices": len(built["invoices"]), "customers": len(built["customers"])}
api/routes_automation.py CHANGED
@@ -56,6 +56,24 @@ def _wire(defn, tenant):
56
  "created": defn.get("created"), "createdBy": defn.get("createdBy"),
57
  "nextRunAt": nxt.strftime("%Y-%m-%d %H:%M") if nxt else "",
58
  "running": bool(live),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  # C3 (wave 22): the trigger config rides whole β€” the webhook token included, because
60
  # the person configuring the external caller has to be shown the URL somewhere, and
61
  # this payload is session-gated behind the same wall as everything else here.
 
56
  "created": defn.get("created"), "createdBy": defn.get("createdBy"),
57
  "nextRunAt": nxt.strftime("%Y-%m-%d %H:%M") if nxt else "",
58
  "running": bool(live),
59
+ # ⭐ WAVE 27 (contract C6) β€” DEBT D-70: "a paid search is already outstanding at the
60
+ # vendor". THE MONEY GUARD, and it was INERT for a whole wave because this line was
61
+ # missing: the client declared `awaitingResults` REQUIRED and read it in `runBlock()`,
62
+ # nothing ever sent it, so `undefined` was falsy and the Run button stayed armed.
63
+ #
64
+ # β›” WHY IT IS NOT `running`. `running` above is PROCESS state (`engine.running`) and is
65
+ # FALSE for the entire 20–30 MINUTE vendor wait, which IS the hazard window: the ticks
66
+ # are 3 minutes apart, so between them the automation is idle and the button re-arms.
67
+ # MEASURED the expensive way on 2026-08-06 (~$0.025): with no snapshot outstanding a
68
+ # Run-now press returned 200 and started a BRAND-NEW billable corpus search.
69
+ #
70
+ # β›” AND NOT A PERSISTED "running" FLAG EITHER β€” the engine header forbids one (it
71
+ # outlives the process and locks the automation forever). `state.pendingSnapshot` is the
72
+ # field that already exists, is already persisted, is already carried untouched through
73
+ # `clean_definition`, and is the SAME expression `pending_collect_ids()` uses to decide
74
+ # what to collect. One truth, two readers.
75
+ "awaitingResults": bool(str((defn.get("state") or {}).get("pendingSnapshot")
76
+ or "").strip()),
77
  # C3 (wave 22): the trigger config rides whole β€” the webhook token included, because
78
  # the person configuring the external caller has to be shown the URL somewhere, and
79
  # this payload is session-gated behind the same wall as everything else here.
api/routes_keychain.py CHANGED
@@ -222,13 +222,31 @@ def connectors(session: Session = Depends(admin_gate)):
222
  # different answers (a persisted snapshot, an in-process cache, a frozen mirror), and
223
  # collapsing them into "everything freezes" would be the kind of tidy summary that
224
  # stops being true the first time one of them changes.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  "pausedNote": ("Pausing a connector never deletes data β€” notes, custom fields and "
226
- "views stay, and nothing reaches the source while it is paused. The "
227
- "customer workspace serves its pause-time snapshot, the product list "
228
- "serves the last copy this server read, and measure columns keep "
229
- "answering from the mirror as it stood when you paused β€” so figures "
230
- "stop moving rather than going blank. Resume to start reading live "
231
- "again.")}
 
 
232
  if session.tenant == "royal-imports":
233
  out["unsynced"] = _unsynced_customer_records(session)
234
  return out
 
222
  # different answers (a persisted snapshot, an in-process cache, a frozen mirror), and
223
  # collapsing them into "everything freezes" would be the kind of tidy summary that
224
  # stops being true the first time one of them changes.
225
+ # ⭐ D-62 CLOSED (wave 27) β€” AND THE REGISTER'S DIAGNOSIS OF IT WAS WRONG, so the
226
+ # correction is recorded here rather than silently applied. D-62 said this note
227
+ # "promises a behaviour on a dashboard measure path that has been dead since W16".
228
+ # MEASURED 2026-08-08, and it is not: measure COLUMNS are grid columns answered from
229
+ # the DuckDB mirror, and `harness/datastore.py` genuinely refuses to sync while
230
+ # paused (`source_paused()` at four sites), so that clause was TRUE. The dead path is
231
+ # `/api/v1/pages/{key}` (D-52), which this note never mentioned.
232
+ #
233
+ # β›” THE REAL DEFECT WAS THE OPPOSITE ONE, and it was the last sentence: "so figures
234
+ # stop moving rather than going blank". BOTH pool paths answer **503** when they have
235
+ # no copy to serve β€” the customer path for a scope with no snapshot
236
+ # (`routes_customers.py:88`) and the product path ALWAYS after a restart, because
237
+ # there is no product snapshot bucket at all (`routes_products.py:60-73`, which says
238
+ # so in as many words). So a paused connector plus a restarted server is exactly the
239
+ # blank screen this sentence promised could not happen. A warning that over-promises
240
+ # is worse than none: it is the sentence somebody quotes when the screen disagrees.
241
  "pausedNote": ("Pausing a connector never deletes data β€” notes, custom fields and "
242
+ "views stay, and nothing reaches the source while it is paused. "
243
+ "Anything this server has already read keeps showing: the customer "
244
+ "workspace serves its pause-time snapshot, the product list serves "
245
+ "the last copy read since startup, and measure columns keep answering "
246
+ "from the mirror as it stood when you paused. What has NOT been read "
247
+ "cannot be shown β€” a scope with no snapshot, or the product list after "
248
+ "a restart, reports that the source is paused instead of showing "
249
+ "figures. Resume to start reading live again.")}
250
  if session.tenant == "royal-imports":
251
  out["unsynced"] = _unsynced_customer_records(session)
252
  return out
api/routes_nav.py CHANGED
@@ -80,12 +80,19 @@ def _now() -> int:
80
  return int(time.time())
81
 
82
 
83
- def _clean_nav_prefs(raw, page_keys):
84
  """Validated wholesale replacement, the `clean_folders` posture: prune, never invent.
85
 
86
  `page_keys` is the set of TOP-LEVEL keys this session may see; a placement of an unknown
87
  or invisible key is dropped (it can return when the grant does β€” placement is cosmetic,
88
  so pruning is loss-free). Unknown folder refs drop the placement, not the folder.
 
 
 
 
 
 
 
89
  """
90
  raw = raw if isinstance(raw, dict) else {}
91
  folders, seen = [], set()
@@ -104,15 +111,54 @@ def _clean_nav_prefs(raw, page_keys):
104
  if isinstance(src, dict):
105
  for k, v in src.items():
106
  k, v = str(k)[:60], str(v)[:40]
107
- if v in ids and (page_keys is None or k in page_keys):
 
 
 
 
108
  placement[k] = v
109
  return {"folders": folders, "placement": placement}
110
 
111
 
112
- def _visible_top_keys(user):
113
- """The keys a placement may name: top-level rows (group heads + parentless pages)."""
114
- pages = perms.nav_pages(user) or []
115
- return {p["key"] for p in pages if not p.get("parent")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
 
118
  def _clean_icon(raw):
@@ -251,11 +297,17 @@ def nav(session: Session = Depends(require_session)):
251
  # merging on the day that invariant changes.
252
  meta = _read_nav_meta(session.runtime)
253
  # Wave 21 (C3): the definitions, once β€” `manage`/`canDelete` below answer from `createdBy`.
 
254
  try:
255
  import core.user_tables as _ut_mod
256
  _ut_defs = _ut_mod.all_tables(st=session.runtime) or {}
 
 
 
 
257
  except Exception:
258
  _ut_defs = {}
 
259
  for p in pages:
260
  # `manage` (R14): may THIS session change this row's icon/name? Answered HERE because
261
  # the server is the only end that knows β€” the client cannot see who created a user
@@ -274,6 +326,28 @@ def nav(session: Session = Depends(require_session)):
274
  _mine = bool(session.admin or (_creator and _creator == session.uname))
275
  p["manage"] = _mine
276
  p["canDelete"] = _mine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  elif session.admin:
278
  p["manage"] = True
279
  entry = meta.get(p.get("key")) if meta else None
@@ -290,11 +364,16 @@ def nav(session: Session = Depends(require_session)):
290
  # for. A second round trip for a list this short, computed from a bucket this route is
291
  # already holding the store open for, would be a request per page load for no gain.
292
  #
293
- # β›” `allowed` IS THE ASSEMBLED PAGE LIST, not `_visible_top_keys`. The latter reads
294
- # `perms.nav_pages` alone, which does NOT include this tenant's `ut_*` databases β€” those are
295
- # merged into `pages` above, by this route, after the permission wall. Pruning against the
296
- # narrower set would have silently dropped every user database from Home's recents: the
297
- # exact surface R7 is about, invisible, with every gate green.
 
 
 
 
 
298
  recents = _read_recents(session.runtime, session.uname,
299
  {str(p.get("key", "")) for p in pages})
300
  return {"pages": pages, "landing": landing, "recents": recents}
@@ -461,7 +540,8 @@ def nav_prefs(session: Session = Depends(require_session)):
461
  stored = (session.runtime.get(_NAV_PREFS_KEY) or {}).get(session.uname) or {}
462
  except Exception:
463
  stored = {}
464
- return {"prefs": _clean_nav_prefs(stored, _visible_top_keys(session.user))}
 
465
 
466
 
467
  @router.post("/nav/prefs")
@@ -469,7 +549,8 @@ def save_nav_prefs(body: dict = Body(default=None),
469
  session: Session = Depends(require_session)):
470
  """Wholesale replace, like the table folder stratum β€” the client sent its complete
471
  picture, validated here; a partial merge would resurrect deleted folders forever."""
472
- clean = _clean_nav_prefs(body or {}, _visible_top_keys(session.user))
 
473
  if not session.runtime.available():
474
  raise err(503, "store_unavailable",
475
  "the tenant store is unavailable β€” nothing was saved")
 
80
  return int(time.time())
81
 
82
 
83
+ def _clean_nav_prefs(raw, page_keys, *, keep_unknown_ut=False):
84
  """Validated wholesale replacement, the `clean_folders` posture: prune, never invent.
85
 
86
  `page_keys` is the set of TOP-LEVEL keys this session may see; a placement of an unknown
87
  or invisible key is dropped (it can return when the grant does β€” placement is cosmetic,
88
  so pruning is loss-free). Unknown folder refs drop the placement, not the folder.
89
+
90
+ `keep_unknown_ut` is the STORE-BLIP escape hatch β€” see `_placeable_top_keys`. When the
91
+ `ut_*` listing could not be read, a `ut_` key absent from `page_keys` is KEPT rather than
92
+ pruned: keeping a placement whose database may since have been deleted is cosmetically
93
+ harmless, while pruning a live one is the silent data loss this function just stopped
94
+ causing. Never widened to non-`ut_` keys β€” those come from the compiled registry, which
95
+ cannot fail to enumerate.
96
  """
97
  raw = raw if isinstance(raw, dict) else {}
98
  folders, seen = [], set()
 
111
  if isinstance(src, dict):
112
  for k, v in src.items():
113
  k, v = str(k)[:60], str(v)[:40]
114
+ if v not in ids:
115
+ continue # the folder is gone; the placement goes with it
116
+ if page_keys is None or k in page_keys:
117
+ placement[k] = v
118
+ elif keep_unknown_ut and k.startswith("ut_"):
119
  placement[k] = v
120
  return {"folders": folders, "placement": placement}
121
 
122
 
123
+ def _placeable_top_keys(session):
124
+ """`(keys, enumerated)` β€” the keys a placement may name, INCLUDING this tenant's databases.
125
+
126
+ β›” THIS IS THE ITEM-6 FIX (wave 27, contract C1), and the bug it closes was invisible by
127
+ construction. The old version read `perms.nav_pages` alone β€” the compiled REGISTRY β€” and
128
+ `perms.py` contains no `ut_` or `user_tables` reference at all, because a tenant's
129
+ user-created databases are merged into the nav payload by `nav()` BELOW the permission wall.
130
+ So every `ut_*` key was absent from this set, and `_clean_nav_prefs` pruned every placement
131
+ naming one β€” on READ and on WRITE.
132
+
133
+ The symptom was "a database I drag into a folder falls out of it later", never "it does not
134
+ work": the write answered **200 OK** having stored `{}`, the client kept its optimistic copy
135
+ (`Shell.commitPrefs` reverts only on `!ok`), and the folder held for the rest of the session.
136
+ The next reload served the pruned copy and the database was back at root. Built-in modules
137
+ (`customer_data`, `product_data`) ARE in the registry and persisted fine, which is exactly
138
+ why it read as intermittent rather than as a missing feature.
139
+
140
+ ⚠ THE SAME MISTAKE, ALREADY MADE AND ALREADY FIXED ONE FUNCTION AWAY. `nav()`'s recents
141
+ block (see its `allowed` comment) hit this in wave 23 and solved it by pruning against the
142
+ ASSEMBLED page list. This is that lesson applied to the second consumer, which the wave-23
143
+ fix did not reach.
144
+
145
+ `enumerated` is False when the `ut_` listing raised β€” the caller must then NOT treat this set
146
+ as authoritative for `ut_` keys (`keep_unknown_ut`). Pruning a person's whole arrangement
147
+ because the store blinked would be the original defect wearing a different cause.
148
+ """
149
+ pages = perms.nav_pages(session.user) or []
150
+ keys = {p["key"] for p in pages if not p.get("parent")}
151
+ try:
152
+ import core.user_tables as user_tables
153
+ # The SAME listing `nav()` renders from β€” `may_open`-filtered, so a placement can never
154
+ # name a database this session cannot see, and the nav and this door agree by sharing
155
+ # one predicate rather than by two lists being kept in step.
156
+ for e in user_tables.nav_entries(viewer=session.uname, is_admin=session.admin,
157
+ st=session.runtime):
158
+ keys.add(str(e.get("key") or ""))
159
+ except Exception:
160
+ return keys, False
161
+ return keys, True
162
 
163
 
164
  def _clean_icon(raw):
 
297
  # merging on the day that invariant changes.
298
  meta = _read_nav_meta(session.runtime)
299
  # Wave 21 (C3): the definitions, once β€” `manage`/`canDelete` below answer from `createdBy`.
300
+ # WAVE 27 (C9): `locked` answers from `recordMode`, off the same one read.
301
  try:
302
  import core.user_tables as _ut_mod
303
  _ut_defs = _ut_mod.all_tables(st=session.runtime) or {}
304
+ # β›” NEVER DEFAULT THIS TO `None`. `_ut_defs.get(k)` is `{}` for an unknown key, so its
305
+ # `.get("recordMode")` is None too οΏ½οΏ½οΏ½ and `None == None` would mark EVERY database locked
306
+ # the moment this import failed. A sentinel that can equal real data is not a sentinel.
307
+ _ut_locked_mode = str(_ut_mod.AUTOMATION_RECORD_MODE)
308
  except Exception:
309
  _ut_defs = {}
310
+ _ut_locked_mode = ""
311
  for p in pages:
312
  # `manage` (R14): may THIS session change this row's icon/name? Answered HERE because
313
  # the server is the only end that knows β€” the client cannot see who created a user
 
326
  _mine = bool(session.admin or (_creator and _creator == session.uname))
327
  p["manage"] = _mine
328
  p["canDelete"] = _mine
329
+ # ⭐ WAVE 27 item 3 (contract C9) β€” A LOCKED DATABASE SAYS SO IN THE RAIL.
330
+ #
331
+ # "Locked" is the owner's item-4 vocabulary and it means exactly ONE thing (DESIGN.md
332
+ # Β§4, THE THREE LOCKS): RECORDS cannot be added, deleted or edited β€” **fields still
333
+ # can**. The automation-owned IG child datasets (posts, comments, snapshots) are the
334
+ # live example; their rows arrive from the engine, so a "+" row there could only
335
+ # refuse, which R8 calls a fake affordance.
336
+ #
337
+ # ⚠ THE AUTHORITY IS `user_tables.records_mutable`, NOT THIS LINE. The comparison is
338
+ # inlined only because `_ut_defs` is already in hand β€” calling the predicate per row
339
+ # would be one store read per database on every nav request β€” and the VALUE comes
340
+ # from the module's own constant rather than a copied string, so the two cannot drift
341
+ # to different answers. If that predicate ever grows a second condition, this must
342
+ # become a call.
343
+ #
344
+ # ⚠ ABSENT READS AS UNLOCKED, and that is the safe direction here even though it is
345
+ # the opposite of `manage`'s fail-closed: the lock ICON is an affordance hint, while
346
+ # the actual refusal is `routes_tables._records_or_refuse`'s 403. A store blip costs
347
+ # a missing hint, never a write that should not have landed.
348
+ if (_ut_locked_mode
349
+ and (_ut_defs.get(key) or {}).get("recordMode") == _ut_locked_mode):
350
+ p["locked"] = True
351
  elif session.admin:
352
  p["manage"] = True
353
  entry = meta.get(p.get("key")) if meta else None
 
364
  # for. A second round trip for a list this short, computed from a bucket this route is
365
  # already holding the store open for, would be a request per page load for no gain.
366
  #
367
+ # β›” `allowed` IS THE ASSEMBLED PAGE LIST β€” the rows this route just built, `ut_*` databases
368
+ # included. Pruning against `perms.nav_pages` alone would silently drop every user database
369
+ # from Home's recents: the exact surface R7 is about, invisible, with every gate green.
370
+ #
371
+ # ⚠ WAVE 27 (item 6): the OTHER consumer of that narrower set β€” the folder-placement door β€”
372
+ # had the identical bug and nobody connected the two for four waves. It is fixed at the
373
+ # source now (`_placeable_top_keys`, which merges the same `may_open`-filtered listing), so
374
+ # both doors finally agree on what a placeable key is. This block keeps using the assembled
375
+ # list because it already holds it: re-enumerating here would be a second store read for an
376
+ # answer sitting in a local variable.
377
  recents = _read_recents(session.runtime, session.uname,
378
  {str(p.get("key", "")) for p in pages})
379
  return {"pages": pages, "landing": landing, "recents": recents}
 
540
  stored = (session.runtime.get(_NAV_PREFS_KEY) or {}).get(session.uname) or {}
541
  except Exception:
542
  stored = {}
543
+ keys, enumerated = _placeable_top_keys(session)
544
+ return {"prefs": _clean_nav_prefs(stored, keys, keep_unknown_ut=not enumerated)}
545
 
546
 
547
  @router.post("/nav/prefs")
 
549
  session: Session = Depends(require_session)):
550
  """Wholesale replace, like the table folder stratum β€” the client sent its complete
551
  picture, validated here; a partial merge would resurrect deleted folders forever."""
552
+ keys, enumerated = _placeable_top_keys(session)
553
+ clean = _clean_nav_prefs(body or {}, keys, keep_unknown_ut=not enumerated)
554
  if not session.runtime.available():
555
  raise err(503, "store_unavailable",
556
  "the tenant store is unavailable β€” nothing was saved")
api/routes_odoo_tables.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_odoo_tables.py β€” the door to the Odoo relational spawn (wave 27 item 17, contract C8).
2
+
3
+ Two endpoints and no cleverness: refresh the locked Odoo databases, and report their freshness.
4
+ The work itself lives in `odoo_relational.py`; this file only decides WHO may ask and turns a
5
+ refusal into a status code.
6
+
7
+ β›” THIS ROUTER SHIPS DEAD UNTIL SESSION A ADDS ITS `include_router` LINE (wave-23 scar: three
8
+ finished routers shipped 404-dead behind entirely green gates, because a cross-fence wiring row can
9
+ only prove both files mention the same path SEGMENT). The pairing is a named checkpoint in the wave
10
+ doc, not an assumption -- and `verify_api` now enumerates `main.app.routes`, which is the control
11
+ that actually answers it.
12
+
13
+ ADMIN-GATED, and not for tidiness: a refresh REWRITES two locked databases for the whole tenant and
14
+ deletes the rows that left the population. That is an operator action.
15
+ """
16
+ from fastapi import Depends
17
+ from fastapi import APIRouter
18
+
19
+ from deps import Session, err, require_session
20
+
21
+ router = APIRouter(prefix="/api/v1")
22
+
23
+
24
+ def _rel():
25
+ import odoo_relational
26
+ return odoo_relational
27
+
28
+
29
+ @router.post("/odoo-tables/refresh")
30
+ def refresh_odoo_tables(session: Session = Depends(require_session)):
31
+ """Rebuild `ut_odoo_invoices` + `ut_odoo_customers` from the tenant's Odoo mirror.
32
+
33
+ Idempotent: row ids are Odoo ids, so a re-run updates in place. Returns what MOVED, because
34
+ "refreshed" with no counts is indistinguishable from a no-op over an empty mirror.
35
+ """
36
+ # β›” `deps.err()` RETURNS an HTTPException, it does not raise one β€” so it must be `raise
37
+ # err(...)`. `return err(...)` serialises the exception object with a **200**, which is the
38
+ # wave-23 shape exactly: a finished route, green everything, wrong on the wire. The house
39
+ # convention is 243 `raise err` against 6 strays; this file uses `raise`.
40
+ rel = _rel()
41
+ if not session.is_admin:
42
+ raise err(403, "forbidden", "Refreshing the Odoo databases is an admin action.")
43
+ if not rel.is_royal(session.tenant):
44
+ # A plain 400 with the reason: this tenant has no Odoo mirror, and spawning two empty
45
+ # locked databases it can never fill would be worse than refusing.
46
+ raise err(400, "not_applicable",
47
+ "These databases are built from the Royal Imports Odoo mirror (R1).")
48
+ try:
49
+ return {"ok": True, **rel.refresh(session.runtime, session.tenant,
50
+ username=session.user)}
51
+ except rel.Refused as e:
52
+ # A refusal is the ANSWER, not a crash: the caller must see WHY nothing was written.
53
+ raise err(409, "refused", str(e))
54
+ except RuntimeError as e:
55
+ # `datastore.ro_con()` raises this while the store is completing its first sync. Relaying
56
+ # it beats writing a partial table from a half-synced mirror.
57
+ raise err(503, "store_not_ready", str(e))
58
+
59
+
60
+ @router.get("/odoo-tables/status")
61
+ def odoo_tables_status(session: Session = Depends(require_session)):
62
+ """Row counts + the newest `refreshed` stamp per table.
63
+
64
+ ⚠ The stamp is the whole point while the resync wiring is outstanding: a locked collections
65
+ worklist that quietly stopped updating is a worklist that lies, so its age must be readable
66
+ without anybody running a refresh to find out.
67
+ """
68
+ rel, out = _rel(), {}
69
+ import core.user_tables as user_tables
70
+ for key in (rel.INVOICES_KEY, rel.CUSTOMERS_KEY):
71
+ table = user_tables.get(key, st=session.runtime) or {}
72
+ rows = (table.get("rows") or {})
73
+ stamps = [str((r or {}).get("refreshed") or "") for r in rows.values()]
74
+ out[key] = {
75
+ "exists": bool(table),
76
+ "rows": len(rows),
77
+ "refreshed": max([s for s in stamps if s], default=""),
78
+ "locked": table.get("recordMode") == user_tables.AUTOMATION_RECORD_MODE,
79
+ }
80
+ return {"ok": True, "applicable": rel.is_royal(session.tenant), "tables": out}
api/routes_tables.py CHANGED
@@ -16,6 +16,7 @@ VISIBILITY is `user_tables.may_open` β€” creator or admin, fail-closed. There is
16
  to check because a user table is not a module; the per-table wall is the whole wall, and it is
17
  applied in `_defn_or_refuse` before any payload is built.
18
  """
 
19
  import time
20
 
21
  from fastapi import Body, Depends
@@ -36,15 +37,71 @@ def _ops(session, table_key):
36
  return table_store.make(f"{table_key}_table_workspace", st=session.runtime)
37
 
38
 
 
 
 
 
 
 
 
39
  def _refresh_relations(session):
40
- """Refresh reciprocal Links and Rollups after a human record/schema mutation."""
41
- import automation_engine as engine
42
- try:
43
- engine.refresh_relations(session.runtime, log=lambda *_args: None)
44
- except Exception as exc: # noqa: BLE001
45
- # The source write already landed. A later automation/tick will repair materialised
46
- # cells; never answer 503 and invite the browser to repeat a successful mutation.
47
- print(f"[tables] relation refresh deferred: {type(exc).__name__}: {exc}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
 
50
  def _defn_or_refuse(session, table_key):
@@ -70,21 +127,31 @@ def _records_or_refuse(session, table_key):
70
  return defn
71
 
72
 
73
- #: Tables whose ROWS ARE PER-USER (D-39, wave 22 C6's view half): a non-admin sees the rows
74
- #: they created plus any row nobody owns; an admin sees the whole pool.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  #:
76
- #: β›” NAMED EXPLICITLY, NEVER INFERRED FROM A `created_by` COLUMN. Every automation-written
77
- #: table carries one β€” a scraped table's rows say `automation` β€” so inferring the rule from the
78
- #: column's presence would hide every scraped row from every non-admin, which is the same
79
- #: silent-disappearance defect one table wide instead of one table narrow.
80
  #:
81
- #: ⚠ AN UNOWNED ROW STAYS VISIBLE TO EVERYONE, and that is deliberate rather than lax: rows
82
- #: written before the ownership stamp existed (nurilab's 58 candidates, measured 2026-08-05)
83
- #: belong to nobody, and a rule that hid them would delete a team's working set from their
84
- #: screen on deploy day while reporting nothing. New rows carry their finder's name, so the
85
- #: owner's ask β€” "each user only works with their own data" β€” holds going forward without a
86
- #: migration that guesses who found what.
87
- PER_USER_TABLES = ("ut_ig_candidates",)
88
 
89
 
90
  def scoped_pool(session: Session, table_key: str):
@@ -98,20 +165,13 @@ def scoped_pool(session: Session, table_key: str):
98
  defn = _defn_or_refuse(session, table_key)
99
  fields_base = [dict(f) for f in (defn.get("fields") or [])]
100
  field_keys = {f["key"] for f in fields_base}
101
- per_user = str(table_key) in PER_USER_TABLES and not session.admin
102
- me = str(session.uname or "").strip().lower()
103
  rows_src = []
104
  for rid, row in (defn.get("rows") or {}).items():
105
  if not str(rid).isdigit():
106
  continue
107
- # D-39 (wave 22's C6 view half): on a PER-USER table a non-admin sees their own rows
108
- # and nobody else's. `created_by` is read off the RAW row, never the field-filtered
109
- # copy below β€” it is written by the engine as row data and is not always a declared
110
- # column, so filtering the projection would silently stop filtering anything.
111
- if per_user:
112
- owner = str((row or {}).get("created_by") or "").strip().lower()
113
- if owner and owner != me:
114
- continue
115
  r = {k: v for k, v in (row or {}).items() if k in field_keys}
116
  r["pid"] = int(rid)
117
  rows_src.append(r)
 
16
  to check because a user table is not a module; the per-table wall is the whole wall, and it is
17
  applied in `_defn_or_refuse` before any payload is built.
18
  """
19
+ import threading
20
  import time
21
 
22
  from fastapi import Body, Depends
 
37
  return table_store.make(f"{table_key}_table_workspace", st=session.runtime)
38
 
39
 
40
+ #: WAVE 27 item 2 (contract C2 / amendment A2) β€” the relation refresh is COALESCED and runs OFF
41
+ #: the request path. `{tenant: True}` while a pass is queued; the worker holds the lock.
42
+ _REL_LOCK = threading.Lock()
43
+ _REL_DIRTY = {}
44
+ _REL_RUNNING = {}
45
+
46
+
47
  def _refresh_relations(session):
48
+ """Mark this tenant's Links/Rollups stale and refresh them AFTER the response, once.
49
+
50
+ β›” WHY THIS IS NOT A DIRECT CALL ANY MORE, and the numbers are the argument. The owner's
51
+ item 2 was "adding a new record visually takes too long, I need to be able to spam it", and
52
+ this function was the largest single cost inside `POST /tables/{key}/rows`:
53
+ `engine.refresh_relations` DEEP-COPIES every table and every row in the tenant before it can
54
+ decide whether anything needs doing (`automation_engine.py:9383-9388`), and when something
55
+ does it commits with `flush="sync"` β€” a store round trip, i.e. an HF Dataset commit on the
56
+ default backend. Every added record paid a whole-tenant snapshot plus a synchronous commit
57
+ before the 201 came back.
58
+
59
+ β›” AND BACKGROUNDING ALONE WOULD HAVE BEEN A WORSE BUG. Twenty rapid adds would queue twenty
60
+ whole-tenant snapshots, each one re-reading a store the previous one just wrote β€” the spam
61
+ the item asks us to support is exactly the load that would melt it. So this COALESCES: at
62
+ most one pass runs, and at most one is queued behind it.
63
+
64
+ ⚠ THE DIRTY FLAG IS THE LOAD-BEARING PART, not the lock. A write landing WHILE a pass is in
65
+ flight must still get a pass afterwards, because the in-flight one snapshotted before that
66
+ write existed. Without the flag the LAST add in a burst is precisely the one whose rollups
67
+ never update β€” the failure nobody would notice until a total was quietly wrong.
68
+
69
+ Eventual consistency is the accepted trade and was already the documented posture: the tick
70
+ repairs materialised cells regardless, and answering 503 here would invite the browser to
71
+ repeat a mutation that already succeeded.
72
+ """
73
+ tenant = str(getattr(session, "tenant", "") or "")
74
+ rt = session.runtime
75
+ with _REL_LOCK:
76
+ _REL_DIRTY[tenant] = True
77
+ if _REL_RUNNING.get(tenant):
78
+ return # a worker is live; it will see the flag and loop
79
+ _REL_RUNNING[tenant] = True
80
+
81
+ def _worker():
82
+ import automation_engine as engine
83
+ try:
84
+ while True:
85
+ with _REL_LOCK:
86
+ if not _REL_DIRTY.get(tenant):
87
+ _REL_RUNNING.pop(tenant, None)
88
+ return
89
+ _REL_DIRTY.pop(tenant, None)
90
+ try:
91
+ engine.refresh_relations(rt, log=lambda *_args: None)
92
+ except Exception as exc: # noqa: BLE001
93
+ # The source write already landed and the response is already sent. Log and
94
+ # let the tick repair it; never retry in a tight loop.
95
+ print(f"[tables] relation refresh deferred: {type(exc).__name__}: {exc}")
96
+ finally:
97
+ # Belt for an unexpected raise on the bookkeeping itself: a tenant left marked
98
+ # RUNNING would never refresh again for the life of the process.
99
+ with _REL_LOCK:
100
+ if _REL_RUNNING.get(tenant) and not _REL_DIRTY.get(tenant):
101
+ _REL_RUNNING.pop(tenant, None)
102
+
103
+ threading.Thread(target=_worker, daemon=True,
104
+ name=f"rel-refresh:{tenant or 'default'}").start()
105
 
106
 
107
  def _defn_or_refuse(session, table_key):
 
127
  return defn
128
 
129
 
130
+ #: β›” THE PER-USER CANDIDATE WALL IS RETIRED (WAVE 27, DEBT D-72). **THE TENANT IS THE UNIT, NOT
131
+ #: THE USER** β€” one profile is ONE row, and everyone who may open the database sees all of it.
132
+ #:
133
+ #: WHY IT HAD TO GO, and it is not a preference: wave 26's R4 made the candidate identity
134
+ #: `(platform, handle)` and `_merge_candidates` stamps only the FIRST finder, later finders never
135
+ #: overwriting. Combined with a wall that then showed a non-admin only `created_by == me`, the
136
+ #: two were SILENT DATA LOSS β€” the second finder's row was merged away into the first finder's,
137
+ #: and the wall then hid the survivor from the person who just found it. They searched, they
138
+ #: paid, and the screen said nothing arrived.
139
+ #:
140
+ #: ⚠ AND THE PAIR WAS MUTUALLY MASKING, which is why it stayed green for a wave: the wall named
141
+ #: `ut_ig_candidates`, and a READ-ONLY census of all four tenant stores
142
+ #: (`ops/w26_candidate_census.py`) proved that table exists in NO tenant β€” since wave 25's R2 the
143
+ #: write target is whatever database the user points the Create-record action at. So the wall
144
+ #: governed a table nobody writes, and fixing EITHER half alone would have armed the other
145
+ #: ([[defects-that-mask-each-other]]).
146
  #:
147
+ #: The register offered two exits and R4 already implied this one. Restoring per-user visibility
148
+ #: instead would have required R4's merge to stop crossing users β€” a bigger change, against the
149
+ #: ruling, to bring back a wall that never governed anything real.
 
150
  #:
151
+ #: β›” DO NOT RE-ADD THIS BY INFERRING THE RULE FROM A `created_by` COLUMN. Every
152
+ #: automation-written table has one (a scraped row says `automation`), so inference would hide
153
+ #: every scraped row from every non-admin β€” the same disappearance defect, one table wide instead
154
+ #: of one table narrow. `created_by` survives as W26/R4's informational "Found by" stamp ONLY.
 
 
 
155
 
156
 
157
  def scoped_pool(session: Session, table_key: str):
 
165
  defn = _defn_or_refuse(session, table_key)
166
  fields_base = [dict(f) for f in (defn.get("fields") or [])]
167
  field_keys = {f["key"] for f in fields_base}
 
 
168
  rows_src = []
169
  for rid, row in (defn.get("rows") or {}).items():
170
  if not str(rid).isdigit():
171
  continue
172
+ # WAVE 27 / D-72: no per-row owner filter. The table-level wall above
173
+ # (`_defn_or_refuse` -> `may_open`) is the WHOLE wall β€” see the retirement note on
174
+ # PER_USER_TABLES' former home. A row this session can reach is a row the tenant owns.
 
 
 
 
 
175
  r = {k: v for k, v in (row or {}).items() if k in field_keys}
176
  r["pid"] = int(rid)
177
  rows_src.append(r)
platform/aios_grid.py CHANGED
@@ -122,7 +122,45 @@ def _round(v):
122
  #: point at, so the column menu there simply never offers one.
123
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
124
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
125
- "automation", "image", "json", "link", "rollup"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
127
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
128
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
@@ -646,6 +684,11 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
646
  **({"max": _clean_rating_max(field.get("max"))} if ftype == "rating" else {}),
647
  **({"automation": _clean_automation(field.get("automation"))}
648
  if ftype == "automation" and _clean_automation(field.get("automation")) else {}),
 
 
 
 
 
649
  **_field_extras(field, ftype),
650
  })
651
  if cohorts and not any(f.get('key') == COHORT_COLUMN for f in out):
@@ -831,8 +874,20 @@ def _clean_rhs(raw, valid_keys):
831
  #: views are sitting in mode:'dashboard' right now (wave 8's own close-out records one). The
832
  #: rename is therefore a stored-value MIGRATION, not a constant rename: accept 'dashboard' on
833
  #: READ forever, only ever WRITE 'chart'.
 
 
 
 
 
 
834
  DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard', 'chart',
835
- 'timeseries', 'catalog'}
 
 
 
 
 
 
836
 
837
  #: C-DISP (wave 2026-08-02): the time-series view's bucket vocabulary and caps, plus the
838
  #: calendar-summary metric cap. types.ts mirrors these as TS_BUCKETS / TS_MAX_LAST_N /
@@ -1296,6 +1351,34 @@ def _clean_display(raw, valid_keys):
1296
  catalogs = _clean_catalogs(raw.get('catalogs'), valid_keys)
1297
  if catalogs:
1298
  out['catalogs'] = catalogs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1299
  return out
1300
 
1301
 
@@ -1584,7 +1667,63 @@ def locked_view_projection(entry, base_config):
1584
  }
1585
 
1586
 
1587
- def views_from_defs(defs, saved_views, fields, system_name="All customers", locked_lists=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1588
  """Convert legacy list formulas into the shared serializable SavedView contract.
1589
 
1590
  `system_name` (wave 16 C-TOPIC) labels the system view per TOPIC ("All products" on the
@@ -1603,6 +1742,15 @@ def views_from_defs(defs, saved_views, fields, system_name="All customers", lock
1603
  "id": "all-customers", "name": system_name, "kind": "system",
1604
  "locked": True, "config": dict(base),
1605
  }]
 
 
 
 
 
 
 
 
 
1606
  op_map = {">=": "gte", ">": "gt", "<=": "lte", "<": "lt", "=": "eq",
1607
  "contains": "contains"}
1608
  for name, definition in (defs or {}).items():
@@ -1664,6 +1812,31 @@ def views_from_defs(defs, saved_views, fields, system_name="All customers", lock
1664
  # One thing, one name: the cohort store owns it (the rename event routes there), so
1665
  # a stale `name` on the saved record can never fork into a second title.
1666
  _v['name'] = _entry.get('name') or _v['id']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1667
  return views
1668
 
1669
 
@@ -1725,7 +1898,13 @@ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storag
1725
  else "All records"
1726
  if str(scope_key or '').startswith('ut_')
1727
  else "All customers"),
1728
- locked_lists=cohort_lists)
 
 
 
 
 
 
1729
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
1730
  # Owner item 3 (2026-07-31): where this user left off. The client's own localStorage copy
1731
  # wins when present; this is the server's answer for a FRESH browser, which used to fall
 
122
  #: point at, so the column menu there simply never offers one.
123
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
124
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
125
+ "automation", "image", "json", "link", "rollup", "code"}
126
+
127
+ #: ⭐ WAVE-27 item 13 (owner ruling R13) β€” the `code` field's LANGUAGES.
128
+ #:
129
+ #: R13 is explicit that this kind is "syntax-highlighted storage + language config, NO execution
130
+ #: engine". So a language is a RENDERING hint and nothing else: it selects a highlighter, it never
131
+ #: selects an interpreter, and no value here may ever grow a run path. The list is short on
132
+ #: purpose β€” every entry costs a highlighter the client actually has to implement, and an
133
+ #: unimplemented language would paint plain text under a label promising colour.
134
+ #:
135
+ #: `plain` is the default and the fallback, so it is never a second way to say nothing: it is the
136
+ #: honest answer for a snippet whose language the user has not chosen.
137
+ CODE_LANGUAGES = {"plain", "json", "sql", "python", "javascript", "typescript",
138
+ "html", "css", "markdown", "yaml", "xml", "shell"}
139
+
140
+
141
+ def _clean_code(raw):
142
+ """The `code` field's config bag -> `{'language': ...}`, or None.
143
+
144
+ Deliberately OPTIONAL rather than required (the `automation` posture, not `link`'s): a code
145
+ column with no declared language is a legitimate state β€” it stores and highlights as plain
146
+ text β€” so refusing the FIELD over a missing bag would block the ordinary create path. An
147
+ unknown language falls back to `plain` rather than refusing, because the value is a rendering
148
+ hint: dropping the user's column to punish a typo in a highlighter name would be the
149
+ disproportionate half of the fail-closed rule.
150
+
151
+ ⚠ `plain` RETURNS NONE, and that is what makes the control reversible rather than one-way.
152
+ Absent already means plain, so storing `{'language': 'plain'}` would be the default wearing a
153
+ second name (the `kanbanClamp` law). But the patch path resolves an OMITTED key to the
154
+ previous value β€” so if plain were merely omitted by the client, switching a column back from
155
+ SQL to Plain text would keep storing SQL and read as a control that does not save. Sending
156
+ the bag explicitly and having it evaluate to None here means: omit = keep, plain = clear.
157
+ """
158
+ if not isinstance(raw, dict):
159
+ return None
160
+ lang = str(raw.get('language') or 'plain').strip().lower()
161
+ if lang not in CODE_LANGUAGES or lang == 'plain':
162
+ return None
163
+ return {'language': lang}
164
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
165
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
166
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
 
684
  **({"max": _clean_rating_max(field.get("max"))} if ftype == "rating" else {}),
685
  **({"automation": _clean_automation(field.get("automation"))}
686
  if ftype == "automation" and _clean_automation(field.get("automation")) else {}),
687
+ # ⭐ WAVE-27 item 13 (R13) β€” the code column's language rides the wire, because the
688
+ # highlighter is chosen per column and the client cannot infer a language from a
689
+ # string. Absent = `plain`, which is what an unconfigured code column renders as.
690
+ **({"code": _clean_code(field.get("code"))}
691
+ if ftype == "code" and _clean_code(field.get("code")) else {}),
692
  **_field_extras(field, ftype),
693
  })
694
  if cohorts and not any(f.get('key') == COHORT_COLUMN for f in out):
 
874
  #: views are sitting in mode:'dashboard' right now (wave 8's own close-out records one). The
875
  #: rename is therefore a stored-value MIGRATION, not a constant rename: accept 'dashboard' on
876
  #: READ forever, only ever WRITE 'chart'.
877
+ #: ⭐ WAVE-27 item 8 (owner ruling R2, contract C3): 'swipe' β€” a DECK of the records whose bound
878
+ #: single-select is EMPTY, triaged one at a time by swiping left or right into two of that
879
+ #: field's options. Landed here FIRST and in the same change as the client registry, which is
880
+ #: the whole reason the two modes above it needed a staged hold: `_clean_display` DROPS an
881
+ #: unknown mode, so a client that offers a mode this set does not carry lets a user build a view
882
+ #: that silently reverts to a grid on the next read.
883
  DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard', 'chart',
884
+ 'timeseries', 'catalog', 'swipe'}
885
+
886
+ #: C3 β€” the swipe binding's option cap. `leftOption`/`rightOption` are stored VALUES of a
887
+ #: single-select, and `_clean_options` trims every choice to 120 chars, so this is that same
888
+ #: number rather than a second opinion about it: a longer string cannot name a real option, and
889
+ #: a SHORTER cap here would silently refuse a binding to a legal one.
890
+ MAX_SWIPE_OPTION = 120
891
 
892
  #: C-DISP (wave 2026-08-02): the time-series view's bucket vocabulary and caps, plus the
893
  #: calendar-summary metric cap. types.ts mirrors these as TS_BUCKETS / TS_MAX_LAST_N /
 
1351
  catalogs = _clean_catalogs(raw.get('catalogs'), valid_keys)
1352
  if catalogs:
1353
  out['catalogs'] = catalogs
1354
+ # ── ⭐ WAVE-27 C3 (item 8 / R2): the swipe binding ────────────────────────────────────
1355
+ # `{fieldKey, leftOption, rightOption}` β€” WHOLE-KEY drop, never a partial one, and that
1356
+ # asymmetry against `charts`/`calendarMetrics` above is the point rather than an oversight.
1357
+ # Those are LISTS of independent cards, so losing one entry costs the user one card. This is
1358
+ # a single three-part BINDING: a swipe view holding a fieldKey with one option, or two
1359
+ # options and no field, is not a degraded swipe view β€” it is a deck that can never write
1360
+ # anything, rendered as though it were configured. Dropping the key entirely puts the view
1361
+ # back in its honest unconfigured state, which is the one state the client has a UI for.
1362
+ #
1363
+ # ⚠ What this CANNOT check, deliberately, and why the client must: whether `fieldKey` names
1364
+ # a SELECT, and whether the two options are still in that select's vocabulary. `valid_keys`
1365
+ # is a key set, and the docstring above draws this exact line β€” "what each mode MEANS ... is
1366
+ # the client's business". So SwipeView owns three losses this function is blind to (field
1367
+ # deleted, field retyped away from select, option removed) and must SHOW each one rather
1368
+ # than fall back to the first option, per the `viewModes.tsx` house rule.
1369
+ swipe = raw.get('swipe')
1370
+ if isinstance(swipe, dict):
1371
+ f_key = swipe.get('fieldKey')
1372
+ left, right = swipe.get('leftOption'), swipe.get('rightOption')
1373
+ ok = (f_key in valid_keys
1374
+ and isinstance(left, str) and isinstance(right, str))
1375
+ if ok:
1376
+ left, right = left.strip()[:MAX_SWIPE_OPTION], right.strip()[:MAX_SWIPE_OPTION]
1377
+ # Both non-empty, and DISTINCT: one option on both sides is a deck whose two
1378
+ # gestures do the same thing, which is two spellings of one state (the
1379
+ # `kanbanClamp` law) wearing a control that promises a choice.
1380
+ if left and right and left.casefold() != right.casefold():
1381
+ out['swipe'] = {'fieldKey': f_key, 'leftOption': left, 'rightOption': right}
1382
  return out
1383
 
1384
 
 
1667
  }
1668
 
1669
 
1670
+ #: ⭐ WAVE-27 item 27 (owner ruling R8) β€” the IG "Overview" view's CURATED COLUMNS, in the
1671
+ #: owner's own order: handle, followers, engagement, location, last enriched.
1672
+ #:
1673
+ #: Written as candidates rather than as a requirement. The template registry REFUSES a template
1674
+ #: whose columns the target lacks (`view_templates.missing_columns`) because applying one writes
1675
+ #: the user's own views and a filter on a missing column silently WIDENS. This view is INJECTED,
1676
+ #: not applied, and it filters nothing β€” so the proportionate rule is the opposite one: take the
1677
+ #: columns the table has, in this order, and skip the rest. An IG database that predates a
1678
+ #: column simply shows the other four.
1679
+ #:
1680
+ #: ⚠ `location_guess` is SESSION B's item-16 column and may not exist yet. That is exactly why
1681
+ #: this list is intersected rather than asserted: a hard requirement here would make the whole
1682
+ #: view vanish (or the assembly refuse) on every tenant until B lands, and then appear by
1683
+ #: surprise. `profile_url` closes the list as the click-through, which is what makes the view
1684
+ #: usable rather than merely informative.
1685
+ IG_OVERVIEW_COLUMNS = ('handle', 'full_name', 'followers', 'avg_engagement',
1686
+ 'location_guess', 'enriched_at', 'profile_url')
1687
+
1688
+ #: The id is PINNED, the `view_templates` discipline: re-assembling must update the same view
1689
+ #: rather than mint "Overview 2". It also lets a user's own edits overlay it through the saved
1690
+ #: -config loop below, exactly as a cohort projection does.
1691
+ IG_OVERVIEW_ID = 'tpl_overview'
1692
+
1693
+ #: How this function recognises an IG preset database WITHOUT importing the engine: two of the
1694
+ #: profile preset columns is a stronger signal than any single one (a hand-made table could
1695
+ #: plausibly own a column called `followers`; owning `followers` AND `avg_engagement` AND
1696
+ #: `handle` is the preset set). `core/` must stay importable without the API layer, so this
1697
+ #: mirrors `user_tables.PROFILE_PRESET_KEYS` the way that module mirrors the engine's.
1698
+ _IG_SIGNATURE = ('handle', 'followers', 'avg_engagement')
1699
+
1700
+
1701
+ def _ig_overview_view(fields, base):
1702
+ """R8's curated Overview, or None when this table is not an Instagram one."""
1703
+ keys = {f['key'] for f in fields}
1704
+ if not all(k in keys for k in _IG_SIGNATURE):
1705
+ return None
1706
+ visible = [k for k in IG_OVERVIEW_COLUMNS if k in keys]
1707
+ return {
1708
+ 'id': IG_OVERVIEW_ID,
1709
+ 'name': 'Overview',
1710
+ 'kind': 'system',
1711
+ # NOT `locked`. The system view is locked because it is the identity of the table ("show
1712
+ # me everything"); this one is a STARTING LAYOUT, and R8 calls it curated rather than
1713
+ # fixed. A user who wants a sixth column should get one.
1714
+ 'note': 'The five things worth seeing first on a creator. Sorted by reach.',
1715
+ 'config': {
1716
+ **dict(base),
1717
+ 'visible': visible,
1718
+ 'order': visible + [k for k in (f['key'] for f in fields) if k not in visible],
1719
+ 'sorts': ([{'colId': 'followers', 'dir': 'desc'}]
1720
+ if 'followers' in keys else []),
1721
+ },
1722
+ }
1723
+
1724
+
1725
+ def views_from_defs(defs, saved_views, fields, system_name="All customers", locked_lists=None,
1726
+ view_order=None):
1727
  """Convert legacy list formulas into the shared serializable SavedView contract.
1728
 
1729
  `system_name` (wave 16 C-TOPIC) labels the system view per TOPIC ("All products" on the
 
1742
  "id": "all-customers", "name": system_name, "kind": "system",
1743
  "locked": True, "config": dict(base),
1744
  }]
1745
+ # ⭐ WAVE-27 item 27 (R8) β€” the IG Overview, ABOVE All records.
1746
+ #
1747
+ # ⚠ INJECTED, not seeded into the store, and that is what makes "existing IG databases gain
1748
+ # it too" true with no migration and no write on a read path. It is the same mechanism the
1749
+ # system view above has always used; the pinned id means a user's own edits overlay it
1750
+ # through the saved-config loop below rather than forking a second view.
1751
+ _overview = _ig_overview_view(fields, base)
1752
+ if _overview:
1753
+ views.insert(0, _overview)
1754
  op_map = {">=": "gte", ">": "gt", "<=": "lte", "<": "lt", "=": "eq",
1755
  "contains": "contains"}
1756
  for name, definition in (defs or {}).items():
 
1812
  # One thing, one name: the cohort store owns it (the rename event routes there), so
1813
  # a stale `name` on the saved record can never fork into a second title.
1814
  _v['name'] = _entry.get('name') or _v['id']
1815
+ # ── ⭐ WAVE-27 item 5, contract C7: the PER-USER VIEW ORDER ───────────────────────────────
1816
+ #
1817
+ # `view_order` is a list of view ids this user dragged into place. Applied LAST, over the
1818
+ # finished list, so it reorders whatever the assembly produced without having to know how any
1819
+ # of it got there (system, list:, cohort projection, saved, injected Overview).
1820
+ #
1821
+ # β›” THE SYSTEM VIEW STAYS AT INDEX 0 (C7), and it is re-pinned here rather than trusted to
1822
+ # sort correctly: `all-customers` is the client's landing default and one of its
1823
+ # UNDELETABLE_VIEW_IDS, so a stored order that happened to omit it β€” or list it third β€”
1824
+ # would move the rail's home row. ⚠ R8's Overview is the ONE thing allowed above it, because
1825
+ # the owner put it there; it is re-pinned with the system view so a drag cannot bury it
1826
+ # either. Both are facts about the table rather than the user's arrangement of it.
1827
+ #
1828
+ # ⚠ UNKNOWN IDS APPEND IN SERVER ORDER (C7). A view created since this order was stored, or
1829
+ # one shared to this user yesterday, must APPEAR β€” dropping it would make sharing look
1830
+ # broken, and the failure would be invisible to whoever shared it. Ids in the stored order
1831
+ # that no longer resolve are simply skipped.
1832
+ if view_order:
1833
+ _rank = {vid: i for i, vid in enumerate(view_order) if isinstance(vid, str)}
1834
+ _pinned = [v for v in views if v.get('id') in (IG_OVERVIEW_ID, 'all-customers')]
1835
+ _rest = [v for v in views if v.get('id') not in (IG_OVERVIEW_ID, 'all-customers')]
1836
+ # A stable sort over a rank that DEFAULTS TO THE END keeps unranked views in their
1837
+ # server order behind the ranked ones, rather than interleaving them by accident.
1838
+ _rest.sort(key=lambda v: _rank.get(v.get('id'), len(_rank) + 1))
1839
+ views = _pinned + _rest
1840
  return views
1841
 
1842
 
 
1898
  else "All records"
1899
  if str(scope_key or '').startswith('ut_')
1900
  else "All customers"),
1901
+ locked_lists=cohort_lists,
1902
+ # ⭐ WAVE-27 item 5 (C7) β€” this user's own rail arrangement, from
1903
+ # their own stratum. Read here rather than sorted by the client so
1904
+ # the ORDER a request answers with is the order that was stored:
1905
+ # sorting client-side would make the rail settle after a paint on
1906
+ # every load, and shared views would land in server order first.
1907
+ view_order=ws.get('viewOrder'))
1908
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
1909
  # Owner item 3 (2026-07-31): where this user left off. The client's own localStorage copy
1910
  # wins when present; this is the server's answer for a FRESH browser, which used to fall
platform/core/grid_events.py CHANGED
The diff for this file is too large to render. See raw diff
 
platform/core/table_store.py CHANGED
@@ -339,6 +339,37 @@ class TableStore:
339
  ws['itemFolders'] = dict(item_folders or {})
340
  self._update(username, _set)
341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  def shared_views(self, viewer, is_admin=False):
343
  """Every SHARED view this viewer may see, by id (wave-9 I17).
344
 
 
339
  ws['itemFolders'] = dict(item_folders or {})
340
  self._update(username, _set)
341
 
342
+ def save_view_order(self, username, order):
343
+ """⭐ WAVE-27 item 5 (contract C7) β€” this user's own ORDER for the views rail.
344
+
345
+ Wholesale, like `save_folders` above and for the same reason: the client sends the full
346
+ list it is looking at, not a delta, because a partial order cannot say where an UNNAMED
347
+ view went.
348
+
349
+ β›” PER USER, and it belongs in this stratum rather than on the view records themselves.
350
+ `aios_grid`'s own folder note argues it out for placements and every word applies: an
351
+ arrangement is a per-user ORGANISING act, not part of what a view IS β€” so keeping it out
352
+ of the view config means duplicating, sharing or exporting a view does not drag one
353
+ person's rail position along with it. It also means a SHARED view can sit in a different
354
+ place for each person who can see it, which is the only coherent answer once two people
355
+ share one view.
356
+
357
+ An empty list CLEARS the arrangement (back to server order) rather than storing `[]`.
358
+ """
359
+ def _set(ws):
360
+ clean = []
361
+ seen = set()
362
+ for vid in (order or []):
363
+ vid = str(vid).strip()[:120]
364
+ if vid and vid not in seen:
365
+ seen.add(vid)
366
+ clean.append(vid)
367
+ if clean:
368
+ ws['viewOrder'] = clean
369
+ else:
370
+ ws.pop('viewOrder', None)
371
+ self._update(username, _set)
372
+
373
  def shared_views(self, viewer, is_admin=False):
374
  """Every SHARED view this viewer may see, by id (wave-9 I17).
375
 
platform/core/user_tables.py CHANGED
@@ -79,9 +79,19 @@ def records_mutable(table_key, st=None):
79
  #: materialised into the row, because a rollup reads ANOTHER TABLE'S ROWS β€” data the client has
80
  #: not loaded and must not have to. `formula` stayed out of this list because it computes
81
  #: client-side over one row; that argument does not reach these two.
 
 
 
 
 
 
 
 
 
 
82
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
83
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
84
- 'link', 'rollup'}
85
  #: A cell is still a scalar on the wire (`Row` values are strings/numbers) β€” what this bounds is
86
  #: the DOCUMENT inside it. Source data is one already-paid provider response; keep it whole so a
87
  #: provider field is never silently discarded merely because the response is rich. 32 MiB matches
@@ -292,6 +302,26 @@ def clean_fields(raw):
292
  entry['options'] = opts
293
  if f.get('default') is True:
294
  entry['default'] = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  # C3 (wave 25): the profile flag rides the CREATE path too, and the one-per-table law
296
  # holds inside a single list. ⚠ This validator and `_clean_field` are two doors onto one
297
  # contract (a pre-existing split β€” `create`/`set_fields` come through here, `add_field`/
@@ -874,6 +904,31 @@ def _clean_field(raw, previous=None):
874
  out['rollup'] = rl
875
  elif ftype == 'rollup':
876
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  return out
878
 
879
 
 
79
  #: materialised into the row, because a rollup reads ANOTHER TABLE'S ROWS β€” data the client has
80
  #: not loaded and must not have to. `formula` stayed out of this list because it computes
81
  #: client-side over one row; that argument does not reach these two.
82
+ #: β›” `image` WAS MISSING FROM THIS SET UNTIL WAVE 27, AND THAT WAS A LIVE DEFECT β€” recorded
83
+ #: here because the shape repeats and the next kind will be added by somebody reading this line.
84
+ #: Wave-19 R7 landed `image` on FOUR of the five surfaces (the `FieldType` union, `CREATABLE_TYPES`,
85
+ #: `aios_grid.CUSTOM_FIELD_TYPES`, the shape/label tables) and missed this one. The client
86
+ #: therefore offered an Image column in EVERY column menu, including on `ut_*` databases, while
87
+ #: `_clean_field` returned None for it β€” so on a user database the column was created, named,
88
+ #: configured, and GONE on the next read, with nothing anywhere going red. It survived three
89
+ #: waves because `verify_fields_contract` diffed the client's offer against the ODOO grid's
90
+ #: acceptance and never against this set. Wave-27 item 13 adds that derived leg, which is what
91
+ #: found it (measured, not reviewed: `_clean_field({'type':'image'})` returned None).
92
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
93
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
94
+ 'link', 'rollup', 'code', 'image'}
95
  #: A cell is still a scalar on the wire (`Row` values are strings/numbers) β€” what this bounds is
96
  #: the DOCUMENT inside it. Source data is one already-paid provider response; keep it whole so a
97
  #: provider field is never silently discarded merely because the response is rich. 32 MiB matches
 
302
  entry['options'] = opts
303
  if f.get('default') is True:
304
  entry['default'] = True
305
+ # ⭐ WAVE-27 item 19 (R15) + D-80 β€” THE PRIMARY COLUMN, CARRIED THROUGH THE CREATE DOOR.
306
+ #
307
+ # `_clean_field` has honoured `pinned` since 2026-08-07; THIS door silently dropped it,
308
+ # and the split the comment below names is why. It did not matter while `create()` minted
309
+ # one column β€” with nothing pinned, `fields.find(f => f.pinned) ?? fields[0]` made the
310
+ # only column the primary either way. R15 seeds FOUR at once, so "whichever came first"
311
+ # stops being a coincidence that happens to be right, and D-80 is the register entry for
312
+ # exactly that fallback quietly being the whole rule. MEASURED before fixing:
313
+ # `clean_fields([{...'pinned': True}])` returned the field without the key.
314
+ if f.get('pinned') is True:
315
+ entry['pinned'] = True
316
+ # ⭐ WAVE-27 item 13 β€” the code language, for the same reason: a `code` column created
317
+ # through THIS door would otherwise arrive without the bag `_clean_field` preserves, and
318
+ # a column whose language depends on which door made it is the divergence the note below
319
+ # warns about, arriving through a different key.
320
+ if ftype == 'code' and f.get('code') is not None:
321
+ import aios_grid as _agc
322
+ c = _agc._clean_code(f.get('code'))
323
+ if c:
324
+ entry['code'] = c
325
  # C3 (wave 25): the profile flag rides the CREATE path too, and the one-per-table law
326
  # holds inside a single list. ⚠ This validator and `_clean_field` are two doors onto one
327
  # contract (a pre-existing split β€” `create`/`set_fields` come through here, `add_field`/
 
904
  out['rollup'] = rl
905
  elif ftype == 'rollup':
906
  return None
907
+ # ⭐ WAVE-27 item 13 (owner ruling R13) β€” the `code` column's language bag.
908
+ #
909
+ # ⚠ Deliberately the WEAKEST posture of the four bags above, and the asymmetry is the whole
910
+ # point rather than an inconsistency. `metric`/`link`/`rollup` bags DEFINE what their column
911
+ # is: without one the cell can never resolve a value, so a missing or mis-shaped bag refuses
912
+ # the field. A `language` chooses a HIGHLIGHTER over a string the column already holds
913
+ # perfectly well β€” so it is optional (an unconfigured code column renders plain), it survives
914
+ # a patch that omits it (the `automation` rule: the gear owns it, a header rename must not
915
+ # clear it), and an unknown language degrades to `plain` instead of destroying the column.
916
+ # R13's "NO execution engine" is why this can be so relaxed: the value selects a renderer and
917
+ # can never select an interpreter.
918
+ # ⚠ Function-local import, the convention `grid_events` already uses for the same module
919
+ # (`import aios_grid as _ag2`, five call sites): `core` must not import the layer above it at
920
+ # MODULE level. One vocabulary, one validator β€” declaring the language list a second time
921
+ # here is exactly the drift the fields contract exists to catch.
922
+ # ⚠ OMIT = KEEP, `plain` = CLEAR. `_clean_code` returns None for plain (see its docstring),
923
+ # so an explicit `{'language': 'plain'}` from the editor drops the key here while a patch
924
+ # that never mentions `code` inherits the previous bag. Without that split, switching a
925
+ # column back to Plain text would be a control that silently does not save.
926
+ code_raw = raw.get('code') if 'code' in raw else prev.get('code')
927
+ if code_raw is not None and ftype == 'code':
928
+ import aios_grid as _agc
929
+ c = _agc._clean_code(code_raw)
930
+ if c:
931
+ out['code'] = c
932
  return out
933
 
934
 
web/src/alerts/AlertsPane.tsx CHANGED
@@ -23,11 +23,14 @@ import {
23
  EMPTY_INBOX,
24
  applyRead,
25
  inboxOrder,
 
26
  isAutomationReview,
27
  routeForTopic,
28
  stampText,
29
  } from "./alertsModel";
30
  import type { Alert, Inbox, Notification } from "./alertsModel";
 
 
31
 
32
  /** The clock face this pane uses for its one glyph β€” drawn, never an emoji. */
33
  function BellIcon() {
@@ -142,6 +145,15 @@ export default function AlertsPane({
142
  onClose();
143
  return;
144
  }
 
 
 
 
 
 
 
 
 
145
  // A route this client cannot resolve opens NOTHING and says so β€” alerts
146
  // outlive the surfaces they were made from.
147
  if (!routeForTopic(n.topic)) {
@@ -198,12 +210,33 @@ export default function AlertsPane({
198
  // "Open the alert's view" over a review notification described a journey
199
  // the click does not take.
200
  title={
201
- isAutomationReview(n)
202
  ? "Open the automation"
203
  : `Open ${n.alertLabel || "the alert's view"}`
204
  }
205
  >
206
- <span className="alerts-row-label">{n.label}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  <span className="alerts-row-meta">
208
  {n.alertLabel ? `${n.alertLabel} Β· ` : ""}
209
  {/* Readable, but never re-derived: `stampText` is string surgery
 
23
  EMPTY_INBOX,
24
  applyRead,
25
  inboxOrder,
26
+ isAutomationOutcome,
27
  isAutomationReview,
28
  routeForTopic,
29
  stampText,
30
  } from "./alertsModel";
31
  import type { Alert, Inbox, Notification } from "./alertsModel";
32
+ // WAVE 27 C5 β€” the ONE generated loop mark, consumed rather than redrawn (C7's rule).
33
+ import { Mark } from "../shell/Brand";
34
 
35
  /** The clock face this pane uses for its one glyph β€” drawn, never an emoji. */
36
  function BellIcon() {
 
145
  onClose();
146
  return;
147
  }
148
+ // ⭐ WAVE 27 C5 β€” a RUN OUTCOME routes to its automation too, and it carries the id in
149
+ // `alertId` rather than `autoId` (`core.alerts.notify`'s shape, not `_queue_review`'s).
150
+ // Beside the review branch and after it: a review notification satisfies BOTH predicates,
151
+ // and only the review one knows about the stage to scroll to.
152
+ if (isAutomationOutcome(n)) {
153
+ onOpenAutomation(n.alertId, undefined);
154
+ onClose();
155
+ return;
156
+ }
157
  // A route this client cannot resolve opens NOTHING and says so β€” alerts
158
  // outlive the surfaces they were made from.
159
  if (!routeForTopic(n.topic)) {
 
210
  // "Open the alert's view" over a review notification described a journey
211
  // the click does not take.
212
  title={
213
+ isAutomationReview(n) || isAutomationOutcome(n)
214
  ? "Open the automation"
215
  : `Open ${n.alertLabel || "the alert's view"}`
216
  }
217
  >
218
+ {/* ⭐ WAVE 27 C5 β€” an automation's row wears the LOOP MARK.
219
+ β›” NOT A STATUS DOT, and not a second one: wave-26 R14 deleted every
220
+ status dot in the automation module on the grounds that *"these
221
+ automations are basically loops"*, and a run that FAILED is already said
222
+ in `n.label` (the run summary) in words. A coloured dot here would
223
+ reintroduce, in the inbox, the vocabulary that was deleted from the
224
+ surface it points at.
225
+ β›” The generated `Mark`, never a redrawn path: `shell/Brand.tsx`'s header
226
+ records a hand-copied version silently painting LAST WAVE'S BRAND while
227
+ a comment claimed parity. */}
228
+ <span className="alerts-row-label">
229
+ {isAutomationOutcome(n) || isAutomationReview(n) ? (
230
+ // ⚠ INSIDE the label span, not beside it. `.alerts-row-main` is a flex
231
+ // COLUMN, so a sibling here becomes a third ROW stacked above the text
232
+ // ([[wrong-parent-not-broken-control]]); inline, it sits on the line it
233
+ // annotates and rides the same ellipsis.
234
+ <span className="alerts-row-mark">
235
+ <Mark size={12} />
236
+ </span>
237
+ ) : null}
238
+ {n.label}
239
+ </span>
240
  <span className="alerts-row-meta">
241
  {n.alertLabel ? `${n.alertLabel} Β· ` : ""}
242
  {/* Readable, but never re-derived: `stampText` is string surgery
web/src/alerts/alertsModel.ts CHANGED
@@ -183,6 +183,31 @@ export function isAutomationReview(n: Notification): boolean {
183
  return n.kind === AUTOMATION_REVIEW_KIND && !!str(n.autoId).trim();
184
  }
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  /** Newest first, and unread before read at the same instant β€” the inbox order.
187
  * Stable: two notifications from one write keep the server's order. */
188
  export function inboxOrder(items: Notification[]): Notification[] {
 
183
  return n.kind === AUTOMATION_REVIEW_KIND && !!str(n.autoId).trim();
184
  }
185
 
186
+ /** WAVE 27 C5 β€” the topic an automation RUN OUTCOME arrives under (`core.alerts.notify`'s
187
+ * default). One place, for the same reason `AUTOMATION_REVIEW_KIND` is one place. */
188
+ export const AUTOMATION_TOPIC = "automation";
189
+
190
+ /**
191
+ * ⭐ WAVE 27 Β· CONTRACT C5 β€” did an automation RUN produce this, rather than a view?
192
+ *
193
+ * β›” A SECOND AUTOMATION SHAPE, AND IT IS NOT THE REVIEW ONE. `isAutomationReview` reads
194
+ * `kind` + `autoId`, which is what `_queue_review` writes. `core.alerts.notify()` β€” the door
195
+ * `_commit_run` uses for "this run succeeded / this run failed" (I7) β€” writes NEITHER: it puts
196
+ * the producer's key in `alertId`, leaves `viewId` empty, sets no `kind` at all, and identifies
197
+ * itself by `topic`. Two producers, two shapes, one inbox.
198
+ *
199
+ * ⚠ WITHOUT THIS the row falls to the view branch, `routeForTopic('automation')` answers null,
200
+ * and clicking a run outcome says *"That alert's table is no longer available to this account"*
201
+ * β€” a confidently wrong sentence about a feature that is working, which is the exact defect
202
+ * `isAutomationReview`'s own header records from wave 23. The shape changed; the trap did not.
203
+ *
204
+ * β›” `alertId` IS REQUIRED, same fail-closed direction as the review predicate: a run outcome
205
+ * whose automation id never arrived would otherwise dispatch an open request naming nothing.
206
+ */
207
+ export function isAutomationOutcome(n: Notification): boolean {
208
+ return str(n.topic).trim() === AUTOMATION_TOPIC && !!str(n.alertId).trim();
209
+ }
210
+
211
  /** Newest first, and unread before read at the same instant β€” the inbox order.
212
  * Stable: two notifications from one write keep the server's order. */
213
  export function inboxOrder(items: Notification[]): Notification[] {
web/src/automation/AutomationBuilder.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/automation/AutomationDetail.tsx CHANGED
@@ -20,9 +20,9 @@
20
  // ([[no-unverifiable-aggregates]]) β€” a number with no way back to its records is
21
  // what this codebase treats as a defect rather than a summary.
22
  // ---------------------------------------------------------------------------
23
- import { useCallback, useEffect, useState } from "react";
24
-
25
- import AutomationBuilder from "./AutomationBuilder";
26
  import AutomationFind from "./AutomationFind";
27
  import AutomationTrigger from "./AutomationTrigger";
28
  import type {
@@ -49,7 +49,7 @@ import {
49
  deleteAutomation,
50
  discoverEstimate,
51
  fieldKeyFor,
52
- listTables,
53
  oauthStatus,
54
  patchAutomation,
55
  previewSource,
@@ -178,13 +178,13 @@ export default function AutomationDetail({
178
  const [saving, setSaving] = useState(false);
179
  const [touched, setTouched] = useState(false);
180
  const [triggerBusy, setTriggerBusy] = useState(false);
181
- const [oauth, setOauth] = useState<OAuthStatus | null>(null);
182
  /**
183
  * ⚠ "SHOW ME THE CRON" IS A VIEW CHOICE, NOT A SCHEDULE CHANGE β€” and forgetting that once
184
  * made the Custom option DEAD. Everything else on the trigger face is derived from the
185
  * stored cron, so picking "Custom (cron)" wrote… the same cron, which `readCron` read back
186
  * as "every Wednesday" and the select snapped straight back. It lives HERE, above the two
187
- * builder controls does not lose it.
188
  */
189
  const [showCron, setShowCron] = useState(false);
190
 
@@ -255,6 +255,45 @@ export default function AutomationDetail({
255
  const [drill, setDrill] = useState<RunRows | null>(null);
256
  const [drillFor, setDrillFor] = useState("");
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  useEffect(() => {
259
  const ac = new AbortController();
260
  listTables(ac.signal)
@@ -427,9 +466,19 @@ export default function AutomationDetail({
427
  * filter with the row still on screen and not a word anywhere. Holding a half-written row back
428
  * is a courtesy; holding it back in silence is the drop class this module refuses everywhere.
429
  */
 
 
 
 
 
 
 
 
 
 
 
430
  const heldNote = (): string => {
431
- if (kind !== "discover_instagram") return "";
432
- const held = preds.length - completePreds().length;
433
  if (held < 1) return "";
434
  return `Saved β€” ${held} condition${held === 1 ? " was" : "s were"} not saved yet, `
435
  + `${held === 1 ? "it needs" : "they need"} a value.`;
@@ -518,9 +567,9 @@ export default function AutomationDetail({
518
  config: buildConfig(),
519
  schedule: { cron: next.cron, enabled: next.enabled },
520
  });
521
- setTouched(false);
522
- setMessage(heldNote());
523
- await onSaved(automation.id);
524
  } catch (e) {
525
  setProblem(e instanceof AutomationError ? e.message : "That schedule was not saved.");
526
  } finally {
@@ -555,9 +604,9 @@ export default function AutomationDetail({
555
  trigger: { key },
556
  schedule: { cron, enabled: key === "schedule" },
557
  });
558
- setTouched(false);
559
- setMessage(heldNote());
560
- await onSaved(automation.id);
561
  } catch (e) {
562
  setProblem(e instanceof AutomationError ? e.message : "That trigger was not saved.");
563
  } finally {
@@ -584,9 +633,9 @@ export default function AutomationDetail({
584
  setSaving(true);
585
  setProblem("");
586
  setMessage("");
587
- try {
588
- const id = await persist();
589
- await onSaved(id);
590
  } catch (e) {
591
  setProblem(e instanceof AutomationError ? e.message : "That could not be saved.");
592
  } finally {
@@ -599,23 +648,58 @@ export default function AutomationDetail({
599
  * switch. Unsaved panel edits are persisted FIRST rather than being discarded
600
  * by the reload that follows, which is the one way this could lose work.
601
  */
602
- const flip = async (nodeId: string) => {
603
- setProblem("");
604
  setMessage("");
605
  try {
606
- if (touched) await persist(false);
607
- await toggleNode(automation.id, nodeId);
608
- await onSaved(automation.id);
609
- } catch (e) {
610
- setProblem(e instanceof AutomationError ? e.message : "That step was not changed.");
611
- }
612
- };
613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  const start = async () => {
615
  setProblem("");
616
  try {
 
617
  await runAutomation(automation.id);
618
- setMessage("Started. The node dots follow it.");
 
 
 
 
 
 
619
  await onSaved(automation.id);
620
  } catch (e) {
621
  setProblem(e instanceof AutomationError ? e.message : "It did not start.");
@@ -690,9 +774,9 @@ export default function AutomationDetail({
690
  setTriggerBusy(true);
691
  setProblem("");
692
  setMessage("");
693
- try {
694
- await patchAutomation(automation.id, body);
695
- await onSaved(automation.id);
696
  } catch (e) {
697
  // β›” THE SERVER'S SENTENCE, VERBATIM. `clean_flow` refuses an empty group, an unready
698
  // action kind, a valueless compare β€” each with a reason worth reading. A client that
@@ -1082,7 +1166,7 @@ export default function AutomationDetail({
1082
  on that point and the consequence (no name in the Board view) is booked, not patched.
1083
  */}
1084
  <div className="auto-head-title">
1085
- <span className="autox-view is-on">Builder</span>
1086
  </div>
1087
  <div className="auto-head-actions">
1088
  {/*
@@ -1157,7 +1241,7 @@ export default function AutomationDetail({
1157
  engine's own steps AND what the owner added, from data the rail already had) and there
1158
  is no longer a state in which the reader gets it by accident.
1159
  */}
1160
- <>
1161
  <AutomationBuilder
1162
  automation={automation}
1163
  // ITEM 15b β€” the name left the header, and this is where it went. Three REQUIRED
@@ -1212,11 +1296,24 @@ export default function AutomationDetail({
1212
  // ONE cron round-trip, rendered inside the Properties panel with its own picker
1213
  // suppressed β€” the builder supplies the "Trigger type" select above it.
1214
  scheduleFace={scheduleFace}
1215
- />
1216
- <aside className="auto-panel" aria-label="Run log">
1217
- <>
 
 
 
 
 
 
 
 
 
 
 
 
 
1218
  <div className="auto-panel-head">
1219
- <h2>Log</h2>
1220
  </div>
1221
  {!automation.runs?.length ? (
1222
  <p className="auto-note">
@@ -1280,13 +1377,13 @@ export default function AutomationDetail({
1280
  </li>
1281
  ))}
1282
  </ol>
1283
- )}
1284
- <p className="auto-hint">
1285
- Open a run to inspect the records it touched.
1286
- </p>
1287
- </>
1288
- </aside>
1289
- </>
1290
  </div>
1291
  </div>
1292
  );
 
20
  // ([[no-unverifiable-aggregates]]) β€” a number with no way back to its records is
21
  // what this codebase treats as a defect rather than a summary.
22
  // ---------------------------------------------------------------------------
23
+ import { useCallback, useEffect, useState } from "react";
24
+
25
+ import AutomationBuilder from "./AutomationBuilder";
26
  import AutomationFind from "./AutomationFind";
27
  import AutomationTrigger from "./AutomationTrigger";
28
  import type {
 
49
  deleteAutomation,
50
  discoverEstimate,
51
  fieldKeyFor,
52
+ listTables,
53
  oauthStatus,
54
  patchAutomation,
55
  previewSource,
 
178
  const [saving, setSaving] = useState(false);
179
  const [touched, setTouched] = useState(false);
180
  const [triggerBusy, setTriggerBusy] = useState(false);
181
+ const [oauth, setOauth] = useState<OAuthStatus | null>(null);
182
  /**
183
  * ⚠ "SHOW ME THE CRON" IS A VIEW CHOICE, NOT A SCHEDULE CHANGE β€” and forgetting that once
184
  * made the Custom option DEAD. Everything else on the trigger face is derived from the
185
  * stored cron, so picking "Custom (cron)" wrote… the same cron, which `readCron` read back
186
  * as "every Wednesday" and the select snapped straight back. It lives HERE, above the two
187
+ * builder controls does not lose it.
188
  */
189
  const [showCron, setShowCron] = useState(false);
190
 
 
255
  const [drill, setDrill] = useState<RunRows | null>(null);
256
  const [drillFor, setDrillFor] = useState("");
257
 
258
+ /**
259
+ * ⭐ WAVE 27 Β· OWNER ITEM 33 / CONTRACT C11 β€” WHICH PANEL OWNS THE RIGHT-HAND COLUMN.
260
+ *
261
+ * β›” THE STATE IS HERE BECAUSE THE TWO PANELS ARE NOT SIBLINGS IN ONE FILE. Properties is
262
+ * rendered by `AutomationBuilder`; the Run log is rendered below by this component. Both are
263
+ * `.auto-panel` children of `.auto-work`, so they were drawn SIDE BY SIDE β€” two 380px columns
264
+ * on a surface whose actual content is the flow. The reference (`reference/Airtable
265
+ * Automation 11.png`) shows one dismissable panel, and the only component that can guarantee
266
+ * "exactly one" is the parent of both.
267
+ *
268
+ * ⚠ PROPERTIES IS THE DEFAULT, not the log. Opening an automation to read last night's run is
269
+ * the rarer errand; opening it to change something is the common one, and the panel that
270
+ * appears should be the one a click on a step is about to fill.
271
+ */
272
+ const [aside, setAside] = useState<"properties" | "runs">("properties");
273
+ /**
274
+ * The switch, drawn in BOTH panel heads so it does not move when the panel does.
275
+ *
276
+ * β›” A RADIOGROUP, not two buttons that happen to look joined: they are two values of one
277
+ * setting, and `aria-pressed` on each would tell a screen reader about two independent
278
+ * toggles that can both be off β€” a state this control cannot express.
279
+ */
280
+ const panelTabs = (
281
+ <div className="auto-paneltabs" role="radiogroup" aria-label="Right-hand panel">
282
+ {([["properties", "Properties"], ["runs", "Run history"]] as const).map(([k, label]) => (
283
+ <button
284
+ key={k}
285
+ type="button"
286
+ role="radio"
287
+ aria-checked={aside === k}
288
+ className={"auto-paneltab" + (aside === k ? " is-on" : "")}
289
+ onClick={() => setAside(k)}
290
+ >
291
+ {label}
292
+ </button>
293
+ ))}
294
+ </div>
295
+ );
296
+
297
  useEffect(() => {
298
  const ac = new AbortController();
299
  listTables(ac.signal)
 
466
  * filter with the row still on screen and not a word anywhere. Holding a half-written row back
467
  * is a courtesy; holding it back in silence is the drop class this module refuses everywhere.
468
  */
469
+ /**
470
+ * ⭐ WAVE 27 (item 11) β€” the COUNT, split out of the sentence below.
471
+ *
472
+ * `start()` has to say the same fact in a different sentence ("it is running without it"),
473
+ * and the alternative was for it to read `heldNote()`'s prose and sniff it for a plural β€”
474
+ * a second reader of a string that exists to be shown to a person. One arithmetic, two
475
+ * wordings, and neither wording is parsed by anything.
476
+ */
477
+ const heldCount = (): number =>
478
+ kind === "discover_instagram" ? preds.length - completePreds().length : 0;
479
+
480
  const heldNote = (): string => {
481
+ const held = heldCount();
 
482
  if (held < 1) return "";
483
  return `Saved β€” ${held} condition${held === 1 ? " was" : "s were"} not saved yet, `
484
  + `${held === 1 ? "it needs" : "they need"} a value.`;
 
567
  config: buildConfig(),
568
  schedule: { cron: next.cron, enabled: next.enabled },
569
  });
570
+ setTouched(false);
571
+ setMessage(heldNote());
572
+ await onSaved(automation.id);
573
  } catch (e) {
574
  setProblem(e instanceof AutomationError ? e.message : "That schedule was not saved.");
575
  } finally {
 
604
  trigger: { key },
605
  schedule: { cron, enabled: key === "schedule" },
606
  });
607
+ setTouched(false);
608
+ setMessage(heldNote());
609
+ await onSaved(automation.id);
610
  } catch (e) {
611
  setProblem(e instanceof AutomationError ? e.message : "That trigger was not saved.");
612
  } finally {
 
633
  setSaving(true);
634
  setProblem("");
635
  setMessage("");
636
+ try {
637
+ const id = await persist();
638
+ await onSaved(id);
639
  } catch (e) {
640
  setProblem(e instanceof AutomationError ? e.message : "That could not be saved.");
641
  } finally {
 
648
  * switch. Unsaved panel edits are persisted FIRST rather than being discarded
649
  * by the reload that follows, which is the one way this could lose work.
650
  */
651
+ const flip = async (nodeId: string) => {
652
+ setProblem("");
653
  setMessage("");
654
  try {
655
+ if (touched) await persist(false);
656
+ await toggleNode(automation.id, nodeId);
657
+ await onSaved(automation.id);
658
+ } catch (e) {
659
+ setProblem(e instanceof AutomationError ? e.message : "That step was not changed.");
660
+ }
661
+ };
662
 
663
+ /**
664
+ * ⭐ WAVE 27 Β· OWNER ITEM 11 β€” **RUN NOW WRITES WHAT IS ON SCREEN.**
665
+ *
666
+ * β›” THE DEFECT, in the owner's words: *"I have to save twice"*. Every trigger-side control
667
+ * this panel owns β€” the discovery conditions (`preds`), the record limit, the and/or join,
668
+ * `maxPosts` β€” lives in LOCAL STATE until something calls `persist()`. `start()` called
669
+ * `runAutomation` directly, so pressing Run after editing a condition ran the automation
670
+ * against the config as it was BEFORE the edit, and the only tell was that pressing Save
671
+ * first made it behave. Two presses looked like a fussy UI; it was a run against stale
672
+ * config, and on a `discover_instagram` automation that is a PAID search of the wrong filter.
673
+ *
674
+ * ⚠ THE FIX IS `flip()`'s, VERBATIM (`:606`), and deliberately not a new discipline: a node
675
+ * switch already persisted unsaved panel edits before toggling, for exactly this reason, and
676
+ * the two buttons sit in the same header. `if (touched)` and not an unconditional PATCH β€”
677
+ * an untouched panel writing its config back would re-send `buildConfig()` on every Run,
678
+ * which is how a clamp or a validator default silently becomes a value the user never chose
679
+ * ([[default-must-pass-its-own-guard]]).
680
+ *
681
+ * ⚠ A FAILED FLUSH MUST NOT RUN. Both calls share one `try`, so a PATCH that 400s leaves the
682
+ * server's sentence on screen and `runAutomation` unreached β€” running anyway would spend
683
+ * money on precisely the config the server just refused.
684
+ *
685
+ * β›” AND THE HELD-BACK SENTENCE IS SAID HERE TOO. `persist(false)` suppresses `heldNote()`
686
+ * because `flip()` had nothing to add to it; this path does. `completePreds()` withholds a
687
+ * condition that has a comparison and no value yet, so a Run pressed mid-edit legitimately
688
+ * searches WITHOUT it β€” silence there would be the module's own drop class (see `heldNote`),
689
+ * and it is worse on this button than on any other because this one is the one that bills.
690
+ */
691
  const start = async () => {
692
  setProblem("");
693
  try {
694
+ if (touched) await persist(false);
695
  await runAutomation(automation.id);
696
+ const held = heldCount();
697
+ setMessage(
698
+ held < 1
699
+ ? "Started. The node dots follow it."
700
+ : `Started β€” running without ${held} condition${held === 1 ? "" : "s"} that still `
701
+ + `${held === 1 ? "needs" : "need"} a value.`
702
+ );
703
  await onSaved(automation.id);
704
  } catch (e) {
705
  setProblem(e instanceof AutomationError ? e.message : "It did not start.");
 
774
  setTriggerBusy(true);
775
  setProblem("");
776
  setMessage("");
777
+ try {
778
+ await patchAutomation(automation.id, body);
779
+ await onSaved(automation.id);
780
  } catch (e) {
781
  // β›” THE SERVER'S SENTENCE, VERBATIM. `clean_flow` refuses an empty group, an unready
782
  // action kind, a valueless compare β€” each with a reason worth reading. A client that
 
1166
  on that point and the consequence (no name in the Board view) is booked, not patched.
1167
  */}
1168
  <div className="auto-head-title">
1169
+ <span className="autox-view is-on">Builder</span>
1170
  </div>
1171
  <div className="auto-head-actions">
1172
  {/*
 
1241
  engine's own steps AND what the owner added, from data the rail already had) and there
1242
  is no longer a state in which the reader gets it by accident.
1243
  */}
1244
+ <>
1245
  <AutomationBuilder
1246
  automation={automation}
1247
  // ITEM 15b β€” the name left the header, and this is where it went. Three REQUIRED
 
1296
  // ONE cron round-trip, rendered inside the Properties panel with its own picker
1297
  // suppressed β€” the builder supplies the "Trigger type" select above it.
1298
  scheduleFace={scheduleFace}
1299
+ // ⭐ WAVE 27 Β· C11 β€” the panel switch and its state, both owned here.
1300
+ showProperties={aside === "properties"}
1301
+ panelTabs={panelTabs}
1302
+ onStepPicked={() => setAside("properties")}
1303
+ />
1304
+ {/* ⚠ THE RUN LOG IS UNMOUNTED WHEN HIDDEN, unlike Properties, and the asymmetry is
1305
+ deliberate rather than an oversight: this panel holds no editing state (its only
1306
+ local state, the drill-down, is this component's and survives), while re-mounting
1307
+ it re-reads nothing β€” the runs ride on `automation`. Properties keeps a half-typed
1308
+ name and cron, so hiding it has to leave it alive. */}
1309
+ <aside
1310
+ className="auto-panel is-appearing"
1311
+ aria-label="Run history"
1312
+ hidden={aside !== "runs"}
1313
+ >
1314
+ <>
1315
  <div className="auto-panel-head">
1316
+ {panelTabs}
1317
  </div>
1318
  {!automation.runs?.length ? (
1319
  <p className="auto-note">
 
1377
  </li>
1378
  ))}
1379
  </ol>
1380
+ )}
1381
+ <p className="auto-hint">
1382
+ Open a run to inspect the records it touched.
1383
+ </p>
1384
+ </>
1385
+ </aside>
1386
+ </>
1387
  </div>
1388
  </div>
1389
  );
web/src/automation/AutomationFind.tsx CHANGED
@@ -1,763 +1,893 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/AutomationFind.tsx β€” the discovery filter, as TOGGLES (owner item 6,
3
- // contract C4).
4
- //
5
- // WHAT CHANGED AND WHY. It was a condition BUILDER: an empty row, a field
6
- // dropdown listing 21 names, "Add a condition". That shape asks the user to
7
- // remember what is searchable before they can look, and it hid the only fact
8
- // that decides whether a search returns anything at all β€” which fields actually
9
- // carry values. The corpus is 620 million profiles and every run is billed, so
10
- // "I did not know I could filter on that" and "I filtered on a field that is
11
- // empty on every row" are both expensive mistakes made in silence.
12
- //
13
- // So every searchable field is ON SCREEN, off by default, and turning one on is
14
- // what creates its condition. The list leads with the fields MEASURED to carry
15
- // values; the rest are grouped under what is known about them, and neither group
16
- // is hidden β€” R3 already decided that "every filter" means the 21 we can stand
17
- // behind, so all 21 are visible.
18
- //
19
- // β›” THE VOCABULARY IS THE SERVER'S, ALL OF IT. Field names, operators, which
20
- // operators take no value, the record ceiling and (once C4 lands it) which
21
- // fields are populated and which narrow β€” every one of those rides on
22
- // `GET /automations`. This file holds no list of its own. The reason is the one
23
- // `automationApi.ts:11-15` gives for cron presets: the thing that ACCEPTS a
24
- // filter is Python, and a client copy of what it accepts is a copy that can
25
- // offer a search the server refuses.
26
- //
27
- // β›” AND IT DOES NOT RE-IMPLEMENT THE GUARD. `guard` carries the server's
28
- // numbers, so the rows can say which fields narrow β€” but the refusal is the
29
- // server's to make and this surface prints it VERBATIM when it comes back
30
- // (`DiscoverGuard`'s note). A client that predicts the refusal is a second copy
31
- // of the rule, free to disagree with the first, and when they disagree the user
32
- // gets a Save button that is disabled for a reason nobody can see.
33
- // ---------------------------------------------------------------------------
34
- import { useEffect, useState } from "react";
35
-
36
- import type {
37
- DiscoverEstimate,
38
- DiscoverFieldMeta,
39
- DiscoverOperator,
40
- DiscoverVocab,
41
- Predicate,
42
- } from "./automationApi";
43
- import { discoverCategories } from "./automationApi";
44
-
45
- interface Props {
46
- /** The server-declared discovery vocabulary (absent until the list loads). */
47
- discover?: DiscoverVocab;
48
- recordsLimit: number;
49
- onRecordsLimit: (n: number) => void;
50
- joinOp: string;
51
- onJoinOp: (v: string) => void;
52
- preds: Predicate[];
53
- onPreds: (next: Predicate[]) => void;
54
- estimate: DiscoverEstimate | null;
55
- onEstimate: () => void;
56
- }
57
-
58
- /**
59
- * A FILTER FIELD'S ICON (owner item 5). Drawn, `currentColor`, never an emoji β€” and in the
60
- * existing `TriggerMark`/`ActionMark` language rather than a new one: same 16 viewBox, same 15px
61
- * box, same 1.4 stroke, so a row here and a card in the builder read as one product.
62
- *
63
- * ⚠ SHARED SHAPES WHERE THE FIELDS SHARE A MEANING, distinct everywhere else. `TriggerMark`'s
64
- * note settled the principle β€” a column of identical glyphs is decoration, the eye learns nothing
65
- * β€” but its converse matters just as much here: `bio_hashtags` and `post_hashtags` ARE both
66
- * hashtags, and drawing two different marks for them would invent a distinction the vendor does
67
- * not make. Twenty-one contrived glyphs would be twenty-one things to misread.
68
- *
69
- * β›” THE FALLBACK IS NOT A MEMBER OF THE SET, which is the `ActionMark` scar exactly: its default
70
- * used to BE the pencil, a real member, so every unmatched kind silently borrowed "edit" and a
71
- * fallback could not be told from a match. The vocabulary is the SERVER's β€” it can grow a field
72
- * tomorrow β€” so an unmatched name draws a neutral mark that is deliberately meaningless.
73
- */
74
- function FilterMark({ name }: { name: string }) {
75
- const common = {
76
- width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
77
- strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
78
- "aria-hidden": true,
79
- };
80
- // Audience size β€” two figures, one behind the other.
81
- if (name === "followers")
82
- return (
83
- <svg {...common}>
84
- <circle cx="6.2" cy="5.6" r="2.4" />
85
- <path d="M2.2 13c.5-2 2.1-3.2 4-3.2s3.5 1.2 4 3.2" />
86
- <path d="M10.6 3.6a2.4 2.4 0 0 1 0 4M11.4 9.9c1.4.4 2.4 1.5 2.8 3.1" />
87
- </svg>
88
- );
89
- // Who this account follows β€” a figure with an outbound arrow.
90
- if (name === "following")
91
- return (
92
- <svg {...common}>
93
- <circle cx="6" cy="5.6" r="2.4" />
94
- <path d="M1.8 13c.5-2 2.1-3.2 4.2-3.2 .6 0 1.2.1 1.7.3" />
95
- <path d="M9.8 10.6h4.2M12.2 8.8l1.8 1.8-1.8 1.8" />
96
- </svg>
97
- );
98
- if (name === "posts_count")
99
- return (
100
- <svg {...common}>
101
- <rect x="2.6" y="2.6" width="4.6" height="4.6" rx="1" />
102
- <rect x="8.8" y="2.6" width="4.6" height="4.6" rx="1" />
103
- <rect x="2.6" y="8.8" width="4.6" height="4.6" rx="1" />
104
- <rect x="8.8" y="8.8" width="4.6" height="4.6" rx="1" />
105
- </svg>
106
- );
107
- // A story highlight β€” the ring Instagram draws around one.
108
- if (name === "highlights_count")
109
- return (
110
- <svg {...common}>
111
- <circle cx="8" cy="8" r="5.6" strokeDasharray="2.6 1.8" />
112
- <circle cx="8" cy="8" r="2.2" />
113
- </svg>
114
- );
115
- if (name === "avg_engagement")
116
- return (
117
- <svg {...common}>
118
- <path d="M8 13.2 3.4 8.8a2.9 2.9 0 0 1 4.6-3.4 2.9 2.9 0 0 1 4.6 3.4z" />
119
- </svg>
120
- );
121
- if (name === "biography")
122
- return (
123
- <svg {...common}>
124
- <rect x="2.4" y="2.8" width="11.2" height="10.4" rx="1.6" />
125
- <path d="M4.8 6h6.4M4.8 8.4h6.4M4.8 10.8h3.6" />
126
- </svg>
127
- );
128
- if (name === "category_name" || name === "business_category_name")
129
- return (
130
- <svg {...common}>
131
- <path d="M8.4 2.6H13v4.6l-6.2 6.2-4.6-4.6z" />
132
- <circle cx="10.8" cy="5.2" r="0.9" />
133
- </svg>
134
- );
135
- if (name === "is_business_account" || name === "is_professional_account")
136
- return (
137
- <svg {...common}>
138
- <rect x="2.2" y="5" width="11.6" height="8.2" rx="1.6" />
139
- <path d="M6 5V3.6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1V5" />
140
- </svg>
141
- );
142
- if (name === "is_verified")
143
- return (
144
- <svg {...common}>
145
- <path d="M8 2.2l1.7 1.2 2-.2.6 2 1.7 1.1-.9 1.9.9 1.9-1.7 1.1-.6 2-2-.2L8 14.2l-1.7-1.2-2 .2-.6-2L2 10.1l.9-1.9L2 6.3l1.7-1.1.6-2 2 .2z" />
146
- <path d="m5.8 8.1 1.5 1.5 3-3.1" />
147
- </svg>
148
- );
149
- // The handle, and the display name it is written under.
150
- if (name === "account" || name === "profile_name")
151
- return (
152
- <svg {...common}>
153
- <circle cx="8" cy="8" r="2.4" />
154
- <path d="M10.4 5.6v3.2a1.9 1.9 0 0 0 3.2 1.3A5.8 5.8 0 1 0 11 13.1" />
155
- </svg>
156
- );
157
- if (name === "full_name")
158
- return (
159
- <svg {...common}>
160
- <circle cx="8" cy="5.6" r="2.6" />
161
- <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
162
- </svg>
163
- );
164
- if (name === "external_url" || name === "profile_url")
165
- return (
166
- <svg {...common}>
167
- <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
168
- <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
169
- <path d="M6.2 8h3.6" />
170
- </svg>
171
- );
172
- if (name === "bio_hashtags" || name === "post_hashtags")
173
- return (
174
- <svg {...common}>
175
- <path d="M6.2 2.8 4.8 13.2M11.2 2.8 9.8 13.2M2.8 6h10.4M2.2 10h10.4" />
176
- </svg>
177
- );
178
- if (name === "related_accounts")
179
- return (
180
- <svg {...common}>
181
- <circle cx="8" cy="3.6" r="1.8" />
182
- <circle cx="3.6" cy="12" r="1.8" />
183
- <circle cx="12.4" cy="12" r="1.8" />
184
- <path d="M6.8 5.2 4.6 10.4M9.2 5.2l2.2 5.2M5.4 12h5.2" />
185
- </svg>
186
- );
187
- // The vendor's own record keys β€” the thing you hold to open exactly one row.
188
- if (name === "id" || name === "fbid")
189
- return (
190
- <svg {...common}>
191
- <circle cx="5.4" cy="10.6" r="2.6" />
192
- <path d="M7.2 8.8 13 3M10.6 5.4l1.6 1.6M9.2 6.8l1.6 1.6" />
193
- </svg>
194
- );
195
- return (
196
- <svg {...common}>
197
- <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
198
- <circle cx="8" cy="8" r="1.4" />
199
- </svg>
200
- );
201
- }
202
-
203
- /** One field's line in the list, with everything known about it. */
204
- interface FieldRow {
205
- name: string;
206
- /** What the row is CALLED. Falls back to the raw name only if the server sent none. */
207
- label: string;
208
- hint: string;
209
- kind: string;
210
- operators: DiscoverOperator[];
211
- options: { value: string; label: string }[];
212
- /** Every stored condition naming this field, with its index in the saved array. */
213
- at: number[];
214
- /** MEASURED to carry values. `null` = the server has not said (C4 not shipped yet). */
215
- populated: boolean | null;
216
- /** A condition here cuts the corpus down. `null` = not said. */
217
- narrowing: boolean | null;
218
- }
219
-
220
- /** A stored value β†’ what the text box shows. A list is the "any of" shape. */
221
- function valueText(v: Predicate["value"]): string {
222
- if (Array.isArray(v)) return v.join(", ");
223
- return v === undefined || v === null ? "" : String(v);
224
- }
225
-
226
- /**
227
- * What the user typed β†’ what is stored. Comma-separated becomes a LIST for the operators that
228
- * accept one, and stays a plain string for the ones that do not.
229
- *
230
- * ⚠ A single value stays a SCALAR rather than a one-element list β€” the server sends scalars
231
- * flat and lists as a nested OR group, and a one-element group is a shape nothing has been
232
- * billed against.
233
- */
234
- function parseValue(text: string, multi: boolean): Predicate["value"] {
235
- if (!multi) return text;
236
- const parts = text.split(",").map((s) => s.trim()).filter(Boolean);
237
- if (parts.length > 1) return parts;
238
- // Keep the RAW text while it is still being typed β€” trimming here would fight the cursor on
239
- // every keystroke, and the server trims anyway.
240
- return text;
241
- }
242
-
243
- /**
244
- * ⭐ WAVE 26 Β· DEBT D-69 β€” A THIRD VALUE COULD NOT BE TYPED, and the cause was one round trip
245
- * through this pair of functions.
246
- *
247
- * `parseValue` returns an ARRAY at 2+ values; `valueText` then renders that array as
248
- * `join(", ")` β€” which has NO TRAILING COMMA. So on a controlled input the separator was
249
- * normalised away between keystrokes: typing `,` onto `skincare, beauty` re-rendered as
250
- * `skincare, beauty`, and the next character landed as `skincare, beautym`. Two keywords
251
- * silently became one that matches nothing. ⚠ It hit the FIRST surface a new user meets (wave 24
252
- * made this panel the only door) and it hit precisely the 3+ keyword list the feature was built
253
- * for β€” the owner's *"if i want to include many keywords like floral, flower, beauty"*.
254
- *
255
- * β›” THE FIX IS THE ONE `parseValue`'s OWN COMMENT ALREADY DESCRIBES FOR THE 1-VALUE CASE:
256
- * keep the raw text while it is being typed. That comment was right and its scope was too narrow
257
- * β€” it protected the cursor at one value and handed the 2+ case to `join`. So the raw text is
258
- * held for whichever input is FOCUSED, and the stored value is still parsed on every keystroke
259
- * (so nothing depends on blur to save) and re-parsed on blur (so the display settles).
260
- *
261
- * ⚠ KEYED BY THE ROW'S REACT KEY, not by index alone: two conditions on the same field are
262
- * ordinary here ("Another condition on Bio"), and an index-only key would leak one row's draft
263
- * into its sibling on a removal.
264
- */
265
- interface Draft {
266
- key: string;
267
- text: string;
268
- }
269
-
270
- /**
271
- * The comparison a freshly toggled field starts with β€” ASKED FOR, never chosen here.
272
- *
273
- * β›” THE THIRD COSTUME OF ONE SCAR, and the reason this function no longer has an opinion.
274
- * Wave 21 made a new condition NULLARY (`is_not_null`) so it would be saveable without a
275
- * value, and called that "narrowing-in-the-right-direction". Wave 22 then wrote the narrowing
276
- * law server-side and `is_not_null` is not in it. From that moment, toggling ANY field on and
277
- * pressing Save returned "add at least one CONTENT condition…" β€” the error told the user to do
278
- * the exact thing they had just done. Wave 24 deleted the wizard and made this panel the only
279
- * door, so it stopped being a corner case and became the first thing a new user hits.
280
- *
281
- * The fix is not a better guess. It is that the module owning the guard also names the default
282
- * (`automation_engine.default_operator`, asserted against `predicate_narrows` in
283
- * `verify_automation.py`), and this file looks it up per FIELD. An absent one falls back to the
284
- * server's first operator β€” never to a nullary, which is the thing that could not narrow.
285
- */
286
- function firstOperator(v: DiscoverVocab | undefined, name: string): string {
287
- const meta = (v?.filterMeta || []).find((m) => m.name === name);
288
- return meta?.defaultOperator || (v?.operators || [])[0] || "";
289
- }
290
-
291
- /**
292
- * The rows, ordered: measured-populated first, then the rest.
293
- *
294
- * TWO SOURCES, AND THE FALLBACK IS NARROWER THAN THE REAL THING. With C4's
295
- * `filterMeta` the answer is per field and complete. Without it, `lead` names
296
- * the three fields seen carrying values and says NOTHING about the other
297
- * eighteen β€” so those come back `null`, not `false`, and the UI prints no claim
298
- * about them rather than an invented one.
299
- */
300
- function buildRows(preds: Predicate[], v?: DiscoverVocab): FieldRow[] {
301
- const meta = new Map<string, DiscoverFieldMeta>(
302
- (v?.filterMeta || []).map((m) => [m.name, m])
303
- );
304
- const lead = new Set(v?.lead || []);
305
- const byName = new Map<string, number[]>();
306
- preds.forEach((p, i) => {
307
- const list = byName.get(p.name);
308
- if (list) list.push(i);
309
- else byName.set(p.name, [i]);
310
- });
311
-
312
- const rows = (v?.fields || []).map((name) => {
313
- const m = meta.get(name);
314
- return {
315
- name,
316
- label: m?.label || name,
317
- hint: m?.hint || "",
318
- kind: m?.kind || "text",
319
- // β›” NO FALLBACK TO THE GLOBAL OPERATOR LIST. An older server that sends no per-field list
320
- // gets a row with no comparisons rather than all fourteen on every field β€” visibly
321
- // unfinished beats quietly offering `at least` on a yes/no column.
322
- operators: m?.operators || [],
323
- options: m?.options || [],
324
- at: byName.get(name) || [],
325
- populated: m ? !!m.populated : lead.has(name) ? true : null,
326
- narrowing: m ? !!m.narrowing : null,
327
- };
328
- });
329
- // Stable partition, never a sort: the server's order inside each half is the
330
- // order the engine lists them in, and re-alphabetising it would be this file
331
- // having an opinion about a server list.
332
- return [...rows.filter((r) => r.populated === true), ...rows.filter((r) => r.populated !== true)];
333
- }
334
-
335
- export default function AutomationFind({
336
- discover,
337
- recordsLimit,
338
- onRecordsLimit,
339
- joinOp,
340
- onJoinOp,
341
- preds,
342
- onPreds,
343
- estimate,
344
- onEstimate,
345
- }: Props) {
346
- const rows = buildRows(preds, discover);
347
- const known = new Set(discover?.fields || []);
348
- // The GLOBAL operator list is gone from this component: comparisons are per field now
349
- // (`row.operators`). `nullary` survives for STRAYS only β€” a stored condition on a field the
350
- // vendor dropped has no per-field row to read from, and it still has to render to be removable.
351
- const nullary = new Set(discover?.nullaryOperators || []);
352
- const withValues = rows.filter((r) => r.populated === true);
353
- const rest = rows.filter((r) => r.populated !== true);
354
- const knownMeta = !!(discover?.filterMeta || []).length;
355
- // ⚠ THE STORED FILTER CAN NAME A FIELD THE LIST NO LONGER HAS β€” a vocabulary
356
- // that moved, an automation copied from elsewhere. It must stay VISIBLE and
357
- // REMOVABLE: a condition the user cannot see is one they cannot delete, and
358
- // every Save keeps sending it. Same defect as a `<select>` whose value matches
359
- // no option, one level up.
360
- const strays = preds
361
- .map((p, i) => ({ p, i }))
362
- .filter(({ p }) => !known.has(p.name));
363
-
364
- const maxRecords = discover?.guard?.maxRecords || discover?.maxRecords || 500;
365
-
366
- /** D-69 β€” the raw text of the input a person is typing in right now (see `Draft`). */
367
- const [draft, setDraft] = useState<Draft | null>(null);
368
-
369
- /**
370
- * ⭐ ITEM 16 / D-71 β€” THE OBSERVED CATEGORY VALUES, fetched WHEN THIS PANEL OPENS.
371
- *
372
- * β›” ON MOUNT, ONCE, AND NEVER ON THE POLLED PAYLOAD. This component is rendered only while the
373
- * Find panel is open, so mounting IS the panel opening β€” and the server moved these off
374
- * `GET /automations` after measuring that deriving them reads two user tables plus the platform
375
- * master, i.e. a network round-trip per open tab every 2.5 s. Putting the request here is the
376
- * client half of that same decision, not an optimisation.
377
- *
378
- * ⚠ AN EMPTY LIST IS AN ANSWER AND IS RENDERED AS ONE. It means this deployment has not seen a
379
- * category value yet β€” which is TRUE for a fresh tenant β€” and the field keeps its free-text
380
- * input either way. It must never read as "loading forever", and it must never be filled in
381
- * with a guess: D-59 is explicit that an invented taxonomy is worse than no dropdown.
382
- */
383
- const [cats, setCats] = useState<{ value: string; count: number }[]>([]);
384
- useEffect(() => {
385
- const ac = new AbortController();
386
- discoverCategories(ac.signal)
387
- .then((r) => setCats(Array.isArray(r?.options) ? r.options : []))
388
- // Fail-quiet, on purpose: the picker is an ASSIST over a control that works without it.
389
- // An error banner here would report a broken panel when the only thing missing is a
390
- // convenience β€” and the free-text input beside it is unaffected.
391
- .catch(() => setCats([]));
392
- return () => ac.abort();
393
- }, []);
394
-
395
- const setAt = (i: number, patch: Partial<Predicate>) =>
396
- onPreds(preds.map((p, j) => (j === i ? { ...p, ...patch } : p)));
397
-
398
- const removeAt = (i: number) => onPreds(preds.filter((_p, j) => j !== i));
399
-
400
- const toggleField = (row: FieldRow) => {
401
- if (row.at.length) {
402
- onPreds(preds.filter((p) => p.name !== row.name));
403
- return;
404
- }
405
- onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }]);
406
- };
407
-
408
- /** One condition line β€” the comparison, its value, and a way out. */
409
- const condition = (i: number, label: string, row?: FieldRow) => {
410
- const p = preds[i];
411
- if (!p) return null;
412
- // The field's OWN comparisons. `row` is absent only for a stray (a stored condition on a
413
- // field the vendor no longer offers), which keeps the raw token so it stays removable.
414
- const ops = row?.operators || [];
415
- const cur = ops.find((o) => o.value === p.operator);
416
- const isNullary = cur ? cur.nullary : nullary.has(p.operator);
417
- const isMulti = !!cur?.multi;
418
- const options = row?.options || [];
419
- const rowKey = `${p.name}-${i}`;
420
- // D-69: the focused input shows what was TYPED; every other one shows the stored value.
421
- const shown = draft && draft.key === rowKey ? draft.text : valueText(p.value);
422
- /*
423
- * ⭐ ITEM 16 / D-71 β€” WHICH FIELDS GET THE OBSERVED-VALUES PICKER, DERIVED OFF THE WIRE.
424
- *
425
- * β›” NOT A CLIENT-SIDE LIST OF FIELD NAMES. Naming the vendor's two category columns here
426
- * would be the D-55 class verbatim β€” the wave-9 silent-drop shape, a client copy of a server
427
- * vocabulary that is free to drift the day the engine adds a third one. (Their literal keys
428
- * are deliberately not written anywhere in this file: the gate asserts the tokens are ABSENT,
429
- * and an absence check cannot tell a hard-coded list from the comment forbidding one.)
430
- * The server already publishes the answer twice over: `kind: "choice"` is its own declaration
431
- * (`BD_FIELD_KINDS`), and `filter_meta` deliberately ships `options: []` for those fields
432
- * because their vocabulary is OBSERVED rather than declared and arrives on its own route.
433
- * So the rule is exactly that: a choice-kind field with no declared options is one whose
434
- * values we can only have learned by seeing them. A new choice field inherits this for free.
435
- */
436
- const wantsObserved = row?.kind === "choice" && !options.length;
437
- /** D-71 β€” APPEND, never replace: the picker has to compose with the comma list. */
438
- const appendValue = (v: string) => {
439
- const has = shown
440
- .split(",")
441
- .map((s) => s.trim().toLowerCase())
442
- .filter(Boolean);
443
- // Picking the same value twice is a no-op rather than a duplicate: the server expands a
444
- // multi-value condition into an OR, and `beauty OR beauty` costs a slot to say nothing.
445
- if (has.includes(v.trim().toLowerCase())) return;
446
- const next = shown.trim() ? `${shown.replace(/[\s,]+$/, "")}, ${v}` : v;
447
- setDraft(null);
448
- setAt(i, { value: parseValue(next, isMulti) });
449
- };
450
- return (
451
- <div className="autob-cond" key={rowKey}>
452
- <select
453
- className="auto-input is-small"
454
- aria-label={`Comparison for ${label}`}
455
- value={p.operator}
456
- onChange={(e) => setAt(i, { operator: e.target.value })}
457
- >
458
- {/* The stored value is ALWAYS an option. A select whose value matches no
459
- option renders the FIRST one, and the next Save writes a comparison
460
- nobody chose β€” this codebase has paid for that twice. */}
461
- {p.operator && !ops.some((o) => o.value === p.operator) ? (
462
- <option value={p.operator}>{p.operator}</option>
463
- ) : null}
464
- {ops.map((o) => (
465
- <option key={o.value} value={o.value}>
466
- {o.label}
467
- </option>
468
- ))}
469
- </select>
470
- {isNullary ? null : options.length ? (
471
- // A fixed vocabulary gets a dropdown. Owner item 2: a yes/no column was a box you
472
- // typed `true` into, beside a comparison list that offered "at least".
473
- <select
474
- className="auto-input is-small"
475
- aria-label={`Value for ${label}`}
476
- value={valueText(p.value)}
477
- onChange={(e) => setAt(i, { value: e.target.value })}
478
- >
479
- <option value="">Choose…</option>
480
- {options.map((o) => (
481
- <option key={o.value} value={o.value}>
482
- {o.label}
483
- </option>
484
- ))}
485
- </select>
486
- ) : (
487
- <input
488
- className="auto-input is-small"
489
- type={row?.kind === "number" ? "number" : "text"}
490
- aria-label={`Value for ${label}`}
491
- // ⭐ OWNER ITEM 3. Several comma-separated values become an "any of" condition, which
492
- // the server sends as its own OR group β€” so it does NOT drag Followers into a union
493
- // the way the Match dropdown would.
494
- placeholder={isMulti ? "floral, flower, beauty" : ""}
495
- // D-69: `shown` is the RAW text while this input has focus, so a trailing comma
496
- // survives long enough to type the next value after it.
497
- value={shown}
498
- onFocus={() => setDraft({ key: rowKey, text: valueText(p.value) })}
499
- onChange={(e) => {
500
- setDraft({ key: rowKey, text: e.target.value });
501
- // The STORE still updates on every keystroke. Parsing only on blur would mean a
502
- // Save pressed straight from the field wrote the previous value β€” trading a typing
503
- // bug for a data-loss one.
504
- setAt(i, { value: parseValue(e.target.value, isMulti) });
505
- }}
506
- onBlur={(e) => {
507
- setDraft(null);
508
- setAt(i, { value: parseValue(e.target.value, isMulti) });
509
- }}
510
- />
511
- )}
512
- {/* ⭐ ITEM 16 / D-71 β€” THE APPEND-PICKER, BESIDE the input and never instead of it.
513
- Free text stays the primary control: these are the values this deployment has SEEN,
514
- not the values that exist, so the picker is a shortcut over a superset it cannot
515
- enumerate. Appending in code also sidesteps D-69 entirely β€” a picked value never has
516
- to survive a round trip through the text box. */}
517
- {wantsObserved && !isNullary ? (
518
- <select
519
- className="auto-input is-small autoc-catpick"
520
- aria-label={`Add a value seen before, to ${label}`}
521
- title={
522
- cats.length
523
- ? "Values this workspace has actually seen, most-seen first. Adds to the list."
524
- : "No category values have been seen in your data yet β€” type one."
525
- }
526
- value=""
527
- disabled={!cats.length}
528
- onChange={(e) => {
529
- if (e.target.value) appendValue(e.target.value);
530
- }}
531
- >
532
- <option value="">{cats.length ? "Seen before…" : "None seen yet"}</option>
533
- {cats.map((c) => (
534
- // The COUNT is the honest half (D-59): a value seen once and one seen forty times
535
- // are different bets, and an alphabetical list of bare strings hides that.
536
- <option key={c.value} value={c.value}>
537
- {c.value} ({c.count.toLocaleString()})
538
- </option>
539
- ))}
540
- </select>
541
- ) : null}
542
- {isMulti && Array.isArray(p.value) && p.value.length > 1 ? (
543
- /*
544
- * ⭐ ITEM 16 / D-71 β€” HOW MANY VALUES THIS CONDITION CARRIES, and against what ceiling.
545
- *
546
- * The COUNT is ours and is always shown. The CEILING is the server's and is shown only
547
- * when the server sends one (`guard.maxValues` β€” an open `ASK ->A:`; `guard` ships
548
- * `{minNarrowing, maxRecords}` today).
549
- * β›” NO CLIENT-SIDE `4`. D-71's exit says "how many of D-68's 4 value slots" β€” but A
550
- * shipped `depth_refusal()`, which computes the depth of the shape actually emitted
551
- * rather than budgeting fixed slots, so the number 4 describes a model that no longer
552
- * exists. Printing it would be a client copy of a server rule that has already changed
553
- * once, which is the specific failure this file's header refuses to commit
554
- * ([[measure-the-real-call]]: a correct-looking answer about the wrong subject).
555
- */
556
- <span className="autob-cond-any" title="Any one of these is a match">
557
- any of {p.value.length}
558
- {discover?.guard?.maxValues ? ` of ${discover.guard.maxValues}` : ""}
559
- </span>
560
- ) : null}
561
- <button
562
- type="button"
563
- className="autob-cond-x"
564
- aria-label={`Remove this condition on ${label}`}
565
- title="Remove this condition"
566
- onClick={() => removeAt(i)}
567
- >
568
- <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
569
- <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
570
- </svg>
571
- </button>
572
- </div>
573
- );
574
- };
575
-
576
- const fieldRow = (row: FieldRow) => {
577
- const on = row.at.length > 0;
578
- return (
579
- <div className={"autob-tgl" + (on ? " is-on" : "")} key={row.name}>
580
- <div className="autob-tgl-head">
581
- <button
582
- type="button"
583
- className={"auto-step-switch autob-tgl-switch" + (on ? " is-on" : "")}
584
- aria-pressed={on}
585
- aria-label={`${on ? "Stop searching" : "Search"} on ${row.label}`}
586
- title={`${on ? "Stop searching" : "Search"} on ${row.label}`}
587
- onClick={() => toggleField(row)}
588
- >
589
- <span className="auto-step-switch-knob" />
590
- </button>
591
- <span className="autob-tgl-mark">
592
- <FilterMark name={row.name} />
593
- </span>
594
- {/* ⭐ THE HUMAN LABEL (owner item 1: "wtf is id/fbid").
595
- This used to render the vendor's own column name verbatim, and the comment
596
- defending it was RIGHT about the reason β€” a refusal names the field, and a label
597
- that reads differently makes the error unmatchable. So the label did not move
598
- alone: `field_label()` is what the SERVER's refusals use too, which is the only
599
- version of this change that does not trade one confusion for another. */}
600
- <span className="autob-tgl-name" title={row.hint || undefined}>
601
- {row.label}
602
- </span>
603
- {/*
604
- ⚠ ONE CHIP, AND IT MARKS THE MINORITY. The first version chipped every
605
- non-narrowing field "broad" AND every unpopulated one "no values seen" β€”
606
- which put two chips on 18 of the 21 rows, and one of them repeated the group
607
- heading the row was already sitting under. A mark that is on almost every row
608
- stops being a mark. Read off the screenshot; no assertion could have said it.
609
-
610
- So: the group label carries POPULATED (it is what the groups ARE), and the
611
- chip carries NARROWING, inverted to mark the five that DO narrow. That is the
612
- actionable half β€” the server refuses a filter with no narrowing condition, so
613
- "these are the ones that satisfy it" is the sentence a user needs, and
614
- "this one does not" is not.
615
- */}
616
- {row.narrowing === true ? (
617
- <span
618
- className="autob-tgl-flag is-narrow"
619
- title="A search needs at least one condition like this."
620
- >
621
- narrows
622
- </span>
623
- ) : null}
624
- </div>
625
- {on ? (
626
- <div className="autob-tgl-body">
627
- {row.at.map((i) => condition(i, row.label, row))}
628
- {row.hint ? <p className="autob-tgl-hint">{row.hint}</p> : null}
629
- <button
630
- type="button"
631
- className="autob-cond-add"
632
- onClick={() =>
633
- onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }])
634
- }
635
- >
636
- Another condition on {row.label}
637
- </button>
638
- </div>
639
- ) : null}
640
- </div>
641
- );
642
- };
643
-
644
- return (
645
- <>
646
- <div className="auto-field">
647
- <label htmlFor="auto-records">How many profiles to fetch</label>
648
- <input
649
- id="auto-records"
650
- className="auto-input"
651
- type="number"
652
- min={1}
653
- max={maxRecords}
654
- value={recordsLimit}
655
- onChange={(e) => onRecordsLimit(Number(e.target.value) || 1)}
656
- />
657
- </div>
658
- {/* Owner item 5: "Stop at the 'A search must be at most 500 profiles a run'". The two
659
- sentences that followed explained the vendor's billing model to somebody who wants a
660
- list of florists. */}
661
- <p className="auto-hint">At most {maxRecords.toLocaleString()} profiles a run.</p>
662
-
663
- <h3>Conditions</h3>
664
- <div className="auto-field autob-match">
665
- <label htmlFor="auto-joinop">Match</label>
666
- <select
667
- id="auto-joinop"
668
- className="auto-input"
669
- value={joinOp}
670
- onChange={(e) => onJoinOp(e.target.value)}
671
- >
672
- <option value="and">All of them</option>
673
- <option value="or">Any of them</option>
674
- </select>
675
- </div>
676
-
677
- {!rows.length ? (
678
- <p className="auto-note">
679
- The searchable fields have not loaded yet.
680
- </p>
681
- ) : null}
682
-
683
- {withValues.length ? (
684
- <div className="autob-tglgroup">
685
- <p
686
- className="autob-tglgroup-label"
687
- title="Most accounts have this filled in."
688
- >
689
- Usually filled in
690
- </p>
691
- {withValues.map(fieldRow)}
692
- </div>
693
- ) : null}
694
-
695
- {rest.length ? (
696
- <div className="autob-tglgroup">
697
- <p
698
- className="autob-tglgroup-label"
699
- title={
700
- knownMeta
701
- ? "Most accounts leave these blank, so a condition here can return nothing."
702
- : "We have not measured how often these are filled in."
703
- }
704
- >
705
- {knownMeta ? "Often blank" : "Not measured"}
706
- </p>
707
- {rest.map(fieldRow)}
708
- </div>
709
- ) : null}
710
-
711
- {strays.length ? (
712
- <div className="autob-tglgroup">
713
- <p className="autob-tglgroup-label">Not in the searchable list</p>
714
- {strays.map(({ p, i }) => (
715
- <div className="autob-tgl is-on is-stray" key={`stray-${i}`}>
716
- <div className="autob-tgl-head">
717
- {/* A stray gets a mark too β€” "every filter row" includes the ones the vendor no
718
- longer offers, and a row missing the icon its neighbours have would read as a
719
- different KIND of thing rather than as a field that fell out of the list. It
720
- draws the neutral fallback by construction: a stray is, by definition, not in
721
- the vocabulary this component has arms for. */}
722
- <span className="autob-tgl-mark">
723
- <FilterMark name={p.name} />
724
- </span>
725
- <span className="autob-tgl-name">{p.name}</span>
726
- <span className="autob-tgl-flag is-stray" title="The server will refuse this condition by name.">
727
- not searchable
728
- </span>
729
- </div>
730
- <div className="autob-tgl-body">{condition(i, p.name)}</div>
731
- </div>
732
- ))}
733
- </div>
734
- ) : null}
735
-
736
- {/* The consequence kept, the mechanism dropped: a condition on an often-blank field
737
- returning nothing is a thing that will happen to somebody and confuse them. Why the
738
- search is slow when broad is our problem, not theirs. */}
739
- <p className="auto-hint">
740
- Conditions on often-blank fields can come back with nothing.
741
- </p>
742
-
743
- <h3>What it costs</h3>
744
- <div className="auto-head-actions">
745
- <button type="button" className="auto-btn" onClick={onEstimate}>
746
- Estimate this search
747
- </button>
748
- </div>
749
- {estimate ? (
750
- <p className="auto-hint">
751
- About <strong>${estimate.usd}</strong> for {estimate.records} profiles, at $
752
- {estimate.unitUsd} each.{" "}
753
- {/*
754
- THE CAVEAT IS NOT OPTIONAL. The vendor never quotes a price before a run and this
755
- deployment cannot read its own balance, so presenting this as a billed figure
756
- would be inventing a measurement.
757
- */}
758
- <strong>This is an estimate</strong> β€” {estimate.note}.
759
- </p>
760
- ) : null}
761
- </>
762
- );
763
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/AutomationFind.tsx β€” the discovery filter, as TOGGLES (owner item 6,
3
+ // contract C4).
4
+ //
5
+ // WHAT CHANGED AND WHY. It was a condition BUILDER: an empty row, a field
6
+ // dropdown listing 21 names, "Add a condition". That shape asks the user to
7
+ // remember what is searchable before they can look, and it hid the only fact
8
+ // that decides whether a search returns anything at all β€” which fields actually
9
+ // carry values. The corpus is 620 million profiles and every run is billed, so
10
+ // "I did not know I could filter on that" and "I filtered on a field that is
11
+ // empty on every row" are both expensive mistakes made in silence.
12
+ //
13
+ // So every searchable field is ON SCREEN, off by default, and turning one on is
14
+ // what creates its condition. The list leads with the fields MEASURED to carry
15
+ // values; the rest are grouped under what is known about them, and neither group
16
+ // is hidden β€” R3 already decided that "every filter" means the 21 we can stand
17
+ // behind, so all 21 are visible.
18
+ //
19
+ // β›” THE VOCABULARY IS THE SERVER'S, ALL OF IT. Field names, operators, which
20
+ // operators take no value, the record ceiling and (once C4 lands it) which
21
+ // fields are populated and which narrow β€” every one of those rides on
22
+ // `GET /automations`. This file holds no list of its own. The reason is the one
23
+ // `automationApi.ts:11-15` gives for cron presets: the thing that ACCEPTS a
24
+ // filter is Python, and a client copy of what it accepts is a copy that can
25
+ // offer a search the server refuses.
26
+ //
27
+ // β›” AND IT DOES NOT RE-IMPLEMENT THE GUARD. `guard` carries the server's
28
+ // numbers, so the rows can say which fields narrow β€” but the refusal is the
29
+ // server's to make and this surface prints it VERBATIM when it comes back
30
+ // (`DiscoverGuard`'s note). A client that predicts the refusal is a second copy
31
+ // of the rule, free to disagree with the first, and when they disagree the user
32
+ // gets a Save button that is disabled for a reason nobody can see.
33
+ // ---------------------------------------------------------------------------
34
+ import { useEffect, useState } from "react";
35
+ // ⭐ WAVE 27 item 29 β€” the overlay layer the grid already owns, consumed rather than
36
+ // re-implemented: it is a body portal (so it escapes `.auto-panel`'s 380px), and it brings
37
+ // the dismiss/focus/placement behaviour every other popover on this product already has.
38
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
39
+ import type { AnchorRect } from "../customer-grid/OverlaySurface";
40
+
41
+ import type {
42
+ DiscoverEstimate,
43
+ DiscoverFieldMeta,
44
+ DiscoverOperator,
45
+ DiscoverVocab,
46
+ Predicate,
47
+ } from "./automationApi";
48
+ import { discoverCategories } from "./automationApi";
49
+
50
+ interface Props {
51
+ /** The server-declared discovery vocabulary (absent until the list loads). */
52
+ discover?: DiscoverVocab;
53
+ recordsLimit: number;
54
+ onRecordsLimit: (n: number) => void;
55
+ joinOp: string;
56
+ onJoinOp: (v: string) => void;
57
+ preds: Predicate[];
58
+ onPreds: (next: Predicate[]) => void;
59
+ estimate: DiscoverEstimate | null;
60
+ onEstimate: () => void;
61
+ }
62
+
63
+ /**
64
+ * A FILTER FIELD'S ICON (owner item 5). Drawn, `currentColor`, never an emoji β€” and in the
65
+ * existing `TriggerMark`/`ActionMark` language rather than a new one: same 16 viewBox, same 15px
66
+ * box, same 1.4 stroke, so a row here and a card in the builder read as one product.
67
+ *
68
+ * ⚠ SHARED SHAPES WHERE THE FIELDS SHARE A MEANING, distinct everywhere else. `TriggerMark`'s
69
+ * note settled the principle β€” a column of identical glyphs is decoration, the eye learns nothing
70
+ * β€” but its converse matters just as much here: `bio_hashtags` and `post_hashtags` ARE both
71
+ * hashtags, and drawing two different marks for them would invent a distinction the vendor does
72
+ * not make. Twenty-one contrived glyphs would be twenty-one things to misread.
73
+ *
74
+ * β›” THE FALLBACK IS NOT A MEMBER OF THE SET, which is the `ActionMark` scar exactly: its default
75
+ * used to BE the pencil, a real member, so every unmatched kind silently borrowed "edit" and a
76
+ * fallback could not be told from a match. The vocabulary is the SERVER's β€” it can grow a field
77
+ * tomorrow β€” so an unmatched name draws a neutral mark that is deliberately meaningless.
78
+ */
79
+ function FilterMark({ name }: { name: string }) {
80
+ const common = {
81
+ width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
82
+ strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
83
+ "aria-hidden": true,
84
+ };
85
+ // Audience size β€” two figures, one behind the other.
86
+ if (name === "followers")
87
+ return (
88
+ <svg {...common}>
89
+ <circle cx="6.2" cy="5.6" r="2.4" />
90
+ <path d="M2.2 13c.5-2 2.1-3.2 4-3.2s3.5 1.2 4 3.2" />
91
+ <path d="M10.6 3.6a2.4 2.4 0 0 1 0 4M11.4 9.9c1.4.4 2.4 1.5 2.8 3.1" />
92
+ </svg>
93
+ );
94
+ // Who this account follows β€” a figure with an outbound arrow.
95
+ if (name === "following")
96
+ return (
97
+ <svg {...common}>
98
+ <circle cx="6" cy="5.6" r="2.4" />
99
+ <path d="M1.8 13c.5-2 2.1-3.2 4.2-3.2 .6 0 1.2.1 1.7.3" />
100
+ <path d="M9.8 10.6h4.2M12.2 8.8l1.8 1.8-1.8 1.8" />
101
+ </svg>
102
+ );
103
+ if (name === "posts_count")
104
+ return (
105
+ <svg {...common}>
106
+ <rect x="2.6" y="2.6" width="4.6" height="4.6" rx="1" />
107
+ <rect x="8.8" y="2.6" width="4.6" height="4.6" rx="1" />
108
+ <rect x="2.6" y="8.8" width="4.6" height="4.6" rx="1" />
109
+ <rect x="8.8" y="8.8" width="4.6" height="4.6" rx="1" />
110
+ </svg>
111
+ );
112
+ // A story highlight β€” the ring Instagram draws around one.
113
+ if (name === "highlights_count")
114
+ return (
115
+ <svg {...common}>
116
+ <circle cx="8" cy="8" r="5.6" strokeDasharray="2.6 1.8" />
117
+ <circle cx="8" cy="8" r="2.2" />
118
+ </svg>
119
+ );
120
+ if (name === "avg_engagement")
121
+ return (
122
+ <svg {...common}>
123
+ <path d="M8 13.2 3.4 8.8a2.9 2.9 0 0 1 4.6-3.4 2.9 2.9 0 0 1 4.6 3.4z" />
124
+ </svg>
125
+ );
126
+ if (name === "biography")
127
+ return (
128
+ <svg {...common}>
129
+ <rect x="2.4" y="2.8" width="11.2" height="10.4" rx="1.6" />
130
+ <path d="M4.8 6h6.4M4.8 8.4h6.4M4.8 10.8h3.6" />
131
+ </svg>
132
+ );
133
+ if (name === "category_name" || name === "business_category_name")
134
+ return (
135
+ <svg {...common}>
136
+ <path d="M8.4 2.6H13v4.6l-6.2 6.2-4.6-4.6z" />
137
+ <circle cx="10.8" cy="5.2" r="0.9" />
138
+ </svg>
139
+ );
140
+ if (name === "is_business_account" || name === "is_professional_account")
141
+ return (
142
+ <svg {...common}>
143
+ <rect x="2.2" y="5" width="11.6" height="8.2" rx="1.6" />
144
+ <path d="M6 5V3.6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1V5" />
145
+ </svg>
146
+ );
147
+ if (name === "is_verified")
148
+ return (
149
+ <svg {...common}>
150
+ <path d="M8 2.2l1.7 1.2 2-.2.6 2 1.7 1.1-.9 1.9.9 1.9-1.7 1.1-.6 2-2-.2L8 14.2l-1.7-1.2-2 .2-.6-2L2 10.1l.9-1.9L2 6.3l1.7-1.1.6-2 2 .2z" />
151
+ <path d="m5.8 8.1 1.5 1.5 3-3.1" />
152
+ </svg>
153
+ );
154
+ // The handle, and the display name it is written under.
155
+ if (name === "account" || name === "profile_name")
156
+ return (
157
+ <svg {...common}>
158
+ <circle cx="8" cy="8" r="2.4" />
159
+ <path d="M10.4 5.6v3.2a1.9 1.9 0 0 0 3.2 1.3A5.8 5.8 0 1 0 11 13.1" />
160
+ </svg>
161
+ );
162
+ if (name === "full_name")
163
+ return (
164
+ <svg {...common}>
165
+ <circle cx="8" cy="5.6" r="2.6" />
166
+ <path d="M3 13.4c.7-2.3 2.6-3.6 5-3.6s4.3 1.3 5 3.6" />
167
+ </svg>
168
+ );
169
+ if (name === "external_url" || name === "profile_url")
170
+ return (
171
+ <svg {...common}>
172
+ <path d="M6.6 9.4 4.9 11a2.6 2.6 0 1 1-1.5-4.4" />
173
+ <path d="M9.4 6.6 11.1 5a2.6 2.6 0 1 1 1.5 4.4" />
174
+ <path d="M6.2 8h3.6" />
175
+ </svg>
176
+ );
177
+ if (name === "bio_hashtags" || name === "post_hashtags")
178
+ return (
179
+ <svg {...common}>
180
+ <path d="M6.2 2.8 4.8 13.2M11.2 2.8 9.8 13.2M2.8 6h10.4M2.2 10h10.4" />
181
+ </svg>
182
+ );
183
+ if (name === "related_accounts")
184
+ return (
185
+ <svg {...common}>
186
+ <circle cx="8" cy="3.6" r="1.8" />
187
+ <circle cx="3.6" cy="12" r="1.8" />
188
+ <circle cx="12.4" cy="12" r="1.8" />
189
+ <path d="M6.8 5.2 4.6 10.4M9.2 5.2l2.2 5.2M5.4 12h5.2" />
190
+ </svg>
191
+ );
192
+ // The vendor's own record keys β€” the thing you hold to open exactly one row.
193
+ if (name === "id" || name === "fbid")
194
+ return (
195
+ <svg {...common}>
196
+ <circle cx="5.4" cy="10.6" r="2.6" />
197
+ <path d="M7.2 8.8 13 3M10.6 5.4l1.6 1.6M9.2 6.8l1.6 1.6" />
198
+ </svg>
199
+ );
200
+ return (
201
+ <svg {...common}>
202
+ <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
203
+ <circle cx="8" cy="8" r="1.4" />
204
+ </svg>
205
+ );
206
+ }
207
+
208
+ /** One field's line in the list, with everything known about it. */
209
+ interface FieldRow {
210
+ name: string;
211
+ /** What the row is CALLED. Falls back to the raw name only if the server sent none. */
212
+ label: string;
213
+ hint: string;
214
+ kind: string;
215
+ operators: DiscoverOperator[];
216
+ options: { value: string; label: string }[];
217
+ /** Every stored condition naming this field, with its index in the saved array. */
218
+ at: number[];
219
+ /** MEASURED to carry values. `null` = the server has not said (C4 not shipped yet). */
220
+ populated: boolean | null;
221
+ /** A condition here cuts the corpus down. `null` = not said. */
222
+ narrowing: boolean | null;
223
+ }
224
+
225
+ /** A stored value β†’ what the text box shows. A list is the "any of" shape. */
226
+ function valueText(v: Predicate["value"]): string {
227
+ if (Array.isArray(v)) return v.join(", ");
228
+ return v === undefined || v === null ? "" : String(v);
229
+ }
230
+
231
+ /**
232
+ * What the user typed β†’ what is stored. Comma-separated becomes a LIST for the operators that
233
+ * accept one, and stays a plain string for the ones that do not.
234
+ *
235
+ * ⚠ A single value stays a SCALAR rather than a one-element list β€” the server sends scalars
236
+ * flat and lists as a nested OR group, and a one-element group is a shape nothing has been
237
+ * billed against.
238
+ */
239
+ function parseValue(text: string, multi: boolean): Predicate["value"] {
240
+ if (!multi) return text;
241
+ const parts = text.split(",").map((s) => s.trim()).filter(Boolean);
242
+ if (parts.length > 1) return parts;
243
+ // Keep the RAW text while it is still being typed β€” trimming here would fight the cursor on
244
+ // every keystroke, and the server trims anyway.
245
+ return text;
246
+ }
247
+
248
+ /**
249
+ * ⭐ WAVE 26 Β· DEBT D-69 β€” A THIRD VALUE COULD NOT BE TYPED, and the cause was one round trip
250
+ * through this pair of functions.
251
+ *
252
+ * `parseValue` returns an ARRAY at 2+ values; `valueText` then renders that array as
253
+ * `join(", ")` β€” which has NO TRAILING COMMA. So on a controlled input the separator was
254
+ * normalised away between keystrokes: typing `,` onto `skincare, beauty` re-rendered as
255
+ * `skincare, beauty`, and the next character landed as `skincare, beautym`. Two keywords
256
+ * silently became one that matches nothing. ⚠ It hit the FIRST surface a new user meets (wave 24
257
+ * made this panel the only door) and it hit precisely the 3+ keyword list the feature was built
258
+ * for β€” the owner's *"if i want to include many keywords like floral, flower, beauty"*.
259
+ *
260
+ * β›” THE FIX IS THE ONE `parseValue`'s OWN COMMENT ALREADY DESCRIBES FOR THE 1-VALUE CASE:
261
+ * keep the raw text while it is being typed. That comment was right and its scope was too narrow
262
+ * β€” it protected the cursor at one value and handed the 2+ case to `join`. So the raw text is
263
+ * held for whichever input is FOCUSED, and the stored value is still parsed on every keystroke
264
+ * (so nothing depends on blur to save) and re-parsed on blur (so the display settles).
265
+ *
266
+ * ⚠ KEYED BY THE ROW'S REACT KEY, not by index alone: two conditions on the same field are
267
+ * ordinary here ("Another condition on Bio"), and an index-only key would leak one row's draft
268
+ * into its sibling on a removal.
269
+ */
270
+ interface Draft {
271
+ key: string;
272
+ text: string;
273
+ }
274
+
275
+ /**
276
+ * The comparison a freshly toggled field starts with β€” ASKED FOR, never chosen here.
277
+ *
278
+ * β›” THE THIRD COSTUME OF ONE SCAR, and the reason this function no longer has an opinion.
279
+ * Wave 21 made a new condition NULLARY (`is_not_null`) so it would be saveable without a
280
+ * value, and called that "narrowing-in-the-right-direction". Wave 22 then wrote the narrowing
281
+ * law server-side and `is_not_null` is not in it. From that moment, toggling ANY field on and
282
+ * pressing Save returned "add at least one CONTENT condition…" β€” the error told the user to do
283
+ * the exact thing they had just done. Wave 24 deleted the wizard and made this panel the only
284
+ * door, so it stopped being a corner case and became the first thing a new user hits.
285
+ *
286
+ * The fix is not a better guess. It is that the module owning the guard also names the default
287
+ * (`automation_engine.default_operator`, asserted against `predicate_narrows` in
288
+ * `verify_automation.py`), and this file looks it up per FIELD. An absent one falls back to the
289
+ * server's first operator β€” never to a nullary, which is the thing that could not narrow.
290
+ */
291
+ function firstOperator(v: DiscoverVocab | undefined, name: string): string {
292
+ const meta = (v?.filterMeta || []).find((m) => m.name === name);
293
+ return meta?.defaultOperator || (v?.operators || [])[0] || "";
294
+ }
295
+
296
+ /**
297
+ * The rows, ordered: measured-populated first, then the rest.
298
+ *
299
+ * TWO SOURCES, AND THE FALLBACK IS NARROWER THAN THE REAL THING. With C4's
300
+ * `filterMeta` the answer is per field and complete. Without it, `lead` names
301
+ * the three fields seen carrying values and says NOTHING about the other
302
+ * eighteen β€” so those come back `null`, not `false`, and the UI prints no claim
303
+ * about them rather than an invented one.
304
+ */
305
+ function buildRows(preds: Predicate[], v?: DiscoverVocab): FieldRow[] {
306
+ const meta = new Map<string, DiscoverFieldMeta>(
307
+ (v?.filterMeta || []).map((m) => [m.name, m])
308
+ );
309
+ const lead = new Set(v?.lead || []);
310
+ const byName = new Map<string, number[]>();
311
+ preds.forEach((p, i) => {
312
+ const list = byName.get(p.name);
313
+ if (list) list.push(i);
314
+ else byName.set(p.name, [i]);
315
+ });
316
+
317
+ const rows = (v?.fields || []).map((name) => {
318
+ const m = meta.get(name);
319
+ return {
320
+ name,
321
+ label: m?.label || name,
322
+ hint: m?.hint || "",
323
+ kind: m?.kind || "text",
324
+ // β›” NO FALLBACK TO THE GLOBAL OPERATOR LIST. An older server that sends no per-field list
325
+ // gets a row with no comparisons rather than all fourteen on every field β€” visibly
326
+ // unfinished beats quietly offering `at least` on a yes/no column.
327
+ operators: m?.operators || [],
328
+ options: m?.options || [],
329
+ at: byName.get(name) || [],
330
+ populated: m ? !!m.populated : lead.has(name) ? true : null,
331
+ narrowing: m ? !!m.narrowing : null,
332
+ };
333
+ });
334
+ // Stable partition, never a sort: the server's order inside each half is the
335
+ // order the engine lists them in, and re-alphabetising it would be this file
336
+ // having an opinion about a server list.
337
+ return [...rows.filter((r) => r.populated === true), ...rows.filter((r) => r.populated !== true)];
338
+ }
339
+
340
+ export default function AutomationFind({
341
+ discover,
342
+ recordsLimit,
343
+ onRecordsLimit,
344
+ joinOp,
345
+ onJoinOp,
346
+ preds,
347
+ onPreds,
348
+ estimate,
349
+ onEstimate,
350
+ }: Props) {
351
+ const rows = buildRows(preds, discover);
352
+ const known = new Set(discover?.fields || []);
353
+ // The GLOBAL operator list is gone from this component: comparisons are per field now
354
+ // (`row.operators`). `nullary` survives for STRAYS only β€” a stored condition on a field the
355
+ // vendor dropped has no per-field row to read from, and it still has to render to be removable.
356
+ const nullary = new Set(discover?.nullaryOperators || []);
357
+ const withValues = rows.filter((r) => r.populated === true);
358
+ const rest = rows.filter((r) => r.populated !== true);
359
+ const knownMeta = !!(discover?.filterMeta || []).length;
360
+ // ⚠ THE STORED FILTER CAN NAME A FIELD THE LIST NO LONGER HAS β€” a vocabulary
361
+ // that moved, an automation copied from elsewhere. It must stay VISIBLE and
362
+ // REMOVABLE: a condition the user cannot see is one they cannot delete, and
363
+ // every Save keeps sending it. Same defect as a `<select>` whose value matches
364
+ // no option, one level up.
365
+ const strays = preds
366
+ .map((p, i) => ({ p, i }))
367
+ .filter(({ p }) => !known.has(p.name));
368
+
369
+ const maxRecords = discover?.guard?.maxRecords || discover?.maxRecords || 500;
370
+
371
+ /** D-69 β€” the raw text of the input a person is typing in right now (see `Draft`). */
372
+ const [draft, setDraft] = useState<Draft | null>(null);
373
+
374
+ /**
375
+ * ⭐ WAVE 27 Β· OWNER ITEM 29 β€” which condition's value is open in the BIG editor, if any.
376
+ *
377
+ * β›” THE TEXT IS HELD HERE, NOT WRITTEN THROUGH ON EVERY KEYSTROKE, and that is the one place
378
+ * this differs from the rail input beside it. The rail input writes per keystroke on purpose
379
+ * (a Save pressed straight from the field must not store the previous value β€” D-69's note).
380
+ * A modal has its own Save, so per-keystroke writes would buy nothing and would make Cancel
381
+ * a lie: the value would already be in the config by the time it was pressed.
382
+ * ⚠ The ANCHOR is captured at click time and stored, because the button it came from is
383
+ * inside a panel that scrolls β€” re-reading it later would place the overlay against a rect
384
+ * that has moved.
385
+ */
386
+ const [big, setBig] = useState<{
387
+ key: string;
388
+ index: number;
389
+ label: string;
390
+ multi: boolean;
391
+ text: string;
392
+ anchor: AnchorRect;
393
+ } | null>(null);
394
+
395
+ /**
396
+ * ⭐ ITEM 16 / D-71 β€” THE OBSERVED CATEGORY VALUES, fetched WHEN THIS PANEL OPENS.
397
+ *
398
+ * β›” ON MOUNT, ONCE, AND NEVER ON THE POLLED PAYLOAD. This component is rendered only while the
399
+ * Find panel is open, so mounting IS the panel opening β€” and the server moved these off
400
+ * `GET /automations` after measuring that deriving them reads two user tables plus the platform
401
+ * master, i.e. a network round-trip per open tab every 2.5 s. Putting the request here is the
402
+ * client half of that same decision, not an optimisation.
403
+ *
404
+ * ⚠ AN EMPTY LIST IS AN ANSWER AND IS RENDERED AS ONE. It means this deployment has not seen a
405
+ * category value yet β€” which is TRUE for a fresh tenant β€” and the field keeps its free-text
406
+ * input either way. It must never read as "loading forever", and it must never be filled in
407
+ * with a guess: D-59 is explicit that an invented taxonomy is worse than no dropdown.
408
+ */
409
+ const [cats, setCats] = useState<{ value: string; count: number }[]>([]);
410
+ useEffect(() => {
411
+ const ac = new AbortController();
412
+ discoverCategories(ac.signal)
413
+ .then((r) => setCats(Array.isArray(r?.options) ? r.options : []))
414
+ // Fail-quiet, on purpose: the picker is an ASSIST over a control that works without it.
415
+ // An error banner here would report a broken panel when the only thing missing is a
416
+ // convenience β€” and the free-text input beside it is unaffected.
417
+ .catch(() => setCats([]));
418
+ return () => ac.abort();
419
+ }, []);
420
+
421
+ const setAt = (i: number, patch: Partial<Predicate>) =>
422
+ onPreds(preds.map((p, j) => (j === i ? { ...p, ...patch } : p)));
423
+
424
+ const removeAt = (i: number) => onPreds(preds.filter((_p, j) => j !== i));
425
+
426
+ const toggleField = (row: FieldRow) => {
427
+ if (row.at.length) {
428
+ onPreds(preds.filter((p) => p.name !== row.name));
429
+ return;
430
+ }
431
+ onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }]);
432
+ };
433
+
434
+ /** One condition line β€” the comparison, its value, and a way out. */
435
+ const condition = (i: number, label: string, row?: FieldRow) => {
436
+ const p = preds[i];
437
+ if (!p) return null;
438
+ // The field's OWN comparisons. `row` is absent only for a stray (a stored condition on a
439
+ // field the vendor no longer offers), which keeps the raw token so it stays removable.
440
+ const ops = row?.operators || [];
441
+ const cur = ops.find((o) => o.value === p.operator);
442
+ const isNullary = cur ? cur.nullary : nullary.has(p.operator);
443
+ const isMulti = !!cur?.multi;
444
+ const options = row?.options || [];
445
+ const rowKey = `${p.name}-${i}`;
446
+ // D-69: the focused input shows what was TYPED; every other one shows the stored value.
447
+ const shown = draft && draft.key === rowKey ? draft.text : valueText(p.value);
448
+ /*
449
+ * ⭐ ITEM 16 / D-71 β€” WHICH FIELDS GET THE OBSERVED-VALUES PICKER, DERIVED OFF THE WIRE.
450
+ *
451
+ * β›” NOT A CLIENT-SIDE LIST OF FIELD NAMES. Naming the vendor's two category columns here
452
+ * would be the D-55 class verbatim β€” the wave-9 silent-drop shape, a client copy of a server
453
+ * vocabulary that is free to drift the day the engine adds a third one. (Their literal keys
454
+ * are deliberately not written anywhere in this file: the gate asserts the tokens are ABSENT,
455
+ * and an absence check cannot tell a hard-coded list from the comment forbidding one.)
456
+ * The server already publishes the answer twice over: `kind: "choice"` is its own declaration
457
+ * (`BD_FIELD_KINDS`), and `filter_meta` deliberately ships `options: []` for those fields
458
+ * because their vocabulary is OBSERVED rather than declared and arrives on its own route.
459
+ * So the rule is exactly that: a choice-kind field with no declared options is one whose
460
+ * values we can only have learned by seeing them. A new choice field inherits this for free.
461
+ */
462
+ const wantsObserved = row?.kind === "choice" && !options.length;
463
+ /** D-71 β€” APPEND, never replace: the picker has to compose with the comma list. */
464
+ const appendValue = (v: string) => {
465
+ const has = shown
466
+ .split(",")
467
+ .map((s) => s.trim().toLowerCase())
468
+ .filter(Boolean);
469
+ // Picking the same value twice is a no-op rather than a duplicate: the server expands a
470
+ // multi-value condition into an OR, and `beauty OR beauty` costs a slot to say nothing.
471
+ if (has.includes(v.trim().toLowerCase())) return;
472
+ const next = shown.trim() ? `${shown.replace(/[\s,]+$/, "")}, ${v}` : v;
473
+ setDraft(null);
474
+ setAt(i, { value: parseValue(next, isMulti) });
475
+ };
476
+ return (
477
+ <div className="autob-cond" key={rowKey}>
478
+ <select
479
+ className="auto-input is-small"
480
+ aria-label={`Comparison for ${label}`}
481
+ value={p.operator}
482
+ onChange={(e) => setAt(i, { operator: e.target.value })}
483
+ >
484
+ {/* The stored value is ALWAYS an option. A select whose value matches no
485
+ option renders the FIRST one, and the next Save writes a comparison
486
+ nobody chose β€” this codebase has paid for that twice. */}
487
+ {p.operator && !ops.some((o) => o.value === p.operator) ? (
488
+ <option value={p.operator}>{p.operator}</option>
489
+ ) : null}
490
+ {ops.map((o) => (
491
+ <option key={o.value} value={o.value}>
492
+ {o.label}
493
+ </option>
494
+ ))}
495
+ </select>
496
+ {isNullary ? null : options.length ? (
497
+ // A fixed vocabulary gets a dropdown. Owner item 2: a yes/no column was a box you
498
+ // typed `true` into, beside a comparison list that offered "at least".
499
+ <select
500
+ className="auto-input is-small"
501
+ aria-label={`Value for ${label}`}
502
+ value={valueText(p.value)}
503
+ onChange={(e) => setAt(i, { value: e.target.value })}
504
+ >
505
+ <option value="">Choose…</option>
506
+ {options.map((o) => (
507
+ <option key={o.value} value={o.value}>
508
+ {o.label}
509
+ </option>
510
+ ))}
511
+ </select>
512
+ ) : (
513
+ <input
514
+ className="auto-input is-small"
515
+ type={row?.kind === "number" ? "number" : "text"}
516
+ aria-label={`Value for ${label}`}
517
+ // ⭐ OWNER ITEM 3. Several comma-separated values become an "any of" condition, which
518
+ // the server sends as its own OR group β€” so it does NOT drag Followers into a union
519
+ // the way the Match dropdown would.
520
+ placeholder={isMulti ? "floral, flower, beauty" : ""}
521
+ // D-69: `shown` is the RAW text while this input has focus, so a trailing comma
522
+ // survives long enough to type the next value after it.
523
+ value={shown}
524
+ onFocus={() => setDraft({ key: rowKey, text: valueText(p.value) })}
525
+ onChange={(e) => {
526
+ setDraft({ key: rowKey, text: e.target.value });
527
+ // The STORE still updates on every keystroke. Parsing only on blur would mean a
528
+ // Save pressed straight from the field wrote the previous value β€” trading a typing
529
+ // bug for a data-loss one.
530
+ setAt(i, { value: parseValue(e.target.value, isMulti) });
531
+ }}
532
+ onBlur={(e) => {
533
+ setDraft(null);
534
+ setAt(i, { value: parseValue(e.target.value, isMulti) });
535
+ }}
536
+ />
537
+ )}
538
+ {/* ⭐ WAVE 27 Β· OWNER ITEM 29 β€” A WIDE EDITOR FOR THE VALUES THAT DO NOT FIT.
539
+ β›” THE COMPLAINT IS GEOMETRY, and the geometry is a CHAIN nothing here can widen:
540
+ `.auto-panel` is 380px, `.autob-cond .auto-input` divides what is left across three
541
+ controls, and `.is-small` trims it again β€” so a bio phrase list ("floral, flower,
542
+ wedding florist, event styling") is typed six characters at a time through a box
543
+ that scrolls sideways. The panel cannot grow; the EDITOR can leave it, and an
544
+ overlay is drawn in a body portal, so it is not bound by that chain at all.
545
+ ⚠ ALWAYS OFFERED, never "appears once the text is long": a control that materialises
546
+ at some threshold is one people do not know exists at the moment they need it.
547
+ ⚠ NOT on a `<select>` value (a fixed vocabulary has nothing to expand) and not on a
548
+ nullary comparison (which has no value at all). */}
549
+ {!isNullary && !options.length ? (
550
+ <button
551
+ type="button"
552
+ className="auto-input is-small autoc-expand"
553
+ aria-label={`Open a bigger editor for ${label}`}
554
+ title="Edit in a bigger box"
555
+ onClick={(e) => {
556
+ // ⚠ READ SYNCHRONOUSLY from the event. `currentTarget` is null by the time React
557
+ // re-invokes a state updater, and a null rect here paints the overlay at 0,0 β€”
558
+ // measured, in this repo, on a different control ([[react-event-currenttarget-updater]]).
559
+ const r = e.currentTarget.getBoundingClientRect();
560
+ setBig({
561
+ key: rowKey,
562
+ index: i,
563
+ label,
564
+ multi: isMulti,
565
+ text: valueText(p.value),
566
+ anchor: { left: r.left, top: r.top, right: r.right, bottom: r.bottom,
567
+ width: r.width, height: r.height },
568
+ });
569
+ }}
570
+ >
571
+ {/* Drawn, never a glyph: the design constitution's "no emojis in the UI" covers
572
+ the arrow characters too, and every other mark in this product is a path in the
573
+ same 16x16 stroke vocabulary. Two corners pulling apart = "make this bigger". */}
574
+ <svg viewBox="0 0 16 16" aria-hidden className="autoc-expand-icon">
575
+ <path d="M9.5 2.5h4v4M13.5 2.5 9.6 6.4" />
576
+ <path d="M6.5 13.5h-4v-4M2.5 13.5l3.9-3.9" />
577
+ </svg>
578
+ </button>
579
+ ) : null}
580
+ {/* ⭐ ITEM 16 / D-71 β€” THE APPEND-PICKER, BESIDE the input and never instead of it.
581
+ Free text stays the primary control: these are the values this deployment has SEEN,
582
+ not the values that exist, so the picker is a shortcut over a superset it cannot
583
+ enumerate. Appending in code also sidesteps D-69 entirely β€” a picked value never has
584
+ to survive a round trip through the text box. */}
585
+ {wantsObserved && !isNullary ? (
586
+ <select
587
+ className="auto-input is-small autoc-catpick"
588
+ aria-label={`Add a value seen before, to ${label}`}
589
+ title={
590
+ cats.length
591
+ ? "Values this workspace has actually seen, most-seen first. Adds to the list."
592
+ : "No category values have been seen in your data yet β€” type one."
593
+ }
594
+ value=""
595
+ disabled={!cats.length}
596
+ onChange={(e) => {
597
+ if (e.target.value) appendValue(e.target.value);
598
+ }}
599
+ >
600
+ <option value="">{cats.length ? "Seen before…" : "None seen yet"}</option>
601
+ {cats.map((c) => (
602
+ // The COUNT is the honest half (D-59): a value seen once and one seen forty times
603
+ // are different bets, and an alphabetical list of bare strings hides that.
604
+ <option key={c.value} value={c.value}>
605
+ {c.value} ({c.count.toLocaleString()})
606
+ </option>
607
+ ))}
608
+ </select>
609
+ ) : null}
610
+ {isMulti && Array.isArray(p.value) && p.value.length > 1 ? (
611
+ /*
612
+ * ⭐ ITEM 16 / D-71 β€” HOW MANY VALUES THIS CONDITION CARRIES, and against what ceiling.
613
+ *
614
+ * The COUNT is ours and is always shown. The CEILING is the server's and is shown only
615
+ * when the server sends one (`guard.maxValues` β€” an open `ASK ->A:`; `guard` ships
616
+ * `{minNarrowing, maxRecords}` today).
617
+ * β›” NO CLIENT-SIDE `4`. D-71's exit says "how many of D-68's 4 value slots" β€” but A
618
+ * shipped `depth_refusal()`, which computes the depth of the shape actually emitted
619
+ * rather than budgeting fixed slots, so the number 4 describes a model that no longer
620
+ * exists. Printing it would be a client copy of a server rule that has already changed
621
+ * once, which is the specific failure this file's header refuses to commit
622
+ * ([[measure-the-real-call]]: a correct-looking answer about the wrong subject).
623
+ */
624
+ <span className="autob-cond-any" title="Any one of these is a match">
625
+ any of {p.value.length}
626
+ {discover?.guard?.maxValues ? ` of ${discover.guard.maxValues}` : ""}
627
+ </span>
628
+ ) : null}
629
+ <button
630
+ type="button"
631
+ className="autob-cond-x"
632
+ aria-label={`Remove this condition on ${label}`}
633
+ title="Remove this condition"
634
+ onClick={() => removeAt(i)}
635
+ >
636
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
637
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
638
+ </svg>
639
+ </button>
640
+ </div>
641
+ );
642
+ };
643
+
644
+ const fieldRow = (row: FieldRow) => {
645
+ const on = row.at.length > 0;
646
+ return (
647
+ <div className={"autob-tgl" + (on ? " is-on" : "")} key={row.name}>
648
+ <div className="autob-tgl-head">
649
+ <button
650
+ type="button"
651
+ className={"auto-step-switch autob-tgl-switch" + (on ? " is-on" : "")}
652
+ aria-pressed={on}
653
+ aria-label={`${on ? "Stop searching" : "Search"} on ${row.label}`}
654
+ title={`${on ? "Stop searching" : "Search"} on ${row.label}`}
655
+ onClick={() => toggleField(row)}
656
+ >
657
+ <span className="auto-step-switch-knob" />
658
+ </button>
659
+ <span className="autob-tgl-mark">
660
+ <FilterMark name={row.name} />
661
+ </span>
662
+ {/* ⭐ THE HUMAN LABEL (owner item 1: "wtf is id/fbid").
663
+ This used to render the vendor's own column name verbatim, and the comment
664
+ defending it was RIGHT about the reason β€” a refusal names the field, and a label
665
+ that reads differently makes the error unmatchable. So the label did not move
666
+ alone: `field_label()` is what the SERVER's refusals use too, which is the only
667
+ version of this change that does not trade one confusion for another. */}
668
+ <span className="autob-tgl-name" title={row.hint || undefined}>
669
+ {row.label}
670
+ </span>
671
+ {/*
672
+ ⚠ ONE CHIP, AND IT MARKS THE MINORITY. The first version chipped every
673
+ non-narrowing field "broad" AND every unpopulated one "no values seen" β€”
674
+ which put two chips on 18 of the 21 rows, and one of them repeated the group
675
+ heading the row was already sitting under. A mark that is on almost every row
676
+ stops being a mark. Read off the screenshot; no assertion could have said it.
677
+
678
+ So: the group label carries POPULATED (it is what the groups ARE), and the
679
+ chip carries NARROWING, inverted to mark the five that DO narrow. That is the
680
+ actionable half β€” the server refuses a filter with no narrowing condition, so
681
+ "these are the ones that satisfy it" is the sentence a user needs, and
682
+ "this one does not" is not.
683
+ */}
684
+ {row.narrowing === true ? (
685
+ <span
686
+ className="autob-tgl-flag is-narrow"
687
+ title="A search needs at least one condition like this."
688
+ >
689
+ narrows
690
+ </span>
691
+ ) : null}
692
+ </div>
693
+ {on ? (
694
+ <div className="autob-tgl-body">
695
+ {row.at.map((i) => condition(i, row.label, row))}
696
+ {row.hint ? <p className="autob-tgl-hint">{row.hint}</p> : null}
697
+ <button
698
+ type="button"
699
+ className="autob-cond-add"
700
+ onClick={() =>
701
+ onPreds([...preds, { name: row.name, operator: firstOperator(discover, row.name) }])
702
+ }
703
+ >
704
+ Another condition on {row.label}
705
+ </button>
706
+ </div>
707
+ ) : null}
708
+ </div>
709
+ );
710
+ };
711
+
712
+ return (
713
+ <>
714
+ <div className="auto-field">
715
+ <label htmlFor="auto-records">How many profiles to fetch</label>
716
+ <input
717
+ id="auto-records"
718
+ className="auto-input"
719
+ type="number"
720
+ min={1}
721
+ max={maxRecords}
722
+ value={recordsLimit}
723
+ onChange={(e) => onRecordsLimit(Number(e.target.value) || 1)}
724
+ />
725
+ </div>
726
+ {/* Owner item 5: "Stop at the 'A search must be at most 500 profiles a run'". The two
727
+ sentences that followed explained the vendor's billing model to somebody who wants a
728
+ list of florists. */}
729
+ <p className="auto-hint">At most {maxRecords.toLocaleString()} profiles a run.</p>
730
+
731
+ <h3>Conditions</h3>
732
+ <div className="auto-field autob-match">
733
+ <label htmlFor="auto-joinop">Match</label>
734
+ <select
735
+ id="auto-joinop"
736
+ className="auto-input"
737
+ value={joinOp}
738
+ onChange={(e) => onJoinOp(e.target.value)}
739
+ >
740
+ <option value="and">All of them</option>
741
+ <option value="or">Any of them</option>
742
+ </select>
743
+ </div>
744
+
745
+ {!rows.length ? (
746
+ <p className="auto-note">
747
+ The searchable fields have not loaded yet.
748
+ </p>
749
+ ) : null}
750
+
751
+ {withValues.length ? (
752
+ <div className="autob-tglgroup">
753
+ <p
754
+ className="autob-tglgroup-label"
755
+ title="Most accounts have this filled in."
756
+ >
757
+ Usually filled in
758
+ </p>
759
+ {withValues.map(fieldRow)}
760
+ </div>
761
+ ) : null}
762
+
763
+ {rest.length ? (
764
+ <div className="autob-tglgroup">
765
+ <p
766
+ className="autob-tglgroup-label"
767
+ title={
768
+ knownMeta
769
+ ? "Most accounts leave these blank, so a condition here can return nothing."
770
+ : "We have not measured how often these are filled in."
771
+ }
772
+ >
773
+ {knownMeta ? "Often blank" : "Not measured"}
774
+ </p>
775
+ {rest.map(fieldRow)}
776
+ </div>
777
+ ) : null}
778
+
779
+ {strays.length ? (
780
+ <div className="autob-tglgroup">
781
+ <p className="autob-tglgroup-label">Not in the searchable list</p>
782
+ {strays.map(({ p, i }) => (
783
+ <div className="autob-tgl is-on is-stray" key={`stray-${i}`}>
784
+ <div className="autob-tgl-head">
785
+ {/* A stray gets a mark too β€” "every filter row" includes the ones the vendor no
786
+ longer offers, and a row missing the icon its neighbours have would read as a
787
+ different KIND of thing rather than as a field that fell out of the list. It
788
+ draws the neutral fallback by construction: a stray is, by definition, not in
789
+ the vocabulary this component has arms for. */}
790
+ <span className="autob-tgl-mark">
791
+ <FilterMark name={p.name} />
792
+ </span>
793
+ <span className="autob-tgl-name">{p.name}</span>
794
+ <span className="autob-tgl-flag is-stray" title="The server will refuse this condition by name.">
795
+ not searchable
796
+ </span>
797
+ </div>
798
+ <div className="autob-tgl-body">{condition(i, p.name)}</div>
799
+ </div>
800
+ ))}
801
+ </div>
802
+ ) : null}
803
+
804
+ {/* The consequence kept, the mechanism dropped: a condition on an often-blank field
805
+ returning nothing is a thing that will happen to somebody and confuse them. Why the
806
+ search is slow when broad is our problem, not theirs. */}
807
+ <p className="auto-hint">
808
+ Conditions on often-blank fields can come back with nothing.
809
+ </p>
810
+
811
+ <h3>What it costs</h3>
812
+ <div className="auto-head-actions">
813
+ <button type="button" className="auto-btn" onClick={onEstimate}>
814
+ Estimate this search
815
+ </button>
816
+ </div>
817
+ {estimate ? (
818
+ <p className="auto-hint">
819
+ About <strong>${estimate.usd}</strong> for {estimate.records} profiles, at $
820
+ {estimate.unitUsd} each.{" "}
821
+ {/*
822
+ THE CAVEAT IS NOT OPTIONAL. The vendor never quotes a price before a run and this
823
+ deployment cannot read its own balance, so presenting this as a billed figure
824
+ would be inventing a measurement.
825
+ */}
826
+ <strong>This is an estimate</strong> β€” {estimate.note}.
827
+ </p>
828
+ ) : null}
829
+
830
+ {/* ⭐ WAVE 27 Β· OWNER ITEM 29 β€” THE BIG EDITOR, rendered ONCE for the whole panel.
831
+ β›” Not one overlay per condition row: `AnchoredOverlay` mounts a body portal and
832
+ installs document-level dismiss/focus handlers, so N of them would be N listener
833
+ stacks fighting over one Escape key. One overlay, told which row it is editing.
834
+ ⚠ `role="dialog"`, not "menu": it holds a text field, and the menu layer's arrow-key
835
+ handling would take the cursor keys away from the text being typed. */}
836
+ {big ? (
837
+ <AnchoredOverlay
838
+ anchor={big.anchor}
839
+ className="autoc-bigedit"
840
+ placement="right-start"
841
+ role="dialog"
842
+ ariaLabel={`Value for ${big.label}`}
843
+ onDismiss={() => setBig(null)}
844
+ dataKind="find-value-editor"
845
+ >
846
+ <label htmlFor="autoc-bigedit-text">{big.label}</label>
847
+ <textarea
848
+ id="autoc-bigedit-text"
849
+ className="autoc-bigedit-text"
850
+ data-overlay-autofocus
851
+ autoFocus
852
+ rows={7}
853
+ spellCheck={false}
854
+ value={big.text}
855
+ placeholder={big.multi ? "floral, flower, wedding florist, event styling" : ""}
856
+ onChange={(e) => setBig((cur) => (cur ? { ...cur, text: e.target.value } : cur))}
857
+ onKeyDown={(e) => {
858
+ // Escape abandons; Ctrl/Cmd+Enter commits. A bare Enter types a NEWLINE, because
859
+ // this is a textarea and the whole reason it exists is that the value is long.
860
+ if (e.key === "Escape") setBig(null);
861
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
862
+ setAt(big.index, { value: parseValue(big.text, big.multi) });
863
+ setBig(null);
864
+ }
865
+ }}
866
+ />
867
+ {/* The same sentence the rail input's placeholder makes, said where there is room
868
+ for it: a comma list is several values, and the server turns them into an OR. */}
869
+ {big.multi ? (
870
+ <p className="auto-hint">
871
+ Separate values with commas β€” the search matches any of them.
872
+ </p>
873
+ ) : null}
874
+ <div className="auto-head-actions">
875
+ <button
876
+ type="button"
877
+ className="auto-btn auto-btn--primary"
878
+ onClick={() => {
879
+ setAt(big.index, { value: parseValue(big.text, big.multi) });
880
+ setBig(null);
881
+ }}
882
+ >
883
+ Done
884
+ </button>
885
+ <button type="button" className="auto-btn" onClick={() => setBig(null)}>
886
+ Cancel
887
+ </button>
888
+ </div>
889
+ </AnchoredOverlay>
890
+ ) : null}
891
+ </>
892
+ );
893
+ }
web/src/automation/automationApi.ts CHANGED
@@ -409,8 +409,8 @@ export interface Action {
409
  }
410
 
411
  /** `flow.ending` (C5) β€” what happens to a record that reaches the end. */
412
- export interface Flow {
413
- actions: Action[];
414
  }
415
 
416
  /**
@@ -434,20 +434,36 @@ export interface ActionCatalogRow {
434
  * still renders every group it sends.
435
  */
436
  groupOrder?: number;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  }
438
 
439
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
440
- export interface FlowVocab {
441
  condOps: string[];
442
  nullaryCondOps: string[];
443
  maxCondDepth: number;
444
  maxCondChildren: number;
445
  maxGroupDepth: number;
446
- maxActions: number;
447
- /** Legacy read compatibility only; the server no longer sends Board review vocabulary. */
448
- reviewDeciders?: string[];
449
- /** Legacy read compatibility only; the server no longer sends Board review readiness. */
450
- aiReady?: boolean;
451
  /**
452
  * ⚠ PER-DEPLOYMENT, AND HONEST RATHER THAN DECORATIVE. With no LLM key configured the engine
453
  * holds every card for a human β€” so an enabled-looking "decided by AI" control would promise
 
409
  }
410
 
411
  /** `flow.ending` (C5) β€” what happens to a record that reaches the end. */
412
+ export interface Flow {
413
+ actions: Action[];
414
  }
415
 
416
  /**
 
434
  * still renders every group it sends.
435
  */
436
  groupOrder?: number;
437
+ /**
438
+ * ⭐ WAVE 27 Β· OWNER ITEM 33 / CONTRACT C4 β€” WHICH CONNECTOR OWNS THIS ACTION.
439
+ *
440
+ * The trigger vocabulary has carried this since wave 24 (`TriggerOption.connector`, which is
441
+ * what nests Gmail / Webhooks / Scraper / TikTok under the Connector heading); the ACTION
442
+ * catalog did not, and that gap IS item 33 β€” the Bright Data and Apify actions sat loose in
443
+ * "Connected" beside unrelated rows, where the Airtable reference
444
+ * (`reference/Airtable Automation 10.png`) shows one row per connector with its own submenu.
445
+ *
446
+ * β›” OPTIONAL, AND THE CLIENT INVENTS NOTHING. B stamps `{key:'scraper', label:'Scraper'}` on
447
+ * the BD/Apify rows server-side; until that lands every row simply has no connector and the
448
+ * menu is exactly the flat list it is today. There is NO client-side list of which kinds are
449
+ * "scraper" actions β€” that would be a second copy of the catalog's own structure, which is
450
+ * the mistake `groupOrder`'s note one field up already records.
451
+ */
452
+ connector?: { key: string; label: string };
453
  }
454
 
455
  /** The builder's own ceilings, server-declared so the client never hard-codes the same numbers. */
456
+ export interface FlowVocab {
457
  condOps: string[];
458
  nullaryCondOps: string[];
459
  maxCondDepth: number;
460
  maxCondChildren: number;
461
  maxGroupDepth: number;
462
+ maxActions: number;
463
+ /** Legacy read compatibility only; the server no longer sends Board review vocabulary. */
464
+ reviewDeciders?: string[];
465
+ /** Legacy read compatibility only; the server no longer sends Board review readiness. */
466
+ aiReady?: boolean;
467
  /**
468
  * ⚠ PER-DEPLOYMENT, AND HONEST RATHER THAN DECORATIVE. With no LLM key configured the engine
469
  * holds every card for a human β€” so an enabled-looking "decided by AI" control would promise
web/src/automation/steps.ts CHANGED
@@ -1,359 +1,422 @@
1
- // ---------------------------------------------------------------------------
2
- // automation/steps.ts β€” the arithmetic behind the numbered Steps (owner ruling R9).
3
- //
4
- // Pure functions, deliberately separate from the component: both of the things in
5
- // here are the kind that go subtly wrong (a step number, a cron round-trip) and
6
- // stay wrong invisibly, so they are written where they can be read on their own.
7
- //
8
- // ⚠ NOTHING HERE INVENTS A STEP. The node list, its order and its `col` all come
9
- // from the server's `engine.graph()` β€” the same module that RUNS the steps β€” and
10
- // this file only counts them (contract C6). A client-side second idea of what the
11
- // steps are is the exact drift the split was built to prevent; the rationale is
12
- // written at AutomationCreate.tsx:1-13.
13
- // ---------------------------------------------------------------------------
14
- import type { Action, Branch, Cond, GraphNode, TriggerOption } from "./automationApi";
15
-
16
- /**
17
- * The branches of an If / then, TOLERATING the pre-wave-24 `{cond, actions}` shape on READ.
18
- *
19
- * ⚠ THIS MIRRORS `automation_engine.group_branches` AND THE DUPLICATION IS DELIBERATE, which is
20
- * worth defending because this file's own header forbids a second idea of the server's data. It
21
- * is a READ-SIDE TOLERANCE, not a second validator: it never decides what is legal, and every
22
- * write still goes to `clean_actions`, which returns the one canonical shape. The alternative is
23
- * strictly worse β€” a group stored in the old shape would render with no branches and no children,
24
- * so a live automation's actions would simply VANISH from the screen while running perfectly.
25
- * A migration the server performs on write and the client tolerates on read is the pair that has
26
- * no window; trusting `branches` alone has one, for exactly as long as a definition sits unsaved.
27
- */
28
- export function groupBranches(a: Action): Branch[] {
29
- const cfg = (a?.config || {}) as {
30
- branches?: Branch[];
31
- cond?: Cond | null;
32
- actions?: Action[];
33
- };
34
- if (Array.isArray(cfg.branches)) return cfg.branches;
35
- // The pre-wave-24 shape, read as the one branch the engine migrates it to.
36
- if (Array.isArray(cfg.actions))
37
- return [{ id: "b1", label: "A", cond: cfg.cond ?? null, actions: cfg.actions }];
38
- return [];
39
- }
40
-
41
- /**
42
- * R8's STEP NUMBERS for a whole flow, keyed by action id.
43
- *
44
- * THE RULING, and each clause is a line here:
45
- * Β· the TRIGGER is unnumbered β€” it is not in this map at all, and the card carries the word
46
- * "Trigger" instead. (This REVERSES wave 21's R9, "Step 1 is always the Trigger".)
47
- * Β· the first action is 1, the second 2, …
48
- * Β· an If / then occupies ONE number. Its branches are alternatives, not later steps, so they
49
- * consume no numbers of their own.
50
- * Β· a branch's children are numbered RELATIVE TO THEIR BRANCH β€” the fork at step 2 gives every
51
- * one of its branches a `2.1`, a `2.2`, and so on. Two branches therefore both contain a
52
- * `2.1`, which is correct rather than colliding: they are alternatives in lettered lanes and
53
- * only one of them ever runs (the engine takes the first matching branch and breaks).
54
- *
55
- * β›” IT DOES NOT LETTER THE BRANCHES, and that is a change from the contract text. `clean_actions`
56
- * assigns the letter server-side (`_branch_letter`, and "Otherwise" for the null-cond last leg),
57
- * preserving any label the client sends β€” so the letter rides on `Branch.label` and a second
58
- * lettering here would be exactly the client-copy-of-a-server-vocabulary this wave keeps deleting.
59
- * The client sends an EMPTY label and renders what comes back, which also means letters re-flow
60
- * correctly when a branch is deleted instead of going stale.
61
- */
62
- export function numberActions(actions: Action[]): Map<string, string> {
63
- const out = new Map<string, string>();
64
- const walk = (list: Action[], prefix: string) => {
65
- (list || []).forEach((a, i) => {
66
- const n = prefix ? `${prefix}.${i + 1}` : String(i + 1);
67
- out.set(a.id, n);
68
- if (a.kind === "group")
69
- for (const br of groupBranches(a)) walk(br.actions || [], n);
70
- });
71
- };
72
- walk(actions || [], "");
73
- return out;
74
- }
75
-
76
- export interface Step {
77
- node: GraphNode;
78
- /** The number the card carries. */
79
- n: number;
80
- /** True when this node shares its position with the one before it β€” an ALTERNATIVE, not a next. */
81
- alt: boolean;
82
- }
83
-
84
- /**
85
- * Number the server's nodes for display.
86
- *
87
- * ⭐ THE NUMBER IS `col + 1`, NOT the array index, and that is the honest one. The
88
- * `field_instagram` graph forks: `capture_paid` and `capture_anon` both sit at
89
- * `col: 3` because they are the SAME position in the flow reached two ways (the
90
- * paid rung answers, or the anonymous ladder does). Numbering them 4 and 5 would
91
- * state a sequence that never happens. They share a number and the second is
92
- * marked `alt`, so the list says "either of these" rather than "then".
93
- *
94
- * "Step 1 is always the Trigger" (R9) therefore falls out of the payload β€” the
95
- * trigger is the node at `col: 0` β€” instead of being asserted by this client. If
96
- * the engine ever emits something else first, the UI shows what the engine does.
97
- */
98
- export function numberSteps(nodes: GraphNode[]): Step[] {
99
- return (nodes || []).map((node, i) => {
100
- const col = typeof node.col === "number" ? node.col : i;
101
- const before = i > 0 ? nodes[i - 1] : null;
102
- const beforeCol = before && typeof before.col === "number" ? before.col : -1;
103
- return { node, n: col + 1, alt: i > 0 && beforeCol === col };
104
- });
105
- }
106
-
107
- /**
108
- * Move `dragId` into `dropId`'s position within one list (owner item 11).
109
- *
110
- * β›” IT RETURNS `null` RATHER THAN THE LIST UNCHANGED, and the distinction is what keeps a
111
- * pointless PATCH off the wire: "these two are the same card", "one of them is not in this list"
112
- * and "here is your new order" are three different answers, and collapsing the first two into
113
- * "the order you already had" would have the caller write the flow back to the server on every
114
- * aborted drag. The caller writes only when this says something happened.
115
- *
116
- * THE CARD LANDS EXACTLY WHERE THE TARGET WAS, in both directions β€” splice out, then splice in at
117
- * the target's ORIGINAL index. Dragging down, the target shifts up; dragging up, it shifts down.
118
- * (The tempting version β€” insert at the target's index *after* the removal β€” is off by one when
119
- * dragging downwards and drops the card one slot short of where the pointer is, which reads as
120
- * the drag not having worked.)
121
- */
122
- export function reorderList<T extends { id: string }>(
123
- list: T[],
124
- dragId: string,
125
- dropId: string
126
- ): T[] | null {
127
- if (!dragId || !dropId || dragId === dropId) return null;
128
- const src = list || [];
129
- const from = src.findIndex((x) => x.id === dragId);
130
- const to = src.findIndex((x) => x.id === dropId);
131
- if (from < 0 || to < 0) return null;
132
- const next = [...src];
133
- const [moved] = next.splice(from, 1);
134
- if (!moved) return null;
135
- next.splice(to, 0, moved);
136
- return next;
137
- }
138
-
139
- /** One Properties section under "How this fetches": a panel, and every node that opens it. */
140
- export interface PanelGroup {
141
- /** The panel key β€” what the caller passes to `renderNodeBody`. */
142
- panel: string;
143
- /** Every machine node whose `panel` is this one, in the server's own order. */
144
- nodes: GraphNode[];
145
- }
146
-
147
- /**
148
- * The machine steps, GROUPED BY PANEL (item 5, contract C-CFG).
149
- *
150
- * β›” GROUPED, NEVER MAPPED ONE-TO-ONE, and the difference is a defect rather than a nicety.
151
- * `panel` is MANY-TO-ONE over nodes, which is easy to miss because the old surface hid it: you
152
- * clicked ONE card and got ONE panel. `field_instagram` gives `capture`, `capture_paid`,
153
- * `capture_anon` AND `capture_metrics` all `panel: "capture"` (`automation_engine.py:3334-3352`),
154
- * and `discover_instagram` gives both of its nodes `panel: "find"` (`:3381`/`:3387`). So a body
155
- * rendered per NODE would print the capture prose four times over, and β€” the one that actually
156
- * loses work β€” mount the 21-toggle discovery filter TWICE against a single `preds` array, two
157
- * editors writing one piece of state where whichever blurred last silently wins.
158
- *
159
- * The detail panel has always joined on `panel` and never on node id (`AutomationDetail`'s own
160
- * note says so); this keeps that law now that the panels are no longer reached by clicking a card.
161
- *
162
- * ORDER IS THE SERVER'S β€” first appearance wins, so the sections read in flow order rather than
163
- * in whatever order a Map or a sort would produce.
164
- */
165
- export function groupByPanel(nodes: GraphNode[]): PanelGroup[] {
166
- const order: string[] = [];
167
- const byPanel = new Map<string, GraphNode[]>();
168
- for (const n of nodes || []) {
169
- // `panel` falls back to the id exactly as `graph()`'s own `node()` does (`panel or nid`),
170
- // so a node the engine ships without one still gets its own section instead of joining
171
- // every other panel-less node under the empty string.
172
- const key = n.panel || n.id;
173
- const seen = byPanel.get(key);
174
- if (seen) seen.push(n);
175
- else {
176
- byPanel.set(key, [n]);
177
- order.push(key);
178
- }
179
- }
180
- return order.map((panel) => ({ panel, nodes: byPanel.get(panel) || [] }));
181
- }
182
-
183
- /** How the Step-1 card is currently set: what it repeats on, and at what time. */
184
- export interface TriggerShape {
185
- /** `day` = every day Β· `0`..`6` = that weekday (cron numbering, 0 = Sunday) Β· `custom` = a cron only. */
186
- every: string;
187
- /** `HH:MM`, empty when the cron does not express a single fire time. */
188
- time: string;
189
- }
190
-
191
- const DAILY = /^(\d{1,2}) (\d{1,2}) \* \* \*$/;
192
- const WEEKLY = /^(\d{1,2}) (\d{1,2}) \* \* ([0-7])$/;
193
-
194
- function two(n: number): string {
195
- return String(n).padStart(2, "0");
196
- }
197
-
198
- /**
199
- * A stored cron β†’ the controls that can express it.
200
- *
201
- * β›” ANYTHING THIS CANNOT EXPRESS COMES BACK AS `custom`, NEVER AS THE FIRST OPTION.
202
- * A `<select>` whose value matches no `<option>` renders the first one, and the next
203
- * Save then writes a schedule nobody chose β€” the defect this codebase has already
204
- * paid for twice ([[cg-condition-builder-items]]; the two `(not in this database)`
205
- * options in AutomationDetail exist for the same reason). A quarter-hourly weekday
206
- * cron is a legal schedule the engine runs happily; the editor's job is to leave it
207
- * alone, not to quietly turn it into "every day at 08:00".
208
- *
209
- * (Written without the literal cron string on purpose β€” a step-slash inside a block
210
- * comment ENDS the comment, and the compiler's 20 cascading errors say nothing about
211
- * the cron.)
212
- */
213
- export function readCron(cron: string): TriggerShape {
214
- const raw = String(cron || "").trim();
215
- const daily = DAILY.exec(raw);
216
- if (daily) {
217
- const [, m, h] = daily;
218
- if (Number(h) <= 23 && Number(m) <= 59) return { every: "day", time: `${two(Number(h))}:${two(Number(m))}` };
219
- }
220
- const weekly = WEEKLY.exec(raw);
221
- if (weekly) {
222
- const [, m, h, d] = weekly;
223
- if (Number(h) <= 23 && Number(m) <= 59) {
224
- return { every: String(Number(d) % 7), time: `${two(Number(h))}:${two(Number(m))}` };
225
- }
226
- }
227
- return { every: "custom", time: "" };
228
- }
229
-
230
- /** The controls β†’ a cron string. `custom` keeps whatever the user typed, untouched. */
231
- export function writeCron(every: string, time: string, custom: string): string {
232
- if (every === "custom") return String(custom || "").trim();
233
- const [h, m] = String(time || "06:00").split(":");
234
- const hh = Math.min(23, Math.max(0, Number(h) || 0));
235
- const mm = Math.min(59, Math.max(0, Number(m) || 0));
236
- return every === "day" ? `${mm} ${hh} * * *` : `${mm} ${hh} * * ${Number(every) || 0}`;
237
- }
238
-
239
- /** The weekday options, in the order a week is read rather than in cron's 0-first order. */
240
- export const WEEKDAYS: { value: string; label: string }[] = [
241
- { value: "1", label: "Every Monday" },
242
- { value: "2", label: "Every Tuesday" },
243
- { value: "3", label: "Every Wednesday" },
244
- { value: "4", label: "Every Thursday" },
245
- { value: "5", label: "Every Friday" },
246
- { value: "6", label: "Every Saturday" },
247
- { value: "0", label: "Every Sunday" },
248
- ];
249
-
250
- // ── WAVE 25 Β· C2: THE GROUPED TRIGGER PICKER'S ARITHMETIC ───────────────────────────────────
251
- //
252
- // β›” WHY THIS IS HERE AND NOT IN THE COMPONENT. Both functions below are the kind that go subtly
253
- // wrong and stay wrong INVISIBLY β€” a group silently sorted first, a stored trigger silently
254
- // rendering as nothing β€” and this file exists precisely so that class can be executed under node
255
- // by `verify_steps.py` instead of eyeballed in a screenshot. It is also D-58's minimum: the
256
- // builder's largest surface has had no gate but `tsc` and eyes, and the picker's grouped and
257
- // SELECTED states are the two things a screenshot is worst at proving (the selected row looks
258
- // identical to an unselected one at a glance, which is the whole scar).
259
- //
260
- // ⚠ NOTHING HERE INVENTS A GROUP, A CAPTION OR AN ORDER β€” the file header's law, applied. Every
261
- // one of the three rides `TriggerOption` from `routes_automation._triggers_vocab`.
262
-
263
- /** One connector's rows inside the Connector group (Gmail / Webhooks / Scraper / TikTok). */
264
- export interface TriggerSubGroup {
265
- key: string;
266
- label: string;
267
- rows: TriggerOption[];
268
- }
269
-
270
- /** One rendered section of the picker: a caption, the rows under it, and any connector nests. */
271
- export interface TriggerGroup {
272
- /** The server's group id. `""` when the server sent none β€” one unlabelled section. */
273
- key: string;
274
- /** The server's caption, PRINTED verbatim. `""` renders no heading, never an invented one. */
275
- label: string;
276
- order: number;
277
- /** Rows that hang directly off the group head. */
278
- rows: TriggerOption[];
279
- /** Connector nests, in first-appearance order. Empty for Time and Database. */
280
- sub: TriggerSubGroup[];
281
- }
282
-
283
- /**
284
- * The picker's sections: CATEGORY first (Time / Database / Connector), then the trigger, with
285
- * connector rows nested under their own product name.
286
- *
287
- * β›” ORDER COMES FROM `groupOrder`, AND AN ABSENT ONE SORTS **LAST**. This is the
288
- * `ACTION_GROUP_ORDER` rule and it is the safe direction: an unordered group is one this client
289
- * has no server opinion about, and putting it at the TOP of the menu would present the
290
- * unclassified thing as the primary answer. Ties keep FIRST-APPEARANCE order, which is what the
291
- * old `<select>` used as its only ordering and is still the honest fallback for a server that
292
- * sends no `groupOrder` at all.
293
- *
294
- * β›” AND NOTHING IS DROPPED. Every option in, every option out β€” `planned` and `ready:false` rows
295
- * included, because a picker that hides them answers "can it run when an email arrives?" with
296
- * silence, and the question then gets asked again (R9's precedent). Faded is a wall the server
297
- * enforces at `clean_trigger`; a shorter list is a lie.
298
- */
299
- export function groupTriggers(options: TriggerOption[]): TriggerGroup[] {
300
- const out: TriggerGroup[] = [];
301
- const byKey = new Map<string, TriggerGroup>();
302
- for (const t of options) {
303
- const key = t.group || "";
304
- let g = byKey.get(key);
305
- if (!g) {
306
- g = {
307
- key,
308
- // ⚠ `groupLabel` OR NOTHING. Falling back to `t.group` would print the id ("connector")
309
- // as a heading β€” a client inventing the server's wording, one `||` at a time.
310
- label: t.groupLabel || "",
311
- order: typeof t.groupOrder === "number" ? t.groupOrder : Number.MAX_SAFE_INTEGER,
312
- rows: [],
313
- sub: [],
314
- };
315
- byKey.set(key, g);
316
- out.push(g);
317
- }
318
- const c = t.connector;
319
- if (c && c.key) {
320
- let s = g.sub.find((x) => x.key === c.key);
321
- if (!s) {
322
- s = { key: c.key, label: c.label || c.key, rows: [] };
323
- g.sub.push(s);
324
- }
325
- s.rows.push(t);
326
- } else {
327
- g.rows.push(t);
328
- }
329
- }
330
- // A STABLE sort by order alone: `Array.prototype.sort` is stable in every runtime this ships to
331
- // (ES2019 mandates it), so equal orders keep the first-appearance sequence above.
332
- return out.sort((a, b) => a.order - b.order);
333
- }
334
-
335
- /**
336
- * The option the picker must render as SELECTED β€” and this function is the scar, in one place.
337
- *
338
- * β›” A `<select>` WHOSE `value` MATCHES NO `<option>` RENDERS THE FIRST ONE. A custom listbox
339
- * fails DIFFERENTLY and worse: it renders nothing selected, looks unconfigured, and the next
340
- * patch writes the blank over a real stored key. This repo has paid for the first form twice
341
- * (`enters_view`'s view id, and the condition builder's operator) and the control it replaces
342
- * carried an explicit guard for it.
343
- *
344
- * So: a stored key the server did not offer comes back as a SYNTHETIC row saying so, never as
345
- * `null`. `null` means one thing only β€” nothing is picked yet β€” which is also what R14 gates the
346
- * Configuration section on, so conflating the two would hide a configured automation's settings.
347
- */
348
- export function selectedTrigger(
349
- options: TriggerOption[],
350
- key: string
351
- ): TriggerOption | null {
352
- if (!key) return null;
353
- const hit = options.find((t) => t.key === key);
354
- if (hit) return hit;
355
- // ⚠ `ready: false` and NO `detail`: this row is not something the reader can act on, and
356
- // inventing a description for a trigger this deployment does not offer would be the client
357
- // speaking for a server that said nothing.
358
- return { key, label: `${key} (not offered here)`, ready: false };
359
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // automation/steps.ts β€” the arithmetic behind the numbered Steps (owner ruling R9).
3
+ //
4
+ // Pure functions, deliberately separate from the component: both of the things in
5
+ // here are the kind that go subtly wrong (a step number, a cron round-trip) and
6
+ // stay wrong invisibly, so they are written where they can be read on their own.
7
+ //
8
+ // ⚠ NOTHING HERE INVENTS A STEP. The node list, its order and its `col` all come
9
+ // from the server's `engine.graph()` β€” the same module that RUNS the steps β€” and
10
+ // this file only counts them (contract C6). A client-side second idea of what the
11
+ // steps are is the exact drift the split was built to prevent; the rationale is
12
+ // written at AutomationCreate.tsx:1-13.
13
+ // ---------------------------------------------------------------------------
14
+ import type { Action, ActionCatalogRow, Branch, Cond, GraphNode, TriggerOption }
15
+ from "./automationApi";
16
+
17
+ /**
18
+ * The branches of an If / then, TOLERATING the pre-wave-24 `{cond, actions}` shape on READ.
19
+ *
20
+ * ⚠ THIS MIRRORS `automation_engine.group_branches` AND THE DUPLICATION IS DELIBERATE, which is
21
+ * worth defending because this file's own header forbids a second idea of the server's data. It
22
+ * is a READ-SIDE TOLERANCE, not a second validator: it never decides what is legal, and every
23
+ * write still goes to `clean_actions`, which returns the one canonical shape. The alternative is
24
+ * strictly worse β€” a group stored in the old shape would render with no branches and no children,
25
+ * so a live automation's actions would simply VANISH from the screen while running perfectly.
26
+ * A migration the server performs on write and the client tolerates on read is the pair that has
27
+ * no window; trusting `branches` alone has one, for exactly as long as a definition sits unsaved.
28
+ */
29
+ export function groupBranches(a: Action): Branch[] {
30
+ const cfg = (a?.config || {}) as {
31
+ branches?: Branch[];
32
+ cond?: Cond | null;
33
+ actions?: Action[];
34
+ };
35
+ if (Array.isArray(cfg.branches)) return cfg.branches;
36
+ // The pre-wave-24 shape, read as the one branch the engine migrates it to.
37
+ if (Array.isArray(cfg.actions))
38
+ return [{ id: "b1", label: "A", cond: cfg.cond ?? null, actions: cfg.actions }];
39
+ return [];
40
+ }
41
+
42
+ /**
43
+ * R8's STEP NUMBERS for a whole flow, keyed by action id.
44
+ *
45
+ * THE RULING, and each clause is a line here:
46
+ * Β· the TRIGGER is unnumbered β€” it is not in this map at all, and the card carries the word
47
+ * "Trigger" instead. (This REVERSES wave 21's R9, "Step 1 is always the Trigger".)
48
+ * Β· the first action is 1, the second 2, …
49
+ * Β· an If / then occupies ONE number. Its branches are alternatives, not later steps, so they
50
+ * consume no numbers of their own.
51
+ * Β· a branch's children are numbered RELATIVE TO THEIR BRANCH β€” the fork at step 2 gives every
52
+ * one of its branches a `2.1`, a `2.2`, and so on. Two branches therefore both contain a
53
+ * `2.1`, which is correct rather than colliding: they are alternatives in lettered lanes and
54
+ * only one of them ever runs (the engine takes the first matching branch and breaks).
55
+ *
56
+ * β›” IT DOES NOT LETTER THE BRANCHES, and that is a change from the contract text. `clean_actions`
57
+ * assigns the letter server-side (`_branch_letter`, and "Otherwise" for the null-cond last leg),
58
+ * preserving any label the client sends β€” so the letter rides on `Branch.label` and a second
59
+ * lettering here would be exactly the client-copy-of-a-server-vocabulary this wave keeps deleting.
60
+ * The client sends an EMPTY label and renders what comes back, which also means letters re-flow
61
+ * correctly when a branch is deleted instead of going stale.
62
+ */
63
+ export function numberActions(actions: Action[]): Map<string, string> {
64
+ const out = new Map<string, string>();
65
+ const walk = (list: Action[], prefix: string) => {
66
+ (list || []).forEach((a, i) => {
67
+ const n = prefix ? `${prefix}.${i + 1}` : String(i + 1);
68
+ out.set(a.id, n);
69
+ if (a.kind === "group")
70
+ for (const br of groupBranches(a)) walk(br.actions || [], n);
71
+ });
72
+ };
73
+ walk(actions || [], "");
74
+ return out;
75
+ }
76
+
77
+ export interface Step {
78
+ node: GraphNode;
79
+ /** The number the card carries. */
80
+ n: number;
81
+ /** True when this node shares its position with the one before it β€” an ALTERNATIVE, not a next. */
82
+ alt: boolean;
83
+ }
84
+
85
+ /**
86
+ * Number the server's nodes for display.
87
+ *
88
+ * ⭐ THE NUMBER IS `col + 1`, NOT the array index, and that is the honest one. The
89
+ * `field_instagram` graph forks: `capture_paid` and `capture_anon` both sit at
90
+ * `col: 3` because they are the SAME position in the flow reached two ways (the
91
+ * paid rung answers, or the anonymous ladder does). Numbering them 4 and 5 would
92
+ * state a sequence that never happens. They share a number and the second is
93
+ * marked `alt`, so the list says "either of these" rather than "then".
94
+ *
95
+ * "Step 1 is always the Trigger" (R9) therefore falls out of the payload β€” the
96
+ * trigger is the node at `col: 0` β€” instead of being asserted by this client. If
97
+ * the engine ever emits something else first, the UI shows what the engine does.
98
+ */
99
+ export function numberSteps(nodes: GraphNode[]): Step[] {
100
+ return (nodes || []).map((node, i) => {
101
+ const col = typeof node.col === "number" ? node.col : i;
102
+ const before = i > 0 ? nodes[i - 1] : null;
103
+ const beforeCol = before && typeof before.col === "number" ? before.col : -1;
104
+ return { node, n: col + 1, alt: i > 0 && beforeCol === col };
105
+ });
106
+ }
107
+
108
+ /**
109
+ * Move `dragId` into `dropId`'s position within one list (owner item 11).
110
+ *
111
+ * β›” IT RETURNS `null` RATHER THAN THE LIST UNCHANGED, and the distinction is what keeps a
112
+ * pointless PATCH off the wire: "these two are the same card", "one of them is not in this list"
113
+ * and "here is your new order" are three different answers, and collapsing the first two into
114
+ * "the order you already had" would have the caller write the flow back to the server on every
115
+ * aborted drag. The caller writes only when this says something happened.
116
+ *
117
+ * THE CARD LANDS EXACTLY WHERE THE TARGET WAS, in both directions β€” splice out, then splice in at
118
+ * the target's ORIGINAL index. Dragging down, the target shifts up; dragging up, it shifts down.
119
+ * (The tempting version β€” insert at the target's index *after* the removal β€” is off by one when
120
+ * dragging downwards and drops the card one slot short of where the pointer is, which reads as
121
+ * the drag not having worked.)
122
+ */
123
+ export function reorderList<T extends { id: string }>(
124
+ list: T[],
125
+ dragId: string,
126
+ dropId: string
127
+ ): T[] | null {
128
+ if (!dragId || !dropId || dragId === dropId) return null;
129
+ const src = list || [];
130
+ const from = src.findIndex((x) => x.id === dragId);
131
+ const to = src.findIndex((x) => x.id === dropId);
132
+ if (from < 0 || to < 0) return null;
133
+ const next = [...src];
134
+ const [moved] = next.splice(from, 1);
135
+ if (!moved) return null;
136
+ next.splice(to, 0, moved);
137
+ return next;
138
+ }
139
+
140
+ /** One Properties section under "How this fetches": a panel, and every node that opens it. */
141
+ export interface PanelGroup {
142
+ /** The panel key β€” what the caller passes to `renderNodeBody`. */
143
+ panel: string;
144
+ /** Every machine node whose `panel` is this one, in the server's own order. */
145
+ nodes: GraphNode[];
146
+ }
147
+
148
+ /**
149
+ * The machine steps, GROUPED BY PANEL (item 5, contract C-CFG).
150
+ *
151
+ * β›” GROUPED, NEVER MAPPED ONE-TO-ONE, and the difference is a defect rather than a nicety.
152
+ * `panel` is MANY-TO-ONE over nodes, which is easy to miss because the old surface hid it: you
153
+ * clicked ONE card and got ONE panel. `field_instagram` gives `capture`, `capture_paid`,
154
+ * `capture_anon` AND `capture_metrics` all `panel: "capture"` (`automation_engine.py:3334-3352`),
155
+ * and `discover_instagram` gives both of its nodes `panel: "find"` (`:3381`/`:3387`). So a body
156
+ * rendered per NODE would print the capture prose four times over, and β€” the one that actually
157
+ * loses work β€” mount the 21-toggle discovery filter TWICE against a single `preds` array, two
158
+ * editors writing one piece of state where whichever blurred last silently wins.
159
+ *
160
+ * The detail panel has always joined on `panel` and never on node id (`AutomationDetail`'s own
161
+ * note says so); this keeps that law now that the panels are no longer reached by clicking a card.
162
+ *
163
+ * ORDER IS THE SERVER'S β€” first appearance wins, so the sections read in flow order rather than
164
+ * in whatever order a Map or a sort would produce.
165
+ */
166
+ export function groupByPanel(nodes: GraphNode[]): PanelGroup[] {
167
+ const order: string[] = [];
168
+ const byPanel = new Map<string, GraphNode[]>();
169
+ for (const n of nodes || []) {
170
+ // `panel` falls back to the id exactly as `graph()`'s own `node()` does (`panel or nid`),
171
+ // so a node the engine ships without one still gets its own section instead of joining
172
+ // every other panel-less node under the empty string.
173
+ const key = n.panel || n.id;
174
+ const seen = byPanel.get(key);
175
+ if (seen) seen.push(n);
176
+ else {
177
+ byPanel.set(key, [n]);
178
+ order.push(key);
179
+ }
180
+ }
181
+ return order.map((panel) => ({ panel, nodes: byPanel.get(panel) || [] }));
182
+ }
183
+
184
+ /** How the Step-1 card is currently set: what it repeats on, and at what time. */
185
+ export interface TriggerShape {
186
+ /** `day` = every day Β· `0`..`6` = that weekday (cron numbering, 0 = Sunday) Β· `custom` = a cron only. */
187
+ every: string;
188
+ /** `HH:MM`, empty when the cron does not express a single fire time. */
189
+ time: string;
190
+ }
191
+
192
+ const DAILY = /^(\d{1,2}) (\d{1,2}) \* \* \*$/;
193
+ const WEEKLY = /^(\d{1,2}) (\d{1,2}) \* \* ([0-7])$/;
194
+
195
+ function two(n: number): string {
196
+ return String(n).padStart(2, "0");
197
+ }
198
+
199
+ /**
200
+ * A stored cron β†’ the controls that can express it.
201
+ *
202
+ * β›” ANYTHING THIS CANNOT EXPRESS COMES BACK AS `custom`, NEVER AS THE FIRST OPTION.
203
+ * A `<select>` whose value matches no `<option>` renders the first one, and the next
204
+ * Save then writes a schedule nobody chose β€” the defect this codebase has already
205
+ * paid for twice ([[cg-condition-builder-items]]; the two `(not in this database)`
206
+ * options in AutomationDetail exist for the same reason). A quarter-hourly weekday
207
+ * cron is a legal schedule the engine runs happily; the editor's job is to leave it
208
+ * alone, not to quietly turn it into "every day at 08:00".
209
+ *
210
+ * (Written without the literal cron string on purpose β€” a step-slash inside a block
211
+ * comment ENDS the comment, and the compiler's 20 cascading errors say nothing about
212
+ * the cron.)
213
+ */
214
+ export function readCron(cron: string): TriggerShape {
215
+ const raw = String(cron || "").trim();
216
+ const daily = DAILY.exec(raw);
217
+ if (daily) {
218
+ const [, m, h] = daily;
219
+ if (Number(h) <= 23 && Number(m) <= 59) return { every: "day", time: `${two(Number(h))}:${two(Number(m))}` };
220
+ }
221
+ const weekly = WEEKLY.exec(raw);
222
+ if (weekly) {
223
+ const [, m, h, d] = weekly;
224
+ if (Number(h) <= 23 && Number(m) <= 59) {
225
+ return { every: String(Number(d) % 7), time: `${two(Number(h))}:${two(Number(m))}` };
226
+ }
227
+ }
228
+ return { every: "custom", time: "" };
229
+ }
230
+
231
+ /** The controls β†’ a cron string. `custom` keeps whatever the user typed, untouched. */
232
+ export function writeCron(every: string, time: string, custom: string): string {
233
+ if (every === "custom") return String(custom || "").trim();
234
+ const [h, m] = String(time || "06:00").split(":");
235
+ const hh = Math.min(23, Math.max(0, Number(h) || 0));
236
+ const mm = Math.min(59, Math.max(0, Number(m) || 0));
237
+ return every === "day" ? `${mm} ${hh} * * *` : `${mm} ${hh} * * ${Number(every) || 0}`;
238
+ }
239
+
240
+ /** The weekday options, in the order a week is read rather than in cron's 0-first order. */
241
+ export const WEEKDAYS: { value: string; label: string }[] = [
242
+ { value: "1", label: "Every Monday" },
243
+ { value: "2", label: "Every Tuesday" },
244
+ { value: "3", label: "Every Wednesday" },
245
+ { value: "4", label: "Every Thursday" },
246
+ { value: "5", label: "Every Friday" },
247
+ { value: "6", label: "Every Saturday" },
248
+ { value: "0", label: "Every Sunday" },
249
+ ];
250
+
251
+ // ── WAVE 25 Β· C2: THE GROUPED TRIGGER PICKER'S ARITHMETIC ───────────────────────────────────
252
+ //
253
+ // β›” WHY THIS IS HERE AND NOT IN THE COMPONENT. Both functions below are the kind that go subtly
254
+ // wrong and stay wrong INVISIBLY β€” a group silently sorted first, a stored trigger silently
255
+ // rendering as nothing β€” and this file exists precisely so that class can be executed under node
256
+ // by `verify_steps.py` instead of eyeballed in a screenshot. It is also D-58's minimum: the
257
+ // builder's largest surface has had no gate but `tsc` and eyes, and the picker's grouped and
258
+ // SELECTED states are the two things a screenshot is worst at proving (the selected row looks
259
+ // identical to an unselected one at a glance, which is the whole scar).
260
+ //
261
+ // ⚠ NOTHING HERE INVENTS A GROUP, A CAPTION OR AN ORDER β€” the file header's law, applied. Every
262
+ // one of the three rides `TriggerOption` from `routes_automation._triggers_vocab`.
263
+
264
+ /** One connector's rows inside the Connector group (Gmail / Webhooks / Scraper / TikTok). */
265
+ export interface TriggerSubGroup {
266
+ key: string;
267
+ label: string;
268
+ rows: TriggerOption[];
269
+ }
270
+
271
+ /** One rendered section of the picker: a caption, the rows under it, and any connector nests. */
272
+ export interface TriggerGroup {
273
+ /** The server's group id. `""` when the server sent none β€” one unlabelled section. */
274
+ key: string;
275
+ /** The server's caption, PRINTED verbatim. `""` renders no heading, never an invented one. */
276
+ label: string;
277
+ order: number;
278
+ /** Rows that hang directly off the group head. */
279
+ rows: TriggerOption[];
280
+ /** Connector nests, in first-appearance order. Empty for Time and Database. */
281
+ sub: TriggerSubGroup[];
282
+ }
283
+
284
+ /**
285
+ * The picker's sections: CATEGORY first (Time / Database / Connector), then the trigger, with
286
+ * connector rows nested under their own product name.
287
+ *
288
+ * β›” ORDER COMES FROM `groupOrder`, AND AN ABSENT ONE SORTS **LAST**. This is the
289
+ * `ACTION_GROUP_ORDER` rule and it is the safe direction: an unordered group is one this client
290
+ * has no server opinion about, and putting it at the TOP of the menu would present the
291
+ * unclassified thing as the primary answer. Ties keep FIRST-APPEARANCE order, which is what the
292
+ * old `<select>` used as its only ordering and is still the honest fallback for a server that
293
+ * sends no `groupOrder` at all.
294
+ *
295
+ * β›” AND NOTHING IS DROPPED. Every option in, every option out β€” `planned` and `ready:false` rows
296
+ * included, because a picker that hides them answers "can it run when an email arrives?" with
297
+ * silence, and the question then gets asked again (R9's precedent). Faded is a wall the server
298
+ * enforces at `clean_trigger`; a shorter list is a lie.
299
+ */
300
+ export function groupTriggers(options: TriggerOption[]): TriggerGroup[] {
301
+ const out: TriggerGroup[] = [];
302
+ const byKey = new Map<string, TriggerGroup>();
303
+ for (const t of options) {
304
+ const key = t.group || "";
305
+ let g = byKey.get(key);
306
+ if (!g) {
307
+ g = {
308
+ key,
309
+ // ⚠ `groupLabel` OR NOTHING. Falling back to `t.group` would print the id ("connector")
310
+ // as a heading β€” a client inventing the server's wording, one `||` at a time.
311
+ label: t.groupLabel || "",
312
+ order: typeof t.groupOrder === "number" ? t.groupOrder : Number.MAX_SAFE_INTEGER,
313
+ rows: [],
314
+ sub: [],
315
+ };
316
+ byKey.set(key, g);
317
+ out.push(g);
318
+ }
319
+ const c = t.connector;
320
+ if (c && c.key) {
321
+ let s = g.sub.find((x) => x.key === c.key);
322
+ if (!s) {
323
+ s = { key: c.key, label: c.label || c.key, rows: [] };
324
+ g.sub.push(s);
325
+ }
326
+ s.rows.push(t);
327
+ } else {
328
+ g.rows.push(t);
329
+ }
330
+ }
331
+ // A STABLE sort by order alone: `Array.prototype.sort` is stable in every runtime this ships to
332
+ // (ES2019 mandates it), so equal orders keep the first-appearance sequence above.
333
+ return out.sort((a, b) => a.order - b.order);
334
+ }
335
+
336
+ /** One rendered section of the ACTION menu: the same shape `TriggerGroup` has, over the
337
+ * catalog's rows. */
338
+ export interface ActionGroup {
339
+ key: string;
340
+ order: number;
341
+ rows: ActionCatalogRow[];
342
+ sub: { key: string; label: string; rows: ActionCatalogRow[] }[];
343
+ }
344
+
345
+ /**
346
+ * ⭐ WAVE 27 Β· OWNER ITEM 33 / CONTRACT C4 β€” the action menu, with connector rows NESTED.
347
+ *
348
+ * β›” THE SAME ARITHMETIC AS `groupTriggers`, AND THAT IS THE POINT. The trigger picker has
349
+ * nested connectors since wave 24; the action menu is the identical question about a different
350
+ * catalog, and C4 asks for the nest to be "driven by server data, name-for-name". So this reads
351
+ * `row.connector` exactly as `groupTriggers` reads `t.connector`, sorts by `groupOrder` with an
352
+ * absent one LAST, and holds no list of connector names of its own.
353
+ *
354
+ * ⚠ INERT UNTIL THE SERVER STAMPS THE ROWS, by construction rather than by a flag: with no
355
+ * `connector` on any row, every row lands in `rows` and `sub` is empty β€” which renders the flat
356
+ * menu that ships today. That is what lets this half land before B's, instead of two sessions
357
+ * having to meet in the middle.
358
+ *
359
+ * β›” THE GROUP KEY IS ALSO ITS LABEL here, unlike triggers. The action catalog's `group` IS the
360
+ * printed caption ("Web action", "Database", "Connected", "Advanced logic") β€” the server sends
361
+ * no separate `groupLabel` for actions β€” so this returns `key` and the caller prints it. Adding
362
+ * a `label` member that merely copied `key` would invent a second name for one string.
363
+ */
364
+ export function groupActions(rows: ActionCatalogRow[]): ActionGroup[] {
365
+ const out: ActionGroup[] = [];
366
+ const byKey = new Map<string, ActionGroup>();
367
+ for (const c of rows) {
368
+ const key = c.group || "";
369
+ let g = byKey.get(key);
370
+ if (!g) {
371
+ g = {
372
+ key,
373
+ order: typeof c.groupOrder === "number" ? c.groupOrder : Number.MAX_SAFE_INTEGER,
374
+ rows: [],
375
+ sub: [],
376
+ };
377
+ byKey.set(key, g);
378
+ out.push(g);
379
+ }
380
+ const con = c.connector;
381
+ if (con && con.key) {
382
+ let s = g.sub.find((x) => x.key === con.key);
383
+ if (!s) {
384
+ // The server's LABEL, or its key when it sent none β€” never a prettified guess.
385
+ s = { key: con.key, label: con.label || con.key, rows: [] };
386
+ g.sub.push(s);
387
+ }
388
+ s.rows.push(c);
389
+ } else {
390
+ g.rows.push(c);
391
+ }
392
+ }
393
+ // Stable by order alone (ES2019 mandates a stable sort), so equal orders keep first
394
+ // appearance β€” the same rule `groupTriggers` states one function up.
395
+ return out.sort((a, b) => a.order - b.order);
396
+ }
397
+
398
+ /**
399
+ * The option the picker must render as SELECTED β€” and this function is the scar, in one place.
400
+ *
401
+ * β›” A `<select>` WHOSE `value` MATCHES NO `<option>` RENDERS THE FIRST ONE. A custom listbox
402
+ * fails DIFFERENTLY and worse: it renders nothing selected, looks unconfigured, and the next
403
+ * patch writes the blank over a real stored key. This repo has paid for the first form twice
404
+ * (`enters_view`'s view id, and the condition builder's operator) and the control it replaces
405
+ * carried an explicit guard for it.
406
+ *
407
+ * So: a stored key the server did not offer comes back as a SYNTHETIC row saying so, never as
408
+ * `null`. `null` means one thing only β€” nothing is picked yet β€” which is also what R14 gates the
409
+ * Configuration section on, so conflating the two would hide a configured automation's settings.
410
+ */
411
+ export function selectedTrigger(
412
+ options: TriggerOption[],
413
+ key: string
414
+ ): TriggerOption | null {
415
+ if (!key) return null;
416
+ const hit = options.find((t) => t.key === key);
417
+ if (hit) return hit;
418
+ // ⚠ `ready: false` and NO `detail`: this row is not something the reader can act on, and
419
+ // inventing a description for a trigger this deployment does not offer would be the client
420
+ // speaking for a server that said nothing.
421
+ return { key, label: `${key} (not offered here)`, ready: false };
422
+ }
web/src/customer-grid/ColumnMenu.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/JsonViewer.tsx CHANGED
@@ -1,481 +1,1015 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / JsonViewer.tsx β€” ⭐ wave-23 C7 (owner item 5 / ruling R5).
3
- //
4
- // THE BIG VIEWER a json cell opens on click. One component, reached from two
5
- // places (the grid cell's click path and the record drawer's value slot), for
6
- // the reason `assetUrl` is one resolver: two readers of the same document that
7
- // disagree about how it folds is a bug nobody can see in either one alone.
8
- //
9
- // The document is a STRING at rest (the scalar Row contract β€” see the `json`
10
- // note in types.ts), so everything here is text in and text out. Nothing in
11
- // this file ever writes a parsed OBJECT back.
12
- //
13
- // THREE decisions worth stating, because each has a plausible alternative:
14
- //
15
- // 1. THE RAW TAB IS THE EDITOR, and there is no field-by-field one. A form
16
- // over a document whose shape nobody declared would have to invent that
17
- // shape from the current value β€” so adding a key would mean editing the
18
- // form's idea of the schema, and the first machine write with a different
19
- // shape would silently drop what it did not recognise.
20
- // 2. PARSE ON SAVE, REFUSE WITH A SENTENCE. Never repair, never re-indent on
21
- // the way in: `{a:1}` is not JSON and quietly "fixing" it to `{"a":1}`
22
- // teaches a person their typo was fine, until the day a value cannot be
23
- // guessed. The host applies the same rule at the write wall (C7), so a
24
- // refusal here says the same thing the server would.
25
- // 3. THE TREE IS READ-ONLY and collapses by DEPTH, not by hand-kept state per
26
- // node beyond what the reader opens. A 200-key payload that arrives fully
27
- // expanded is a scroll bar, not a document.
28
- // ---------------------------------------------------------------------------
29
-
30
- import { useEffect, useId, useMemo, useRef, useState } from "react";
31
- import type { ReactNode } from "react";
32
- import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
33
- import { dayText, jsonParse, jsonPretty, MAX_JSON_BYTES, postsWindowOf } from "./display";
34
- import type { PostSummary, PostsWindow } from "./display";
35
-
36
- /** Bytes, not characters β€” the host's cap is on the stored UTF-8, and a
37
- * document of 20,000 emoji is 80 KB. Counting `length` would let a value
38
- * through here that the server then refuses, which is the one refusal a user
39
- * cannot act on (nothing on screen said it was too big). */
40
- export function jsonByteLength(text: string): number {
41
- return typeof TextEncoder === "undefined"
42
- ? text.length
43
- : new TextEncoder().encode(text).length;
44
- }
45
-
46
- /** The one-line summary in the modal's header: what this document IS. */
47
- export function jsonSummary(text: string): string {
48
- const parsed = jsonParse(text);
49
- const bytes = jsonByteLength(text);
50
- const size = bytes < 1024 ? `${bytes} bytes` : `${(bytes / 1024).toFixed(1)} KB`;
51
- if (String(text ?? "").trim() === "") return "Empty";
52
- if (!parsed.ok) return `Not valid JSON Β· ${size}`;
53
- const v = parsed.value;
54
- if (Array.isArray(v)) return `${v.length} item${v.length === 1 ? "" : "s"} Β· ${size}`;
55
- if (v !== null && typeof v === "object") {
56
- const n = Object.keys(v as object).length;
57
- return `${n} key${n === 1 ? "" : "s"} Β· ${size}`;
58
- }
59
- return `${v === null ? "null" : typeof v} Β· ${size}`;
60
- }
61
-
62
- // --- the tree ---------------------------------------------------------------
63
-
64
- /** How deep a node is open when the viewer mounts. Two levels shows the shape
65
- * of every payload this product actually receives (an object of objects) and
66
- * stops before the leaf spam of a scraped array. */
67
- const OPEN_TO_DEPTH = 2;
68
-
69
- function isBranch(v: unknown): v is Record<string, unknown> | unknown[] {
70
- return v !== null && typeof v === "object";
71
- }
72
-
73
- /** The value's own text, in its own ink class. Strings keep their quotes: a
74
- * bare `12` and a `"12"` are different documents and the tree is where that
75
- * difference has to be visible. */
76
- function Leaf({ v }: { v: unknown }): ReactNode {
77
- if (v === null) return <span className="cg-json-null">null</span>;
78
- if (typeof v === "string") return <span className="cg-json-str">&quot;{v}&quot;</span>;
79
- if (typeof v === "number") return <span className="cg-json-num">{String(v)}</span>;
80
- if (typeof v === "boolean") return <span className="cg-json-bool">{String(v)}</span>;
81
- return <span className="cg-json-str">{String(v)}</span>;
82
- }
83
-
84
- function Node({
85
- name,
86
- value,
87
- depth,
88
- last,
89
- }: {
90
- name: string | null;
91
- value: unknown;
92
- depth: number;
93
- last: boolean;
94
- }) {
95
- const [open, setOpen] = useState(depth < OPEN_TO_DEPTH);
96
- if (!isBranch(value))
97
- return (
98
- <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
99
- {name !== null && <span className="cg-json-key">{name}</span>}
100
- {name !== null && <span className="cg-json-punct">: </span>}
101
- <Leaf v={value} />
102
- {!last && <span className="cg-json-punct">,</span>}
103
- </div>
104
- );
105
-
106
- const array = Array.isArray(value);
107
- const entries: [string, unknown][] = array
108
- ? (value as unknown[]).map((v, i) => [String(i), v])
109
- : Object.entries(value as Record<string, unknown>);
110
- const openMark = array ? "[" : "{";
111
- const closeMark = array ? "]" : "}";
112
-
113
- return (
114
- <>
115
- <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
116
- <button
117
- type="button"
118
- className={"cg-json-twist" + (open ? " is-open" : "")}
119
- onClick={() => setOpen((o) => !o)}
120
- aria-expanded={open}
121
- aria-label={`${open ? "Collapse" : "Expand"} ${name ?? "the document"}`}
122
- >
123
- <svg viewBox="0 0 16 16" width="10" height="10" aria-hidden>
124
- <path
125
- d="M6 4l4 4-4 4"
126
- fill="none"
127
- stroke="currentColor"
128
- strokeWidth="1.6"
129
- strokeLinecap="round"
130
- strokeLinejoin="round"
131
- />
132
- </svg>
133
- </button>
134
- {name !== null && <span className="cg-json-key">{name}</span>}
135
- {name !== null && <span className="cg-json-punct">: </span>}
136
- <span className="cg-json-punct">{openMark}</span>
137
- {/* Collapsed, the count IS the content β€” a bare `{…}` tells a reader
138
- nothing about whether opening it is worth the click. */}
139
- {!open && (
140
- <span className="cg-json-count">
141
- {entries.length} {array ? (entries.length === 1 ? "item" : "items")
142
- : entries.length === 1 ? "key" : "keys"}
143
- </span>
144
- )}
145
- {!open && <span className="cg-json-punct">{closeMark}{last ? "" : ","}</span>}
146
- </div>
147
- {open &&
148
- entries.map(([k, v], i) => (
149
- <Node
150
- key={k}
151
- name={array ? null : k}
152
- value={v}
153
- depth={depth + 1}
154
- last={i === entries.length - 1}
155
- />
156
- ))}
157
- {open && (
158
- <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
159
- <span className="cg-json-punct">
160
- {closeMark}
161
- {last ? "" : ","}
162
- </span>
163
- </div>
164
- )}
165
- </>
166
- );
167
- }
168
-
169
- // --- ⭐ wave-26 item 8 (contract C2): the POSTS reading ----------------------
170
- //
171
- // The owner's ask was that the `posts` cell "reads as POSTS, not raw JSON". The
172
- // tree is a fine JSON reader and a poor post reader: `posts β†’ 3 β†’ caption` is
173
- // four clicks to see one line somebody wrote. So a posts document opens on its
174
- // OWN tab, and the tree and raw tabs stay exactly where they were β€” this adds a
175
- // reading, it does not replace the document.
176
- //
177
- // β›” AN ABSENT METRIC RENDERS AS NOTHING, NEVER AS A ZERO. `postsWindowOf` keeps
178
- // them `undefined` when unbought (C2: metrics are ABSENT KEYS when
179
- // `postMetrics` was off), and the row below tests each one before painting it.
180
- // A `0 views` on a post that was never measured is a fabricated measurement,
181
- // and it is indistinguishable on screen from a real one.
182
-
183
- /** One metric, or nothing at all. The guard IS the feature β€” see above. */
184
- function Metric({ label, value }: { label: string; value: number | undefined }) {
185
- if (value === undefined) return null;
186
- return (
187
- <span className="cg-posts-metric">
188
- <b>{value.toLocaleString()}</b> {label}
189
- </span>
190
- );
191
- }
192
-
193
- function PostRow({ post }: { post: PostSummary }) {
194
- const day = post.posted_at ? dayText(post.posted_at) : "";
195
- /* ⚠ A ROW WITH NOTHING READABLE IS POSSIBLE BY CONSTRUCTION. `postsWindowOf` accepts any
196
- object inside `posts` β€” deliberately, because refusing an unrecognised member would hide a
197
- post the engine wrote in a shape this file has not learned yet. The engine's own writer
198
- fills these, so in practice it takes a hand-edited document to get here; when it happens the
199
- card must not paint as an empty rectangle, which reads as a rendering bug rather than as a
200
- thin record. The shortcode is the post's identity and is the honest last resort. */
201
- const bare = !day && !post.type && !post.caption && !post.url;
202
- return (
203
- <div className="cg-posts-row">
204
- {bare && (
205
- <span className="cg-posts-kind">{post.shortcode ?? "A post with no details"}</span>
206
- )}
207
- <div className="cg-posts-head">
208
- {day && <span className="cg-posts-day">{day}</span>}
209
- {/* The type is the post's own word (`reel`, `image`) β€” shown verbatim rather
210
- than mapped, because a vocabulary this file invents would drift from the
211
- vendor's the first time they add one. */}
212
- {post.type && <span className="cg-posts-kind">{post.type}</span>}
213
- {post.url && (
214
- <a
215
- className="cg-posts-link"
216
- href={post.url}
217
- target="_blank"
218
- rel="noopener noreferrer"
219
- >
220
- Open
221
- </a>
222
- )}
223
- </div>
224
- {post.caption && <p className="cg-posts-caption">{post.caption}</p>}
225
- {/* β›” NO `views` ROW HERE (2026-08-08 β€” instagram-capture.md Β§4e). The vendor's `views` is
226
- delivered at ACCOUNT grain: one value repeated across every reel of a creator. Rendering
227
- it beside this post's own likes and comments is exactly the reading that made it look
228
- like a post metric in the first place, and this panel would have kept saying so after
229
- the column was retired. `plays` is the honest per-reel field; it is omitted rather than
230
- shown empty, because a blank metric chip claims we looked and got zero. */}
231
- <div className="cg-posts-metrics">
232
- <Metric label="likes" value={post.likes} />
233
- <Metric label="comments" value={post.comments} />
234
- </div>
235
- </div>
236
- );
237
- }
238
-
239
- function PostsPanel({ window: w }: { window: PostsWindow }) {
240
- if (w.posts.length === 0)
241
- return <p className="cg-json-empty">No posts were captured for this profile.</p>;
242
- return (
243
- <div className="cg-posts">
244
- {/* β›” THE ONE SENTENCE THIS PANEL OWES A READER (DESIGN.md Β§4 β€” never over-explain).
245
- It is a WINDOW: the append tables keep the whole series (R1/R3), so a reader must not
246
- take these for every post the account has ever made. And when metrics were not bought,
247
- saying so is the only way an empty metrics row reads as "not measured" rather than
248
- "measured as nothing". */}
249
- <p className="cg-posts-note">
250
- The {w.posts.length} most recent post{w.posts.length === 1 ? "" : "s"}
251
- {w.as_of ? `, as of ${dayText(w.as_of)}` : ""}
252
- {w.metrics ? "." : " β€” engagement was not collected for this run."}
253
- </p>
254
- <ul className="cg-posts-list">
255
- {w.posts.map((p, i) => (
256
- <li key={p.shortcode ?? p.url ?? i} className="cg-posts-item">
257
- <PostRow post={p} />
258
- </li>
259
- ))}
260
- </ul>
261
- </div>
262
- );
263
- }
264
-
265
- // --- the modal --------------------------------------------------------------
266
-
267
- export interface JsonViewerProps {
268
- /** The column's own label β€” the modal's title. */
269
- label: string;
270
- /** The stored document, as a string. */
271
- value: string;
272
- /** Absent = read-only (the field is machine-owned, Odoo-sourced, or this
273
- * viewer permits the reader nothing). Present = the raw tab is an editor. */
274
- onSave?: (next: string) => void;
275
- onClose: () => void;
276
- }
277
-
278
- export default function JsonViewer({ label, value, onSave, onClose }: JsonViewerProps) {
279
- const panelRef = useRef<HTMLDivElement>(null);
280
- const titleId = useId();
281
- const tabsId = useId();
282
- /** `null` = nobody has chosen one, so the landing tab is derived (see `shown`). */
283
- const [picked, setPicked] = useState<"posts" | "tree" | "raw" | null>(null);
284
- const [draft, setDraft] = useState(value);
285
- const [error, setError] = useState("");
286
- const [copied, setCopied] = useState(false);
287
-
288
- // ⚠ The draft re-seeds when the CELL changes underneath (a machine write
289
- // landing while the viewer is open), and only then β€” keying on `value` alone
290
- // would also stamp on every keystroke's re-render if a parent echoed it back.
291
- useEffect(() => {
292
- setDraft(value);
293
- setError("");
294
- }, [value]);
295
-
296
- useOverlayLayer({
297
- panelRef,
298
- onDismiss: onClose,
299
- dismissOnOutside: true,
300
- initialFocus: "[data-overlay-autofocus]",
301
- trapFocus: true,
302
- });
303
-
304
- const parsed = useMemo(() => jsonParse(draft), [draft]);
305
- const dirty = draft !== value;
306
- /* ⭐ Item 8 β€” is this document a POSTS WINDOW? Read off the DRAFT, so editing the raw tab into
307
- (or out of) the shape moves the tab with it rather than stranding a Posts tab over a
308
- document that is no longer one. */
309
- const posts = useMemo(
310
- () => (parsed.ok ? postsWindowOf(parsed.value) : null),
311
- [parsed]
312
- );
313
- /* The tab set is DERIVED from the document, and the shown tab is derived from the set β€” never
314
- corrected by an effect. Two things fall out of that, both of which an effect gets wrong:
315
-
316
- ⚠ POSTS IS THE LANDING TAB when the document is one, which is the whole of the owner's ask
317
- ("reads as POSTS, not raw JSON"). A `useState` initialiser cannot do it: the cell value
318
- arrives asynchronously and can change under an open viewer, so it would seed "tree" for
319
- exactly the render that matters and the reader would meet the JSON first.
320
- ⚠ A tab the reader PICKED wins while it still exists β€” and stops winning the moment it does
321
- not. Editing a posts document into something else on the raw tab would otherwise leave the
322
- panel rendering a Posts tab that is no longer in the list above it. */
323
- const tabs = posts ? (["posts", "tree", "raw"] as const) : (["tree", "raw"] as const);
324
- const shown =
325
- picked && (tabs as readonly string[]).includes(picked) ? picked : posts ? "posts" : "tree";
326
-
327
- const save = () => {
328
- const text = draft.trim();
329
- // Blank is a legal edit: it clears the cell, which is how a document is
330
- // removed. Everything else must parse before it is allowed to leave here.
331
- if (text !== "") {
332
- if (!jsonParse(text).ok) {
333
- setError("That is not valid JSON β€” nothing was saved. Check for a trailing comma, a "
334
- + "single quote, or an unquoted key.");
335
- return;
336
- }
337
- const bytes = jsonByteLength(text);
338
- if (bytes > MAX_JSON_BYTES) {
339
- setError(`That document is ${(bytes / 1024).toFixed(1)} KB and the limit is 32 KB β€” `
340
- + "nothing was saved.");
341
- return;
342
- }
343
- }
344
- setError("");
345
- onSave?.(text);
346
- onClose();
347
- };
348
-
349
- const copy = () => {
350
- void navigator.clipboard?.writeText(draft).then(
351
- () => {
352
- setCopied(true);
353
- window.setTimeout(() => setCopied(false), 1400);
354
- },
355
- () => setError("The browser refused clipboard access β€” select the raw text and copy it.")
356
- );
357
- };
358
-
359
- return (
360
- <BodyPortal>
361
- <div className="cg-record-backdrop">
362
- <div
363
- className="cg-json-modal"
364
- ref={panelRef}
365
- role="dialog"
366
- aria-modal="true"
367
- aria-labelledby={titleId}
368
- data-overlay-kind="json-viewer"
369
- tabIndex={-1}
370
- >
371
- <div className="cg-json-head">
372
- <div>
373
- <div className="cg-json-title" id={titleId}>{label}</div>
374
- {/* The summary is the ONE explanatory line (DESIGN.md Β§4): what
375
- this document is, not what a JSON field is for. */}
376
- <div className="cg-json-sub">{jsonSummary(draft)}</div>
377
- </div>
378
- <div className="cg-json-headacts">
379
- <button type="button" className="cg-json-btn" onClick={copy}>
380
- {copied ? "Copied" : "Copy"}
381
- </button>
382
- <button
383
- type="button"
384
- className="cg-icon-btn"
385
- onClick={onClose}
386
- aria-label="Close viewer"
387
- >
388
- Γ—
389
- </button>
390
- </div>
391
- </div>
392
-
393
- <div className="cg-record-tabs" role="tablist" aria-label="Document view">
394
- {tabs.map((k) => (
395
- <button
396
- key={k}
397
- type="button"
398
- role="tab"
399
- id={`${tabsId}-${k}`}
400
- aria-selected={shown === k}
401
- aria-controls={`${tabsId}-panel`}
402
- className={"cg-record-tab" + (shown === k ? " is-on" : "")}
403
- onClick={() => setPicked(k)}
404
- data-overlay-autofocus={k === tabs[0] ? true : undefined}
405
- >
406
- {k === "posts" ? "Posts" : k === "tree" ? "Tree" : "Raw"}
407
- </button>
408
- ))}
409
- </div>
410
-
411
- <div
412
- className="cg-json-body"
413
- id={`${tabsId}-panel`}
414
- role="tabpanel"
415
- aria-labelledby={`${tabsId}-${shown}`}
416
- >
417
- {shown === "posts" && posts ? (
418
- <PostsPanel window={posts} />
419
- ) : shown === "tree" ? (
420
- parsed.ok ? (
421
- <div className="cg-json-tree">
422
- <Node name={null} value={parsed.value} depth={0} last />
423
- </div>
424
- ) : (
425
- // β›” NOT an empty tree and NOT a repaired one. A document the app
426
- // cannot open is a fact about the value, and the raw tab is where
427
- // it gets read β€” so the empty state POINTS THERE rather than
428
- // describing what JSON is.
429
- <p className="cg-json-empty">
430
- {draft.trim() === ""
431
- ? "Nothing here yet."
432
- : "This value is not valid JSON β€” read it on the Raw tab."}
433
- </p>
434
- )
435
- ) : onSave ? (
436
- <textarea
437
- className="cg-json-raw"
438
- value={draft}
439
- spellCheck={false}
440
- onChange={(e) => {
441
- setDraft(e.target.value);
442
- if (error) setError("");
443
- }}
444
- aria-label={`${label} raw JSON`}
445
- />
446
- ) : (
447
- <pre className="cg-json-raw cg-json-raw--ro">{jsonPretty(draft)}</pre>
448
- )}
449
- </div>
450
-
451
- {(error || (onSave && dirty)) && (
452
- <div className="cg-json-foot">
453
- {error ? (
454
- <span className="cg-json-err">{error}</span>
455
- ) : (
456
- <span className="cg-json-hint">Unsaved changes</span>
457
- )}
458
- {onSave && (
459
- <span className="cg-json-footacts">
460
- <button
461
- type="button"
462
- className="cg-json-btn"
463
- onClick={() => {
464
- setDraft(value);
465
- setError("");
466
- }}
467
- >
468
- Revert
469
- </button>
470
- <button type="button" className="cg-json-btn cg-json-btn--primary" onClick={save}>
471
- Save
472
- </button>
473
- </span>
474
- )}
475
- </div>
476
- )}
477
- </div>
478
- </div>
479
- </BodyPortal>
480
- );
481
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / JsonViewer.tsx β€” ⭐ wave-23 C7 (owner item 5 / ruling R5).
3
+ //
4
+ // THE BIG VIEWER a json cell opens on click. One component, reached from two
5
+ // places (the grid cell's click path and the record drawer's value slot), for
6
+ // the reason `assetUrl` is one resolver: two readers of the same document that
7
+ // disagree about how it folds is a bug nobody can see in either one alone.
8
+ //
9
+ // The document is a STRING at rest (the scalar Row contract β€” see the `json`
10
+ // note in types.ts), so everything here is text in and text out. Nothing in
11
+ // this file ever writes a parsed OBJECT back.
12
+ //
13
+ // THREE decisions worth stating, because each has a plausible alternative:
14
+ //
15
+ // 1. THE RAW TAB IS THE EDITOR, and there is no field-by-field one. A form
16
+ // over a document whose shape nobody declared would have to invent that
17
+ // shape from the current value β€” so adding a key would mean editing the
18
+ // form's idea of the schema, and the first machine write with a different
19
+ // shape would silently drop what it did not recognise.
20
+ // 2. PARSE ON SAVE, REFUSE WITH A SENTENCE. Never repair, never re-indent on
21
+ // the way in: `{a:1}` is not JSON and quietly "fixing" it to `{"a":1}`
22
+ // teaches a person their typo was fine, until the day a value cannot be
23
+ // guessed. The host applies the same rule at the write wall (C7), so a
24
+ // refusal here says the same thing the server would.
25
+ // 3. THE TREE COLLAPSES BY DEPTH, not by hand-kept state per node beyond what
26
+ // the reader opens. A 200-key payload that arrives fully expanded is a
27
+ // scroll bar, not a document.
28
+ //
29
+ // ⭐ WAVE-27 item 13 (owner ruling R13) AMENDS decision 3: THE TREE IS EDITABLE
30
+ // NOW, two-way synced with the raw tab, and the raw text WINS on conflict.
31
+ //
32
+ // "Wins" is structural rather than a rule anybody has to enforce: `draft` (the
33
+ // raw text) is the single source of truth, `parsed` is derived from it, and the
34
+ // tree is a projection of `parsed`. A tree edit writes a new VALUE at a path,
35
+ // re-serialises the whole document and sets `draft` β€” so there is never a second
36
+ // copy of the document to reconcile, and a draft that stops parsing simply has
37
+ // no tree to show (the raw tab is where it gets read, exactly as before).
38
+ //
39
+ // β›” WHAT THE TREE EDITS, AND WHAT IT DELIBERATELY DOES NOT. Leaf VALUES, in
40
+ // place, keeping each leaf's own type. NOT keys, NOT structure, NOT a value's
41
+ // type β€” those stay on the raw tab, and that is decision 1 above still standing:
42
+ // a form that can add a key has to have an opinion about the document's shape,
43
+ // and nobody declared one. Editing `"12"` into `12` is a shape change, so it is
44
+ // a raw edit; editing `"Anna"` into `"Anne"` is a value change, so it is here.
45
+ // ---------------------------------------------------------------------------
46
+
47
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
48
+ import type { ReactNode } from "react";
49
+ import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
50
+ import { dayText, jsonParse, jsonPretty, MAX_JSON_BYTES, postsWindowOf } from "./display";
51
+ import type { PostSummary, PostsWindow } from "./display";
52
+
53
+ /** Bytes, not characters β€” the host's cap is on the stored UTF-8, and a
54
+ * document of 20,000 emoji is 80 KB. Counting `length` would let a value
55
+ * through here that the server then refuses, which is the one refusal a user
56
+ * cannot act on (nothing on screen said it was too big). */
57
+ export function jsonByteLength(text: string): number {
58
+ return typeof TextEncoder === "undefined"
59
+ ? text.length
60
+ : new TextEncoder().encode(text).length;
61
+ }
62
+
63
+ /** The one-line summary in the modal's header: what this document IS. */
64
+ export function jsonSummary(text: string): string {
65
+ const parsed = jsonParse(text);
66
+ const bytes = jsonByteLength(text);
67
+ const size = bytes < 1024 ? `${bytes} bytes` : `${(bytes / 1024).toFixed(1)} KB`;
68
+ if (String(text ?? "").trim() === "") return "Empty";
69
+ if (!parsed.ok) return `Not valid JSON Β· ${size}`;
70
+ const v = parsed.value;
71
+ if (Array.isArray(v)) return `${v.length} item${v.length === 1 ? "" : "s"} Β· ${size}`;
72
+ if (v !== null && typeof v === "object") {
73
+ const n = Object.keys(v as object).length;
74
+ return `${n} key${n === 1 ? "" : "s"} Β· ${size}`;
75
+ }
76
+ return `${v === null ? "null" : typeof v} Β· ${size}`;
77
+ }
78
+
79
+ // --- the tree ---------------------------------------------------------------
80
+
81
+ /** How deep a node is open when the viewer mounts. Two levels shows the shape
82
+ * of every payload this product actually receives (an object of objects) and
83
+ * stops before the leaf spam of a scraped array. */
84
+ const OPEN_TO_DEPTH = 2;
85
+
86
+ function isBranch(v: unknown): v is Record<string, unknown> | unknown[] {
87
+ return v !== null && typeof v === "object";
88
+ }
89
+
90
+ /** The value's own text, in its own ink class. Strings keep their quotes: a
91
+ * bare `12` and a `"12"` are different documents and the tree is where that
92
+ * difference has to be visible. */
93
+ function Leaf({ v }: { v: unknown }): ReactNode {
94
+ if (v === null) return <span className="cg-json-null">null</span>;
95
+ if (typeof v === "string") return <span className="cg-json-str">&quot;{v}&quot;</span>;
96
+ if (typeof v === "number") return <span className="cg-json-num">{String(v)}</span>;
97
+ if (typeof v === "boolean") return <span className="cg-json-bool">{String(v)}</span>;
98
+ return <span className="cg-json-str">{String(v)}</span>;
99
+ }
100
+
101
+ /**
102
+ * ⭐ R13 β€” the path a tree edit names, and the ONE function that applies it.
103
+ *
104
+ * Structural clone down the path only: every container on the way is copied, everything else is
105
+ * shared. That keeps a 32 KB document's edit cheap AND keeps the old value untouched, which is
106
+ * what makes the raw tab's Revert honest.
107
+ *
108
+ * ⚠ Returns the ORIGINAL root unchanged if the path does not resolve β€” a stale path (the raw tab
109
+ * changed the shape under an open tree) must not invent the containers it names. The caller reads
110
+ * that as "nothing to do" rather than silently growing the document a key it never had.
111
+ */
112
+ function setAtPath(root: unknown, path: (string | number)[], next: unknown): unknown {
113
+ if (path.length === 0) return next;
114
+ const [head, ...rest] = path;
115
+ if (Array.isArray(root)) {
116
+ const i = typeof head === "number" ? head : Number(head);
117
+ if (!Number.isInteger(i) || i < 0 || i >= root.length) return root;
118
+ const copy = root.slice();
119
+ copy[i] = setAtPath(root[i], rest, next);
120
+ return copy;
121
+ }
122
+ if (root !== null && typeof root === "object") {
123
+ const obj = root as Record<string, unknown>;
124
+ const k = String(head);
125
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return root;
126
+ return { ...obj, [k]: setAtPath(obj[k], rest, next) };
127
+ }
128
+ return root;
129
+ }
130
+
131
+ /**
132
+ * R13 β€” the in-place leaf editor.
133
+ *
134
+ * TYPE-PRESERVING by construction, which is the whole reason it is not one "edit as JSON" box:
135
+ * a string edits as text (no quotes to type), a number as a number, a boolean as its two values.
136
+ * A leaf therefore cannot change TYPE here β€” that is a shape change and belongs to the raw tab
137
+ * (see the amendment at the top of the file).
138
+ *
139
+ * β›” A number that does not parse is REFUSED, not repaired and not coerced to a string. This is
140
+ * decision 2 of the header applied one level down: quietly turning `12a` into `"12a"` teaches a
141
+ * person their typo was fine, right up until a consumer of the document expects arithmetic.
142
+ */
143
+ function LeafEditor({
144
+ value,
145
+ onCommit,
146
+ onCancel,
147
+ }: {
148
+ value: string | number | boolean;
149
+ onCommit: (next: string | number | boolean) => void;
150
+ onCancel: () => void;
151
+ }) {
152
+ const kind = typeof value;
153
+ const [text, setText] = useState(() => String(value));
154
+ const [bad, setBad] = useState(false);
155
+ const commit = () => {
156
+ if (kind === "number") {
157
+ const n = Number(text.trim());
158
+ if (text.trim() === "" || !Number.isFinite(n)) {
159
+ setBad(true);
160
+ return;
161
+ }
162
+ onCommit(n);
163
+ return;
164
+ }
165
+ onCommit(text);
166
+ };
167
+ if (kind === "boolean")
168
+ return (
169
+ <select
170
+ className="cg-json-leafedit"
171
+ autoFocus
172
+ value={String(value)}
173
+ aria-label="Value"
174
+ onChange={(e) => onCommit(e.target.value === "true")}
175
+ onBlur={onCancel}
176
+ >
177
+ <option value="true">true</option>
178
+ <option value="false">false</option>
179
+ </select>
180
+ );
181
+ return (
182
+ <input
183
+ className={"cg-json-leafedit" + (bad ? " is-bad" : "")}
184
+ autoFocus
185
+ value={text}
186
+ spellCheck={false}
187
+ aria-label="Value"
188
+ aria-invalid={bad || undefined}
189
+ title={bad ? "That is not a number β€” the value was not changed." : undefined}
190
+ onChange={(e) => {
191
+ setText(e.target.value);
192
+ if (bad) setBad(false);
193
+ }}
194
+ onKeyDown={(e) => {
195
+ if (e.key === "Enter") {
196
+ e.preventDefault();
197
+ commit();
198
+ } else if (e.key === "Escape") {
199
+ e.preventDefault();
200
+ onCancel();
201
+ }
202
+ }}
203
+ // Blur commits rather than discards: a person who clicks away from an edit box in a
204
+ // document editor means "keep it" far more often than "throw it away", and Escape is the
205
+ // discard that is actually reachable.
206
+ onBlur={commit}
207
+ />
208
+ );
209
+ }
210
+
211
+ function Node({
212
+ name,
213
+ value,
214
+ depth,
215
+ last,
216
+ path,
217
+ onValue,
218
+ editing,
219
+ onEditing,
220
+ }: {
221
+ name: string | null;
222
+ value: unknown;
223
+ depth: number;
224
+ last: boolean;
225
+ /** ⭐ R13 β€” where this node lives in the document, for `setAtPath`. */
226
+ path: (string | number)[];
227
+ /** ⭐ R13 β€” absent = the tree is READ-ONLY (the same condition `onSave` states one level up:
228
+ * a machine-owned, Odoo-sourced or unpermitted field). Present = leaves are editable. */
229
+ onValue?: (path: (string | number)[], next: unknown) => void;
230
+ /** The ONE leaf currently open for editing, as a joined path. Hoisted out of the node so
231
+ * opening a second editor closes the first β€” per-node state would leave a trail of open
232
+ * inputs down a document. */
233
+ editing?: string;
234
+ onEditing?: (key: string | undefined) => void;
235
+ }) {
236
+ const [open, setOpen] = useState(depth < OPEN_TO_DEPTH);
237
+ const pathKey = path.join("");
238
+ if (!isBranch(value)) {
239
+ const canEdit = !!onValue && value !== null;
240
+ return (
241
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
242
+ {name !== null && <span className="cg-json-key">{name}</span>}
243
+ {name !== null && <span className="cg-json-punct">: </span>}
244
+ {canEdit && editing === pathKey ? (
245
+ <LeafEditor
246
+ value={value as string | number | boolean}
247
+ onCommit={(next) => {
248
+ onValue(path, next);
249
+ onEditing?.(undefined);
250
+ }}
251
+ onCancel={() => onEditing?.(undefined)}
252
+ />
253
+ ) : canEdit ? (
254
+ // A real button, so the keyboard reaches every leaf the mouse does. `null` is
255
+ // deliberately NOT editable: there is no type to preserve, so any edit would be a
256
+ // shape change, which belongs to the raw tab.
257
+ <button
258
+ type="button"
259
+ className="cg-json-leafbtn"
260
+ onClick={() => onEditing?.(pathKey)}
261
+ title="Edit this value"
262
+ >
263
+ <Leaf v={value} />
264
+ </button>
265
+ ) : (
266
+ <Leaf v={value} />
267
+ )}
268
+ {!last && <span className="cg-json-punct">,</span>}
269
+ </div>
270
+ );
271
+ }
272
+
273
+ const array = Array.isArray(value);
274
+ const entries: [string, unknown][] = array
275
+ ? (value as unknown[]).map((v, i) => [String(i), v])
276
+ : Object.entries(value as Record<string, unknown>);
277
+ const openMark = array ? "[" : "{";
278
+ const closeMark = array ? "]" : "}";
279
+
280
+ return (
281
+ <>
282
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
283
+ <button
284
+ type="button"
285
+ className={"cg-json-twist" + (open ? " is-open" : "")}
286
+ onClick={() => setOpen((o) => !o)}
287
+ aria-expanded={open}
288
+ aria-label={`${open ? "Collapse" : "Expand"} ${name ?? "the document"}`}
289
+ >
290
+ <svg viewBox="0 0 16 16" width="10" height="10" aria-hidden>
291
+ <path
292
+ d="M6 4l4 4-4 4"
293
+ fill="none"
294
+ stroke="currentColor"
295
+ strokeWidth="1.6"
296
+ strokeLinecap="round"
297
+ strokeLinejoin="round"
298
+ />
299
+ </svg>
300
+ </button>
301
+ {name !== null && <span className="cg-json-key">{name}</span>}
302
+ {name !== null && <span className="cg-json-punct">: </span>}
303
+ <span className="cg-json-punct">{openMark}</span>
304
+ {/* Collapsed, the count IS the content β€” a bare `{…}` tells a reader
305
+ nothing about whether opening it is worth the click. */}
306
+ {!open && (
307
+ <span className="cg-json-count">
308
+ {entries.length} {array ? (entries.length === 1 ? "item" : "items")
309
+ : entries.length === 1 ? "key" : "keys"}
310
+ </span>
311
+ )}
312
+ {!open && <span className="cg-json-punct">{closeMark}{last ? "" : ","}</span>}
313
+ </div>
314
+ {open &&
315
+ entries.map(([k, v], i) => (
316
+ <Node
317
+ key={k}
318
+ name={array ? null : k}
319
+ value={v}
320
+ depth={depth + 1}
321
+ last={i === entries.length - 1}
322
+ path={[...path, array ? Number(k) : k]}
323
+ onValue={onValue}
324
+ editing={editing}
325
+ onEditing={onEditing}
326
+ />
327
+ ))}
328
+ {open && (
329
+ <div className="cg-json-row" style={{ paddingLeft: depth * 14 }}>
330
+ <span className="cg-json-punct">
331
+ {closeMark}
332
+ {last ? "" : ","}
333
+ </span>
334
+ </div>
335
+ )}
336
+ </>
337
+ );
338
+ }
339
+
340
+ // --- ⭐ wave-26 item 8 (contract C2): the POSTS reading ----------------------
341
+ //
342
+ // The owner's ask was that the `posts` cell "reads as POSTS, not raw JSON". The
343
+ // tree is a fine JSON reader and a poor post reader: `posts β†’ 3 β†’ caption` is
344
+ // four clicks to see one line somebody wrote. So a posts document opens on its
345
+ // OWN tab, and the tree and raw tabs stay exactly where they were β€” this adds a
346
+ // reading, it does not replace the document.
347
+ //
348
+ // β›” AN ABSENT METRIC RENDERS AS NOTHING, NEVER AS A ZERO. `postsWindowOf` keeps
349
+ // them `undefined` when unbought (C2: metrics are ABSENT KEYS when
350
+ // `postMetrics` was off), and the row below tests each one before painting it.
351
+ // A `0 views` on a post that was never measured is a fabricated measurement,
352
+ // and it is indistinguishable on screen from a real one.
353
+
354
+ /** One metric, or nothing at all. The guard IS the feature β€” see above. */
355
+ function Metric({ label, value }: { label: string; value: number | undefined }) {
356
+ if (value === undefined) return null;
357
+ return (
358
+ <span className="cg-posts-metric">
359
+ <b>{value.toLocaleString()}</b> {label}
360
+ </span>
361
+ );
362
+ }
363
+
364
+ function PostRow({ post }: { post: PostSummary }) {
365
+ const day = post.posted_at ? dayText(post.posted_at) : "";
366
+ /* ⚠ A ROW WITH NOTHING READABLE IS POSSIBLE BY CONSTRUCTION. `postsWindowOf` accepts any
367
+ object inside `posts` β€” deliberately, because refusing an unrecognised member would hide a
368
+ post the engine wrote in a shape this file has not learned yet. The engine's own writer
369
+ fills these, so in practice it takes a hand-edited document to get here; when it happens the
370
+ card must not paint as an empty rectangle, which reads as a rendering bug rather than as a
371
+ thin record. The shortcode is the post's identity and is the honest last resort. */
372
+ const bare = !day && !post.type && !post.caption && !post.url;
373
+ return (
374
+ <div className="cg-posts-row">
375
+ {bare && (
376
+ <span className="cg-posts-kind">{post.shortcode ?? "A post with no details"}</span>
377
+ )}
378
+ <div className="cg-posts-head">
379
+ {day && <span className="cg-posts-day">{day}</span>}
380
+ {/* The type is the post's own word (`reel`, `image`) β€” shown verbatim rather
381
+ than mapped, because a vocabulary this file invents would drift from the
382
+ vendor's the first time they add one. */}
383
+ {post.type && <span className="cg-posts-kind">{post.type}</span>}
384
+ {post.url && (
385
+ <a
386
+ className="cg-posts-link"
387
+ href={post.url}
388
+ target="_blank"
389
+ rel="noopener noreferrer"
390
+ >
391
+ Open
392
+ </a>
393
+ )}
394
+ </div>
395
+ {post.caption && <p className="cg-posts-caption">{post.caption}</p>}
396
+ {/* β›” NO `views` ROW HERE (2026-08-08 β€” instagram-capture.md Β§4e). The vendor's `views` is
397
+ delivered at ACCOUNT grain: one value repeated across every reel of a creator. Rendering
398
+ it beside this post's own likes and comments is exactly the reading that made it look
399
+ like a post metric in the first place, and this panel would have kept saying so after
400
+ the column was retired. `plays` is the honest per-reel field; it is omitted rather than
401
+ shown empty, because a blank metric chip claims we looked and got zero. */}
402
+ <div className="cg-posts-metrics">
403
+ <Metric label="likes" value={post.likes} />
404
+ <Metric label="comments" value={post.comments} />
405
+ </div>
406
+ </div>
407
+ );
408
+ }
409
+
410
+ function PostsPanel({ window: w }: { window: PostsWindow }) {
411
+ if (w.posts.length === 0)
412
+ return <p className="cg-json-empty">No posts were captured for this profile.</p>;
413
+ return (
414
+ <div className="cg-posts">
415
+ {/* β›” THE ONE SENTENCE THIS PANEL OWES A READER (DESIGN.md Β§4 β€” never over-explain).
416
+ It is a WINDOW: the append tables keep the whole series (R1/R3), so a reader must not
417
+ take these for every post the account has ever made. And when metrics were not bought,
418
+ saying so is the only way an empty metrics row reads as "not measured" rather than
419
+ "measured as nothing". */}
420
+ <p className="cg-posts-note">
421
+ The {w.posts.length} most recent post{w.posts.length === 1 ? "" : "s"}
422
+ {w.as_of ? `, as of ${dayText(w.as_of)}` : ""}
423
+ {w.metrics ? "." : " β€” engagement was not collected for this run."}
424
+ </p>
425
+ <ul className="cg-posts-list">
426
+ {w.posts.map((p, i) => (
427
+ <li key={p.shortcode ?? p.url ?? i} className="cg-posts-item">
428
+ <PostRow post={p} />
429
+ </li>
430
+ ))}
431
+ </ul>
432
+ </div>
433
+ );
434
+ }
435
+
436
+ // --- the shared modal shell -------------------------------------------------
437
+ //
438
+ // ⭐ WAVE-27 item 13 (R13) β€” extracted from `JsonViewer`'s own chrome when the CODE editor
439
+ // arrived, because "a big value that opens in a modal with a title, a summary line, a copy
440
+ // button and a footer" is now two things rather than one. One shell, so the two cannot drift
441
+ // into looking like different products β€” the reason `assetUrl` is one resolver, applied to
442
+ // furniture instead of to URLs.
443
+ //
444
+ // It owns ONLY the chrome. Tabs, body and footer are children: what a document IS differs
445
+ // between a JSON payload and a snippet, and a shell that tried to own that would end up with a
446
+ // `mode` flag threaded through every branch.
447
+
448
+ function ViewerShell({
449
+ label,
450
+ summary,
451
+ kind,
452
+ panelRef,
453
+ titleId,
454
+ onClose,
455
+ onCopy,
456
+ copied,
457
+ children,
458
+ }: {
459
+ label: string;
460
+ summary: string;
461
+ /** `data-overlay-kind` β€” the overlay layer's own identifier, distinct per viewer. */
462
+ kind: string;
463
+ panelRef: React.RefObject<HTMLDivElement>;
464
+ titleId: string;
465
+ onClose: () => void;
466
+ onCopy: () => void;
467
+ copied: boolean;
468
+ children: ReactNode;
469
+ }) {
470
+ return (
471
+ <BodyPortal>
472
+ <div className="cg-record-backdrop">
473
+ <div
474
+ className="cg-json-modal"
475
+ ref={panelRef}
476
+ role="dialog"
477
+ aria-modal="true"
478
+ aria-labelledby={titleId}
479
+ data-overlay-kind={kind}
480
+ tabIndex={-1}
481
+ >
482
+ <div className="cg-json-head">
483
+ <div>
484
+ <div className="cg-json-title" id={titleId}>{label}</div>
485
+ <div className="cg-json-sub">{summary}</div>
486
+ </div>
487
+ <div className="cg-json-headacts">
488
+ <button type="button" className="cg-json-btn" onClick={onCopy}>
489
+ {copied ? "Copied" : "Copy"}
490
+ </button>
491
+ <button
492
+ type="button"
493
+ className="cg-icon-btn"
494
+ onClick={onClose}
495
+ aria-label="Close viewer"
496
+ >
497
+ Γ—
498
+ </button>
499
+ </div>
500
+ </div>
501
+ {children}
502
+ </div>
503
+ </div>
504
+ </BodyPortal>
505
+ );
506
+ }
507
+
508
+ // --- ⭐ WAVE-27 item 13 (R13): the CODE editor ------------------------------
509
+ //
510
+ // A snippet is not a document, and the difference decides everything below:
511
+ //
512
+ // Β· IT NEED NOT PARSE. Half-written SQL is the normal state of a snippet, so there is no
513
+ // validate-on-save and no refusal β€” the only limit is the byte cap the store enforces
514
+ // anyway. This is the one rule `json` has that `code` deliberately does not.
515
+ // Β· THERE IS NO TREE. A snippet has no structure to project, so there is one panel, not tabs.
516
+ // Β· THE HIGHLIGHTER IS A RENDERER, NEVER AN INTERPRETER (R13: "NO execution engine"). It
517
+ // colours strings, comments, numbers and a per-language keyword list. Nothing here can run,
518
+ // fetch or evaluate anything, and no `language` value opens a path to something that could.
519
+ //
520
+ // The editor is a transparent-text `<textarea>` over a `<pre>` painted with the same text: the
521
+ // standard underlay, chosen over a contentEditable because a textarea keeps native undo, native
522
+ // selection and IME composition, all of which a hand-rolled editor loses on day one. The two
523
+ // layers MUST share font, size, line-height, padding and wrapping or the caret drifts from the
524
+ // glyphs β€” that pairing is stated in the CSS beside both rules, and the scroll sync below is the
525
+ // third leg of it.
526
+
527
+ interface Tok { t: string; c: string }
528
+
529
+ const LINE_COMMENT: Record<string, string[]> = {
530
+ json: [], plain: [],
531
+ sql: ["--"], python: ["#"], shell: ["#"], yaml: ["#"],
532
+ javascript: ["//"], typescript: ["//"], css: [], html: [], xml: [], markdown: [],
533
+ };
534
+ const BLOCK_COMMENT: Record<string, [string, string] | undefined> = {
535
+ javascript: ["/*", "*/"], typescript: ["/*", "*/"], css: ["/*", "*/"],
536
+ sql: ["/*", "*/"], html: ["<!--", "-->"], xml: ["<!--", "-->"],
537
+ };
538
+ const KEYWORDS: Record<string, string[]> = {
539
+ sql: ["select", "from", "where", "join", "left", "right", "inner", "outer", "on", "group",
540
+ "order", "by", "having", "limit", "offset", "insert", "into", "values", "update", "set",
541
+ "delete", "create", "table", "view", "as", "and", "or", "not", "null", "is", "in", "like",
542
+ "between", "case", "when", "then", "else", "end", "distinct", "union", "all", "with"],
543
+ python: ["def", "class", "return", "if", "elif", "else", "for", "while", "in", "not", "and",
544
+ "or", "import", "from", "as", "try", "except", "finally", "raise", "with", "lambda", "None",
545
+ "True", "False", "yield", "pass", "break", "continue", "global", "assert", "async", "await"],
546
+ javascript: ["const", "let", "var", "function", "return", "if", "else", "for", "while", "of",
547
+ "in", "new", "class", "extends", "import", "export", "from", "default", "try", "catch",
548
+ "finally", "throw", "async", "await", "typeof", "instanceof", "null", "undefined", "true",
549
+ "false", "this", "switch", "case", "break", "continue", "delete", "void", "yield"],
550
+ typescript: ["const", "let", "var", "function", "return", "if", "else", "for", "while", "of",
551
+ "in", "new", "class", "extends", "implements", "interface", "type", "enum", "import",
552
+ "export", "from", "default", "try", "catch", "finally", "throw", "async", "await", "typeof",
553
+ "instanceof", "null", "undefined", "true", "false", "this", "readonly", "public", "private",
554
+ "protected", "as", "satisfies", "switch", "case", "break", "continue"],
555
+ shell: ["if", "then", "else", "fi", "for", "in", "do", "done", "while", "case", "esac",
556
+ "function", "return", "export", "local", "echo", "cd", "set", "source"],
557
+ yaml: ["true", "false", "null"],
558
+ json: ["true", "false", "null"],
559
+ html: [], xml: [], css: [], markdown: [], plain: [],
560
+ };
561
+
562
+ const IDENT = /[A-Za-z_$][A-Za-z0-9_$]*/y;
563
+ const NUMBER = /\d+(\.\d+)?/y;
564
+
565
+ /**
566
+ * R13 β€” the tokenizer. Single left-to-right pass, no backtracking, no regex over the whole
567
+ * document: a 32 KB snippet must colour without blocking a keystroke.
568
+ *
569
+ * ⚠ EVERY branch consumes at least one character. A tokenizer that can advance zero characters
570
+ * hangs the tab, and it is the one bug in this shape that cannot be seen by reading the output.
571
+ */
572
+ export function tokenizeCode(text: string, lang: string): Tok[] {
573
+ const out: Tok[] = [];
574
+ const keywords = new Set(KEYWORDS[lang] ?? []);
575
+ const lineMarks = LINE_COMMENT[lang] ?? [];
576
+ const block = BLOCK_COMMENT[lang];
577
+ const push = (t: string, c: string) => {
578
+ if (!t) return;
579
+ const prev = out[out.length - 1];
580
+ if (prev && prev.c === c) prev.t += t;
581
+ else out.push({ t, c });
582
+ };
583
+ let i = 0;
584
+ while (i < text.length) {
585
+ const ch = text[i];
586
+ // Block comment
587
+ if (block && text.startsWith(block[0], i)) {
588
+ const end = text.indexOf(block[1], i + block[0].length);
589
+ const stop = end < 0 ? text.length : end + block[1].length;
590
+ push(text.slice(i, stop), "com");
591
+ i = stop;
592
+ continue;
593
+ }
594
+ // Line comment
595
+ const mark = lineMarks.find((m) => text.startsWith(m, i));
596
+ if (mark) {
597
+ const nl = text.indexOf("\n", i);
598
+ const stop = nl < 0 ? text.length : nl;
599
+ push(text.slice(i, stop), "com");
600
+ i = stop;
601
+ continue;
602
+ }
603
+ // String β€” quotes close at the line end as well as at their pair, so one unterminated quote
604
+ // cannot paint the rest of the file as a string (the failure every naive highlighter has).
605
+ if (ch === '"' || ch === "'" || ch === "`") {
606
+ let j = i + 1;
607
+ while (j < text.length && text[j] !== ch && text[j] !== "\n") {
608
+ if (text[j] === "\\") j += 1;
609
+ j += 1;
610
+ }
611
+ const stop = j < text.length && text[j] === ch ? j + 1 : j;
612
+ push(text.slice(i, stop), "str");
613
+ i = stop;
614
+ continue;
615
+ }
616
+ if (ch >= "0" && ch <= "9") {
617
+ NUMBER.lastIndex = i;
618
+ const m = NUMBER.exec(text);
619
+ const t = m ? m[0] : ch;
620
+ push(t, "num");
621
+ i += t.length;
622
+ continue;
623
+ }
624
+ if (/[A-Za-z_$]/.test(ch)) {
625
+ IDENT.lastIndex = i;
626
+ const m = IDENT.exec(text);
627
+ const word = m ? m[0] : ch;
628
+ push(word, keywords.has(word) || keywords.has(word.toLowerCase()) ? "kw" : "");
629
+ i += word.length;
630
+ continue;
631
+ }
632
+ push(ch, "");
633
+ i += 1;
634
+ }
635
+ return out;
636
+ }
637
+
638
+ export interface CodeViewerProps {
639
+ label: string;
640
+ value: string;
641
+ language: string;
642
+ /** Absent = read-only, the same condition `JsonViewer` states. */
643
+ onSave?: (next: string) => void;
644
+ onClose: () => void;
645
+ }
646
+
647
+ export function CodeViewer({ label, value, language, onSave, onClose }: CodeViewerProps) {
648
+ const panelRef = useRef<HTMLDivElement>(null);
649
+ const preRef = useRef<HTMLPreElement>(null);
650
+ const titleId = useId();
651
+ const [draft, setDraft] = useState(value);
652
+ const [error, setError] = useState("");
653
+ const [copied, setCopied] = useState(false);
654
+
655
+ // Re-seeds when the CELL changes underneath, and only then β€” the JsonViewer rule, same reason.
656
+ useEffect(() => {
657
+ setDraft(value);
658
+ setError("");
659
+ }, [value]);
660
+
661
+ useOverlayLayer({
662
+ panelRef,
663
+ onDismiss: onClose,
664
+ dismissOnOutside: true,
665
+ initialFocus: "[data-overlay-autofocus]",
666
+ trapFocus: true,
667
+ });
668
+
669
+ const toks = useMemo(() => tokenizeCode(draft, language), [draft, language]);
670
+ const dirty = draft !== value;
671
+ const bytes = jsonByteLength(draft);
672
+ const lines = draft === "" ? 0 : draft.split("\n").length;
673
+ const size = bytes < 1024 ? `${bytes} bytes` : `${(bytes / 1024).toFixed(1)} KB`;
674
+ const summary = draft.trim() === ""
675
+ ? "Empty"
676
+ : `${lines} line${lines === 1 ? "" : "s"} Β· ${size}`;
677
+
678
+ const save = () => {
679
+ // β›” NO parse check, and its absence is the design. A snippet that does not compile is the
680
+ // normal state of one; refusing to save it would make the column useless for the thing it
681
+ // exists for. The byte cap still applies, because the STORE enforces it either way and a
682
+ // refusal the user only meets on the server is the one they cannot act on.
683
+ if (bytes > MAX_JSON_BYTES) {
684
+ setError(`That snippet is ${(bytes / 1024).toFixed(1)} KB and the limit is 32 KB β€” `
685
+ + "nothing was saved.");
686
+ return;
687
+ }
688
+ setError("");
689
+ onSave?.(draft);
690
+ onClose();
691
+ };
692
+
693
+ const copy = () => {
694
+ void navigator.clipboard?.writeText(draft).then(
695
+ () => {
696
+ setCopied(true);
697
+ window.setTimeout(() => setCopied(false), 1400);
698
+ },
699
+ () => setError("The browser refused clipboard access β€” select the text and copy it.")
700
+ );
701
+ };
702
+
703
+ const painted = (
704
+ <pre className="cg-code-paint" ref={preRef} aria-hidden>
705
+ {toks.map((t, i) => (
706
+ <span key={i} className={t.c ? `cg-code-${t.c}` : undefined}>{t.t}</span>
707
+ ))}
708
+ {/* A trailing newline has no glyph, so without this the last line scrolls out of step
709
+ with the textarea's own extra row. */}
710
+ {"\n"}
711
+ </pre>
712
+ );
713
+
714
+ return (
715
+ <ViewerShell
716
+ label={label}
717
+ summary={summary}
718
+ kind="code-viewer"
719
+ panelRef={panelRef}
720
+ titleId={titleId}
721
+ onClose={onClose}
722
+ onCopy={copy}
723
+ copied={copied}
724
+ >
725
+ <div className="cg-json-body">
726
+ <div className="cg-code-wrap">
727
+ {painted}
728
+ {onSave ? (
729
+ <textarea
730
+ className="cg-code-input"
731
+ value={draft}
732
+ spellCheck={false}
733
+ data-overlay-autofocus
734
+ aria-label={`${label} source`}
735
+ onChange={(e) => {
736
+ setDraft(e.target.value);
737
+ if (error) setError("");
738
+ }}
739
+ // The third leg of the underlay: scroll the paint with the text, or the colours
740
+ // slide off the characters the moment the snippet is taller than the box.
741
+ onScroll={(e) => {
742
+ const el = preRef.current;
743
+ if (!el) return;
744
+ el.scrollTop = e.currentTarget.scrollTop;
745
+ el.scrollLeft = e.currentTarget.scrollLeft;
746
+ }}
747
+ />
748
+ ) : null}
749
+ </div>
750
+ </div>
751
+ {(error || (onSave && dirty)) && (
752
+ <div className="cg-json-foot">
753
+ {error ? (
754
+ <span className="cg-json-err">{error}</span>
755
+ ) : (
756
+ <span className="cg-json-hint">Unsaved changes</span>
757
+ )}
758
+ {onSave && (
759
+ <span className="cg-json-footacts">
760
+ <button
761
+ type="button"
762
+ className="cg-json-btn"
763
+ onClick={() => {
764
+ setDraft(value);
765
+ setError("");
766
+ }}
767
+ >
768
+ Revert
769
+ </button>
770
+ <button type="button" className="cg-json-btn cg-json-btn--primary" onClick={save}>
771
+ Save
772
+ </button>
773
+ </span>
774
+ )}
775
+ </div>
776
+ )}
777
+ </ViewerShell>
778
+ );
779
+ }
780
+
781
+ // --- the modal --------------------------------------------------------------
782
+
783
+ export interface JsonViewerProps {
784
+ /** The column's own label β€” the modal's title. */
785
+ label: string;
786
+ /** The stored document, as a string. */
787
+ value: string;
788
+ /** Absent = read-only (the field is machine-owned, Odoo-sourced, or this
789
+ * viewer permits the reader nothing). Present = the raw tab is an editor. */
790
+ onSave?: (next: string) => void;
791
+ onClose: () => void;
792
+ }
793
+
794
+ export default function JsonViewer({ label, value, onSave, onClose }: JsonViewerProps) {
795
+ const panelRef = useRef<HTMLDivElement>(null);
796
+ const titleId = useId();
797
+ const tabsId = useId();
798
+ /** `null` = nobody has chosen one, so the landing tab is derived (see `shown`). */
799
+ const [picked, setPicked] = useState<"posts" | "tree" | "raw" | null>(null);
800
+ const [draft, setDraft] = useState(value);
801
+ const [error, setError] = useState("");
802
+ const [copied, setCopied] = useState(false);
803
+
804
+ // ⚠ The draft re-seeds when the CELL changes underneath (a machine write
805
+ // landing while the viewer is open), and only then β€” keying on `value` alone
806
+ // would also stamp on every keystroke's re-render if a parent echoed it back.
807
+ useEffect(() => {
808
+ setDraft(value);
809
+ setError("");
810
+ }, [value]);
811
+
812
+ useOverlayLayer({
813
+ panelRef,
814
+ onDismiss: onClose,
815
+ dismissOnOutside: true,
816
+ initialFocus: "[data-overlay-autofocus]",
817
+ trapFocus: true,
818
+ });
819
+
820
+ const parsed = useMemo(() => jsonParse(draft), [draft]);
821
+ const dirty = draft !== value;
822
+ /** ⭐ R13 β€” which leaf is open for editing, as a joined path. ONE at a time (see `Node`). */
823
+ const [editingLeaf, setEditingLeaf] = useState<string | undefined>(undefined);
824
+ /**
825
+ * ⭐ R13 β€” a tree edit, applied to the RAW TEXT.
826
+ *
827
+ * This is what makes "two-way synced, raw wins" true without a reconciliation rule: the tree
828
+ * never holds a document of its own. It re-parses the current draft, writes one value, and
829
+ * serialises the whole thing back β€” so the raw tab and the tree are always literally the same
830
+ * string, and the next render's tree comes from that string rather than from what the tree
831
+ * thought it did.
832
+ *
833
+ * ⚠ Re-parsed HERE rather than reusing the `parsed` memo: between a click and a commit the raw
834
+ * tab may have changed the document, and `setAtPath` returning the root unchanged for a path
835
+ * that no longer resolves is the guard that keeps a stale edit from inventing keys.
836
+ *
837
+ * ⚠ `jsonPretty` reformats the WHOLE document, so a hand-indented payload is normalised by a
838
+ * tree edit. Stated rather than worked around: the alternative is a surgical text splice, which
839
+ * needs a position map from the parse β€” and a wrong splice writes a value into the wrong key.
840
+ */
841
+ const editLeaf = (path: (string | number)[], next: unknown) => {
842
+ const now = jsonParse(draft);
843
+ if (!now.ok) return;
844
+ const updated = setAtPath(now.value, path, next);
845
+ if (updated === now.value) return; // stale path β€” nothing was written
846
+ setDraft(jsonPretty(JSON.stringify(updated)));
847
+ if (error) setError("");
848
+ };
849
+ /* ⭐ Item 8 β€” is this document a POSTS WINDOW? Read off the DRAFT, so editing the raw tab into
850
+ (or out of) the shape moves the tab with it rather than stranding a Posts tab over a
851
+ document that is no longer one. */
852
+ const posts = useMemo(
853
+ () => (parsed.ok ? postsWindowOf(parsed.value) : null),
854
+ [parsed]
855
+ );
856
+ /* The tab set is DERIVED from the document, and the shown tab is derived from the set β€” never
857
+ corrected by an effect. Two things fall out of that, both of which an effect gets wrong:
858
+
859
+ ⚠ POSTS IS THE LANDING TAB when the document is one, which is the whole of the owner's ask
860
+ ("reads as POSTS, not raw JSON"). A `useState` initialiser cannot do it: the cell value
861
+ arrives asynchronously and can change under an open viewer, so it would seed "tree" for
862
+ exactly the render that matters and the reader would meet the JSON first.
863
+ ⚠ A tab the reader PICKED wins while it still exists β€” and stops winning the moment it does
864
+ not. Editing a posts document into something else on the raw tab would otherwise leave the
865
+ panel rendering a Posts tab that is no longer in the list above it. */
866
+ const tabs = posts ? (["posts", "tree", "raw"] as const) : (["tree", "raw"] as const);
867
+ const shown =
868
+ picked && (tabs as readonly string[]).includes(picked) ? picked : posts ? "posts" : "tree";
869
+
870
+ const save = () => {
871
+ const text = draft.trim();
872
+ // Blank is a legal edit: it clears the cell, which is how a document is
873
+ // removed. Everything else must parse before it is allowed to leave here.
874
+ if (text !== "") {
875
+ if (!jsonParse(text).ok) {
876
+ setError("That is not valid JSON β€” nothing was saved. Check for a trailing comma, a "
877
+ + "single quote, or an unquoted key.");
878
+ return;
879
+ }
880
+ const bytes = jsonByteLength(text);
881
+ if (bytes > MAX_JSON_BYTES) {
882
+ setError(`That document is ${(bytes / 1024).toFixed(1)} KB and the limit is 32 KB β€” `
883
+ + "nothing was saved.");
884
+ return;
885
+ }
886
+ }
887
+ setError("");
888
+ onSave?.(text);
889
+ onClose();
890
+ };
891
+
892
+ const copy = () => {
893
+ void navigator.clipboard?.writeText(draft).then(
894
+ () => {
895
+ setCopied(true);
896
+ window.setTimeout(() => setCopied(false), 1400);
897
+ },
898
+ () => setError("The browser refused clipboard access β€” select the raw text and copy it.")
899
+ );
900
+ };
901
+
902
+ return (
903
+ <ViewerShell
904
+ label={label}
905
+ /* The summary is the ONE explanatory line (DESIGN.md Β§4): what this document is, not
906
+ what a JSON field is for. */
907
+ summary={jsonSummary(draft)}
908
+ kind="json-viewer"
909
+ panelRef={panelRef}
910
+ titleId={titleId}
911
+ onClose={onClose}
912
+ onCopy={copy}
913
+ copied={copied}
914
+ >
915
+
916
+ <div className="cg-record-tabs" role="tablist" aria-label="Document view">
917
+ {tabs.map((k) => (
918
+ <button
919
+ key={k}
920
+ type="button"
921
+ role="tab"
922
+ id={`${tabsId}-${k}`}
923
+ aria-selected={shown === k}
924
+ aria-controls={`${tabsId}-panel`}
925
+ className={"cg-record-tab" + (shown === k ? " is-on" : "")}
926
+ onClick={() => setPicked(k)}
927
+ data-overlay-autofocus={k === tabs[0] ? true : undefined}
928
+ >
929
+ {k === "posts" ? "Posts" : k === "tree" ? "Tree" : "Raw"}
930
+ </button>
931
+ ))}
932
+ </div>
933
+
934
+ <div
935
+ className="cg-json-body"
936
+ id={`${tabsId}-panel`}
937
+ role="tabpanel"
938
+ aria-labelledby={`${tabsId}-${shown}`}
939
+ >
940
+ {shown === "posts" && posts ? (
941
+ <PostsPanel window={posts} />
942
+ ) : shown === "tree" ? (
943
+ parsed.ok ? (
944
+ <div className="cg-json-tree">
945
+ <Node
946
+ name={null}
947
+ value={parsed.value}
948
+ depth={0}
949
+ last
950
+ path={[]}
951
+ /* ⭐ R13 β€” the tree edits under exactly the condition the raw tab does.
952
+ `onSave` absent already means "this reader may not change the value", and
953
+ giving the tree a second, looser answer to that question is how one door
954
+ keeps taking writes after the other stops. */
955
+ onValue={onSave ? editLeaf : undefined}
956
+ editing={editingLeaf}
957
+ onEditing={setEditingLeaf}
958
+ />
959
+ </div>
960
+ ) : (
961
+ // β›” NOT an empty tree and NOT a repaired one. A document the app
962
+ // cannot open is a fact about the value, and the raw tab is where
963
+ // it gets read β€” so the empty state POINTS THERE rather than
964
+ // describing what JSON is.
965
+ <p className="cg-json-empty">
966
+ {draft.trim() === ""
967
+ ? "Nothing here yet."
968
+ : "This value is not valid JSON β€” read it on the Raw tab."}
969
+ </p>
970
+ )
971
+ ) : onSave ? (
972
+ <textarea
973
+ className="cg-json-raw"
974
+ value={draft}
975
+ spellCheck={false}
976
+ onChange={(e) => {
977
+ setDraft(e.target.value);
978
+ if (error) setError("");
979
+ }}
980
+ aria-label={`${label} raw JSON`}
981
+ />
982
+ ) : (
983
+ <pre className="cg-json-raw cg-json-raw--ro">{jsonPretty(draft)}</pre>
984
+ )}
985
+ </div>
986
+
987
+ {(error || (onSave && dirty)) && (
988
+ <div className="cg-json-foot">
989
+ {error ? (
990
+ <span className="cg-json-err">{error}</span>
991
+ ) : (
992
+ <span className="cg-json-hint">Unsaved changes</span>
993
+ )}
994
+ {onSave && (
995
+ <span className="cg-json-footacts">
996
+ <button
997
+ type="button"
998
+ className="cg-json-btn"
999
+ onClick={() => {
1000
+ setDraft(value);
1001
+ setError("");
1002
+ }}
1003
+ >
1004
+ Revert
1005
+ </button>
1006
+ <button type="button" className="cg-json-btn cg-json-btn--primary" onClick={save}>
1007
+ Save
1008
+ </button>
1009
+ </span>
1010
+ )}
1011
+ </div>
1012
+ )}
1013
+ </ViewerShell>
1014
+ );
1015
+ }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -1,20 +1,35 @@
1
- import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
 
2
  import type { ReactNode, TextareaHTMLAttributes } from "react";
3
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import {
5
  automationDetail,
6
  automationState,
7
  automationStateLabel,
8
  checkboxOn,
9
  formatDisplay,
 
10
  jsonPreview,
11
  } from "./cells";
12
  // The ONE scheme guard, shared with the kanban card since wave 26 (item 11). From `display`
13
  // rather than `cells` because `cells` re-exports only the handful the canvas needed.
14
  import { actionHref } from "./display";
15
- import JsonViewer from "./JsonViewer";
16
  import { StarRow, StarIcon } from "./Stars";
17
- import { isPickType, mayEditField, ratingMax } from "./types";
18
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
19
  // Item 9 (wave 14) β€” the pure value round-trip. Everything that could silently
20
  // LOSE a stored value moving it into an editor and back lives there, gated by
@@ -260,6 +275,8 @@ export default function RecordDetail({
260
  * reason `imageBusy` is one pair: a record has a handful of document columns and only one
261
  * modal can be on screen. */
262
  const [jsonKey, setJsonKey] = useState<string | null>(null);
 
 
263
  const overlayFields = fields.filter((field) => field.source === "overlay");
264
  // ⚠ These five buckets are the DEFAULT ORDER of the interleaved list (C-LAYOUT) and NOTHING
265
  // ELSE. They used to double as the editability split β€” picked/rating fields rendered
@@ -372,7 +389,12 @@ export default function RecordDetail({
372
  // No scope, no Insights β€” see the prop's note. `tab` is forced back rather than merely
373
  // unreachable, so a host that stops supplying the scope mid-session cannot leave the modal
374
  // showing a panel it can no longer address.
375
- const [tab, setTab] = useState<"fields" | "insights">("fields");
 
 
 
 
 
376
  const canInsights = scope != null;
377
  const activeTab = canInsights ? tab : "fields";
378
  // `mode: "timeseries"` is the only required member of DisplaySpec and it is a truthful one
@@ -385,6 +407,51 @@ export default function RecordDetail({
385
  // wave17 item 5 β€” the same population as `insightPids`, as VALUES, so a snapshot metric can
386
  // read this record's own numbers. Memoised for the identical reason the pid list is.
387
  const insightRows = useMemo(() => [record], [record]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
389
  /**
390
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
@@ -831,6 +898,25 @@ export default function RecordDetail({
831
  </button>
832
  </span>
833
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834
  } else if (field.type === "automation") {
835
  // C5-AUTOFIELD (wave 18). It has to be its OWN branch and not the read-only fallback
836
  // below, because that branch explains read-only-ness as a PERMISSION ("You do not have
@@ -985,7 +1071,7 @@ export default function RecordDetail({
985
  (see C-LAYOUT's amendment): the label for the list as a whole. */}
986
  {canInsights && (
987
  <div className="cg-record-tabs" role="tablist" aria-label="Record view">
988
- {(["fields", "insights"] as const).map((key) => (
989
  <button
990
  key={key}
991
  type="button"
@@ -996,7 +1082,7 @@ export default function RecordDetail({
996
  className={"cg-record-tab" + (activeTab === key ? " is-on" : "")}
997
  onClick={() => setTab(key)}
998
  >
999
- {key === "fields" ? "Fields" : "Insights"}
1000
  </button>
1001
  ))}
1002
  </div>
@@ -1008,22 +1094,111 @@ export default function RecordDetail({
1008
  role={canInsights ? "tabpanel" : undefined}
1009
  aria-labelledby={canInsights ? `${tabsId}-${activeTab}` : undefined}
1010
  >
1011
- {activeTab === "insights" && scope ? (
1012
- // `locked` says the pid set is the PREMISE, not a control: you are reading one
1013
- // customer, so the filter surface is the record itself (the owner's words). The
1014
- // panel keeps its own bucket/span/field controls live against local state.
1015
  <div className="cg-record-insights">
1016
- <TimeSeriesPanel
1017
- scope={scope}
1018
- pids={insightPids}
1019
- fields={fields}
1020
- /* wave17 item 5 / R9 β€” the population `insightPids` names, which here is one
1021
- record. sum-vs-avg is then moot: both reduce to this record's own value. */
1022
- rows={insightRows}
1023
- display={tsDisplay}
1024
- onDisplay={(next) => setTsDisplay((d) => ({ ...d, ...next }))}
1025
- locked
1026
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1027
  </div>
1028
  ) : (
1029
  <>
@@ -1090,6 +1265,26 @@ export default function RecordDetail({
1090
  />
1091
  );
1092
  })()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1093
  </BodyPortal>
1094
  );
1095
  }
 
1
+ import { lazy, Suspense, useEffect, useId, useLayoutEffect, useMemo, useRef, useState }
2
+ from "react";
3
  import type { ReactNode, TextareaHTMLAttributes } from "react";
4
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
5
+
6
+ /**
7
+ * ⭐ WAVE-27 item 20 (R5 / contract C10) β€” the embedded grid a Details section renders.
8
+ *
9
+ * β›” LAZY BECAUSE THE IMPORT IS A CYCLE, not because it is big. `CustomerGrid` mounts
10
+ * `RecordDetail`; a static import back the other way is `A -> B -> A`, which bundlers resolve by
11
+ * leaving one side `undefined` at module-evaluation time β€” a crash that appears only on whichever
12
+ * module happens to evaluate first, i.e. the kind that survives every local test and lands in
13
+ * production. `React.lazy` defers the resolution to first RENDER, by which point both modules
14
+ * exist. It also composes with item 34's route-level splitting instead of fighting it: a reader
15
+ * who never opens a Details tab never downloads a second copy of anything.
16
+ */
17
+ const LinkedGrid = lazy(() => import("./CustomerGrid"));
18
  import {
19
  automationDetail,
20
  automationState,
21
  automationStateLabel,
22
  checkboxOn,
23
  formatDisplay,
24
+ codePreview,
25
  jsonPreview,
26
  } from "./cells";
27
  // The ONE scheme guard, shared with the kanban card since wave 26 (item 11). From `display`
28
  // rather than `cells` because `cells` re-exports only the handful the canvas needed.
29
  import { actionHref } from "./display";
30
+ import JsonViewer, { CodeViewer } from "./JsonViewer";
31
  import { StarRow, StarIcon } from "./Stars";
32
+ import { codeLanguageOf, isPickType, mayEditField, ratingMax } from "./types";
33
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
  // Item 9 (wave 14) β€” the pure value round-trip. Everything that could silently
35
  // LOSE a stored value moving it into an editor and back lives there, gated by
 
275
  * reason `imageBusy` is one pair: a record has a handful of document columns and only one
276
  * modal can be on screen. */
277
  const [jsonKey, setJsonKey] = useState<string | null>(null);
278
+ /** ⭐ Wave-27 item 13 (R13) β€” the open CODE column, the `jsonKey` pattern one kind over. */
279
+ const [codeKey, setCodeKey] = useState<string | null>(null);
280
  const overlayFields = fields.filter((field) => field.source === "overlay");
281
  // ⚠ These five buckets are the DEFAULT ORDER of the interleaved list (C-LAYOUT) and NOTHING
282
  // ELSE. They used to double as the editability split β€” picked/rating fields rendered
 
389
  // No scope, no Insights β€” see the prop's note. `tab` is forced back rather than merely
390
  // unreachable, so a host that stops supplying the scope mid-session cannot leave the modal
391
  // showing a panel it can no longer address.
392
+ // ⭐ WAVE-27 item 20 (owner ruling R5, contract C10) β€” the tab is "Details" now, and the
393
+ // rename is the smaller half. It USED to be "Insights" and hold exactly one thing, a
394
+ // time-series panel; R5 makes it the record's whole relational context β€” every database this
395
+ // record LINKS to, rendered as a real grid of just its linked rows β€” with the time series
396
+ // demoted to one section among them.
397
+ const [tab, setTab] = useState<"fields" | "details">("fields");
398
  const canInsights = scope != null;
399
  const activeTab = canInsights ? tab : "fields";
400
  // `mode: "timeseries"` is the only required member of DisplaySpec and it is a truthful one
 
407
  // wave17 item 5 β€” the same population as `insightPids`, as VALUES, so a snapshot metric can
408
  // read this record's own numbers. Memoised for the identical reason the pid list is.
409
  const insightRows = useMemo(() => [record], [record]);
410
+ /**
411
+ * ⭐ WAVE-27 item 20 (R5 / C10) β€” one section per LINK column on this record's table.
412
+ *
413
+ * ⚠ A link cell is a COMMA-JOINED LIST OF ROW IDS (the scalar `Row` contract β€” an array cell
414
+ * cannot exist here), parsed exactly the way `CustomerGrid`'s own link modal parses it: trim,
415
+ * to number, keep positive integers, de-duplicate. A second parse that disagreed about a
416
+ * trailing comma would show a different set of records than the picker just wrote.
417
+ *
418
+ * ⚠ A link with NO TARGET TABLE is skipped rather than rendered empty. `_clean_field` refuses
419
+ * a `link` without its bag, so this can only be a definition older than that rule β€” and an
420
+ * embedded grid of `scope: ""` would fetch the customer table and present somebody else's
421
+ * records under this column's name.
422
+ *
423
+ * Memoised: `embeddedRecordIds` is read by identity inside the grid's own row projection, so a
424
+ * fresh array per render would re-project on every keystroke in the drawer.
425
+ */
426
+ /**
427
+ * ⭐ WAVE-27 item 20 β€” which Details sections have been OPENED.
428
+ *
429
+ * β›” THE SECTIONS ARE COLLAPSED UNTIL ASKED FOR, and that is a correctness decision as much
430
+ * as a performance one. An embedded grid FETCHES ITS WHOLE TABLE and filters to
431
+ * `embeddedRecordIds` client-side (`CustomerGrid.tsx:621-628`) β€” so on an Instagram profile,
432
+ * whose preset carries FOUR link columns (`posts_link`, `profile_snapshots_link`,
433
+ * `post_snapshots_link`, `comments_link`), opening this tab would mount four glide canvases
434
+ * and pull four tables, two of them append-only snapshot tables. The count in each heading is
435
+ * already known WITHOUT the grid (it is the length of the parsed id list), so a collapsed
436
+ * section still tells you what is in it.
437
+ */
438
+ const [openLinks, setOpenLinks] = useState<Set<string>>(new Set());
439
+ const linkSections = useMemo(
440
+ () =>
441
+ fields
442
+ .filter((f) => f.type === "link" && typeof f.link?.table === "string" && f.link.table)
443
+ .map((f) => ({
444
+ field: f,
445
+ table: f.link!.table as SurfaceScope,
446
+ ids: [...new Set(
447
+ String(record[f.key] ?? "")
448
+ .split(",")
449
+ .map((part) => Number(part.trim()))
450
+ .filter((pid) => Number.isInteger(pid) && pid > 0)
451
+ )],
452
+ })),
453
+ [fields, record]
454
+ );
455
 
456
  /**
457
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
 
898
  </button>
899
  </span>
900
  );
901
+ } else if (field.type === "code") {
902
+ // ⭐ WAVE-27 item 13 (R13) β€” the SAME shape the json slot above uses, and deliberately
903
+ // so: both are big values that live behind one button, and giving them different
904
+ // affordances in the same list would make "open the big value" two gestures to learn.
905
+ // What differs is the preview (a snippet has no structure to summarise β€” see
906
+ // `codePreview`) and the viewer it opens.
907
+ const raw = rawText(record[field.key]);
908
+ slot = (
909
+ <span className="cg-detail-value cg-detail-jsonslot">
910
+ <span className="cg-detail-jsonpreview">{codePreview(raw) || "β€”"}</span>
911
+ <button
912
+ type="button"
913
+ className="cg-detail-imagebtn"
914
+ onClick={() => setCodeKey(field.key)}
915
+ >
916
+ Open
917
+ </button>
918
+ </span>
919
+ );
920
  } else if (field.type === "automation") {
921
  // C5-AUTOFIELD (wave 18). It has to be its OWN branch and not the read-only fallback
922
  // below, because that branch explains read-only-ness as a PERMISSION ("You do not have
 
1071
  (see C-LAYOUT's amendment): the label for the list as a whole. */}
1072
  {canInsights && (
1073
  <div className="cg-record-tabs" role="tablist" aria-label="Record view">
1074
+ {(["fields", "details"] as const).map((key) => (
1075
  <button
1076
  key={key}
1077
  type="button"
 
1082
  className={"cg-record-tab" + (activeTab === key ? " is-on" : "")}
1083
  onClick={() => setTab(key)}
1084
  >
1085
+ {key === "fields" ? "Fields" : "Details"}
1086
  </button>
1087
  ))}
1088
  </div>
 
1094
  role={canInsights ? "tabpanel" : undefined}
1095
  aria-labelledby={canInsights ? `${tabsId}-${activeTab}` : undefined}
1096
  >
1097
+ {activeTab === "details" && scope ? (
 
 
 
1098
  <div className="cg-record-insights">
1099
+ {/* ⭐ WAVE-27 item 20 (R5 / C10) β€” ONE SECTION PER LINK FIELD, each an embedded
1100
+ grid of the linked database showing exactly this record's linked rows.
1101
+
1102
+ ⚠ THE ROWS ARE THE PREMISE, NOT A FILTER, which is the same idea `locked`
1103
+ states for the time series below: you are reading ONE record, so "which rows"
1104
+ is settled by the record and the embedded grid's toolbar narrows within them.
1105
+ `embeddedRecordIds` is the projection that already enforces that
1106
+ (`CustomerGrid.tsx:621-628`), so nothing new decides it here. */}
1107
+ {linkSections.map((sec) => (
1108
+ <section className="cg-detail-section cg-detail-linksec" key={sec.field.key}>
1109
+ <h3 className="cg-detail-sechead">
1110
+ {sec.ids.length === 0 ? (
1111
+ <span>{sec.field.label}</span>
1112
+ ) : (
1113
+ <button
1114
+ type="button"
1115
+ className="cg-detail-sectoggle"
1116
+ aria-expanded={openLinks.has(sec.field.key)}
1117
+ onClick={() =>
1118
+ setOpenLinks((prev) => {
1119
+ const next = new Set(prev);
1120
+ if (next.has(sec.field.key)) next.delete(sec.field.key);
1121
+ else next.add(sec.field.key);
1122
+ return next;
1123
+ })
1124
+ }
1125
+ >
1126
+ {sec.field.label}
1127
+ </button>
1128
+ )}
1129
+ <span className="cg-detail-seccount">
1130
+ {sec.ids.length.toLocaleString()}{" "}
1131
+ {sec.ids.length === 1 ? "record" : "records"}
1132
+ </span>
1133
+ </h3>
1134
+ {sec.ids.length === 0 ? (
1135
+ // Stated, never an empty grid. An embedded grid of nothing looks like a
1136
+ // surface that failed to load; a sentence says which of the two it is.
1137
+ <p className="cg-detail-secempty">
1138
+ Nothing linked yet. Open the {sec.field.label} cell on the Fields tab to
1139
+ link records.
1140
+ </p>
1141
+ ) : !openLinks.has(sec.field.key) ? null : (
1142
+ <div className="cg-detail-linkgrid">
1143
+ {/* ⚠ LAZY, and it is load-bearing rather than a performance nicety:
1144
+ `CustomerGrid` mounts THIS component, so a static import here would be
1145
+ a module cycle. `React.lazy` breaks it at the module graph (the import
1146
+ only resolves when a section actually renders) and composes with the
1147
+ route-level splitting rather than fighting it. */}
1148
+ {/* β›” THE SHARED MARK, NEVER A SENTENCE (owner R6, and `verify_icons`
1149
+ enforces it across every source file β€” it caught a "Loading…" here on
1150
+ this gate's first run). `aria-label` is REQUIRED by C-SPIN: "no words"
1151
+ means no words ON SCREEN, and deleting the label would take the wait
1152
+ away from a screen reader entirely. */}
1153
+ <Suspense
1154
+ fallback={
1155
+ <div className="cg-detail-secempty">
1156
+ <span className="lp-spin" role="status" aria-label="Loading" />
1157
+ </div>
1158
+ }
1159
+ >
1160
+ {/* β›” ONE ATTRIBUTE IS MISSING ON PURPOSE AND IT IS THE VIEW-KIND
1161
+ SWITCHER β€” `embeddedMode="browse"`. R5 asks for the FULL switcher
1162
+ here; `CustomerGrid.tsx:4113` suppresses the mode control for every
1163
+ embedded grid (`serverWindowed || embedded ? undefined : …`), so the
1164
+ prop that distinguishes a BROWSE embed from the link PICKER embed
1165
+ does not exist yet. It is requested as dated amendment A3 to contract
1166
+ C10 in the wave-27 split doc (SESSION C owns `CustomerGrid.tsx`).
1167
+
1168
+ Everything else in this section is already correct β€” the target
1169
+ table, the pinned rows and the toolbar all work today β€” so this ships
1170
+ useful rather than waiting. When the prop lands, this becomes one
1171
+ added line and nothing else moves. It is deliberately NOT smuggled in
1172
+ through a cast: a spread that passed an unknown prop would typecheck
1173
+ forever and silently do nothing, which is the failure mode this wave
1174
+ keeps paying for. */}
1175
+ <LinkedGrid
1176
+ scope={sec.table}
1177
+ embedded
1178
+ embeddedRecordIds={sec.ids}
1179
+ />
1180
+ </Suspense>
1181
+ </div>
1182
+ )}
1183
+ </section>
1184
+ ))}
1185
+ {/* The time series STAYS, as ONE section (R5's own wording). `locked` says the pid
1186
+ set is the PREMISE, not a control: you are reading one customer, so the filter
1187
+ surface is the record itself (the owner's words). The panel keeps its own
1188
+ bucket/span/field controls live against local state. */}
1189
+ <section className="cg-detail-section">
1190
+ <TimeSeriesPanel
1191
+ scope={scope}
1192
+ pids={insightPids}
1193
+ fields={fields}
1194
+ /* wave17 item 5 / R9 β€” the population `insightPids` names, which here is one
1195
+ record. sum-vs-avg is then moot: both reduce to this record's own value. */
1196
+ rows={insightRows}
1197
+ display={tsDisplay}
1198
+ onDisplay={(next) => setTsDisplay((d) => ({ ...d, ...next }))}
1199
+ locked
1200
+ />
1201
+ </section>
1202
  </div>
1203
  ) : (
1204
  <>
 
1265
  />
1266
  );
1267
  })()}
1268
+ {/* ⭐ Wave-27 item 13 (R13) β€” the code editor, stacked the same way and for the same
1269
+ reason: `useOverlayLayer` puts it on top, so Escape closes the editor and leaves the
1270
+ record open. */}
1271
+ {codeKey && (() => {
1272
+ const field = fields.find((f) => f.key === codeKey);
1273
+ if (!field) return null;
1274
+ return (
1275
+ <CodeViewer
1276
+ label={field.label}
1277
+ value={rawText(record[field.key])}
1278
+ language={codeLanguageOf(field)}
1279
+ onSave={
1280
+ mayEditField(field, viewer)
1281
+ ? (next) => onNotesCommit(field.key, next)
1282
+ : undefined
1283
+ }
1284
+ onClose={() => setCodeKey(null)}
1285
+ />
1286
+ );
1287
+ })()}
1288
  </BodyPortal>
1289
  );
1290
  }
web/src/customer-grid/SwipeView.tsx ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // Β· nothing is silently hidden β€” the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ import { choiceOptions } from "./types";
30
+ import type { DisplaySpec, Field, Row } from "./types";
31
+ import { formatDisplay } from "./cells";
32
+ import { actionHref } from "./display";
33
+ import { optionTint } from "./choiceColors";
34
+ import { ModeIcon } from "./icons";
35
+
36
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
37
+
38
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
39
+ type BindingFault =
40
+ | { kind: "unbound" }
41
+ | { kind: "field-gone"; fieldKey: string }
42
+ | { kind: "not-select"; field: Field }
43
+ | { kind: "option-gone"; field: Field; missing: string[] };
44
+
45
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
46
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
47
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
48
+ const field = fieldByKey.get(spec.fieldKey);
49
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
50
+ // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
51
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
52
+ // adds and sometimes overwrites is two gestures wearing one button.
53
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
54
+ const options = choiceOptions(field);
55
+ const has = new Set(options.map((o) => o.toLowerCase()));
56
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
57
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
58
+ return { ok: true, field, spec };
59
+ }
60
+
61
+ /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
62
+ const isUndecided = (row: Row, key: string): boolean =>
63
+ String(row[key] ?? "").trim() === "";
64
+
65
+ export function SwipeView({
66
+ rows,
67
+ fields,
68
+ fieldByKey,
69
+ spec,
70
+ cardKeys,
71
+ titleKey,
72
+ canWrite,
73
+ readOnlyReason,
74
+ canBind,
75
+ onSpec,
76
+ onSwipe,
77
+ onOpen,
78
+ }: {
79
+ /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
80
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
81
+ * patch lands; there is no local cursor to drift out of step with the data. */
82
+ rows: Row[];
83
+ /** Every field, for the picker's field list. */
84
+ fields: Field[];
85
+ fieldByKey: Map<string, Field>;
86
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
87
+ spec: SwipeSpec | undefined;
88
+ /** The handful of visible fields the card lists under its title. */
89
+ cardKeys: string[];
90
+ titleKey: string;
91
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
92
+ canWrite: boolean;
93
+ /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
94
+ readOnlyReason: string | null;
95
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
96
+ * view-editing permission and NOT `canWrite` β€” conflating the two is
97
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
98
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
99
+ canBind: boolean;
100
+ /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
101
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
102
+ onSpec: (next: SwipeSpec | undefined) => void;
103
+ onSwipe: (pid: number, value: string) => void;
104
+ onOpen: (pid: number) => void;
105
+ }) {
106
+ // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
107
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
108
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
109
+ // state rather than quietly shrinking the deck (rule 8b).
110
+ const [later, setLater] = useState<Set<number>>(new Set());
111
+ const deckRef = useRef<HTMLDivElement>(null);
112
+
113
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
114
+ const boundKey = binding.ok ? binding.field.key : null;
115
+
116
+ const undecided = useMemo(
117
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
118
+ [rows, boundKey]
119
+ );
120
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
121
+ const card = deck[0];
122
+
123
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
124
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
125
+ useEffect(() => {
126
+ setLater((prev) => {
127
+ if (prev.size === 0) return prev;
128
+ const live = new Set(undecided.map((r) => r.pid));
129
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
130
+ return next.size === prev.size ? prev : next;
131
+ });
132
+ }, [undecided]);
133
+
134
+ const decide = useCallback(
135
+ (value: string) => {
136
+ if (!card || !canWrite) return;
137
+ onSwipe(card.pid, value);
138
+ },
139
+ [card, canWrite, onSwipe]
140
+ );
141
+
142
+ // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
143
+ // path: the whole point of the mode is that one hand can clear a queue.
144
+ useEffect(() => {
145
+ if (!binding.ok || !canWrite || !card) return;
146
+ const onKey = (e: KeyboardEvent) => {
147
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
148
+ const el = document.activeElement as HTMLElement | null;
149
+ // Never steal an arrow key from a text field or a native control the user is inside.
150
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
151
+ return;
152
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
153
+ e.preventDefault();
154
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
155
+ };
156
+ window.addEventListener("keydown", onKey);
157
+ return () => window.removeEventListener("keydown", onKey);
158
+ }, [binding, canWrite, card, decide]);
159
+
160
+ if (!binding.ok) {
161
+ return (
162
+ <div className="cg-swipe" ref={deckRef}>
163
+ <SwipeBinder
164
+ fault={binding.fault}
165
+ fields={fields}
166
+ fieldByKey={fieldByKey}
167
+ spec={spec}
168
+ canBind={canBind}
169
+ onSpec={onSpec}
170
+ />
171
+ </div>
172
+ );
173
+ }
174
+
175
+ const { field } = binding;
176
+ const leftTint = optionTint(field, binding.spec.leftOption);
177
+ const rightTint = optionTint(field, binding.spec.rightOption);
178
+
179
+ return (
180
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
181
+ <div className="cg-swipe-bar">
182
+ <span className="cg-swipe-bound">
183
+ <ModeIcon mode="swipe" />
184
+ Sorting into <strong>{field.label}</strong>
185
+ </span>
186
+ <span className="cg-swipe-left">
187
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
188
+ </span>
189
+ {canBind && (
190
+ <button
191
+ type="button"
192
+ className="cg-link-btn"
193
+ onClick={() => onSpec(undefined)}
194
+ title="Choose a different field or different options for this deck"
195
+ >
196
+ Change
197
+ </button>
198
+ )}
199
+ </div>
200
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
201
+ {card ? (
202
+ <div className="cg-swipe-deck">
203
+ <button
204
+ type="button"
205
+ className="cg-swipe-side cg-swipe-side--left"
206
+ disabled={!canWrite}
207
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
208
+ onClick={() => decide(binding.spec.leftOption)}
209
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
210
+ >
211
+ <span aria-hidden className="cg-swipe-arrow">
212
+ <svg width="16" height="16" viewBox="0 0 16 16">
213
+ <path
214
+ d="M11 3.2 6.2 8l4.8 4.8"
215
+ fill="none"
216
+ stroke="currentColor"
217
+ strokeWidth="1.6"
218
+ strokeLinecap="round"
219
+ strokeLinejoin="round"
220
+ />
221
+ </svg>
222
+ </span>
223
+ {binding.spec.leftOption}
224
+ </button>
225
+ <article
226
+ className="cg-swipe-card"
227
+ role="button"
228
+ tabIndex={0}
229
+ onClick={() => onOpen(card.pid)}
230
+ onKeyDown={(e) => {
231
+ if (e.key !== "Enter" && e.key !== " ") return;
232
+ e.preventDefault();
233
+ onOpen(card.pid);
234
+ }}
235
+ >
236
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
237
+ <div className="cg-swipe-cells">
238
+ {cardKeys.map((k) => {
239
+ const f = fieldByKey.get(k);
240
+ if (!f) return null;
241
+ const text = formatDisplay(f, card[k]);
242
+ if (!text) return null;
243
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
244
+ // scheme guard β€” and every gesture that reaches it must be stopped from also
245
+ // reaching the card, which is a button (the kanban card's note, same trap).
246
+ const href = actionHref(f, card[k]);
247
+ return (
248
+ <div key={k} className="cg-swipe-cell">
249
+ <span className="cg-lv-k">{f.label}</span>
250
+ {href ? (
251
+ <a
252
+ className="cg-lv-v"
253
+ href={href}
254
+ target="_blank"
255
+ rel="noopener noreferrer"
256
+ title={text}
257
+ onClick={(e) => e.stopPropagation()}
258
+ onKeyDown={(e) => e.stopPropagation()}
259
+ >
260
+ {text}
261
+ </a>
262
+ ) : (
263
+ <span className="cg-lv-v">{text}</span>
264
+ )}
265
+ </div>
266
+ );
267
+ })}
268
+ </div>
269
+ {canWrite && (
270
+ <button
271
+ type="button"
272
+ className="cg-link-btn cg-swipe-later"
273
+ onClick={(e) => {
274
+ e.stopPropagation();
275
+ setLater((prev) => new Set(prev).add(card.pid));
276
+ }}
277
+ >
278
+ Decide later
279
+ </button>
280
+ )}
281
+ </article>
282
+ <button
283
+ type="button"
284
+ className="cg-swipe-side cg-swipe-side--right"
285
+ disabled={!canWrite}
286
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
287
+ onClick={() => decide(binding.spec.rightOption)}
288
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
289
+ >
290
+ {binding.spec.rightOption}
291
+ <span aria-hidden className="cg-swipe-arrow">
292
+ <svg width="16" height="16" viewBox="0 0 16 16">
293
+ <path
294
+ d="M5 3.2 9.8 8 5 12.8"
295
+ fill="none"
296
+ stroke="currentColor"
297
+ strokeWidth="1.6"
298
+ strokeLinecap="round"
299
+ strokeLinejoin="round"
300
+ />
301
+ </svg>
302
+ </span>
303
+ </button>
304
+ </div>
305
+ ) : (
306
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
307
+ // between "the deck is finished" and "the filter hid everything", and the two want
308
+ // different next actions. `later` is disclosed rather than quietly subtracted.
309
+ <div className="cg-mode-empty cg-swipe-empty">
310
+ {later.size > 0 ? (
311
+ <>
312
+ <p>
313
+ {later.size.toLocaleString()}{" "}
314
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
315
+ in this view is missing a <strong>{field.label}</strong>.
316
+ </p>
317
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
318
+ Bring them back
319
+ </button>
320
+ </>
321
+ ) : (
322
+ <p>
323
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
324
+ view's filters to sort more.
325
+ </p>
326
+ )}
327
+ </div>
328
+ )}
329
+ </div>
330
+ );
331
+ }
332
+
333
+ /**
334
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
335
+ * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
336
+ * error screen beside a separate setup screen.
337
+ */
338
+ function SwipeBinder({
339
+ fault,
340
+ fields,
341
+ fieldByKey,
342
+ spec,
343
+ canBind,
344
+ onSpec,
345
+ }: {
346
+ fault: BindingFault;
347
+ fields: Field[];
348
+ fieldByKey: Map<string, Field>;
349
+ spec: SwipeSpec | undefined;
350
+ canBind: boolean;
351
+ onSpec: (next: SwipeSpec | undefined) => void;
352
+ }) {
353
+ const selects = useMemo(
354
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
355
+ [fields]
356
+ );
357
+ const [fieldKey, setFieldKey] = useState<string>(() => {
358
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
359
+ return selects[0]?.key ?? "";
360
+ });
361
+ const chosen = fieldByKey.get(fieldKey);
362
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
363
+ const [left, setLeft] = useState<string>("");
364
+ const [right, setRight] = useState<string>("");
365
+
366
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
367
+ // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
368
+ // previous field would offer a value the new field cannot hold.
369
+ useEffect(() => {
370
+ setLeft(options[0] ?? "");
371
+ setRight(options.find((o) => o !== options[0]) ?? "");
372
+ }, [options]);
373
+
374
+ const message = ((): string => {
375
+ switch (fault.kind) {
376
+ case "field-gone":
377
+ return "The field this deck sorted into has been deleted. Pick another one.";
378
+ case "not-select":
379
+ return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
380
+ + " sort into. Pick another field.";
381
+ case "option-gone":
382
+ return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
383
+ fault.missing.length === 1 ? "is" : "are"
384
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
385
+ fault.field.label
386
+ }”. Pick the sides again.`;
387
+ default:
388
+ return "Sort records one at a time into two options of a single-select field.";
389
+ }
390
+ })();
391
+
392
+ if (!canBind) {
393
+ return (
394
+ <div className="cg-mode-empty">
395
+ <p>{message}</p>
396
+ <p>Its creator or an admin can set this view up.</p>
397
+ </div>
398
+ );
399
+ }
400
+ if (selects.length === 0) {
401
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
402
+ // requirement is what turns a dead end into a next action.
403
+ return (
404
+ <div className="cg-mode-empty">
405
+ <p>
406
+ A swipe deck sorts into a single-select field with at least two options. This database
407
+ does not have one yet β€” add a single-select column, then come back.
408
+ </p>
409
+ </div>
410
+ );
411
+ }
412
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
413
+ return (
414
+ <div className="cg-swipe-setup">
415
+ <p className="cg-swipe-setup-note">{message}</p>
416
+ <label className="cg-swipe-setup-row">
417
+ <span>Sort into</span>
418
+ <select
419
+ className="cg-select"
420
+ value={fieldKey}
421
+ onChange={(e) => setFieldKey(e.target.value)}
422
+ >
423
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
424
+ renders its FIRST option and reports a choice the user never made
425
+ ([[cg-condition-builder-items]]). */}
426
+ {selects.map((f) => (
427
+ <option key={f.key} value={f.key}>
428
+ {f.label}
429
+ </option>
430
+ ))}
431
+ </select>
432
+ </label>
433
+ <div className="cg-swipe-setup-sides">
434
+ <label className="cg-swipe-setup-row">
435
+ <span>Swipe left</span>
436
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
437
+ {options.map((o) => (
438
+ <option key={o} value={o}>
439
+ {o}
440
+ </option>
441
+ ))}
442
+ </select>
443
+ </label>
444
+ <label className="cg-swipe-setup-row">
445
+ <span>Swipe right</span>
446
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
447
+ {options.map((o) => (
448
+ <option key={o} value={o}>
449
+ {o}
450
+ </option>
451
+ ))}
452
+ </select>
453
+ </label>
454
+ </div>
455
+ {!ready && left && right && (
456
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
457
+ // option, so a Save that looked like it worked would simply not persist.
458
+ <p className="cg-swipe-setup-warn">
459
+ The two sides must be different options β€” otherwise both gestures do the same thing.
460
+ </p>
461
+ )}
462
+ <button
463
+ type="button"
464
+ className="cg-btn cg-btn--primary"
465
+ disabled={!ready}
466
+ onClick={() =>
467
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
468
+ }
469
+ >
470
+ Start sorting
471
+ </button>
472
+ </div>
473
+ );
474
+ }
475
+
476
+ export default SwipeView;
web/src/customer-grid/ViewSidebar.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/cells.ts CHANGED
@@ -1,724 +1,744 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / cells.ts
3
- // The ONLY place that turns a (field, value) into a glide GridCell. glide has
4
- // no per-column formatter β€” all formatting is per-cell here, in getCellContent.
5
- //
6
- // currency/int -> NumberCell (raw number kept for copy/paste, right-aligned)
7
- // pct -> NumberCell showing v.toFixed(1)+"%" (yoy_pct is already in percent-points)
8
- // date -> TextCell (locale date string; read-only, no picker in core)
9
- // status -> BubbleCell (Airtable-style colored pill via themeOverride)
10
- // checkbox -> BooleanCell (wave-5 item 11; overlay stores '1' or '')
11
- // url -> UriCell (renders as a link; opening is CustomerGrid's click path)
12
- // phone/email -> TextCell (actionable links in the record drawer)
13
- // rating -> Custom (canvas-drawn stars β€” SVG/vector paths, NEVER emoji)
14
- // created_time -> TextCell (read-only; the row's `_created`, injected at its key)
15
- // formula -> NumberCell (client-computed, read-only; blank = could not compute)
16
- // text/other -> TextCell
17
- //
18
- // Wave-5 item 10: `field.format` shapes the DISPLAY string (thousands /
19
- // decimals 0..4 / 34.0M abbreviation for numbers; include-time + local|utc
20
- // for dates). A field with NO format renders byte-identically to before the
21
- // format existed β€” parity is asserted by keeping the default paths in terms
22
- // of the same toLocaleString calls.
23
- //
24
- // Editability is the CALLER's decision (permissions + stratum + type); this
25
- // module just applies the flag it is handed.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { GridCellKind } from "@glideapps/glide-data-grid";
29
- import type {
30
- CustomCell,
31
- CustomRenderer,
32
- GridCell,
33
- Theme,
34
- } from "@glideapps/glide-data-grid";
35
- import { assetUrl } from "./catalogData";
36
- import type { Field } from "./types";
37
- import { ratingMax } from "./types";
38
- import {
39
- LP_BLUE_TEXT,
40
- LP_BLUE_TINT,
41
- LP_GREEN_DEEP,
42
- LP_GREEN_TINT,
43
- LP_RED_DEEP,
44
- LP_RED_TINT,
45
- LP_YELLOW_DEEP,
46
- LP_YELLOW_TINT,
47
- STATUS_BUBBLE,
48
- } from "./theme";
49
- // ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
50
- // another. C-AVATAR names choiceColors' as the avatar fallback's source, so the two stay
51
- // distinguishable at the call site rather than one silently shadowing the other.
52
- import { optionTint, pickTint as choicePickTint } from "./choiceColors";
53
- import { automationState, avatarInitials, avatarSize, checkboxOn, dateTimeText, formulaIsBlank,
54
- formulaIsText, jsonPreview, num, numberText, userCellPayload } from "./display";
55
- import type { AutomationState, CellValue, UserCellData } from "./display";
56
-
57
- // Wave-7 (item W2): the pure display-string half moved to display.ts so the
58
- // export builders can run under node without dragging glide along. Re-exported
59
- // here so every existing import keeps working unchanged.
60
- export { checkboxOn, dateTimeText, formatDisplay } from "./display";
61
- // C-AVATAR β€” the pure halves live in display.ts (node-reachable, so a gate can hold them);
62
- // re-exported here so callers keep importing "the cell module" for everything avatar-shaped.
63
- export { avatarInitials, avatarSize, userCellPayload } from "./display";
64
- export type { UserCellData } from "./display";
65
- // C5-AUTOFIELD β€” same arrangement: the string parsing is pure and lives in display.ts (a node
66
- // gate can hold it); only the canvas tint table below needs this module.
67
- export { automationDetail, automationState, automationStateLabel } from "./display";
68
- export type { AutomationState } from "./display";
69
- // Wave-23 C7 β€” same arrangement again: the parse, the preview and the pretty-printer are pure
70
- // (`verify_grid_ux` drives them under node); only the canvas cell below needs this module.
71
- export { jsonParse, jsonPretty, jsonPreview, MAX_JSON_BYTES } from "./display";
72
-
73
- /**
74
- * Wave-18 C5-AUTOFIELD β€” the cell tint per automation state.
75
- *
76
- * Standing brand rule: the PASTEL is the fill and the measured `-deep` variant carries the ink.
77
- * `bgCell` + `textDark` is that pairing at cell scale, and every combination below is one of the
78
- * pairs already measured for `STATUS_BUBBLE` (β‰₯ 4.9:1), so nothing new needed measuring.
79
- *
80
- * `none` deliberately has NO override: a cell that has never run reads as an ordinary empty
81
- * cell, because a tint would claim the automation had produced something.
82
- */
83
- const AUTOMATION_TINT: Record<AutomationState, Partial<Theme> | undefined> = {
84
- ok: { bgCell: LP_GREEN_TINT, textDark: LP_GREEN_DEEP },
85
- partial: { bgCell: LP_YELLOW_TINT, textDark: LP_YELLOW_DEEP },
86
- blocked: { bgCell: LP_YELLOW_TINT, textDark: LP_YELLOW_DEEP },
87
- error: { bgCell: LP_RED_TINT, textDark: LP_RED_DEEP },
88
- queued: { bgCell: LP_BLUE_TINT, textDark: LP_BLUE_TEXT },
89
- none: undefined,
90
- };
91
-
92
- /** Stable pill tint for a user-defined choice. Hashed from the VALUE, so the same choice keeps
93
- * its colour across rows, sessions and users without anyone picking one β€” and a renamed option
94
- * simply gets a new colour rather than inheriting a stale mapping. */
95
- const PICK_TINTS = [
96
- // 2026-07-31 (owner item 7): ONE construction β€” every pill is a `-tint` wash carrying its
97
- // family's `-deep` ink, the standing brand rule ("pastels are fills; text takes the deep
98
- // weight"). The old second pass (full pastel + near-black ink) is GONE: it is what read as
99
- // "black font on a saturated chip". Six families now β€” the four C1 hues, the brand purple,
100
- // and a neutral grey β€” all mirrored from index.css tokens; every pairing measures β‰₯ 5.0:1.
101
- { bg: "#EDF3FD", fg: "#4F6079" }, // blue-tint / LP_BLUE_TEXT
102
- { bg: "#EBF6EF", fg: "#35754E" }, // green-tint / green-deep
103
- { bg: "#FBF4E0", fg: "#7E6428" }, // yellow-tint/ yellow-deep
104
- { bg: "#FCEEEC", fg: "#A3453C" }, // red-tint / red-deep
105
- { bg: "#F1EEFB", fg: "#6B57A8" }, // purple-tint/ purple-deep (--lp-purple family)
106
- { bg: "#EEF1F4", fg: "#4B5563" }, // neutral wash / slate β€” the sixth distinct family
107
- ];
108
-
109
- export function pickTint(v: string): { bg: string; fg: string } {
110
- let h = 0;
111
- for (let i = 0; i < v.length; i += 1) h = (h * 31 + v.charCodeAt(i)) >>> 0;
112
- return PICK_TINTS[h % PICK_TINTS.length];
113
- }
114
-
115
- // --- rating: a canvas-drawn star row (owner constant: vector, never emoji) --
116
-
117
- export interface RatingCellData {
118
- kind: "aios-rating";
119
- /** 0 = unset (draws all-empty outlines). */
120
- value: number;
121
- max: number;
122
- }
123
- export type RatingCell = CustomCell<RatingCellData>;
124
-
125
- function drawStar(
126
- ctx: CanvasRenderingContext2D,
127
- cx: number,
128
- cy: number,
129
- r: number,
130
- filled: boolean
131
- ): void {
132
- ctx.beginPath();
133
- for (let i = 0; i < 10; i += 1) {
134
- const rad = (Math.PI / 5) * i - Math.PI / 2;
135
- const rr = i % 2 === 0 ? r : r * 0.45;
136
- const px = cx + Math.cos(rad) * rr;
137
- const py = cy + Math.sin(rad) * rr;
138
- if (i === 0) ctx.moveTo(px, py);
139
- else ctx.lineTo(px, py);
140
- }
141
- ctx.closePath();
142
- if (filled) {
143
- // I7c: C1's yellow is a FILL token (1.38:1) and a star has to be seen, so the
144
- // filled star rides the deep amber variant: 3.29:1 on white, clearing the 3:1
145
- // non-text bar the old gold #C8A24B never did (it measured 2.41:1).
146
- ctx.fillStyle = "#A98A3E";
147
- ctx.fill();
148
- } else {
149
- ctx.strokeStyle = "rgba(118, 143, 182, 0.55)"; // blue-deep outline, empty slots
150
- ctx.lineWidth = 1;
151
- ctx.stroke();
152
- }
153
- }
154
-
155
- // --- user: the assignee AVATAR (wave-14 item 11 / R6 / contract C-AVATAR) -----
156
- //
157
- // R6: a grid cell shows the PHOTO OR ICON ONLY β€” no name text. (Pickers and the record modal
158
- // are where a name belongs; the column is a glanceable "who owns this", and thirty repetitions
159
- // of "Farhan Sanyoto" down a column is the thing the owner asked to stop reading.)
160
- //
161
- // The name is still the cell's COPY value. An avatar-only cell with no `copyData` makes an
162
- // assignee column copy as nothing β€” a real regression that no screenshot shows.
163
-
164
- export type UserCell = CustomCell<UserCellData>;
165
-
166
- /**
167
- * Decoded avatar images, keyed by their data URL. `null` = this URL failed to decode, so we
168
- * stop retrying it and paint the fallback forever (a corrupt stored photo must not spin).
169
- *
170
- * ⚠ Module scope, like the tint tables above: an Image per cell per frame would re-decode a
171
- * base64 payload on every scroll tick.
172
- */
173
- const _avatarImgs = new Map<string, HTMLImageElement | null>();
174
- let _avatarRepaint: (() => void) | undefined;
175
-
176
- /**
177
- * ⚠ THE HALF THAT IS EASY TO FORGET. glide repaints when `getCellContent`'s identity changes β€”
178
- * it knows nothing about an `Image.onload` that fires three frames later. Without this hook the
179
- * fallback initials paint once and STAY, and because the fallback is a deliberate, correct-looking
180
- * design, nothing on screen says the photo never arrived. (Same shape as wave-13's "honest empty
181
- * state that made the failure look deliberate".)
182
- *
183
- * CustomerGrid calls this once and bumps a counter that is in `useGetCellContent`'s deps.
184
- */
185
- export function setAvatarRepaint(fn: (() => void) | undefined): void {
186
- _avatarRepaint = fn;
187
- }
188
-
189
- function avatarImage(dataUrl: string): HTMLImageElement | null {
190
- const hit = _avatarImgs.get(dataUrl);
191
- if (hit !== undefined) return hit;
192
- // A DOM-less environment (a node gate, a locked-down embed) has no Image constructor. Cache
193
- // the refusal so the fallback is what paints, rather than throwing inside a draw call.
194
- if (typeof Image === "undefined") {
195
- _avatarImgs.set(dataUrl, null);
196
- return null;
197
- }
198
- const img = new Image();
199
- _avatarImgs.set(dataUrl, img);
200
- img.onload = () => _avatarRepaint?.();
201
- img.onerror = () => {
202
- _avatarImgs.set(dataUrl, null);
203
- _avatarRepaint?.();
204
- };
205
- img.src = dataUrl;
206
- return img;
207
- }
208
-
209
- /** C-AVATAR β€” the circle, photo or not. Exported so any other canvas surface paints the same
210
- * avatar rather than growing a second almost-matching one. */
211
- export function drawAvatar(
212
- ctx: CanvasRenderingContext2D,
213
- cx: number,
214
- cy: number,
215
- r: number,
216
- name: string,
217
- photo: string | undefined,
218
- fontFamily: string
219
- ): void {
220
- const img = photo ? avatarImage(photo) : null;
221
- // `complete` alone is not enough: a FAILED decode is also "complete", with a zero natural size.
222
- if (img && img.complete && img.naturalWidth > 0) {
223
- ctx.save();
224
- ctx.beginPath();
225
- ctx.arc(cx, cy, r, 0, Math.PI * 2);
226
- ctx.clip();
227
- // COVER, not contain: a portrait must fill the circle, not sit letterboxed inside it.
228
- const scale = Math.max((r * 2) / img.naturalWidth, (r * 2) / img.naturalHeight);
229
- const w = img.naturalWidth * scale;
230
- const h = img.naturalHeight * scale;
231
- ctx.drawImage(img, cx - w / 2, cy - h / 2, w, h);
232
- ctx.restore();
233
- return;
234
- }
235
- // The fallback, and it is the DEFAULT state until HOST's C-AVATAR lands β€” never a broken-image
236
- // glyph. Hashed from the full name so one person keeps one colour across rows and sessions.
237
- const tint = choicePickTint(name);
238
- ctx.save();
239
- ctx.beginPath();
240
- ctx.arc(cx, cy, r, 0, Math.PI * 2);
241
- ctx.fillStyle = tint.bg;
242
- ctx.fill();
243
- ctx.fillStyle = tint.fg;
244
- ctx.font = `600 ${Math.round(r * 0.9)}px ${fontFamily}`;
245
- ctx.textAlign = "center";
246
- ctx.textBaseline = "middle";
247
- ctx.fillText(avatarInitials(name), cx, cy + 0.5);
248
- ctx.restore();
249
- }
250
-
251
- /** Registered once on the DataEditor (customRenderers), beside the rating renderer. */
252
- export const userCellRenderer: CustomRenderer<UserCell> = {
253
- kind: GridCellKind.Custom,
254
- isMatch: (cell): cell is UserCell =>
255
- (cell.data as UserCellData | undefined)?.kind === "aios-user",
256
- draw: (args, cell) => {
257
- const { ctx, rect, theme } = args;
258
- const { name, photo } = cell.data;
259
- if (!name) return true; // unassigned paints nothing β€” an empty circle would look assigned
260
- const d = avatarSize(rect.height);
261
- const cx = rect.x + theme.cellHorizontalPadding + d / 2;
262
- const cy = rect.y + rect.height / 2;
263
- // Never paint outside the cell: a column dragged narrow drops the avatar rather than
264
- // bleeding it over its neighbour.
265
- if (cx + d / 2 > rect.x + rect.width - theme.cellHorizontalPadding) return true;
266
- drawAvatar(ctx, cx, cy, d / 2, name, photo, theme.fontFamily);
267
- return true;
268
- },
269
- };
270
-
271
- // --- image: the record THUMBNAIL (wave-19 R7 / contract C5) -------------------
272
- //
273
- // The cell holds a REFERENCE, never bytes (`types.ts: imageRefKind`), so what paints here is an
274
- // <img> the browser fetches from the asset routes and caches like any other image. Same
275
- // module-scoped decode cache and same repaint hook as the avatar above, and for the same reason:
276
- // glide repaints on `getCellContent` identity, and knows nothing about an `onload` three frames
277
- // later. Without the hook the placeholder paints once and stays β€” a deliberate-looking empty
278
- // frame over a picture that did arrive.
279
-
280
- export interface ImageCellData {
281
- kind: "aios-image";
282
- /** The resolved URL, or "" when the cell is empty (paints the placeholder frame). */
283
- url: string;
284
- /** The raw cell value β€” the copy/export payload, so a picture column is not invisible in a CSV. */
285
- ref: string;
286
- }
287
- export type ImageCell = CustomCell<ImageCellData>;
288
-
289
- const _cellImgs = new Map<string, HTMLImageElement | null>();
290
-
291
- function cellImage(url: string): HTMLImageElement | null {
292
- const hit = _cellImgs.get(url);
293
- if (hit !== undefined) return hit;
294
- if (typeof Image === "undefined") {
295
- _cellImgs.set(url, null);
296
- return null;
297
- }
298
- const img = new Image();
299
- _cellImgs.set(url, img);
300
- img.onload = () => _avatarRepaint?.();
301
- img.onerror = () => {
302
- // A reference that does not resolve is NOT retried: an unknown SKU code is the ordinary
303
- // state of a product with no master on file, and retrying it every repaint would be a
304
- // 404 per scroll tick per row.
305
- _cellImgs.set(url, null);
306
- _avatarRepaint?.();
307
- };
308
- img.src = url;
309
- return img;
310
- }
311
-
312
- /** Registered once on the DataEditor (customRenderers), beside rating and user. */
313
- export const imageCellRenderer: CustomRenderer<ImageCell> = {
314
- kind: GridCellKind.Custom,
315
- isMatch: (cell): cell is ImageCell =>
316
- (cell.data as ImageCellData | undefined)?.kind === "aios-image",
317
- draw: (args, cell) => {
318
- const { ctx, rect, theme } = args;
319
- const { url } = cell.data;
320
- const pad = theme.cellHorizontalPadding;
321
- // Square, inset by 3px top and bottom so a tall row shows a bigger picture and a short one
322
- // still leaves the grid line visible.
323
- const size = Math.max(0, Math.min(rect.height - 6, rect.width - pad * 2));
324
- if (size <= 2) return true; // column dragged too narrow: paint nothing, never bleed
325
- const x = rect.x + pad;
326
- const y = rect.y + (rect.height - size) / 2;
327
- const img = url ? cellImage(url) : null;
328
- ctx.save();
329
- ctx.beginPath();
330
- // A 3px radius, matching the choice pills β€” one rounding vocabulary across the canvas.
331
- const r = Math.min(3, size / 2);
332
- ctx.moveTo(x + r, y);
333
- ctx.arcTo(x + size, y, x + size, y + size, r);
334
- ctx.arcTo(x + size, y + size, x, y + size, r);
335
- ctx.arcTo(x, y + size, x, y, r);
336
- ctx.arcTo(x, y, x + size, y, r);
337
- ctx.closePath();
338
- // `complete` alone is not enough β€” a FAILED decode is also complete, with a zero natural size.
339
- if (img && img.complete && img.naturalWidth > 0) {
340
- ctx.clip();
341
- // CONTAIN, not cover: a product photo cropped to a square loses the thing being sold.
342
- // Letterboxing inside the frame is the honest fit for a catalogue picture.
343
- const scale = Math.min(size / img.naturalWidth, size / img.naturalHeight);
344
- const w = img.naturalWidth * scale;
345
- const h = img.naturalHeight * scale;
346
- ctx.drawImage(img, x + (size - w) / 2, y + (size - h) / 2, w, h);
347
- } else {
348
- // The empty frame: a quiet outline, never a broken-image glyph and never a coloured block
349
- // that would read as content. Identical whether the cell is empty or the fetch failed β€”
350
- // the record modal is where a user finds out which, in words.
351
- ctx.fillStyle = LP_BLUE_TINT;
352
- ctx.fill();
353
- ctx.strokeStyle = "rgba(118, 143, 182, 0.45)";
354
- ctx.lineWidth = 1;
355
- ctx.stroke();
356
- }
357
- ctx.restore();
358
- return true;
359
- },
360
- };
361
-
362
- /** Registered once on the DataEditor (customRenderers). Pure canvas paths. */
363
- export const ratingCellRenderer: CustomRenderer<RatingCell> = {
364
- kind: GridCellKind.Custom,
365
- isMatch: (cell): cell is RatingCell =>
366
- (cell.data as RatingCellData | undefined)?.kind === "aios-rating",
367
- draw: (args, cell) => {
368
- const { ctx, rect, theme } = args;
369
- const { value, max } = cell.data;
370
- const size = 13;
371
- const gap = 3;
372
- const cy = rect.y + rect.height / 2;
373
- let cx = rect.x + theme.cellHorizontalPadding + size / 2;
374
- const maxRight = rect.x + rect.width - theme.cellHorizontalPadding;
375
- for (let i = 0; i < max; i += 1) {
376
- if (cx + size / 2 > maxRight) break; // never paint outside the cell
377
- drawStar(ctx, cx, cy, size / 2, i < value);
378
- cx += size + gap;
379
- }
380
- return true;
381
- },
382
- };
383
-
384
- /** Build the cell for one (field, value). `editable` gates overlay + readonly.
385
- *
386
- * ⚠ A BLANK numeric cell renders EMPTY, never "$0" (2026-07-27). `''`/null is how a value that
387
- * could not be computed degrades β€” a measure column whose store query failed, an overlay number
388
- * nobody typed, a FORMULA that hit an error β€” and painting it as $0 would state a number nobody
389
- * computed. A real 0 arrives as the NUMBER 0 (the pool and the zero-group both emit it) and
390
- * still renders "$0". Mirrors the blank-vs-zero rule the engine already has (`isBlank`: 0 is
391
- * NOT blank). */
392
- export function makeCell(
393
- field: Field,
394
- v: CellValue,
395
- editable: boolean,
396
- /** C-AVATAR β€” username β†’ data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
397
- * username absent from it, paints the initials fallback. */
398
- userAvatars?: Record<string, string>
399
- ): GridCell {
400
- // β›” NO MACHINE WASH (owner item 2, 2026-08-06): *"Remove the light grey highlight for the
401
- // column that is supposedly pre-set."* Wave-23 R9 introduced a grey background on every
402
- // machine-owned cell; on a `ut_*` database that is EVERY column but one, so the grid read as a
403
- // sea of grey with a white stripe rather than as a table. The fact it was trying to state β€”
404
- // *something else fills this column* β€” is now stated in WORDS where a reader will meet it
405
- // (the `Pre-set` chip in Hide fields, `isPresetField`) and enforced where it matters (the
406
- // cells refuse the edit, `isMachineWritten`). A label beats a tint the reader has to be taught.
407
- return baseCell(field, v, editable, userAvatars);
408
- }
409
-
410
- /* β›” THE MACHINE WASH IS RETIRED (owner item 2, 2026-08-06).
411
-
412
- Wave-23 C8/R9 washed every machine-owned cell grey. On the Customer grid that was a handful
413
- of columns; on a `ut_*` database it is EVERY column but the identity one, so the owner's
414
- Instagram table rendered as a grey sheet with one white stripe. `withMachineWash` and
415
- `theme.machineCellTheme` are deleted with it β€” a composer nothing composes is a subject a gate
416
- can still go green on ([[gate-answers-the-wrong-question]]), so the precedence assertions that
417
- guarded it were RETARGETED onto the new law rather than dropped: `makeCell` adds no wash, and
418
- a machine cell keeps exactly the override it already carried.
419
-
420
- What replaced the signal, because removing it without replacing it would be a loss:
421
- Β· the `Pre-set` chip in Hide fields (`isPresetField`) β€” the same word Odoo columns use;
422
- Β· the custom-field DOT no longer painted on them (they are not yours to edit);
423
- Β· and the cells genuinely refuse the edit now (`isMachineWritten`), which the wash never did. */
424
-
425
- function baseCell(
426
- field: Field,
427
- v: CellValue,
428
- editable: boolean,
429
- userAvatars?: Record<string, string>
430
- ): GridCell {
431
- const ro = { allowOverlay: editable, readonly: !editable };
432
- const blank = v == null || v === "";
433
-
434
- switch (field.type) {
435
- case "currency":
436
- return {
437
- kind: GridCellKind.Number,
438
- data: blank ? undefined : num(v),
439
- displayData: blank ? "" : "$" + numberText(num(v), field.format),
440
- contentAlign: "right",
441
- ...ro,
442
- };
443
- case "int":
444
- return {
445
- kind: GridCellKind.Number,
446
- data: blank ? undefined : num(v),
447
- displayData: blank ? "" : numberText(num(v), field.format),
448
- contentAlign: "right",
449
- ...ro,
450
- };
451
- case "formula": {
452
- // Computed client-side (formulaEngine.ts) over values ALREADY injected at this key by
453
- // CustomerGrid's computedRows. Read-only by nature β€” the caller passes editable=false.
454
- // 2026-07-31 (owner item 2): a formula may now return TEXT (CONCATENATE, &, TEXT(),
455
- // TRUE/FALSE) β€” a non-numeric result renders as a text cell, never as NaN.
456
- //
457
- // β›” THE TEST WAS `!Number.isFinite(num(v))` AND IT NEVER FIRED. `num()` returns 0 for
458
- // anything non-finite, so that read `Number.isFinite(0)` β€” always true β€” and every text
459
- // formula printed as `0` here and in `formatDisplay`, which held its own copy of the same
460
- // broken test. `formulaIsText` is now the ONE test, asked of the RAW value, shared by both
461
- // renderers precisely because two copies is how they drifted. See its note in display.ts.
462
- // ⚠ `formulaIsBlank`, NOT this function's shared `blank` (which is `v === ""`). A formula
463
- // returning a SPACE is neither empty by that test nor text by the one below it, so it fell
464
- // through to the numeric path and painted `0` β€” `Number(" ")` is 0. The two predicates are
465
- // written to be total over a formula's three states; using only one of them re-opens the
466
- // gap in miniature.
467
- const formulaBlank = formulaIsBlank(v);
468
- if (!formulaBlank && formulaIsText(v)) {
469
- return {
470
- kind: GridCellKind.Text,
471
- data: v,
472
- displayData: v,
473
- allowOverlay: false,
474
- readonly: true,
475
- };
476
- }
477
- const asNum = num(v);
478
- return {
479
- kind: GridCellKind.Number,
480
- data: formulaBlank ? undefined : asNum,
481
- displayData: formulaBlank ? "" : numberText(asNum, field.format),
482
- contentAlign: "right",
483
- allowOverlay: false,
484
- readonly: true,
485
- };
486
- }
487
- case "pct":
488
- return {
489
- kind: GridCellKind.Number,
490
- data: blank ? undefined : num(v),
491
- displayData: blank ? "" : num(v).toFixed(1) + "%",
492
- contentAlign: "right",
493
- ...ro,
494
- };
495
- /* ⭐ WAVE-26 ITEM 3 β€” `copyData` IS THE STORED STAMP, and it is not decoration.
496
- MEASURED in the installed glide (`data-editor/copy-paste.js::convertCellToBuffer`): a
497
- `Text` cell copies as `copyData ?? displayData`, and the text/plain buffer takes that
498
- FORMATTED string β€” so without this line, copying a date puts the DISPLAY string on the
499
- clipboard. That was survivable while the display read `8/5/2026` (no space, so
500
- `new Date()` re-parsed it); item 3 changed it to `Aug 5, 2026`, whose first space
501
- `parseStamp` turns into `AugT5, 2026` β€” an Invalid Date that renders verbatim forever.
502
- β›” So a display change silently became a WRITE change, one paste away. The same argument
503
- `userCellPayload` records for the assignee cell: a value's clipboard identity is its
504
- STORED form, and leaving it to a fallback makes it depend on which buffer the browser
505
- hands back (the text/html one carries `gdg-raw-value`, the plain one does not).
506
- ⚠ `coerceClipboardValue` normalises a pasted display string as the second half of this;
507
- neither is sufficient alone β€” this one fixes OUR copy, that one fixes Excel's. */
508
- case "date":
509
- return {
510
- kind: GridCellKind.Text,
511
- data: String(v ?? ""),
512
- displayData: dateTimeText(field, v),
513
- copyData: String(v ?? ""),
514
- ...ro,
515
- };
516
- case "created_time":
517
- return {
518
- kind: GridCellKind.Text,
519
- data: String(v ?? ""),
520
- displayData: dateTimeText(field, v),
521
- copyData: String(v ?? ""),
522
- allowOverlay: false,
523
- readonly: true,
524
- };
525
- case "checkbox":
526
- // glide toggles a non-readonly BooleanCell on click and reports it through
527
- // onCellEdited β€” no overlay editor involved.
528
- return {
529
- kind: GridCellKind.Boolean,
530
- data: checkboxOn(v),
531
- allowOverlay: false,
532
- readonly: !editable,
533
- };
534
- case "url":
535
- // Renders as a link. OPENING is CustomerGrid's click path (scheme-guarded);
536
- // hoverEffect gives the pointer affordance.
537
- return {
538
- kind: GridCellKind.Uri,
539
- data: String(v ?? ""),
540
- hoverEffect: true,
541
- ...ro,
542
- };
543
- case "image": {
544
- // Wave-19 R7 / C5. `allowOverlay:false` for the same reason `select` has it: the value is
545
- // a REFERENCE that is picked or uploaded, never typed into a cell β€” the record modal owns
546
- // the picker and the upload. `copyData` carries the raw ref so the column is not invisible
547
- // in a copy or an export (the lesson the avatar cell booked one wave earlier).
548
- const ref = String(v ?? "").trim();
549
- return {
550
- kind: GridCellKind.Custom,
551
- data: {
552
- kind: "aios-image",
553
- url: ref ? assetUrl(ref, "web") : "",
554
- ref,
555
- } satisfies ImageCellData,
556
- copyData: ref,
557
- allowOverlay: false,
558
- };
559
- }
560
- case "json": {
561
- // ⭐ Wave-23 C7 (owner item 5) β€” the compact preview; the DOCUMENT lives in the viewer.
562
- //
563
- // `allowOverlay: false` for the same reason `select` and `image` carry it: glide's text
564
- // overlay is a one-line box, and a one-line box over a 32 KB document is an editor that
565
- // can only damage the value β€” one keystroke in the wrong place and a well-formed payload
566
- // becomes unparseable, saved. CustomerGrid opens the viewer on click instead (the same
567
- // `onCellClicked` path the pickers use), and THAT is where the raw text is editable, with
568
- // parse-on-save.
569
- //
570
- // ⚠ `readonly` is NOT set, and the difference matters: `allowOverlay:false` means "no
571
- // inline editor", while `readonly` would tell glide the CELL cannot change β€” which would
572
- // also block the paste path that legitimately writes a whole document into it.
573
- //
574
- // ⚠ `copyData` carries the RAW document, never the preview (the lesson the image cell
575
- // booked in wave 19). Copy a json column and you get the payload; copy the preview and
576
- // you get the sentence "{…} 5 keys", which is not data and cannot be pasted back.
577
- const raw = String(v ?? "");
578
- const text = jsonPreview(raw);
579
- return {
580
- kind: GridCellKind.Text,
581
- data: text,
582
- displayData: text,
583
- copyData: raw,
584
- allowOverlay: false,
585
- };
586
- }
587
- case "rating": {
588
- const max = ratingMax(field);
589
- const n = Math.max(0, Math.min(max, Math.round(num(v))));
590
- return {
591
- kind: GridCellKind.Custom,
592
- data: { kind: "aios-rating", value: blank ? 0 : n, max } satisfies RatingCellData,
593
- copyData: blank ? "" : String(n),
594
- allowOverlay: false,
595
- };
596
- }
597
- case "automation": {
598
- // Wave-18 C5-AUTOFIELD. The cell is what the last RUN wrote β€” `ok Β· 2026-08-03 14:10 Β·
599
- // 12 posts` β€” so it is read-only by NATURE, not by policy: a value typed here would be
600
- // overwritten by the next run with nothing anywhere saying so. The column's behaviour is
601
- // configured through its gear, the way a formula's expression is.
602
- //
603
- // A tinted CELL rather than a bubble, and that is the whole design: the state and the
604
- // detail are one sentence, and splitting them into two pills would put "2026-08-03 14:10
605
- // Β· 12 posts" in a bubble, which is not what a bubble is for. `bgCell` is the one theme
606
- // key glide alpha-blends (theme.ts:172), so the tints below are the flat pastels rather
607
- // than anything semi-transparent.
608
- const text = String(v ?? "");
609
- return {
610
- kind: GridCellKind.Text,
611
- data: text,
612
- displayData: text,
613
- allowOverlay: false,
614
- readonly: true,
615
- themeOverride: AUTOMATION_TINT[automationState(text)],
616
- };
617
- }
618
- case "link": {
619
- // ⭐ 2026-08-07 β€” a relation, painted as ONE bubble saying how many rows it reaches.
620
- //
621
- // β›” NOT one bubble per linked row, and that is a measured decision rather than a
622
- // simplification: the cell holds row IDS, and a column of `1,2,3` pills tells a reader
623
- // nothing β€” the ids are not names. Airtable can paint the linked record's PRIMARY value
624
- // because it has that row loaded; this client has not loaded the other table at all. So
625
- // the honest cell is the COUNT, and the record drawer is where the rows themselves belong.
626
- //
627
- // ⚠ `copyData` carries the RAW id list, never the "12 posts" sentence β€” the W26 date-cell
628
- // lesson, where a glide Text cell copies `copyData ?? displayData` and the FORMATTED
629
- // string silently reached the clipboard and then the paste path. A count is not data and
630
- // cannot be pasted back into a relation.
631
- const ids = String(v ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
632
- return {
633
- kind: GridCellKind.Bubble,
634
- data: ids.length ? [ids.length === 1 ? "1 record" : `${ids.length} records`] : [],
635
- copyData: String(v ?? ""),
636
- allowOverlay: false,
637
- };
638
- }
639
- case "rollup": {
640
- // ⭐ 2026-08-07 β€” an aggregate the HOST computed. Read-only by nature, exactly like
641
- // `formula`: the value is arithmetic, and a value box over arithmetic is an editor that
642
- // can only produce a number the next refresh throws away.
643
- //
644
- // ⚠ BLANK STAYS BLANK. `_rollup_fold` returns "" for "no rows to aggregate" and only the
645
- // count family ever returns a real 0 β€” so painting `0` here for an empty cell would invent
646
- // the measurement the server just refused to invent. `num(v)` would do exactly that
647
- // (`num("")` is 0), which is why the raw string is rendered rather than a parsed number.
648
- const text = String(v ?? "");
649
- return {
650
- kind: GridCellKind.Text,
651
- data: text,
652
- displayData: text,
653
- copyData: text,
654
- allowOverlay: false,
655
- readonly: true,
656
- };
657
- }
658
- case "status":
659
- return {
660
- kind: GridCellKind.Bubble,
661
- data: [String(v ?? "")],
662
- allowOverlay: false,
663
- themeOverride: STATUS_BUBBLE[String(v ?? "").toLowerCase()],
664
- };
665
- case "user": {
666
- // Wave-14 item 11 / R6 β€” the AVATAR ONLY, no name text. Split out of the `select` branch
667
- // below (it was a name pill until this wave) because "who owns this" is a face, not a
668
- // sentence, once a column has thirty rows of it.
669
- //
670
- // Still `allowOverlay:false`, for the same reason `select` is: the value is PICKED, never
671
- // typed, and CustomerGrid opens its anchored picker on click (onCellClicked β†’ isPickType,
672
- // which already includes `user`, so the click path needs no change).
673
- //
674
- // ⚠ `copyData` carries the NAME. The cell shows no text, so without this the column would
675
- // copy and export as empty β€” invisible in every screenshot. Built by `userCellPayload` in
676
- // display.ts so a node gate can actually assert that (this module imports glide).
677
- return {
678
- kind: GridCellKind.Custom,
679
- ...userCellPayload(String(v ?? ""), userAvatars),
680
- allowOverlay: false,
681
- };
682
- }
683
- case "select": {
684
- // Picked, never typed. `allowOverlay:false` keeps glide's text editor OUT of the way β€”
685
- // a free-text editor on a constrained field is how a column ends up holding "Done",
686
- // "done" and "DONE" as three different values. CustomerGrid opens an anchored picker on
687
- // click instead (onCellClicked), which is also why this stays dependency-free: glide's
688
- // dropdown cell lives in a separate package we deliberately have not added.
689
- const s = String(v ?? "");
690
- const tint = optionTint(field, s);
691
- return {
692
- kind: GridCellKind.Bubble,
693
- data: s ? [s] : [],
694
- allowOverlay: false,
695
- themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
696
- };
697
- }
698
- case "multiselect": {
699
- // The cell holds a comma-joined SET (the `multi` contract the Cohorts column uses), so
700
- // every member paints as its own pill. One themeOverride per CELL is all glide offers, so
701
- // the pills share the first member's tint rather than each carrying its own.
702
- const parts = String(v ?? "")
703
- .split(",")
704
- .map((s) => s.trim())
705
- .filter((s) => s !== "");
706
- const tint = parts.length ? optionTint(field, parts[0]) : undefined;
707
- return {
708
- kind: GridCellKind.Bubble,
709
- data: parts,
710
- allowOverlay: false,
711
- themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
712
- };
713
- }
714
- default:
715
- // text / status-family fallthrough β€” phone and email ride this branch too: typed as
716
- // text in the grid, rendered as actionable tel:/mailto: links in the record drawer.
717
- return {
718
- kind: GridCellKind.Text,
719
- data: String(v ?? ""),
720
- displayData: String(v ?? ""),
721
- ...ro,
722
- };
723
- }
724
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / cells.ts
3
+ // The ONLY place that turns a (field, value) into a glide GridCell. glide has
4
+ // no per-column formatter β€” all formatting is per-cell here, in getCellContent.
5
+ //
6
+ // currency/int -> NumberCell (raw number kept for copy/paste, right-aligned)
7
+ // pct -> NumberCell showing v.toFixed(1)+"%" (yoy_pct is already in percent-points)
8
+ // date -> TextCell (locale date string; read-only, no picker in core)
9
+ // status -> BubbleCell (Airtable-style colored pill via themeOverride)
10
+ // checkbox -> BooleanCell (wave-5 item 11; overlay stores '1' or '')
11
+ // url -> UriCell (renders as a link; opening is CustomerGrid's click path)
12
+ // phone/email -> TextCell (actionable links in the record drawer)
13
+ // rating -> Custom (canvas-drawn stars β€” SVG/vector paths, NEVER emoji)
14
+ // created_time -> TextCell (read-only; the row's `_created`, injected at its key)
15
+ // formula -> NumberCell (client-computed, read-only; blank = could not compute)
16
+ // text/other -> TextCell
17
+ //
18
+ // Wave-5 item 10: `field.format` shapes the DISPLAY string (thousands /
19
+ // decimals 0..4 / 34.0M abbreviation for numbers; include-time + local|utc
20
+ // for dates). A field with NO format renders byte-identically to before the
21
+ // format existed β€” parity is asserted by keeping the default paths in terms
22
+ // of the same toLocaleString calls.
23
+ //
24
+ // Editability is the CALLER's decision (permissions + stratum + type); this
25
+ // module just applies the flag it is handed.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { GridCellKind } from "@glideapps/glide-data-grid";
29
+ import type {
30
+ CustomCell,
31
+ CustomRenderer,
32
+ GridCell,
33
+ Theme,
34
+ } from "@glideapps/glide-data-grid";
35
+ import { assetUrl } from "./catalogData";
36
+ import type { Field } from "./types";
37
+ import { ratingMax } from "./types";
38
+ import {
39
+ LP_BLUE_TEXT,
40
+ LP_BLUE_TINT,
41
+ LP_GREEN_DEEP,
42
+ LP_GREEN_TINT,
43
+ LP_RED_DEEP,
44
+ LP_RED_TINT,
45
+ LP_YELLOW_DEEP,
46
+ LP_YELLOW_TINT,
47
+ STATUS_BUBBLE,
48
+ } from "./theme";
49
+ // ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
50
+ // another. C-AVATAR names choiceColors' as the avatar fallback's source, so the two stay
51
+ // distinguishable at the call site rather than one silently shadowing the other.
52
+ import { optionTint, pickTint as choicePickTint } from "./choiceColors";
53
+ import { automationState, avatarInitials, avatarSize, checkboxOn, dateTimeText, formulaIsBlank,
54
+ codePreview, formulaIsText, jsonPreview, num, numberText, userCellPayload } from "./display";
55
+ import type { AutomationState, CellValue, UserCellData } from "./display";
56
+
57
+ // Wave-7 (item W2): the pure display-string half moved to display.ts so the
58
+ // export builders can run under node without dragging glide along. Re-exported
59
+ // here so every existing import keeps working unchanged.
60
+ export { checkboxOn, dateTimeText, formatDisplay } from "./display";
61
+ // C-AVATAR β€” the pure halves live in display.ts (node-reachable, so a gate can hold them);
62
+ // re-exported here so callers keep importing "the cell module" for everything avatar-shaped.
63
+ export { avatarInitials, avatarSize, userCellPayload } from "./display";
64
+ export type { UserCellData } from "./display";
65
+ // C5-AUTOFIELD β€” same arrangement: the string parsing is pure and lives in display.ts (a node
66
+ // gate can hold it); only the canvas tint table below needs this module.
67
+ export { automationDetail, automationState, automationStateLabel } from "./display";
68
+ export type { AutomationState } from "./display";
69
+ // Wave-23 C7 β€” same arrangement again: the parse, the preview and the pretty-printer are pure
70
+ // (`verify_grid_ux` drives them under node); only the canvas cell below needs this module.
71
+ export { codePreview, jsonParse, jsonPretty, jsonPreview, MAX_JSON_BYTES } from "./display";
72
+
73
+ /**
74
+ * Wave-18 C5-AUTOFIELD β€” the cell tint per automation state.
75
+ *
76
+ * Standing brand rule: the PASTEL is the fill and the measured `-deep` variant carries the ink.
77
+ * `bgCell` + `textDark` is that pairing at cell scale, and every combination below is one of the
78
+ * pairs already measured for `STATUS_BUBBLE` (β‰₯ 4.9:1), so nothing new needed measuring.
79
+ *
80
+ * `none` deliberately has NO override: a cell that has never run reads as an ordinary empty
81
+ * cell, because a tint would claim the automation had produced something.
82
+ */
83
+ const AUTOMATION_TINT: Record<AutomationState, Partial<Theme> | undefined> = {
84
+ ok: { bgCell: LP_GREEN_TINT, textDark: LP_GREEN_DEEP },
85
+ partial: { bgCell: LP_YELLOW_TINT, textDark: LP_YELLOW_DEEP },
86
+ blocked: { bgCell: LP_YELLOW_TINT, textDark: LP_YELLOW_DEEP },
87
+ error: { bgCell: LP_RED_TINT, textDark: LP_RED_DEEP },
88
+ queued: { bgCell: LP_BLUE_TINT, textDark: LP_BLUE_TEXT },
89
+ none: undefined,
90
+ };
91
+
92
+ /** Stable pill tint for a user-defined choice. Hashed from the VALUE, so the same choice keeps
93
+ * its colour across rows, sessions and users without anyone picking one β€” and a renamed option
94
+ * simply gets a new colour rather than inheriting a stale mapping. */
95
+ const PICK_TINTS = [
96
+ // 2026-07-31 (owner item 7): ONE construction β€” every pill is a `-tint` wash carrying its
97
+ // family's `-deep` ink, the standing brand rule ("pastels are fills; text takes the deep
98
+ // weight"). The old second pass (full pastel + near-black ink) is GONE: it is what read as
99
+ // "black font on a saturated chip". Six families now β€” the four C1 hues, the brand purple,
100
+ // and a neutral grey β€” all mirrored from index.css tokens; every pairing measures β‰₯ 5.0:1.
101
+ { bg: "#EDF3FD", fg: "#4F6079" }, // blue-tint / LP_BLUE_TEXT
102
+ { bg: "#EBF6EF", fg: "#35754E" }, // green-tint / green-deep
103
+ { bg: "#FBF4E0", fg: "#7E6428" }, // yellow-tint/ yellow-deep
104
+ { bg: "#FCEEEC", fg: "#A3453C" }, // red-tint / red-deep
105
+ { bg: "#F1EEFB", fg: "#6B57A8" }, // purple-tint/ purple-deep (--lp-purple family)
106
+ { bg: "#EEF1F4", fg: "#4B5563" }, // neutral wash / slate β€” the sixth distinct family
107
+ ];
108
+
109
+ export function pickTint(v: string): { bg: string; fg: string } {
110
+ let h = 0;
111
+ for (let i = 0; i < v.length; i += 1) h = (h * 31 + v.charCodeAt(i)) >>> 0;
112
+ return PICK_TINTS[h % PICK_TINTS.length];
113
+ }
114
+
115
+ // --- rating: a canvas-drawn star row (owner constant: vector, never emoji) --
116
+
117
+ export interface RatingCellData {
118
+ kind: "aios-rating";
119
+ /** 0 = unset (draws all-empty outlines). */
120
+ value: number;
121
+ max: number;
122
+ }
123
+ export type RatingCell = CustomCell<RatingCellData>;
124
+
125
+ function drawStar(
126
+ ctx: CanvasRenderingContext2D,
127
+ cx: number,
128
+ cy: number,
129
+ r: number,
130
+ filled: boolean
131
+ ): void {
132
+ ctx.beginPath();
133
+ for (let i = 0; i < 10; i += 1) {
134
+ const rad = (Math.PI / 5) * i - Math.PI / 2;
135
+ const rr = i % 2 === 0 ? r : r * 0.45;
136
+ const px = cx + Math.cos(rad) * rr;
137
+ const py = cy + Math.sin(rad) * rr;
138
+ if (i === 0) ctx.moveTo(px, py);
139
+ else ctx.lineTo(px, py);
140
+ }
141
+ ctx.closePath();
142
+ if (filled) {
143
+ // I7c: C1's yellow is a FILL token (1.38:1) and a star has to be seen, so the
144
+ // filled star rides the deep amber variant: 3.29:1 on white, clearing the 3:1
145
+ // non-text bar the old gold #C8A24B never did (it measured 2.41:1).
146
+ ctx.fillStyle = "#A98A3E";
147
+ ctx.fill();
148
+ } else {
149
+ ctx.strokeStyle = "rgba(118, 143, 182, 0.55)"; // blue-deep outline, empty slots
150
+ ctx.lineWidth = 1;
151
+ ctx.stroke();
152
+ }
153
+ }
154
+
155
+ // --- user: the assignee AVATAR (wave-14 item 11 / R6 / contract C-AVATAR) -----
156
+ //
157
+ // R6: a grid cell shows the PHOTO OR ICON ONLY β€” no name text. (Pickers and the record modal
158
+ // are where a name belongs; the column is a glanceable "who owns this", and thirty repetitions
159
+ // of "Farhan Sanyoto" down a column is the thing the owner asked to stop reading.)
160
+ //
161
+ // The name is still the cell's COPY value. An avatar-only cell with no `copyData` makes an
162
+ // assignee column copy as nothing β€” a real regression that no screenshot shows.
163
+
164
+ export type UserCell = CustomCell<UserCellData>;
165
+
166
+ /**
167
+ * Decoded avatar images, keyed by their data URL. `null` = this URL failed to decode, so we
168
+ * stop retrying it and paint the fallback forever (a corrupt stored photo must not spin).
169
+ *
170
+ * ⚠ Module scope, like the tint tables above: an Image per cell per frame would re-decode a
171
+ * base64 payload on every scroll tick.
172
+ */
173
+ const _avatarImgs = new Map<string, HTMLImageElement | null>();
174
+ let _avatarRepaint: (() => void) | undefined;
175
+
176
+ /**
177
+ * ⚠ THE HALF THAT IS EASY TO FORGET. glide repaints when `getCellContent`'s identity changes β€”
178
+ * it knows nothing about an `Image.onload` that fires three frames later. Without this hook the
179
+ * fallback initials paint once and STAY, and because the fallback is a deliberate, correct-looking
180
+ * design, nothing on screen says the photo never arrived. (Same shape as wave-13's "honest empty
181
+ * state that made the failure look deliberate".)
182
+ *
183
+ * CustomerGrid calls this once and bumps a counter that is in `useGetCellContent`'s deps.
184
+ */
185
+ export function setAvatarRepaint(fn: (() => void) | undefined): void {
186
+ _avatarRepaint = fn;
187
+ }
188
+
189
+ function avatarImage(dataUrl: string): HTMLImageElement | null {
190
+ const hit = _avatarImgs.get(dataUrl);
191
+ if (hit !== undefined) return hit;
192
+ // A DOM-less environment (a node gate, a locked-down embed) has no Image constructor. Cache
193
+ // the refusal so the fallback is what paints, rather than throwing inside a draw call.
194
+ if (typeof Image === "undefined") {
195
+ _avatarImgs.set(dataUrl, null);
196
+ return null;
197
+ }
198
+ const img = new Image();
199
+ _avatarImgs.set(dataUrl, img);
200
+ img.onload = () => _avatarRepaint?.();
201
+ img.onerror = () => {
202
+ _avatarImgs.set(dataUrl, null);
203
+ _avatarRepaint?.();
204
+ };
205
+ img.src = dataUrl;
206
+ return img;
207
+ }
208
+
209
+ /** C-AVATAR β€” the circle, photo or not. Exported so any other canvas surface paints the same
210
+ * avatar rather than growing a second almost-matching one. */
211
+ export function drawAvatar(
212
+ ctx: CanvasRenderingContext2D,
213
+ cx: number,
214
+ cy: number,
215
+ r: number,
216
+ name: string,
217
+ photo: string | undefined,
218
+ fontFamily: string
219
+ ): void {
220
+ const img = photo ? avatarImage(photo) : null;
221
+ // `complete` alone is not enough: a FAILED decode is also "complete", with a zero natural size.
222
+ if (img && img.complete && img.naturalWidth > 0) {
223
+ ctx.save();
224
+ ctx.beginPath();
225
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
226
+ ctx.clip();
227
+ // COVER, not contain: a portrait must fill the circle, not sit letterboxed inside it.
228
+ const scale = Math.max((r * 2) / img.naturalWidth, (r * 2) / img.naturalHeight);
229
+ const w = img.naturalWidth * scale;
230
+ const h = img.naturalHeight * scale;
231
+ ctx.drawImage(img, cx - w / 2, cy - h / 2, w, h);
232
+ ctx.restore();
233
+ return;
234
+ }
235
+ // The fallback, and it is the DEFAULT state until HOST's C-AVATAR lands β€” never a broken-image
236
+ // glyph. Hashed from the full name so one person keeps one colour across rows and sessions.
237
+ const tint = choicePickTint(name);
238
+ ctx.save();
239
+ ctx.beginPath();
240
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
241
+ ctx.fillStyle = tint.bg;
242
+ ctx.fill();
243
+ ctx.fillStyle = tint.fg;
244
+ ctx.font = `600 ${Math.round(r * 0.9)}px ${fontFamily}`;
245
+ ctx.textAlign = "center";
246
+ ctx.textBaseline = "middle";
247
+ ctx.fillText(avatarInitials(name), cx, cy + 0.5);
248
+ ctx.restore();
249
+ }
250
+
251
+ /** Registered once on the DataEditor (customRenderers), beside the rating renderer. */
252
+ export const userCellRenderer: CustomRenderer<UserCell> = {
253
+ kind: GridCellKind.Custom,
254
+ isMatch: (cell): cell is UserCell =>
255
+ (cell.data as UserCellData | undefined)?.kind === "aios-user",
256
+ draw: (args, cell) => {
257
+ const { ctx, rect, theme } = args;
258
+ const { name, photo } = cell.data;
259
+ if (!name) return true; // unassigned paints nothing β€” an empty circle would look assigned
260
+ const d = avatarSize(rect.height);
261
+ const cx = rect.x + theme.cellHorizontalPadding + d / 2;
262
+ const cy = rect.y + rect.height / 2;
263
+ // Never paint outside the cell: a column dragged narrow drops the avatar rather than
264
+ // bleeding it over its neighbour.
265
+ if (cx + d / 2 > rect.x + rect.width - theme.cellHorizontalPadding) return true;
266
+ drawAvatar(ctx, cx, cy, d / 2, name, photo, theme.fontFamily);
267
+ return true;
268
+ },
269
+ };
270
+
271
+ // --- image: the record THUMBNAIL (wave-19 R7 / contract C5) -------------------
272
+ //
273
+ // The cell holds a REFERENCE, never bytes (`types.ts: imageRefKind`), so what paints here is an
274
+ // <img> the browser fetches from the asset routes and caches like any other image. Same
275
+ // module-scoped decode cache and same repaint hook as the avatar above, and for the same reason:
276
+ // glide repaints on `getCellContent` identity, and knows nothing about an `onload` three frames
277
+ // later. Without the hook the placeholder paints once and stays β€” a deliberate-looking empty
278
+ // frame over a picture that did arrive.
279
+
280
+ export interface ImageCellData {
281
+ kind: "aios-image";
282
+ /** The resolved URL, or "" when the cell is empty (paints the placeholder frame). */
283
+ url: string;
284
+ /** The raw cell value β€” the copy/export payload, so a picture column is not invisible in a CSV. */
285
+ ref: string;
286
+ }
287
+ export type ImageCell = CustomCell<ImageCellData>;
288
+
289
+ const _cellImgs = new Map<string, HTMLImageElement | null>();
290
+
291
+ function cellImage(url: string): HTMLImageElement | null {
292
+ const hit = _cellImgs.get(url);
293
+ if (hit !== undefined) return hit;
294
+ if (typeof Image === "undefined") {
295
+ _cellImgs.set(url, null);
296
+ return null;
297
+ }
298
+ const img = new Image();
299
+ _cellImgs.set(url, img);
300
+ img.onload = () => _avatarRepaint?.();
301
+ img.onerror = () => {
302
+ // A reference that does not resolve is NOT retried: an unknown SKU code is the ordinary
303
+ // state of a product with no master on file, and retrying it every repaint would be a
304
+ // 404 per scroll tick per row.
305
+ _cellImgs.set(url, null);
306
+ _avatarRepaint?.();
307
+ };
308
+ img.src = url;
309
+ return img;
310
+ }
311
+
312
+ /** Registered once on the DataEditor (customRenderers), beside rating and user. */
313
+ export const imageCellRenderer: CustomRenderer<ImageCell> = {
314
+ kind: GridCellKind.Custom,
315
+ isMatch: (cell): cell is ImageCell =>
316
+ (cell.data as ImageCellData | undefined)?.kind === "aios-image",
317
+ draw: (args, cell) => {
318
+ const { ctx, rect, theme } = args;
319
+ const { url } = cell.data;
320
+ const pad = theme.cellHorizontalPadding;
321
+ // Square, inset by 3px top and bottom so a tall row shows a bigger picture and a short one
322
+ // still leaves the grid line visible.
323
+ const size = Math.max(0, Math.min(rect.height - 6, rect.width - pad * 2));
324
+ if (size <= 2) return true; // column dragged too narrow: paint nothing, never bleed
325
+ const x = rect.x + pad;
326
+ const y = rect.y + (rect.height - size) / 2;
327
+ const img = url ? cellImage(url) : null;
328
+ ctx.save();
329
+ ctx.beginPath();
330
+ // A 3px radius, matching the choice pills β€” one rounding vocabulary across the canvas.
331
+ const r = Math.min(3, size / 2);
332
+ ctx.moveTo(x + r, y);
333
+ ctx.arcTo(x + size, y, x + size, y + size, r);
334
+ ctx.arcTo(x + size, y + size, x, y + size, r);
335
+ ctx.arcTo(x, y + size, x, y, r);
336
+ ctx.arcTo(x, y, x + size, y, r);
337
+ ctx.closePath();
338
+ // `complete` alone is not enough β€” a FAILED decode is also complete, with a zero natural size.
339
+ if (img && img.complete && img.naturalWidth > 0) {
340
+ ctx.clip();
341
+ // CONTAIN, not cover: a product photo cropped to a square loses the thing being sold.
342
+ // Letterboxing inside the frame is the honest fit for a catalogue picture.
343
+ const scale = Math.min(size / img.naturalWidth, size / img.naturalHeight);
344
+ const w = img.naturalWidth * scale;
345
+ const h = img.naturalHeight * scale;
346
+ ctx.drawImage(img, x + (size - w) / 2, y + (size - h) / 2, w, h);
347
+ } else {
348
+ // The empty frame: a quiet outline, never a broken-image glyph and never a coloured block
349
+ // that would read as content. Identical whether the cell is empty or the fetch failed β€”
350
+ // the record modal is where a user finds out which, in words.
351
+ ctx.fillStyle = LP_BLUE_TINT;
352
+ ctx.fill();
353
+ ctx.strokeStyle = "rgba(118, 143, 182, 0.45)";
354
+ ctx.lineWidth = 1;
355
+ ctx.stroke();
356
+ }
357
+ ctx.restore();
358
+ return true;
359
+ },
360
+ };
361
+
362
+ /** Registered once on the DataEditor (customRenderers). Pure canvas paths. */
363
+ export const ratingCellRenderer: CustomRenderer<RatingCell> = {
364
+ kind: GridCellKind.Custom,
365
+ isMatch: (cell): cell is RatingCell =>
366
+ (cell.data as RatingCellData | undefined)?.kind === "aios-rating",
367
+ draw: (args, cell) => {
368
+ const { ctx, rect, theme } = args;
369
+ const { value, max } = cell.data;
370
+ const size = 13;
371
+ const gap = 3;
372
+ const cy = rect.y + rect.height / 2;
373
+ let cx = rect.x + theme.cellHorizontalPadding + size / 2;
374
+ const maxRight = rect.x + rect.width - theme.cellHorizontalPadding;
375
+ for (let i = 0; i < max; i += 1) {
376
+ if (cx + size / 2 > maxRight) break; // never paint outside the cell
377
+ drawStar(ctx, cx, cy, size / 2, i < value);
378
+ cx += size + gap;
379
+ }
380
+ return true;
381
+ },
382
+ };
383
+
384
+ /** Build the cell for one (field, value). `editable` gates overlay + readonly.
385
+ *
386
+ * ⚠ A BLANK numeric cell renders EMPTY, never "$0" (2026-07-27). `''`/null is how a value that
387
+ * could not be computed degrades β€” a measure column whose store query failed, an overlay number
388
+ * nobody typed, a FORMULA that hit an error β€” and painting it as $0 would state a number nobody
389
+ * computed. A real 0 arrives as the NUMBER 0 (the pool and the zero-group both emit it) and
390
+ * still renders "$0". Mirrors the blank-vs-zero rule the engine already has (`isBlank`: 0 is
391
+ * NOT blank). */
392
+ export function makeCell(
393
+ field: Field,
394
+ v: CellValue,
395
+ editable: boolean,
396
+ /** C-AVATAR β€” username β†’ data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
397
+ * username absent from it, paints the initials fallback. */
398
+ userAvatars?: Record<string, string>
399
+ ): GridCell {
400
+ // β›” NO MACHINE WASH (owner item 2, 2026-08-06): *"Remove the light grey highlight for the
401
+ // column that is supposedly pre-set."* Wave-23 R9 introduced a grey background on every
402
+ // machine-owned cell; on a `ut_*` database that is EVERY column but one, so the grid read as a
403
+ // sea of grey with a white stripe rather than as a table. The fact it was trying to state β€”
404
+ // *something else fills this column* β€” is now stated in WORDS where a reader will meet it
405
+ // (the `Pre-set` chip in Hide fields, `isPresetField`) and enforced where it matters (the
406
+ // cells refuse the edit, `isMachineWritten`). A label beats a tint the reader has to be taught.
407
+ return baseCell(field, v, editable, userAvatars);
408
+ }
409
+
410
+ /* β›” THE MACHINE WASH IS RETIRED (owner item 2, 2026-08-06).
411
+
412
+ Wave-23 C8/R9 washed every machine-owned cell grey. On the Customer grid that was a handful
413
+ of columns; on a `ut_*` database it is EVERY column but the identity one, so the owner's
414
+ Instagram table rendered as a grey sheet with one white stripe. `withMachineWash` and
415
+ `theme.machineCellTheme` are deleted with it β€” a composer nothing composes is a subject a gate
416
+ can still go green on ([[gate-answers-the-wrong-question]]), so the precedence assertions that
417
+ guarded it were RETARGETED onto the new law rather than dropped: `makeCell` adds no wash, and
418
+ a machine cell keeps exactly the override it already carried.
419
+
420
+ What replaced the signal, because removing it without replacing it would be a loss:
421
+ Β· the `Pre-set` chip in Hide fields (`isPresetField`) β€” the same word Odoo columns use;
422
+ Β· the custom-field DOT no longer painted on them (they are not yours to edit);
423
+ Β· and the cells genuinely refuse the edit now (`isMachineWritten`), which the wash never did. */
424
+
425
+ function baseCell(
426
+ field: Field,
427
+ v: CellValue,
428
+ editable: boolean,
429
+ userAvatars?: Record<string, string>
430
+ ): GridCell {
431
+ const ro = { allowOverlay: editable, readonly: !editable };
432
+ const blank = v == null || v === "";
433
+
434
+ switch (field.type) {
435
+ case "currency":
436
+ return {
437
+ kind: GridCellKind.Number,
438
+ data: blank ? undefined : num(v),
439
+ displayData: blank ? "" : "$" + numberText(num(v), field.format),
440
+ contentAlign: "right",
441
+ ...ro,
442
+ };
443
+ case "int":
444
+ return {
445
+ kind: GridCellKind.Number,
446
+ data: blank ? undefined : num(v),
447
+ displayData: blank ? "" : numberText(num(v), field.format),
448
+ contentAlign: "right",
449
+ ...ro,
450
+ };
451
+ case "formula": {
452
+ // Computed client-side (formulaEngine.ts) over values ALREADY injected at this key by
453
+ // CustomerGrid's computedRows. Read-only by nature β€” the caller passes editable=false.
454
+ // 2026-07-31 (owner item 2): a formula may now return TEXT (CONCATENATE, &, TEXT(),
455
+ // TRUE/FALSE) β€” a non-numeric result renders as a text cell, never as NaN.
456
+ //
457
+ // β›” THE TEST WAS `!Number.isFinite(num(v))` AND IT NEVER FIRED. `num()` returns 0 for
458
+ // anything non-finite, so that read `Number.isFinite(0)` β€” always true β€” and every text
459
+ // formula printed as `0` here and in `formatDisplay`, which held its own copy of the same
460
+ // broken test. `formulaIsText` is now the ONE test, asked of the RAW value, shared by both
461
+ // renderers precisely because two copies is how they drifted. See its note in display.ts.
462
+ // ⚠ `formulaIsBlank`, NOT this function's shared `blank` (which is `v === ""`). A formula
463
+ // returning a SPACE is neither empty by that test nor text by the one below it, so it fell
464
+ // through to the numeric path and painted `0` β€” `Number(" ")` is 0. The two predicates are
465
+ // written to be total over a formula's three states; using only one of them re-opens the
466
+ // gap in miniature.
467
+ const formulaBlank = formulaIsBlank(v);
468
+ if (!formulaBlank && formulaIsText(v)) {
469
+ return {
470
+ kind: GridCellKind.Text,
471
+ data: v,
472
+ displayData: v,
473
+ allowOverlay: false,
474
+ readonly: true,
475
+ };
476
+ }
477
+ const asNum = num(v);
478
+ return {
479
+ kind: GridCellKind.Number,
480
+ data: formulaBlank ? undefined : asNum,
481
+ displayData: formulaBlank ? "" : numberText(asNum, field.format),
482
+ contentAlign: "right",
483
+ allowOverlay: false,
484
+ readonly: true,
485
+ };
486
+ }
487
+ case "pct":
488
+ return {
489
+ kind: GridCellKind.Number,
490
+ data: blank ? undefined : num(v),
491
+ displayData: blank ? "" : num(v).toFixed(1) + "%",
492
+ contentAlign: "right",
493
+ ...ro,
494
+ };
495
+ /* ⭐ WAVE-26 ITEM 3 β€” `copyData` IS THE STORED STAMP, and it is not decoration.
496
+ MEASURED in the installed glide (`data-editor/copy-paste.js::convertCellToBuffer`): a
497
+ `Text` cell copies as `copyData ?? displayData`, and the text/plain buffer takes that
498
+ FORMATTED string β€” so without this line, copying a date puts the DISPLAY string on the
499
+ clipboard. That was survivable while the display read `8/5/2026` (no space, so
500
+ `new Date()` re-parsed it); item 3 changed it to `Aug 5, 2026`, whose first space
501
+ `parseStamp` turns into `AugT5, 2026` β€” an Invalid Date that renders verbatim forever.
502
+ β›” So a display change silently became a WRITE change, one paste away. The same argument
503
+ `userCellPayload` records for the assignee cell: a value's clipboard identity is its
504
+ STORED form, and leaving it to a fallback makes it depend on which buffer the browser
505
+ hands back (the text/html one carries `gdg-raw-value`, the plain one does not).
506
+ ⚠ `coerceClipboardValue` normalises a pasted display string as the second half of this;
507
+ neither is sufficient alone β€” this one fixes OUR copy, that one fixes Excel's. */
508
+ case "date":
509
+ return {
510
+ kind: GridCellKind.Text,
511
+ data: String(v ?? ""),
512
+ displayData: dateTimeText(field, v),
513
+ copyData: String(v ?? ""),
514
+ ...ro,
515
+ };
516
+ case "created_time":
517
+ return {
518
+ kind: GridCellKind.Text,
519
+ data: String(v ?? ""),
520
+ displayData: dateTimeText(field, v),
521
+ copyData: String(v ?? ""),
522
+ allowOverlay: false,
523
+ readonly: true,
524
+ };
525
+ case "checkbox":
526
+ // glide toggles a non-readonly BooleanCell on click and reports it through
527
+ // onCellEdited β€” no overlay editor involved.
528
+ return {
529
+ kind: GridCellKind.Boolean,
530
+ data: checkboxOn(v),
531
+ allowOverlay: false,
532
+ readonly: !editable,
533
+ };
534
+ case "url":
535
+ // Renders as a link. OPENING is CustomerGrid's click path (scheme-guarded);
536
+ // hoverEffect gives the pointer affordance.
537
+ return {
538
+ kind: GridCellKind.Uri,
539
+ data: String(v ?? ""),
540
+ hoverEffect: true,
541
+ ...ro,
542
+ };
543
+ case "image": {
544
+ // Wave-19 R7 / C5. `allowOverlay:false` for the same reason `select` has it: the value is
545
+ // a REFERENCE that is picked or uploaded, never typed into a cell β€” the record modal owns
546
+ // the picker and the upload. `copyData` carries the raw ref so the column is not invisible
547
+ // in a copy or an export (the lesson the avatar cell booked one wave earlier).
548
+ const ref = String(v ?? "").trim();
549
+ return {
550
+ kind: GridCellKind.Custom,
551
+ data: {
552
+ kind: "aios-image",
553
+ url: ref ? assetUrl(ref, "web") : "",
554
+ ref,
555
+ } satisfies ImageCellData,
556
+ copyData: ref,
557
+ allowOverlay: false,
558
+ };
559
+ }
560
+ case "json": {
561
+ // ⭐ Wave-23 C7 (owner item 5) β€” the compact preview; the DOCUMENT lives in the viewer.
562
+ //
563
+ // `allowOverlay: false` for the same reason `select` and `image` carry it: glide's text
564
+ // overlay is a one-line box, and a one-line box over a 32 KB document is an editor that
565
+ // can only damage the value β€” one keystroke in the wrong place and a well-formed payload
566
+ // becomes unparseable, saved. CustomerGrid opens the viewer on click instead (the same
567
+ // `onCellClicked` path the pickers use), and THAT is where the raw text is editable, with
568
+ // parse-on-save.
569
+ //
570
+ // ⚠ `readonly` is NOT set, and the difference matters: `allowOverlay:false` means "no
571
+ // inline editor", while `readonly` would tell glide the CELL cannot change β€” which would
572
+ // also block the paste path that legitimately writes a whole document into it.
573
+ //
574
+ // ⚠ `copyData` carries the RAW document, never the preview (the lesson the image cell
575
+ // booked in wave 19). Copy a json column and you get the payload; copy the preview and
576
+ // you get the sentence "{…} 5 keys", which is not data and cannot be pasted back.
577
+ const raw = String(v ?? "");
578
+ const text = jsonPreview(raw);
579
+ return {
580
+ kind: GridCellKind.Text,
581
+ data: text,
582
+ displayData: text,
583
+ copyData: raw,
584
+ allowOverlay: false,
585
+ };
586
+ }
587
+ case "code": {
588
+ // ⭐ Wave-27 item 13 (R13) β€” the compact preview; the SNIPPET lives in the editor.
589
+ //
590
+ // Every rule the json cell above states applies here for the same reasons, so this is
591
+ // written the same way rather than differently: `allowOverlay:false` because glide's
592
+ // one-line text overlay over a multi-line snippet is an editor that can only damage the
593
+ // value; `readonly` deliberately NOT set, so the paste path that legitimately writes a
594
+ // whole snippet still works; `copyData` the RAW text, never the preview, or copying a code
595
+ // column would yield "SELECT * FROM … +12 more", which is not data and cannot be pasted
596
+ // back (the lesson the image cell booked in wave 19, and the W26 date-cell repeat of it).
597
+ const raw = String(v ?? "");
598
+ const text = codePreview(raw);
599
+ return {
600
+ kind: GridCellKind.Text,
601
+ data: text,
602
+ displayData: text,
603
+ copyData: raw,
604
+ allowOverlay: false,
605
+ };
606
+ }
607
+ case "rating": {
608
+ const max = ratingMax(field);
609
+ const n = Math.max(0, Math.min(max, Math.round(num(v))));
610
+ return {
611
+ kind: GridCellKind.Custom,
612
+ data: { kind: "aios-rating", value: blank ? 0 : n, max } satisfies RatingCellData,
613
+ copyData: blank ? "" : String(n),
614
+ allowOverlay: false,
615
+ };
616
+ }
617
+ case "automation": {
618
+ // Wave-18 C5-AUTOFIELD. The cell is what the last RUN wrote β€” `ok Β· 2026-08-03 14:10 Β·
619
+ // 12 posts` β€” so it is read-only by NATURE, not by policy: a value typed here would be
620
+ // overwritten by the next run with nothing anywhere saying so. The column's behaviour is
621
+ // configured through its gear, the way a formula's expression is.
622
+ //
623
+ // A tinted CELL rather than a bubble, and that is the whole design: the state and the
624
+ // detail are one sentence, and splitting them into two pills would put "2026-08-03 14:10
625
+ // Β· 12 posts" in a bubble, which is not what a bubble is for. `bgCell` is the one theme
626
+ // key glide alpha-blends (theme.ts:172), so the tints below are the flat pastels rather
627
+ // than anything semi-transparent.
628
+ const text = String(v ?? "");
629
+ return {
630
+ kind: GridCellKind.Text,
631
+ data: text,
632
+ displayData: text,
633
+ allowOverlay: false,
634
+ readonly: true,
635
+ themeOverride: AUTOMATION_TINT[automationState(text)],
636
+ };
637
+ }
638
+ case "link": {
639
+ // ⭐ 2026-08-07 β€” a relation, painted as ONE bubble saying how many rows it reaches.
640
+ //
641
+ // β›” NOT one bubble per linked row, and that is a measured decision rather than a
642
+ // simplification: the cell holds row IDS, and a column of `1,2,3` pills tells a reader
643
+ // nothing β€” the ids are not names. Airtable can paint the linked record's PRIMARY value
644
+ // because it has that row loaded; this client has not loaded the other table at all. So
645
+ // the honest cell is the COUNT, and the record drawer is where the rows themselves belong.
646
+ //
647
+ // ⚠ `copyData` carries the RAW id list, never the "12 posts" sentence β€” the W26 date-cell
648
+ // lesson, where a glide Text cell copies `copyData ?? displayData` and the FORMATTED
649
+ // string silently reached the clipboard and then the paste path. A count is not data and
650
+ // cannot be pasted back into a relation.
651
+ const ids = String(v ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
652
+ return {
653
+ kind: GridCellKind.Bubble,
654
+ data: ids.length ? [ids.length === 1 ? "1 record" : `${ids.length} records`] : [],
655
+ copyData: String(v ?? ""),
656
+ allowOverlay: false,
657
+ };
658
+ }
659
+ case "rollup": {
660
+ // ⭐ 2026-08-07 β€” an aggregate the HOST computed. Read-only by nature, exactly like
661
+ // `formula`: the value is arithmetic, and a value box over arithmetic is an editor that
662
+ // can only produce a number the next refresh throws away.
663
+ //
664
+ // ⚠ BLANK STAYS BLANK. `_rollup_fold` returns "" for "no rows to aggregate" and only the
665
+ // count family ever returns a real 0 β€” so painting `0` here for an empty cell would invent
666
+ // the measurement the server just refused to invent. `num(v)` would do exactly that
667
+ // (`num("")` is 0), which is why the raw string is rendered rather than a parsed number.
668
+ const text = String(v ?? "");
669
+ return {
670
+ kind: GridCellKind.Text,
671
+ data: text,
672
+ displayData: text,
673
+ copyData: text,
674
+ allowOverlay: false,
675
+ readonly: true,
676
+ };
677
+ }
678
+ case "status":
679
+ return {
680
+ kind: GridCellKind.Bubble,
681
+ data: [String(v ?? "")],
682
+ allowOverlay: false,
683
+ themeOverride: STATUS_BUBBLE[String(v ?? "").toLowerCase()],
684
+ };
685
+ case "user": {
686
+ // Wave-14 item 11 / R6 β€” the AVATAR ONLY, no name text. Split out of the `select` branch
687
+ // below (it was a name pill until this wave) because "who owns this" is a face, not a
688
+ // sentence, once a column has thirty rows of it.
689
+ //
690
+ // Still `allowOverlay:false`, for the same reason `select` is: the value is PICKED, never
691
+ // typed, and CustomerGrid opens its anchored picker on click (onCellClicked β†’ isPickType,
692
+ // which already includes `user`, so the click path needs no change).
693
+ //
694
+ // ⚠ `copyData` carries the NAME. The cell shows no text, so without this the column would
695
+ // copy and export as empty β€” invisible in every screenshot. Built by `userCellPayload` in
696
+ // display.ts so a node gate can actually assert that (this module imports glide).
697
+ return {
698
+ kind: GridCellKind.Custom,
699
+ ...userCellPayload(String(v ?? ""), userAvatars),
700
+ allowOverlay: false,
701
+ };
702
+ }
703
+ case "select": {
704
+ // Picked, never typed. `allowOverlay:false` keeps glide's text editor OUT of the way β€”
705
+ // a free-text editor on a constrained field is how a column ends up holding "Done",
706
+ // "done" and "DONE" as three different values. CustomerGrid opens an anchored picker on
707
+ // click instead (onCellClicked), which is also why this stays dependency-free: glide's
708
+ // dropdown cell lives in a separate package we deliberately have not added.
709
+ const s = String(v ?? "");
710
+ const tint = optionTint(field, s);
711
+ return {
712
+ kind: GridCellKind.Bubble,
713
+ data: s ? [s] : [],
714
+ allowOverlay: false,
715
+ themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
716
+ };
717
+ }
718
+ case "multiselect": {
719
+ // The cell holds a comma-joined SET (the `multi` contract the Cohorts column uses), so
720
+ // every member paints as its own pill. One themeOverride per CELL is all glide offers, so
721
+ // the pills share the first member's tint rather than each carrying its own.
722
+ const parts = String(v ?? "")
723
+ .split(",")
724
+ .map((s) => s.trim())
725
+ .filter((s) => s !== "");
726
+ const tint = parts.length ? optionTint(field, parts[0]) : undefined;
727
+ return {
728
+ kind: GridCellKind.Bubble,
729
+ data: parts,
730
+ allowOverlay: false,
731
+ themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
732
+ };
733
+ }
734
+ default:
735
+ // text / status-family fallthrough β€” phone and email ride this branch too: typed as
736
+ // text in the grid, rendered as actionable tel:/mailto: links in the record drawer.
737
+ return {
738
+ kind: GridCellKind.Text,
739
+ data: String(v ?? ""),
740
+ displayData: String(v ?? ""),
741
+ ...ro,
742
+ };
743
+ }
744
+ }
web/src/customer-grid/display.ts CHANGED
@@ -329,6 +329,29 @@ export function jsonParse(v: CellValue): { ok: boolean; value?: unknown } {
329
  }
330
  }
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  /** One compact line for a json cell. See the note above for why each case reads as it does. */
333
  export function jsonPreview(v: CellValue): string {
334
  const raw = String(v ?? "").trim();
@@ -548,6 +571,11 @@ export function formatDisplay(field: Field, v: CellValue): string {
548
  // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
549
  // falling through would dump a whole 32 KB document into a CSV cell.
550
  return jsonPreview(v);
 
 
 
 
 
551
  case "automation":
552
  // The machine-written line, verbatim. Explicit rather than left to the `default` branch
553
  // below: `formula` fell through a default once and printed every text result as `0` for
 
329
  }
330
  }
331
 
332
+ /**
333
+ * ⭐ WAVE-27 item 13 (R13) β€” one compact line for a CODE cell.
334
+ *
335
+ * Deliberately NOT `jsonPreview`, and the difference is the whole reason `code` is its own kind:
336
+ * a json preview SUMMARISES a parsed document ("{…} 5 keys"), which it can only do because the
337
+ * value is guaranteed to parse. A snippet has no structure to summarise and often does not parse
338
+ * at all β€” half-written SQL is the normal state of one β€” so the honest preview is the first
339
+ * non-blank LINE, clipped, plus the line count when there is more underneath. That way the cell
340
+ * says what the snippet starts with AND that there is more, instead of inventing a shape for it.
341
+ */
342
+ export function codePreview(v: CellValue): string {
343
+ const raw = String(v ?? "");
344
+ if (raw.trim() === "") return "";
345
+ const lines = raw.split("\n");
346
+ const firstIdx = lines.findIndex((l) => l.trim() !== "");
347
+ const first = clip((lines[firstIdx < 0 ? 0 : firstIdx] ?? "").trim(), 60);
348
+ // The count is of REAL lines, so a snippet padded with blank lines does not claim depth it
349
+ // does not have β€” and it is checkable against what opening the editor shows
350
+ // ([[no-unverifiable-aggregates]]).
351
+ const n = lines.filter((l) => l.trim() !== "").length;
352
+ return n > 1 ? `${first} +${n - 1} more` : first;
353
+ }
354
+
355
  /** One compact line for a json cell. See the note above for why each case reads as it does. */
356
  export function jsonPreview(v: CellValue): string {
357
  const raw = String(v ?? "").trim();
 
571
  // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
572
  // falling through would dump a whole 32 KB document into a CSV cell.
573
  return jsonPreview(v);
574
+ case "code":
575
+ // ⭐ Wave-27 item 13 (R13) β€” the same compact line the canvas cell paints, and explicit
576
+ // for `json`'s exact reason: a snippet is multi-LINE, and falling through to `default`
577
+ // would put raw newlines into a CSV cell, a kanban card and a calendar chip.
578
+ return codePreview(v);
579
  case "automation":
580
  // The machine-written line, verbatim. Explicit rather than left to the `default` branch
581
  // below: `formula` fell through a default once and printed every text result as `0` for
web/src/customer-grid/filterSeed.ts ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / filterSeed.ts
3
+ // ⭐ WAVE 27 Β· OWNER ITEM 22 β€” **A RECORD ADDED ON A FILTERED VIEW SATISFIES THAT VIEW.**
4
+ //
5
+ // THE DEFECT. `addTableRow(scope)` posted `{values: {}}` β€” a blank row, always. On any view
6
+ // with conditions the row is created, is real, and is INVISIBLE: the "+" appears to do nothing,
7
+ // and the record the user is now typing into does not exist as far as they can see. Airtable
8
+ // seeds the conditions it can; so does every spreadsheet-shaped tool, because a create button
9
+ // that produces something you cannot see is indistinguishable from one that failed.
10
+ //
11
+ // β›” WHAT THIS IS NOT. It is not a filter evaluator and must never grow into one. It answers
12
+ // exactly one narrow question β€” *"which cells does this filter FORCE a matching row to hold?"* β€”
13
+ // and its default answer is NOTHING. Every clause below that declines is doing the feature's
14
+ // real work: a guess here is a value written into the user's data that they never typed.
15
+ //
16
+ // β›” THE WALL IS BORROWED, NOT REBUILT. Which columns may receive a value is `mayEditField`'s
17
+ // question and it already answers it (read-only by nature, derived links, machine-written
18
+ // columns incl. the IG pre-set fields, per-field permissions). Re-deciding it here would be a
19
+ // second copy of an edit permission, and the two copies disagreeing is how a machine column
20
+ // gets a hand-written value ([[one-evaluator-per-question]]).
21
+ //
22
+ // ⚠ WHAT IT STILL CANNOT MAKE TRUE, stated rather than hidden: a `cohortLock` (membership is not
23
+ // a cell), a live SEARCH box, and any condition below. A row that lands outside the view for one
24
+ // of those is the pre-existing behaviour, not a regression this introduces β€” and the honest fix
25
+ // for the lock case is a different feature (adding the new row to the cohort), not a value.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import {
29
+ COHORT_FIELD,
30
+ isFilterGroup,
31
+ mayEditField,
32
+ } from "./types";
33
+ import type {
34
+ Conjunction,
35
+ Field,
36
+ FilterGroup,
37
+ FilterNode,
38
+ FilterRule,
39
+ Viewer,
40
+ } from "./types";
41
+
42
+ /**
43
+ * Does this ONE leaf force a value, and if so which?
44
+ *
45
+ * Every `return null` below is a case where a row satisfying the condition exists but is not
46
+ * UNIQUELY determined, or where the value is not a literal at all. Enumerated rather than
47
+ * defaulted, because the tempting shape ("if it has a value, use it") is wrong for most of
48
+ * this vocabulary:
49
+ *
50
+ * Β· `neq` / `doesNotContain` / `isNotEmpty` β€” NEGATIONS. They say what the cell must not be,
51
+ * which leaves every other value legal; picking one would be inventing data to satisfy a
52
+ * condition that never asked for it.
53
+ * Β· `contains` β€” a SUBSTRING is not a value. `contains "Inc"` is satisfied by a cell reading
54
+ * exactly `Inc`, so it is technically derivable, and it is refused anyway: the user asked
55
+ * for rows whose name CONTAINS something, and writing the fragment as the whole name puts a
56
+ * word in the record's identity column that nobody typed.
57
+ * Β· `gt` / `gte` / `lt` / `lte` / `between` / `within` β€” RANGES. Infinitely many satisfying
58
+ * values and no canonical one; `gte 10000` seeding `10000` would be this module choosing a
59
+ * number the user will not notice is not theirs.
60
+ * Β· `isEmpty` β€” already true of a blank new row, so it implies nothing to WRITE. (Returning
61
+ * `""` would be identical in effect and would put an explicit empty in the POST body, which
62
+ * reads as "the user cleared this".)
63
+ * Β· the RANK family (`topN`, `aboveAvg`, …) β€” their truth depends on the OTHER rows, so no
64
+ * cell value can make them true at insert time.
65
+ * Β· a MEASURE leaf (it carries `window`) β€” the subject is a server-computed aggregate over a
66
+ * time window, not a column of this row.
67
+ * Β· a COHORT leaf (`__cohort__`) β€” membership of a set, which is not a cell at all.
68
+ * Β· `rhs` present (CG-9, compare against another attribute) β€” the right-hand side is another
69
+ * COLUMN, so the implied value depends on cells this row does not have yet.
70
+ * Β· an ANCHORED date (`dateMode` other than `exact`) β€” `value` is then an offset like "7", not
71
+ * a date; resolving it would be a second copy of `windows.ts`'s anchor arithmetic, and a
72
+ * wrong copy of a date rule writes a plausible wrong day.
73
+ */
74
+ function impliedValue(rule: FilterRule): string | null {
75
+ if (rule.op !== "eq") return null;
76
+ if (rule.colId === COHORT_FIELD) return null;
77
+ if (rule.window) return null;
78
+ if (rule.rhs) return null;
79
+ if (rule.dateMode && rule.dateMode !== "exact") return null;
80
+ const value = typeof rule.value === "string" ? rule.value : "";
81
+ // A valueless `eq` is a half-written condition (the panel keeps the row while the user picks
82
+ // its value). It narrows nothing yet and implies nothing yet.
83
+ return value.trim() === "" ? null : value;
84
+ }
85
+
86
+ /**
87
+ * Walk the tree, collecting `colId -> the set of values something forces it to hold`.
88
+ *
89
+ * β›” **CONJUNCTIVE PATHS ONLY, AND THAT IS THE LOAD-BEARING RULE.** A row satisfies an `or`
90
+ * group by matching ONE of its branches; taking a value from every branch satisfies none of
91
+ * them in general and can build a row that matches nothing at all ("state is FL **or** state is
92
+ * TX" cannot be answered by a cell). So a group joined by `or` contributes NOTHING β€” not its
93
+ * first branch, which would be this module silently choosing which half of the user's question
94
+ * to answer. Descent continues only through `and`, at any depth.
95
+ */
96
+ function collect(
97
+ nodes: FilterNode[],
98
+ conj: Conjunction,
99
+ into: Map<string, Set<string>>
100
+ ): void {
101
+ if (conj === "or") return;
102
+ for (const node of nodes) {
103
+ if (isFilterGroup(node)) {
104
+ const group = node as FilterGroup;
105
+ collect(group.children || [], group.conj === "or" ? "or" : "and", into);
106
+ continue;
107
+ }
108
+ const rule = node as FilterRule;
109
+ const value = impliedValue(rule);
110
+ if (value === null) continue;
111
+ const bag = into.get(rule.colId) ?? new Set<string>();
112
+ bag.add(value);
113
+ into.set(rule.colId, bag);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The cells a new record must carry to satisfy this view, or `{}` when the filter forces
119
+ * nothing.
120
+ *
121
+ * @param nodes the view's filter tree (`ViewConfig.filters`).
122
+ * @param conj how the ROOT list is joined (`ViewConfig.filterConj`; absent = "and").
123
+ * @param fields the table's columns β€” the only source of "may this receive a value".
124
+ * @param viewer who is adding the row; `mayEditField` fails CLOSED without one for any
125
+ * restricted column, which is the correct direction here too.
126
+ */
127
+ export function filterSeedValues(
128
+ nodes: FilterNode[] | undefined,
129
+ conj: Conjunction | undefined,
130
+ fields: Field[],
131
+ viewer: Viewer | undefined
132
+ ): Record<string, string> {
133
+ const found = new Map<string, Set<string>>();
134
+ collect(Array.isArray(nodes) ? nodes : [], conj === "or" ? "or" : "and", found);
135
+ const byKey = new Map(fields.map((f) => [f.key, f]));
136
+ const out: Record<string, string> = {};
137
+ for (const [colId, values] of found) {
138
+ // β›” A CONTRADICTION CONTRIBUTES NOTHING, INCLUDING ITS FIRST HALF. `name is "A" AND name is
139
+ // "B"` matches no row at all, so there is no value that satisfies it β€” and seeding "A"
140
+ // would produce a row that looks like it should be visible, is not, and now carries a value
141
+ // half the filter refuses. The condition is the user's to fix; the add stays silent about
142
+ // that column.
143
+ if (values.size !== 1) continue;
144
+ const field = byKey.get(colId);
145
+ // A condition naming a column this table does not have (a stale view, a renamed key) is not
146
+ // an error here β€” it simply implies nothing about a cell that does not exist.
147
+ if (!field) continue;
148
+ if (!mayEditField(field, viewer)) continue;
149
+ out[colId] = [...values][0];
150
+ }
151
+ return out;
152
+ }
web/src/customer-grid/folders.ts CHANGED
@@ -40,6 +40,16 @@ export interface FolderStamps {
40
  * (that is the durable form); this is what to render until it does.
41
  */
42
  ordered?: { at: number; order: string[] };
 
 
 
 
 
 
 
 
 
 
43
  }
44
 
45
  export const FOLDER_STAMP_MAX = 64;
@@ -72,6 +82,46 @@ export function pruneFolderStamps(stamps: FolderStamps | undefined, now: number)
72
  // Item 19: a single stamp, so it is kept or dropped whole β€” pruning it by halves is
73
  // exactly the partial sequence the field's own note refuses.
74
  if (isRecent(stamps?.ordered?.at, now) && stamps?.ordered) out.ordered = stamps.ordered;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  return out;
76
  }
77
 
 
40
  * (that is the durable form); this is what to render until it does.
41
  */
42
  ordered?: { at: number; order: string[] };
43
+ /**
44
+ * ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” the FULL VIEW order this browser just set.
45
+ *
46
+ * A separate stamp from `ordered` above, deliberately, even though both are "a list this
47
+ * browser dragged into shape": they age independently and they are different decisions. One
48
+ * stamp holding both would make reordering a folder revive a view order the user had already
49
+ * let go of, and vice versa β€” the exact "a sequence nobody ever chose" failure `ordered`'s own
50
+ * note refuses one level down.
51
+ */
52
+ orderedViews?: { at: number; order: string[] };
53
  }
54
 
55
  export const FOLDER_STAMP_MAX = 64;
 
82
  // Item 19: a single stamp, so it is kept or dropped whole β€” pruning it by halves is
83
  // exactly the partial sequence the field's own note refuses.
84
  if (isRecent(stamps?.ordered?.at, now) && stamps?.ordered) out.ordered = stamps.ordered;
85
+ // Item 5 (C7): the same rule for the VIEW order, kept or dropped whole for the same reason.
86
+ if (isRecent(stamps?.orderedViews?.at, now) && stamps?.orderedViews)
87
+ out.orderedViews = stamps.orderedViews;
88
+ return out;
89
+ }
90
+
91
+ /**
92
+ * ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” the rail's view order, as this browser last set it.
93
+ *
94
+ * β›” WHY IT IS NEEDED AT ALL: the server assembles view order (`aios_grid.py:1602-1647`) and the
95
+ * echo is one round trip behind the drop. Without this the row springs back to its old place the
96
+ * instant the workspace refreshes, which reads as "the drag did not work" β€” the NO-BLIP law's
97
+ * subject, applied to a sequence instead of to a value.
98
+ *
99
+ * ⚠ PAST THE ECHO WINDOW THE SERVER WINS, unconditionally. That asymmetry is the whole design of
100
+ * this module: inside the window a local drag is newer truth; outside it, a difference between
101
+ * the copies is divergence between SESSIONS, and the durable store decides.
102
+ *
103
+ * β›” IDS THE STAMP DOES NOT NAME KEEP THEIR SERVER ORDER, appended after the named ones β€” the
104
+ * same rule the host applies to a `folder_reorder` payload. A view created in another tab since
105
+ * the drop is not evidence that the drop was wrong; dropping it would be this function deleting
106
+ * a view from the rail to defend a sequence.
107
+ */
108
+ export function applyViewOrder<T extends { id: string }>(
109
+ views: T[],
110
+ stamps: FolderStamps | undefined,
111
+ now: number
112
+ ): T[] {
113
+ const stamp = stamps?.orderedViews;
114
+ if (!stamp || !isRecent(stamp.at, now) || !Array.isArray(stamp.order)) return views;
115
+ const byId = new Map(views.map((v) => [v.id, v]));
116
+ const out: T[] = [];
117
+ const placed = new Set<string>();
118
+ for (const id of stamp.order) {
119
+ const v = byId.get(id);
120
+ if (!v || placed.has(id)) continue;
121
+ placed.add(id);
122
+ out.push(v);
123
+ }
124
+ for (const v of views) if (!placed.has(v.id)) out.push(v);
125
  return out;
126
  }
127
 
web/src/customer-grid/iconShapes.ts CHANGED
@@ -123,6 +123,17 @@ export const TYPE_SHAPES: Record<FieldType, IconShape[]> = {
123
  { d: "M9.6 3.2c1.5 0 1.5 3.4 1.5 3.4s.1 1.4 1.5 1.4-1.5 1.4-1.5 1.4 0 3.4-1.5 3.4" },
124
  { d: circle(8, 8, 0.85), fill: true },
125
  ],
 
 
 
 
 
 
 
 
 
 
 
126
  // Wave-19 R7 β€” a framed picture: the mount, a sun, and the hill line every photo glyph
127
  // resolves to at 16px. Drawn on the same 16-unit grid as its neighbours.
128
  image: [
@@ -202,6 +213,16 @@ export const MODE_SHAPES: Record<DisplayMode, IconShape[]> = {
202
  // has to read as a record being MADE, so it is the only mark whose bottom line is open.
203
  // Deliberately not a clipboard (nothing else here has a frame with a tab) and not a pencil
204
  // (an edit affordance means something else app-wide).
 
 
 
 
 
 
 
 
 
 
205
  form: [
206
  { d: "M3.4 2.8h9.2v10.4H3.4z" },
207
  { d: "M5.6 5.6h4.8" },
@@ -374,6 +395,10 @@ export const MODE_LABELS: Record<DisplayMode, string> = {
374
  // it (the public page, the share panel, the `form_submitted` trigger); a synonym here would
375
  // be the one surface calling it something else.
376
  form: "Form",
 
 
 
 
377
  };
378
 
379
  /**
@@ -406,6 +431,24 @@ export const MODE_LABELS: Record<DisplayMode, string> = {
406
  // "C6 HOST MIRROR APPLIED β€” you may flip CREATABLE_MODES now" (2026-08-03), so it is offerable.
407
  // It lands LAST by contract: the owner's seven-mode order above is a product decision and the
408
  // new mode joins the end of it rather than being sorted into it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
  export const CREATABLE_MODES: DisplayMode[] = [
410
  "grid",
411
  "chart",
@@ -437,6 +480,12 @@ export const MODE_TONE: Record<DisplayMode, FolderTone> = {
437
  // board/date, red spatial). A form arranges nothing β€” it is a door records come in through β€”
438
  // so giving it a colour would file it under a family it is not in.
439
  form: "neutral",
 
 
 
 
 
 
440
  };
441
 
442
  /**
@@ -476,6 +525,10 @@ export const TYPE_LABELS: Record<FieldType, string> = {
476
  // "Reference") would make the feature they came for look absent.
477
  link: "Link to another record",
478
  rollup: "Rollup",
 
 
 
 
479
  status: "Lifecycle status (Odoo)", // never creatable; present so the map stays total
480
  };
481
 
 
123
  { d: "M9.6 3.2c1.5 0 1.5 3.4 1.5 3.4s.1 1.4 1.5 1.4-1.5 1.4-1.5 1.4 0 3.4-1.5 3.4" },
124
  { d: circle(8, 8, 0.85), fill: true },
125
  ],
126
+ // ⭐ Wave-27 item 13 (R13) β€” THE ANGLE BRACKETS, the mark every editor on earth uses for
127
+ // "this is source". Drawn as two chevrons with a slash leaning between them, which is what
128
+ // separates it from `json` two entries up: json draws BRACES (a document's own syntax), code
129
+ // draws BRACKETS (a snippet's). Deliberately not a terminal prompt (that reads as "run this",
130
+ // and R13 is explicit there is no execution engine) and not a page of lines (`list` mode and
131
+ // `text` already trade on that reading).
132
+ code: [
133
+ { d: "M5.6 4.9 2.6 8l3 3.1" },
134
+ { d: "M10.4 4.9 13.4 8l-3 3.1" },
135
+ { d: "M9.1 3.6 6.9 12.4" },
136
+ ],
137
  // Wave-19 R7 β€” a framed picture: the mount, a sun, and the hill line every photo glyph
138
  // resolves to at 16px. Drawn on the same 16-unit grid as its neighbours.
139
  image: [
 
213
  // has to read as a record being MADE, so it is the only mark whose bottom line is open.
214
  // Deliberately not a clipboard (nothing else here has a frame with a tab) and not a pencil
215
  // (an edit affordance means something else app-wide).
216
+ // ⭐ Wave-27 C3 (owner item 8) β€” a CARD WITH TWO ARROWS LEAVING IT, left and right. Every
217
+ // other mark here draws an arrangement of many records; this one has to read as ONE record
218
+ // with two exits, because that is exactly what the deck is. Deliberately not a stack of cards
219
+ // (that is a lane, and `kanban` owns it) and not a hand or a gesture glyph (nothing else in
220
+ // this vocabulary draws a body part, and it would read as "drag" rather than "decide").
221
+ swipe: [
222
+ { d: "M5.4 3.4h5.2v9.2H5.4z" },
223
+ { d: "M3.6 8H1.4M2.8 6.8 1.4 8l1.4 1.2" },
224
+ { d: "M12.4 8h2.2M13.2 6.8 14.6 8l-1.4 1.2" },
225
+ ],
226
  form: [
227
  { d: "M3.4 2.8h9.2v10.4H3.4z" },
228
  { d: "M5.6 5.6h4.8" },
 
395
  // it (the public page, the share panel, the `form_submitted` trigger); a synonym here would
396
  // be the one surface calling it something else.
397
  form: "Form",
398
+ // ⭐ Wave-27 C3 (item 8) β€” the owner's own word for it. Not "Triage" or "Review": the gesture
399
+ // IS the name here, and the two candidates both collide with vocabulary this product already
400
+ // spends elsewhere (a `review` automation decision, the retired review lanes).
401
+ swipe: "Swipe",
402
  };
403
 
404
  /**
 
431
  // "C6 HOST MIRROR APPLIED β€” you may flip CREATABLE_MODES now" (2026-08-03), so it is offerable.
432
  // It lands LAST by contract: the owner's seven-mode order above is a product decision and the
433
  // new mode joins the end of it rather than being sorted into it.
434
+ // ⭐ Wave-27 C3 (owner item 8) β€” `swipe` is HELD OUT of this list, and the reason corrects a
435
+ // mistake this file made an hour earlier.
436
+ //
437
+ // β›” THE HOLD WAS NEVER ONLY ABOUT THE TWO REGISTRIES. It was first written as "do not offer a
438
+ // mode the HOST has not accepted", and one session owning both registries this wave genuinely
439
+ // does close that half β€” which is what made it tempting to skip. But the rule the hold really
440
+ // encodes is broader and this wave proved it: **do not offer a mode whose CONSUMER does not
441
+ // exist.** `swipe` was briefly listed here while `CustomerGrid`'s mode dispatch had no branch
442
+ // for it, so picking "Swipe" wrote a mode the host now happily PERSISTS, and the body rendered
443
+ // a grid under a chip reading "View Β· Swipe" β€” surviving reload, with the agreement leg green
444
+ // because it only ever compared two lists.
445
+ //
446
+ // So the hold stands until SESSION C mounts `SwipeView` (contract C3), and it is no longer a
447
+ // mailbox handshake: `verify_icons` DERIVES the condition β€” either `swipe` is absent here, or
448
+ // `CustomerGrid.tsx` mounts `SwipeView` β€” so the mount landing flips the gate green on its own
449
+ // and nobody has to remember this line. `form` (wave-23) is the same defect from the other
450
+ // direction, sitting unoffered because its host mirror never landed; both are booked in D's
451
+ // mailbox as one shape.
452
  export const CREATABLE_MODES: DisplayMode[] = [
453
  "grid",
454
  "chart",
 
480
  // board/date, red spatial). A form arranges nothing β€” it is a door records come in through β€”
481
  // so giving it a colour would file it under a family it is not in.
482
  form: "neutral",
483
+ // ⭐ Wave-27 C3 β€” YELLOW, with `kanban`, and this is a family claim rather than a leftover:
484
+ // a swipe deck writes the SAME single-select a kanban stacks by (R2 binds it to one), so the
485
+ // two are one family seen at two zooms β€” all the lanes at once, or one card at a time. Filing
486
+ // it neutral (the `catalog`/`form` reasoning) would be wrong for the opposite reason those
487
+ // two are neutral: this mode does arrange records, and it arranges them by the board's field.
488
+ swipe: "yellow",
489
  };
490
 
491
  /**
 
525
  // "Reference") would make the feature they came for look absent.
526
  link: "Link to another record",
527
  rollup: "Rollup",
528
+ // ⭐ Wave-27 item 13 (R13) β€” "Code", not "Snippet" or "Source": it is the word the field kind
529
+ // is called everywhere else in this wave (the ruling, the language picker, the viewer header),
530
+ // and it says what the column holds without implying the product will run it.
531
+ code: "Code",
532
  status: "Lifecycle status (Odoo)", // never creatable; present so the map stays total
533
  };
534
 
web/src/customer-grid/timeSeriesData.ts CHANGED
@@ -31,6 +31,46 @@
31
  import type { ChartAgg, ChartModel } from "../viz/chartData";
32
  import { TS_MAX_BUCKETS, TS_MAX_FIELDS, TS_MAX_LAST_N, TS_BUCKETS } from "./types";
33
  import type { Field, Row, TsBucket, TsCellStyle, TsCustomRow, TsDeltaKind } from "./types";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  // ---------------------------------------------------------------- the wire
36
 
@@ -1025,7 +1065,10 @@ export function buildTsSheet(
1025
  const rows: TsSheetRow[] = table.rows.map((r) => ({
1026
  id: r.field,
1027
  kind: "metric" as const,
1028
- label: r.label,
 
 
 
1029
  sublabel: r.window?.label,
1030
  agg: r.agg,
1031
  cells: r.cells,
 
31
  import type { ChartAgg, ChartModel } from "../viz/chartData";
32
  import { TS_MAX_BUCKETS, TS_MAX_FIELDS, TS_MAX_LAST_N, TS_BUCKETS } from "./types";
33
  import type { Field, Row, TsBucket, TsCellStyle, TsCustomRow, TsDeltaKind } from "./types";
34
+ import { WINDOW_LABELS } from "./windows";
35
+
36
+ /**
37
+ * ⭐ WAVE-27 item 18 (I4) β€” drop a measure label's trailing WINDOW QUALIFIER, except YTD.
38
+ *
39
+ * A measure column is named `"<measure> Β· <window>"` (`ColumnMenu.tsx:1454`), and a time-series
40
+ * row ALREADY prints its window as the sublabel underneath β€” so the period was being said twice
41
+ * in a stack two lines tall. This removes the duplicate, and only the duplicate.
42
+ *
43
+ * β›” THREE GUARDS, and every one of them is here because a looser rule breaks a REAL label in
44
+ * this product's own contract (measured against `aios_grid_fields.json`, not imagined):
45
+ *
46
+ * 1. ONLY the `" Β· "` form. A substring match on period words would eat "Days of supply"
47
+ * (the "ly" is in "supply") and reduce "YoY %" to "%". Both are live labels.
48
+ * 2. ONLY a phrase from the CLOSED `WINDOW_LABELS` vocabulary. Anything else after a `Β·` is
49
+ * somebody's own naming and none of this function's business.
50
+ * 3. ONLY when the row still shows the window as a SUBLABEL. Without that, stripping does not
51
+ * de-duplicate β€” it DELETES the only statement of the period on screen, and two rows over
52
+ * different windows would then render under one identical name.
53
+ *
54
+ * `ytd` is exempt per I4: "Revenue YTD" is how people say the metric's NAME, not a period they
55
+ * would rather see below it. ⚠ `ytd_last_year` ("last year to date") is NOT exempt β€” I4 names
56
+ * YTD, and LYTD is a comparison period rather than an identity. Flagged in D's mailbox as the
57
+ * one judgement call in this rule.
58
+ */
59
+ export function stripWindowStamp(label: string, sublabel?: string): string {
60
+ if (!sublabel) return label; // guard 3
61
+ const cut = label.lastIndexOf(" Β· ");
62
+ if (cut < 0) return label; // guard 1
63
+ const tail = label.slice(cut + 3).trim();
64
+ if (tail === WINDOW_LABELS.ytd) return label; // I4's exception
65
+ const known = Object.values(WINDOW_LABELS).some((phrase) =>
66
+ phrase.includes("{n}")
67
+ // `the last {n} days` -> match any integer, and ONLY an integer.
68
+ ? new RegExp(`^${phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
69
+ .replace("\\{n\\}", "\\d+")}$`).test(tail)
70
+ : phrase === tail
71
+ );
72
+ return known ? label.slice(0, cut).trimEnd() : label; // guard 2
73
+ }
74
 
75
  // ---------------------------------------------------------------- the wire
76
 
 
1065
  const rows: TsSheetRow[] = table.rows.map((r) => ({
1066
  id: r.field,
1067
  kind: "metric" as const,
1068
+ // ⭐ WAVE-27 item 18 (I4) β€” the window qualifier comes OFF the row label here, once, at the
1069
+ // build. Every consumer inherits it: the panel, the CSV export and the clipboard export all
1070
+ // read `sheet.rows[].label`, so stripping at each of them would be three chances to disagree.
1071
+ label: stripWindowStamp(r.label, r.window?.label),
1072
  sublabel: r.window?.label,
1073
  agg: r.agg,
1074
  cells: r.cells,
web/src/customer-grid/types.ts CHANGED
@@ -67,10 +67,56 @@ export type FieldType =
67
  // is what lets Royal's 1,142 existing SKU masters appear with nothing uploaded, and it keeps
68
  // the row payload the same size it was β€” a base64 image per row would be a megabyte tax on
69
  // every scroll.
70
- | "image";
 
 
 
 
 
 
 
 
 
71
 
72
  export type FieldSource = "odoo" | "overlay";
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  /** The types a user may create from the column menu. Odoo-sourced fields are not in this list β€”
75
  * their type comes from the model, and `status` in particular is Odoo's lifecycle, not a
76
  * user-defined set. */
@@ -108,6 +154,15 @@ export const CREATABLE_TYPES: readonly FieldType[] = [
108
  // That is the honest state rather than a hidden entry β€” a menu whose contents change based on
109
  // which page you are on is a menu people stop trusting.
110
  "link", "rollup",
 
 
 
 
 
 
 
 
 
111
  ];
112
 
113
  /**
@@ -347,9 +402,19 @@ export type FieldScope = "cohort" | "global";
347
  // accepts the name β€” the identical hold `timeseries` and `catalog` served, for the identical
348
  // reason: `_clean_display` DROPS an unknown mode, so offering it early would let somebody build
349
  // a whole form, share its link, and have the view silently revert to a grid on the next read.
 
 
 
 
 
 
 
 
 
 
350
  export const DISPLAY_MODES = [
351
  "grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries", "catalog",
352
- "form",
353
  ] as const;
354
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
355
 
@@ -482,6 +547,23 @@ export interface DisplaySpec {
482
  * say what to print.
483
  */
484
  catalogs?: CatalogSpec[];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  }
486
 
487
  /**
@@ -506,6 +588,13 @@ export const TS_MAX_LAST_N = 120;
506
  export const TS_MAX_FIELDS = 12;
507
  /** C-DISP β€” the cap on a calendar view's summary metrics. */
508
  export const MAX_CALENDAR_METRICS = 4;
 
 
 
 
 
 
 
509
 
510
  // ── C6-CATALOG (wave 18, owner item 4) β€” the catalog view's vocabulary and caps ──────────────
511
  // Every name below is mirrored by `aios_grid.py` under the SAME name, and `cleanCatalogs`
@@ -979,6 +1068,23 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
979
  // ── C6-CATALOG (wave 18) ────────────────────────────────────────────────────────────────
980
  const catalogs = cleanCatalogs(d.catalogs);
981
  if (catalogs) out.catalogs = catalogs;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
  if (
983
  out.mode === "grid" &&
984
  !out.dateField &&
@@ -1009,7 +1115,12 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
1009
  // that makes that true. Without it, switching a catalog view back to Grid reduces the whole
1010
  // spec to `undefined` and the user's catalogues are GONE on the next save β€” the only key
1011
  // here whose payload is authored content rather than a re-derivable projection.
1012
- !out.catalogs
 
 
 
 
 
1013
  )
1014
  return undefined;
1015
  return out;
@@ -1309,10 +1420,10 @@ export interface Field {
1309
  urlField?: string;
1310
  /** kind-specific knobs. Scalars only β€” the host clamps keys and value lengths. */
1311
  settings?: Record<string, string | number | boolean>;
1312
- /** the automation definition that owns this column (engine-stamped; the machine marker). */
1313
- flowId?: string;
1314
- /** true when the field is part of a product-owned preset schema and cannot be redefined */
1315
- preset?: boolean;
1316
  /** true on the `stage_<autoId>` column an automation board walks its records through. */
1317
  stageField?: boolean;
1318
  };
@@ -1434,12 +1545,12 @@ export interface Field {
1434
  table: string;
1435
  /** the column IN THE LINKED TABLE that holds this row's key β€” presence = derived */
1436
  on?: string;
1437
- /** the column on THIS table supplying the join value; defaults to the profile/pinned one */
1438
- from?: string;
1439
- /** source link field key when this is Airtable's computed reciprocal side */
1440
- inverse?: string;
1441
- /** reciprocal field key on the target table when this is the user-picked source side */
1442
- reciprocal?: string;
1443
  /** Airtable's `prefersSingleRecordLink` */
1444
  single?: boolean;
1445
  };
@@ -1459,27 +1570,34 @@ export interface Field {
1459
  /** the column in the linked table to aggregate; absent only for `countall` */
1460
  field?: string;
1461
  fn: RollupFn;
1462
- limit?: number;
1463
- sortBy?: string;
1464
- sortDir?: "asc" | "desc";
1465
- /** collapse duplicate logical records after ranking, before applying the window */
1466
- distinctBy?: string;
1467
- /** optional Airtable-style conditions applied to linked records before aggregation */
1468
- conditions?: RollupCondition[];
1469
- conditionConj?: "and" | "or";
1470
- };
1471
- }
1472
-
1473
- export const ROLLUP_CONDITION_OPS = [
1474
- "eq", "neq", "contains", "not_contains", "is_empty", "is_not_empty",
1475
- "gt", "gte", "lt", "lte",
1476
- ] as const;
1477
- export type RollupConditionOp = (typeof ROLLUP_CONDITION_OPS)[number];
1478
- export interface RollupCondition {
1479
- field: string;
1480
- op: RollupConditionOp;
1481
- value?: string;
1482
- }
 
 
 
 
 
 
 
1483
 
1484
  /**
1485
  * Airtable's 17 rollup functions, minus the two that are meaningless over a scalar cell.
@@ -1491,7 +1609,7 @@ export interface RollupCondition {
1491
  * the same discipline every other cross-language vocabulary here uses.
1492
  */
1493
  export const ROLLUP_FNS = [
1494
- "sum", "average", "min", "max", "latest", "count", "counta", "countall",
1495
  "and", "or", "xor", "concatenate", "arrayjoin", "arraycompact", "arrayunique",
1496
  ] as const;
1497
  export type RollupFn = (typeof ROLLUP_FNS)[number];
@@ -1502,8 +1620,8 @@ export const ROLLUP_NUMERIC_FNS: ReadonlySet<string> =
1502
 
1503
  /** Human wording for each function, so a column menu never shows a bare identifier. */
1504
  export const ROLLUP_FN_LABELS: Record<RollupFn, string> = {
1505
- sum: "Sum", average: "Average", min: "Minimum", max: "Maximum",
1506
- latest: "Latest value",
1507
  count: "Count of numbers", counta: "Count of filled cells", countall: "Count of records",
1508
  and: "All are true", or: "Any is true", xor: "Exactly one is true",
1509
  concatenate: "Join (no separator)", arrayjoin: "Join with commas",
@@ -1517,9 +1635,9 @@ export const ROLLUP_FN_LABELS: Record<RollupFn, string> = {
1517
  * is rewritten on every refresh pass, so accepting a typed value would not merely be wrong β€” it
1518
  * would appear to work and then silently revert, which is worse than refusing it.
1519
  */
1520
- export function isDerivedLink(field: Field): boolean {
1521
- return field.type === "link" && !!(field.link?.on || field.link?.inverse);
1522
- }
1523
 
1524
  /**
1525
  * Is this the table's PROFILE column (C3/R7)?
@@ -2353,7 +2471,23 @@ export function allViewName(scope: string): string {
2353
  * the host refuses β€” a menu entry that emits an event the host silently drops is worse than
2354
  * no entry at all, because it reads as success.
2355
  */
2356
- export const UNDELETABLE_VIEW_IDS = new Set([ALL_VIEW_ID]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2357
 
2358
  // ─────────────────────────────────────────────── wave 16 C-TOPIC: the grid's TOPIC
2359
  /**
@@ -2855,11 +2989,11 @@ export interface ScopeCounts {
2855
  windowed: boolean;
2856
  }
2857
 
2858
- export interface CustomersPayload {
2859
- fields: Field[];
2860
- rows: Row[];
2861
- /** false on automation-owned child databases whose records are populated only by the engine */
2862
- recordsMutable?: boolean;
2863
  workspace?: GridWorkspace;
2864
  /** Present only for server-windowed tables. See ScopeCounts. */
2865
  counts?: ScopeCounts;
 
67
  // is what lets Royal's 1,142 existing SKU masters appear with nothing uploaded, and it keeps
68
  // the row payload the same size it was β€” a base64 image per row would be a megabyte tax on
69
  // every scroll.
70
+ | "image"
71
+ // ⭐ WAVE-27 item 13 (owner ruling R13) β€” `code` is a SNIPPET on a record: a query, a config
72
+ // block, a template, a webhook payload someone pasted. It is `json`'s sibling and differs in
73
+ // exactly one way that matters: json's value must PARSE (the host refuses one that does not),
74
+ // and a code cell's must not β€” half-written SQL is the normal state of a snippet, and a
75
+ // validator would refuse the very thing the column is for. So the cell is a plain string with
76
+ // a per-column `language` that selects a HIGHLIGHTER and nothing else. R13: "syntax-highlighted
77
+ // storage + language config, NO execution engine" β€” no value of `language` may ever reach a
78
+ // run path, and there is none to reach.
79
+ | "code";
80
 
81
  export type FieldSource = "odoo" | "overlay";
82
 
83
+ /**
84
+ * R13 β€” the languages a `code` column may declare. Mirrors `aios_grid.CODE_LANGUAGES`
85
+ * name-for-name; the fields-contract gate diffs the two, because a language the client offers
86
+ * and the host does not know silently degrades to `plain` on the next read.
87
+ *
88
+ * Short on purpose: every entry costs a real highlighter, and an unimplemented language would
89
+ * paint plain text under a label promising colour. `plain` is the default AND the fallback.
90
+ */
91
+ export const CODE_LANGUAGES = [
92
+ "plain", "json", "sql", "python", "javascript", "typescript",
93
+ "html", "css", "markdown", "yaml", "xml", "shell",
94
+ ] as const;
95
+ export type CodeLanguage = (typeof CODE_LANGUAGES)[number];
96
+
97
+ /** Human labels for the picker β€” the vocabulary above is wire values, not display text. */
98
+ export const CODE_LANGUAGE_LABELS: Record<CodeLanguage, string> = {
99
+ plain: "Plain text",
100
+ json: "JSON",
101
+ sql: "SQL",
102
+ python: "Python",
103
+ javascript: "JavaScript",
104
+ typescript: "TypeScript",
105
+ html: "HTML",
106
+ css: "CSS",
107
+ markdown: "Markdown",
108
+ yaml: "YAML",
109
+ xml: "XML",
110
+ shell: "Shell",
111
+ };
112
+
113
+ export function codeLanguageOf(field: { code?: { language?: string } }): CodeLanguage {
114
+ const lang = field.code?.language;
115
+ return (CODE_LANGUAGES as readonly string[]).includes(lang ?? "")
116
+ ? (lang as CodeLanguage)
117
+ : "plain";
118
+ }
119
+
120
  /** The types a user may create from the column menu. Odoo-sourced fields are not in this list β€”
121
  * their type comes from the model, and `status` in particular is Odoo's lifecycle, not a
122
  * user-defined set. */
 
154
  // That is the honest state rather than a hidden entry β€” a menu whose contents change based on
155
  // which page you are on is a menu people stop trusting.
156
  "link", "rollup",
157
+ // ⭐ WAVE-27 item 13 (R13) β€” landing in the SAME change as `FieldType`, `CUSTOM_FIELD_TYPES`,
158
+ // `UT_FIELD_TYPES`, the shape/label/sprite tables, the cell renderer and the ColumnMenu
159
+ // editor. `json`'s close-out audit is the reason that sentence is worth writing down: it
160
+ // reached four of five surfaces and shipped real, documented and unreachable.
161
+ //
162
+ // ⚠ Unlike `link`/`rollup` it needs NO config bag to be creatable β€” a code column with no
163
+ // declared language stores and renders as plain text, which is a legitimate state. So
164
+ // `ColumnMenu.canCreate` does not gate on it, and the language picker is an ordinary edit.
165
+ "code",
166
  ];
167
 
168
  /**
 
402
  // accepts the name β€” the identical hold `timeseries` and `catalog` served, for the identical
403
  // reason: `_clean_display` DROPS an unknown mode, so offering it early would let somebody build
404
  // a whole form, share its link, and have the view silently revert to a grid on the next read.
405
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3): `swipe` β€” a DECK of the records whose bound
406
+ // single-select is EMPTY, triaged one at a time into two of that field's options.
407
+ //
408
+ // ⚠ It is the FIRST mode to land WITHOUT the staged hold every mode above it served, and that is
409
+ // a fact about ownership rather than a relaxation of the rule: wave 27 gives one session both
410
+ // `aios_grid.DISPLAY_MODES` and this file, so the host mirror and the client registry ship in the
411
+ // SAME change and there is never a moment where one knows the name and the other does not. The
412
+ // hold existed to cover exactly that gap. `icons.test.ts` still asserts the agreement, so a future
413
+ // session that adds a mode to only one end goes red rather than shipping a view that silently
414
+ // reverts to a grid on the next read.
415
  export const DISPLAY_MODES = [
416
  "grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries", "catalog",
417
+ "form", "swipe",
418
  ] as const;
419
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
420
 
 
547
  * say what to print.
548
  */
549
  catalogs?: CatalogSpec[];
550
+ /**
551
+ * ⭐ WAVE-27 C3 (item 8 / R2) β€” the swipe deck's BINDING: which single-select the deck triages
552
+ * into, and which of its options each direction writes.
553
+ *
554
+ * All three parts or none. `cleanDisplay` and the host's `_clean_display` both drop the WHOLE
555
+ * key rather than a part of it, deliberately breaking the per-entry-drop rule `charts` and
556
+ * `calendarMetrics` follow above: those are lists of independent cards, so losing one entry
557
+ * costs one card, while this is a single binding whose parts are meaningless apart. A deck with
558
+ * a field and one option is not a degraded deck β€” it is a deck that can never write anything,
559
+ * painted as though it were configured.
560
+ *
561
+ * ⚠ Neither validator can check that `fieldKey` still names a SELECT, or that the two options
562
+ * are still in its vocabulary β€” `cleanDisplay` resolves no field refs at all (the rule the
563
+ * `dateField`/`stackField` loop states). `SwipeView` owns those three losses and must SHOW
564
+ * each one instead of falling back to a first option (`viewModes.tsx`'s house rule).
565
+ */
566
+ swipe?: { fieldKey: string; leftOption: string; rightOption: string };
567
  }
568
 
569
  /**
 
588
  export const TS_MAX_FIELDS = 12;
589
  /** C-DISP β€” the cap on a calendar view's summary metrics. */
590
  export const MAX_CALENDAR_METRICS = 4;
591
+ /**
592
+ * C3 (item 8) β€” the swipe binding's option cap. Mirrors `aios_grid.MAX_SWIPE_OPTION`, which is
593
+ * itself the 120 `_clean_options` trims every choice to β€” NOT a second opinion about how long an
594
+ * option may be. A shorter cap here would silently refuse a binding to a legal option, which is
595
+ * the mirror-drift failure this file's clause-by-clause parity exists to prevent.
596
+ */
597
+ export const MAX_SWIPE_OPTION = 120;
598
 
599
  // ── C6-CATALOG (wave 18, owner item 4) β€” the catalog view's vocabulary and caps ──────────────
600
  // Every name below is mirrored by `aios_grid.py` under the SAME name, and `cleanCatalogs`
 
1068
  // ── C6-CATALOG (wave 18) ────────────────────────────────────────────────────────────────
1069
  const catalogs = cleanCatalogs(d.catalogs);
1070
  if (catalogs) out.catalogs = catalogs;
1071
+ // ── ⭐ WAVE-27 C3 (item 8 / R2): the swipe binding ───────────────────────────────────────
1072
+ // Byte-for-byte the host's clause, in the same order, including the case-insensitive
1073
+ // distinctness test β€” this file's standing law is that an accepted save reads back
1074
+ // identically on both engines, and "left and right are the same option" is the one rejection
1075
+ // a user could reach through the picker.
1076
+ if (d.swipe && typeof d.swipe === "object" && !Array.isArray(d.swipe)) {
1077
+ const s = d.swipe as Record<string, unknown>;
1078
+ if (
1079
+ typeof s.fieldKey === "string" && s.fieldKey !== "" &&
1080
+ typeof s.leftOption === "string" && typeof s.rightOption === "string"
1081
+ ) {
1082
+ const left = s.leftOption.trim().slice(0, MAX_SWIPE_OPTION);
1083
+ const right = s.rightOption.trim().slice(0, MAX_SWIPE_OPTION);
1084
+ if (left && right && left.toLowerCase() !== right.toLowerCase())
1085
+ out.swipe = { fieldKey: s.fieldKey, leftOption: left, rightOption: right };
1086
+ }
1087
+ }
1088
  if (
1089
  out.mode === "grid" &&
1090
  !out.dateField &&
 
1115
  // that makes that true. Without it, switching a catalog view back to Grid reduces the whole
1116
  // spec to `undefined` and the user's catalogues are GONE on the next save β€” the only key
1117
  // here whose payload is authored content rather than a re-derivable projection.
1118
+ !out.catalogs &&
1119
+ // C3 β€” the swipe binding rides the W13 carry with every key above it: Swipe -> Grid ->
1120
+ // Swipe restores the bound field and both options instead of reopening the picker. Missing
1121
+ // this line is not cosmetic β€” it would reduce a swipe view switched back to Grid to
1122
+ // `undefined`, and the binding would be GONE on the next save.
1123
+ !out.swipe
1124
  )
1125
  return undefined;
1126
  return out;
 
1420
  urlField?: string;
1421
  /** kind-specific knobs. Scalars only β€” the host clamps keys and value lengths. */
1422
  settings?: Record<string, string | number | boolean>;
1423
+ /** the automation definition that owns this column (engine-stamped; the machine marker). */
1424
+ flowId?: string;
1425
+ /** true when the field is part of a product-owned preset schema and cannot be redefined */
1426
+ preset?: boolean;
1427
  /** true on the `stage_<autoId>` column an automation board walks its records through. */
1428
  stageField?: boolean;
1429
  };
 
1545
  table: string;
1546
  /** the column IN THE LINKED TABLE that holds this row's key β€” presence = derived */
1547
  on?: string;
1548
+ /** the column on THIS table supplying the join value; defaults to the profile/pinned one */
1549
+ from?: string;
1550
+ /** source link field key when this is Airtable's computed reciprocal side */
1551
+ inverse?: string;
1552
+ /** reciprocal field key on the target table when this is the user-picked source side */
1553
+ reciprocal?: string;
1554
  /** Airtable's `prefersSingleRecordLink` */
1555
  single?: boolean;
1556
  };
 
1570
  /** the column in the linked table to aggregate; absent only for `countall` */
1571
  field?: string;
1572
  fn: RollupFn;
1573
+ limit?: number;
1574
+ sortBy?: string;
1575
+ sortDir?: "asc" | "desc";
1576
+ /** collapse duplicate logical records after ranking, before applying the window */
1577
+ distinctBy?: string;
1578
+ /** optional Airtable-style conditions applied to linked records before aggregation */
1579
+ conditions?: RollupCondition[];
1580
+ conditionConj?: "and" | "or";
1581
+ };
1582
+ /**
1583
+ * ⭐ WAVE-27 item 13 (R13) β€” the `code` column's language, per COLUMN rather than per cell.
1584
+ * A column holds one kind of snippet; a per-cell language would make the highlighter a value
1585
+ * the user has to maintain row by row. Absent = `plain` (read it through `codeLanguageOf`,
1586
+ * never `field.code!.language` β€” an unconfigured code column is the common case).
1587
+ */
1588
+ code?: { language: string };
1589
+ }
1590
+
1591
+ export const ROLLUP_CONDITION_OPS = [
1592
+ "eq", "neq", "contains", "not_contains", "is_empty", "is_not_empty",
1593
+ "gt", "gte", "lt", "lte",
1594
+ ] as const;
1595
+ export type RollupConditionOp = (typeof ROLLUP_CONDITION_OPS)[number];
1596
+ export interface RollupCondition {
1597
+ field: string;
1598
+ op: RollupConditionOp;
1599
+ value?: string;
1600
+ }
1601
 
1602
  /**
1603
  * Airtable's 17 rollup functions, minus the two that are meaningless over a scalar cell.
 
1609
  * the same discipline every other cross-language vocabulary here uses.
1610
  */
1611
  export const ROLLUP_FNS = [
1612
+ "sum", "average", "min", "max", "latest", "count", "counta", "countall",
1613
  "and", "or", "xor", "concatenate", "arrayjoin", "arraycompact", "arrayunique",
1614
  ] as const;
1615
  export type RollupFn = (typeof ROLLUP_FNS)[number];
 
1620
 
1621
  /** Human wording for each function, so a column menu never shows a bare identifier. */
1622
  export const ROLLUP_FN_LABELS: Record<RollupFn, string> = {
1623
+ sum: "Sum", average: "Average", min: "Minimum", max: "Maximum",
1624
+ latest: "Latest value",
1625
  count: "Count of numbers", counta: "Count of filled cells", countall: "Count of records",
1626
  and: "All are true", or: "Any is true", xor: "Exactly one is true",
1627
  concatenate: "Join (no separator)", arrayjoin: "Join with commas",
 
1635
  * is rewritten on every refresh pass, so accepting a typed value would not merely be wrong β€” it
1636
  * would appear to work and then silently revert, which is worse than refusing it.
1637
  */
1638
+ export function isDerivedLink(field: Field): boolean {
1639
+ return field.type === "link" && !!(field.link?.on || field.link?.inverse);
1640
+ }
1641
 
1642
  /**
1643
  * Is this the table's PROFILE column (C3/R7)?
 
2471
  * the host refuses β€” a menu entry that emits an event the host silently drops is worse than
2472
  * no entry at all, because it reads as success.
2473
  */
2474
+ /**
2475
+ * ⭐ WAVE-27 item 27 (R8) β€” the injected IG "Overview". Mirrors `aios_grid.IG_OVERVIEW_ID`.
2476
+ *
2477
+ * β›” IT HAS TO BE IN THE SET BELOW, and finding out why is the whole reason this constant is
2478
+ * not "the system view's id". Overview is INJECTED by `views_from_defs` on every read of an
2479
+ * Instagram database β€” so a Delete would remove the saved record, appear to work, and the view
2480
+ * would be back on the next load. The rule this file states one paragraph up is exactly that:
2481
+ * the client hides what the host refuses, because a control that reads as success and undoes
2482
+ * itself is worse than no control.
2483
+ *
2484
+ * ⚠ RENAME is deliberately still allowed. A rename writes a saved record under this pinned id,
2485
+ * and the assembly's saved-config overlay REPLACES the projection with it β€” so unlike delete, it
2486
+ * persists and means what it says.
2487
+ */
2488
+ export const IG_OVERVIEW_VIEW_ID = "tpl_overview";
2489
+
2490
+ export const UNDELETABLE_VIEW_IDS = new Set([ALL_VIEW_ID, IG_OVERVIEW_VIEW_ID]);
2491
 
2492
  // ─────────────────────────────────────────────── wave 16 C-TOPIC: the grid's TOPIC
2493
  /**
 
2989
  windowed: boolean;
2990
  }
2991
 
2992
+ export interface CustomersPayload {
2993
+ fields: Field[];
2994
+ rows: Row[];
2995
+ /** false on automation-owned child databases whose records are populated only by the engine */
2996
+ recordsMutable?: boolean;
2997
  workspace?: GridWorkspace;
2998
  /** Present only for server-windowed tables. See ScopeCounts. */
2999
  counts?: ScopeCounts;
web/src/index.css CHANGED
@@ -1435,49 +1435,49 @@ body {
1435
  cursor: pointer;
1436
  }
1437
  .cg-option-add:hover { text-decoration: underline; }
1438
- .cg-field-hint {
1439
  display: block;
1440
  font-size: var(--lp-fs-3xs);
1441
  line-height: 1.45;
1442
  color: #8a8a96;
1443
  padding: 2px 0 4px;
1444
- }
1445
-
1446
- .cg-rollup-conditions {
1447
- display: grid;
1448
- gap: 8px;
1449
- }
1450
-
1451
- .cg-rollup-conditions__head {
1452
- display: flex;
1453
- align-items: center;
1454
- justify-content: space-between;
1455
- gap: 10px;
1456
- color: var(--cg-text);
1457
- font-size: var(--lp-fs-2xs);
1458
- font-weight: 650;
1459
- }
1460
-
1461
- .cg-rollup-conditions__head .cg-btn {
1462
- min-height: 28px;
1463
- padding: 4px 9px;
1464
- }
1465
-
1466
- .cg-rollup-condition {
1467
- display: grid;
1468
- grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 30px;
1469
- align-items: center;
1470
- gap: 6px;
1471
- }
1472
-
1473
- .cg-rollup-condition > input {
1474
- grid-column: 1 / span 2;
1475
- }
1476
-
1477
- .cg-rollup-condition .cg-icon-btn {
1478
- width: 30px;
1479
- height: 30px;
1480
- }
1481
  /* why a control is unavailable, in the place the control would have been. An empty popover
1482
  reads as broken; a sentence reads as a decision (CG-3). */
1483
  .cg-pop-note {
@@ -4760,7 +4760,32 @@ a.cg-map-ctl-b { text-decoration: none; }
4760
  guessed: that flyout is ~215px wide on a ~31px row pitch with ~16px marks, against our
4761
  178px / 30px / 15px. The type stays `--lp-fs-xs`: the owner asked for room, not for a
4762
  larger font, and SC-1 fixes this surface's size. Room comes from the box, not the text. */
4763
- .cg-create-flyout { width: 212px; padding: 5px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4764
  /* ⚠ SPECIFICITY, not preference: these must out-rank `.cg-view-menu button` (0,1,1 β€” a class
4765
  AND an element), which sets min-height:30px and padding:0 8px on every row in this overlay.
4766
  Written as `.cg-create-row` alone (0,1,0) the roominess silently lost and the flyout stayed
@@ -9966,6 +9991,24 @@ a.cg-map-ctl-b { text-decoration: none; }
9966
  gap: 9px;
9967
  }
9968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9969
  /* ── Item 19 (C-FOLDER-REORDER) β€” dragging a FOLDER to reorder ──────────────
9970
  A private drag MIME (`application/x-loopable-fold`) keeps this apart from the
9971
  view drag, which carries `text/plain`; the indicator is an insertion RULE at
@@ -10311,6 +10354,17 @@ a.cg-map-ctl-b { text-decoration: none; }
10311
  background: var(--lp-primary);
10312
  vertical-align: middle;
10313
  }
 
 
 
 
 
 
 
 
 
 
 
10314
  .alerts-row-meta { color: var(--lp-muted); font-size: var(--lp-fs-3xs); }
10315
  .alerts-row-toggle {
10316
  flex: 0 0 auto;
@@ -11526,3 +11580,453 @@ textarea.cg-json-raw:focus {
11526
  }
11527
 
11528
  /* === WAVE23 GRID+FORMS β€” D REGION END ==================================================== */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435
  cursor: pointer;
1436
  }
1437
  .cg-option-add:hover { text-decoration: underline; }
1438
+ .cg-field-hint {
1439
  display: block;
1440
  font-size: var(--lp-fs-3xs);
1441
  line-height: 1.45;
1442
  color: #8a8a96;
1443
  padding: 2px 0 4px;
1444
+ }
1445
+
1446
+ .cg-rollup-conditions {
1447
+ display: grid;
1448
+ gap: 8px;
1449
+ }
1450
+
1451
+ .cg-rollup-conditions__head {
1452
+ display: flex;
1453
+ align-items: center;
1454
+ justify-content: space-between;
1455
+ gap: 10px;
1456
+ color: var(--cg-text);
1457
+ font-size: var(--lp-fs-2xs);
1458
+ font-weight: 650;
1459
+ }
1460
+
1461
+ .cg-rollup-conditions__head .cg-btn {
1462
+ min-height: 28px;
1463
+ padding: 4px 9px;
1464
+ }
1465
+
1466
+ .cg-rollup-condition {
1467
+ display: grid;
1468
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 30px;
1469
+ align-items: center;
1470
+ gap: 6px;
1471
+ }
1472
+
1473
+ .cg-rollup-condition > input {
1474
+ grid-column: 1 / span 2;
1475
+ }
1476
+
1477
+ .cg-rollup-condition .cg-icon-btn {
1478
+ width: 30px;
1479
+ height: 30px;
1480
+ }
1481
  /* why a control is unavailable, in the place the control would have been. An empty popover
1482
  reads as broken; a sentence reads as a decision (CG-3). */
1483
  .cg-pop-note {
 
4760
  guessed: that flyout is ~215px wide on a ~31px row pitch with ~16px marks, against our
4761
  178px / 30px / 15px. The type stays `--lp-fs-xs`: the owner asked for room, not for a
4762
  larger font, and SC-1 fixes this surface's size. Room comes from the box, not the text. */
4763
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 1 β€” WIDE ENOUGH FOR THE LONGEST BLURB, ON ONE LINE.
4764
+ The owner's complaint was step 2: each "Who can edit" choice carries a sentence saying what it
4765
+ does, and at 212px all three wrapped, so a three-choice question read as six lines of grey.
4766
+
4767
+ β›” MEASURED, NOT GUESSED. Advance widths summed from the EMBEDDED Inter (the `@font-face`
4768
+ data URI at the top of this file β€” the font users actually see, which is the whole reason it
4769
+ is embedded), variable default weight 400:
4770
+ "Only you can change this view." 162.09px
4771
+ "Only the people you pick can change it." 205.50px
4772
+ "Anyone who can see this table can change it." 235.40px <- the longest
4773
+ The box has to carry 235.40px of text plus everything left of it:
4774
+ 10 flyout padding + 2 border + 4 form padding + 16 row padding
4775
+ + 15 radio + 9 gap + 16 mark + 9 gap = 81px
4776
+ 235.40 + 81 = 316.4, taken to 320 for subpixel accumulation. Re-measure if a blurb changes;
4777
+ `VIEW_EDIT_BLURBS` in types.ts is the source of all three strings.
4778
+
4779
+ β›” `max-width` IS RESTATED AND THAT IS LOAD-BEARING, not tidiness: `.cg-view-menu` (the class
4780
+ this panel also wears) caps every menu at 260px, so `width: 320px` ALONE would have been
4781
+ clamped to 260 β€” the blurbs would still wrap, the declaration would read as applied, and
4782
+ nothing anywhere would go red. Same specificity, later rule, so this wins; the pairing is
4783
+ what makes the number real.
4784
+
4785
+ ⚠ ONE WIDTH FOR BOTH STEPS, deliberately. A modifier that widened only the form would leave
4786
+ the type menu at 212 and make the panel GROW under the cursor mid-interaction (the overlay's
4787
+ ResizeObserver would then re-place it), which is a worse artifact than a roomy type menu. */
4788
+ .cg-create-flyout { width: 320px; max-width: 320px; padding: 5px; }
4789
  /* ⚠ SPECIFICITY, not preference: these must out-rank `.cg-view-menu button` (0,1,1 β€” a class
4790
  AND an element), which sets min-height:30px and padding:0 8px on every row in this overlay.
4791
  Written as `.cg-create-row` alone (0,1,0) the roominess silently lost and the flyout stayed
 
9991
  gap: 9px;
9992
  }
9993
 
9994
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 1 β€” the permission MARK's column.
9995
+ The row is a flex line: radio | mark | (label over blurb). `flex: 0 0 auto` is the same rule
9996
+ the create rows' own marks carry two hundred lines up β€” without it a long blurb shrinks the
9997
+ ICON before it wraps the text, and a 9px person is a smudge.
9998
+ The 1px nudge lands the 16px mark on the cap-height of the 12px label beside it; `flex-start`
9999
+ on the row aligns it to the TOP, which is where it belongs when the blurb is under the name. */
10000
+ .cg-perm-mark {
10001
+ flex: 0 0 auto;
10002
+ margin-top: 1px;
10003
+ }
10004
+ /* The user list belongs to the row above it, and it says so by indenting past the controls
10005
+ rather than by drawing a second box. It was 18px, measured against a row that started
10006
+ `radio | label`; item 1 inserts a 16px mark and a 9px gap between those two, so the same
10007
+ visual relationship is 18 + 25. Left as an indent rather than an exact alignment to the text
10008
+ column (57px): at that depth the checkbox list starts closer to the middle of the panel than
10009
+ to its left edge, which reads as a different section rather than a continuation of one. */
10010
+ .cg-create-flyout .cg-perm-users { margin-left: 43px; }
10011
+
10012
  /* ── Item 19 (C-FOLDER-REORDER) β€” dragging a FOLDER to reorder ──────────────
10013
  A private drag MIME (`application/x-loopable-fold`) keeps this apart from the
10014
  view drag, which carries `text/plain`; the indicator is an insertion RULE at
 
10354
  background: var(--lp-primary);
10355
  vertical-align: middle;
10356
  }
10357
+ /* [W27-C] WAVE 27 C5 β€” an automation's row wears the loop mark on its own line.
10358
+ `inline-flex` + a baseline nudge rather than a float or a grid column: the mark belongs to
10359
+ the SENTENCE (it says where this line came from), so it must ellipsise with it and must not
10360
+ change the row's height. No dot, no colour β€” W26 R14 deleted the status vocabulary and the
10361
+ run's own summary already says what happened, in words. */
10362
+ .alerts-row-mark {
10363
+ display: inline-flex;
10364
+ align-items: center;
10365
+ margin-right: 6px;
10366
+ vertical-align: -2px;
10367
+ }
10368
  .alerts-row-meta { color: var(--lp-muted); font-size: var(--lp-fs-3xs); }
10369
  .alerts-row-toggle {
10370
  flex: 0 0 auto;
 
11580
  }
11581
 
11582
  /* === WAVE23 GRID+FORMS β€” D REGION END ==================================================== */
11583
+
11584
+ /* === [W27-D] WAVE27 β€” SESSION D REGION START ==============================================
11585
+ Owner items 8 (swipe view), 13 (code field / JSON), 19, 20 (record Details tab).
11586
+ Every rule below is inside this anchor; SESSION C's wave-27 rules live in [W27-C].
11587
+ ========================================================================================= */
11588
+
11589
+ /* ── Item 8 (R2 / C3) β€” the SWIPE deck ────────────────────────────────────────────────────
11590
+ One card, two exits. The layout is deliberately NOT the kanban's rail: a lane rail says
11591
+ "here is the distribution", and this mode says "here is the next decision", so the card is
11592
+ centred with its two options as full-height targets either side of it β€” the same shape the
11593
+ gesture has on a phone, which is what makes the arrow keys feel like the buttons. */
11594
+ .cg-swipe {
11595
+ height: 100%;
11596
+ display: flex;
11597
+ flex-direction: column;
11598
+ background: var(--lp-surface-2);
11599
+ outline: none;
11600
+ }
11601
+ .cg-swipe-bar {
11602
+ display: flex;
11603
+ align-items: center;
11604
+ gap: 10px;
11605
+ padding: 8px 12px;
11606
+ border-bottom: 1px solid var(--lp-line);
11607
+ background: var(--lp-surface);
11608
+ font-size: var(--lp-fs-2xs);
11609
+ color: var(--lp-muted);
11610
+ }
11611
+ .cg-swipe-bound { display: inline-flex; align-items: center; gap: 6px; }
11612
+ .cg-swipe-bound strong { color: var(--lp-ink); font-weight: 600; }
11613
+ /* The count sits hard right, away from the binding it is NOT a property of. */
11614
+ .cg-swipe-left { margin-left: auto; }
11615
+ .cg-swipe-deck {
11616
+ flex: 1 1 auto;
11617
+ min-height: 0;
11618
+ display: flex;
11619
+ align-items: center;
11620
+ justify-content: center;
11621
+ gap: 16px;
11622
+ padding: 20px 16px;
11623
+ }
11624
+ .cg-swipe-side {
11625
+ flex: 0 0 auto;
11626
+ display: inline-flex;
11627
+ align-items: center;
11628
+ gap: 8px;
11629
+ align-self: stretch;
11630
+ max-width: 200px;
11631
+ padding: 0 18px;
11632
+ border: 1px solid var(--lp-line);
11633
+ border-radius: var(--lp-r-lg);
11634
+ background: var(--lp-surface);
11635
+ color: var(--lp-ink);
11636
+ font-size: var(--lp-fs-sm);
11637
+ font-weight: 600;
11638
+ cursor: pointer;
11639
+ /* The option name can be long; it wraps rather than clipping, because a truncated option is
11640
+ a button whose promise you cannot read. */
11641
+ overflow-wrap: anywhere;
11642
+ text-align: center;
11643
+ }
11644
+ .cg-swipe-side:hover:not(:disabled) { filter: brightness(0.97); }
11645
+ .cg-swipe-side:disabled { opacity: 0.5; cursor: default; }
11646
+ .cg-swipe-arrow { display: inline-flex; flex: 0 0 auto; }
11647
+ .cg-swipe-card {
11648
+ flex: 0 1 460px;
11649
+ min-width: 0;
11650
+ align-self: center;
11651
+ max-height: 100%;
11652
+ overflow: auto;
11653
+ background: var(--lp-surface);
11654
+ border: 1px solid var(--lp-line);
11655
+ border-radius: var(--lp-r-lg);
11656
+ padding: 16px 18px;
11657
+ box-shadow: 0 2px 6px rgba(16, 24, 32, 0.06);
11658
+ cursor: pointer;
11659
+ text-align: left;
11660
+ }
11661
+ .cg-swipe-title {
11662
+ margin: 0 0 10px;
11663
+ font-size: var(--lp-fs-md);
11664
+ font-weight: 600;
11665
+ color: var(--lp-ink);
11666
+ overflow-wrap: anywhere;
11667
+ }
11668
+ .cg-swipe-cells { display: flex; flex-direction: column; gap: 6px; }
11669
+ .cg-swipe-cell {
11670
+ display: flex;
11671
+ gap: 10px;
11672
+ font-size: var(--lp-fs-xs);
11673
+ min-width: 0;
11674
+ }
11675
+ .cg-swipe-cell .cg-lv-k { flex: 0 0 34%; }
11676
+ .cg-swipe-cell .cg-lv-v { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
11677
+ .cg-swipe-later { margin-top: 12px; }
11678
+ .cg-swipe-empty { max-width: 420px; margin: 0 auto; text-align: center; }
11679
+ .cg-swipe-empty p { margin: 0 0 12px; }
11680
+
11681
+ /* The binder β€” the setup panel, and the surface every LOST binding lands on. Centred and
11682
+ narrow: it is a short question, not a settings page. */
11683
+ .cg-swipe-setup {
11684
+ max-width: 420px;
11685
+ margin: 32px auto;
11686
+ display: flex;
11687
+ flex-direction: column;
11688
+ gap: 12px;
11689
+ padding: 20px;
11690
+ background: var(--lp-surface);
11691
+ border: 1px solid var(--lp-line);
11692
+ border-radius: var(--lp-r-lg);
11693
+ }
11694
+ .cg-swipe-setup-note { margin: 0; font-size: var(--lp-fs-xs); color: var(--lp-muted); }
11695
+ .cg-swipe-setup-row { display: flex; flex-direction: column; gap: 4px; }
11696
+ .cg-swipe-setup-row > span { font-size: var(--lp-fs-2xs); color: var(--lp-muted); }
11697
+ .cg-swipe-setup-sides { display: flex; gap: 12px; }
11698
+ .cg-swipe-setup-sides .cg-swipe-setup-row { flex: 1 1 0; min-width: 0; }
11699
+ .cg-swipe-setup-warn {
11700
+ margin: 0;
11701
+ font-size: var(--lp-fs-2xs);
11702
+ color: var(--lp-red-deep);
11703
+ }
11704
+
11705
+
11706
+ /* ── Item 13 (R13) β€” the CODE editor's highlight UNDERLAY ─────────────────────────────────
11707
+ A transparent-text <textarea> sits exactly over a <pre> painted with the same characters.
11708
+ β›” THE TWO LAYERS MUST AGREE ON EVERY METRIC THAT MOVES A GLYPH β€” font, size, line-height,
11709
+ padding, border width, white-space and word-break. Any single mismatch slides the caret off
11710
+ the colours, and it does so gradually (fine on line 1, a character out by line 40), which is
11711
+ exactly the kind of drift a screenshot of the top of the box does not show. Both rules
11712
+ therefore inherit one shared block rather than being written twice.
11713
+ The metrics below are `.cg-json-raw`'s own, so the code editor and the JSON raw tab are the
11714
+ same box with different ink. */
11715
+ .cg-code-wrap {
11716
+ position: relative;
11717
+ height: 100%;
11718
+ min-height: 220px;
11719
+ }
11720
+ .cg-code-paint,
11721
+ .cg-code-input {
11722
+ position: absolute;
11723
+ inset: 0;
11724
+ display: block;
11725
+ width: 100%;
11726
+ height: 100%;
11727
+ margin: 0;
11728
+ padding: 10px 12px;
11729
+ border: 1px solid transparent;
11730
+ border-radius: var(--lp-r-md);
11731
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
11732
+ font-size: var(--lp-fs-xs);
11733
+ line-height: 1.55;
11734
+ white-space: pre-wrap;
11735
+ word-break: break-word;
11736
+ overflow: auto;
11737
+ tab-size: 2;
11738
+ }
11739
+ .cg-code-paint {
11740
+ border-color: var(--lp-line);
11741
+ background: var(--lp-surface-2);
11742
+ color: var(--lp-ink);
11743
+ pointer-events: none;
11744
+ }
11745
+ .cg-code-input {
11746
+ background: transparent;
11747
+ /* The text itself is invisible; the CARET is not, and `caret-color` is the only way to keep
11748
+ one without the other. */
11749
+ color: transparent;
11750
+ caret-color: var(--lp-ink);
11751
+ resize: none;
11752
+ }
11753
+ .cg-code-input:focus {
11754
+ outline: none;
11755
+ border-color: var(--lp-blue-deep);
11756
+ }
11757
+ /* The token inks. Same four families the JSON tree already uses, so a JSON snippet in a code
11758
+ column and the same document in the tree are coloured by one vocabulary. */
11759
+ .cg-code-str { color: var(--lp-green-deep); }
11760
+ .cg-code-num { color: var(--lp-blue-deep); }
11761
+ .cg-code-kw { color: var(--lp-purple-deep); font-weight: 600; }
11762
+ .cg-code-com { color: var(--lp-muted); font-style: italic; }
11763
+
11764
+ /* ── Item 13 (R13) β€” the JSON tree's in-place leaf editor ─────────────────────────────────
11765
+ The button is the value: no chrome until hover, because a tree with a box drawn round every
11766
+ leaf stops reading as a document. */
11767
+ .cg-json-leafbtn {
11768
+ padding: 0 3px;
11769
+ border: 1px solid transparent;
11770
+ border-radius: var(--lp-r-sm);
11771
+ background: none;
11772
+ font: inherit;
11773
+ cursor: text;
11774
+ text-align: left;
11775
+ }
11776
+ .cg-json-leafbtn:hover,
11777
+ .cg-json-leafbtn:focus-visible {
11778
+ border-color: var(--lp-line);
11779
+ background: var(--lp-surface);
11780
+ }
11781
+ .cg-json-leafedit {
11782
+ padding: 0 3px;
11783
+ border: 1px solid var(--lp-blue-deep);
11784
+ border-radius: var(--lp-r-sm);
11785
+ background: var(--lp-surface);
11786
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
11787
+ font-size: var(--lp-fs-xs);
11788
+ color: var(--lp-ink);
11789
+ min-width: 80px;
11790
+ }
11791
+ .cg-json-leafedit.is-bad { border-color: var(--lp-red-deep); }
11792
+
11793
+ /* ── Item 3 (C9) β€” the LOCKED-DATABASE padlock in the nav flyout ──────────────────────────
11794
+ Sits after the label and takes the row's own ink at reduced weight: it is a fact about the
11795
+ row, not a control, so it must not compete with the name it qualifies. `flex: 0 0 auto` keeps
11796
+ it from being squeezed out when a long database name wraps β€” a hint that vanishes exactly on
11797
+ the rows with the longest names is a hint nobody can rely on. */
11798
+ .shell-nav-lock {
11799
+ display: inline-flex;
11800
+ align-items: center;
11801
+ flex: 0 0 auto;
11802
+ margin-left: 4px;
11803
+ color: currentColor;
11804
+ opacity: 0.55;
11805
+ }
11806
+
11807
+ /* ── Item 20 (R5 / C10) β€” the record drawer's DETAILS tab ─────────────────────────────────
11808
+ One section per linked database, each holding a real embedded grid. The heading carries the
11809
+ count so a section states its size before it is scrolled β€” and the count is the LENGTH of the
11810
+ id list the section actually renders, never a separate number ([[no-unverifiable-aggregates]]).
11811
+ ⚠ The embedded grid needs a HEIGHT: it lays out with an internal scroller, so inside an
11812
+ auto-height section it would collapse to nothing. A fixed viewport per section also stops one
11813
+ 500-row link from burying the sections beneath it. */
11814
+ .cg-detail-linksec { display: flex; flex-direction: column; gap: 8px; }
11815
+ .cg-detail-sechead {
11816
+ display: flex;
11817
+ align-items: baseline;
11818
+ gap: 8px;
11819
+ margin: 0;
11820
+ font-size: var(--lp-fs-sm);
11821
+ font-weight: 600;
11822
+ color: var(--lp-ink);
11823
+ }
11824
+ /* The section heading IS the disclosure control once the section has records. A button rather
11825
+ than a chevron+label pair: the whole name is the target, which is what makes it findable at a
11826
+ glance in a stack of four. */
11827
+ .cg-detail-sectoggle {
11828
+ padding: 0;
11829
+ border: 0;
11830
+ background: none;
11831
+ font: inherit;
11832
+ color: inherit;
11833
+ cursor: pointer;
11834
+ text-align: left;
11835
+ }
11836
+ .cg-detail-sectoggle::before {
11837
+ content: "";
11838
+ display: inline-block;
11839
+ width: 0;
11840
+ height: 0;
11841
+ margin-right: 6px;
11842
+ border-left: 4px solid currentColor;
11843
+ border-top: 4px solid transparent;
11844
+ border-bottom: 4px solid transparent;
11845
+ transform: rotate(0deg);
11846
+ transition: transform 120ms ease;
11847
+ vertical-align: middle;
11848
+ }
11849
+ .cg-detail-sectoggle[aria-expanded="true"]::before { transform: rotate(90deg); }
11850
+ .cg-detail-seccount {
11851
+ font-size: var(--lp-fs-2xs);
11852
+ font-weight: 400;
11853
+ color: var(--lp-muted);
11854
+ }
11855
+ .cg-detail-secempty {
11856
+ margin: 0;
11857
+ font-size: var(--lp-fs-xs);
11858
+ color: var(--lp-muted);
11859
+ }
11860
+ .cg-detail-linkgrid {
11861
+ height: 320px;
11862
+ min-height: 320px;
11863
+ border: 1px solid var(--lp-line);
11864
+ border-radius: var(--lp-r-md);
11865
+ overflow: hidden;
11866
+ background: var(--lp-surface);
11867
+ }
11868
+
11869
+ /* === [W27-D] WAVE27 β€” SESSION D REGION END =============================================== */
11870
+
11871
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” dragging a VIEW to reorder the rail.
11872
+ Deliberately the SAME two marks the folder drag already uses (`.cg-fold.is-folddrag` /
11873
+ `.is-drop-above`, wave-20 item 19): the row being carried fades, and an insertion RULE is
11874
+ drawn at the top edge of the row it would land above. A fill would be wrong here for the
11875
+ reason it is wrong there β€” a filled row already means "drop this INTO me", which is what a
11876
+ folder does and a view never can. Two gestures on one rail must not share a picture. */
11877
+ .cg-view-row.is-viewdrag { opacity: 0.45; }
11878
+ .cg-view-row.is-drop-above { box-shadow: inset 0 2px 0 0 var(--lp-primary); }
11879
+
11880
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 21 (R14) β€” the alerted view's live matched count.
11881
+ RED, because that is what the alert accent means everywhere else in this product, and R14
11882
+ asked for it by name. Tabular numerals so a column of badges does not jitter as the counts
11883
+ move; `flex: 0 0 auto` so the badge takes its width FIRST and the view NAME ellipsises around
11884
+ it β€” a badge that could itself be cut off is the one number the user asked to always see. */
11885
+ .cg-view-count {
11886
+ flex: 0 0 auto;
11887
+ min-width: 20px;
11888
+ padding: 1px 5px;
11889
+ border-radius: 999px;
11890
+ background: var(--lp-red);
11891
+ color: var(--lp-red-deep);
11892
+ font-size: var(--lp-fs-3xs);
11893
+ font-weight: 650;
11894
+ font-variant-numeric: tabular-nums;
11895
+ text-align: center;
11896
+ line-height: 1.5;
11897
+ }
11898
+
11899
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 29 β€” the wide value editor, and the button that opens it.
11900
+ β›” THE PANEL CANNOT GROW, so the editor leaves it. `.auto-panel` is 380px (index.css ~:7737),
11901
+ `.autob-cond .auto-input` divides what is left across three controls and `.is-small` trims it
11902
+ again β€” a comma list of bio phrases was being typed six characters at a time through a box
11903
+ that scrolls sideways. `AnchoredOverlay` draws in a body portal, so none of that chain
11904
+ applies to it. 420px is a measured choice, not a round number: at `--lp-fs-2xs` it holds
11905
+ ~60 characters per line, which is the longest single phrase the vendor's own examples use. */
11906
+ .autoc-expand {
11907
+ flex: 0 0 auto;
11908
+ width: 26px;
11909
+ padding: 0;
11910
+ display: inline-flex;
11911
+ align-items: center;
11912
+ justify-content: center;
11913
+ cursor: pointer;
11914
+ }
11915
+ .autoc-expand-icon {
11916
+ width: 14px;
11917
+ height: 14px;
11918
+ fill: none;
11919
+ stroke: currentColor;
11920
+ stroke-width: 1.4;
11921
+ stroke-linecap: round;
11922
+ stroke-linejoin: round;
11923
+ }
11924
+ .autoc-bigedit {
11925
+ z-index: var(--cg-z-menu);
11926
+ display: flex;
11927
+ flex-direction: column;
11928
+ gap: 6px;
11929
+ width: 420px;
11930
+ max-width: 420px;
11931
+ padding: 10px;
11932
+ border: 1px solid var(--lp-line);
11933
+ border-radius: var(--lp-r-lg);
11934
+ background: var(--cg-white);
11935
+ /* The `.cg-view-menu` shadow, matched by value: this product has no shadow TOKEN,
11936
+ so a `var(--lp-shadow-md, …)` would have silently rendered its own fallback and
11937
+ looked like a token was being honoured. Checked before writing it. */
11938
+ box-shadow: 0 8px 24px rgba(20, 24, 40, 0.13);
11939
+ }
11940
+ .autoc-bigedit > label {
11941
+ font-size: var(--lp-fs-3xs);
11942
+ font-weight: 600;
11943
+ color: var(--lp-muted);
11944
+ }
11945
+ /* MONOSPACE, deliberately: the content is a comma-separated LIST, and a proportional face
11946
+ makes two adjacent commas hard to tell from one. ⚠ THE SAME STACK `.auto-input.is-mono`
11947
+ ALREADY USES, written out rather than through a `--lp-mono` var β€” there IS no such token
11948
+ (checked; six sites in this file spell the stack out), and inventing one here would put
11949
+ the product's mono face in two places that can drift. */
11950
+ .autoc-bigedit-text {
11951
+ width: 100%;
11952
+ min-height: 118px;
11953
+ padding: 7px 8px;
11954
+ border: 1px solid var(--lp-line);
11955
+ border-radius: var(--lp-r-md);
11956
+ background: var(--cg-white);
11957
+ color: var(--cg-text);
11958
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
11959
+ font-size: var(--lp-fs-2xs);
11960
+ line-height: 1.5;
11961
+ resize: vertical;
11962
+ }
11963
+ .autoc-bigedit-text:focus {
11964
+ outline: none;
11965
+ border-color: var(--lp-primary);
11966
+ }
11967
+
11968
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 33 / CONTRACT C11 β€” Properties ⇄ Run history.
11969
+ The two `.auto-panel` asides used to be drawn SIDE BY SIDE: two 380px columns squeezing the
11970
+ flow they are both about. One shows at a time now, and the switch lives in both heads so it
11971
+ does not move when the panel does (`reference/Airtable Automation 11.png`).
11972
+ ⚠ `[hidden]` needs `display: none !important` here because `.auto-panel` sets `display: flex`,
11973
+ and a class rule beats the UA's `[hidden] { display: none }` β€” the attribute would be honoured
11974
+ by the accessibility tree and ignored by the eye, which is a panel that is invisible to a
11975
+ screen reader and painted for everyone else. */
11976
+ .auto-panel[hidden] { display: none !important; }
11977
+ .auto-paneltabs {
11978
+ display: inline-flex;
11979
+ gap: 2px;
11980
+ padding: 2px;
11981
+ border: 1px solid var(--lp-line);
11982
+ border-radius: var(--lp-r-md);
11983
+ background: var(--lp-surface-2);
11984
+ }
11985
+ .auto-paneltab {
11986
+ padding: 3px 9px;
11987
+ border: 0;
11988
+ border-radius: calc(var(--lp-r-md) - 2px);
11989
+ background: transparent;
11990
+ color: var(--lp-muted);
11991
+ font-size: var(--lp-fs-3xs);
11992
+ font-weight: 600;
11993
+ cursor: pointer;
11994
+ }
11995
+ .auto-paneltab.is-on { background: var(--cg-white); color: var(--cg-text); }
11996
+ .auto-paneltab:hover:not(.is-on) { color: var(--cg-text); }
11997
+ /* THE SHORT ANIMATION C11 asks for β€” 120ms, and only the panel that is BECOMING visible runs
11998
+ it. Long enough to say "this arrived", short enough that a click on a step card does not feel
11999
+ like it is waiting for scenery. `prefers-reduced-motion` turns it off rather than shortening
12000
+ it: a fade is decoration, and decoration is what that setting is for. */
12001
+ @keyframes auto-panel-in {
12002
+ from { opacity: 0; transform: translateX(6px); }
12003
+ to { opacity: 1; transform: none; }
12004
+ }
12005
+ .auto-panel.is-appearing:not([hidden]) { animation: auto-panel-in 120ms ease-out; }
12006
+ @media (prefers-reduced-motion: reduce) {
12007
+ .auto-panel.is-appearing:not([hidden]) { animation: none; }
12008
+ }
12009
+
12010
+ /* [W27-C] ⭐ WAVE 27 Β· OWNER ITEM 33 / CONTRACT C4 β€” one row per CONNECTOR in the action menu,
12011
+ with its own actions behind a chevron (`reference/Airtable Automation 10.png`).
12012
+ A `<details>` element, so the disclosure has no state of this component's to get wrong and
12013
+ answers Enter and Space for free. The marker is replaced by a drawn chevron for the same
12014
+ reason every other mark here is drawn: the UA triangle is a different weight from everything
12015
+ around it and cannot be recoloured. */
12016
+ .autox-menu-nest > summary { list-style: none; cursor: pointer; }
12017
+ .autox-menu-nest > summary::-webkit-details-marker { display: none; }
12018
+ .autox-menu-sum::before {
12019
+ content: "";
12020
+ flex: 0 0 auto;
12021
+ width: 8px;
12022
+ height: 8px;
12023
+ margin-right: 4px;
12024
+ border-right: 1.4px solid var(--lp-muted);
12025
+ border-bottom: 1.4px solid var(--lp-muted);
12026
+ transform: rotate(-45deg);
12027
+ transition: transform 0.12s ease;
12028
+ }
12029
+ .autox-menu-nest[open] > .autox-menu-sum::before { transform: rotate(45deg); }
12030
+ /* The nested rows are INDENTED past the connector's own chevron, so "these belong to Scraper"
12031
+ is read from the geometry rather than from having watched the click that opened them. */
12032
+ .autox-menu-nest .autox-menu-row { padding-left: 26px; }
web/src/settings/permsModel.ts CHANGED
@@ -161,6 +161,11 @@ const FIELD_TYPE_TABLE: Record<FieldType, true> = {
161
  // land in two separate changes. Nothing about the permissions wall treats either kind
162
  // specially β€” a link/rollup column is granted and hidden like any other column.
163
  link: true, rollup: true,
 
 
 
 
 
164
  };
165
 
166
  export const KNOWN_FIELD_TYPES: ReadonlySet<string> = new Set(Object.keys(FIELD_TYPE_TABLE));
 
161
  // land in two separate changes. Nothing about the permissions wall treats either kind
162
  // specially β€” a link/rollup column is granted and hidden like any other column.
163
  link: true, rollup: true,
164
+ // ⭐ Wave-27 item 13 (R13) β€” same one-key edit, same reason, and `settings/**` is D's fence
165
+ // this wave so it is not even an exception: the alarm above is a COMPILE error, so the union
166
+ // and this listing cannot land in two changes. Nothing about the permissions wall treats a
167
+ // code column specially β€” it is granted and hidden like any other column.
168
+ code: true,
169
  };
170
 
171
  export const KNOWN_FIELD_TYPES: ReadonlySet<string> = new Set(Object.keys(FIELD_TYPE_TABLE));
web/src/shell/Shell.tsx CHANGED
@@ -30,10 +30,29 @@
30
  // a dependency the embed bundle would have to keep excluded.
31
  // ---------------------------------------------------------------------------
32
 
33
- import { useCallback, useEffect, useRef, useState } from "react";
34
  import { createPortal } from "react-dom";
35
  import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
36
- import AutomationSurface from "../automation/AutomationSurface";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  import CustomerGrid from "../customer-grid/CustomerGrid";
38
  import { clearCustomersCache } from "../customer-grid/apiBridge";
39
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
@@ -41,15 +60,16 @@ import { OverlayProvider } from "../customer-grid/OverlaySurface";
41
  // so it no longer has to tell the grid that it did.
42
  import { API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, signal } from "../apiContract";
43
  import { PageSurface } from "../pages/PageSurface";
44
- import { SettingsModal } from "../settings/SettingsModal";
 
45
  import type { SettingsSection } from "../settings/SettingsModal";
46
  import { Brand } from "./Brand";
47
  import LoginPage from "./LoginPage";
48
  import { CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, HOME_ROUTE, MAX_NAV_FOLDERS, appLink, databaseEntries, dbChipClass, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, foldNav, postOpened, resolveRoute, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
49
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, Recent } from "./nav";
50
- import HomePage from "../home/HomePage";
51
- import TemplatePicker from "../home/TemplatePicker";
52
- import ConnectorsPage from "../connectors/ConnectorsPage";
53
  // WAVE 23 C9 (W23-W2) β€” SESSION D's public page. A STATIC import, not a lazy one: the wave's own
54
  // rule is that a required import fails the build when the file is not there, which is the whole
55
  // difference between a mount and an intention (verify_wiring's header).
@@ -64,7 +84,22 @@ import type { AutomationTile } from "../home/homeModel";
64
  // it, so the frame adds a fetch, not a protocol.
65
  import { listAutomations } from "../automation/automationApi";
66
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
67
- import AlertsPane from "../alerts/AlertsPane";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
69
  import {
70
  ALERT_CREATE_EVENT,
@@ -78,7 +113,7 @@ import ShareDialog from "./ShareDialog";
78
  import { SHARE_OPEN_EVENT, parseShareRequest } from "./shareModel";
79
  import type { ShareRequest } from "./shareModel";
80
  // WAVE 19 R8 β€” the chosen database mark. Read-only across the session fence.
81
- import { FolderMark } from "../customer-grid/icons";
82
  import type { FolderIcon } from "../customer-grid/types";
83
  import { isAdmin, logout, me } from "./session";
84
  import type { SessionUser } from "./session";
@@ -1211,6 +1246,40 @@ export default function Shell() {
1211
  * change (see the tombstones in `apiContract.ts` and `AutomationSurface.tsx`). Leaving either
1212
  * side behind rebuilds the wave-24 defect from the opposite end.
1213
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1214
  const createDb = useCallback(async () => {
1215
  setNewDb((cur) => {
1216
  if (!cur || cur.busy || !cur.name.trim()) return cur;
@@ -1229,7 +1298,9 @@ export default function Shell() {
1229
  method: "POST",
1230
  credentials: CREDENTIALS,
1231
  headers: { "Content-Type": "application/json" },
1232
- body: JSON.stringify({ label: name.trim(), source: "Blank" }),
 
 
1233
  });
1234
  const body = (await res.json().catch(() => null)) as
1235
  | { key?: string; error?: { message?: string } }
@@ -1239,6 +1310,28 @@ export default function Shell() {
1239
  err: body?.error?.message || `The server answered ${res.status}.` });
1240
  return;
1241
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1242
  setNewDb(null);
1243
  setNavEpoch((e) => e + 1);
1244
  window.location.hash = `#/${body.key}`;
@@ -1679,6 +1772,25 @@ export default function Shell() {
1679
  <DbIcon />
1680
  )}
1681
  <span className="shell-nav-label">{item.label}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1682
  {/* A hand-off opens the current application in a new tab; the
1683
  arrow declares that before the click finds out. */}
1684
  {item.kind === "handoff" ? <ExtIcon /> : null}
@@ -1984,7 +2096,7 @@ export default function Shell() {
1984
  {...(active.icon ? { icon: active.icon } : {})}
1985
  />
1986
  <div className="shell-auto-host">
1987
- <AutomationSurface />
1988
  </div>
1989
  </div>
1990
  ) : active?.kind === "native" ? (
@@ -2027,7 +2139,7 @@ export default function Shell() {
2027
  // The one action the page cannot perform itself: a `manage: "keychain"` row opens
2028
  // Settings on the Keychains tab, and the Settings MODAL is the frame's. Same division
2029
  // as every other panel here β€” the page knows what it wants, the frame owns the door.
2030
- <ConnectorsPage onKeychain={() => setSettings("keychains")} />
2031
  ) : nav.phase === "ready" ? (
2032
  // ⭐ WAVE 23 item 9 (R7, C10) β€” HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
2033
  //
@@ -2047,35 +2159,37 @@ export default function Shell() {
2047
  // hero's create door, and its empty line carries the hero's sentence (HomePage's
2048
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
2049
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
2050
- <HomePage
2051
- // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
2052
- // pass), which is the only way it could have been found. The Automation SURFACE is a
2053
- // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
2054
- // "Databases" β€” beside an "Automations" section listing the things it contains. The
2055
- // rail has excluded it since wave 19 R10 for exactly this reason (`dbEntries`, :1261);
2056
- // Home was drawing the unfiltered list.
2057
- // ⚠ STILL THE GRANTED NAV, so the C10 law is untouched: `dbEntries` is `entries` minus
2058
- // one key, not a list this frame invented.
2059
- entries={dbEntries}
2060
- recents={recents}
2061
- automations={autoTiles}
2062
- // ⭐ WAVE 24 item 14 β€” the templates CARD is boarded. It opens the same
2063
- // under-construction note the AI assistant uses, rather than the picker.
2064
- // ⚠ The flyout's "From a template" row is UNAFFECTED (R9 keeps it working) β€” see
2065
- // HomePage's own note on why that asymmetry is deliberate rather than a miss.
2066
- onTemplates={() => setAssistOpen("templates")}
2067
- onNewDatabase={() => openNewDb("blank")}
2068
- /* β›” `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
2069
- onConnectors={() => {
2070
- window.location.hash = `#/${CONNECTORS_ROUTE}`;
2071
- }}
2072
- // The same two-part move every click-through in this frame makes: the frame owns the
2073
- // hash, the surface owns which automation is selected. Route, then ASK.
2074
- onOpenAutomation={(autoId) => {
2075
- window.location.hash = "#/automation";
2076
- signal(AUTOMATION_OPEN_EVENT, { autoId });
2077
- }}
2078
- />
 
 
2079
  ) : nav.phase === "error" ? (
2080
  // ⚠ WAVE 17 ITEM 4 (R6) β€” THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
2081
  // branch is what keeps them apart. `active` resolves from `entries`, which is empty
@@ -2192,14 +2306,16 @@ export default function Shell() {
2192
  // WAVE 23 C12 (wiring W23-W6) β€” the picker. It applies views to an EXISTING
2193
  // database rather than making one, which is what a platform-curated template is:
2194
  // a set of saved views, not a table (R10).
2195
- <TemplatePicker
2196
- entries={dbEntries}
2197
- onToast={setToast}
2198
- onDone={(tableKey) => {
2199
- setNewDb(null);
2200
- window.location.hash = `#/${tableKey}`;
2201
- }}
2202
- />
 
 
2203
  ) : (
2204
  <>
2205
  <input
@@ -2240,57 +2356,61 @@ export default function Shell() {
2240
  ) : null}
2241
 
2242
  {settings ? (
2243
- <SettingsModal
2244
- user={session.user}
2245
- section={settings}
2246
- onSection={setSettings}
2247
- onClose={() => setSettings(null)}
2248
- onUser={(u) => setSession({ phase: "authed", user: u })}
2249
- // Wave 15 β€” the nav already holds a server-filtered {key: label} for
2250
- // every surface this account may open, so "Your access" names its
2251
- // restrictions in the words the rail uses rather than in registry
2252
- // keys. Derived here rather than mapped in the modal so there is only
2253
- // one place either door learns what a module is called.
2254
- moduleLabels={Object.fromEntries(entries.map((e) => [e.key, e.label]))}
2255
- />
 
 
2256
  ) : null}
2257
 
2258
  {/* C-ALERT (item 25): the inbox. */}
2259
  {alertsOpen ? (
2260
- <AlertsPane
2261
- onClose={() => setAlertsOpen(false)}
2262
- onInbox={setInbox}
2263
- onToast={setToast}
2264
- onOpenView={(topic, viewId) => {
2265
- const route = routeForTopic(topic);
2266
- if (!route) return;
2267
- window.location.hash = `#/${route}`;
2268
- // ⚠ HALF A CLICK-THROUGH UNTIL S3 LISTENS (amendment A-S4-4): this lands
2269
- // the reader on the right TABLE and asks the grid to select the view. The
2270
- // grid owns view selection β€” its `activeViewId` is seeded from its own
2271
- // storage key, which this frame does not know β€” so until the listener
2272
- // exists the request is simply not heard. Navigating anyway is the honest
2273
- // half: a notification that took you nowhere would be worse.
2274
- window.dispatchEvent(
2275
- new CustomEvent("aios:view-open", { detail: { topic, viewId } })
2276
- );
2277
- }}
2278
- // ⭐ WAVE 23 C6 (wiring W23-W5) β€” the review notification's click-through.
2279
- //
2280
- // THE SAME TWO-PART MOVE the view click-through makes, and for the same reason: the
2281
- // frame owns the hash, the automation SURFACE owns which automation is selected
2282
- // (`activeId` is its own state, seeded from its own list β€” this frame cannot see it
2283
- // and must not learn to). So: route, then ASK.
2284
- //
2285
- // ⚠ THE ORDER IS LOAD-BEARING. The hash is set FIRST so the surface is mounting (or
2286
- // already mounted) when the event arrives; dispatching first would fire into a route
2287
- // that does not exist yet. `signal` is `apiContract`'s helper β€” the same channel the
2288
- // grid's own listeners use, rather than a second hand-rolled `dispatchEvent` here.
2289
- onOpenAutomation={(autoId, stageId) => {
2290
- window.location.hash = "#/automation";
2291
- signal(AUTOMATION_OPEN_EVENT, { autoId, ...(stageId ? { stageId } : {}) });
2292
- }}
2293
- />
 
 
2294
  ) : null}
2295
 
2296
  {/* C-SHARE (items 18/23/26): the access editor β€” one dialog, three kinds. */}
 
30
  // a dependency the embed bundle would have to keep excluded.
31
  // ---------------------------------------------------------------------------
32
 
33
+ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
34
  import { createPortal } from "react-dom";
35
  import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
36
+ /**
37
+ * ⭐ WAVE-27 item 34 (I5) β€” ROUTE-LEVEL CODE SPLITTING.
38
+ *
39
+ * Six surfaces that are already mounted CONDITIONALLY (an automation route, the settings modal,
40
+ * the connectors page, home, the template picker, the alerts pane) become their own chunks. The
41
+ * shell downloads them when a person actually opens one β€” which for most sessions is never, and
42
+ * for every session is not the first paint.
43
+ *
44
+ * ⚠ EVERY ONE OF THESE WAS ALREADY BEHIND A CONDITION IN THE JSX, and that is what makes the
45
+ * split real rather than cosmetic: a `lazy` whose mount renders unconditionally downloads on the
46
+ * first paint anyway and buys a Suspense boundary for nothing. `CustomerGrid` is deliberately NOT
47
+ * in this list, for the mirror-image reason β€” it IS the first paint on nearly every route, so
48
+ * splitting it would add a round trip to the common case. (The build reports it as an INEFFECTIVE
49
+ * dynamic import from `RecordDetail`; that is expected and correct β€” that import exists to break
50
+ * a module CYCLE, not to move bytes. See the note beside it.)
51
+ *
52
+ * ⚠ `SettingsModal` is a NAMED export, so its loader maps to `{ default }`. A default-import
53
+ * `lazy()` over a named export fails at RUNTIME, on click, and only for that one surface.
54
+ */
55
+ const AutomationSurface = lazy(() => import("../automation/AutomationSurface"));
56
  import CustomerGrid from "../customer-grid/CustomerGrid";
57
  import { clearCustomersCache } from "../customer-grid/apiBridge";
58
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
 
60
  // so it no longer has to tell the grid that it did.
61
  import { API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, signal } from "../apiContract";
62
  import { PageSurface } from "../pages/PageSurface";
63
+ const SettingsModal = lazy(() =>
64
+ import("../settings/SettingsModal").then((m) => ({ default: m.SettingsModal })));
65
  import type { SettingsSection } from "../settings/SettingsModal";
66
  import { Brand } from "./Brand";
67
  import LoginPage from "./LoginPage";
68
  import { CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, HOME_ROUTE, MAX_NAV_FOLDERS, appLink, databaseEntries, dbChipClass, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, foldNav, postOpened, resolveRoute, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
69
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, Recent } from "./nav";
70
+ const HomePage = lazy(() => import("../home/HomePage"));
71
+ const TemplatePicker = lazy(() => import("../home/TemplatePicker"));
72
+ const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage"));
73
  // WAVE 23 C9 (W23-W2) β€” SESSION D's public page. A STATIC import, not a lazy one: the wave's own
74
  // rule is that a required import fails the build when the file is not there, which is the whole
75
  // difference between a mount and an intention (verify_wiring's header).
 
84
  // it, so the frame adds a fetch, not a protocol.
85
  import { listAutomations } from "../automation/automationApi";
86
  import { CreateNewRow, FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
87
+ const AlertsPane = lazy(() => import("../alerts/AlertsPane"));
88
+
89
+ /**
90
+ * Item 34's Suspense boundary, one definition for all six surfaces.
91
+ *
92
+ * β›” THE FALLBACK IS DELIBERATELY EMPTY, and that is a design decision rather than a stub. The
93
+ * standing R6 rule is that this product shows a shared spinner mark and never load TEXT
94
+ * (`verify_icons` asserts it across every source file, so a "Loading..." here would go red).
95
+ * These chunks are tens of kilobytes off the same origin that just served the shell, so the
96
+ * honest choice between a flash of a spinner and a frame of nothing is nothing β€” a spinner that
97
+ * appears and vanishes within one frame reads as a glitch, not as progress.
98
+ */
99
+ function Lazily({ children }: { children: ReactNode }) {
100
+ return <Suspense fallback={null}>{children}</Suspense>;
101
+ }
102
+
103
  import { createAlert, fetchInbox } from "../alerts/alertsApi";
104
  import {
105
  ALERT_CREATE_EVENT,
 
113
  import { SHARE_OPEN_EVENT, parseShareRequest } from "./shareModel";
114
  import type { ShareRequest } from "./shareModel";
115
  // WAVE 19 R8 β€” the chosen database mark. Read-only across the session fence.
116
+ import { FolderMark, LockMark } from "../customer-grid/icons";
117
  import type { FolderIcon } from "../customer-grid/types";
118
  import { isAdmin, logout, me } from "./session";
119
  import type { SessionUser } from "./session";
 
1246
  * change (see the tombstones in `apiContract.ts` and `AutomationSurface.tsx`). Leaving either
1247
  * side behind rebuilds the wave-24 defect from the opposite end.
1248
  */
1249
+ /**
1250
+ * ⭐ WAVE-27 item 19 (owner ruling R15) β€” WHAT A HAND-MADE DATABASE STARTS WITH.
1251
+ *
1252
+ * `user_tables.create()` mints exactly ONE column (`Name`) and zero rows, so a new database
1253
+ * opened as a single blank column with nothing in it β€” a surface with no shape to copy. R15
1254
+ * seeds four columns and three blank records instead.
1255
+ *
1256
+ * β›” IT LIVES AT THIS DOOR, NOT IN `create()`, AND THAT IS THE RULING'S OWN SCOPE. R15 is
1257
+ * "hand-created databases only; preset/automation spawns untouched", and `source` cannot
1258
+ * express that: MEASURED, `automation_engine.py:1983` mints a database for the automation
1259
+ * builder's "+ New database" through the same `create()` with the DEFAULT source, i.e. `Blank`.
1260
+ * Seeding inside `create()` would therefore put four columns and three empty rows in front of
1261
+ * every automation target as well β€” and `_vestigial_name_field` (the wave-26 migration) is
1262
+ * written against `create()` minting EXACTLY ONE column, so it would start reading the seed as
1263
+ * somebody's work. This dialog is the only door a person names a database at.
1264
+ *
1265
+ * β›” `status` SHIPS WITH ITS OPTIONS. A select declaring none is the W26 item-24 defect
1266
+ * verbatim β€” `if ([])` is truthy, so a panel hands back an empty list as an ANSWER and the
1267
+ * filter reads as dead β€” and `aios_grid` separately degrades an option-less select to text on
1268
+ * read, so the column would not even stay a select.
1269
+ *
1270
+ * β›” `name` DECLARES `pinned`. D-80 is exactly this key going unwritten: the primary column
1271
+ * resolves as `fields.find(f => f.pinned) ?? fields[0]`, and because nothing ever set the flag,
1272
+ * "whichever column was created first" WAS the rule. With four columns arriving at once,
1273
+ * leaving it implicit stops being harmless.
1274
+ */
1275
+ const SEED_FIELDS = [
1276
+ { key: "name", label: "Name", type: "text", pinned: true },
1277
+ { key: "status", label: "Status", type: "select",
1278
+ options: ["Todo", "In progress", "Done"] },
1279
+ { key: "assignee", label: "Assignee", type: "user" },
1280
+ { key: "date", label: "Date", type: "date" },
1281
+ ];
1282
+ const SEED_ROWS = 3;
1283
  const createDb = useCallback(async () => {
1284
  setNewDb((cur) => {
1285
  if (!cur || cur.busy || !cur.name.trim()) return cur;
 
1298
  method: "POST",
1299
  credentials: CREDENTIALS,
1300
  headers: { "Content-Type": "application/json" },
1301
+ // R15's four columns ride the SAME body the route already forwards to
1302
+ // `user_tables.create(fields=...)` β€” no new endpoint, no server change.
1303
+ body: JSON.stringify({ label: name.trim(), source: "Blank", fields: SEED_FIELDS }),
1304
  });
1305
  const body = (await res.json().catch(() => null)) as
1306
  | { key?: string; error?: { message?: string } }
 
1310
  err: body?.error?.message || `The server answered ${res.status}.` });
1311
  return;
1312
  }
1313
+ // R15's three blank records, through the ORDINARY row door the grid's own "+" uses.
1314
+ //
1315
+ // ⚠ SEQUENTIAL, not `Promise.all`: three concurrent writes race the same store
1316
+ // document, and the last read-modify-write would win with two rows lost.
1317
+ //
1318
+ // ⚠ FAILURE HERE DOES NOT FAIL THE CREATE, and that asymmetry is deliberate. The
1319
+ // database and its four columns already exist; reporting "could not create it" over a
1320
+ // missing blank row would be false, and rolling the database back would destroy the
1321
+ // part that worked. A database that opens with two blank rows instead of three is not
1322
+ // a state anybody can be harmed by β€” the grid's "+" adds the third.
1323
+ for (let i = 0; i < SEED_ROWS; i += 1) {
1324
+ try {
1325
+ await fetch(`${API_V1}/tables/${body.key}/rows`, {
1326
+ method: "POST",
1327
+ credentials: CREDENTIALS,
1328
+ headers: { "Content-Type": "application/json" },
1329
+ body: JSON.stringify({ values: {} }),
1330
+ });
1331
+ } catch {
1332
+ break; // the store is unreachable; the next two would fail the same way
1333
+ }
1334
+ }
1335
  setNewDb(null);
1336
  setNavEpoch((e) => e + 1);
1337
  window.location.hash = `#/${body.key}`;
 
1772
  <DbIcon />
1773
  )}
1774
  <span className="shell-nav-label">{item.label}</span>
1775
+ {/* ⭐ WAVE 27 item 3 (contract C9) β€” A LOCKED DATABASE SAYS SO HERE.
1776
+ The nav flyout is the only place every database is listed, so it is
1777
+ where the fact belongs β€” you learn it before you open the thing and
1778
+ go looking for a "+" that will not be there.
1779
+
1780
+ ⚠ THE TITLE NAMES **WHICH** LOCK, and that is a standing rule rather
1781
+ than politeness: ONE `LockMark` glyph carries all three of the owner's
1782
+ locks (locked database / pre-set field / locked view β€” DESIGN.md Β§4),
1783
+ so a bare padlock says only "something here is restricted". This one
1784
+ means records, and it says the half that STAYS OPEN in the same breath,
1785
+ because "locked" reads as read-only and fields are not. */}
1786
+ {item.locked ? (
1787
+ <span
1788
+ className="shell-nav-lock"
1789
+ title="Locked database β€” records are added by an automation. You can still add and edit fields."
1790
+ >
1791
+ <LockMark size={11} />
1792
+ </span>
1793
+ ) : null}
1794
  {/* A hand-off opens the current application in a new tab; the
1795
  arrow declares that before the click finds out. */}
1796
  {item.kind === "handoff" ? <ExtIcon /> : null}
 
2096
  {...(active.icon ? { icon: active.icon } : {})}
2097
  />
2098
  <div className="shell-auto-host">
2099
+ <Lazily><AutomationSurface /></Lazily>
2100
  </div>
2101
  </div>
2102
  ) : active?.kind === "native" ? (
 
2139
  // The one action the page cannot perform itself: a `manage: "keychain"` row opens
2140
  // Settings on the Keychains tab, and the Settings MODAL is the frame's. Same division
2141
  // as every other panel here β€” the page knows what it wants, the frame owns the door.
2142
+ <Lazily><ConnectorsPage onKeychain={() => setSettings("keychains")} /></Lazily>
2143
  ) : nav.phase === "ready" ? (
2144
  // ⭐ WAVE 23 item 9 (R7, C10) β€” HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
2145
  //
 
2159
  // hero's create door, and its empty line carries the hero's sentence (HomePage's
2160
  // `home-empty`, which branches on `entries.length === 0` for exactly this reason).
2161
  // Booked as a dated amendment in the wave doc, since it moves an R4 surface.
2162
+ <Lazily>
2163
+ <HomePage
2164
+ // ⭐ `dbEntries`, NOT `entries` β€” found by LOOKING at it (wave 24 close-out visual
2165
+ // pass), which is the only way it could have been found. The Automation SURFACE is a
2166
+ // granted nav entry with an href, so `allDatabases` drew it a tile under the heading
2167
+ // "Databases" β€” beside an "Automations" section listing the things it contains. The
2168
+ // rail has excluded it since wave 19 R10 for exactly this reason (`dbEntries`, :1261);
2169
+ // Home was drawing the unfiltered list.
2170
+ // ⚠ STILL THE GRANTED NAV, so the C10 law is untouched: `dbEntries` is `entries` minus
2171
+ // one key, not a list this frame invented.
2172
+ entries={dbEntries}
2173
+ recents={recents}
2174
+ automations={autoTiles}
2175
+ // ⭐ WAVE 24 item 14 β€” the templates CARD is boarded. It opens the same
2176
+ // under-construction note the AI assistant uses, rather than the picker.
2177
+ // ⚠ The flyout's "From a template" row is UNAFFECTED (R9 keeps it working) β€” see
2178
+ // HomePage's own note on why that asymmetry is deliberate rather than a miss.
2179
+ onTemplates={() => setAssistOpen("templates")}
2180
+ onNewDatabase={() => openNewDb("blank")}
2181
+ /* β›” `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
2182
+ onConnectors={() => {
2183
+ window.location.hash = `#/${CONNECTORS_ROUTE}`;
2184
+ }}
2185
+ // The same two-part move every click-through in this frame makes: the frame owns the
2186
+ // hash, the surface owns which automation is selected. Route, then ASK.
2187
+ onOpenAutomation={(autoId) => {
2188
+ window.location.hash = "#/automation";
2189
+ signal(AUTOMATION_OPEN_EVENT, { autoId });
2190
+ }}
2191
+ />
2192
+ </Lazily>
2193
  ) : nav.phase === "error" ? (
2194
  // ⚠ WAVE 17 ITEM 4 (R6) β€” THE ERROR AND THE EMPTY ARE DIFFERENT SENTENCES, and this
2195
  // branch is what keeps them apart. `active` resolves from `entries`, which is empty
 
2306
  // WAVE 23 C12 (wiring W23-W6) β€” the picker. It applies views to an EXISTING
2307
  // database rather than making one, which is what a platform-curated template is:
2308
  // a set of saved views, not a table (R10).
2309
+ <Lazily>
2310
+ <TemplatePicker
2311
+ entries={dbEntries}
2312
+ onToast={setToast}
2313
+ onDone={(tableKey) => {
2314
+ setNewDb(null);
2315
+ window.location.hash = `#/${tableKey}`;
2316
+ }}
2317
+ />
2318
+ </Lazily>
2319
  ) : (
2320
  <>
2321
  <input
 
2356
  ) : null}
2357
 
2358
  {settings ? (
2359
+ <Lazily>
2360
+ <SettingsModal
2361
+ user={session.user}
2362
+ section={settings}
2363
+ onSection={setSettings}
2364
+ onClose={() => setSettings(null)}
2365
+ onUser={(u) => setSession({ phase: "authed", user: u })}
2366
+ // Wave 15 β€” the nav already holds a server-filtered {key: label} for
2367
+ // every surface this account may open, so "Your access" names its
2368
+ // restrictions in the words the rail uses rather than in registry
2369
+ // keys. Derived here rather than mapped in the modal so there is only
2370
+ // one place either door learns what a module is called.
2371
+ moduleLabels={Object.fromEntries(entries.map((e) => [e.key, e.label]))}
2372
+ />
2373
+ </Lazily>
2374
  ) : null}
2375
 
2376
  {/* C-ALERT (item 25): the inbox. */}
2377
  {alertsOpen ? (
2378
+ <Lazily>
2379
+ <AlertsPane
2380
+ onClose={() => setAlertsOpen(false)}
2381
+ onInbox={setInbox}
2382
+ onToast={setToast}
2383
+ onOpenView={(topic, viewId) => {
2384
+ const route = routeForTopic(topic);
2385
+ if (!route) return;
2386
+ window.location.hash = `#/${route}`;
2387
+ // ⚠ HALF A CLICK-THROUGH UNTIL S3 LISTENS (amendment A-S4-4): this lands
2388
+ // the reader on the right TABLE and asks the grid to select the view. The
2389
+ // grid owns view selection β€” its `activeViewId` is seeded from its own
2390
+ // storage key, which this frame does not know β€” so until the listener
2391
+ // exists the request is simply not heard. Navigating anyway is the honest
2392
+ // half: a notification that took you nowhere would be worse.
2393
+ window.dispatchEvent(
2394
+ new CustomEvent("aios:view-open", { detail: { topic, viewId } })
2395
+ );
2396
+ }}
2397
+ // ⭐ WAVE 23 C6 (wiring W23-W5) β€” the review notification's click-through.
2398
+ //
2399
+ // THE SAME TWO-PART MOVE the view click-through makes, and for the same reason: the
2400
+ // frame owns the hash, the automation SURFACE owns which automation is selected
2401
+ // (`activeId` is its own state, seeded from its own list β€” this frame cannot see it
2402
+ // and must not learn to). So: route, then ASK.
2403
+ //
2404
+ // ⚠ THE ORDER IS LOAD-BEARING. The hash is set FIRST so the surface is mounting (or
2405
+ // already mounted) when the event arrives; dispatching first would fire into a route
2406
+ // that does not exist yet. `signal` is `apiContract`'s helper β€” the same channel the
2407
+ // grid's own listeners use, rather than a second hand-rolled `dispatchEvent` here.
2408
+ onOpenAutomation={(autoId, stageId) => {
2409
+ window.location.hash = "#/automation";
2410
+ signal(AUTOMATION_OPEN_EVENT, { autoId, ...(stageId ? { stageId } : {}) });
2411
+ }}
2412
+ />
2413
+ </Lazily>
2414
  ) : null}
2415
 
2416
  {/* C-SHARE (items 18/23/26): the access editor β€” one dialog, three kinds. */}
web/src/shell/nav.ts CHANGED
@@ -96,6 +96,23 @@ export interface NavPage {
96
  * only off-switch"), so the entry is absent rather than refused.
97
  */
98
  canDelete?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  }
100
 
101
  /**
@@ -170,6 +187,9 @@ export function parsePages(body: unknown): NavPage[] {
170
  // C3 (W-5): read with the same `=== true` strictness as `manage` β€” a
171
  // truthy-but-not-true value from a drifted server must not open a delete.
172
  ...(p.canDelete === true ? { canDelete: true } : {}),
 
 
 
173
  });
174
  }
175
  return out;
@@ -629,6 +649,9 @@ export interface NavEntry {
629
  * CREATOR or an admin, never the whole `may_open` set `manage` rides on (see
630
  * the long note on `NavPage.canDelete`). Absent β‡’ no. */
631
  canDelete?: boolean;
 
 
 
632
  /**
633
  * ⭐ WAVE 25 (D-54) β€” THIS ROW IS A SURFACE, NOT A DATABASE.
634
  *
@@ -785,6 +808,9 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
785
  // the answer on the payload and never on the row the rail renders, which
786
  // is precisely how wave 20 shipped four wirings that went nowhere.
787
  ...(p.canDelete ? { canDelete: true } : {}),
 
 
 
788
  // ⭐ D-54 β€” the databases/surfaces split, stamped at the ONE place rows are built.
789
  // Not `kind`: a surface is `native` (this tree renders it) and so are the grids, so the
790
  // existing discriminator cannot answer this question and widening it would have made
 
96
  * only off-switch"), so the entry is absent rather than refused.
97
  */
98
  canDelete?: boolean;
99
+ /**
100
+ * ⭐ WAVE 27 item 3 (contract C9) β€” IS THIS A **LOCKED DATABASE**?
101
+ *
102
+ * The owner's item-4 vocabulary, and it means exactly one thing (DESIGN.md Β§4, THE THREE
103
+ * LOCKS): RECORDS cannot be added, deleted or edited β€” **FIELDS STILL CAN BE**. It is not
104
+ * "read-only", and a UI that hid the add-field door on the strength of this flag would be a
105
+ * defect, not caution.
106
+ *
107
+ * Answered server-side from `user_tables.records_mutable`'s own condition (`routes_nav.py`),
108
+ * because the client cannot see a table's `recordMode`.
109
+ *
110
+ * ⚠ ABSENT β‡’ UNLOCKED, which is the OPPOSITE direction from `manage`/`canDelete` above and
111
+ * is deliberate: those two gate CONTROLS, so absence must deny. This one draws a HINT beside a
112
+ * name, while the real refusal is the route's 403. A store blip should cost a missing padlock,
113
+ * never a control that silently disappears.
114
+ */
115
+ locked?: boolean;
116
  }
117
 
118
  /**
 
187
  // C3 (W-5): read with the same `=== true` strictness as `manage` β€” a
188
  // truthy-but-not-true value from a drifted server must not open a delete.
189
  ...(p.canDelete === true ? { canDelete: true } : {}),
190
+ // ⭐ WAVE 27 item 3 / C9 β€” same `=== true` strictness. A locked database is a padlock
191
+ // beside a name, so a drifted server sending a truthy string must not paint one.
192
+ ...(p.locked === true ? { locked: true } : {}),
193
  });
194
  }
195
  return out;
 
649
  * CREATOR or an admin, never the whole `may_open` set `manage` rides on (see
650
  * the long note on `NavPage.canDelete`). Absent β‡’ no. */
651
  canDelete?: boolean;
652
+ /** ⭐ WAVE 27 item 3 / C9 β€” a LOCKED database: no new records, fields still fine (see the
653
+ * long note on `NavPage.locked`). Absent β‡’ unlocked. */
654
+ locked?: boolean;
655
  /**
656
  * ⭐ WAVE 25 (D-54) β€” THIS ROW IS A SURFACE, NOT A DATABASE.
657
  *
 
808
  // the answer on the payload and never on the row the rail renders, which
809
  // is precisely how wave 20 shipped four wirings that went nowhere.
810
  ...(p.canDelete ? { canDelete: true } : {}),
811
+ // ⭐ WAVE 27 item 3 / C9 β€” THE SECOND HALF, for the reason stated directly above: a flag
812
+ // parsed onto the payload and dropped here reaches no row anybody renders.
813
+ ...(p.locked ? { locked: true } : {}),
814
  // ⭐ D-54 β€” the databases/surfaces split, stamped at the ONE place rows are built.
815
  // Not `kind`: a surface is `native` (this tree renders it) and so are the grids, so the
816
  // existing discriminator cannot answer this question and widening it would have made
web/src/viz/seriesData.ts CHANGED
@@ -49,6 +49,13 @@ export const VIZ_FIELD_TYPES: ReadonlySet<string> = new Set([
49
  // without this `asFields` would report a rollup column as `text` and the chart builder would
50
  // refuse to plot the one column the feature exists to produce.
51
  "link", "rollup",
 
 
 
 
 
 
 
52
  ]);
53
 
54
  /**
 
49
  // without this `asFields` would report a rollup column as `text` and the chart builder would
50
  // refuse to plot the one column the feature exists to produce.
51
  "link", "rollup",
52
+ // ⭐ Wave-27 item 13 (R13) β€” `code`. THE BATCH LINE a fourth time, and this one was caught by
53
+ // `verify_ui` rather than by the compiler, which is the whole point of that gate existing: the
54
+ // union in `viz/types.ts` went red under `tsc` the moment `code` joined the grid's, and this
55
+ // Set stayed green while `asFields` quietly reported a code column as `text`. Categorical
56
+ // either way (`isNumericFieldType` does not name it); what listing it buys is that the surface
57
+ // stops mis-naming the column.
58
+ "code",
59
  ]);
60
 
61
  /**
web/src/viz/types.ts CHANGED
@@ -63,7 +63,15 @@ export type FieldType =
63
  // string β€” the vocabulary has to know both words regardless, or the grid cannot hand its own
64
  // fields to DashboardView at all, which is the alarm two rules below going off. KEEP THIS
65
  // COMMENT FREE OF THE STATEMENT-TERMINATOR CHARACTER, as the two notes above say
66
- | "link" | "rollup";
 
 
 
 
 
 
 
 
67
 
68
  export type FieldSource = "odoo" | "overlay";
69
 
 
63
  // string β€” the vocabulary has to know both words regardless, or the grid cannot hand its own
64
  // fields to DashboardView at all, which is the alarm two rules below going off. KEEP THIS
65
  // COMMENT FREE OF THE STATEMENT-TERMINATOR CHARACTER, as the two notes above say
66
+ | "link" | "rollup"
67
+ // ⭐ Wave-27 item 13 (R13) β€” `code`, and the alarm two rules below is exactly how it got here:
68
+ // `GridFieldFitsViz` went red the moment the grid's union grew, which is this file working as
69
+ // designed. It stays CATEGORICAL by construction rather than by a branch β€” `isNumericFieldType`
70
+ // does not name it, so the engine groups it as a category and the shared formatter prints the
71
+ // stored string. Grouping a table by a snippet is a question nobody asks, but the vocabulary
72
+ // has to know the word or the grid cannot hand its own fields to DashboardView at all. KEEP
73
+ // THIS COMMENT FREE OF THE STATEMENT-TERMINATOR CHARACTER, as the three notes above say
74
+ | "code";
75
 
76
  export type FieldSource = "odoo" | "overlay";
77